fix(webui): multiplex dashboard live updates over one stream

This commit is contained in:
sam committed 2026-09-25 14:05:34 +10:00
1 parent c1143ea3db
commit 29004db774
25 files changed
+835 -322

No files matched your search

@@ -47,10 +47,6 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) {
name: "daemon log feed", method: http.MethodGet, path: "/api/logs",
want: http.StatusOK, emptyJSON: `"disabled":true`,
},
{
name: "daemon log stream", method: http.MethodGet, path: "/api/logs/stream",
want: http.StatusServiceUnavailable,
},
{
// Task logs are a State Store read contract now
// (archie-core-iaqx), so the route answers with real data
+3
View File
@@ -75,6 +75,9 @@ func Run(ctx context.Context, options Options) error {
log.Error("event pump stopped; the activity feed will only show history", "err", err)
}
}()
liveCtx, stopLive := context.WithCancel(ctx)
defer stopLive()
go srv.RunLive(liveCtx)
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", opts.Listen)
if err != nil {
+15 -7
View File
@@ -1,6 +1,7 @@
package webui
import (
"context"
"net/http"
"time"
@@ -38,16 +39,23 @@ type applyStatusView struct {
// process is running. A process with no apply-status wiring renders an empty
// page rather than failing: that is a deployment fact, not an error.
func (s *Server) handleApplyStatus(w http.ResponseWriter, r *http.Request) {
view := applyStatusView{Records: []applyStatusRecord{}, Processes: applystatus.Processes()}
if s.ApplyStatus == nil {
writeJSON(w, view)
return
}
records, err := s.ApplyStatus.ListApplyStatus(r.Context())
view, err := s.readApplyStatus(r.Context())
if err != nil {
http.Error(w, "apply status unavailable", http.StatusServiceUnavailable)
return
}
writeJSON(w, view)
}
func (s *Server) readApplyStatus(ctx context.Context) (applyStatusView, error) {
view := applyStatusView{Records: []applyStatusRecord{}, Processes: applystatus.Processes()}
if s.ApplyStatus == nil {
return view, nil
}
records, err := s.ApplyStatus.ListApplyStatus(ctx)
if err != nil {
return view, err
}
now := s.clock()
for _, record := range records {
view.Records = append(view.Records, applyStatusRecord{
@@ -55,7 +63,7 @@ func (s *Server) handleApplyStatus(w http.ResponseWriter, r *http.Request) {
Error: record.Error, ReportedAt: record.ReportedAt, State: applyState(record, now),
})
}
writeJSON(w, view)
return view, nil
}
// applyState reads staleness before the error: a process that stopped
-48
View File
@@ -4,10 +4,7 @@ import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"time"
"google.golang.org/grpc/codes"
@@ -126,51 +123,6 @@ func (s *Server) handleControlPlaneCommand(w http.ResponseWriter, r *http.Reques
writeJSON(w, controlPlaneResourceResponse{Resource: controlPlaneResourceView(response.Resource)})
}
func (s *Server) handleControlPlaneWatch(w http.ResponseWriter, r *http.Request) {
if s.ControlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
after, err := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
if err != nil && r.URL.Query().Get("after") != "" {
http.Error(w, "invalid after version", http.StatusBadRequest)
return
}
stream, err := s.ControlPlane.Watch(r.Context(), &controlpb.WatchRequest{Kind: r.PathValue("kind"), AfterVersion: after})
if err != nil {
writeControlPlaneError(w, err)
return
}
flusher, ok := w.(http.Flusher)
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")
// Headers go out now: the browser marks the stream live on them, and an
// unchanged resource may send nothing for hours.
w.WriteHeader(http.StatusOK)
flusher.Flush()
for {
response, recvErr := stream.Recv()
if errors.Is(recvErr, io.EOF) || r.Context().Err() != nil {
return
}
if recvErr != nil {
return
}
payload, marshalErr := json.Marshal(controlPlaneResourceResponse{Resource: controlPlaneResourceView(response.Resource)})
if marshalErr != nil {
return
}
if _, err = w.Write(append(append([]byte("data: "), payload...), '\n', '\n')); err != nil {
return
}
flusher.Flush()
}
}
func controlPlaneResourceView(resource *controlpb.Resource) controlPlaneResource {
if resource == nil {
return controlPlaneResource{}
+7 -19
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
@@ -59,31 +60,18 @@ func (f *controlPlaneClientStub) Watch(context.Context, *controlpb.WatchRequest,
return f.watch, f.err
}
// idleWatch is a watch stream with nothing to deliver: Recv blocks until the
// request ends, as a real stream does while the resource is unchanged.
type idleWatch struct {
grpc.ClientStream
done <-chan struct{}
}
func (w idleWatch) Recv() (*controlpb.WatchResponse, error) {
<-w.done
return nil, context.Canceled
}
// TestControlPlaneWatchOpensBeforeTheFirstChange: a browser marks an event
// stream live when its headers arrive. Holding them until the first change
// leaves every settings card reading "Connecting" on an unchanged resource.
func TestControlPlaneWatchOpensBeforeTheFirstChange(t *testing.T) {
server := httptest.NewServer((&Server{ControlPlane: &controlPlaneClientStub{watch: idleWatch{done: t.Context().Done()}}}).Handler())
// The multiplexed stream answers before any topic changes. An unchanged
// resource must not leave the connection pill at Connecting indefinitely.
func TestLiveStreamOpensBeforeTheFirstChange(t *testing.T) {
server := httptest.NewServer((&Server{Store: &fakeEventStore{}, Log: slog.New(slog.DiscardHandler)}).Handler())
t.Cleanup(server.Close)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/control-plane/watch/workflow-execution-settings", nil)
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/stream", nil)
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("watch did not answer before its first change: %v", err)
t.Fatalf("stream did not answer before its first change: %v", err)
}
defer response.Body.Close()
if got := response.Header.Get("Content-Type"); got != "text/event-stream" {
-43
View File
@@ -7,7 +7,6 @@ import (
"errors"
"net/http"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
@@ -34,48 +33,6 @@ func (s *Server) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{"identities": values})
}
func (s *Server) handleIdentitiesWatch(w http.ResponseWriter, r *http.Request) {
if s.Identities == nil {
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
return
}
flusher, ok := w.(http.Flusher)
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")
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var previous string
for {
values, err := s.Identities.List(r.Context())
if err != nil {
return
}
if values == nil {
values = []identity.Identity{}
}
payload, err := json.Marshal(map[string]any{"identities": values})
if err != nil {
return
}
if current := string(payload); current != previous {
if _, err = w.Write(append(append([]byte("data: "), payload...), '\n', '\n')); err != nil {
return
}
flusher.Flush()
previous = current
}
select {
case <-r.Context().Done():
return
case <-ticker.C:
}
}
}
func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
var request identityRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
-32
View File
@@ -1,7 +1,6 @@
package webui
import (
"encoding/json"
"net/http"
"slices"
"strconv"
@@ -77,37 +76,6 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
})
}
func (s *Server) handleLogStream(w http.ResponseWriter, r *http.Request) {
if s.LogFeed == nil {
http.Error(w, "live daemon log feed unavailable", http.StatusServiceUnavailable)
return
}
flusher, ok := w.(http.Flusher)
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")
entries := s.LogFeed.Subscribe(r.Context())
for {
select {
case <-r.Context().Done():
return
case entry, ok := <-entries:
if !ok {
return
}
data, err := json.Marshal(entry)
if err != nil {
continue
}
_, _ = w.Write([]byte("id: " + strconv.FormatInt(entry.ID, 10) + "\ndata: " + string(data) + "\n\n"))
flusher.Flush()
}
}
}
func mergeComponents(history []string, live []logging.Entry) []string {
seen := make(map[string]struct{}, len(history))
for _, component := range history {
+216
View File
@@ -0,0 +1,216 @@
package webui
import (
"context"
"encoding/json"
"log/slog"
"reflect"
"slices"
"time"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
// liveUpdate is one topic's payload. Only durable tasks and the bounded log
// feed have replay cursors; resource and identity topics replay their latest
// snapshot on every connection instead.
type liveUpdate struct {
topic string
data any
}
type liveSubscriber struct {
updates chan liveUpdate
stale chan struct{}
}
func (s *Server) publish(update liveUpdate, key string) {
s.mu.Lock()
defer s.mu.Unlock()
if key != "" {
if s.latest == nil {
s.latest = make(map[string]liveUpdate)
}
if previous, ok := s.latest[key]; ok && reflect.DeepEqual(previous.data, update.data) {
return
}
s.latest[key] = update
}
for subscriber := range s.conns {
select {
case subscriber.updates <- update:
default:
// The client cannot consume a complete stream. Disconnect it so
// EventSource reconnects and replays cursors + latest snapshots.
delete(s.conns, subscriber)
close(subscriber.stale)
}
}
}
// registerSSEConn subscribes before taking a snapshot. Updates published
// during catch-up land in the channel; snapshots describe the same point in
// time as registration and are sent before the channel is drained.
func (s *Server) registerSSEConn() (<-chan liveUpdate, []liveUpdate, <-chan struct{}, func()) {
subscriber := &liveSubscriber{updates: make(chan liveUpdate, 64), stale: make(chan struct{})}
s.mu.Lock()
if s.conns == nil {
s.conns = make(map[*liveSubscriber]struct{})
}
s.conns[subscriber] = struct{}{}
keys := make([]string, 0, len(s.latest))
for key := range s.latest {
keys = append(keys, key)
}
slices.Sort(keys)
snapshot := make([]liveUpdate, 0, len(keys))
for _, key := range keys {
snapshot = append(snapshot, s.latest[key])
}
s.mu.Unlock()
return subscriber.updates, snapshot, subscriber.stale, func() {
s.mu.Lock()
delete(s.conns, subscriber)
s.mu.Unlock()
}
}
// RunLive owns the process-wide producers. A browser never creates an upstream
// watch or poller, and a late browser gets the last observed values from the
// hub. The caller's context owns all producers and their retry timers.
func (s *Server) RunLive(ctx context.Context) {
if s.Identities != nil {
go s.pollIdentities(ctx)
}
if s.ApplyStatus != nil {
go s.pollApplyStatus(ctx)
}
if s.ControlPlane == nil {
return
}
delay := 250 * time.Millisecond
for ctx.Err() == nil {
catalog, err := s.ControlPlane.Catalog(ctx, &controlpb.CatalogRequest{})
if err == nil {
for _, resource := range catalog.Resources {
if resource.ApplyMode == "domain-managed" || resource.QueryService != "" || !slices.Contains(resource.Commands, "replace") {
continue
}
go s.watchResource(ctx, resource.Kind)
}
return
}
s.logLive("control-plane catalog unavailable; retrying", "retry_in", delay, "err", err)
if !waitLive(ctx, delay) {
return
}
delay = min(2*delay, 30*time.Second)
}
}
func (s *Server) watchResource(ctx context.Context, kind string) {
const minDelay, maxDelay = 250 * time.Millisecond, 30 * time.Second
var version int64
delay := minDelay
for ctx.Err() == nil {
started := time.Now()
progressed := false
stream, err := s.ControlPlane.Watch(ctx, &controlpb.WatchRequest{Kind: kind, AfterVersion: version})
if err == nil {
for ctx.Err() == nil {
response, recvErr := stream.Recv()
if recvErr != nil {
err = recvErr
break
}
if resource := response.GetResource(); resource != nil && resource.Version > version {
version = resource.Version
progressed = true
s.publish(liveUpdate{topic: "control-plane", data: controlPlaneResourceResponse{Resource: controlPlaneResourceView(resource)}}, "control-plane/"+kind)
}
}
}
if ctx.Err() != nil {
return
}
// Acceptance alone is not health: the State Store can accept a gRPC
// stream then fail its first read. Charge attempts that end without an
// update before twice the prospective retry delay (keepWatch rule).
failedDelay := min(2*delay, maxDelay)
if progressed || time.Since(started) >= 2*failedDelay {
delay = minDelay
} else {
delay = failedDelay
}
s.logLive("control-plane watch ended; reconnecting", "kind", kind, "after_version", version, "retry_in", delay, "err", err)
if !waitLive(ctx, delay) {
return
}
}
}
func (s *Server) pollIdentities(ctx context.Context) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
values, err := s.Identities.List(ctx)
if err == nil {
if values == nil {
values = []identity.Identity{}
}
s.publish(liveUpdate{topic: "identities", data: map[string]any{"identities": values}}, "identities")
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
func (s *Server) pollApplyStatus(ctx context.Context) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
// Compute staleness as the existing HTTP projection does, but publish
// only when the visible value changes, not on every poll.
view, err := s.readApplyStatus(ctx)
if err == nil {
s.publish(liveUpdate{topic: "apply-status", data: view}, "apply-status")
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
func waitLive(ctx context.Context, delay time.Duration) bool {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}
func (s *Server) logLive(message string, args ...any) {
if s.Log != nil {
s.Log.Warn(message, args...)
} else {
slog.Default().Warn(message, args...)
}
}
// marshalLiveFrame keeps every topic's shape in one wire envelope. A topic's
// existing payload stays intact inside data, including raw resource JSON.
func marshalLiveFrame(update liveUpdate) ([]byte, error) {
return json.Marshal(struct {
Topic string `json:"topic"`
Data any `json:"data"`
}{update.topic, update.data})
}
+262
View File
@@ -0,0 +1,262 @@
package webui
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/test/bufconn"
"github.com/samcharles93/archie-core/internal/app/controlplane"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
"github.com/samcharles93/archie-core/internal/logging"
)
type liveResourceStore struct{ controlplane.ResourceStore }
func (*liveResourceStore) Resource(_ context.Context, kind string) (storecontract.Resource, error) {
if kind == controlplane.PersonasKind {
return storecontract.Resource{Kind: kind, Version: 1, Value: []byte(`{"default":"archie","personas":[]}`)}, nil
}
return storecontract.Resource{}, storecontract.ErrResourceNotFound
}
// The real control-plane server (not a scripted Recv) must keep one upstream
// Watch per generic kind independently of how many browser streams connect.
// Its 250ms Resource poll runs once per kind, not once per browser.
func TestLiveHubSharesRealControlPlaneWatches(t *testing.T) {
steps, err := workflowsteps.NewManager()
if err != nil {
t.Fatal(err)
}
upstream, err := controlplane.NewServer(&liveResourceStore{}, steps)
if err != nil {
t.Fatal(err)
}
var watches atomic.Int32
listener := bufconn.Listen(1 << 20)
grpcServer := grpc.NewServer(grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if info.FullMethod == controlpb.ControlPlaneService_Watch_FullMethodName {
watches.Add(1)
}
return handler(srv, stream)
}))
controlpb.RegisterControlPlaneServiceServer(grpcServer, upstream)
go func() { _ = grpcServer.Serve(listener) }()
t.Cleanup(func() { grpcServer.Stop(); _ = listener.Close() })
conn, err := grpc.NewClient("passthrough:///controlplane", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
return listener.DialContext(ctx)
}))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
srv := &Server{ControlPlane: controlpb.NewControlPlaneServiceClient(conn), Store: &fakeEventStore{}, Log: slog.New(slog.DiscardHandler)}
go srv.RunLive(ctx)
catalog, err := upstream.Catalog(ctx, &controlpb.CatalogRequest{})
if err != nil {
t.Fatal(err)
}
generic := 0
for _, descriptor := range catalog.Resources {
if descriptor.ApplyMode != "domain-managed" && descriptor.QueryService == "" {
generic++
}
}
waitUntil(t, func() bool { return int(watches.Load()) == generic })
waitUntil(t, func() bool {
srv.mu.Lock()
defer srv.mu.Unlock()
_, ok := srv.latest["control-plane/"+controlplane.PersonasKind]
return ok
})
httpServer := httptest.NewServer(srv.Handler())
defer httpServer.Close()
for range 3 {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, httpServer.URL+"/api/stream", nil)
if err != nil {
t.Fatal(err)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatal(err)
}
line, err := readTopic(bufio.NewScanner(response.Body), "control-plane")
if err != nil {
t.Fatal(err)
}
var frame struct {
Data controlPlaneResourceResponse `json:"data"`
}
if err := json.Unmarshal([]byte(line), &frame); err != nil {
t.Fatal(err)
}
if frame.Data.Resource.Kind != controlplane.PersonasKind || frame.Data.Resource.Version != 1 {
t.Fatalf("late subscriber got %+v", frame.Data.Resource)
}
_ = response.Body.Close()
}
if got := int(watches.Load()); got != generic {
t.Fatalf("%d upstream watches after three clients, want %d", got, generic)
}
}
func readTopic(scanner *bufio.Scanner, topic string) (string, error) {
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "data: ") {
continue
}
data := strings.TrimPrefix(line, "data: ")
var frame struct {
Topic string `json:"topic"`
}
if err := json.Unmarshal([]byte(data), &frame); err != nil {
return "", err
}
if frame.Topic == topic {
return data, nil
}
}
return "", errors.New("stream ended before topic " + topic)
}
func waitUntil(t *testing.T, ready func() bool) {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if ready() {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatal("live producer did not become ready")
}
type countedIdentities struct {
identity.Repository
reads atomic.Int32
}
func (f *countedIdentities) List(context.Context) ([]identity.Identity, error) {
f.reads.Add(1)
return []identity.Identity{identity.System()}, nil
}
func TestIdentitiesPollOnceForSeveralClients(t *testing.T) {
identities := &countedIdentities{}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
srv := &Server{Store: &fakeEventStore{}, Log: slog.New(slog.DiscardHandler), Identities: identities}
go srv.RunLive(ctx)
waitUntil(t, func() bool { return identities.reads.Load() >= 1 })
server := httptest.NewServer(srv.Handler())
defer server.Close()
for range 3 {
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/stream", nil)
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
if _, err := readTopic(bufio.NewScanner(response.Body), "identities"); err != nil {
t.Fatal(err)
}
}
waitUntil(t, func() bool { return identities.reads.Load() >= 2 })
if got := identities.reads.Load(); got != 2 {
t.Fatalf("%d identity reads with three clients, want 2 (one per poll tick)", got)
}
}
func TestSlowLiveSubscriberIsDisconnectedForSnapshotReplay(t *testing.T) {
srv := &Server{}
_, _, stale, unregister := srv.registerSSEConn()
defer unregister()
for i := range 65 {
srv.Broadcast(events.Event{ID: int64(i + 1), At: testAt})
}
select {
case <-stale:
default:
t.Fatal("full subscriber was not disconnected: its dropped updates cannot be replayed until reconnect")
}
}
func TestLiveStreamReplaysLogsOnlyWhenRequestedAndResumesBothCursors(t *testing.T) {
feed := logging.NewFeed(20)
// Feed's production writer stamps IDs; drive it through its public slog handler.
log := slog.New(logging.NewFeedHandler(slog.NewTextHandler(new(bytes.Buffer), nil), feed))
log.Info("before")
srv := &Server{Store: &fakeEventStore{all: []events.Event{{ID: 1, At: testAt}, {ID: 2, At: testAt}}}, Log: slog.New(slog.DiscardHandler), LogFeed: feed}
base := httptest.NewServer(srv.Handler())
defer base.Close()
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
get := func(path string) *http.Response {
t.Helper()
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, base.URL+path, nil)
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatal(err)
}
return response
}
// A task-only connection must not subscribe to log traffic.
plain := get("/api/stream")
defer plain.Body.Close()
withLogs := get("/api/stream?topics=logs")
line, err := readTopic(bufio.NewScanner(withLogs.Body), "logs")
if err != nil {
t.Fatal(err)
}
var frame struct {
Data logging.Entry `json:"data"`
}
if err := json.Unmarshal([]byte(line), &frame); err != nil || frame.Data.ID != 1 {
t.Fatalf("log replay = %q, %v", line, err)
}
_ = withLogs.Body.Close()
log.Info("after")
cursor := streamCursors{Tasks: cursor(1), Logs: 1}.id()
resumed := get("/api/stream?topics=logs&since=" + cursor)
defer resumed.Body.Close()
reader := bufio.NewScanner(resumed.Body)
line, err = readTopic(reader, "tasks")
if err != nil {
t.Fatal(err)
}
var taskFrame struct {
Data events.Event `json:"data"`
}
if err := json.Unmarshal([]byte(line), &taskFrame); err != nil || taskFrame.Data.ID != 2 {
t.Fatalf("resumed task = %q, %v", line, err)
}
line, err = readTopic(reader, "logs")
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal([]byte(line), &frame); err != nil || frame.Data.ID != 2 {
t.Fatalf("resumed log = %q, %v", line, err)
}
}
+5 -15
View File
@@ -195,8 +195,9 @@ type Server struct {
// When Cfg is present, Cfg.Get().Web.TrustForwardedHeaders is also checked.
TrustForwardedHeaders bool
mu sync.Mutex
conns map[chan events.Event]struct{}
mu sync.Mutex
conns map[*liveSubscriber]struct{}
latest map[string]liveUpdate
}
func (s *Server) trustForwardedHeaders() bool {
@@ -223,17 +224,9 @@ type EventPublisher interface {
Publish(events.Event)
}
// Broadcast fans an (ID-stamped) event out to every connected SSE
// client; stalled clients drop events rather than blocking the caller.
// Broadcast delivers a persisted task event through the shared stream hub.
func (s *Server) Broadcast(e events.Event) {
s.mu.Lock()
defer s.mu.Unlock()
for c := range s.conns {
select {
case c <- e:
default:
}
}
s.publish(liveUpdate{topic: "tasks", data: e}, "")
}
func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
@@ -292,15 +285,12 @@ func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/control-plane/resources/{kind}", s.handleControlPlaneQuery)
mux.HandleFunc("GET /api/control-plane/resources/{kind}/history", s.handleControlPlaneHistory)
mux.HandleFunc("POST /api/control-plane/resources/{kind}/commands/{command}", s.handleControlPlaneCommand)
mux.HandleFunc("GET /api/control-plane/watch/{kind}", s.handleControlPlaneWatch)
mux.HandleFunc("GET /api/control-plane/audit", s.handleAudit)
mux.HandleFunc("GET /api/identities", s.handleIdentitiesList)
mux.HandleFunc("GET /api/identities/watch", s.handleIdentitiesWatch)
mux.HandleFunc("POST /api/identities", s.handleIdentityCreate)
mux.HandleFunc("POST /api/identities/{id}/{command}", s.handleIdentityCommand)
mux.HandleFunc("GET /api/config", s.handleConfig)
mux.HandleFunc("GET /api/logs", s.handleLogs)
mux.HandleFunc("GET /api/logs/stream", s.handleLogStream)
}
func (s *Server) registerChatRoutes(mux *http.ServeMux) {
+127 -52
View File
@@ -2,12 +2,14 @@ package webui
import (
"context"
"encoding/base64"
"encoding/json"
"log/slog"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
)
// sseBacklogPageSize bounds one EventsSince fetch during catch-up.
@@ -30,61 +32,79 @@ func sseVisible(e events.Event) bool {
return !sseNoiseKinds[e.Kind]
}
// 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.
// handleSSE serves task history, latest resource snapshots, and optional
// live logs over one connection. Append-only topics resume from independent
// cursors; state topics replay their latest value on each connection.
func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) {
stream, ok := newSSEStream(s.Store, s.Log, w, sseSince(r))
cursors := sseCursors(r)
stream, ok := newSSEStream(s.Store, s.Log, w, cursors.Tasks)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
stream.logsSince = cursors.Logs
// Register before reading the backlog. An event published between the
// backlog read and subscription would otherwise be lost permanently.
conn, unregister := s.registerSSEConn()
conn, snapshot, stale, unregister := s.registerSSEConn()
defer unregister()
var logs <-chan logging.Entry
if r.URL.Query().Get("topics") == "logs" && s.LogFeed != nil {
logs = s.LogFeed.Subscribe(r.Context())
}
// Headers make an idle stream live before any resource changes.
w.WriteHeader(http.StatusOK)
stream.fl.Flush()
if !stream.catchUp(r.Context(), "") {
return
}
stream.drain(r.Context(), conn)
for _, update := range snapshot {
if !stream.sendLive(update) {
return
}
}
if r.URL.Query().Get("topics") == "logs" && !stream.sendLogSnapshot(s.LogFeed) {
return
}
stream.drain(r.Context(), conn, stale, logs)
}
// sseSince resolves the cursor 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. An absent or unparseable
// cursor degrades to "from the beginning": a browser holding a legacy integer
// id (the pre-cursor id: field) or garbage must not break the feed, exactly
// as a failed ParseInt yielded 0 before the cursor became a string.
func sseSince(r *http.Request) string {
since := r.URL.Query().Get("since")
// sseSince is the task-only cursor view retained for legacy clients/tests.
// Native reconnects prefer Last-Event-ID; deliberate reconnects use ?since=.
// An invalid or pre-cursor integer degrades to replay from the beginning.
func sseSince(r *http.Request) string { return sseCursors(r).Tasks }
type streamCursors struct {
Tasks string `json:"tasks"`
Logs int64 `json:"logs"`
}
// EventSource only sends Last-Event-ID on reconnects it owns. A deliberate
// reconnect (entering/leaving Logs) supplies the same token in ?since=.
func sseCursors(r *http.Request) streamCursors {
value := r.URL.Query().Get("since")
if header := r.Header.Get("Last-Event-ID"); header != "" {
since = header
value = header
}
if _, _, ok := storecontract.ParseEventCursor(since); !ok {
return ""
var cursors streamCursors
if data, err := base64.RawURLEncoding.DecodeString(value); err == nil {
_ = json.Unmarshal(data, &cursors)
} else if _, _, ok := storecontract.ParseEventCursor(value); ok {
cursors.Tasks = value // legacy task cursor
}
return since
if _, _, ok := storecontract.ParseEventCursor(cursors.Tasks); !ok {
cursors.Tasks = ""
}
if cursors.Logs < 0 {
cursors.Logs = 0
}
return cursors
}
// 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 {
s.conns = map[chan events.Event]struct{}{}
}
s.conns[c] = struct{}{}
s.mu.Unlock()
return c, func() {
s.mu.Lock()
delete(s.conns, c)
s.mu.Unlock()
}
func (c streamCursors) id() string {
encoded, _ := json.Marshal(c)
return base64.RawURLEncoding.EncodeToString(encoded)
}
// sseStream renders one client's event-stream response: an SSE frame per
@@ -92,11 +112,12 @@ func (s *Server) registerSSEConn() (chan events.Event, func()) {
// running "since" cursor that deduplicates the backlog against live
// broadcasts covering the same event.
type sseStream struct {
store storecontract.TaskStore
log *slog.Logger
w http.ResponseWriter
fl http.Flusher
since string
store storecontract.TaskStore
log *slog.Logger
w http.ResponseWriter
fl http.Flusher
since string
logsSince int64
}
// newSSEStream builds a stream over w, reporting false if w cannot be
@@ -114,12 +135,44 @@ func newSSEStream(st storecontract.TaskStore, log *slog.Logger, w http.ResponseW
// 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 s.writeLive(liveUpdate{topic: "tasks", data: e}, streamCursors{Tasks: storecontract.EventCursor(e.At, e.ID), Logs: s.logsSince}.id())
}
func (s *sseStream) sendLogSnapshot(feed *logging.Feed) bool {
if feed == nil {
return s.sendLive(liveUpdate{topic: "logs-status", data: map[string]bool{"available": false}})
}
for _, entry := range feed.Snapshot() {
if !s.sendLog(entry) {
return false
}
}
return true
}
func (s *sseStream) sendLog(entry logging.Entry) bool {
if entry.ID <= s.logsSince {
return true
}
if !s.writeLive(liveUpdate{topic: "logs", data: entry}, streamCursors{Tasks: s.since, Logs: entry.ID}.id()) {
return false
}
if _, err := s.w.Write([]byte("id: " + storecontract.EventCursor(e.At, e.ID) + "\ndata: " + string(body) + "\n\n")); err != nil {
s.logsSince = entry.ID
return true
}
func (s *sseStream) sendLive(update liveUpdate) bool { return s.writeLive(update, "") }
func (s *sseStream) writeLive(update liveUpdate, id string) bool {
body, err := marshalLiveFrame(update)
if err != nil {
return false
}
prefix := ""
if id != "" {
prefix = "id: " + id + "\n"
}
if _, err := s.w.Write([]byte(prefix + "data: " + string(body) + "\n\n")); err != nil {
return false
}
s.fl.Flush()
@@ -190,25 +243,47 @@ func (s *sseStream) sendPage(backlog []events.Event, target string) (reachedTarg
// 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) {
func (s *sseStream) drain(ctx context.Context, conn <-chan liveUpdate, stale <-chan struct{}, logs <-chan logging.Entry) {
for {
select {
case <-ctx.Done():
return
case e := <-conn:
cursor := storecontract.EventCursor(e.At, e.ID)
if cursor <= s.since {
case <-stale:
return
case entry, ok := <-logs:
if !ok {
logs = nil
continue
}
if !s.catchUp(ctx, cursor) {
if !s.sendLog(entry) {
return
}
if cursor > s.since {
if sseVisible(e) && !s.send(e) {
case update := <-conn:
if update.topic == "tasks" {
e, ok := update.data.(events.Event)
if ok && !s.relayTask(ctx, e) {
return
}
s.since = cursor
} else if !s.sendLive(update) {
return
}
}
}
}
func (s *sseStream) relayTask(ctx context.Context, e events.Event) bool {
cursor := storecontract.EventCursor(e.At, e.ID)
if cursor <= s.since {
return true
}
if !s.catchUp(ctx, cursor) {
return false
}
if cursor > s.since {
if sseVisible(e) && !s.send(e) {
return false
}
s.since = cursor
}
return true
}
+30
View File
@@ -2,6 +2,7 @@ package webui
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
@@ -171,6 +172,25 @@ func TestSSEStreamCatchUpPagesAcrossMultipleFetches(t *testing.T) {
}
}
// Every task frame identifies its topic so one EventSource can dispatch it
// without interpreting the event's domain payload.
func TestSSETaskFrameCarriesTopic(t *testing.T) {
stream, rec := newTestSSEStream("")
if !stream.send(events.Event{ID: 1, At: testAt, Kind: events.KindTaskQueued}) {
t.Fatal("send failed")
}
line := strings.Split(rec.Body.String(), "\n")[1]
var frame struct {
Topic string `json:"topic"`
}
if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &frame); err != nil {
t.Fatal(err)
}
if frame.Topic != "tasks" {
t.Fatalf("topic = %q, want tasks", frame.Topic)
}
}
// A target 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".
@@ -229,6 +249,16 @@ func TestSSEStreamSendPageSkipsNoiseKindsButAdvancesSince(t *testing.T) {
}
}
func TestSSEMultiTopicCursorHeaderWinsOverDeliberateReconnectURL(t *testing.T) {
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet,
"/api/stream?topics=logs&since="+streamCursors{Tasks: cursor(1), Logs: 4}.id(), nil)
request.Header.Set("Last-Event-ID", streamCursors{Tasks: cursor(2), Logs: 5}.id())
got := sseCursors(request)
if got.Tasks != cursor(2) || got.Logs != 5 {
t.Fatalf("cursors = %+v, want tasks 2 and logs 5 from native reconnect", got)
}
}
// TestSSESinceDegradesUnparseableCursorToBeginning is the legacy-cursor
// tolerance guard: a browser holding the pre-cursor integer id: field, or a
// ?since= carrying garbage, must resume from the beginning rather than error