diff options
Diffstat (limited to 'internal/nats/nats.go')
-rw-r--r-- | internal/nats/nats.go | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/internal/nats/nats.go b/internal/nats/nats.go new file mode 100644 index 0000000..9662868 --- /dev/null +++ b/internal/nats/nats.go @@ -0,0 +1,66 @@ +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() +} |