diff options
author | Alan Pearce | 2024-12-12 11:09:47 +0100 |
---|---|---|
committer | Alan Pearce | 2024-12-12 18:16:10 +0100 |
commit | fed650743913797a314d8fc7d7550ba21dce0a12 (patch) | |
tree | c2d5e62fafbf9cee7f862927a5894da807f5d34b /internal/nats/nats.go | |
parent | b66c1ed87b556844421886ead373ffdd4ca25663 (diff) | |
download | website-fed650743913797a314d8fc7d7550ba21dce0a12.tar.lz website-fed650743913797a314d8fc7d7550ba21dce0a12.tar.zst website-fed650743913797a314d8fc7d7550ba21dce0a12.zip |
setup embedded NATS cluster nats
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() +} |