perf(hub): drop SSE streams on shutdown so redeploys don't eat the 10s drain 🛑⚡
Some checks are pending
CI / vet-build-test (push) Waiting to run

Every connected client daemon holds a long-lived /v1/events SSE stream, and
http.Server.Shutdown waits for connections to go idle — which these never do —
so a graceful shutdown always burned the full 10s drain timeout (felt on every
hub redeploy with clients connected). RegisterOnShutdown now signals the broker
to return every active /v1/events handler, so shutdown completes near-instantly.

Test: TestCloseEventStreams (live stream returns promptly after the hook).
Round 8 was 0 GO — the codebase is mined out; this is the reversed no-go.
This commit is contained in:
shoemoney 2026-06-30 17:57:55 -05:00
parent f4e50c4a40
commit 73c3f309a5
3 changed files with 80 additions and 1 deletions

View file

@ -179,6 +179,10 @@ func serveCmd() *cobra.Command {
MaxHeaderBytes: 1 << 20, 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) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop() defer stop()

View file

@ -16,9 +16,19 @@ import (
type broker struct { type broker struct {
mu sync.Mutex mu sync.Mutex
subs map[chan proto.Event]string // channel -> share filter ("" = all shares) 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 { func (b *broker) sub(share string) chan proto.Event {
ch := make(chan proto.Event, 16) 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. // 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) { func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request, _ string) {
flusher, ok := w.(http.Flusher) flusher, ok := w.(http.Flusher)
if !ok { if !ok {
@ -77,6 +92,8 @@ func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request, _ string)
select { select {
case <-r.Context().Done(): case <-r.Context().Done():
return return
case <-s.broker.done: // server shutting down — return so the conn goes idle and Shutdown completes fast
return
case <-ping.C: case <-ping.C:
fmt.Fprint(w, ": ping\n\n") // comment line keeps idle proxies from closing us fmt.Fprint(w, ": ping\n\n") // comment line keeps idle proxies from closing us
flusher.Flush() flusher.Flush()

View file

@ -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")
}
}