devbox/internal/hub/events.go
shoemoney 73c3f309a5
Some checks are pending
CI / vet-build-test (push) Waiting to run
perf(hub): drop SSE streams on shutdown so redeploys don't eat the 10s drain 🛑⚡
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.
2026-06-30 17:57:55 -05:00

106 lines
2.9 KiB
Go

package hub
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/shoemoney/devbox/pkg/proto"
)
// broker fans hub change events out to connected SSE subscribers. A slow
// subscriber's events are dropped rather than blocking the push path — the
// device re-syncs via Head() regardless, so a missed nudge is harmless.
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{}, 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)
b.mu.Lock()
b.subs[ch] = share
b.mu.Unlock()
return ch
}
func (b *broker) unsub(ch chan proto.Event) {
b.mu.Lock()
if _, ok := b.subs[ch]; ok {
delete(b.subs, ch)
close(ch)
}
b.mu.Unlock()
}
// publish delivers ev to every subscriber whose filter matches. Held under the
// same lock as unsub, so a channel is never sent-to after it is closed.
func (b *broker) publish(ev proto.Event) {
b.mu.Lock()
defer b.mu.Unlock()
for ch, filter := range b.subs {
if filter != "" && filter != ev.Share {
continue
}
select {
case ch <- ev:
default: // subscriber is slow; drop (it will re-sync via Head())
}
}
}
// 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 {
writeErr(w, http.StatusInternalServerError, "streaming unsupported")
return
}
ch := s.broker.sub(r.URL.Query().Get("share"))
defer s.broker.unsub(ch)
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-cache")
h.Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
flusher.Flush()
ping := time.NewTicker(25 * time.Second)
defer ping.Stop()
for {
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()
case ev := <-ch:
b, _ := json.Marshal(ev)
fmt.Fprintf(w, "data: %s\n\n", b)
flusher.Flush()
}
}
}