handover: end a host's streams at the move's start, not at the take
A planned move waited up to its 10 s in-flight bound for the host's requests before it released the host. An SSE stream or an upgraded connection never ends on its own, so every move with one open (the probe's /events stream on every host) spent the whole bound waiting. This moves the stream close earlier, from the take to the move's start. Right after BeginMove, before the ticket and in-flight wait, moveOne now ends the host's long-lived responses on this box: - edge-held streams (CloseHeldHost, as at the take before); - proxied SSE responses (text/event-stream), whose body now ends at the next event boundary, so the client sees a clean end after a whole event and reconnects with Last-Event-ID; - upgraded connections (101, WebSockets), closed as the connection drain closes them at its bound. The activator gives every request it serves an edge.StreamEnd and keeps them per host; the tenant proxies' response hook marks the ones that turn out to be streams. EndMoveStreams ends only marked ones, and any that open later during the move. Ordinary requests keep the 10 s bound. The clients reconnect and are held by the move gate like any other request, then forwarded once taken. The later CloseHeldHost after SetMoveTaken stays: it is idempotent and closes any edge-held stream opened on this box during the move.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+858
−8
internal/activator/activator.go+7 −0internal/activator/handover.go+3 −0internal/activator/movestreams.go+116 −0internal/activator/movestreams_test.go+243 −0internal/edge/cookiescope.go+4 −1internal/edge/movestreams.go+268 −0internal/edge/movestreams_test.go+139 −0internal/host/hadrain.go+14 −4internal/host/hadrain_test.go+64 −3
Intent
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 69ccad74a..1ccca9328 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -1384,6 +1384,9 @@ type Service struct { |
| // moves is the planned handover's per-host state and admission |
| // tickets (handover.go), under mu. |
| moves moveTable |
| + // moveStreams are the requests in flight per host that a move may end |
| + // early, if they are streams (movestreams.go). |
| + moveStreams moveStreams |
| // drainLog is the drain transaction's release log (hadrainmove.go). |
| drainLog drainReleases |
| @@ -6552,6 +6555,10 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| return a.serveWakeError(w, r, rt, err) |
| } |
| defer release() |
| + // A move of the host ends it early if its response is a stream |
| + // (movestreams.go). |
| + r, untrack := a.moveStreams.track(rt.Host, r) |
| + defer untrack() |
| // Counted in flight now: the request's admission ticket ends |
| // (handover.go). |
| edge.ReleaseMoveTicket(r) |
diff --git a/internal/activator/handover.go b/internal/activator/handover.go| index 1ebb9bd6e..4a7973f8e 100644 |
| --- a/internal/activator/handover.go |
| +++ b/internal/activator/handover.go |
| @@ -297,6 +297,7 @@ func (a *Service) BeginMove(host string) error { |
| a.moves.hosts = make(map[string]*hostMove) |
| } |
| a.moves.hosts[host] = &hostMove{route: e.route, phase: moveHolding, changed: make(chan struct{})} |
| + a.moveStreams.reset(host) |
| return nil |
| } |
| @@ -381,6 +382,7 @@ func (a *Service) SetMoveLeft(host, reason string) { |
| log.Printf("activator: handover of %s left: %s; its held requests get today's answer", host, reason) |
| m.gone = true |
| delete(a.moves.hosts, host) |
| + a.moveStreams.reset(host) |
| m.notifyLocked() |
| } |
| @@ -392,6 +394,7 @@ func (a *Service) EndDrainMoves() { |
| for host, m := range a.moves.hosts { |
| m.gone = true |
| delete(a.moves.hosts, host) |
| + a.moveStreams.reset(host) |
| m.notifyLocked() |
| } |
| } |
diff --git a/internal/activator/movestreams.go b/internal/activator/movestreams.go| new file mode 100644 |
| index 000000000..7eb7a20fb |
| --- /dev/null |
| +++ b/internal/activator/movestreams.go |
| @@ -0,0 +1,116 @@ |
| +package activator |
| + |
| +// A move ends its host's long-lived responses at its start (region HA |
| +// spec §25.4 step 3.1, §25.8, R3.5). The drain waits up to its in-flight |
| +// bound (10 s) for the host's requests here before it releases the host; |
| +// an SSE stream or an upgraded connection (a WebSocket) never ends on its |
| +// own, so one open stream held every move to the whole bound. Now each |
| +// request served for a host carries an edge.StreamEnd, and EndMoveStreams |
| +// ends those whose response is a stream: SSE at its next event boundary, |
| +// an upgraded connection by closing it. Their clients reconnect and are |
| +// held by the move like any other request. An ordinary request is not |
| +// touched and keeps the bound. |
| +// |
| +// Memory only. The table has its own lock, so a request's track and |
| +// untrack never take a.mu; a.mu may be held around reset (lock order: |
| +// a.mu, then moveStreams.mu, never the other way). |
| + |
| +import ( |
| + "net/http" |
| + "sync" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| +) |
| + |
| +type moveStreams struct { |
| + mu sync.Mutex |
| + // hosts is every request in flight per host. |
| + hosts map[string]map[*edge.StreamEnd]struct{} |
| + // ending is the hosts whose move has ended its streams: a request |
| + // tracked from then on is ended too once its response is a stream (a |
| + // request admitted on a ticket before the move began). |
| + ending map[string]bool |
| +} |
| + |
| +// track gives r a StreamEnd and counts it under host until the returned |
| +// func runs. |
| +func (m *moveStreams) track(host string, r *http.Request) (*http.Request, func()) { |
| + r, s := edge.WithStreamEnd(r) |
| + m.mu.Lock() |
| + if m.hosts == nil { |
| + m.hosts = make(map[string]map[*edge.StreamEnd]struct{}) |
| + } |
| + set := m.hosts[host] |
| + if set == nil { |
| + set = make(map[*edge.StreamEnd]struct{}) |
| + m.hosts[host] = set |
| + } |
| + set[s] = struct{}{} |
| + ending := m.ending[host] |
| + m.mu.Unlock() |
| + if ending { |
| + s.End() |
| + } |
| + return r, func() { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if set := m.hosts[host]; set != nil { |
| + delete(set, s) |
| + if len(set) == 0 { |
| + delete(m.hosts, host) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// reset forgets that host's streams were ended: a move begins or ends. |
| +func (m *moveStreams) reset(host string) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + delete(m.ending, host) |
| +} |
| + |
| +// endingLocked marks host's streams ended until reset, and answers the |
| +// requests in flight for it. a.mu is held, so no reset runs in between. |
| +func (m *moveStreams) endingLocked(host string) []*edge.StreamEnd { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if m.ending == nil { |
| + m.ending = make(map[string]bool) |
| + } |
| + m.ending[host] = true |
| + var all []*edge.StreamEnd |
| + for s := range m.hosts[host] { |
| + all = append(all, s) |
| + } |
| + return all |
| +} |
| + |
| +// end ends each of all that is a stream, or becomes one, and answers how |
| +// many are streams now. |
| +func end(all []*edge.StreamEnd) int { |
| + n := 0 |
| + for _, s := range all { |
| + s.End() |
| + if s.Stream() { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// EndMoveStreams ends host's long-lived responses on this box at the |
| +// move's start (§25.4 step 3.1): SSE streams at their next event boundary |
| +// and upgraded connections at once, and any that open later during the |
| +// move. It answers how many were ended now, and 0 when host is not moving |
| +// here (BeginMove first). |
| +func (a *Service) EndMoveStreams(host string) int { |
| + a.mu.Lock() |
| + if a.moves.hosts[host] == nil { |
| + a.mu.Unlock() |
| + return 0 |
| + } |
| + all := a.moveStreams.endingLocked(host) |
| + a.mu.Unlock() |
| + return end(all) |
| +} |
diff --git a/internal/activator/movestreams_test.go b/internal/activator/movestreams_test.go| new file mode 100644 |
| index 000000000..0a530c0ea |
| --- /dev/null |
| +++ b/internal/activator/movestreams_test.go |
| @@ -0,0 +1,243 @@ |
| +package activator |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/http/httputil" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| +) |
| + |
| +// A move ends its host's long-lived responses at its start (region HA |
| +// §25.4 step 3.1, §25.8): an SSE stream or an upgraded connection open |
| +// when the move begins no longer holds the in-flight wait to its bound. |
| +// An ordinary request still does. The scene is haServiceEntry, served |
| +// through a.ServeHTTP behind a reverse proxy with the edge's move hook, |
| +// as the edge's tenant proxies have it (responseModifier). |
| + |
| +// moveStreamUpstream is the app: /events is an SSE stream that sends an |
| +// event every 20 ms until its client goes; /ws upgrades and echoes until |
| +// either side closes; /slow answers once release is closed. |
| +func moveStreamUpstream(t *testing.T, release <-chan struct{}) *url.URL { |
| + t.Helper() |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch r.URL.Path { |
| + case "/events": |
| + w.Header().Set("Content-Type", "text/event-stream") |
| + w.WriteHeader(http.StatusOK) |
| + f := w.(http.Flusher) |
| + for i := 0; ; i++ { |
| + // Two writes per event, so a boundary is never a read's |
| + // edge by accident. |
| + fmt.Fprintf(w, "id: %d\n", i) |
| + f.Flush() |
| + fmt.Fprintf(w, "data: tick %d\n\n", i) |
| + f.Flush() |
| + select { |
| + case <-r.Context().Done(): |
| + return |
| + case <-time.After(20 * time.Millisecond): |
| + } |
| + } |
| + case "/ws": |
| + conn, brw, err := http.NewResponseController(w).Hijack() |
| + if err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + defer conn.Close() |
| + brw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: echo\r\nConnection: Upgrade\r\n\r\n") |
| + brw.Flush() |
| + io.Copy(conn, brw) |
| + case "/slow": |
| + select { |
| + case <-release: |
| + case <-r.Context().Done(): |
| + } |
| + io.WriteString(w, "done") |
| + } |
| + })) |
| + t.Cleanup(srv.Close) |
| + u, _ := url.Parse(srv.URL) |
| + return u |
| +} |
| + |
| +// moveStreamFront serves s's host through a.ServeHTTP and a reverse |
| +// proxy to up whose response hook is the edge's. |
| +func moveStreamFront(t *testing.T, s *haSvc, up *url.URL) string { |
| + t.Helper() |
| + proxy := &httputil.ReverseProxy{ |
| + Rewrite: func(pr *httputil.ProxyRequest) { pr.SetURL(up) }, |
| + ModifyResponse: func(resp *http.Response) error { edge.MarkMoveStream(resp); return nil }, |
| + } |
| + front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + s.a.ServeHTTP(w, r, s.rt, proxy) |
| + })) |
| + t.Cleanup(front.Close) |
| + return front.URL |
| +} |
| + |
| +func (s *haSvc) inflight() int { |
| + s.a.mu.Lock() |
| + defer s.a.mu.Unlock() |
| + if e := s.a.entries[s.rt.Host]; e != nil { |
| + return e.inflight |
| + } |
| + return 0 |
| +} |
| + |
| +// openEvents opens the SSE stream and reads its first two events. |
| +func openEvents(t *testing.T, front string) (*http.Response, *bufio.Reader) { |
| + t.Helper() |
| + resp, err := http.Get(front + "/events") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { resp.Body.Close() }) |
| + br := bufio.NewReader(resp.Body) |
| + for seen := 0; seen < 2; { |
| + line, err := br.ReadString('\n') |
| + if err != nil { |
| + t.Fatalf("reading the stream: %v", err) |
| + } |
| + if line == "\n" { |
| + seen++ |
| + } |
| + } |
| + return resp, br |
| +} |
| + |
| +// moveAndWait begins the move, ends its streams and waits for the host's |
| +// requests here as the drain does, with the drain's 10 s bound. It |
| +// answers how long the wait took and its error. |
| +func moveAndWait(t *testing.T, s *haSvc, bound time.Duration) (time.Duration, error) { |
| + t.Helper() |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + start := time.Now() |
| + s.a.EndMoveStreams(s.rt.Host) |
| + ctx, cancel := context.WithTimeout(t.Context(), bound) |
| + defer cancel() |
| + err := s.a.WaitDrainInflight(ctx, s.rt.Host) |
| + return time.Since(start), err |
| +} |
| + |
| +func TestMoveEndsAnSSEStreamAtItsStart(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + front := moveStreamFront(t, s, moveStreamUpstream(t, nil)) |
| + _, br := openEvents(t, front) |
| + if n := s.inflight(); n != 1 { |
| + t.Fatalf("in flight = %d with the stream open, want 1", n) |
| + } |
| + took, err := moveAndWait(t, s, 10*time.Second) |
| + if err != nil || took > time.Second { |
| + t.Fatalf("the in-flight wait took %v (%v): an open SSE stream held the move", took, err) |
| + } |
| + // The client sees a clean end after a whole event. |
| + rest, err := io.ReadAll(br) |
| + if err != nil { |
| + t.Fatalf("the stream did not end cleanly: %v (after %q)", err, rest) |
| + } |
| + if len(rest) > 0 && !strings.HasSuffix(string(rest), "\n\n") { |
| + t.Fatalf("the stream ended mid-event: %q", rest) |
| + } |
| + if n := s.inflight(); n != 0 { |
| + t.Fatalf("in flight = %d after the end", n) |
| + } |
| +} |
| + |
| +// A stream that opens after the move's start (its request admitted before |
| +// it, on a ticket) is ended as soon as its head says it is one. |
| +func TestMoveEndsAStreamThatOpensAfterItsStart(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + front := moveStreamFront(t, s, moveStreamUpstream(t, nil)) |
| + if _, err := moveAndWait(t, s, 10*time.Second); err != nil { |
| + t.Fatal(err) |
| + } |
| + resp, err := http.Get(front + "/events") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + done := make(chan error, 1) |
| + go func() { _, err := io.ReadAll(resp.Body); done <- err }() |
| + select { |
| + case err := <-done: |
| + if err != nil { |
| + t.Fatalf("the late stream did not end cleanly: %v", err) |
| + } |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("a stream opened during the move was not ended") |
| + } |
| +} |
| + |
| +func TestMoveEndsAnUpgradedConnectionAtItsStart(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + front := moveStreamFront(t, s, moveStreamUpstream(t, nil)) |
| + conn, err := net.Dial("tcp", strings.TrimPrefix(front, "http://")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer conn.Close() |
| + io.WriteString(conn, "GET /ws HTTP/1.1\r\nHost: shop.example.com\r\nUpgrade: echo\r\nConnection: Upgrade\r\n\r\n") |
| + br := bufio.NewReader(conn) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil || resp.StatusCode != http.StatusSwitchingProtocols { |
| + t.Fatalf("upgrade: %v %v", resp, err) |
| + } |
| + io.WriteString(conn, "ping") |
| + buf := make([]byte, 4) |
| + if _, err := io.ReadFull(br, buf); err != nil || string(buf) != "ping" { |
| + t.Fatalf("echo: %q %v", buf, err) |
| + } |
| + if n := s.inflight(); n != 1 { |
| + t.Fatalf("in flight = %d with the connection open, want 1", n) |
| + } |
| + took, err := moveAndWait(t, s, 10*time.Second) |
| + if err != nil || took > time.Second { |
| + t.Fatalf("the in-flight wait took %v (%v): an upgraded connection held the move", took, err) |
| + } |
| + conn.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| + if _, err := br.ReadByte(); !errors.Is(err, io.EOF) { |
| + t.Fatalf("the connection is still open: %v", err) |
| + } |
| +} |
| + |
| +// An ordinary request is not ended: it holds the in-flight wait to its |
| +// bound, as before. |
| +func TestMoveKeepsTheBoundForAnOrdinaryRequest(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + release := make(chan struct{}) |
| + front := moveStreamFront(t, s, moveStreamUpstream(t, release)) |
| + got := make(chan string, 1) |
| + go func() { |
| + resp, err := http.Get(front + "/slow") |
| + if err != nil { |
| + got <- err.Error() |
| + return |
| + } |
| + defer resp.Body.Close() |
| + b, _ := io.ReadAll(resp.Body) |
| + got <- string(b) |
| + }() |
| + waitUntil(t, "the request in flight", func() bool { return s.inflight() == 1 }) |
| + took, err := moveAndWait(t, s, 300*time.Millisecond) |
| + if !errors.Is(err, context.DeadlineExceeded) || took < 300*time.Millisecond { |
| + t.Fatalf("the wait ended after %v (%v): an ordinary request was cut short", took, err) |
| + } |
| + close(release) |
| + if b := <-got; b != "done" { |
| + t.Fatalf("the ordinary request answered %q", b) |
| + } |
| +} |
diff --git a/internal/edge/cookiescope.go b/internal/edge/cookiescope.go| index 2f42a1298..d4e899c1e 100644 |
| --- a/internal/edge/cookiescope.go |
| +++ b/internal/edge/cookiescope.go |
| @@ -77,7 +77,8 @@ func appsDomainFromEnv() string { |
| // (stripAssetResponseHeaders, stripAssetTrailers: the edge's own are set |
| // after this, never inherited from the app), the removal of any |
| // X-Carlos-Holder the app set, as a header or a trailer (stripAppHolder), |
| -// and the cookie scoping above, in that order. Only the marker depends on |
| +// the cookie scoping above, and the mark of a stream a move may end |
| +// (MarkMoveStream, movestreams.go), in that order. Only the marker depends on |
| // order: it is read before the scrub deletes it. |
| // |
| // X-Carlos-Holder names the box holding an HA host's lease (forwardha.go), |
| @@ -98,6 +99,8 @@ func (e *Edge) responseModifier(rt registry.Route) func(*http.Response) error { |
| stripAssetTrailers(resp) |
| stripAppHolder(resp) |
| e.scopeCookies(rt, resp) |
| + // Last, so an SSE body's move wrapper is the outermost reader. |
| + MarkMoveStream(resp) |
| return nil |
| } |
| } |
diff --git a/internal/edge/movestreams.go b/internal/edge/movestreams.go| new file mode 100644 |
| index 000000000..0ae88eace |
| --- /dev/null |
| +++ b/internal/edge/movestreams.go |
| @@ -0,0 +1,268 @@ |
| +package edge |
| + |
| +// Long-lived responses a planned move ends at its start (region HA spec |
| +// §25.4 step 3.1, §25.8, R3.5). A move waits up to its in-flight bound for |
| +// the host's requests here to finish before it releases the host; an SSE |
| +// stream or an upgraded connection never finishes on its own, so without |
| +// this every move with one open waited the whole bound. |
| +// |
| +// The activator gives each request it serves for an HA host a StreamEnd |
| +// (WithStreamEnd) and keeps it per host while the request runs. The |
| +// tenant proxies' response hook (responseModifier, MarkMoveStream) marks |
| +// it when the response turns out to be a stream: a 101 (an upgraded |
| +// connection, a WebSocket) or a text/event-stream. End is a no-op for any |
| +// other request, so an ordinary request keeps the move's bound. |
| +// |
| +// Ending a stream: |
| +// - SSE: the response body ends at its next event boundary, as io.EOF, |
| +// so the proxy finishes the response normally and the client sees a |
| +// clean end after a whole event. It reconnects (EventSource sends |
| +// Last-Event-ID) and is held by the move like any other request; |
| +// - an upgraded connection: the request's context is cancelled, which |
| +// makes the proxy close both sides, as the connection drain does at |
| +// its bound. The client reconnects and is held the same way. |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "sync" |
| +) |
| + |
| +type streamKind uint8 |
| + |
| +const ( |
| + streamNone streamKind = iota |
| + streamSSE |
| + streamUpgrade |
| +) |
| + |
| +// StreamEnd is one proxied request a move may end early. Memory only. |
| +type StreamEnd struct { |
| + cancel context.CancelFunc |
| + |
| + mu sync.Mutex |
| + kind streamKind |
| + ending bool |
| + // stop is closed once an SSE stream is to end at its next boundary. |
| + stop chan struct{} |
| +} |
| + |
| +type streamEndKey struct{} |
| + |
| +// WithStreamEnd gives r a StreamEnd: r's context becomes cancellable by |
| +// it, and the response hook finds it there. |
| +func WithStreamEnd(r *http.Request) (*http.Request, *StreamEnd) { |
| + ctx, cancel := context.WithCancel(r.Context()) |
| + s := &StreamEnd{cancel: cancel, stop: make(chan struct{})} |
| + return r.WithContext(context.WithValue(ctx, streamEndKey{}, s)), s |
| +} |
| + |
| +// End ends the request if its response is a stream, now or once it turns |
| +// out to be one: a request whose response has not started yet is ended |
| +// as soon as its head says it is a stream. A request that never becomes |
| +// one is not touched. Idempotent. |
| +func (s *StreamEnd) End() { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if s.ending { |
| + return |
| + } |
| + s.ending = true |
| + s.endLocked() |
| +} |
| + |
| +// Stream reports whether the response was marked as a stream. |
| +func (s *StreamEnd) Stream() bool { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.kind != streamNone |
| +} |
| + |
| +func (s *StreamEnd) endLocked() { |
| + switch s.kind { |
| + case streamSSE: |
| + close(s.stop) |
| + case streamUpgrade: |
| + s.cancel() |
| + } |
| +} |
| + |
| +func (s *StreamEnd) mark(k streamKind) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if s.kind != streamNone { |
| + return |
| + } |
| + s.kind = k |
| + if s.ending { |
| + s.endLocked() |
| + } |
| +} |
| + |
| +// MarkMoveStream is the tenant proxies' response hook for moves: it marks |
| +// the request's StreamEnd when resp is a stream, and makes an SSE body |
| +// end at an event boundary once the StreamEnd is ended. A response whose |
| +// request has no StreamEnd is left as it is. |
| +func MarkMoveStream(resp *http.Response) { |
| + if resp == nil || resp.Request == nil { |
| + return |
| + } |
| + s, _ := resp.Request.Context().Value(streamEndKey{}).(*StreamEnd) |
| + if s == nil { |
| + return |
| + } |
| + switch { |
| + case resp.StatusCode == http.StatusSwitchingProtocols: |
| + s.mark(streamUpgrade) |
| + case isEventStream(resp.Header.Get("Content-Type")) && resp.Body != nil && resp.Body != http.NoBody: |
| + resp.Body = newEventBoundaryBody(resp.Body, s.stop) |
| + s.mark(streamSSE) |
| + } |
| +} |
| + |
| +func isEventStream(ct string) bool { |
| + mt, _, err := mime.ParseMediaType(ct) |
| + return err == nil && mt == "text/event-stream" |
| +} |
| + |
| +// eventBoundaryBody passes an SSE body through until stop is closed, then |
| +// ends it with io.EOF at the first event boundary (a blank line) at or |
| +// after what it has already passed on. Bytes past that boundary are |
| +// dropped: the client gets them again after its reconnect. If stop closes |
| +// while what has been passed on ends at a boundary, the upstream body is |
| +// closed so a read blocked on it returns. |
| +type eventBoundaryBody struct { |
| + rc io.ReadCloser |
| + stop <-chan struct{} |
| + done chan struct{} |
| + |
| + mu sync.Mutex |
| + // tail is the last bytes passed on (at most 3), for a boundary that |
| + // spans two reads; at is whether what was passed on ends at a |
| + // boundary (true before the first byte). |
| + tail []byte |
| + at bool |
| + ended bool |
| + closed bool |
| +} |
| + |
| +func newEventBoundaryBody(rc io.ReadCloser, stop <-chan struct{}) *eventBoundaryBody { |
| + b := &eventBoundaryBody{rc: rc, stop: stop, done: make(chan struct{}), at: true} |
| + go b.watch() |
| + return b |
| +} |
| + |
| +// watch closes the upstream body when stop closes at a boundary, so a |
| +// blocked read returns and Read can end the stream. |
| +func (b *eventBoundaryBody) watch() { |
| + select { |
| + case <-b.stop: |
| + case <-b.done: |
| + return |
| + } |
| + b.mu.Lock() |
| + at := b.at |
| + b.mu.Unlock() |
| + if at { |
| + _ = b.rc.Close() |
| + } |
| +} |
| + |
| +func (b *eventBoundaryBody) stopped() bool { |
| + select { |
| + case <-b.stop: |
| + return true |
| + default: |
| + return false |
| + } |
| +} |
| + |
| +func (b *eventBoundaryBody) Read(p []byte) (int, error) { |
| + b.mu.Lock() |
| + if b.ended { |
| + b.mu.Unlock() |
| + return 0, io.EOF |
| + } |
| + if b.at && b.stopped() { |
| + b.ended = true |
| + b.mu.Unlock() |
| + return 0, io.EOF |
| + } |
| + b.mu.Unlock() |
| + n, err := b.rc.Read(p) |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + if b.stopped() { |
| + if k := boundaryIn(b.tail, p[:n]); k >= 0 { |
| + b.ended = true |
| + if k == 0 { |
| + return 0, io.EOF |
| + } |
| + return k, nil |
| + } |
| + } |
| + b.passed(p[:n]) |
| + return n, err |
| +} |
| + |
| +// passed records p as passed on. |
| +func (b *eventBoundaryBody) passed(p []byte) { |
| + if len(p) == 0 { |
| + return |
| + } |
| + t := append(b.tail, p...) |
| + if len(t) > 3 { |
| + t = t[len(t)-3:] |
| + } |
| + b.tail = append(b.tail[:0], t...) |
| + b.at = endsAtBoundary(b.tail) |
| +} |
| + |
| +func (b *eventBoundaryBody) Close() error { |
| + b.mu.Lock() |
| + if b.closed { |
| + b.mu.Unlock() |
| + return nil |
| + } |
| + b.closed = true |
| + close(b.done) |
| + b.mu.Unlock() |
| + return b.rc.Close() |
| +} |
| + |
| +// boundaryIn is the largest k (0 <= k <= len(p)) such that tail followed |
| +// by p[:k] ends at an event boundary, or -1 when there is none. |
| +func boundaryIn(tail, p []byte) int { |
| + for k := len(p); k >= 0; k-- { |
| + var last []byte |
| + if k >= 4 { |
| + last = p[k-4 : k] |
| + } else { |
| + last = append(append([]byte(nil), tail...), p[:k]...) |
| + } |
| + if endsAtBoundary(last) { |
| + return k |
| + } |
| + } |
| + return -1 |
| +} |
| + |
| +// endsAtBoundary reports whether b ends with a blank line: a line end |
| +// ("\r\n", "\n" or "\r") right after another. An empty b is the start of |
| +// the stream, a boundary too. |
| +func endsAtBoundary(b []byte) bool { |
| + n := len(b) |
| + switch { |
| + case n == 0: |
| + return true |
| + case n >= 2 && b[n-2] == '\r' && b[n-1] == '\n': |
| + n -= 2 |
| + case b[n-1] == '\n' || b[n-1] == '\r': |
| + n-- |
| + default: |
| + return false |
| + } |
| + return n > 0 && (b[n-1] == '\n' || b[n-1] == '\r') |
| +} |
diff --git a/internal/edge/movestreams_test.go b/internal/edge/movestreams_test.go| new file mode 100644 |
| index 000000000..da172d5dc |
| --- /dev/null |
| +++ b/internal/edge/movestreams_test.go |
| @@ -0,0 +1,139 @@ |
| +package edge |
| + |
| +import ( |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func TestEndsAtBoundary(t *testing.T) { |
| + for in, want := range map[string]bool{ |
| + "": true, |
| + "\n\n": true, |
| + "a\n\n": true, |
| + "a\r\n\r\n": true, |
| + "\n\r\n": true, |
| + "a\r\r": true, |
| + "a\n": false, |
| + "a\r\n": false, |
| + "a\r": false, |
| + "data: x": false, |
| + "a\r\n\r": true, |
| + "data: x\n\nd": false, |
| + } { |
| + if got := endsAtBoundary([]byte(in)); got != want { |
| + t.Errorf("endsAtBoundary(%q) = %v, want %v", in, got, want) |
| + } |
| + } |
| + for _, c := range []struct { |
| + tail, p string |
| + want int |
| + }{ |
| + {"", "data: a\n\ndata: b", 9}, |
| + {"a\n", "\ndata: b", 1}, |
| + {"a\r\n", "\r\nx", 2}, |
| + {"\n\n", "data", 0}, |
| + {"x", "data: b\n", -1}, |
| + {"", "a\n\ndata: b\n\nc", 12}, |
| + } { |
| + if got := boundaryIn([]byte(c.tail), []byte(c.p)); got != c.want { |
| + t.Errorf("boundaryIn(%q, %q) = %d, want %d", c.tail, c.p, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +// A stream ended mid-event passes on the rest of that event, then ends at |
| +// its boundary; bytes after the boundary are dropped. |
| +func TestEventBoundaryBodyEndsAfterTheEvent(t *testing.T) { |
| + pr, pw := io.Pipe() |
| + stop := make(chan struct{}) |
| + b := newEventBoundaryBody(pr, stop) |
| + defer b.Close() |
| + got := make(chan string, 1) |
| + go func() { all, _ := io.ReadAll(b); got <- string(all) }() |
| + pw.Write([]byte("id: 1\ndata: one\n\n")) |
| + pw.Write([]byte("id: 2\n")) |
| + time.Sleep(20 * time.Millisecond) |
| + close(stop) // mid-event: it is not cut here |
| + pw.Write([]byte("data: two\n\nid: 3\n")) |
| + select { |
| + case s := <-got: |
| + if s != "id: 1\ndata: one\n\nid: 2\ndata: two\n\n" { |
| + t.Fatalf("passed on %q", s) |
| + } |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("the stream did not end at the boundary") |
| + } |
| +} |
| + |
| +// Ended between events, a read blocked on the upstream returns: the body |
| +// ends at once. |
| +func TestEventBoundaryBodyEndsABlockedRead(t *testing.T) { |
| + pr, pw := io.Pipe() |
| + defer pw.Close() |
| + stop := make(chan struct{}) |
| + b := newEventBoundaryBody(pr, stop) |
| + defer b.Close() |
| + got := make(chan error, 1) |
| + go func() { |
| + buf := make([]byte, 64) |
| + for { |
| + if _, err := b.Read(buf); err != nil { |
| + got <- err |
| + return |
| + } |
| + } |
| + }() |
| + pw.Write([]byte("data: one\n\n")) |
| + time.Sleep(20 * time.Millisecond) |
| + close(stop) |
| + select { |
| + case err := <-got: |
| + if err != io.EOF { |
| + t.Fatalf("ended with %v, want io.EOF", err) |
| + } |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("a read blocked between events was not ended") |
| + } |
| +} |
| + |
| +// The tenant proxies' response hook marks a stream and nothing else. |
| +func TestResponseModifierMarksMoveStreams(t *testing.T) { |
| + e := &Edge{} |
| + mod := e.responseModifier(registry.Route{Host: "shop.example.com"}) |
| + for _, c := range []struct { |
| + status int |
| + ct string |
| + want bool |
| + }{ |
| + {http.StatusOK, "text/event-stream; charset=utf-8", true}, |
| + {http.StatusSwitchingProtocols, "", true}, |
| + {http.StatusOK, "text/html", false}, |
| + {http.StatusOK, "application/json", false}, |
| + } { |
| + r, s := WithStreamEnd(httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil)) |
| + resp := &http.Response{StatusCode: c.status, Header: http.Header{}, Request: r, Body: io.NopCloser(strings.NewReader("data: x\n\n"))} |
| + if c.ct != "" { |
| + resp.Header.Set("Content-Type", c.ct) |
| + } |
| + if err := mod(resp); err != nil { |
| + t.Fatal(err) |
| + } |
| + if s.Stream() != c.want { |
| + t.Errorf("%d %q: stream %v, want %v", c.status, c.ct, s.Stream(), c.want) |
| + } |
| + // End on a request that is not a stream touches nothing. |
| + s.End() |
| + if !c.want && r.Context().Err() != nil { |
| + t.Errorf("%d %q: an ordinary request was cancelled", c.status, c.ct) |
| + } |
| + if c.status == http.StatusSwitchingProtocols && r.Context().Err() == nil { |
| + t.Error("an upgraded connection was not ended") |
| + } |
| + } |
| +} |
diff --git a/internal/host/hadrain.go b/internal/host/hadrain.go| index fb4f0e006..156904860 100644 |
| --- a/internal/host/hadrain.go |
| +++ b/internal/host/hadrain.go |
| @@ -79,6 +79,7 @@ type drainActivator interface { |
| DrainHosts() []activator.DrainHost |
| DrainHeld() []string |
| BeginMove(host string) error |
| + EndMoveStreams(host string) int |
| WaitMoveTickets(ctx context.Context, host string) error |
| WaitDrainInflight(ctx context.Context, host string) error |
| SetMoveReleasing(host string) error |
| @@ -716,8 +717,16 @@ func (d *drainDriver) moveOne(ctx context.Context, txn string, h activator.Drain |
| } |
| return leave("begin", err.Error(), activator.DrainRelease{}) |
| } |
| - // 3.2: tickets and the in-flight drain share today's 10 s bound. At the |
| - // bound the stop ends what is left, as a shutdown stop does. |
| + // 3.1: the host's long-lived responses here end now, at the move's |
| + // start, not at the take: SSE streams at an event boundary, upgraded |
| + // connections, and edge-held streams (R3.5). None ends on its own, so |
| + // each would hold the wait below to its bound. Their clients reconnect |
| + // and are held like any other request until the take (§25.8). |
| + d.act.EndMoveStreams(host) |
| + d.edge.CloseHeldHost(host) |
| + // 3.2: tickets and the in-flight drain share today's 10 s bound for |
| + // every other request. At the bound the stop ends what is left, as a |
| + // shutdown stop does. |
| ictx, icancel := context.WithTimeout(ctx, drainInflightBound) |
| _ = d.act.WaitMoveTickets(ictx, host) |
| _ = d.act.WaitDrainInflight(ictx, host) |
| @@ -745,8 +754,9 @@ func (d *drainDriver) moveOne(ctx context.Context, txn string, h activator.Drain |
| if err := d.act.SetMoveTaken(host, holder, gen); err != nil { |
| return leave("take", err.Error(), rel) |
| } |
| - // Its edge-held streams here reconnect to the holder now, at an event |
| - // boundary, not at the end of the drain (R3.5). |
| + // Its edge-held streams were closed at the move's start (3.1). Any |
| + // opened here since then reconnect to the holder now, at an event |
| + // boundary, not at the end of the drain (R3.5). Idempotent. |
| d.edge.CloseHeldHost(host) |
| d.note(func() { |
| rep.Moved = append(rep.Moved, drainMoved{Host: host, Holder: holder, Gen: gen, Confirmed: how}) |
diff --git a/internal/host/hadrain_test.go b/internal/host/hadrain_test.go| index 8b5ca5ebb..f1f19bc7e 100644 |
| --- a/internal/host/hadrain_test.go |
| +++ b/internal/host/hadrain_test.go |
| @@ -65,6 +65,11 @@ type fakeDrainAct struct { |
| logOn bool |
| logEnds int |
| notMoving map[string]bool |
| + // streams are hosts with a stream open here: the in-flight wait |
| + // holds to its bound until the move ends it (EndMoveStreams). |
| + streams map[string]bool |
| + // streamEnded is closed when EndMoveStreams ends a stream. |
| + streamEnded chan struct{} |
| onBeginMove func(string) |
| } |
| @@ -122,8 +127,34 @@ func (f *fakeDrainAct) BeginMove(host string) error { |
| } |
| return nil |
| } |
| -func (f *fakeDrainAct) WaitMoveTickets(context.Context, string) error { return nil } |
| -func (f *fakeDrainAct) WaitDrainInflight(context.Context, string) error { return nil } |
| +func (f *fakeDrainAct) WaitMoveTickets(context.Context, string) error { return nil } |
| +func (f *fakeDrainAct) EndMoveStreams(host string) int { |
| + f.rec.add("end-streams " + host) |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if !f.streams[host] { |
| + return 0 |
| + } |
| + f.streams[host] = false |
| + close(f.streamEnded) |
| + f.streamEnded = make(chan struct{}) |
| + return 1 |
| +} |
| +func (f *fakeDrainAct) WaitDrainInflight(ctx context.Context, host string) error { |
| + for { |
| + f.mu.Lock() |
| + open, ended := f.streams[host], f.streamEnded |
| + f.mu.Unlock() |
| + if !open { |
| + return nil |
| + } |
| + select { |
| + case <-ended: |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| + } |
| +} |
| func (f *fakeDrainAct) SetMoveReleasing(host string) error { |
| f.rec.add("releasing " + host) |
| return nil |
| @@ -504,7 +535,7 @@ func TestDrainDriverWholeSequence(t *testing.T) { |
| t.Fatalf("report counts %+v", rep) |
| } |
| ev := act.rec.events() |
| - order := []string{"draining", "ask draining b", "begin busy.example.com", "stop busy.example.com", "take busy.example.com b", "taken busy.example.com b", "close-held busy.example.com", "drained", "ask drained b", "end-moves", "connections"} |
| + order := []string{"draining", "ask draining b", "begin busy.example.com", "end-streams busy.example.com", "close-held busy.example.com", "releasing busy.example.com", "stop busy.example.com", "take busy.example.com b", "taken busy.example.com b", "drained", "ask drained b", "end-moves", "connections"} |
| last := -1 |
| for _, step := range order { |
| i := indexOf(ev, step) |
| @@ -534,6 +565,36 @@ func TestDrainDriverWholeSequence(t *testing.T) { |
| } |
| } |
| +// A host with a stream open at the move's start (an SSE stream or an |
| +// upgraded connection, which never ends on its own) is not held to the |
| +// in-flight bound: the move ends its streams and its edge-held streams |
| +// right after BeginMove, before the wait, and reaches the release at once |
| +// (§25.4 step 3.1, §25.8). The bound itself is unchanged. |
| +func TestMoveEndsStreamsBeforeTheInflightWait(t *testing.T) { |
| + if drainInflightBound != 10*time.Second { |
| + t.Fatalf("drainInflightBound = %v, want today's 10 s", drainInflightBound) |
| + } |
| + act, ed, marks := healthyDrain() |
| + act.streams = map[string]bool{"busy.example.com": true, "quiet.example.com": true} |
| + act.streamEnded = make(chan struct{}) |
| + d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| + start := time.Now() |
| + rep := runDrain(t, d, "t1") |
| + if took := time.Since(start); took > time.Second { |
| + t.Fatalf("the drain took %v: open streams held the moves to the in-flight bound", took) |
| + } |
| + if rep.Result != "ok" || len(rep.Moved) != 2 { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + ev := act.rec.events() |
| + for _, host := range []string{"busy.example.com", "quiet.example.com"} { |
| + begin, streams, held, releasing := indexOf(ev, "begin "+host), indexOf(ev, "end-streams "+host), indexOf(ev, "close-held "+host), indexOf(ev, "releasing "+host) |
| + if begin < 0 || streams < begin || held < begin || releasing < streams || releasing < held { |
| + t.Fatalf("%s: streams not ended between BeginMove and the release: %v", host, ev) |
| + } |
| + } |
| +} |
| + |
| // A wake still restoring, or an acquire paused before its PUT, when the |
| // drain starts: nothing moves until the box is quiet. |
| func TestDrainWaitsForQuiescence(t *testing.T) { |