diff --git a/pkgs/mcpx/internal/daemon/events_gap_test.go b/pkgs/mcpx/internal/daemon/events_gap_test.go new file mode 100644 index 0000000000..4d15532627 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/events_gap_test.go @@ -0,0 +1,139 @@ +package daemon + +import ( + "bytes" + "context" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/dezren39/mcpx/internal/defaults" + "github.com/dezren39/mcpx/internal/events" + "github.com/dezren39/mcpx/internal/settings" +) + +// A subscriber that falls behind LIVE must be told, in band, on the stream. +// +// Subscribe-time replay already reports its gap (handleEvents' first gap +// event, pinned by TestAReplayLargerThanTheSubscriberBufferMissesNothing in +// the events package). Post-subscribe drops were counted by +// Subscription.Dropped and read by nothing, so a client that stalled for a +// moment silently missed events while the docs promised it would be told. +// +// The stall is produced without timing luck: the writer's first Flush blocks +// until the test releases it, which is exactly a slow client, so every event +// published in that window is dropped by the subscription's non-blocking +// send. After the release the handler must emit the gap notice before the +// next event it delivers. +func TestEventsTellsAStalledSubscriberWhatItMissed(t *testing.T) { + bus := events.New(defaults.EventHistory) + s := &Server{Events: bus, set: gapTestSettings(t)} + + w := newGatedWriter() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/v1/events", nil) + if err != nil { + t.Fatal(err) + } + + done := make(chan struct{}) + go func() { + defer close(done) + s.handleEvents(w, req) + }() + + // The first flush happens after the subscription exists and before the + // read loop starts, so once it is entered the subscription is live and + // nothing has been drained yet. + select { + case <-w.entered: + case <-time.After(2 * time.Second): + t.Fatal("handler never reached its first flush") + } + + // Far more than the subscriber buffer, published while the client is + // stalled: the excess is what Dropped counts. + for i := 0; i < defaults.EventSubscriberBuf+64; i++ { + bus.Publish(events.Event{Kind: events.CallFinished}) + } + close(w.release) + + deadline := time.Now().Add(2 * time.Second) + for !strings.Contains(w.String(), "event: gap") { + if time.Now().After(deadline) { + t.Fatalf("no gap event on the stream after a live drop; body so far:\n%s", w.String()) + } + time.Sleep(5 * time.Millisecond) + } + cancel() + <-done + + body := w.String() + gapLine := body[strings.Index(body, "event: gap"):] + if !strings.Contains(gapLine, `"dropped":`) { + t.Errorf("gap event should say how many were dropped, got %q", gapLine) + } + if !strings.Contains(gapLine, `"latest":`) { + t.Errorf("gap event should name the latest sequence for resync, got %q", gapLine) + } + // The notice has to come before the event that follows the hole, or the + // client reads a sequence jump first and only then learns why. + if i, j := strings.Index(body, "event: gap"), strings.Index(body, "event: call.finished"); i > j { + t.Errorf("gap event written after the event it precedes:\n%s", body) + } +} + +func gapTestSettings(t *testing.T) *settings.Set { + t.Helper() + sch, err := settings.New(settings.Registry()) + if err != nil { + t.Fatal(err) + } + return settings.NewSet(sch).WithOverrides(nil, "test") +} + +// gatedWriter is an http.ResponseWriter whose first Flush blocks until the +// test closes release. It records the body under a mutex because the handler +// writes from its own goroutine while the test reads. +type gatedWriter struct { + mu sync.Mutex + buf bytes.Buffer + header http.Header + entered chan struct{} + release chan struct{} + once sync.Once +} + +func newGatedWriter() *gatedWriter { + return &gatedWriter{ + header: http.Header{}, + entered: make(chan struct{}), + release: make(chan struct{}), + } +} + +func (g *gatedWriter) Header() http.Header { return g.header } + +func (g *gatedWriter) Write(p []byte) (int, error) { + g.mu.Lock() + defer g.mu.Unlock() + return g.buf.Write(p) +} + +func (g *gatedWriter) WriteHeader(int) {} + +func (g *gatedWriter) Flush() { + g.once.Do(func() { + close(g.entered) + <-g.release + }) +} + +func (g *gatedWriter) String() string { + g.mu.Lock() + defer g.mu.Unlock() + return g.buf.String() +} diff --git a/pkgs/mcpx/internal/daemon/server.go b/pkgs/mcpx/internal/daemon/server.go index 91a81a6a5f..a62e25b215 100644 --- a/pkgs/mcpx/internal/daemon/server.go +++ b/pkgs/mcpx/internal/daemon/server.go @@ -1440,22 +1440,49 @@ func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) { ping := time.NewTicker(s.set.Duration("http.ssePing")) defer ping.Stop() + // lastSeq is the sequence of the last event this client actually + // received. A live drop leaves a hole after it, and the gap notice names + // that hole rather than the client discovering it by finding a sequence + // number missing -- which is exactly the silent loss the bus promises + // not to have. + lastSeq := since + // toldDrops is the subscription's drop count at the last notice, so one + // stall produces one gap event and not a notice per delivered event. + var toldDrops uint64 + tellGap := func() { + dropped := sub.Dropped.Load() + if dropped == 0 || dropped == toldDrops { + return + } + toldDrops = dropped + fmt.Fprintf(w, "event: gap\ndata: {\"since\":%d,\"latest\":%d,\"dropped\":%d}\n\n", + lastSeq, s.Events.Latest(), dropped) + flusher.Flush() + } + for { select { case <-r.Context().Done(): return case <-ping.C: + // Checked here too: a subscriber that stopped reading long + // enough to lose events has nothing new to read afterwards, so + // waiting for the next event to report the loss could wait + // forever. + tellGap() fmt.Fprintf(w, ": ping\n\n") flusher.Flush() case e, open := <-sub.C: if !open { return } + tellGap() b, err := json.Marshal(e) if err != nil { continue } fmt.Fprintf(w, "id: %d\nevent: %s\ndata: %s\n\n", e.Seq, e.Kind, b) + lastSeq = e.Seq flusher.Flush() } } diff --git a/pkgs/mcpx/internal/events/events_history_test.go b/pkgs/mcpx/internal/events/events_history_test.go new file mode 100644 index 0000000000..dbf37fbee6 --- /dev/null +++ b/pkgs/mcpx/internal/events/events_history_test.go @@ -0,0 +1,37 @@ +package events_test + +import ( + "testing" + + "github.com/dezren39/mcpx/internal/events" +) + +// The retained history is what "reconnect from zero" promises. The existing +// regression test replays 300 events, more than the subscriber buffer but +// well short of the history the daemon actually keeps; a full history is the +// case where the buffer-sizing fix has to hold for every retained event, and +// where "no gap" has to mean all 1024, not "all that fitted". +func TestAFullRetainedHistoryReplaysAtSinceZero(t *testing.T) { + const keep = 1024 + b := events.New(keep) + for i := 0; i < keep; i++ { + b.Publish(events.Event{Kind: events.CallFinished}) + } + + s, gap := b.SubscribeFrom(events.Filter{}, 0, true) + defer s.Close() + if gap { + t.Fatalf("replaying the full retained history from zero reported a gap") + } + if got := s.Dropped.Load(); got != 0 { + t.Fatalf("full-history replay dropped %d events", got) + } + + for want := uint64(1); want <= keep; want++ { + e := recv(t, s) + if e.Seq != want { + t.Fatalf("event %d of the replay has seq %d", want, e.Seq) + } + } + none(t, s) +}