main.go209 lines, 6.6 KB
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "flag" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "os/signal" |
| 12 | "syscall" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/fiston-user/payments/db" |
| 16 | "github.com/fiston-user/payments/internal/notification" |
| 17 | "github.com/fiston-user/payments/internal/platform/config" |
| 18 | "github.com/fiston-user/payments/internal/platform/health" |
| 19 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 20 | "github.com/fiston-user/payments/internal/platform/logging" |
| 21 | "github.com/fiston-user/payments/internal/platform/mtls" |
| 22 | "github.com/fiston-user/payments/internal/platform/natsx" |
| 23 | "github.com/fiston-user/payments/internal/platform/postgres" |
| 24 | "github.com/fiston-user/payments/internal/platform/telemetry" |
| 25 | "github.com/fiston-user/payments/internal/transfer/transferevents" |
| 26 | "github.com/fiston-user/payments/internal/wallet/walletevents" |
| 27 | "github.com/nats-io/nats.go/jetstream" |
| 28 | "github.com/prometheus/client_golang/prometheus/promhttp" |
| 29 | "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" |
| 30 | ) |
| 31 | |
| 32 | // version is stamped at build time: go build -ldflags "-X main.version=v1.2.3". |
| 33 | var version = "dev" |
| 34 | |
| 35 | func main() { |
| 36 | replay := flag.Bool("replay-dead-letters", false, "send the dead letters again, and exit") |
| 37 | healthcheck := flag.Bool("healthcheck", false, "exit 0 if the service is ready: for Docker") |
| 38 | migrate := flag.Bool("migrate", false, "apply the database migrations, and exit") |
| 39 | flag.Parse() |
| 40 | cfg, err := loadConfig(config.New(os.LookupEnv)) |
| 41 | if err != nil { |
| 42 | // There's no logger yet: its settings are part of the configuration. |
| 43 | fmt.Fprintln(os.Stderr, "notification:", err) |
| 44 | os.Exit(2) |
| 45 | } |
| 46 | // Docker's health check: the binary checks itself, then exits. |
| 47 | if *healthcheck { |
| 48 | if err := health.Probe(cfg.HTTPAddr); err != nil { |
| 49 | fmt.Fprintln(os.Stderr, err) |
| 50 | os.Exit(1) |
| 51 | } |
| 52 | return |
| 53 | } |
| 54 | logger := logging.New(os.Stdout, logging.Options{ |
| 55 | Service: "notification", |
| 56 | Version: version, |
| 57 | Level: cfg.LogLevel, |
| 58 | Format: cfg.LogFormat, |
| 59 | }) |
| 60 | // Code that logs through the slog package functions gets our logger too. |
| 61 | slog.SetDefault(logger) |
| 62 | logger.Info("starting", "env", cfg.Env, "log_level", cfg.LogLevel.String()) |
| 63 | |
| 64 | // Apply the migrations, then exit: the one-shot step before a new version |
| 65 | // starts, in Compose, and in Kubernetes. |
| 66 | if *migrate { |
| 67 | version, err := postgres.Migrate(cfg.DatabaseURL, db.Migrations("notification")) |
| 68 | if err != nil { |
| 69 | logger.Error("migrate", "err", err) |
| 70 | os.Exit(1) |
| 71 | } |
| 72 | logger.Info("database migrated", "schema_version", version) |
| 73 | return |
| 74 | } |
| 75 | |
| 76 | // Traces go to the collector in OTEL_EXPORTER_OTLP_ENDPOINT, if there is one. |
| 77 | stopTracing, err := telemetry.Setup(context.Background(), |
| 78 | telemetry.Options{Service: "notification", Version: version, Env: cfg.Env}) |
| 79 | if err != nil { |
| 80 | logger.Error("telemetry", "err", err) |
| 81 | os.Exit(1) |
| 82 | } |
| 83 | |
| 84 | pool, err := postgres.NewPool(context.Background(), cfg.DatabaseURL, int32(cfg.DBMaxConns)) |
| 85 | if err != nil { |
| 86 | logger.Error("connect to postgres", "err", err) |
| 87 | os.Exit(1) |
| 88 | } |
| 89 | logger.Info("connected to postgres", "max_conns", pool.Config().MaxConns) |
| 90 | |
| 91 | // Email goes out through SMTP, to the addresses the auth service knows, |
| 92 | // cached for a minute. We ask over mTLS: auth knows us by our certificate. |
| 93 | certs, err := mtls.Load(cfg.TLSDir) |
| 94 | if err != nil { |
| 95 | logger.Error("load certificates", "err", err) |
| 96 | os.Exit(1) |
| 97 | } |
| 98 | toAuth := &http.Transport{TLSClientConfig: certs.Client("auth")} |
| 99 | notifier := notification.NewNotifier( |
| 100 | notification.NewStore(pool), |
| 101 | notification.NewCachedUsers(notification.AuthUsers{BaseURL: cfg.AuthURL, Client: &http.Client{ |
| 102 | Timeout: 5 * time.Second, |
| 103 | Transport: otelhttp.NewTransport(toAuth), // a span, and the context |
| 104 | }}, time.Minute), |
| 105 | notification.SMTP{Addr: cfg.SMTPAddr, From: "no-reply@payments.example"}, |
| 106 | logger, |
| 107 | ) |
| 108 | if *replay { |
| 109 | n, err := notifier.Replay(context.Background()) |
| 110 | pool.Close() |
| 111 | if err != nil { |
| 112 | logger.Error("replay dead letters", "err", err) |
| 113 | os.Exit(1) |
| 114 | } |
| 115 | logger.Info("dead letters replayed", "sent", n) |
| 116 | return |
| 117 | } |
| 118 | |
| 119 | // NATS, for events. Like Postgres, it must be there when we start. |
| 120 | nc, err := natsx.Connect(cfg.NATSURL, "notification", logger) |
| 121 | if err != nil { |
| 122 | logger.Error("connect to nats", "err", err) |
| 123 | os.Exit(1) |
| 124 | } |
| 125 | logger.Info("connected to nats", "url", nc.ConnectedUrl()) |
| 126 | js, err := jetstream.New(nc) |
| 127 | if err != nil { |
| 128 | logger.Error("jetstream", "err", err) |
| 129 | os.Exit(1) |
| 130 | } |
| 131 | |
| 132 | // Its work arrives through NATS, so here, NATS is part of being ready. |
| 133 | probes := health.New(logger, map[string]health.Check{ |
| 134 | "postgres": pool.Ping, |
| 135 | "nats": natsx.Connected(nc), |
| 136 | }) |
| 137 | mux := http.NewServeMux() |
| 138 | probes.Register(mux) |
| 139 | // For Prometheus, which scrapes it every few seconds. The gateway never routes it. |
| 140 | mux.Handle("GET /metrics", promhttp.Handler()) |
| 141 | |
| 142 | mux.HandleFunc("/", httpx.NotFound) |
| 143 | |
| 144 | srv := &http.Server{ |
| 145 | Addr: cfg.HTTPAddr, |
| 146 | Handler: httpx.Chain(httpx.Routes(mux), |
| 147 | httpx.Observe(), |
| 148 | httpx.RequestID, |
| 149 | httpx.AccessLog(logger), |
| 150 | httpx.Recover(logger), |
| 151 | ), |
| 152 | ReadHeaderTimeout: 5 * time.Second, |
| 153 | ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn), |
| 154 | } |
| 155 | |
| 156 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 157 | defer stop() |
| 158 | |
| 159 | // One durable consumer on each stream we listen to. We don't create the |
| 160 | // streams: the services that publish to them do. |
| 161 | var consumers []jetstream.ConsumeContext |
| 162 | for stream, subject := range map[string]string{ |
| 163 | transferevents.Stream: "transfer.events.>", |
| 164 | walletevents.Stream: walletevents.Subject(walletevents.TransferCompleted), |
| 165 | } { |
| 166 | cc, err := notifier.Consume(ctx, js, stream, subject) |
| 167 | if err != nil { |
| 168 | logger.Error("consume", "err", err) |
| 169 | os.Exit(1) |
| 170 | } |
| 171 | consumers = append(consumers, cc) |
| 172 | } |
| 173 | |
| 174 | go func() { |
| 175 | logger.Info("notification service listening", "addr", srv.Addr) |
| 176 | if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 177 | logger.Error("server failed", "err", err) |
| 178 | os.Exit(1) |
| 179 | } |
| 180 | }() |
| 181 | |
| 182 | <-ctx.Done() |
| 183 | logger.Info("shutting down gracefully") |
| 184 | // Readiness fails first, so load balancers stop sending us new requests. |
| 185 | probes.Drain(cfg.DrainDelay) |
| 186 | |
| 187 | shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) |
| 188 | defer cancel() |
| 189 | |
| 190 | if err := srv.Shutdown(shutdownCtx); err != nil { |
| 191 | logger.Error("http shutdown failed", "err", err) |
| 192 | } |
| 193 | logger.Info("server stopped") |
| 194 | // Stop pulling, and finish the messages we already have. One that's cut |
| 195 | // short is delivered again, later: at least once. |
| 196 | for _, cc := range consumers { |
| 197 | cc.Drain() |
| 198 | <-cc.Closed() |
| 199 | } |
| 200 | logger.Info("consumers stopped") |
| 201 | |
| 202 | nc.Close() |
| 203 | pool.Close() |
| 204 | logger.Info("nats and database pool closed") |
| 205 | // Last, the spans still waiting in the batch, from everything that stopped. |
| 206 | if err := stopTracing(shutdownCtx); err != nil { |
| 207 | logger.Error("flush traces", "err", err) |
| 208 | } |
| 209 | } |