main.go176 lines, 5.7 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 | "syscall" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/fiston-user/payments/internal/gateway" |
| 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/debug" |
| 20 | "github.com/fiston-user/payments/internal/platform/health" |
| 21 | "github.com/fiston-user/payments/internal/platform/logging" |
| 22 | "github.com/fiston-user/payments/internal/platform/mtls" |
| 23 | "github.com/fiston-user/payments/internal/platform/redis" |
| 24 | "github.com/fiston-user/payments/internal/platform/telemetry" |
| 25 | "github.com/fiston-user/payments/internal/wallet/walletclient" |
| 26 | "github.com/prometheus/client_golang/prometheus/promhttp" |
| 27 | "google.golang.org/grpc/credentials" |
| 28 | ) |
| 29 | |
| 30 | // version is stamped at build time: go build -ldflags "-X main.version=v1.2.3". |
| 31 | var version = "dev" |
| 32 | |
| 33 | func main() { |
| 34 | healthcheck := flag.Bool("healthcheck", false, "exit 0 if the service is ready: for Docker") |
| 35 | flag.Parse() |
| 36 | cfg, err := loadConfig(config.New(os.LookupEnv)) |
| 37 | if err != nil { |
| 38 | // There's no logger yet: its settings are part of the configuration. |
| 39 | fmt.Fprintln(os.Stderr, "gateway:", err) |
| 40 | os.Exit(2) |
| 41 | } |
| 42 | // Docker's health check: the binary checks itself, then exits. |
| 43 | if *healthcheck { |
| 44 | if err := health.Probe(cfg.MetricsAddr); err != nil { |
| 45 | fmt.Fprintln(os.Stderr, err) |
| 46 | os.Exit(1) |
| 47 | } |
| 48 | return |
| 49 | } |
| 50 | logger := logging.New(os.Stdout, logging.Options{ |
| 51 | Service: "gateway", |
| 52 | Version: version, |
| 53 | Level: cfg.LogLevel, |
| 54 | Format: cfg.LogFormat, |
| 55 | }) |
| 56 | slog.SetDefault(logger) |
| 57 | logger.Info("starting", "env", cfg.Env, "log_level", cfg.LogLevel.String()) |
| 58 | |
| 59 | // Traces go to the collector in OTEL_EXPORTER_OTLP_ENDPOINT, if there is one. |
| 60 | stopTracing, err := telemetry.Setup(context.Background(), |
| 61 | telemetry.Options{Service: "gateway", Version: version, Env: cfg.Env}) |
| 62 | if err != nil { |
| 63 | logger.Error("telemetry", "err", err) |
| 64 | os.Exit(1) |
| 65 | } |
| 66 | |
| 67 | pub, err := authn.ReadPublicKey(cfg.PublicKeyFile) |
| 68 | if err != nil { |
| 69 | logger.Error("read auth public key", "err", err) |
| 70 | os.Exit(1) |
| 71 | } |
| 72 | // Redis only holds rate limits. Down, it costs us the limits, not the API. |
| 73 | rdb, err := redis.NewClient(cfg.RedisURL) |
| 74 | if err != nil { |
| 75 | logger.Error("connect to redis", "err", err) |
| 76 | os.Exit(1) |
| 77 | } |
| 78 | // One client for the whole process: every request shares its connection, |
| 79 | // over mTLS. The wallet knows us by our certificate. |
| 80 | certs, err := mtls.Load(cfg.TLSDir) |
| 81 | if err != nil { |
| 82 | logger.Error("load certificates", "err", err) |
| 83 | os.Exit(1) |
| 84 | } |
| 85 | creds := credentials.NewTLS(certs.Client("wallet")) |
| 86 | wallet, err := walletclient.New(cfg.WalletAddr, creds, 5*time.Second) |
| 87 | if err != nil { |
| 88 | logger.Error("wallet client", "err", err) |
| 89 | os.Exit(1) |
| 90 | } |
| 91 | |
| 92 | srv := &http.Server{ |
| 93 | Addr: cfg.HTTPAddr, |
| 94 | Handler: gateway.New(gateway.Config{ |
| 95 | AuthURL: cfg.AuthURL, |
| 96 | Transfers: cfg.TransferURL, |
| 97 | Webhooks: cfg.WebhookURL, |
| 98 | WalletAPI: cfg.WalletURL, |
| 99 | Wallet: wallet, |
| 100 | Verifier: authn.NewVerifier(pub), |
| 101 | Redis: rdb, |
| 102 | IPLimit: cfg.IPLimit, |
| 103 | UserLimit: cfg.UserLimit, |
| 104 | Origins: cfg.Origins, |
| 105 | Logger: logger, |
| 106 | }), |
| 107 | // We face the internet: every phase of a request has a limit. |
| 108 | ReadHeaderTimeout: 5 * time.Second, // slowloris: headers sent a byte at a time |
| 109 | ReadTimeout: 10 * time.Second, // the whole request, body included |
| 110 | WriteTimeout: 15 * time.Second, // longer than any upstream timeout |
| 111 | IdleTimeout: 60 * time.Second, // keep-alive connections between requests |
| 112 | MaxHeaderBytes: 16 << 10, |
| 113 | ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn), |
| 114 | } |
| 115 | |
| 116 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 117 | defer stop() |
| 118 | |
| 119 | // Metrics and probes, on a port of their own: the gateway's port faces the |
| 120 | // internet. It checks nothing else: if it checked the services behind it, |
| 121 | // one of them down would take every gateway out with it. |
| 122 | probes := health.New(logger, nil) |
| 123 | ops := http.NewServeMux() |
| 124 | ops.Handle("GET /metrics", promhttp.Handler()) |
| 125 | ops.Handle("/internal/debug/", mtls.Allow("ops")(debug.Handler())) |
| 126 | probes.Register(ops) |
| 127 | metrics := &http.Server{Addr: cfg.MetricsAddr, Handler: ops, ReadHeaderTimeout: 5 * time.Second} |
| 128 | go func() { |
| 129 | if err := metrics.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 130 | logger.Error("metrics server failed", "err", err) |
| 131 | os.Exit(1) |
| 132 | } |
| 133 | }() |
| 134 | // The same mux over mTLS, on the internal port: the only way to the |
| 135 | // profiler, which mtls.Allow keeps for our ops tools. |
| 136 | go func() { |
| 137 | lis, err := tls.Listen("tcp", cfg.InternalAddr, certs.Server()) |
| 138 | if err == nil { |
| 139 | err = metrics.Serve(lis) |
| 140 | } |
| 141 | if !errors.Is(err, http.ErrServerClosed) { |
| 142 | logger.Error("internal server failed", "err", err) |
| 143 | os.Exit(1) |
| 144 | } |
| 145 | }() |
| 146 | |
| 147 | go func() { |
| 148 | logger.Info("gateway listening", "addr", srv.Addr, |
| 149 | "auth", cfg.AuthURL.String(), "wallet", cfg.WalletAddr, "transfer", cfg.TransferURL.String()) |
| 150 | if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 151 | logger.Error("server failed", "err", err) |
| 152 | os.Exit(1) |
| 153 | } |
| 154 | }() |
| 155 | |
| 156 | <-ctx.Done() |
| 157 | logger.Info("shutting down gracefully") |
| 158 | // Readiness fails first, so load balancers stop sending us new requests. |
| 159 | probes.Drain(cfg.DrainDelay) |
| 160 | |
| 161 | shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) |
| 162 | defer cancel() |
| 163 | if err := srv.Shutdown(shutdownCtx); err != nil { |
| 164 | logger.Error("shutdown failed", "err", err) |
| 165 | } |
| 166 | metrics.Shutdown(shutdownCtx) |
| 167 | logger.Info("server stopped") |
| 168 | |
| 169 | wallet.Close() |
| 170 | rdb.Close() |
| 171 | logger.Info("wallet and redis clients closed") |
| 172 | // Last, the spans still waiting in the batch, from everything that stopped. |
| 173 | if err := stopTracing(shutdownCtx); err != nil { |
| 174 | logger.Error("flush traces", "err", err) |
| 175 | } |
| 176 | } |