main.go175 lines, 5.5 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/db" |
| 17 | "github.com/fiston-user/payments/internal/auth" |
| 18 | "github.com/fiston-user/payments/internal/platform/authn" |
| 19 | "github.com/fiston-user/payments/internal/platform/config" |
| 20 | "github.com/fiston-user/payments/internal/platform/health" |
| 21 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 22 | "github.com/fiston-user/payments/internal/platform/logging" |
| 23 | "github.com/fiston-user/payments/internal/platform/mtls" |
| 24 | "github.com/fiston-user/payments/internal/platform/postgres" |
| 25 | "github.com/fiston-user/payments/internal/platform/telemetry" |
| 26 | "github.com/prometheus/client_golang/prometheus/promhttp" |
| 27 | ) |
| 28 | |
| 29 | // version is stamped at build time: go build -ldflags "-X main.version=v1.2.3". |
| 30 | var version = "dev" |
| 31 | |
| 32 | func main() { |
| 33 | healthcheck := flag.Bool("healthcheck", false, "exit 0 if the service is ready: for Docker") |
| 34 | migrate := flag.Bool("migrate", false, "apply the database migrations, and exit") |
| 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, "auth:", 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.HTTPAddr); 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: "auth", |
| 52 | Version: version, |
| 53 | Level: cfg.LogLevel, |
| 54 | Format: cfg.LogFormat, |
| 55 | }) |
| 56 | // Code that logs through the slog package functions gets our logger too. |
| 57 | slog.SetDefault(logger) |
| 58 | logger.Info("starting", "env", cfg.Env, "log_level", cfg.LogLevel.String()) |
| 59 | |
| 60 | // Apply the migrations, then exit: the one-shot step before a new version |
| 61 | // starts, in Compose, and in Kubernetes. |
| 62 | if *migrate { |
| 63 | version, err := postgres.Migrate(cfg.DatabaseURL, db.Migrations("auth")) |
| 64 | if err != nil { |
| 65 | logger.Error("migrate", "err", err) |
| 66 | os.Exit(1) |
| 67 | } |
| 68 | logger.Info("database migrated", "schema_version", version) |
| 69 | return |
| 70 | } |
| 71 | |
| 72 | // Traces go to the collector in OTEL_EXPORTER_OTLP_ENDPOINT, if there is one. |
| 73 | stopTracing, err := telemetry.Setup(context.Background(), |
| 74 | telemetry.Options{Service: "auth", Version: version, Env: cfg.Env}) |
| 75 | if err != nil { |
| 76 | logger.Error("telemetry", "err", err) |
| 77 | os.Exit(1) |
| 78 | } |
| 79 | |
| 80 | pool, err := postgres.NewPool(context.Background(), cfg.DatabaseURL, int32(cfg.DBMaxConns)) |
| 81 | if err != nil { |
| 82 | logger.Error("connect to postgres", "err", err) |
| 83 | os.Exit(1) |
| 84 | } |
| 85 | logger.Info("connected to postgres", "max_conns", pool.Config().MaxConns) |
| 86 | |
| 87 | // The private key signs access tokens. Without it, we can't do our job. |
| 88 | key, err := auth.ReadPrivateKey(cfg.PrivateKeyFile) |
| 89 | if err != nil { |
| 90 | logger.Error("read signing key", "err", err) |
| 91 | os.Exit(1) |
| 92 | } |
| 93 | signer := auth.NewSigner(key, cfg.AccessTTL) |
| 94 | logger.Info("signing key loaded", "kid", authn.KeyID(signer.PublicKey())) |
| 95 | // Our certificate, and our CA's: for mTLS with our other services. |
| 96 | certs, err := mtls.Load(cfg.TLSDir) |
| 97 | if err != nil { |
| 98 | logger.Error("load certificates", "err", err) |
| 99 | os.Exit(1) |
| 100 | } |
| 101 | |
| 102 | probes := health.New(logger, map[string]health.Check{"postgres": pool.Ping}) |
| 103 | mux := http.NewServeMux() |
| 104 | probes.Register(mux) |
| 105 | // For Prometheus, which scrapes it every few seconds. The gateway never routes it. |
| 106 | mux.Handle("GET /metrics", promhttp.Handler()) |
| 107 | |
| 108 | // The auth API, and a JSON 404 for everything else. |
| 109 | svc := auth.NewService(pool, signer, cfg.RefreshTTL) |
| 110 | handler := auth.NewHandler(svc, authn.NewVerifier(signer.PublicKey())) |
| 111 | handler.Register(mux) |
| 112 | // Users' email addresses, over mTLS: only the notification service may ask. |
| 113 | internal := http.NewServeMux() |
| 114 | handler.RegisterInternal(internal) |
| 115 | internal.HandleFunc("/", httpx.NotFound) |
| 116 | mux.Handle("/internal/", mtls.Allow("notification")(httpx.Routes(internal))) |
| 117 | mux.HandleFunc("/", httpx.NotFound) |
| 118 | |
| 119 | srv := &http.Server{ |
| 120 | Addr: cfg.HTTPAddr, |
| 121 | Handler: httpx.Chain(httpx.Routes(mux), |
| 122 | httpx.Observe(), |
| 123 | httpx.RequestID, |
| 124 | httpx.AccessLog(logger), |
| 125 | httpx.Recover(logger), |
| 126 | ), |
| 127 | ReadHeaderTimeout: 5 * time.Second, |
| 128 | ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn), |
| 129 | } |
| 130 | |
| 131 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 132 | defer stop() |
| 133 | |
| 134 | go func() { |
| 135 | logger.Info("auth service listening", "addr", srv.Addr) |
| 136 | if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 137 | logger.Error("server failed", "err", err) |
| 138 | os.Exit(1) |
| 139 | } |
| 140 | }() |
| 141 | |
| 142 | // The internal port: the same routes, over mTLS. Only what comes in |
| 143 | // through it gets past mtls.Allow. |
| 144 | go func() { |
| 145 | lis, err := tls.Listen("tcp", cfg.InternalAddr, certs.Server()) |
| 146 | if err == nil { |
| 147 | err = srv.Serve(lis) |
| 148 | } |
| 149 | if !errors.Is(err, http.ErrServerClosed) { |
| 150 | logger.Error("internal server failed", "err", err) |
| 151 | os.Exit(1) |
| 152 | } |
| 153 | }() |
| 154 | |
| 155 | <-ctx.Done() |
| 156 | logger.Info("shutting down gracefully") |
| 157 | // Readiness fails first, so load balancers stop sending us new requests. |
| 158 | probes.Drain(cfg.DrainDelay) |
| 159 | |
| 160 | shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) |
| 161 | defer cancel() |
| 162 | |
| 163 | if err := srv.Shutdown(shutdownCtx); err != nil { |
| 164 | logger.Error("shutdown failed", "err", err) |
| 165 | } |
| 166 | logger.Info("server stopped") |
| 167 | |
| 168 | // Close the pool last: requests that were still finishing needed it. |
| 169 | pool.Close() |
| 170 | logger.Info("database pool closed") |
| 171 | // Last, the spans still waiting in the batch, from everything that stopped. |
| 172 | if err := stopTracing(shutdownCtx); err != nil { |
| 173 | logger.Error("flush traces", "err", err) |
| 174 | } |
| 175 | } |