// Package server runs the HTTP listener with the lifecycle the lab // requires: readiness drops first, the process keeps serving for a drain // delay while the load balancer notices, then the listener stops accepting, // in-flight requests drain within a bounded timeout and the process exits. package server import ( "context" "errors" "log/slog" "net" "net/http" "time" ) // Readiness is switched off when shutdown starts. type Readiness interface { SetReady(ready bool) } // Run serves until ctx is cancelled, keeps serving for drainDelay with // readiness off, then shuts down within shutdownTimeout. // // The balancer learns about a stopping replica only from its failing // readiness checks. Closing the listener at once would let it send requests // to a closed port, or over a kept-alive connection the server is closing, // until the checks catch up. drainDelay must therefore exceed the balancer's // detection time. func Run(ctx context.Context, log *slog.Logger, ln net.Listener, h http.Handler, ready Readiness, drainDelay, shutdownTimeout time.Duration) error { srv := &http.Server{ Handler: h, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 64 * 1024, ErrorLog: slog.NewLogLogger(log.Handler(), slog.LevelWarn), } served := make(chan error, 1) go func() { err := srv.Serve(ln) if errors.Is(err, http.ErrServerClosed) { err = nil } served <- err }() log.Info("listening", "addr", ln.Addr().String()) select { case err := <-served: return err case <-ctx.Done(): } log.Info("shutdown started", "drain_delay", drainDelay.String(), "timeout", shutdownTimeout.String()) ready.SetReady(false) time.Sleep(drainDelay) drain, cancel := context.WithTimeout(context.Background(), shutdownTimeout) defer cancel() if err := srv.Shutdown(drain); err != nil { log.Error("shutdown forced", "error", err.Error()) _ = srv.Close() return err } <-served log.Info("shutdown completed") return nil }