From fed650743913797a314d8fc7d7550ba21dce0a12 Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Thu, 12 Dec 2024 11:09:47 +0100 Subject: setup embedded NATS cluster --- internal/nats/log.go | 27 +++++++++++++++++++++ internal/nats/nats.go | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 internal/nats/log.go create mode 100644 internal/nats/nats.go (limited to 'internal') diff --git a/internal/nats/log.go b/internal/nats/log.go new file mode 100644 index 0000000..cc9d1c2 --- /dev/null +++ b/internal/nats/log.go @@ -0,0 +1,27 @@ +package nats + +import ( + "go.alanpearce.eu/x/log" + "go.uber.org/zap" +) + +type Logger struct { + *zap.SugaredLogger +} + +func adaptLogger(log *log.Logger) *Logger { + if log == nil { + panic("zl cannot be nil") + } + return &Logger{ + log.GetLogger().Sugar(), + } +} + +func (l *Logger) Tracef(format string, v ...any) { + l.Debugf(format, v...) +} + +func (l *Logger) Noticef(format string, v ...any) { + l.Infof(format, v...) +} 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() +} -- cgit 1.4.1