refactor(webui): decompose handleSSE to cut cognitive complexity
handleSSE mixed connection registration, backlog catch-up, and live broadcast relay into one function with three nested closures -- gocognit flagged it at 52 against a limit of 30. Extracted each concern into its own top-level piece: sseSince (resume-point resolution), registerSSEConn (subscribe/unsubscribe), and a new sseStream type carrying the per-connection state (send, catchUp, sendPage, drain) that the closures used to capture implicitly. Behavior is unchanged -- catchUp/sendPage's page-boundary and target-reached logic is the same control flow the original closure had, just named and independently testable. handleSSE itself is now a straight-line sequence of calls. Added direct unit tests against sendPage/catchUp for the boundary cases a full HTTP round-trip test doesn't exercise: a target reached mid-page vs. at a page boundary, a target of zero (drain everything), a write failure stopping the page immediately, and backlog spanning more than one EventsSince fetch.
This commit is contained in:
1 parent
95bb4b5bb6
commit
8ae23164bb
2 files changed
+322
-66
No files matched your search
+141
-66
@@ -1,46 +1,57 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// handleSSE streams events: catch-up from the store (?since=<event id>),
|
||||
// then live from the broadcast hub.
|
||||
// sseBacklogPageSize bounds one EventsSince fetch during catch-up.
|
||||
const sseBacklogPageSize = 200
|
||||
|
||||
// handleSSE streams events: catch-up from the store (?since=<event id>, or
|
||||
// the Last-Event-ID header on a reconnect), then live from the broadcast
|
||||
// hub.
|
||||
func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) {
|
||||
fl, ok := w.(http.Flusher)
|
||||
stream, ok := newSSEStream(s.Store, s.Log, w, sseSince(r))
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
|
||||
querySince, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
||||
since := querySince
|
||||
if headerValue := r.Header.Get("Last-Event-ID"); headerValue != "" {
|
||||
if headerSince, err := strconv.ParseInt(headerValue, 10, 64); err == nil {
|
||||
since = headerSince
|
||||
}
|
||||
}
|
||||
send := func(e events.Event) bool {
|
||||
b, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
s.Log.Error("sse event marshal failed", "error", err, "event_id", e.ID)
|
||||
return false
|
||||
}
|
||||
if _, err := w.Write([]byte("id: " + strconv.FormatInt(e.ID, 10) + "\ndata: " + string(b) + "\n\n")); err != nil {
|
||||
return false
|
||||
}
|
||||
fl.Flush()
|
||||
return true
|
||||
}
|
||||
|
||||
// Register before reading the backlog. An event published between the
|
||||
// backlog read and subscription would otherwise be lost permanently.
|
||||
conn, unregister := s.registerSSEConn()
|
||||
defer unregister()
|
||||
|
||||
if !stream.catchUp(r.Context(), 0) {
|
||||
return
|
||||
}
|
||||
stream.drain(r.Context(), conn)
|
||||
}
|
||||
|
||||
// sseSince resolves the event ID a client wants to resume after. A valid
|
||||
// Last-Event-ID header -- how EventSource itself resumes a dropped
|
||||
// connection -- takes precedence over the ?since= query parameter, which
|
||||
// only matters for a client's very first connection.
|
||||
func sseSince(r *http.Request) int64 {
|
||||
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
||||
if header := r.Header.Get("Last-Event-ID"); header != "" {
|
||||
if fromHeader, err := strconv.ParseInt(header, 10, 64); err == nil {
|
||||
since = fromHeader
|
||||
}
|
||||
}
|
||||
return since
|
||||
}
|
||||
|
||||
// registerSSEConn subscribes a channel to Broadcast and returns the
|
||||
// function that unsubscribes it.
|
||||
func (s *Server) registerSSEConn() (chan events.Event, func()) {
|
||||
c := make(chan events.Event, 64)
|
||||
s.mu.Lock()
|
||||
if s.conns == nil {
|
||||
@@ -48,64 +59,128 @@ func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
s.conns[c] = struct{}{}
|
||||
s.mu.Unlock()
|
||||
defer func() {
|
||||
|
||||
return c, func() {
|
||||
s.mu.Lock()
|
||||
delete(s.conns, c)
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
catchUp := func(targetID int64) bool {
|
||||
for {
|
||||
before := since
|
||||
backlog, err := s.Store.EventsSince(r.Context(), since, 200)
|
||||
if err != nil {
|
||||
s.Log.Error("sse backlog fetch failed", "error", err, "since", since)
|
||||
// Comments are invisible to EventSource clients. Close after
|
||||
// surfacing the gap so EventSource invokes its reconnect path.
|
||||
_, _ = w.Write([]byte(":error " + err.Error() + "\n\n"))
|
||||
fl.Flush()
|
||||
return false
|
||||
}
|
||||
for _, e := range backlog {
|
||||
if e.ID <= since {
|
||||
continue
|
||||
}
|
||||
if !send(e) {
|
||||
return false
|
||||
}
|
||||
since = e.ID
|
||||
if targetID > 0 && since >= targetID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if len(backlog) < 200 || since == before || (targetID > 0 && since >= targetID) {
|
||||
return true
|
||||
}
|
||||
// sseStream renders one client's event-stream response: an SSE frame per
|
||||
// event, an SSE comment when the persisted backlog can't be read, and the
|
||||
// running "since" watermark that deduplicates the backlog against live
|
||||
// broadcasts covering the same event.
|
||||
type sseStream struct {
|
||||
store store.TaskStore
|
||||
log *slog.Logger
|
||||
w http.ResponseWriter
|
||||
fl http.Flusher
|
||||
since int64
|
||||
}
|
||||
|
||||
// newSSEStream builds a stream over w, reporting false if w cannot be
|
||||
// flushed incrementally -- SSE does not work without that.
|
||||
func newSSEStream(st store.TaskStore, log *slog.Logger, w http.ResponseWriter, since int64) (*sseStream, bool) {
|
||||
fl, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
return &sseStream{store: st, log: log, w: w, fl: fl, since: since}, true
|
||||
}
|
||||
|
||||
// send writes one event as an SSE frame. It reports false on a write
|
||||
// error, meaning the connection is gone and the caller must stop.
|
||||
func (s *sseStream) send(e events.Event) bool {
|
||||
body, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
s.log.Error("sse event marshal failed", "error", err, "event_id", e.ID)
|
||||
return false
|
||||
}
|
||||
if _, err := s.w.Write([]byte("id: " + strconv.FormatInt(e.ID, 10) + "\ndata: " + string(body) + "\n\n")); err != nil {
|
||||
return false
|
||||
}
|
||||
s.fl.Flush()
|
||||
return true
|
||||
}
|
||||
|
||||
// writeErrorComment reports a backlog fetch failure as an SSE comment.
|
||||
// Comments are invisible to EventSource's own event parsing, but writing
|
||||
// one and flushing before the handler returns is what actually reaches the
|
||||
// client: it ends the response, which is what drives EventSource's
|
||||
// reconnect.
|
||||
func (s *sseStream) writeErrorComment(err error) {
|
||||
_, _ = s.w.Write([]byte(":error " + err.Error() + "\n\n"))
|
||||
s.fl.Flush()
|
||||
}
|
||||
|
||||
// catchUp sends every persisted event after s.since, advancing s.since as
|
||||
// it goes, until it reaches targetID (0 means "drain everything currently
|
||||
// available"), runs out of backlog, or fails. It reports false on failure
|
||||
// -- a fetch error or a dead connection -- meaning the caller must stop.
|
||||
func (s *sseStream) catchUp(ctx context.Context, targetID int64) bool {
|
||||
for {
|
||||
before := s.since
|
||||
backlog, err := s.store.EventsSince(ctx, s.since, sseBacklogPageSize)
|
||||
if err != nil {
|
||||
s.log.Error("sse backlog fetch failed", "error", err, "since", s.since)
|
||||
s.writeErrorComment(err)
|
||||
return false
|
||||
}
|
||||
reachedTarget, ok := s.sendPage(backlog, targetID)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if reachedTarget || len(backlog) < sseBacklogPageSize || s.since == before {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !catchUp(0) {
|
||||
return
|
||||
// sendPage sends every event in backlog newer than s.since, advancing it as
|
||||
// it goes. reachedTarget reports whether targetID was reached mid-page --
|
||||
// stopping there is correct, since nothing beyond it is needed yet -- and
|
||||
// ok reports whether every send succeeded.
|
||||
func (s *sseStream) sendPage(backlog []events.Event, targetID int64) (reachedTarget, ok bool) {
|
||||
for _, e := range backlog {
|
||||
if e.ID <= s.since {
|
||||
continue
|
||||
}
|
||||
if !s.send(e) {
|
||||
return false, false
|
||||
}
|
||||
s.since = e.ID
|
||||
if targetID > 0 && s.since >= targetID {
|
||||
return true, true
|
||||
}
|
||||
}
|
||||
return false, true
|
||||
}
|
||||
|
||||
// drain relays broadcast events after the initial catch-up. A broadcast can
|
||||
// reach the client before its event lands in the durable store, so each one
|
||||
// first fills any persisted gap ahead of it, then is delivered directly if
|
||||
// catch-up did not already cover it -- both paths go through the same
|
||||
// since-based deduplication.
|
||||
func (s *sseStream) drain(ctx context.Context, conn <-chan events.Event) {
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case e := <-c:
|
||||
if e.ID <= since {
|
||||
case e := <-conn:
|
||||
if e.ID <= s.since {
|
||||
continue
|
||||
}
|
||||
if !catchUp(e.ID) {
|
||||
if !s.catchUp(ctx, e.ID) {
|
||||
return
|
||||
}
|
||||
// Broadcast may carry an event that has not yet reached the
|
||||
// durable store. Deliver that live event after filling any
|
||||
// persisted gap, while keeping the ID deduplication invariant.
|
||||
if e.ID > since {
|
||||
if !send(e) {
|
||||
if e.ID > s.since {
|
||||
if !s.send(e) {
|
||||
return
|
||||
}
|
||||
since = e.ID
|
||||
s.since = e.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func newTestSSEStream(since int64) (*sseStream, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
return &sseStream{
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
w: rec,
|
||||
fl: rec,
|
||||
since: since,
|
||||
}, rec
|
||||
}
|
||||
|
||||
// sendPage is the seam catchUp's page-boundary logic depends on: it must
|
||||
// stop the instant targetID is reached, even mid-page, rather than sending
|
||||
// events beyond what the caller asked for.
|
||||
func TestSSEStreamSendPageStopsAtTargetMidPage(t *testing.T) {
|
||||
s, _ := newTestSSEStream(0)
|
||||
backlog := []events.Event{{ID: 1}, {ID: 2}, {ID: 3}, {ID: 4}, {ID: 5}}
|
||||
|
||||
reachedTarget, ok := s.sendPage(backlog, 3)
|
||||
|
||||
if !ok {
|
||||
t.Fatal("sendPage() ok = false, want true")
|
||||
}
|
||||
if !reachedTarget {
|
||||
t.Fatal("reachedTarget = false, want true: target 3 was inside the page")
|
||||
}
|
||||
if s.since != 3 {
|
||||
t.Fatalf("since = %d, want 3 (stopped at the target, not the end of the page)", s.since)
|
||||
}
|
||||
}
|
||||
|
||||
// A target beyond the page must not be reported reached: the caller needs
|
||||
// another page.
|
||||
func TestSSEStreamSendPageDoesNotReportTargetReachedBeyondThePage(t *testing.T) {
|
||||
s, _ := newTestSSEStream(0)
|
||||
backlog := []events.Event{{ID: 1}, {ID: 2}, {ID: 3}}
|
||||
|
||||
reachedTarget, ok := s.sendPage(backlog, 10)
|
||||
|
||||
if !ok {
|
||||
t.Fatal("sendPage() ok = false, want true")
|
||||
}
|
||||
if reachedTarget {
|
||||
t.Fatal("reachedTarget = true, want false: target 10 was never reached in this page")
|
||||
}
|
||||
if s.since != 3 {
|
||||
t.Fatalf("since = %d, want 3 (the whole page was sent)", s.since)
|
||||
}
|
||||
}
|
||||
|
||||
// targetID == 0 means "drain everything available"; sendPage must never
|
||||
// treat it as a target to stop at, or catchUp's initial call (which always
|
||||
// passes 0) would stop after the very first event.
|
||||
func TestSSEStreamSendPageIgnoresZeroTarget(t *testing.T) {
|
||||
s, _ := newTestSSEStream(0)
|
||||
backlog := []events.Event{{ID: 1}, {ID: 2}, {ID: 3}}
|
||||
|
||||
reachedTarget, ok := s.sendPage(backlog, 0)
|
||||
|
||||
if !ok || reachedTarget {
|
||||
t.Fatalf("sendPage(targetID=0) = (%v, %v), want (false, true)", reachedTarget, ok)
|
||||
}
|
||||
if s.since != 3 {
|
||||
t.Fatalf("since = %d, want 3 (the whole page was sent)", s.since)
|
||||
}
|
||||
}
|
||||
|
||||
// A send failure must stop the page immediately and report failure, not
|
||||
// silently skip the failed event and keep going.
|
||||
func TestSSEStreamSendPageStopsOnWriteFailure(t *testing.T) {
|
||||
s, _ := newTestSSEStream(0)
|
||||
s.w = failingWriter{}
|
||||
backlog := []events.Event{{ID: 1}, {ID: 2}}
|
||||
|
||||
reachedTarget, ok := s.sendPage(backlog, 0)
|
||||
|
||||
if ok {
|
||||
t.Fatal("sendPage() ok = true, want false: the write failed")
|
||||
}
|
||||
if reachedTarget {
|
||||
t.Fatal("reachedTarget = true, want false on failure")
|
||||
}
|
||||
if s.since != 0 {
|
||||
t.Fatalf("since = %d, want 0 (unchanged: the first send already failed)", s.since)
|
||||
}
|
||||
}
|
||||
|
||||
// failingWriter fails every Write, so send() can be tested against a dead
|
||||
// connection without a real network failure.
|
||||
type failingWriter struct{}
|
||||
|
||||
func (failingWriter) Header() http.Header { return http.Header{} }
|
||||
func (failingWriter) Write([]byte) (int, error) { return 0, errWriteFailed }
|
||||
func (failingWriter) WriteHeader(statusCode int) {}
|
||||
|
||||
var errWriteFailed = errors.New("write failed")
|
||||
|
||||
// fakeEventStore serves EventsSince from a fixed, pre-seeded slice, paginating
|
||||
// the same way the real store does: up to limit events with id > sinceID.
|
||||
type fakeEventStore struct {
|
||||
store.TaskStore
|
||||
all []events.Event
|
||||
}
|
||||
|
||||
func (f *fakeEventStore) EventsSince(_ context.Context, sinceID int64, limit int) ([]events.Event, error) {
|
||||
page := make([]events.Event, 0, limit)
|
||||
for _, e := range f.all {
|
||||
if e.ID <= sinceID {
|
||||
continue
|
||||
}
|
||||
page = append(page, e)
|
||||
if len(page) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// catchUp must page across more than one EventsSince fetch when the backlog
|
||||
// exceeds sseBacklogPageSize in one page, rather than stopping after the
|
||||
// first page as though that were everything.
|
||||
func TestSSEStreamCatchUpPagesAcrossMultipleFetches(t *testing.T) {
|
||||
const total = sseBacklogPageSize + 50
|
||||
all := make([]events.Event, total)
|
||||
for i := range all {
|
||||
all[i] = events.Event{ID: int64(i + 1)}
|
||||
}
|
||||
|
||||
s, rec := newTestSSEStream(0)
|
||||
s.store = &fakeEventStore{all: all}
|
||||
|
||||
if !s.catchUp(context.Background(), 0) {
|
||||
t.Fatal("catchUp() = false, want true")
|
||||
}
|
||||
if s.since != int64(total) {
|
||||
t.Fatalf("since = %d, want %d (every event drained across pages)", s.since, total)
|
||||
}
|
||||
if n := countSSEFrames(rec.Body.String()); n != total {
|
||||
t.Fatalf("sent %d SSE frames, want %d", n, total)
|
||||
}
|
||||
}
|
||||
|
||||
// A targetID landing exactly on the last event of a full page must still be
|
||||
// recognised as reached, not mistaken for "page not yet exhausted, fetch
|
||||
// another".
|
||||
func TestSSEStreamCatchUpStopsAtTargetOnPageBoundary(t *testing.T) {
|
||||
all := make([]events.Event, sseBacklogPageSize+50)
|
||||
for i := range all {
|
||||
all[i] = events.Event{ID: int64(i + 1)}
|
||||
}
|
||||
|
||||
s, _ := newTestSSEStream(0)
|
||||
s.store = &fakeEventStore{all: all}
|
||||
|
||||
if !s.catchUp(context.Background(), sseBacklogPageSize) {
|
||||
t.Fatal("catchUp() = false, want true")
|
||||
}
|
||||
if s.since != sseBacklogPageSize {
|
||||
t.Fatalf("since = %d, want %d (stopped exactly at the target, not the whole backlog)", s.since, sseBacklogPageSize)
|
||||
}
|
||||
}
|
||||
|
||||
// countSSEFrames counts "data:" lines, which appear exactly once per event
|
||||
// frame (see sseStream.send's "id: ...\ndata: ...\n\n" format).
|
||||
func countSSEFrames(body string) int {
|
||||
return strings.Count(body, "\ndata: ")
|
||||
}
|
||||
Reference in new issue
Block a user