edge, activator: held-stream whole-branch review fixes (#432)
Human
Prompt
fix the four P2s and the Activator-comment P3 from the whole-branch review of edge-held streams, plus CI's StopAdmitRace drain failure.
From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
- A reload closing a registered stream before its first response now commits the empty event stream instead of an empty plain 200. - Each leg request carries its own outcome; the first leg's cause and answered flag come back with its head and are copied onto the browser's request by the task. - Tests: generous Commit outside commit-timing tests, the blocked-write deadline measured at the writer, admission waits tested by a startup gate, and a tunnel witness that a marked cacheable answer is never stored at the hub. - edge.Activator comments describe immediate leg admissibility and the wake notification hook. - StopAdmitRace bounds the child's /live handler drain, and attributes a long Shutdown to requestless connections the child reports.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+558
−58
internal/activator/activator_test.go+42 −3internal/activator/heldlegs_test.go+52 −15internal/activator/heldstream_e2e_test.go+94 −10internal/edge/edge.go+10 −4internal/edge/heldstream.go+65 −10internal/edge/heldstream_sim_test.go+1 −0internal/edge/heldstream_test.go+198 −16internal/edge/tunnel_e2e_test.go+96 −0
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go| index 1d7af31a5..3a3c2fe55 100644 |
| --- a/internal/activator/activator_test.go |
| +++ b/internal/activator/activator_test.go |
| @@ -6265,8 +6265,13 @@ func fakeAppMain() { |
| // fakeAppRecord is one line of the SSE-mode child's log |
| // (ACTIVATOR_FAKE_APP_LOG): "start" when it binds, "req" per request, |
| -// "sigterm" when SIGTERM arrives and "shutdown" when srv.Shutdown returns. |
| -// At is wall-clock nanoseconds; Ms is the shutdown's duration. |
| +// "sigterm" when SIGTERM arrives, "drain" once srv.Shutdown has closed its |
| +// listener and "shutdown" when srv.Shutdown returns. At is wall-clock |
| +// nanoseconds; Ms is the shutdown's duration. On "drain", Live is the /live |
| +// handlers still open and New the connections that have not sent a request |
| +// (net/http's Shutdown waits up to about 6 s for each of those before it |
| +// treats it as idle). On "shutdown", LiveMs is how long after SIGTERM the |
| +// last /live handler returned (0 when none was open). |
| type fakeAppRecord struct { |
| Pid int `json:"pid"` |
| Kind string `json:"kind"` |
| @@ -6276,6 +6281,9 @@ type fakeAppRecord struct { |
| Header map[string][]string `json:"header,omitempty"` |
| Ms int64 `json:"ms,omitempty"` |
| Err string `json:"err,omitempty"` |
| + Live int64 `json:"live,omitempty"` |
| + New int `json:"new,omitempty"` |
| + LiveMs int64 `json:"live_ms,omitempty"` |
| } |
| // fakeAppSSEMain is fakeAppMain's SSE mode (ACTIVATOR_FAKE_APP_SSE=1), the |
| @@ -6322,12 +6330,19 @@ func fakeAppSSEMain(ln net.Listener) { |
| return out |
| } |
| var cookieSent atomic.Bool |
| + var liveOpen atomic.Int64 |
| + var lastLiveEnd atomic.Int64 // UnixNano |
| h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| logRec(fakeAppRecord{Kind: "req", Path: r.URL.Path, Query: r.URL.RawQuery, Header: r.Header.Clone()}) |
| if r.URL.Path != "/live" { |
| w.WriteHeader(http.StatusOK) |
| return |
| } |
| + liveOpen.Add(1) |
| + defer func() { |
| + lastLiveEnd.Store(time.Now().UnixNano()) |
| + liveOpen.Add(-1) |
| + }() |
| q := r.URL.Query() |
| switch { |
| case q.Get("expire") == "1": |
| @@ -6373,7 +6388,28 @@ func fakeAppSSEMain(ln net.Listener) { |
| } |
| } |
| }) |
| - srv := &http.Server{Handler: h} |
| + var connMu sync.Mutex |
| + conns := map[net.Conn]http.ConnState{} |
| + srv := &http.Server{Handler: h, ConnState: func(c net.Conn, st http.ConnState) { |
| + connMu.Lock() |
| + defer connMu.Unlock() |
| + if st == http.StateClosed || st == http.StateHijacked { |
| + delete(conns, c) |
| + } else { |
| + conns[c] = st |
| + } |
| + }} |
| + srv.RegisterOnShutdown(func() { |
| + connMu.Lock() |
| + n := 0 |
| + for _, st := range conns { |
| + if st == http.StateNew { |
| + n++ |
| + } |
| + } |
| + connMu.Unlock() |
| + logRec(fakeAppRecord{Kind: "drain", Live: liveOpen.Load(), New: n}) |
| + }) |
| sig := make(chan os.Signal, 1) |
| signal.Notify(sig, syscall.SIGTERM) |
| logRec(fakeAppRecord{Kind: "start"}) |
| @@ -6385,6 +6421,9 @@ func fakeAppSSEMain(ln net.Listener) { |
| err := srv.Shutdown(ctx) |
| cancel() |
| rec := fakeAppRecord{Kind: "shutdown", Ms: time.Since(began).Milliseconds()} |
| + if end := lastLiveEnd.Load(); end > began.UnixNano() { |
| + rec.LiveMs = time.Duration(end - began.UnixNano()).Milliseconds() |
| + } |
| if err != nil { |
| rec.Err = err.Error() |
| } |
diff --git a/internal/activator/heldlegs_test.go b/internal/activator/heldlegs_test.go| index 6ed23d2cd..43b0f27b4 100644 |
| --- a/internal/activator/heldlegs_test.go |
| +++ b/internal/activator/heldlegs_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| @@ -147,7 +148,10 @@ func TestHeldAdmissibleMatchesAdmit(t *testing.T) { |
| awake bool // wake the host first |
| startup <-chan struct{} // a.Startup, set before any wake |
| after func(t *testing.T, a *Service, b *fakeBackend) // arrange the state |
| - want bool |
| + // waits: the host is woken, then a.Startup is replaced by a gate |
| + // only the test closes, so AdmitHeldLeg can admit only by waiting. |
| + waits bool |
| + want bool |
| }{ |
| {name: "asleep"}, |
| {name: "awake", awake: true, want: true}, |
| @@ -198,10 +202,8 @@ func TestHeldAdmissibleMatchesAdmit(t *testing.T) { |
| }}, |
| {name: "Startup nil", awake: true, want: true}, |
| {name: "Startup closed", awake: true, startup: closed, want: true}, |
| - {name: "Startup open", awake: true, after: func(t *testing.T, a *Service, _ *fakeBackend) { |
| - // Woken before the gate was set; the gate is not yet closed. |
| - a.Startup = make(chan struct{}) |
| - }}, |
| + // Woken before the gate was set; the gate is not yet closed. |
| + {name: "Startup open", awake: true, waits: true}, |
| } |
| for _, c := range cases { |
| t.Run(c.name, func(t *testing.T) { |
| @@ -217,23 +219,58 @@ func TestHeldAdmissibleMatchesAdmit(t *testing.T) { |
| if c.after != nil { |
| c.after(t, a, b) |
| } |
| + var gate chan struct{} |
| + if c.waits { |
| + gate = make(chan struct{}) |
| + a.Startup = gate |
| + } |
| admissible := a.HeldAdmissible(host) |
| - ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) |
| - defer cancel() |
| - start := time.Now() |
| - leg, err := a.AdmitHeldLeg(ctx, rt) |
| - took := time.Since(start) |
| - if leg != nil { |
| - defer leg.Done() |
| + type result struct { |
| + leg edge.HeldLeg |
| + err error |
| + } |
| + resC := make(chan result, 1) |
| + go func() { |
| + leg, err := a.AdmitHeldLeg(t.Context(), rt) |
| + resC <- result{leg, err} |
| + }() |
| + // Admitted without waiting: every gate this case could wait on |
| + // stays shut until the call has returned, so a call that |
| + // returns a leg here did not wait for one. The bound only ends |
| + // a call that waits for ever; it classifies nothing. |
| + var res result |
| + if c.waits { |
| + // Never flaky: a call can only be early, never late, here. |
| + select { |
| + case r := <-resC: |
| + t.Fatalf("AdmitHeldLeg returned %v, %v with the startup gate shut", r.leg, r.err) |
| + default: |
| + } |
| + close(gate) |
| + res = <-resC |
| + // It returned only once the test opened the gate, with a |
| + // leg: it waited, so it was not admitted without waiting. |
| + if res.err != nil || res.leg == nil { |
| + t.Errorf("AdmitHeldLeg after the startup gate opened = %v, %v; want a leg", res.leg, res.err) |
| + } |
| + } else { |
| + select { |
| + case res = <-resC: |
| + case <-time.After(30 * time.Second): |
| + t.Fatalf("AdmitHeldLeg still waiting after 30s with every gate shut") |
| + } |
| + } |
| + if res.leg != nil { |
| + defer res.leg.Done() |
| } |
| - admitted := err == nil && took < 50*time.Millisecond |
| + admitted := !c.waits && res.err == nil |
| if admissible != c.want { |
| t.Errorf("HeldAdmissible = %v, want %v", admissible, c.want) |
| } |
| if admissible != admitted { |
| - t.Errorf("HeldAdmissible = %v but AdmitHeldLeg = %v after %v", admissible, err, took) |
| + t.Errorf("HeldAdmissible = %v but AdmitHeldLeg = %v (waited for a gate: %v)", admissible, res.err, c.waits) |
| } |
| - if err != nil && leg != nil { |
| + if res.err != nil && res.leg != nil { |
| t.Errorf("a refused admission returned a leg") |
| } |
| }) |
diff --git a/internal/activator/heldstream_e2e_test.go b/internal/activator/heldstream_e2e_test.go| index 9575d723f..5613f12a5 100644 |
| --- a/internal/activator/heldstream_e2e_test.go |
| +++ b/internal/activator/heldstream_e2e_test.go |
| @@ -801,18 +801,61 @@ func TestHeldE2EOverlapSwap(t *testing.T) { |
| // Case 10: the stop race. A stream reopens its leg in a tight loop |
| // (ReopenSpacing 1 ms; the app ends each leg at once) while the idle sweep |
| -// stops the instance, 50 times. After each stop the child's log shows no |
| -// /live request that started after its SIGTERM, and its drain stayed under |
| -// 2000 ms: every leg admitted before the stop was cancelled by it, and none |
| -// was admitted after. |
| +// stops the instance, 50 times. Every leg on each child was registered, |
| +// under a.mu, on the awake and current entry before the child's SIGTERM, |
| +// and the child served no more /live requests than legs were registered on |
| +// it; every /live handler open at the stop ended within 2000 ms of it: |
| +// every leg admitted before the stop was cancelled by it, and none was |
| +// admitted after. The child's own handler start is not the admission: a |
| +// request a leg wrote before the stop cancelled it can still be read just |
| +// after SIGTERM on a loaded box. A drain of 2000 ms or more passes only |
| +// when the child reports a connection that never sent a request, which |
| +// net/http's Shutdown waits on for about 5 s. |
| func TestHeldE2EStopAdmitRace(t *testing.T) { |
| cfg := e2eHeldConfig() |
| cfg.ReopenSpacing = time.Millisecond |
| cfg.ShortLeg = 0 |
| h := newHeldE2E(t, heldE2EOpts{idle: 150 * time.Millisecond, cfg: cfg}) |
| + // Every registration, seen in the critical section that makes it |
| + // (heldLegRegistered runs under a.mu): the child it is on, when, and |
| + // whether its entry was still the awake, current one. beginStopLocked |
| + // moves the entry to stopping under the same lock, so a leg admitted |
| + // after the stop began shows here as not awake or not current. |
| + type legReg struct { |
| + pid int |
| + at int64 |
| + awake bool |
| + current bool |
| + } |
| + var regMu sync.Mutex |
| + var regs []legReg |
| + hook := func(sa *Service, e *actEntry, _ *heldLeg) { |
| + if sa != h.a { |
| + return |
| + } |
| + r := legReg{at: time.Now().UnixNano(), awake: e.state == actAwake, current: sa.entries[e.host] == e} |
| + if p, ok := e.proc.(*childProc); ok && p.cmd != nil && p.cmd.Process != nil { |
| + r.pid = p.cmd.Process.Pid |
| + } |
| + regMu.Lock() |
| + regs = append(regs, r) |
| + regMu.Unlock() |
| + } |
| + heldLegRegistered.Store(&hook) |
| + t.Cleanup(func() { heldLegRegistered.Store(nil) }) |
| + regsOn := func(pid int) (out []legReg) { |
| + regMu.Lock() |
| + defer regMu.Unlock() |
| + for _, r := range regs { |
| + if r.pid == pid { |
| + out = append(out, r) |
| + } |
| + } |
| + return out |
| + } |
| b := newBrowser(t, h.front.URL, "/live?end=1&carlos_hold=1") |
| c := b.connect() |
| - raced := 0 |
| + raced, lateReqs := 0, 0 |
| for i := 0; i < 50; i++ { |
| pid := h.wake() |
| waitE2E(t, 10*time.Second, fmt.Sprintf("iteration %d's stop", i), h.asleep) |
| @@ -820,15 +863,55 @@ func TestHeldE2EStopAdmitRace(t *testing.T) { |
| if !ok { |
| t.Fatalf("iteration %d: child %d stopped with no SIGTERM logged", i, pid) |
| } |
| - rec := h.shutdownOf(pid, 5*time.Second) |
| - if rec.Ms >= 2000 || rec.Err != "" { |
| - t.Fatalf("iteration %d: drain %d ms (%q), want under 2000", i, rec.Ms, rec.Err) |
| - } |
| + rec := h.shutdownOf(pid, 30*time.Second) |
| legs := h.liveReqs(pid) |
| + // The stop race itself is judged where admission happens: every |
| + // leg on this child was registered on the awake, current entry, |
| + // before its SIGTERM. |
| + on := regsOn(pid) |
| + for _, r := range on { |
| + if !r.awake || !r.current { |
| + t.Fatalf("iteration %d: a leg was registered on child %d's entry after its stop began (awake %v, current %v)", i, pid, r.awake, r.current) |
| + } |
| + if r.at > term.At { |
| + t.Fatalf("iteration %d: a leg was registered on child %d %s after its SIGTERM", i, pid, time.Duration(r.at-term.At)) |
| + } |
| + } |
| + // The child may still read a request a leg wrote before the stop |
| + // cancelled it after SIGTERM arrives: its handler start is not the |
| + // leg's admission. Each such request is one of the legs above, so |
| + // there are never more /live requests than registrations. |
| + late := 0 |
| for _, l := range legs { |
| if l.At > term.At { |
| - t.Fatalf("iteration %d: a /live leg started %s after child %d's SIGTERM", i, time.Duration(l.At-term.At), pid) |
| + late++ |
| + } |
| + } |
| + if len(legs) > len(on) { |
| + t.Fatalf("iteration %d: child %d served %d /live requests (%d after its SIGTERM) for %d registered legs", i, pid, len(legs), late, len(on)) |
| + } |
| + if late > 0 { |
| + lateReqs += late |
| + t.Logf("iteration %d: %d /live request(s) reached child %d after its SIGTERM, all from legs registered before it", i, late, pid) |
| + } |
| + // The drain is bounded by what the child says it waited on, not by |
| + // wall time alone. Every /live handler open at the stop must end |
| + // promptly: its leg was cancelled before SIGTERM. Shutdown may |
| + // still wait on a connection that never sent a request (an edge |
| + // dial that completed after its leg was cancelled; net/http waits |
| + // about 5 s before it treats one as idle), which is not a leg. |
| + drain, _ := h.find(pid, "drain") |
| + if rec.Err != "" || rec.LiveMs >= 2000 { |
| + t.Fatalf("iteration %d: drain %d ms (%q), /live handlers drained after %d ms (%d open when it began), want under 2000", |
| + i, rec.Ms, rec.Err, rec.LiveMs, drain.Live) |
| + } |
| + if rec.Ms >= 2000 { |
| + if drain.New == 0 { |
| + t.Fatalf("iteration %d: drain %d ms with /live handlers done after %d ms and no requestless connection: nothing the child reports explains it", |
| + i, rec.Ms, rec.LiveMs) |
| } |
| + t.Logf("iteration %d: drain %d ms on %d requestless connection(s); /live handlers done after %d ms (%d open when it began)", |
| + i, rec.Ms, drain.New, rec.LiveMs, drain.Live) |
| } |
| if len(legs) > 0 { |
| raced++ |
| @@ -837,6 +920,7 @@ func TestHeldE2EStopAdmitRace(t *testing.T) { |
| t.Fatalf("iteration %d: the browser's stream ended", i) |
| } |
| } |
| + t.Logf("%d of 50 children served /live legs; %d /live request(s) were read after a SIGTERM", raced, lateReqs) |
| if raced < 25 { |
| t.Fatalf("legs reached only %d of 50 processes: the reopen loop did not run against the stops", raced) |
| } |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 07000619e..5dbc88e01 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -94,12 +94,18 @@ type Activator interface { |
| ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool |
| RetireExcept(keep map[string]bool) |
| // AdmitHeldLeg admits one upstream leg of an edge-held event stream, or |
| - // errors when the instance is not awake on a current generation. |
| + // errors when the instance is not awake on a current generation. It |
| + // never starts a wake and the leg is never activity. |
| AdmitHeldLeg(ctx context.Context, rt registry.Route) (HeldLeg, error) |
| - // HeldAdmissible reports whether host is hibernate-managed here, so a |
| - // stream request may be held. |
| + // HeldAdmissible reports whether AdmitHeldLeg would admit a leg for host |
| + // now, without waiting: the instance is awake and may take one. A held |
| + // stream reopens its leg only then; it is not a test of whether the |
| + // host is hibernate-managed. |
| HeldAdmissible(host string) bool |
| - // SetHeldWakeHook installs the callback that wakes host for a held stream. |
| + // SetHeldWakeHook installs the callback the activator calls when host |
| + // may have become admissible: a wake that something else started has |
| + // completed, a recovery hold released, a fence lifted. It only notifies |
| + // the held streams (Edge.HeldWake); it never wakes the host. |
| SetHeldWakeHook(f func(host string)) |
| } |
diff --git a/internal/edge/heldstream.go b/internal/edge/heldstream.go| index cd619bbf5..68c14487e 100644 |
| --- a/internal/edge/heldstream.go |
| +++ b/internal/edge/heldstream.go |
| @@ -93,6 +93,10 @@ type heldSet struct { |
| // beforeRegister is a test seam, nil in production: called by |
| // serveHeld just before it registers a stream. |
| beforeRegister func() |
| + // afterMapCheck is a test seam, nil in production: called by serveHeld |
| + // once the published map says this edge holds the host, before the |
| + // stream's task starts. |
| + afterMapCheck func() |
| } |
| // heldStream is one held stream's entry in the set: the signals other |
| @@ -329,6 +333,9 @@ func (e *Edge) serveHeld(w http.ResponseWriter, r *http.Request, rt registry.Rou |
| writeHeldClosed(w, s.cfg.WriteDeadline) |
| return |
| } |
| + if s.afterMapCheck != nil { |
| + s.afterMapCheck() |
| + } |
| t := &heldTask{ |
| e: e, cfg: s.cfg, st: st, host: rt.Host, rt: rt, proxy: proxy, |
| w: w, rc: http.NewResponseController(w), r: r, |
| @@ -394,18 +401,30 @@ const ( |
| heldLegEnd |
| ) |
| -// heldLegMsg is what a leg's reader hands the task. |
| +// heldLegMsg is what a leg's reader hands the task. attr is set on the |
| +// head. |
| type heldLegMsg struct { |
| run *heldLegRun |
| kind heldLegMsgKind |
| status int |
| header http.Header |
| sse bool |
| + attr heldLegAttr |
| block sseBlock |
| chunk []byte |
| err error |
| } |
| +// heldLegAttr is what a leg's own outcome said when its head was written: |
| +// whether the activator answered it and why the edge could not get an |
| +// answer. The task copies it onto the browser's request when that head |
| +// becomes the browser's answer, so the observer files it as it would an |
| +// ordinary request's. |
| +type heldLegAttr struct { |
| + answered bool |
| + cause string |
| +} |
| + |
| var ( |
| errHeldLegClosed = errors.New("edge: held leg closed") |
| errHeldLegNoResponse = errors.New("edge: held leg ended without a response") |
| @@ -449,6 +468,13 @@ func (t *heldTask) run() heldCloseReason { |
| case <-ctx.Done(): |
| return heldCloseClientGone |
| case <-t.st.closeC: |
| + // A reload closed the stream. A browser with no response yet |
| + // gets the empty event stream, as before registration |
| + // (writeHeldClosed): EventSource reconnects from that, where an |
| + // empty plain 200 would stop it for good (§3.4). |
| + if !t.committed { |
| + _ = t.commit() |
| + } |
| return heldCloseUnmanaged |
| case <-maxT.C: |
| // The task only ever writes whole blocks, so this is a block |
| @@ -573,9 +599,9 @@ func (t *heldTask) openLeg(leg HeldLeg, exempt bool) { |
| } |
| run := &heldLegRun{leg: leg, cancel: cancel, quit: make(chan struct{}), start: time.Now(), exempt: exempt} |
| t.leg, t.lastLegStart = run, run.start |
| - req := t.legRequest(ctx) |
| + req, out := t.legRequest(ctx) |
| pr, pw := io.Pipe() |
| - lw := &heldLegWriter{hdr: make(http.Header), headC: make(chan heldLegHeadMsg, 1), pw: pw} |
| + lw := &heldLegWriter{hdr: make(http.Header), headC: make(chan heldLegHeadMsg, 1), pw: pw, out: out} |
| proxy := t.proxy |
| go func() { |
| defer lw.finish() |
| @@ -590,9 +616,14 @@ func (t *heldTask) openLeg(leg HeldLeg, exempt bool) { |
| t.headerT = time.NewTimer(t.cfg.LegHeader) |
| } |
| -// legRequest builds a leg's GET from the browser's request (§3.3). |
| -func (t *heldTask) legRequest(ctx context.Context) *http.Request { |
| - req := t.r.Clone(ctx) |
| +// legRequest builds a leg's GET from the browser's request (§3.3). The leg |
| +// gets its own outcome: its proxy run is the only writer of it, so a retired |
| +// leg's proxy, still finishing after a replacement starts, shares no state |
| +// with the replacement or the browser's request. What the task needs of it |
| +// comes back with the leg's head (heldLegAttr). |
| +func (t *heldTask) legRequest(ctx context.Context) (*http.Request, *outcome) { |
| + out := &outcome{start: time.Now()} |
| + req := t.r.Clone(context.WithValue(ctx, answeredKey{}, out)) |
| req.Method = http.MethodGet |
| req.Body, req.GetBody, req.ContentLength = http.NoBody, nil, 0 |
| req.URL.RawQuery, _ = stripHoldMarker(t.r.URL.RawQuery) |
| @@ -605,7 +636,7 @@ func (t *heldTask) legRequest(ctx context.Context) *http.Request { |
| } else { |
| req.Header.Del("Last-Event-ID") |
| } |
| - return req |
| + return req, out |
| } |
| // retireLeg ends the open leg and deregisters it with the activator. |
| @@ -644,6 +675,11 @@ func (t *heldTask) onLeg(m heldLegMsg) (heldCloseReason, bool) { |
| } |
| return 0, false |
| } |
| + if !m.sse { |
| + // This head, or the edge's 204 or 502 for it, is the browser's |
| + // answer: the observer files it with what the leg noted. |
| + t.attribute(m.attr) |
| + } |
| switch { |
| case m.sse: |
| if err := t.writeFirstHead(http.StatusOK, m.header, true); err != nil { |
| @@ -693,6 +729,14 @@ func (t *heldTask) onLeg(m heldLegMsg) (heldCloseReason, bool) { |
| return 0, false |
| } |
| +// attribute copies a first leg's attribution onto the browser's request's |
| +// outcome. Only the task goroutine writes that outcome. |
| +func (t *heldTask) attribute(a heldLegAttr) { |
| + if o := outcomeFrom(t.r); o != nil { |
| + o.answered, o.cause = a.answered, a.cause |
| + } |
| +} |
| + |
| // legEnded handles the open leg ending without a terminal answer (§3.3 step |
| // 6, §3.6): reopen if the host is admissible, otherwise hold. |
| func (t *heldTask) legEnded() (heldCloseReason, bool) { |
| @@ -854,16 +898,27 @@ func isHeldSSE(status int, h http.Header) bool { |
| type heldLegHeadMsg struct { |
| status int |
| header http.Header |
| + attr heldLegAttr |
| } |
| // heldLegWriter is the response writer a leg's proxy run writes into: it |
| // hands the status and a header copy over once, then pipes body bytes to |
| -// the leg's reader. Only the proxy goroutine uses it. |
| +// the leg's reader. Only the proxy goroutine uses it, and out, the leg's |
| +// own outcome. |
| type heldLegWriter struct { |
| hdr http.Header |
| sent bool |
| headC chan heldLegHeadMsg |
| pw *io.PipeWriter |
| + out *outcome |
| +} |
| + |
| +// attr reads the leg's outcome, on the proxy goroutine that writes it. |
| +func (lw *heldLegWriter) attr() heldLegAttr { |
| + if lw.out == nil { |
| + return heldLegAttr{} |
| + } |
| + return heldLegAttr{answered: lw.out.answered, cause: lw.out.cause} |
| } |
| func (lw *heldLegWriter) Header() http.Header { return lw.hdr } |
| @@ -873,7 +928,7 @@ func (lw *heldLegWriter) WriteHeader(code int) { |
| return // informational answers are not the leg's head |
| } |
| lw.sent = true |
| - lw.headC <- heldLegHeadMsg{status: code, header: lw.hdr.Clone()} |
| + lw.headC <- heldLegHeadMsg{status: code, header: lw.hdr.Clone(), attr: lw.attr()} |
| } |
| func (lw *heldLegWriter) Write(b []byte) (int, error) { |
| @@ -923,7 +978,7 @@ func readHeldLeg(run *heldLegRun, pr *io.PipeReader, headC <-chan heldLegHeadMsg |
| return |
| } |
| sse := isHeldSSE(hd.status, hd.header) |
| - if !send(heldLegMsg{kind: heldLegHead, status: hd.status, header: hd.header, sse: sse}) { |
| + if !send(heldLegMsg{kind: heldLegHead, status: hd.status, header: hd.header, sse: sse, attr: hd.attr}) { |
| return |
| } |
| if sse { |
diff --git a/internal/edge/heldstream_sim_test.go b/internal/edge/heldstream_sim_test.go| index 0c87e212c..a8530362c 100644 |
| --- a/internal/edge/heldstream_sim_test.go |
| +++ b/internal/edge/heldstream_sim_test.go |
| @@ -260,6 +260,7 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| cfg := heldTestConfig() |
| cfg.MaxHold = time.Minute |
| cfg.LegHeader = time.Second |
| + cfg.Commit = 20 * time.Millisecond // the timing the simulation was calibrated with |
| bound := cfg.Tick + cfg.ReopenSpacing + cfg.BackoffCap + slack |
| var totalAdmitted, totalClosedShort, conclusiveTotal, skipped int |
| var maxLag time.Duration |
diff --git a/internal/edge/heldstream_test.go b/internal/edge/heldstream_test.go| index cb276111f..571b757ca 100644 |
| --- a/internal/edge/heldstream_test.go |
| +++ b/internal/edge/heldstream_test.go |
| @@ -20,11 +20,16 @@ import ( |
| const heldTestHost = "shop.example.com" |
| -// heldTestConfig is the brief's short config. |
| +// heldTestConfig is the brief's short config, with a generous Commit: no |
| +// test that is not about the commit timer may race it. A first-response |
| +// test must see the first leg's answer, however slowly a loaded box |
| +// admits and proxies it; a held stream's own response comes from hold() |
| +// when admission refuses, not from the timer. Tests about the timer set |
| +// their own. |
| func heldTestConfig() HeldConfig { |
| return HeldConfig{ |
| PerHost: 64, PerBox: 4096, |
| - MaxHold: 2 * time.Second, Commit: 20 * time.Millisecond, LegHeader: time.Second, |
| + MaxHold: 2 * time.Second, Commit: time.Minute, LegHeader: time.Second, |
| // The brief's 30 ms write deadline is set only by the tests about |
| // deadlines; elsewhere a starved test process must not turn a slow |
| // first write into a closed connection. |
| @@ -517,23 +522,78 @@ func TestHeldHTTP2IdleSurvivesWriteDeadline(t *testing.T) { |
| } |
| } |
| +// deadlineWriter records, for the last downstream write or flush that |
| +// failed, the write deadline armed for it and when the call returned, so a |
| +// test measures the deadline at the writer rather than at whoever observes |
| +// the stream ending. |
| +type deadlineWriter struct { |
| + http.ResponseWriter |
| + rc *http.ResponseController |
| + mu sync.Mutex |
| + armed time.Time // the deadline last armed (zero: disarmed) |
| + armedAt time.Time // when it was armed |
| + failArm time.Time // armed deadline for the failed call |
| + failAtArm time.Time |
| + failDone time.Time // when the failed call returned |
| +} |
| + |
| +func (d *deadlineWriter) SetWriteDeadline(t time.Time) error { |
| + d.mu.Lock() |
| + d.armed, d.armedAt = t, time.Now() |
| + d.mu.Unlock() |
| + return d.rc.SetWriteDeadline(t) |
| +} |
| + |
| +func (d *deadlineWriter) note(err error) { |
| + if err == nil { |
| + return |
| + } |
| + now := time.Now() |
| + d.mu.Lock() |
| + if d.failDone.IsZero() { |
| + d.failArm, d.failAtArm, d.failDone = d.armed, d.armedAt, now |
| + } |
| + d.mu.Unlock() |
| +} |
| + |
| +func (d *deadlineWriter) Write(b []byte) (int, error) { |
| + n, err := d.ResponseWriter.Write(b) |
| + d.note(err) |
| + return n, err |
| +} |
| + |
| +func (d *deadlineWriter) FlushError() error { |
| + err := d.rc.Flush() |
| + d.note(err) |
| + return err |
| +} |
| + |
| func TestHeldBlockedWriteEnds(t *testing.T) { |
| cfg := heldTestConfig() |
| cfg.WriteDeadline = 30 * time.Millisecond |
| cfg.MaxHold = time.Minute |
| + // writeSlack bounds how long after its armed deadline the failed write |
| + // may return: the deadline fires in the runtime's netpoller, so a |
| + // loaded box adds scheduling delay, but a write that is not bounded by |
| + // the deadline at all (one armed for the idle time, or none) blocks for |
| + // the test's whole life. |
| + const writeSlack = time.Second |
| big := "data: " + strings.Repeat("x", 16<<10) + "\n\n" |
| - // lastSent is when the proxy's last write was taken off the pipe; the |
| - // task's blocked downstream write starts just before it. |
| - var lastSent atomic.Int64 |
| h := newHeldHarness(t, cfg, func(n int, w http.ResponseWriter, r *http.Request) { |
| sseHead(w) |
| for r.Context().Err() == nil { |
| if _, err := io.WriteString(w, big); err != nil { |
| return |
| } |
| - lastSent.Store(time.Now().UnixNano()) |
| } |
| }) |
| + dwC := make(chan *deadlineWriter, 1) |
| + rt := registry.Route{Host: heldTestHost} |
| + h.srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + dw := &deadlineWriter{ResponseWriter: w, rc: http.NewResponseController(w)} |
| + dwC <- dw |
| + h.e.serveHeld(dw, r, rt, h.proxy) |
| + }) |
| h.start(t) |
| addr := strings.TrimPrefix(h.srv.URL, "http://") |
| conn, err := net.Dial("tcp", addr) |
| @@ -543,19 +603,35 @@ func TestHeldBlockedWriteEnds(t *testing.T) { |
| defer conn.Close() |
| _ = conn.(*net.TCPConn).SetReadBuffer(4096) |
| fmt.Fprintf(conn, "GET /live?carlos_hold=1 HTTP/1.1\r\nHost: %s\r\nAccept: text/event-stream\r\n\r\n", heldTestHost) |
| - // Never read: the edge's writes block on a full socket. |
| + // Never read: the edge's writes block on a full socket. The bound below |
| + // only ends a hung test; what is asserted is measured at the writer. |
| + var r heldCloseReason |
| select { |
| - case r := <-h.ends: |
| - ended := time.Now() |
| - if r != heldCloseWriteFailed { |
| - t.Fatalf("close reason %v", r) |
| - } |
| - if gap := ended.Sub(time.Unix(0, lastSent.Load())); gap > cfg.WriteDeadline+cfg.Tick { |
| - t.Fatalf("stream ended %v after its writes blocked", gap) |
| - } |
| - case <-time.After(10 * time.Second): |
| + case r = <-h.ends: |
| + case <-time.After(30 * time.Second): |
| t.Fatal("stream task did not end") |
| } |
| + if r != heldCloseWriteFailed { |
| + t.Fatalf("close reason %v", r) |
| + } |
| + dw := <-dwC |
| + dw.mu.Lock() |
| + arm, armedAt, done := dw.failArm, dw.failAtArm, dw.failDone |
| + dw.mu.Unlock() |
| + if done.IsZero() { |
| + t.Fatal("the stream ended write_deadline with no failed write") |
| + } |
| + if arm.IsZero() { |
| + t.Fatal("the failed write ran with no deadline armed") |
| + } |
| + // Armed just before the writer saw it, so a little under WriteDeadline |
| + // from the writer's clock, never more. |
| + if got := arm.Sub(armedAt); got > cfg.WriteDeadline || got < cfg.WriteDeadline-writeSlack { |
| + t.Fatalf("armed a %v deadline, want WriteDeadline %v", got, cfg.WriteDeadline) |
| + } |
| + if late := done.Sub(arm); late > writeSlack { |
| + t.Fatalf("the blocked write returned %v after its deadline", late) |
| + } |
| waitFor(t, time.Second, "held set empty", func() bool { return len(h.e.held.hosts()) == 0 }) |
| } |
| @@ -746,3 +822,109 @@ func TestHeldStreamStatsResume(t *testing.T) { |
| h.e.HeldWake(heldTestHost) |
| waitFor(t, time.Second, "resumed", func() bool { return h.e.HeldStreamStats().Resumes == 1 }) |
| } |
| + |
| +// Whole-branch fix P2-1: a reload that closes a stream after serveHeld's |
| +// map check and before the first response still gives the browser the empty |
| +// event stream, never an empty plain 200 that would stop EventSource for |
| +// good. The seam closes the stream at exactly that point; the first leg |
| +// never answers. |
| +func TestHeldReloadBeforeFirstResponse(t *testing.T) { |
| + h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) { |
| + <-r.Context().Done() |
| + }) |
| + h.e.held.afterMapCheck = func() { h.e.held.closeHost(heldTestHost) } |
| + h.start(t) |
| + resp := h.get(t, "/live?carlos_hold=1", nil) |
| + body, err := readFor(resp.Body, 10*time.Second) |
| + if err != io.EOF { |
| + t.Fatalf("stream did not end: %v (body %q)", err, body) |
| + } |
| + if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "text/event-stream" || |
| + resp.Header.Get("Cache-Control") != "no-store" || body != "" { |
| + t.Fatalf("status %d headers %v body %q: want the empty event stream", resp.StatusCode, resp.Header, body) |
| + } |
| + if r := <-h.ends; r != heldCloseUnmanaged { |
| + t.Fatalf("close reason %v", r) |
| + } |
| +} |
| + |
| +// Whole-branch fix P2-2: each leg owns its request's outcome. A leg retired |
| +// at its header timeout keeps running its proxy after the replacement |
| +// starts; both note a cause and a generation on their own request, with no |
| +// ordering between them (the race detector reports a shared outcome). Each |
| +// leg's outcome is its own, and neither is the browser's. |
| +func TestHeldLegsOwnOutcome(t *testing.T) { |
| + cfg := heldTestConfig() |
| + cfg.LegHeader = 50 * time.Millisecond |
| + replacement := make(chan struct{}) |
| + oldDone := make(chan struct{}) |
| + outs := make([]*outcome, 2) |
| + h := newHeldHarness(t, cfg, func(n int, w http.ResponseWriter, r *http.Request) { |
| + switch n { |
| + case 0: |
| + outs[0] = outcomeFrom(r) |
| + // No head: the header timeout retires this leg. Its cancellation |
| + // is handled only once the replacement has started. |
| + <-r.Context().Done() |
| + <-replacement |
| + noteCause(r, "old") |
| + noteServedGen(r, heldTestHost, 1) |
| + close(oldDone) |
| + case 1: |
| + outs[1] = outcomeFrom(r) |
| + close(replacement) |
| + noteCause(r, "new") |
| + noteServedGen(r, heldTestHost, 2) |
| + sseHead(w) |
| + <-r.Context().Done() |
| + default: |
| + <-r.Context().Done() |
| + } |
| + }) |
| + browserOut := make(chan *outcome, 1) |
| + rt := registry.Route{Host: heldTestHost} |
| + h.srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + r, o := withOutcome(r) |
| + browserOut <- o |
| + h.e.serveHeld(w, r, rt, h.proxy) |
| + }) |
| + h.start(t) |
| + resp := h.get(t, "/live?carlos_hold=1", nil) |
| + if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "text/event-stream" { |
| + t.Fatalf("status %d headers %v", resp.StatusCode, resp.Header) |
| + } |
| + select { |
| + case <-oldDone: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the retired leg's proxy never finished") |
| + } |
| + o := <-browserOut |
| + if outs[0] == nil || outs[1] == nil || outs[0] == outs[1] || outs[0] == o || outs[1] == o { |
| + t.Fatalf("leg outcomes %p, %p, browser %p: want two of their own", outs[0], outs[1], o) |
| + } |
| +} |
| + |
| +// Whole-branch fix P2-2: a first leg's answer that becomes the browser's |
| +// carries the leg's attribution back to the browser's request, so the |
| +// observer files it as it would an ordinary request. |
| +func TestHeldFirstLegAttribution(t *testing.T) { |
| + h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) { |
| + noteCause(r, "upstream_refused") |
| + w.WriteHeader(http.StatusBadGateway) |
| + }) |
| + got := make(chan outcome, 1) |
| + rt := registry.Route{Host: heldTestHost} |
| + h.srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + r, o := withOutcome(r) |
| + h.e.serveHeld(w, r, rt, h.proxy) |
| + got <- *o |
| + }) |
| + h.start(t) |
| + resp := h.get(t, "/live?carlos_hold=1", nil) |
| + if resp.StatusCode != http.StatusBadGateway { |
| + t.Fatalf("status %d", resp.StatusCode) |
| + } |
| + if o := <-got; o.cause != "upstream_refused" || o.answered { |
| + t.Fatalf("browser outcome cause %q answered %v", o.cause, o.answered) |
| + } |
| +} |
diff --git a/internal/edge/tunnel_e2e_test.go b/internal/edge/tunnel_e2e_test.go| index d1df3ece0..f6fe04f16 100644 |
| --- a/internal/edge/tunnel_e2e_test.go |
| +++ b/internal/edge/tunnel_e2e_test.go |
| @@ -321,3 +321,99 @@ func TestTunnelForwardsHoldMarkerAndSkipsCache(t *testing.T) { |
| time.Sleep(100 * time.Millisecond) |
| } |
| } |
| + |
| +// TestTunnelMarkedResponseNeverStored: the storage half of §7's hub cache |
| +// bypass (whole-branch fix P2-4). The box answers a marked request with a |
| +// finite, explicitly cacheable response, which the hub would store for an |
| +// unmarked one. With an empty hub cache, the marked URL's key stays absent |
| +// after the answer has gone through the hub, and a second marked request |
| +// reaches the box again. TestTunnelForwardsHoldMarkerAndSkipsCache covers |
| +// the lookup half. |
| +func TestTunnelMarkedResponseNeverStored(t *testing.T) { |
| + const host = "shop.example.com" |
| + reg := tunnelRoute(t, registry.Route{ |
| + Host: host, Kind: "instance", Status: "ready", Tunnel: "pi-box", Hibernate: true, |
| + }) |
| + hubEdge, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cache := NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes) |
| + hubEdge.EnableCache(cache) |
| + // served is signalled once the hub has finished serving a /page |
| + // request, its cache store (or not) included, whatever the client has |
| + // read by then. |
| + served := make(chan struct{}, 4) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + hubEdge.ServeHTTP(w, r) |
| + if r.URL.Path == "/page" { |
| + served <- struct{}{} |
| + } |
| + })) |
| + defer srv.Close() |
| + u, err := url.Parse(srv.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + hub := NewTunnelHub(u.Hostname(), map[string]string{"pi-box": "sekrit"}) |
| + hubEdge.EnableTunnels(hub) |
| + if err := hubEdge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // The box: an awake app's finite answer, cacheable by its headers. |
| + var mu sync.Mutex |
| + var boxQueries []string |
| + boxHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + mu.Lock() |
| + boxQueries = append(boxQueries, r.URL.RawQuery) |
| + mu.Unlock() |
| + w.Header().Set("Content-Type", "text/plain") |
| + w.Header().Set("Cache-Control", "public, max-age=60") |
| + _, _ = io.WriteString(w, "hello from the box") |
| + }) |
| + stop := startFakeRemoteHost(t, srv.URL, "pi-box", "sekrit", boxHandler) |
| + defer stop() |
| + waitForTunnelState(t, hub, "pi-box", "connected", e2eReconnectBound) |
| + |
| + key := CacheKey{Host: host, Method: http.MethodGet, Path: "/page", RawQuery: "carlos_hold=1"} |
| + get := func() *http.Request { |
| + req, err := http.NewRequest(http.MethodGet, srv.URL+"/page?carlos_hold=1", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Host = host |
| + return req |
| + } |
| + for i := 1; i <= 2; i++ { |
| + resp, err := http.DefaultClient.Do(get()) |
| + if err != nil { |
| + t.Fatalf("request %d: %v", i, err) |
| + } |
| + body, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if err != nil || resp.StatusCode != http.StatusOK || string(body) != "hello from the box" { |
| + t.Fatalf("request %d: status %d body %q err %v", i, resp.StatusCode, body, err) |
| + } |
| + select { |
| + case <-served: |
| + case <-time.After(10 * time.Second): |
| + t.Fatalf("request %d: the hub never finished serving", i) |
| + } |
| + if _, hit := cache.GetFor(key, get()); hit { |
| + t.Fatalf("request %d: the hub stored the marked answer under %+v", i, key) |
| + } |
| + cache.mu.Lock() |
| + n := len(cache.entries) |
| + cache.mu.Unlock() |
| + if n != 0 { |
| + t.Fatalf("request %d: hub cache holds %d entries, want none", i, n) |
| + } |
| + } |
| + mu.Lock() |
| + seen := append([]string(nil), boxQueries...) |
| + mu.Unlock() |
| + if len(seen) != 2 || seen[0] != "carlos_hold=1" || seen[1] != "carlos_hold=1" { |
| + t.Fatalf("box saw queries %q, want two marked requests: the second must reach the box, not the hub's cache", seen) |
| + } |
| +} |