main.go257 lines, 8.8 KB
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/tls" |
| 6 | "errors" |
| 7 | "flag" |
| 8 | "fmt" |
| 9 | "log/slog" |
| 10 | "net/http" |
| 11 | "os" |
| 12 | "os/signal" |
| 13 | "sync" |
| 14 | "syscall" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/fiston-user/payments/db" |
| 18 | "github.com/fiston-user/payments/internal/fx" |
| 19 | "github.com/fiston-user/payments/internal/platform/authn" |
| 20 | "github.com/fiston-user/payments/internal/platform/config" |
| 21 | "github.com/fiston-user/payments/internal/platform/debug" |
| 22 | "github.com/fiston-user/payments/internal/platform/health" |
| 23 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 24 | "github.com/fiston-user/payments/internal/platform/logging" |
| 25 | "github.com/fiston-user/payments/internal/platform/mtls" |
| 26 | "github.com/fiston-user/payments/internal/platform/natsx" |
| 27 | "github.com/fiston-user/payments/internal/platform/outbox" |
| 28 | "github.com/fiston-user/payments/internal/platform/postgres" |
| 29 | "github.com/fiston-user/payments/internal/platform/redis" |
| 30 | "github.com/fiston-user/payments/internal/platform/telemetry" |
| 31 | "github.com/fiston-user/payments/internal/transfer" |
| 32 | "github.com/fiston-user/payments/internal/transfer/risk" |
| 33 | "github.com/fiston-user/payments/internal/transfer/transferevents" |
| 34 | "github.com/fiston-user/payments/internal/wallet/walletclient" |
| 35 | "github.com/nats-io/nats.go/jetstream" |
| 36 | "github.com/prometheus/client_golang/prometheus/promhttp" |
| 37 | "google.golang.org/grpc/credentials" |
| 38 | ) |
| 39 | |
| 40 | // version is stamped at build time: go build -ldflags "-X main.version=v1.2.3". |
| 41 | var version = "dev" |
| 42 | |
| 43 | func main() { |
| 44 | healthcheck := flag.Bool("healthcheck", false, "exit 0 if the service is ready: for Docker") |
| 45 | migrate := flag.Bool("migrate", false, "apply the database migrations, and exit") |
| 46 | flag.Parse() |
| 47 | cfg, err := loadConfig(config.New(os.LookupEnv)) |
| 48 | if err != nil { |
| 49 | // There's no logger yet: its settings are part of the configuration. |
| 50 | fmt.Fprintln(os.Stderr, "transfer:", err) |
| 51 | os.Exit(2) |
| 52 | } |
| 53 | // Docker's health check: the binary checks itself, then exits. |
| 54 | if *healthcheck { |
| 55 | if err := health.Probe(cfg.HTTPAddr); err != nil { |
| 56 | fmt.Fprintln(os.Stderr, err) |
| 57 | os.Exit(1) |
| 58 | } |
| 59 | return |
| 60 | } |
| 61 | logger := logging.New(os.Stdout, logging.Options{ |
| 62 | Service: "transfer", |
| 63 | Version: version, |
| 64 | Level: cfg.LogLevel, |
| 65 | Format: cfg.LogFormat, |
| 66 | }) |
| 67 | // Code that logs through the slog package functions gets our logger too. |
| 68 | slog.SetDefault(logger) |
| 69 | logger.Info("starting", "env", cfg.Env, "log_level", cfg.LogLevel.String()) |
| 70 | |
| 71 | // Apply the migrations, then exit: the one-shot step before a new version |
| 72 | // starts, in Compose, and in Kubernetes. |
| 73 | if *migrate { |
| 74 | version, err := postgres.Migrate(cfg.DatabaseURL, db.Migrations("transfer")) |
| 75 | if err != nil { |
| 76 | logger.Error("migrate", "err", err) |
| 77 | os.Exit(1) |
| 78 | } |
| 79 | logger.Info("database migrated", "schema_version", version) |
| 80 | return |
| 81 | } |
| 82 | |
| 83 | // Traces go to the collector in OTEL_EXPORTER_OTLP_ENDPOINT, if there is one. |
| 84 | stopTracing, err := telemetry.Setup(context.Background(), |
| 85 | telemetry.Options{Service: "transfer", Version: version, Env: cfg.Env}) |
| 86 | if err != nil { |
| 87 | logger.Error("telemetry", "err", err) |
| 88 | os.Exit(1) |
| 89 | } |
| 90 | |
| 91 | pool, err := postgres.NewPool(context.Background(), cfg.DatabaseURL, int32(cfg.DBMaxConns)) |
| 92 | if err != nil { |
| 93 | logger.Error("connect to postgres", "err", err) |
| 94 | os.Exit(1) |
| 95 | } |
| 96 | logger.Info("connected to postgres", "max_conns", pool.Config().MaxConns) |
| 97 | outbox.RegisterMetrics(pool) |
| 98 | postgres.RegisterMetrics("main", pool) |
| 99 | |
| 100 | // NATS, for events. Like Postgres, it must be there when we start. |
| 101 | nc, err := natsx.Connect(cfg.NATSURL, "transfer", logger) |
| 102 | if err != nil { |
| 103 | logger.Error("connect to nats", "err", err) |
| 104 | os.Exit(1) |
| 105 | } |
| 106 | logger.Info("connected to nats", "url", nc.ConnectedUrl()) |
| 107 | js, err := jetstream.New(nc) |
| 108 | if err != nil { |
| 109 | logger.Error("jetstream", "err", err) |
| 110 | os.Exit(1) |
| 111 | } |
| 112 | stream := transferevents.StreamConfig(cfg.NATSReplicas) |
| 113 | if err := natsx.EnsureStream(context.Background(), js, stream); err != nil { |
| 114 | logger.Error("create stream", "err", err) |
| 115 | os.Exit(1) |
| 116 | } |
| 117 | |
| 118 | // The auth service's public key: enough to check access tokens, and |
| 119 | // useless for making them. |
| 120 | pub, err := authn.ReadPublicKey(cfg.PublicKeyFile) |
| 121 | if err != nil { |
| 122 | logger.Error("read auth public key", "err", err) |
| 123 | os.Exit(1) |
| 124 | } |
| 125 | verifier := authn.NewVerifier(pub) |
| 126 | // Our certificate, and our CA's: for mTLS with our other services. |
| 127 | certs, err := mtls.Load(cfg.TLSDir) |
| 128 | if err != nil { |
| 129 | logger.Error("load certificates", "err", err) |
| 130 | os.Exit(1) |
| 131 | } |
| 132 | |
| 133 | // The wallet's gRPC API, over mTLS. Each call gets three seconds, retries included. |
| 134 | creds := credentials.NewTLS(certs.Client("wallet")) |
| 135 | wallet, err := walletclient.New(cfg.WalletAddr, creds, 3*time.Second) |
| 136 | if err != nil { |
| 137 | logger.Error("wallet client", "err", err) |
| 138 | os.Exit(1) |
| 139 | } |
| 140 | // Redis keeps the velocity counters. Like the gateway's limiter, it's never |
| 141 | // a reason to be unready: without it, transfers go to review. |
| 142 | rdb, err := redis.NewClient(cfg.RedisURL) |
| 143 | if err != nil { |
| 144 | logger.Error("redis", "err", err) |
| 145 | os.Exit(1) |
| 146 | } |
| 147 | rates, err := fx.DevRates(cfg.Env) |
| 148 | if err != nil { |
| 149 | logger.Error("fx rates", "err", err) |
| 150 | os.Exit(1) |
| 151 | } |
| 152 | store := transfer.NewStore(pool) |
| 153 | store.ReviewTimeout = cfg.ReviewTimeout |
| 154 | engine := risk.NewEngine(risk.Rules(cfg.Risk)...) |
| 155 | velocity := risk.NewVelocity(rdb, cfg.Risk.CountWindow, cfg.Risk.AmountWindow) |
| 156 | screener := transfer.NewRiskScreener(engine, velocity, wallet, store, rates, logger) |
| 157 | orchestrator := transfer.NewOrchestrator(store, transfer.NewWallet(wallet), screener, logger) |
| 158 | |
| 159 | // Like the wallet: ready with its database. Events wait in the outbox. |
| 160 | probes := health.New(logger, map[string]health.Check{"postgres": pool.Ping}) |
| 161 | mux := http.NewServeMux() |
| 162 | probes.Register(mux) |
| 163 | // For Prometheus, which scrapes it every few seconds. The gateway never routes it. |
| 164 | mux.Handle("GET /metrics", promhttp.Handler()) |
| 165 | |
| 166 | // The transfer API, where every route needs an access token. A new |
| 167 | // transfer wakes the orchestrator up. |
| 168 | api := http.NewServeMux() |
| 169 | handler := transfer.NewHandler(store, orchestrator.Wake) |
| 170 | handler.Register(api) |
| 171 | api.HandleFunc("/", httpx.NotFound) |
| 172 | mux.Handle("/v1/", verifier.Require(httpx.Routes(api))) |
| 173 | // The review API, over mTLS: only our back office's tools, ops, may call |
| 174 | // it, for a reviewer who signed in, with the reviewer role. |
| 175 | internal := http.NewServeMux() |
| 176 | handler.RegisterInternal(internal) |
| 177 | internal.HandleFunc("/", httpx.NotFound) |
| 178 | mux.Handle("/internal/", httpx.Chain(httpx.Routes(internal), |
| 179 | mtls.Allow("ops"), verifier.Require, authn.RequireRole("reviewer"))) |
| 180 | // Go's profiler, for our ops tools: their certificate, and no reviewer. |
| 181 | mux.Handle("/internal/debug/", mtls.Allow("ops")(debug.Handler())) |
| 182 | mux.HandleFunc("/", httpx.NotFound) |
| 183 | |
| 184 | srv := &http.Server{ |
| 185 | Addr: cfg.HTTPAddr, |
| 186 | Handler: httpx.Chain(httpx.Routes(mux), |
| 187 | httpx.Observe(), |
| 188 | httpx.RequestID, |
| 189 | httpx.AccessLog(logger), |
| 190 | httpx.Recover(logger), |
| 191 | ), |
| 192 | ReadHeaderTimeout: 5 * time.Second, |
| 193 | ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn), |
| 194 | } |
| 195 | |
| 196 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 197 | defer stop() |
| 198 | |
| 199 | // The orchestrator and the relay have contexts of their own: they keep |
| 200 | // working while the server drains, and stop after it, in that order. |
| 201 | orchCtx, stopOrch := context.WithCancel(context.Background()) |
| 202 | relayCtx, stopRelay := context.WithCancel(context.Background()) |
| 203 | var orch, relay sync.WaitGroup |
| 204 | orch.Go(func() { orchestrator.Run(orchCtx) }) |
| 205 | relay.Go(func() { outbox.NewRelay(pool, js, logger).Run(relayCtx) }) |
| 206 | |
| 207 | go func() { |
| 208 | logger.Info("transfer service listening", "addr", srv.Addr) |
| 209 | if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 210 | logger.Error("server failed", "err", err) |
| 211 | os.Exit(1) |
| 212 | } |
| 213 | }() |
| 214 | |
| 215 | // The internal port: the same routes, over mTLS. Only what comes in |
| 216 | // through it gets past mtls.Allow. |
| 217 | go func() { |
| 218 | lis, err := tls.Listen("tcp", cfg.InternalAddr, certs.Server()) |
| 219 | if err == nil { |
| 220 | err = srv.Serve(lis) |
| 221 | } |
| 222 | if !errors.Is(err, http.ErrServerClosed) { |
| 223 | logger.Error("internal server failed", "err", err) |
| 224 | os.Exit(1) |
| 225 | } |
| 226 | }() |
| 227 | |
| 228 | <-ctx.Done() |
| 229 | logger.Info("shutting down gracefully") |
| 230 | // Readiness fails first, so load balancers stop sending us new requests. |
| 231 | probes.Drain(cfg.DrainDelay) |
| 232 | |
| 233 | shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) |
| 234 | defer cancel() |
| 235 | |
| 236 | if err := srv.Shutdown(shutdownCtx); err != nil { |
| 237 | logger.Error("http shutdown failed", "err", err) |
| 238 | } |
| 239 | logger.Info("server stopped") |
| 240 | // Steps in flight finish, and are written down. Then the relay publishes |
| 241 | // the events they wrote. Anything left over goes out on the next start. |
| 242 | stopOrch() |
| 243 | orch.Wait() |
| 244 | stopRelay() |
| 245 | relay.Wait() |
| 246 | logger.Info("orchestrator and outbox relay stopped") |
| 247 | |
| 248 | wallet.Close() |
| 249 | rdb.Close() |
| 250 | nc.Close() |
| 251 | pool.Close() |
| 252 | logger.Info("wallet client, nats and database pool closed") |
| 253 | // Last, the spans still waiting in the batch, from everything that stopped. |
| 254 | if err := stopTracing(shutdownCtx); err != nil { |
| 255 | logger.Error("flush traces", "err", err) |
| 256 | } |
| 257 | } |