All checks were successful
check / check (push) Successful in 6m20s
The fx OnStart hook returned as soon as the serving goroutine was spawned, so a failed listen was discovered only inside that goroutine. It logged the error and cancelled the server's own context, which nothing outside the goroutine observes: fx reported RUNNING and the process stayed alive with nothing bound. The service was down and looked up, so systemd Restart=on-failure and Docker restart policies never fired. The Server now takes fx.Shutdowner and, on a listen failure, asks it to stop the app with ListenFailureExitCode. Shutdown runs through fx's normal stop sequence, so every OnStop hook — including the HTTP drain and the database close — still executes; the clean-shutdown path is untouched. Server.exitCode goes with it. Its only writer set it to zero during cleanShutdown and its only reader was serve()'s return value, which Run discards; the process status is fx's to decide. Left in place it would have been a genuine data race, since the new path makes cleanShutdown and serve()'s return run concurrently under -race. Verified by TestListenFailure_ShutsDownTheApp, which occupies a port, starts the wired app on it, and requires a non-zero shutdown signal within two seconds. Reverting the fix fails it with "listen failure left the app running".
57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
// httpReadTimeout is the maximum duration for reading the
|
|
// entire request, including the body.
|
|
httpReadTimeout = 10 * time.Second
|
|
|
|
// httpWriteTimeout is the maximum duration before timing out
|
|
// writes of the response. It must stay above the router's
|
|
// requestTimeout (60s, in routes.go) so the middleware timeout
|
|
// fires first and returns a clean 503, rather than the transport
|
|
// cutting the connection at the socket write deadline.
|
|
httpWriteTimeout = 65 * time.Second
|
|
|
|
// httpMaxHeaderBytes is the maximum number of bytes the
|
|
// server will read parsing the request headers.
|
|
httpMaxHeaderBytes = 1 << 20
|
|
)
|
|
|
|
func (s *Server) serveUntilShutdown() {
|
|
listenAddr := fmt.Sprintf(":%d", s.params.Config.Port)
|
|
s.httpServer = &http.Server{
|
|
Addr: listenAddr,
|
|
ReadTimeout: httpReadTimeout,
|
|
WriteTimeout: httpWriteTimeout,
|
|
MaxHeaderBytes: httpMaxHeaderBytes,
|
|
Handler: s,
|
|
}
|
|
|
|
// add routes
|
|
// this does any necessary setup in each handler
|
|
s.SetupRoutes()
|
|
|
|
s.log.Info("http begin listen", "listenaddr", listenAddr)
|
|
|
|
err := s.httpServer.ListenAndServe()
|
|
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
s.log.Error("listen error", "error", err)
|
|
s.shutdownOnListenFailure()
|
|
}
|
|
}
|
|
|
|
// ServeHTTP delegates to the router.
|
|
func (s *Server) ServeHTTP(
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
) {
|
|
s.router.ServeHTTP(w, r)
|
|
}
|