diff --git a/cmd/devbox-hub/main.go b/cmd/devbox-hub/main.go index bfee547..52cfdd4 100644 --- a/cmd/devbox-hub/main.go +++ b/cmd/devbox-hub/main.go @@ -179,6 +179,10 @@ func serveCmd() *cobra.Command { MaxHeaderBytes: 1 << 20, } + // On shutdown, drop SSE streams first — otherwise the drain waits the full + // timeout, since every connected client daemon holds a long-lived /v1/events stream. + httpSrv.RegisterOnShutdown(srv.CloseEventStreams) + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() diff --git a/internal/hub/events.go b/internal/hub/events.go index ba3adcf..b69786c 100644 --- a/internal/hub/events.go +++ b/internal/hub/events.go @@ -16,9 +16,19 @@ import ( type broker struct { mu sync.Mutex subs map[chan proto.Event]string // channel -> share filter ("" = all shares) + + done chan struct{} // closed once to tell every SSE handler to return + closeOnce sync.Once } -func newBroker() *broker { return &broker{subs: map[chan proto.Event]string{}} } +func newBroker() *broker { + return &broker{subs: map[chan proto.Event]string{}, done: make(chan struct{})} +} + +// shutdown signals every active SSE handler to return. Without it, graceful +// shutdown waits the full drain timeout because long-lived /v1/events streams +// never go idle on their own (every connected client daemon holds one). +func (b *broker) shutdown() { b.closeOnce.Do(func() { close(b.done) }) } func (b *broker) sub(share string) chan proto.Event { ch := make(chan proto.Event, 16) @@ -54,6 +64,11 @@ func (b *broker) publish(ev proto.Event) { } // handleEvents streams change events to a device as Server-Sent Events. +// CloseEventStreams makes every active /v1/events handler return promptly, so a +// graceful Shutdown isn't held hostage by long-lived SSE streams (every connected +// client daemon holds one). Wire it via http.Server.RegisterOnShutdown. +func (s *Server) CloseEventStreams() { s.broker.shutdown() } + func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request, _ string) { flusher, ok := w.(http.Flusher) if !ok { @@ -77,6 +92,8 @@ func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request, _ string) select { case <-r.Context().Done(): return + case <-s.broker.done: // server shutting down — return so the conn goes idle and Shutdown completes fast + return case <-ping.C: fmt.Fprint(w, ": ping\n\n") // comment line keeps idle proxies from closing us flusher.Flush() diff --git a/internal/hub/events_test.go b/internal/hub/events_test.go new file mode 100644 index 0000000..8d86227 --- /dev/null +++ b/internal/hub/events_test.go @@ -0,0 +1,58 @@ +package hub + +import ( + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/shoemoney/devbox/internal/hub/blobstore" + "github.com/shoemoney/devbox/internal/hub/meta" + "github.com/shoemoney/devbox/pkg/proto" +) + +// TestCloseEventStreams proves a live /v1/events SSE stream returns promptly when +// CloseEventStreams fires (what RegisterOnShutdown calls) — otherwise a graceful +// shutdown would block the full drain timeout on streams that never go idle. +func TestCloseEventStreams(t *testing.T) { + db, err := meta.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + store, err := blobstore.NewDisk(t.TempDir()) + if err != nil { + t.Fatal(err) + } + s := NewServer(db, store) + srv := httptest.NewServer(s.Handler()) + defer srv.Close() + + if err := db.CreateToken(HashToken("tok"), time.Now().Unix()+3600); err != nil { + t.Fatal(err) + } + bearer := joinWith(t, srv.URL, "tok").Bearer + + req, _ := http.NewRequest(http.MethodGet, srv.URL+proto.PathEvents, nil) + req.Header.Set(proto.AuthHeader, "Bearer "+bearer) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("events status = %d", resp.StatusCode) + } + + done := make(chan struct{}) + go func() { io.Copy(io.Discard, resp.Body); close(done) }() + + s.CloseEventStreams() // the RegisterOnShutdown hook + + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("event stream did not return promptly after CloseEventStreams") + } +}