Files
magpie/internal/gateway/sse.go
T
yetone 68ab4c06da gateway: a handed-off gateway answers a kept-alive connection's next request rather than closing it under the agent (#3451)
TestRestartHandsTheGatewayOver went red on ubuntu CI at b3edcabf2 (run
40676722560: "4 of 5 requests during the restart answered", connection
reset by peer), and three times under load since 10-25 with no owner.
It is a real gap a user meets on an update: once the gateway is handed
to the new magpie, the old one's end calls Shutdown, which closes every
idle kept-alive connection at once. An agent that has just sent its next
request on one (Go's transport, Node's agent and curl reuse them) gets
the connection reset, and a POST is not retried. #3568 made the end wait
only for connections taken whose first request was unread.

Now:
- unreadConns also counts kept-alive connections idle between requests
  (StateIdle until the next state), and a handover's end waits for them
  as for new ones, unreadWait (5s) at most, before Shutdown;
- once the gateway takes no connection (stopAccepting), each reply it
  gives says Connection: close (closesWhenHandedOff), so the agent's
  next request dials the magpie serving the port after it;
- the SSE writer keeps a Connection value already set, where it wrote
  keep-alive over the close.
A connection its agent leaves idle the whole 5s is closed by Shutdown,
as its idle timeout would close it. `make dev`'s ending backend
(Handover) takes the same path.

Run on mote (macOS 27, arm64) at this tree on 51e3169fb:
- new TestHandedOffGatewayAnswersAKeptAliveConnection (handed off and
  make dev): a request on a connection answered before the handover,
  sent 100ms after the end began, is answered "quick" with the
  connection closed, and the old one ends within 3s. Red on the old code
  with this test, both subtests: "" unexpected EOF, as #3451 reads.
- go test -count=3 -run 'TestHandedOff|TestHandedOver|TestInherited|
  TestToolCallOfTheMagpieBefore' ./internal/gateway: ok; the same
  handover tests -race -count=3: ok.
- go test -count=8 -run '^TestRestartHandsTheGatewayOver$'
  ./internal/gui: ok.
- go test -timeout 45m ./internal/gateway ./internal/gui
  ./internal/handoff: gateway ok (459s), handoff ok; gui red only on
  TestMainWindowCorners/macOS_26_SDK, mote's macOS 27, filed as #3949.
- gofmt -l clean; go vet ./internal/gateway ./internal/gui;
  GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway ok.
Not broken by hand separately: the Connection: close alone (the test's
r.Close check guards it) and the SSE writer's keep, which no test
streams through after a handover.
Not run: the full ./... suite; Linux (the CI red's OS) only through CI.
2026-10-28 19:43:39 +08:00

144 lines
3.3 KiB
Go

package gateway
import (
"bufio"
"bytes"
"encoding/json"
"io"
"net/http"
"strings"
"time"
)
// readSSE walks a server-sent event stream, calling fn with each event's
// name and data. Data lines of one event are joined with newlines.
func readSSE(r io.Reader, fn func(event, data string) error) error {
return readSSEAlive(r, fn, nil)
}
// readSSEAlive is readSSE that also calls alive, when not nil, after each
// event and each comment: every sign that the stream is alive, a
// keepalive (": keepalive") as much as an answer.
func readSSEAlive(r io.Reader, fn func(event, data string) error, alive func()) error {
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 0, 64<<10), 32<<20)
var event string
var data []string
flush := func() error {
if len(data) == 0 {
event = ""
return nil
}
err := fn(event, strings.Join(data, "\n"))
event, data = "", nil
if err == nil && alive != nil {
alive()
}
return err
}
for sc.Scan() {
line := sc.Text()
switch {
case line == "":
if err := flush(); err != nil {
return err
}
case strings.HasPrefix(line, ":"):
if alive != nil {
alive()
}
case strings.HasPrefix(line, "event:"):
event = strings.TrimSpace(line[6:])
case strings.HasPrefix(line, "data:"):
data = append(data, strings.TrimPrefix(line[5:], " "))
}
}
if err := flush(); err != nil {
return err
}
return sc.Err()
}
// sseWriter writes events to a client and flushes each one.
type sseWriter struct {
w http.ResponseWriter
f http.Flusher
begun bool
wrote time.Time // when the client was last written to
}
func newSSEWriter(w http.ResponseWriter) *sseWriter {
f, _ := w.(http.Flusher)
return &sseWriter{w: w, f: f}
}
func (s *sseWriter) begin() {
if s.begun {
return
}
s.begun = true
h := s.w.Header()
h.Set("Content-Type", "text/event-stream; charset=utf-8")
h.Set("Cache-Control", "no-cache")
if h.Get("Connection") == "" { // a handed-off gateway's close stays (closesWhenHandedOff)
h.Set("Connection", "keep-alive")
}
h.Set("X-Accel-Buffering", "no")
s.w.WriteHeader(http.StatusOK)
s.flush()
s.wrote = time.Now()
}
func (s *sseWriter) flush() {
if s.f != nil {
s.f.Flush()
}
}
// quiet is how long the client has had nothing from s; a stream not yet
// begun has been quiet for ever.
func (s *sseWriter) quiet() time.Duration {
if !s.begun {
return 1<<63 - 1
}
return time.Since(s.wrote)
}
// comment writes an SSE comment, which every event stream reader skips:
// no event, only the news that the stream is alive. No blank line after
// it: openai-go v2 (Crush) reads a blank line as an event even with no
// data, and fails on it ("unexpected end of JSON input").
func (s *sseWriter) comment(text string) {
s.begin()
io.WriteString(s.w, ": "+text+"\n")
s.flush()
s.wrote = time.Now()
}
// event writes one event; a JSON-marshallable value or a raw string.
func (s *sseWriter) event(name string, v any) {
s.begin()
var b bytes.Buffer
if name != "" {
b.WriteString("event: ")
b.WriteString(name)
b.WriteByte('\n')
}
b.WriteString("data: ")
switch x := v.(type) {
case string:
b.WriteString(x)
case []byte:
b.Write(x)
case json.RawMessage:
b.Write(x)
default:
j, _ := json.Marshal(x)
b.Write(j)
}
b.WriteString("\n\n")
s.w.Write(b.Bytes())
s.flush()
s.wrote = time.Now()
}