Просмотр исходного кода

fix(sse): enforce client limits and swap agent streams atomically (#1612)

Check maxClients and register the client in the same critical section so concurrent streams cannot exceed the configured limit.

Replace the agent connection in one atomic swap. The previous stream receives bye and is closed outside the mutex, so two simultaneous streams for one slug cannot leave a hidden connection.

Closes #1611
Nacho 1 месяц назад
Родитель
Сommit
6fe6274251

+ 19 - 14
server-go/internal/sse/agenthub.go

@@ -138,6 +138,14 @@ func (h *AgentHub) SendPrivileged(slug, event string, data any) error {
 	return nil
 }
 
+func (h *AgentHub) swapConn(c *agentConn) *agentConn {
+	h.mu.Lock()
+	old := h.conns[c.slug]
+	h.conns[c.slug] = c
+	h.mu.Unlock()
+	return old
+}
+
 func (h *AgentHub) removeConn(c *agentConn) {
 	h.mu.Lock()
 	if h.conns[c.slug] == c {
@@ -202,26 +210,23 @@ func (h *AgentHub) HandleStream(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	// Cerrar conexión anterior del mismo slug. El write va FUERA del mutex:
-	// un cliente lento no debe bloquear Send/remove de otros (issue #200).
-	h.mu.Lock()
-	old, ok := h.conns[slug]
-	h.mu.Unlock()
-	if ok {
-		_ = old.write("event: bye\ndata: {}\n\n")
-		time.Sleep(100 * time.Millisecond) // dar tiempo al flush
-		h.removeConn(old)
-	}
-
 	w.Header().Set("Content-Type", "text/event-stream")
 	w.Header().Set("X-Accel-Buffering", "no")
 	w.Header().Set("Cache-Control", "no-cache")
 	w.WriteHeader(http.StatusOK)
 
 	c := &agentConn{slug: slug, secure: auth.IsSecureRequest(r), w: w, flusher: flusher, done: make(chan struct{})}
-	h.mu.Lock()
-	h.conns[slug] = c
-	h.mu.Unlock()
+	// El reemplazo del mapa es atomico: dos streams simultaneos no pueden
+	// leer el mismo "old" y dejar uno de ellos fuera del mapa. El "bye" se
+	// escribe fuera del mutex para que un cliente lento no bloquee al resto
+	// (issue #200).
+	old := h.swapConn(c)
+	if old != nil {
+		go func() {
+			_ = old.write("event: bye\ndata: {}\n\n")
+			old.close()
+		}()
+	}
 	defer h.removeConn(c)
 	defer func() { // FORK: runs first, before the handler returns
 		c.wmu.Lock()

+ 120 - 0
server-go/internal/sse/agenthub_swap_test.go

@@ -0,0 +1,120 @@
+package sse
+
+import (
+	"context"
+	"net/http/httptest"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+)
+
+func TestSwapConnIsAtomic(t *testing.T) {
+	h := NewAgentHub(func(string, string) bool { return true })
+	const n = 32
+
+	conns := make([]*agentConn, n)
+	olds := make([]*agentConn, n)
+	start := make(chan struct{})
+	var wg sync.WaitGroup
+
+	for i := 0; i < n; i++ {
+		conns[i] = &agentConn{slug: "rt1", done: make(chan struct{})}
+		wg.Add(1)
+		go func(i int) {
+			defer wg.Done()
+			<-start
+			olds[i] = h.swapConn(conns[i])
+		}(i)
+	}
+	close(start)
+	wg.Wait()
+
+	seen := make(map[*agentConn]bool, n-1)
+	for _, old := range olds {
+		if old == nil {
+			continue
+		}
+		if seen[old] {
+			t.Fatalf("duplicate previous connection: %p", old)
+		}
+		seen[old] = true
+	}
+	if len(seen) != n-1 {
+		t.Fatalf("previous connections: got %d want %d", len(seen), n-1)
+	}
+
+	h.mu.Lock()
+	got := h.conns["rt1"]
+	h.mu.Unlock()
+	if got == nil {
+		t.Fatal("no active connection")
+	}
+	found := false
+	for _, c := range conns {
+		if c == got {
+			found = true
+			break
+		}
+	}
+	if !found {
+		t.Fatalf("unexpected active connection: %p", got)
+	}
+}
+
+func TestConcurrentAgentStreamsKeepOne(t *testing.T) {
+	h := NewAgentHub(func(string, string) bool { return true })
+
+	type stream struct {
+		rec    *httptest.ResponseRecorder
+		cancel context.CancelFunc
+		done   chan struct{}
+	}
+	streams := make([]*stream, 2)
+	start := make(chan struct{})
+
+	for i := range streams {
+		req := httptest.NewRequest("GET", "/api/agents/rt1/stream", nil)
+		req.SetPathValue("slug", "rt1")
+		ctx, cancel := context.WithCancel(req.Context())
+		req = req.WithContext(ctx)
+		rec := httptest.NewRecorder()
+		s := &stream{rec: rec, cancel: cancel, done: make(chan struct{})}
+		streams[i] = s
+
+		go func() {
+			defer close(s.done)
+			<-start
+			h.HandleStream(rec, req)
+		}()
+	}
+	close(start)
+
+	var loser int
+	select {
+	case <-streams[0].done:
+		loser = 0
+	case <-streams[1].done:
+		loser = 1
+	case <-time.After(3 * time.Second):
+		t.Fatal("no stream was replaced")
+	}
+	for _, s := range streams {
+		s.cancel()
+	}
+	<-streams[1-loser].done
+
+	if !strings.Contains(streams[loser].rec.Body.String(), "event: bye") {
+		t.Fatal("replaced stream did not receive bye")
+	}
+	if strings.Contains(streams[1-loser].rec.Body.String(), "event: bye") {
+		t.Fatal("active stream received bye")
+	}
+
+	h.mu.Lock()
+	left := len(h.conns)
+	h.mu.Unlock()
+	if left != 0 {
+		t.Fatalf("connections left: %d", left)
+	}
+}

+ 11 - 13
server-go/internal/sse/hub.go

@@ -155,13 +155,6 @@ func (h *Hub) NotifyShutdown() {
 
 // HandleStream sirve GET /api/stream (requiere sesión: RequireAuth antes).
 func (h *Hub) HandleStream(w http.ResponseWriter, r *http.Request) {
-	h.mu.Lock()
-	full := len(h.clients) >= h.maxClients
-	h.mu.Unlock()
-	if full {
-		auth.WriteError(w, http.StatusServiceUnavailable, "too_many_clients")
-		return
-	}
 	flusher, ok := w.(http.Flusher)
 	if !ok {
 		auth.WriteError(w, http.StatusInternalServerError, "internal_error")
@@ -169,13 +162,12 @@ func (h *Hub) HandleStream(w http.ResponseWriter, r *http.Request) {
 	}
 	sessionID := auth.SessionIDFromContext(r.Context())
 
-	w.Header().Set("Content-Type", "text/event-stream")
-	w.Header().Set("X-Accel-Buffering", "no")
-	w.Header().Set("Cache-Control", "no-cache") // sobrescribe el no-store
-	// Deliberadamente SIN Content-Encoding (ver sse.js:3-6).
-	w.WriteHeader(http.StatusOK)
-
 	h.mu.Lock()
+	if len(h.clients) >= h.maxClients {
+		h.mu.Unlock()
+		auth.WriteError(w, http.StatusServiceUnavailable, "too_many_clients")
+		return
+	}
 	c := &client{id: h.nextID, sessionID: sessionID, w: w, flusher: flusher, done: make(chan struct{})}
 	h.nextID++
 	h.clients[c.id] = c
@@ -183,6 +175,12 @@ func (h *Hub) HandleStream(w http.ResponseWriter, r *http.Request) {
 	defer h.remove(c)
 	defer c.finish() // FORK: runs first, before the handler returns
 
+	w.Header().Set("Content-Type", "text/event-stream")
+	w.Header().Set("X-Accel-Buffering", "no")
+	w.Header().Set("Cache-Control", "no-cache") // sobrescribe el no-store
+	// Deliberadamente SIN Content-Encoding (ver sse.js:3-6).
+	w.WriteHeader(http.StatusOK)
+
 	// Primer snapshot inmediato al conectar
 	if h.getOverview != nil {
 		if ov := h.getOverview(); ov != nil {

+ 68 - 0
server-go/internal/sse/hub_capacity_test.go

@@ -0,0 +1,68 @@
+package sse
+
+import (
+	"context"
+	"net/http/httptest"
+	"sync"
+	"testing"
+	"time"
+)
+
+func TestHandleStreamHonorsMaxClientsConcurrently(t *testing.T) {
+	h := NewHub(nil, 1, nil)
+	const n = 8
+
+	start := make(chan struct{})
+	results := make(chan int, n)
+	cancels := make([]context.CancelFunc, n)
+	var wg sync.WaitGroup
+
+	for i := 0; i < n; i++ {
+		req := httptest.NewRequest("GET", "/api/stream", nil)
+		ctx, cancel := context.WithCancel(req.Context())
+		cancels[i] = cancel
+		req = req.WithContext(ctx)
+		rec := httptest.NewRecorder()
+
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			<-start
+			h.HandleStream(rec, req)
+			results <- rec.Code
+		}()
+	}
+	close(start)
+
+	for i := 0; i < n-1; i++ {
+		select {
+		case code := <-results:
+			if code != 503 {
+				t.Fatalf("concurrent stream: got %d want 503", code)
+			}
+		case <-time.After(3 * time.Second):
+			t.Fatal("timeout waiting for rejected streams")
+		}
+	}
+
+	for _, cancel := range cancels {
+		cancel()
+	}
+
+	select {
+	case code := <-results:
+		if code != 200 {
+			t.Fatalf("accepted stream: got %d want 200", code)
+		}
+	case <-time.After(3 * time.Second):
+		t.Fatal("timeout waiting for accepted stream")
+	}
+	wg.Wait()
+
+	h.mu.Lock()
+	left := len(h.clients)
+	h.mu.Unlock()
+	if left != 0 {
+		t.Fatalf("clients left: %d", left)
+	}
+}