Explorar el Código

fix(sse): serialize agentHub writes, check Flush errors, add IdleTimeout (#75) (#81)

agentConn.write() was called concurrently from Send() (refresh handler),
the heartbeat ticker, and the 'bye' broadcast on connection replacement —
all racing on the ResponseWriter with no serialization. The client hub had
a wmu mutex for this exact reason; agentConn did not. Add wmu to agentConn.

Both client.write() and agentConn.write() called c.flusher.Flush() (the
http.Flusher interface, which returns no error) instead of rc.Flush() (the
ResponseController method, which does). A zombie peer whose write deadline
expired could pass the Fprint (buffered) and silently fail the Flush without
the hub ever noticing — the dead client stayed registered. Use rc.Flush()
and propagate the error so the hub removes the client.

http.Server had ReadHeaderTimeout but no IdleTimeout. Add 2m to close idle
keep-alive connections without affecting active SSE streams.

Regression test with -race: 8 goroutines x 50 concurrent writes to a single
agentConn. Without wmu the -race detector flags the data race and the body
is corrupted (4928 vs 8800 bytes); with the fix all 20 packages pass -race.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho hace 3 meses
padre
commit
3a3e259449

+ 1 - 0
server-go/cmd/netpulse/main.go

@@ -286,6 +286,7 @@ func run() error {
 		Addr:              fmt.Sprintf(":%d", cfg.Port),
 		Handler:           handler,
 		ReadHeaderTimeout: 10 * time.Second,
+		IdleTimeout:       2 * time.Minute,
 	}
 
 	errCh := make(chan error, 1)

+ 6 - 1
server-go/internal/sse/agenthub.go

@@ -25,6 +25,7 @@ type agentConn struct {
 	slug    string
 	w       http.ResponseWriter
 	flusher http.Flusher
+	wmu     sync.Mutex
 	done    chan struct{}
 	once    sync.Once
 }
@@ -79,12 +80,16 @@ func (h *AgentHub) remove(slug string) {
 }
 
 func (c *agentConn) write(payload string) error {
+	c.wmu.Lock()
+	defer c.wmu.Unlock()
 	rc := http.NewResponseController(c.w)
 	_ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
 	if _, err := fmt.Fprint(c.w, payload); err != nil {
 		return err
 	}
-	c.flusher.Flush()
+	if err := rc.Flush(); err != nil {
+		return err
+	}
 	return nil
 }
 

+ 47 - 0
server-go/internal/sse/agenthub_test.go

@@ -0,0 +1,47 @@
+package sse
+
+import (
+	"net/http/httptest"
+	"sync"
+	"testing"
+)
+
+// TestAgentConnWriteConcurrentNoRace verifica que llamadas concurrentes a
+// agentConn.write() (desde Send, heartbeat y el "bye" de reemplazo) no
+// intercalan escrituras en el ResponseWriter. El detector -race debe estar
+// limpio. Sin el wmu en agentConn, este test detecta la data race.
+func TestAgentConnWriteConcurrentNoRace(t *testing.T) {
+	rec := httptest.NewRecorder()
+	c := &agentConn{
+		slug:    "test",
+		w:       rec,
+		flusher: rec,
+		done:    make(chan struct{}),
+	}
+
+	const goroutines = 8
+	const writesEach = 50
+
+	var wg sync.WaitGroup
+	wg.Add(goroutines)
+	for i := 0; i < goroutines; i++ {
+		go func() {
+			defer wg.Done()
+			for j := 0; j < writesEach; j++ {
+				if err := c.write("event: ping\ndata: {}\n\n"); err != nil {
+					t.Errorf("write failed: %v", err)
+					return
+				}
+			}
+		}()
+	}
+	wg.Wait()
+
+	totalWrites := goroutines * writesEach
+	got := rec.Body.Len()
+	// Cada payload "event: ping\ndata: {}\n\n" = 22 bytes.
+	want := totalWrites * len("event: ping\ndata: {}\n\n")
+	if got != want {
+		t.Fatalf("body length = %d, want %d (interleaved/corrupted writes)", got, want)
+	}
+}

+ 3 - 1
server-go/internal/sse/hub.go

@@ -39,7 +39,9 @@ func (c *client) write(payload string) error {
 	if _, err := fmt.Fprint(c.w, payload); err != nil {
 		return err
 	}
-	c.flusher.Flush()
+	if err := rc.Flush(); err != nil {
+		return err
+	}
 	return nil
 }