main.go329 lines, 11 KB
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/tls" |
| 6 | "errors" |
| 7 | "flag" |
| 8 | "fmt" |
| 9 | "log/slog" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "os" |
| 13 | "os/signal" |
| 14 | "sync" |
| 15 | "syscall" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/fiston-user/payments/db" |
| 19 | walletv1 "github.com/fiston-user/payments/gen/wallet/v1" |
| 20 | "github.com/fiston-user/payments/internal/fx" |
| 21 | "github.com/fiston-user/payments/internal/platform/authn" |
| 22 | "github.com/fiston-user/payments/internal/platform/config" |
| 23 | "github.com/fiston-user/payments/internal/platform/debug" |
| 24 | "github.com/fiston-user/payments/internal/platform/grpcx" |
| 25 | "github.com/fiston-user/payments/internal/platform/health" |
| 26 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 27 | "github.com/fiston-user/payments/internal/platform/idempotency" |
| 28 | "github.com/fiston-user/payments/internal/platform/jobs" |
| 29 | "github.com/fiston-user/payments/internal/platform/logging" |
| 30 | "github.com/fiston-user/payments/internal/platform/mtls" |
| 31 | "github.com/fiston-user/payments/internal/platform/natsx" |
| 32 | "github.com/fiston-user/payments/internal/platform/outbox" |
| 33 | "github.com/fiston-user/payments/internal/platform/postgres" |
| 34 | "github.com/fiston-user/payments/internal/platform/redis" |
| 35 | "github.com/fiston-user/payments/internal/platform/telemetry" |
| 36 | "github.com/fiston-user/payments/internal/wallet" |
| 37 | "github.com/fiston-user/payments/internal/wallet/walletevents" |
| 38 | "github.com/nats-io/nats.go/jetstream" |
| 39 | "github.com/prometheus/client_golang/prometheus/promhttp" |
| 40 | "google.golang.org/grpc/credentials" |
| 41 | grpchealth "google.golang.org/grpc/health" |
| 42 | healthpb "google.golang.org/grpc/health/grpc_health_v1" |
| 43 | "google.golang.org/grpc/reflection" |
| 44 | ) |
| 45 | |
| 46 | // version is stamped at build time: go build -ldflags "-X main.version=v1.2.3". |
| 47 | var version = "dev" |
| 48 | |
| 49 | func main() { |
| 50 | healthcheck := flag.Bool("healthcheck", false, "exit 0 if the service is ready: for Docker") |
| 51 | migrate := flag.Bool("migrate", false, "apply the database migrations, and exit") |
| 52 | flag.Parse() |
| 53 | cfg, err := loadConfig(config.New(os.LookupEnv)) |
| 54 | if err != nil { |
| 55 | // There's no logger yet: its settings are part of the configuration. |
| 56 | fmt.Fprintln(os.Stderr, "wallet:", err) |
| 57 | os.Exit(2) |
| 58 | } |
| 59 | // Docker's health check: the binary checks itself, then exits. |
| 60 | if *healthcheck { |
| 61 | if err := health.Probe(cfg.HTTPAddr); err != nil { |
| 62 | fmt.Fprintln(os.Stderr, err) |
| 63 | os.Exit(1) |
| 64 | } |
| 65 | return |
| 66 | } |
| 67 | logger := logging.New(os.Stdout, logging.Options{ |
| 68 | Service: "wallet", |
| 69 | Version: version, |
| 70 | Level: cfg.LogLevel, |
| 71 | Format: cfg.LogFormat, |
| 72 | }) |
| 73 | // Code that logs through the slog package functions gets our logger too. |
| 74 | slog.SetDefault(logger) |
| 75 | logger.Info("starting", "env", cfg.Env, "log_level", cfg.LogLevel.String()) |
| 76 | |
| 77 | // Apply the migrations, then exit: the one-shot step before a new version |
| 78 | // starts, in Compose, and in Kubernetes. |
| 79 | if *migrate { |
| 80 | version, err := postgres.Migrate(cfg.DatabaseURL, db.Migrations("wallet")) |
| 81 | if err != nil { |
| 82 | logger.Error("migrate", "err", err) |
| 83 | os.Exit(1) |
| 84 | } |
| 85 | logger.Info("database migrated", "schema_version", version) |
| 86 | return |
| 87 | } |
| 88 | |
| 89 | // Traces go to the collector in OTEL_EXPORTER_OTLP_ENDPOINT, if there is one. |
| 90 | stopTracing, err := telemetry.Setup(context.Background(), |
| 91 | telemetry.Options{Service: "wallet", Version: version, Env: cfg.Env}) |
| 92 | if err != nil { |
| 93 | logger.Error("telemetry", "err", err) |
| 94 | os.Exit(1) |
| 95 | } |
| 96 | |
| 97 | pool, err := postgres.NewPool(context.Background(), cfg.DatabaseURL, int32(cfg.DBMaxConns)) |
| 98 | if err != nil { |
| 99 | logger.Error("connect to postgres", "err", err) |
| 100 | os.Exit(1) |
| 101 | } |
| 102 | logger.Info("connected to postgres", "max_conns", pool.Config().MaxConns) |
| 103 | outbox.RegisterMetrics(pool) |
| 104 | postgres.RegisterMetrics("main", pool) |
| 105 | // Reports get a pool of their own, a bulkhead: at the end of the month, |
| 106 | // finance can't take the connections that payments need. |
| 107 | reports, err := postgres.NewPool(context.Background(), cfg.DatabaseURL, int32(cfg.DBReportConns)) |
| 108 | if err != nil { |
| 109 | logger.Error("connect to postgres", "err", err) |
| 110 | os.Exit(1) |
| 111 | } |
| 112 | postgres.RegisterMetrics("reports", reports) |
| 113 | wallet.RegisterMetrics(pool) |
| 114 | |
| 115 | // Redis is only a cache in front of Postgres. If it's down, we start |
| 116 | // anyway, without the cache, and use it as soon as it's back. |
| 117 | rdb, err := redis.NewClient(cfg.RedisURL) |
| 118 | if err != nil { |
| 119 | logger.Error("connect to redis", "err", err) |
| 120 | os.Exit(1) |
| 121 | } |
| 122 | if err := rdb.Ping(context.Background()).Err(); err != nil { |
| 123 | logger.Warn("redis unreachable, idempotency keys use postgres only", "err", err) |
| 124 | } else { |
| 125 | logger.Info("connected to redis") |
| 126 | } |
| 127 | |
| 128 | // NATS, for events. Like Postgres, and unlike Redis, it must be there when |
| 129 | // we start: the stream has to exist. |
| 130 | nc, err := natsx.Connect(cfg.NATSURL, "wallet", logger) |
| 131 | if err != nil { |
| 132 | logger.Error("connect to nats", "err", err) |
| 133 | os.Exit(1) |
| 134 | } |
| 135 | logger.Info("connected to nats", "url", nc.ConnectedUrl()) |
| 136 | js, err := jetstream.New(nc) |
| 137 | if err != nil { |
| 138 | logger.Error("jetstream", "err", err) |
| 139 | os.Exit(1) |
| 140 | } |
| 141 | if err := natsx.EnsureStream(context.Background(), js, walletevents.StreamConfig(cfg.NATSReplicas)); err != nil { |
| 142 | logger.Error("create stream", "err", err) |
| 143 | os.Exit(1) |
| 144 | } |
| 145 | |
| 146 | // The auth service's public key: enough to check access tokens, and |
| 147 | // useless for making them. |
| 148 | pub, err := authn.ReadPublicKey(cfg.PublicKeyFile) |
| 149 | if err != nil { |
| 150 | logger.Error("read auth public key", "err", err) |
| 151 | os.Exit(1) |
| 152 | } |
| 153 | verifier := authn.NewVerifier(pub) |
| 154 | // Our certificate, and our CA's: for mTLS with our other services. |
| 155 | certs, err := mtls.Load(cfg.TLSDir) |
| 156 | if err != nil { |
| 157 | logger.Error("load certificates", "err", err) |
| 158 | os.Exit(1) |
| 159 | } |
| 160 | |
| 161 | // The wallet is ready when its database is. NATS isn't checked: while it's |
| 162 | // down, events wait in the outbox, and payments carry on. |
| 163 | probes := health.New(logger, map[string]health.Check{"postgres": pool.Ping}) |
| 164 | mux := http.NewServeMux() |
| 165 | probes.Register(mux) |
| 166 | // For Prometheus, which scrapes it every few seconds. The gateway never routes it. |
| 167 | mux.Handle("GET /metrics", promhttp.Handler()) |
| 168 | |
| 169 | // The wallet API, where every route needs an access token, and a JSON 404 |
| 170 | // for everything else. |
| 171 | // Rates for currency conversion: built into the binary, for development. |
| 172 | // In production, a Provider that asks a bank, or a market data feed. |
| 173 | rates, err := fx.DevRates(cfg.Env) |
| 174 | if err != nil { |
| 175 | logger.Error("fx rates", "err", err) |
| 176 | os.Exit(1) |
| 177 | } |
| 178 | store := wallet.NewStore(pool).ReportsOn(reports) |
| 179 | svc := wallet.NewService(store).WithFX(wallet.FX{ |
| 180 | Rates: rates, QuoteTTL: cfg.FXQuoteTTL, FeeBps: int64(cfg.FXFeeBps), |
| 181 | }) |
| 182 | keys := idempotency.NewStore(pool, rdb) |
| 183 | handler := wallet.NewHandler(svc, keys) |
| 184 | api := http.NewServeMux() |
| 185 | handler.Register(api) |
| 186 | api.HandleFunc("/", httpx.NotFound) |
| 187 | mux.Handle("/v1/", verifier.Require(httpx.Routes(api))) |
| 188 | // Reports for finance, over mTLS: only our back office's tools may fetch them. |
| 189 | internal := http.NewServeMux() |
| 190 | handler.RegisterInternal(internal) |
| 191 | internal.HandleFunc("/", httpx.NotFound) |
| 192 | mux.Handle("/internal/", mtls.Allow("ops")(httpx.Routes(internal))) |
| 193 | // Go's profiler, for our ops tools: over mTLS, on the internal port. |
| 194 | mux.Handle("/internal/debug/", mtls.Allow("ops")(debug.Handler())) |
| 195 | mux.HandleFunc("/", httpx.NotFound) |
| 196 | |
| 197 | // The same service, over gRPC, for our other services. Every RPC needs an |
| 198 | // access token, except health checks, and holds: sagas call those for |
| 199 | // users who may be long gone. The gateway never routes to them. |
| 200 | noToken := []string{ |
| 201 | healthpb.Health_ServiceDesc.ServiceName, |
| 202 | walletv1.HoldService_ServiceDesc.ServiceName, |
| 203 | } |
| 204 | grpcSrv := grpcx.NewServer(logger, credentials.NewTLS(certs.Server()), |
| 205 | // Who may call what, by their certificates. The gateway calls the |
| 206 | // wallet API for its users, and only sagas may hold money. |
| 207 | mtls.Authorize(map[string][]string{ |
| 208 | walletv1.WalletService_ServiceDesc.ServiceName: {"gateway"}, |
| 209 | walletv1.HoldService_ServiceDesc.ServiceName: {"transfer"}, |
| 210 | healthpb.Health_ServiceDesc.ServiceName: {"gateway", "transfer"}, |
| 211 | }), |
| 212 | verifier.UnaryInterceptor(noToken...)) |
| 213 | walletv1.RegisterWalletServiceServer(grpcSrv, wallet.NewGRPCServer(svc, keys)) |
| 214 | walletv1.RegisterHoldServiceServer(grpcSrv, wallet.NewHoldServer(svc)) |
| 215 | healthSrv := grpchealth.NewServer() |
| 216 | healthpb.RegisterHealthServer(grpcSrv, healthSrv) |
| 217 | // Reflection lets tools like grpcurl discover our API. Handy in |
| 218 | // development; in production, the contract is the .proto file. |
| 219 | if cfg.Env == "development" { |
| 220 | reflection.Register(grpcSrv) |
| 221 | } |
| 222 | |
| 223 | srv := &http.Server{ |
| 224 | Addr: cfg.HTTPAddr, |
| 225 | Handler: httpx.Chain(httpx.Routes(mux), |
| 226 | httpx.Observe(), |
| 227 | httpx.RequestID, |
| 228 | httpx.AccessLog(logger), |
| 229 | httpx.Recover(logger), |
| 230 | ), |
| 231 | ReadHeaderTimeout: 5 * time.Second, |
| 232 | ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn), |
| 233 | } |
| 234 | |
| 235 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 236 | defer stop() |
| 237 | |
| 238 | // Forget expired idempotency keys, once an hour. |
| 239 | go keys.Cleanup(ctx, time.Hour) |
| 240 | |
| 241 | // Scheduled jobs: every replica campaigns, and only the leader runs them. |
| 242 | // They stop the moment we're asked to, so another replica takes over while |
| 243 | // we drain. |
| 244 | runner := jobs.NewRunner(pool, logger, jobs.Job{ |
| 245 | Name: "reconcile", |
| 246 | Every: cfg.ReconcileEvery, |
| 247 | At: cfg.ReconcileAt, |
| 248 | Run: wallet.ReconcileJob(store, logger), |
| 249 | }) |
| 250 | elector := jobs.NewElector(cfg.DatabaseURL, "wallet-jobs", logger) |
| 251 | var leader sync.WaitGroup |
| 252 | leader.Go(func() { elector.Run(ctx, runner.Run) }) |
| 253 | |
| 254 | // The outbox relay publishes our events. It has a context of its own, so |
| 255 | // it keeps publishing while the servers drain, and stops after them. |
| 256 | relayCtx, stopRelay := context.WithCancel(context.Background()) |
| 257 | var relay sync.WaitGroup |
| 258 | relay.Go(func() { outbox.NewRelay(pool, js, logger).Run(relayCtx) }) |
| 259 | |
| 260 | go func() { |
| 261 | logger.Info("wallet service listening", "addr", srv.Addr) |
| 262 | if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 263 | logger.Error("server failed", "err", err) |
| 264 | os.Exit(1) |
| 265 | } |
| 266 | }() |
| 267 | |
| 268 | // The internal port: the same routes, over mTLS. Only what comes in |
| 269 | // through it gets past mtls.Allow. |
| 270 | go func() { |
| 271 | lis, err := tls.Listen("tcp", cfg.InternalAddr, certs.Server()) |
| 272 | if err == nil { |
| 273 | err = srv.Serve(lis) |
| 274 | } |
| 275 | if !errors.Is(err, http.ErrServerClosed) { |
| 276 | logger.Error("internal server failed", "err", err) |
| 277 | os.Exit(1) |
| 278 | } |
| 279 | }() |
| 280 | |
| 281 | lis, err := net.Listen("tcp", cfg.GRPCAddr) |
| 282 | if err != nil { |
| 283 | logger.Error("grpc listen", "err", err) |
| 284 | os.Exit(1) |
| 285 | } |
| 286 | go func() { |
| 287 | logger.Info("grpc server listening", "addr", cfg.GRPCAddr) |
| 288 | if err := grpcSrv.Serve(lis); err != nil { |
| 289 | logger.Error("grpc server failed", "err", err) |
| 290 | os.Exit(1) |
| 291 | } |
| 292 | }() |
| 293 | |
| 294 | <-ctx.Done() |
| 295 | logger.Info("shutting down gracefully") |
| 296 | // Readiness fails first, over HTTP and gRPC, so load balancers stop sending |
| 297 | // us new requests. Then both servers drain, within one deadline. |
| 298 | healthSrv.Shutdown() |
| 299 | probes.Drain(cfg.DrainDelay) |
| 300 | |
| 301 | shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) |
| 302 | defer cancel() |
| 303 | var wg sync.WaitGroup |
| 304 | wg.Go(func() { |
| 305 | if err := srv.Shutdown(shutdownCtx); err != nil { |
| 306 | logger.Error("http shutdown failed", "err", err) |
| 307 | } |
| 308 | }) |
| 309 | wg.Go(func() { grpcx.Shutdown(shutdownCtx, grpcSrv) }) |
| 310 | wg.Wait() |
| 311 | logger.Info("servers stopped") |
| 312 | // Then the relay. A batch it was in the middle of rolls back, and goes |
| 313 | // out on the next start: at least once. |
| 314 | stopRelay() |
| 315 | relay.Wait() |
| 316 | leader.Wait() |
| 317 | logger.Info("outbox relay and jobs stopped") |
| 318 | |
| 319 | // Close the connections last: requests that were still finishing needed them. |
| 320 | nc.Close() |
| 321 | pool.Close() |
| 322 | reports.Close() |
| 323 | rdb.Close() |
| 324 | logger.Info("nats, database pool and redis client closed") |
| 325 | // Last, the spans still waiting in the batch, from everything that stopped. |
| 326 | if err := stopTracing(shutdownCtx); err != nil { |
| 327 | logger.Error("flush traces", "err", err) |
| 328 | } |
| 329 | } |