natsx.go100 lines, 3.1 KB
| 1 | // Package natsx connects services to NATS, and sets up JetStream streams. |
| 2 | package natsx |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "maps" |
| 10 | "slices" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/nats-io/nats.go" |
| 14 | "github.com/nats-io/nats.go/jetstream" |
| 15 | ) |
| 16 | |
| 17 | // Connect connects to the NATS server at url. The name shows up in the |
| 18 | // server's list of connections, so we can tell who's who. Once connected, the |
| 19 | // client reconnects by itself, forever, and logs every change. |
| 20 | func Connect(url, name string, logger *slog.Logger) (*nats.Conn, error) { |
| 21 | nc, err := nats.Connect(url, |
| 22 | nats.Name(name), |
| 23 | nats.Timeout(2*time.Second), |
| 24 | nats.MaxReconnects(-1), |
| 25 | nats.ReconnectWait(time.Second), |
| 26 | // While disconnected, publishing fails right away, instead of waiting |
| 27 | // in a buffer in memory that dies with the process. |
| 28 | nats.ReconnectBufSize(-1), |
| 29 | nats.DisconnectErrHandler(func(_ *nats.Conn, err error) { |
| 30 | if err != nil { |
| 31 | logger.Warn("nats disconnected", "err", err) |
| 32 | } |
| 33 | }), |
| 34 | nats.ReconnectHandler(func(nc *nats.Conn) { |
| 35 | logger.Info("nats reconnected", "url", nc.ConnectedUrl()) |
| 36 | }), |
| 37 | nats.ErrorHandler(func(_ *nats.Conn, sub *nats.Subscription, err error) { |
| 38 | if sub != nil { |
| 39 | logger.Error("nats error", "subject", sub.Subject, "err", err) |
| 40 | return |
| 41 | } |
| 42 | logger.Error("nats error", "err", err) |
| 43 | }), |
| 44 | ) |
| 45 | if err != nil { |
| 46 | return nil, fmt.Errorf("nats: connect to %s: %w", url, err) |
| 47 | } |
| 48 | return nc, nil |
| 49 | } |
| 50 | |
| 51 | // Connected is a readiness check: is nc connected to NATS, right now? |
| 52 | func Connected(nc *nats.Conn) func(context.Context) error { |
| 53 | return func(context.Context) error { |
| 54 | if !nc.IsConnected() { |
| 55 | return fmt.Errorf("nats: %s", nc.Status()) |
| 56 | } |
| 57 | return nil |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // EnsureStream creates a stream, or updates it to cfg if it exists. Every |
| 62 | // instance of a service can call it at startup, any number of times, and a |
| 63 | // changed config rolls out with the next deploy. |
| 64 | func EnsureStream(ctx context.Context, js jetstream.JetStream, cfg jetstream.StreamConfig) error { |
| 65 | ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| 66 | defer cancel() |
| 67 | stream, err := js.CreateOrUpdateStream(ctx, cfg) |
| 68 | if err != nil { |
| 69 | return fmt.Errorf("nats: stream %s: %w", cfg.Name, err) |
| 70 | } |
| 71 | slog.InfoContext(ctx, "stream ready", "stream", cfg.Name, "subjects", cfg.Subjects, |
| 72 | "messages", stream.CachedInfo().State.Msgs) |
| 73 | return nil |
| 74 | } |
| 75 | |
| 76 | // WaitForStream waits until the stream called name exists. The service that |
| 77 | // publishes to it creates it when it starts, and in Kubernetes, services |
| 78 | // start in no particular order. It gives up when ctx is done. |
| 79 | func WaitForStream(ctx context.Context, js jetstream.JetStream, name string) error { |
| 80 | for { |
| 81 | _, err := js.Stream(ctx, name) |
| 82 | if !errors.Is(err, jetstream.ErrStreamNotFound) { |
| 83 | return err |
| 84 | } |
| 85 | slog.InfoContext(ctx, "waiting for stream", "stream", name) |
| 86 | select { |
| 87 | case <-ctx.Done(): |
| 88 | return ctx.Err() |
| 89 | case <-time.After(time.Second): |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | // HeaderCarrier lets OpenTelemetry read and write a message's headers: Get |
| 95 | // and Set come with nats.Header, and Keys lists them. |
| 96 | type HeaderCarrier struct{ nats.Header } |
| 97 | |
| 98 | func (c HeaderCarrier) Keys() []string { |
| 99 | return slices.Collect(maps.Keys(c.Header)) |
| 100 | } |