main.go197 lines, 6.1 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 | "sync" |
| 13 | "syscall" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/fiston-user/payments/db" |
| 17 | "github.com/fiston-user/payments/internal/platform/authn" |
| 18 | "github.com/fiston-user/payments/internal/platform/config" |
| 19 | "github.com/fiston-user/payments/internal/platform/health" |
| 20 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 21 | "github.com/fiston-user/payments/internal/platform/logging" |
| 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/webhook" |
| 26 | "github.com/fiston-user/payments/internal/webhook/webhookdb" |
| 27 | "github.com/nats-io/nats.go/jetstream" |
| 28 | "github.com/prometheus/client_golang/prometheus/promhttp" |
| 29 | ) |
| 30 | |
| 31 | // version is stamped at build time: go build -ldflags "-X main.version=v1.2.3". |
| 32 | var version = "dev" |
| 33 | |
| 34 | func main() { |
| 35 | healthcheck := flag.Bool("healthcheck", false, "exit 0 if the service is ready: for Docker") |
| 36 | migrate := flag.Bool("migrate", false, "apply the database migrations, and exit") |
| 37 | flag.Parse() |
| 38 | cfg, err := loadConfig(config.New(os.LookupEnv)) |
| 39 | if err != nil { |
| 40 | // There's no logger yet: its settings are part of the configuration. |
| 41 | fmt.Fprintln(os.Stderr, "webhook:", err) |
| 42 | os.Exit(2) |
| 43 | } |
| 44 | // Docker's health check: the binary checks itself, then exits. |
| 45 | if *healthcheck { |
| 46 | if err := health.Probe(cfg.HTTPAddr); err != nil { |
| 47 | fmt.Fprintln(os.Stderr, err) |
| 48 | os.Exit(1) |
| 49 | } |
| 50 | return |
| 51 | } |
| 52 | logger := logging.New(os.Stdout, logging.Options{ |
| 53 | Service: "webhook", |
| 54 | Version: version, |
| 55 | Level: cfg.LogLevel, |
| 56 | Format: cfg.LogFormat, |
| 57 | }) |
| 58 | // Code that logs through the slog package functions gets our logger too. |
| 59 | slog.SetDefault(logger) |
| 60 | logger.Info("starting", "env", cfg.Env, "log_level", cfg.LogLevel.String()) |
| 61 | |
| 62 | // Apply the migrations, then exit: the one-shot step before a new version |
| 63 | // starts, in Compose, and in Kubernetes. |
| 64 | if *migrate { |
| 65 | version, err := postgres.Migrate(cfg.DatabaseURL, db.Migrations("webhook")) |
| 66 | if err != nil { |
| 67 | logger.Error("migrate", "err", err) |
| 68 | os.Exit(1) |
| 69 | } |
| 70 | logger.Info("database migrated", "schema_version", version) |
| 71 | return |
| 72 | } |
| 73 | |
| 74 | // Traces go to the collector in OTEL_EXPORTER_OTLP_ENDPOINT, if there is one. |
| 75 | stopTracing, err := telemetry.Setup(context.Background(), |
| 76 | telemetry.Options{Service: "webhook", Version: version, Env: cfg.Env}) |
| 77 | if err != nil { |
| 78 | logger.Error("telemetry", "err", err) |
| 79 | os.Exit(1) |
| 80 | } |
| 81 | |
| 82 | pool, err := postgres.NewPool(context.Background(), cfg.DatabaseURL, int32(cfg.DBMaxConns)) |
| 83 | if err != nil { |
| 84 | logger.Error("connect to postgres", "err", err) |
| 85 | os.Exit(1) |
| 86 | } |
| 87 | logger.Info("connected to postgres", "max_conns", pool.Config().MaxConns) |
| 88 | |
| 89 | // The auth service's public key: every route checks the caller's token, |
| 90 | // like the transfer service's. |
| 91 | pub, err := authn.ReadPublicKey(cfg.PublicKeyFile) |
| 92 | if err != nil { |
| 93 | logger.Error("read auth public key", "err", err) |
| 94 | os.Exit(1) |
| 95 | } |
| 96 | verifier := authn.NewVerifier(pub) |
| 97 | |
| 98 | // Deliveries go out through a client that, in production, refuses to |
| 99 | // connect to our own network. |
| 100 | production := cfg.Env == "production" |
| 101 | q := webhookdb.New(pool) |
| 102 | worker := webhook.NewWorker(q, webhook.NewClient(production), logger) |
| 103 | worker.Schedule = cfg.RetrySchedule |
| 104 | |
| 105 | // NATS, for events. Like Postgres, it must be there when we start. |
| 106 | nc, err := natsx.Connect(cfg.NATSURL, "webhook", logger) |
| 107 | if err != nil { |
| 108 | logger.Error("connect to nats", "err", err) |
| 109 | os.Exit(1) |
| 110 | } |
| 111 | logger.Info("connected to nats", "url", nc.ConnectedUrl()) |
| 112 | js, err := jetstream.New(nc) |
| 113 | if err != nil { |
| 114 | logger.Error("jetstream", "err", err) |
| 115 | os.Exit(1) |
| 116 | } |
| 117 | |
| 118 | // Its work arrives through NATS, so here, NATS is part of being ready. |
| 119 | probes := health.New(logger, map[string]health.Check{ |
| 120 | "postgres": pool.Ping, |
| 121 | "nats": natsx.Connected(nc), |
| 122 | }) |
| 123 | mux := http.NewServeMux() |
| 124 | probes.Register(mux) |
| 125 | // For Prometheus, which scrapes it every few seconds. The gateway never routes it. |
| 126 | mux.Handle("GET /metrics", promhttp.Handler()) |
| 127 | |
| 128 | // The webhook API, where every route needs an access token. |
| 129 | api := http.NewServeMux() |
| 130 | webhook.NewAPI(q, production, worker.Wake).Register(api) |
| 131 | api.HandleFunc("/", httpx.NotFound) |
| 132 | mux.Handle("/v1/", verifier.Require(httpx.Routes(api))) |
| 133 | |
| 134 | mux.HandleFunc("/", httpx.NotFound) |
| 135 | |
| 136 | srv := &http.Server{ |
| 137 | Addr: cfg.HTTPAddr, |
| 138 | Handler: httpx.Chain(httpx.Routes(mux), |
| 139 | httpx.Observe(), |
| 140 | httpx.RequestID, |
| 141 | httpx.AccessLog(logger), |
| 142 | httpx.Recover(logger), |
| 143 | ), |
| 144 | ReadHeaderTimeout: 5 * time.Second, |
| 145 | ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn), |
| 146 | } |
| 147 | |
| 148 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 149 | defer stop() |
| 150 | |
| 151 | // Transfer events become deliveries, and the worker sends them. It has a |
| 152 | // context of its own: it keeps sending while the server drains. |
| 153 | cc, err := webhook.NewFanOut(q, worker.Wake, logger).Consume(ctx, js) |
| 154 | if err != nil { |
| 155 | logger.Error("consume", "err", err) |
| 156 | os.Exit(1) |
| 157 | } |
| 158 | workerCtx, stopWorker := context.WithCancel(context.Background()) |
| 159 | var wg sync.WaitGroup |
| 160 | wg.Go(func() { worker.Run(workerCtx) }) |
| 161 | |
| 162 | go func() { |
| 163 | logger.Info("webhook service listening", "addr", srv.Addr) |
| 164 | if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 165 | logger.Error("server failed", "err", err) |
| 166 | os.Exit(1) |
| 167 | } |
| 168 | }() |
| 169 | |
| 170 | <-ctx.Done() |
| 171 | logger.Info("shutting down gracefully") |
| 172 | // Readiness fails first, so load balancers stop sending us new requests. |
| 173 | probes.Drain(cfg.DrainDelay) |
| 174 | |
| 175 | shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) |
| 176 | defer cancel() |
| 177 | |
| 178 | if err := srv.Shutdown(shutdownCtx); err != nil { |
| 179 | logger.Error("http shutdown failed", "err", err) |
| 180 | } |
| 181 | logger.Info("server stopped") |
| 182 | // Stop pulling events, and finish the ones we have. Then the worker |
| 183 | // finishes its batch, and stops. |
| 184 | cc.Drain() |
| 185 | <-cc.Closed() |
| 186 | stopWorker() |
| 187 | wg.Wait() |
| 188 | logger.Info("consumer and worker stopped") |
| 189 | |
| 190 | nc.Close() |
| 191 | pool.Close() |
| 192 | logger.Info("nats and database pool closed") |
| 193 | // Last, the spans still waiting in the batch, from everything that stopped. |
| 194 | if err := stopTracing(shutdownCtx); err != nil { |
| 195 | logger.Error("flush traces", "err", err) |
| 196 | } |
| 197 | } |