package nats import ( "fmt" "os" "time" "github.com/nats-io/nats-server/v2/server" "gitlab.com/tozd/go/errors" "go.alanpearce.eu/x/log" ) const flyPrivateHostname = "fly-local-6pn" var srv *server.Server func Start(log *log.Logger) error { var err error appName := os.Getenv("FLY_APP_NAME") if appName == "" { log.Warn("no FLY_APP_NAME") return nil } privateIP := os.Getenv("FLY_PRIVATE_IP") if privateIP == "" { log.Warn("no FLY_PRIVATE_IP") return nil } hostname := fmt.Sprintf("%s.internal", appName) opts := &server.Options{ ServerName: os.Getenv("FLY_MACHINE_ID"), Host: flyPrivateHostname, Port: 4222, Cluster: server.ClusterOpts{ Name: appName, Host: flyPrivateHostname, Port: 7221, ConnectRetries: 60, }, RoutesStr: "nats-route://" + hostname + ":7221", } srv, err = server.NewServer(opts) if err != nil { return errors.WithMessage(err, "could not start NATS server") } srv.SetLoggerV2(adaptLogger(log), false, false, false) srv.Start() if !srv.ReadyForConnections(4 * time.Second) { log.Warn("server not ready") } return nil } func Stop() { go srv.Shutdown() srv.WaitForShutdown() }