package sww import ( "context" "errors" "io" "log/slog" "net" "net/http" "time" "go.uber.org/fx" "go.uber.org/fx/fxevent" ) // shutdownTimeout is how long requests in progress may take to finish // once sww is told to stop, before their connections are closed. // runit and docker wait a little longer before they kill the process. const shutdownTimeout = 5 * time.Second // requestLog is where a daemon's server writes the request log: stdout, and // the remote log sender while there is one. fx tells parts apart by type, so // it has a type of its own. type requestLog struct { io.Writer } // servingFailed gets why serving failed, for run, which then stops the // daemon. fx tells parts apart by type, so it has a type of its own. type servingFailed chan error // utcNow is the time the state files, the alerts and the rate limits go by. func utcNow() time.Time { return time.Now().UTC() } // startError is why a daemon cannot start: the message its process log gives, // and the error it logs with it. type startError struct { message string err error } func (e startError) Error() string { return e.message + ": " + e.err.Error() } func (e startError) Unwrap() error { return e.err } // cannotStart logs why a daemon cannot start, with the message of the // startError in err, and returns its exit status. func cannotStart(processLog *slog.Logger, err error) int { message, cause := "cannot start", err failed, ok := errors.AsType[startError](err) if ok { message, cause = failed.message, failed.err } processLog.Error(message, "error", cause.Error()) return 1 } // listen listens on address, which the setting names. func listen(address, setting string) (net.Listener, error) { listener, err := (&net.ListenConfig{}).Listen( context.Background(), "tcp", address) if err != nil { return nil, startError{"cannot listen on " + setting, err} } return listener, nil } // background returns the hook that runs loop on a goroutine of its own from // the start, and at the stop ends it and waits for it to return. func background(loop func(context.Context)) fx.Hook { running, stop := context.WithCancel(context.Background()) ended := make(chan struct{}) return fx.StartStopHook( func() { go func() { loop(running) close(ended) }() }, func() { stop() <-ended }, ) } // serve serves requests on listener from the start. At the stop it gives the // requests in progress shutdownTimeout to finish, then closes their // connections. When serving fails, it logs why and sends the error to // failed. func serve( lc fx.Lifecycle, server *http.Server, listener net.Listener, processLog *slog.Logger, failed servingFailed, ) { served := make(chan error, 1) lc.Append(fx.Hook{ OnStart: func(context.Context) error { go func() { err := server.Serve(listener) if !errors.Is(err, http.ErrServerClosed) { processLog.Error("serving failed", "error", err.Error()) failed <- err } served <- err }() return nil }, OnStop: func(ctx context.Context) error { processLog.Info("stopping") shutdownCtx, cancel := context.WithTimeout(ctx, shutdownTimeout) defer cancel() err := server.Shutdown(shutdownCtx) if err != nil { processLog.Warn("requests still in progress were cut off", "error", err.Error()) _ = server.Close() } err = <-served if !errors.Is(err, http.ErrServerClosed) { return err } return nil }, }) } // run starts app, which serves until ctx is done or serving fails, as // failed tells. Then it stops app and takes the daemon's last step. It // returns the process's exit status, 1 when serving failed, a part could // not stop in order or the last step failed; each logs why. func run( ctx context.Context, app *fx.App, failed servingFailed, processLog *slog.Logger, lastStep func() error, ) int { // The hooks only start goroutines, and end them at the stop, so neither // is cut short by a deadline or by ctx. err := app.Start(context.WithoutCancel(ctx)) if err != nil { return cannotStart(processLog, err) } status := 0 select { case <-ctx.Done(): case <-failed: status = 1 } err = app.Stop(context.WithoutCancel(ctx)) if err != nil { status = 1 } err = lastStep() if err != nil { status = 1 } if status == 0 { processLog.Info("stopped") } return status } // fxEventLogger returns what fx.WithLogger takes to write fx's own events to // processLog at debug, which the daemons' log levels normally hold back. Its // errors are at debug too: the daemon logs each one itself. func fxEventLogger(processLog *slog.Logger) func() fxevent.Logger { return func() fxevent.Logger { logger := &fxevent.SlogLogger{Logger: processLog} logger.UseLogLevel(slog.LevelDebug) logger.UseErrorLevel(slog.LevelDebug) return logger } }