314 lines
9.8 KiB
Go
314 lines
9.8 KiB
Go
package bootstrap
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/wahrwelt-kit/go-logkit"
|
|
|
|
"lincodex/backend/config"
|
|
"lincodex/backend/internal/adapter/secondary/prometheus"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/worker/deliverymetrics"
|
|
"lincodex/backend/internal/worker/jobrunner"
|
|
"lincodex/backend/internal/worker/mailsender"
|
|
"lincodex/backend/internal/worker/outboxrelay"
|
|
)
|
|
|
|
const (
|
|
readHeaderTimeout = 5 * time.Second
|
|
idleTimeout = time.Minute
|
|
)
|
|
|
|
type Application struct {
|
|
config config.Config
|
|
apiHandler http.Handler
|
|
metrics *prometheus.Metrics
|
|
logger *slog.Logger
|
|
// mailSender is the transport selected by EMAIL_PROVIDER. Only the mail
|
|
// sending worker calls it.
|
|
mailSender outbound.MailSender
|
|
// relay publishes outbox events while the servers run. It is nil when
|
|
// the relay is disabled or the database is not configured.
|
|
relay *outboxrelay.Relay
|
|
// consumers apply events from the event bus while the servers run. The
|
|
// list is empty until a handler is registered in eventHandlers.
|
|
consumers eventConsumers
|
|
// jobs runs scheduled jobs when they fall due while the servers run. It
|
|
// is nil when the worker is disabled, no job kind is registered, or the
|
|
// database is not configured.
|
|
jobs *jobrunner.Worker
|
|
// mailSending sends the stored service mail of the account flows while
|
|
// the servers run. It is nil with EMAIL_PROVIDER=disabled or when the
|
|
// database is not configured.
|
|
mailSending *mailsender.Worker
|
|
// notificationSending sends the stored product notifications while the
|
|
// servers run, after their rights checks. It is nil under the same
|
|
// conditions as mailSending.
|
|
notificationSending *notificationSendingWorker
|
|
// deliveryMetrics reads the delivery and quota gauges while the servers
|
|
// run. It is nil when the database is not configured.
|
|
deliveryMetrics *deliverymetrics.Sampler
|
|
}
|
|
|
|
func NewApplication(
|
|
config config.Config,
|
|
apiHandler http.Handler,
|
|
metrics *prometheus.Metrics,
|
|
logger *slog.Logger,
|
|
mailSender outbound.MailSender,
|
|
relay *outboxrelay.Relay,
|
|
consumers eventConsumers,
|
|
jobs *jobrunner.Worker,
|
|
mailSending *mailsender.Worker,
|
|
notificationSending *notificationSendingWorker,
|
|
deliveryMetrics *deliverymetrics.Sampler,
|
|
) *Application {
|
|
return &Application{
|
|
config: config,
|
|
apiHandler: apiHandler,
|
|
metrics: metrics,
|
|
logger: logger,
|
|
mailSender: mailSender,
|
|
relay: relay,
|
|
consumers: consumers,
|
|
jobs: jobs,
|
|
mailSending: mailSending,
|
|
notificationSending: notificationSending,
|
|
deliveryMetrics: deliveryMetrics,
|
|
}
|
|
}
|
|
|
|
func Run() (runErr error) {
|
|
settings, err := config.Load()
|
|
if err != nil {
|
|
return fmt.Errorf("bootstrap.Run - load configuration: %w", err)
|
|
}
|
|
|
|
log, err := logkit.New(
|
|
logkit.WithLevel(logLevel(settings.LogLevel)),
|
|
logkit.WithServiceName("lincodex-backend"),
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("bootstrap.Run - create logger: %w", err)
|
|
}
|
|
defer func() {
|
|
if err := log.Close(); err != nil {
|
|
runErr = errors.Join(runErr, fmt.Errorf("bootstrap.Run - close logger: %w", err))
|
|
}
|
|
}()
|
|
logger := slog.New(logkit.SlogHandler(log))
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
if err := run(ctx, settings, logger); err != nil {
|
|
return err
|
|
}
|
|
logger.Info("application stopped")
|
|
return nil
|
|
}
|
|
|
|
func run(ctx context.Context, config config.Config, logger *slog.Logger) error {
|
|
application, cleanup, err := start(ctx, config, logger)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer cleanup()
|
|
return application.run(ctx)
|
|
}
|
|
|
|
// start prepares the application without opening listeners. The mail
|
|
// transport is selected before migrations, so a configuration that cannot
|
|
// start never changes the database. The demo policy seed and the mail quota
|
|
// report run after the migrations that create their tables.
|
|
func start(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) {
|
|
if err := config.Validate(); err != nil {
|
|
return nil, nil, fmt.Errorf("bootstrap.start - validate configuration: %w", err)
|
|
}
|
|
mailSender, err := newMailSender(config, logger)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("bootstrap.start - select mail transport: %w", err)
|
|
}
|
|
if err := migrateDatabase(ctx, config, logger); err != nil {
|
|
return nil, nil, fmt.Errorf("bootstrap.start - migrate database: %w", err)
|
|
}
|
|
if err := seedDemoPolicy(ctx, config, logger); err != nil {
|
|
return nil, nil, fmt.Errorf("bootstrap.start - seed demo policy: %w", err)
|
|
}
|
|
reportMailQuota(ctx, config, logger)
|
|
application, cleanup, err := initialize(ctx, config, logger, mailSender)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err)
|
|
}
|
|
return application, cleanup, nil
|
|
}
|
|
|
|
func logLevel(value string) logkit.Level {
|
|
switch value {
|
|
case "debug":
|
|
return logkit.DebugLevel
|
|
case "warn":
|
|
return logkit.WarnLevel
|
|
case "error":
|
|
return logkit.ErrorLevel
|
|
default:
|
|
return logkit.InfoLevel
|
|
}
|
|
}
|
|
|
|
func (application *Application) run(ctx context.Context) error {
|
|
var listenerConfig net.ListenConfig
|
|
apiListener, err := listenerConfig.Listen(ctx, "tcp", application.config.HTTPAddr)
|
|
if err != nil {
|
|
return fmt.Errorf("Application.run - listen on HTTP_ADDR: %w", err)
|
|
}
|
|
metricsListener, err := listenerConfig.Listen(ctx, "tcp", application.config.MetricsAddr)
|
|
if err != nil {
|
|
// Preserve the listen failure while releasing the first socket.
|
|
_ = apiListener.Close()
|
|
return fmt.Errorf("Application.run - listen on METRICS_ADDR: %w", err)
|
|
}
|
|
application.logger.Info("servers started",
|
|
slog.String("http_addr", application.config.HTTPAddr),
|
|
slog.String("metrics_addr", application.config.MetricsAddr),
|
|
)
|
|
|
|
// The workers stop when the servers stop, including after a server
|
|
// failure that leaves ctx running.
|
|
runCtx, stopRun := context.WithCancel(ctx)
|
|
defer stopRun()
|
|
workersStopped := application.startWorkers(runCtx)
|
|
|
|
apiServer := newHTTPServer(application.apiHandler)
|
|
metricsServer := newHTTPServer(application.metrics.Handler())
|
|
err = serveServers(
|
|
runCtx,
|
|
apiListener,
|
|
apiServer,
|
|
metricsListener,
|
|
metricsServer,
|
|
application.config.ShutdownTimeout,
|
|
)
|
|
application.logger.Info("servers stopped")
|
|
stopRun()
|
|
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT, each
|
|
// consumer its record in progress within CONSUMER_SHUTDOWN_GRACE plus
|
|
// one offset commit, the job worker its job in progress within
|
|
// JOBS_SHUTDOWN_GRACE plus one release, and the mail sending worker its
|
|
// send in progress within its shutdown grace plus one settlement, so the
|
|
// cleanup that closes their pools, producer, and group members runs after
|
|
// all of them stopped.
|
|
<-workersStopped
|
|
application.logger.Info("workers stopped")
|
|
return err
|
|
}
|
|
|
|
// startWorkers runs the relay, every consumer, the scheduled job worker, the
|
|
// mail sending worker, and the delivery metrics sampler until ctx ends and returns a channel that
|
|
// closes when all of them have stopped. The workers stop together with the
|
|
// servers; none of them depends on another.
|
|
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
|
|
var workers sync.WaitGroup
|
|
if application.relay != nil {
|
|
workers.Go(func() { application.relay.Run(ctx) })
|
|
}
|
|
for _, consumer := range application.consumers {
|
|
workers.Go(func() { consumer.Run(ctx) })
|
|
}
|
|
if application.jobs != nil {
|
|
workers.Go(func() { application.jobs.Run(ctx) })
|
|
}
|
|
if application.mailSending != nil {
|
|
workers.Go(func() { application.mailSending.Run(ctx) })
|
|
}
|
|
if application.notificationSending != nil {
|
|
workers.Go(func() { application.notificationSending.Run(ctx) })
|
|
}
|
|
if application.deliveryMetrics != nil {
|
|
workers.Go(func() { application.deliveryMetrics.Run(ctx) })
|
|
}
|
|
stopped := make(chan struct{})
|
|
go func() {
|
|
defer close(stopped)
|
|
workers.Wait()
|
|
}()
|
|
return stopped
|
|
}
|
|
|
|
func newHTTPServer(handler http.Handler) *http.Server {
|
|
return &http.Server{
|
|
Handler: handler,
|
|
ReadHeaderTimeout: readHeaderTimeout,
|
|
IdleTimeout: idleTimeout,
|
|
}
|
|
}
|
|
|
|
func serveServers(
|
|
ctx context.Context,
|
|
apiListener net.Listener,
|
|
apiServer *http.Server,
|
|
metricsListener net.Listener,
|
|
metricsServer *http.Server,
|
|
shutdownTimeout time.Duration,
|
|
) error {
|
|
type serveResult struct {
|
|
name string
|
|
err error
|
|
}
|
|
servers := []struct {
|
|
name string
|
|
server *http.Server
|
|
listener net.Listener
|
|
}{
|
|
{name: "API", server: apiServer, listener: apiListener},
|
|
{name: "metrics", server: metricsServer, listener: metricsListener},
|
|
}
|
|
results := make(chan serveResult, len(servers))
|
|
for _, entry := range servers {
|
|
go func() { results <- serveResult{name: entry.name, err: entry.server.Serve(entry.listener)} }()
|
|
}
|
|
|
|
serving := len(servers)
|
|
var runErr error
|
|
select {
|
|
case <-ctx.Done():
|
|
case result := <-results:
|
|
serving--
|
|
if result.err != nil && !errors.Is(result.err, http.ErrServerClosed) {
|
|
runErr = fmt.Errorf("bootstrap.serveServers - %s server stopped: %w", result.name, result.err)
|
|
}
|
|
}
|
|
|
|
shutdownContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout)
|
|
defer cancel()
|
|
var shutdownErr error
|
|
for _, entry := range servers {
|
|
if err := entry.server.Shutdown(shutdownContext); err != nil {
|
|
shutdownErr = errors.Join(shutdownErr, err)
|
|
if closeErr := entry.server.Close(); closeErr != nil {
|
|
shutdownErr = errors.Join(shutdownErr, closeErr)
|
|
}
|
|
}
|
|
}
|
|
for serving > 0 {
|
|
result := <-results
|
|
serving--
|
|
if result.err != nil && !errors.Is(result.err, http.ErrServerClosed) {
|
|
runErr = errors.Join(runErr, fmt.Errorf("bootstrap.serveServers - %s server stopped: %w", result.name, result.err))
|
|
}
|
|
}
|
|
if shutdownErr != nil {
|
|
return errors.Join(runErr, fmt.Errorf("bootstrap.serveServers - shut down servers: %w", shutdownErr))
|
|
}
|
|
return runErr
|
|
}
|