carlos / platform Public

edge: the held-stream task (#432)

Human

Prompt

Task 5 of #432, the per-stream task that holds an opted-in
event stream, relays whole SSE events from activator-admitted legs run
through the route's own proxy, heartbeats, and reopens on a wake signal
or a tick.

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

heldstream.go adds HeldConfig/DefaultHeldConfig, SetHeldConfig,
the held set (per-host and per-box caps, wake, closeHost, hosts),
stripHoldMarker and Edge.serveHeld. The handler goroutine is the only
writer of the browser's connection; admission, the leg's proxy run and
its SSE reader feed it over channels. First-leg answers follow spec 3.3
(SSE relayed with no-store, 3xx to 204, non-SSE 200 to 502, others
passed through); later legs must be SSE or the stream closes. The
2-second commit, the cursor seed, the reopen rule with short legs and
backoff, swaps and post-hold reopens exempt, MaxHold and per-write
deadlines (disarmed after each write) are in. Over a cap the browser
gets retry: 30000 and the activator is never called. Close reasons
funnel through heldSet.finish for Task 7's counters. Edge gains held,
built in New. Not wired into ServeHTTP yet (Task 6).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 63cc9cf7075b5cdcffe7d09eb6d2332163029e32 parent 1595be9
4 files changed, +1,861 −1
  • internal/edge/edge.go +6 −1
  • internal/edge/heldstream.go +845 −0
  • internal/edge/heldstream_sim_test.go +428 −0
  • internal/edge/heldstream_test.go +582 −0
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 0f5cd5c57..da3279d98 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -117,6 +117,10 @@ type Edge struct {
// processes woken per request. Nil keeps the proxy-only behavior; with it
// set, unflagged routes are still proxied straight (the flag is per host).
act Activator
+ // held is the edge-held event streams this edge holds (heldstream.go),
+ // built in New with DefaultHeldConfig; SetHeldConfig replaces it before
+ // serving.
+ held *heldSet
// gate is the password curtain (internal/gate) for routes whose row
// carries a gate hash. Always constructed: the check is one string
// compare on up.route.Gate for every ungated host, and the limiter it
@@ -548,7 +552,8 @@ func New(reg *registry.Registry, act Activator) (*Edge, error) {
func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, error) {
e := &Edge{reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(hold), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000),
- planLimiter: ratelimit.NewLimiter(time.Now, 100_000), burst: newBurstLimiter(time.Now), notices: newBurstNotices()}
+ planLimiter: ratelimit.NewLimiter(time.Now, 100_000), burst: newBurstLimiter(time.Now), notices: newBurstNotices(),
+ held: newHeldSet(DefaultHeldConfig)}
e.geo = geo.NewSwappable()
e.geoLookup = e.geo.Lookup
e.guardMint = e.mintRef
diff --git a/internal/edge/heldstream.go b/internal/edge/heldstream.go
new file mode 100644
index 000000000..ababa1a38
--- /dev/null
+++ b/internal/edge/heldstream.go
@@ -0,0 +1,845 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "io"
+ "log"
+ "mime"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Edge-held event streams (spec 2026-10-28-edge-held-streams-design.md §3.3,
+// §3.3a, §3.6, §3.7). A browser's marked EventSource request is owned by one
+// stream task: the handler goroutine that runs serveHeld. It is the only
+// writer of the browser's connection. Admission, the leg's proxy run and the
+// leg's reader each run in their own goroutine and feed the task over
+// channels, so nothing they wait on can stall a heartbeat, a cancellation
+// or the maximum hold. A leg is admitted by the activator (AdmitHeldLeg), so
+// it never counts as activity and never starts a wake.
+
+// HeldConfig holds the held-stream bounds and timings. It is exported so
+// tests in other packages can shorten it (SetHeldConfig).
+type HeldConfig struct {
+ // PerHost and PerBox cap the streams held at once (§3.6).
+ PerHost, PerBox int
+ // MaxHold recycles a browser connection; Commit is how long the browser
+ // may wait for a first response; LegHeader bounds a leg's response
+ // headers; WriteDeadline bounds one downstream write; Tick is the
+ // heartbeat interval and the admissibility backstop (§3.7).
+ MaxHold, Commit, LegHeader, WriteDeadline, Tick time.Duration
+ // ReopenSpacing is the least time between two leg opens and the first
+ // backoff step; a leg shorter than ShortLeg is a short leg; backoff
+ // doubles up to BackoffCap.
+ ReopenSpacing, ShortLeg, BackoffCap time.Duration
+ // ShortLegsToClose short legs in a row close the browser's stream.
+ ShortLegsToClose int
+}
+
+// DefaultHeldConfig is the spec's values.
+var DefaultHeldConfig = HeldConfig{64, 4096, time.Hour, 2 * time.Second, 10 * time.Second, 10 * time.Second, 25 * time.Second, time.Second, 30 * time.Second, 30 * time.Second, 5}
+
+// SetHeldConfig replaces the held set with an empty one using c. Call it
+// before serving: streams held by the old set are not moved.
+func (e *Edge) SetHeldConfig(c HeldConfig) { e.held = newHeldSet(c) }
+
+// heldCloseReason is why a held stream ended. finish is the one place every
+// stream's end passes through.
+type heldCloseReason int
+
+const (
+ heldCloseClientGone heldCloseReason = iota // the browser left
+ heldCloseWriteFailed // a downstream write or flush failed (deadline included)
+ heldCloseMaxHold // MaxHold reached
+ heldCloseShortLegs // ShortLegsToClose short legs in a row
+ heldCloseUnmanaged // the host left this edge (closeHost)
+ heldCloseRefused // a reopen was not answered with an event stream
+ heldCloseRedirect // the first leg answered 3xx; the browser got 204
+ heldClosePassThrough // the first leg's non-200 answer went to the browser
+ heldCloseBadGateway // the first leg's 200 was not an identity event stream
+ heldCloseEventTooLarge // an event exceeded sseMaxEvent
+)
+
+var heldCloseNames = [...]string{"client_gone", "write_deadline", "max_hold", "short_legs", "unmanaged", "refused", "redirect", "pass_through", "bad_gateway", "event_too_large"}
+
+func (r heldCloseReason) String() string {
+ if int(r) < len(heldCloseNames) {
+ return heldCloseNames[r]
+ }
+ return "unknown"
+}
+
+// heldSet is this edge's held streams, by host.
+type heldSet struct {
+ cfg HeldConfig
+ mu sync.Mutex
+ byHost map[string]map[*heldStream]struct{}
+ total int
+ // onFinish is a test seam, nil in production: called after a stream
+ // has left the set.
+ onFinish func(host string, r heldCloseReason)
+}
+
+// heldStream is one held stream's entry in the set: the signals other
+// goroutines send its task.
+type heldStream struct {
+ host string
+ wakeC chan struct{} // buffered 1; a full buffer drops the signal
+ closeC chan struct{} // closed once by closeHost
+ closeOnce sync.Once
+}
+
+func newHeldSet(cfg HeldConfig) *heldSet {
+ return &heldSet{cfg: cfg, byHost: make(map[string]map[*heldStream]struct{})}
+}
+
+// register adds a stream for host, or returns nil over a cap.
+func (s *heldSet) register(host string) *heldStream {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.total >= s.cfg.PerBox || len(s.byHost[host]) >= s.cfg.PerHost {
+ return nil
+ }
+ st := &heldStream{host: host, wakeC: make(chan struct{}, 1), closeC: make(chan struct{})}
+ m := s.byHost[host]
+ if m == nil {
+ m = make(map[*heldStream]struct{})
+ s.byHost[host] = m
+ }
+ m[st] = struct{}{}
+ s.total++
+ return st
+}
+
+// finish removes st from the set. Every held stream ends here, with its
+// reason (counters, spec §3.9, attach here).
+func (s *heldSet) finish(st *heldStream, r heldCloseReason) {
+ s.mu.Lock()
+ if m := s.byHost[st.host]; m != nil {
+ if _, ok := m[st]; ok {
+ delete(m, st)
+ s.total--
+ }
+ if len(m) == 0 {
+ delete(s.byHost, st.host)
+ }
+ }
+ s.mu.Unlock()
+ if s.onFinish != nil {
+ s.onFinish(st.host, r)
+ }
+}
+
+// wake signals every stream held for host that the host may have become
+// admissible. It never blocks; a signal a stream has not taken yet absorbs
+// this one.
+func (s *heldSet) wake(host string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for st := range s.byHost[host] {
+ select {
+ case st.wakeC <- struct{}{}:
+ default:
+ }
+ }
+}
+
+// closeHost closes every stream held for host: this edge no longer manages
+// it (reload).
+func (s *heldSet) closeHost(host string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for st := range s.byHost[host] {
+ st.closeOnce.Do(func() { close(st.closeC) })
+ }
+}
+
+// hosts lists the hosts with at least one held stream.
+func (s *heldSet) hosts() []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ out := make([]string, 0, len(s.byHost))
+ for h := range s.byHost {
+ out = append(out, h)
+ }
+ return out
+}
+
+// holdMarker is the opt-in query parameter and its one accepted value
+// (spec §3.1).
+const holdMarkerName, holdMarkerValue = "carlos_hold", "1"
+
+// stripHoldMarker removes every carlos_hold=1 pair from rawQuery, leaving
+// the other pairs byte for byte in their order. marked reports whether one
+// was there.
+func stripHoldMarker(rawQuery string) (stripped string, marked bool) {
+ if !strings.Contains(rawQuery, "hold") && !strings.Contains(rawQuery, "%") {
+ return rawQuery, false
+ }
+ pairs := strings.Split(rawQuery, "&")
+ kept := pairs[:0:0]
+ for _, p := range pairs {
+ k, v, ok := strings.Cut(p, "=")
+ if ok {
+ dk, err1 := url.QueryUnescape(k)
+ dv, err2 := url.QueryUnescape(v)
+ if err1 == nil && err2 == nil && dk == holdMarkerName && dv == holdMarkerValue {
+ marked = true
+ continue
+ }
+ }
+ kept = append(kept, p)
+ }
+ if !marked {
+ return rawQuery, false
+ }
+ return strings.Join(kept, "&"), true
+}
+
+// writeHeldRetry is the over-cap answer (§3.6): one retry event, then close.
+func writeHeldRetry(w http.ResponseWriter, deadline time.Duration) {
+ rc := http.NewResponseController(w)
+ _ = rc.SetWriteDeadline(time.Now().Add(deadline))
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.WriteString(w, "retry: 30000\n\n")
+ _ = rc.Flush()
+ _ = rc.SetWriteDeadline(time.Time{})
+}
+
+// serveHeld runs one held stream to completion. proxy is the route's own
+// handler chain (up.proxy) and rt its route. It never hands the request to
+// the activator's ServeHTTP and never falls back to proxying it as an
+// ordinary request.
+func (e *Edge) serveHeld(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) {
+ s := e.held
+ var st *heldStream
+ if s != nil && e.act != nil {
+ st = s.register(rt.Host)
+ }
+ if st == nil {
+ d := DefaultHeldConfig.WriteDeadline
+ if s != nil {
+ d = s.cfg.WriteDeadline
+ }
+ writeHeldRetry(w, d)
+ return
+ }
+ t := &heldTask{
+ e: e, cfg: s.cfg, st: st, host: rt.Host, rt: rt, proxy: proxy,
+ w: w, rc: http.NewResponseController(w), r: r,
+ cursor: r.Header.Get("Last-Event-ID"),
+ admitC: make(chan heldAdmit, 1), legC: make(chan heldLegMsg),
+ }
+ s.finish(st, t.run())
+}
+
+// heldTask is one held stream's state, owned by the handler goroutine.
+type heldTask struct {
+ e *Edge
+ cfg HeldConfig
+ st *heldStream
+ host string
+ rt registry.Route
+ proxy http.Handler
+ w http.ResponseWriter
+ rc *http.ResponseController
+ r *http.Request
+ ctx context.Context
+
+ committed bool // the browser has a response
+ cursor string // the last event ID relayed (or the browser's own)
+ lastWrite time.Time // last successful downstream write
+
+ admitC chan heldAdmit
+ admitting bool
+ admitExempt bool
+
+ legC chan heldLegMsg
+ leg *heldLegRun
+ headerT *time.Timer
+ passThrough bool // the first leg's non-SSE answer is being copied
+ lastLegStart time.Time
+ shortLegs int
+
+ reopenT *time.Timer
+ reopenExempt bool
+}
+
+type heldAdmit struct {
+ leg HeldLeg
+ err error
+}
+
+// heldLegRun is one open leg.
+type heldLegRun struct {
+ leg HeldLeg
+ cancel context.CancelFunc // ends the leg's request
+ quit chan struct{} // closed when the task retires the leg
+ start time.Time
+ // exempt: opened after a hold, so it is not a short leg (§3.6).
+ exempt bool
+}
+
+type heldLegMsgKind int
+
+const (
+ heldLegHead heldLegMsgKind = iota
+ heldLegBlock
+ heldLegChunk
+ heldLegEnd
+)
+
+// heldLegMsg is what a leg's reader hands the task.
+type heldLegMsg struct {
+ run *heldLegRun
+ kind heldLegMsgKind
+ status int
+ header http.Header
+ sse bool
+ block sseBlock
+ chunk []byte
+ err error
+}
+
+var (
+ errHeldLegClosed = errors.New("edge: held leg closed")
+ errHeldLegNoResponse = errors.New("edge: held leg ended without a response")
+ errHeldLegHeaderTimeout = errors.New("edge: held leg response headers timed out")
+)
+
+func timerC(t *time.Timer) <-chan time.Time {
+ if t == nil {
+ return nil
+ }
+ return t.C
+}
+
+func (t *heldTask) run() heldCloseReason {
+ ctx, cancel := context.WithCancel(t.r.Context())
+ t.ctx = ctx
+ defer t.cleanup(cancel)
+ t.lastWrite = time.Now()
+ commitT := time.NewTimer(t.cfg.Commit)
+ defer commitT.Stop()
+ maxT := time.NewTimer(t.cfg.MaxHold)
+ defer maxT.Stop()
+ tickT := time.NewTimer(t.cfg.Tick)
+ defer tickT.Stop()
+
+ t.startAdmit(false)
+ for {
+ var admitC <-chan heldAdmit
+ if t.admitting {
+ admitC = t.admitC
+ }
+ var legC <-chan heldLegMsg
+ if t.leg != nil {
+ legC = t.legC
+ }
+ var commitC <-chan time.Time
+ if !t.committed {
+ commitC = commitT.C
+ }
+ select {
+ case <-ctx.Done():
+ return heldCloseClientGone
+ case <-t.st.closeC:
+ return heldCloseUnmanaged
+ case <-maxT.C:
+ // The task only ever writes whole blocks, so this is a block
+ // boundary.
+ return heldCloseMaxHold
+ case <-commitC:
+ if err := t.commit(); err != nil {
+ return heldCloseWriteFailed
+ }
+ case res := <-admitC:
+ t.admitting = false
+ if res.err != nil {
+ // Every refusal is the same: hold.
+ if err := t.hold(); err != nil {
+ return heldCloseWriteFailed
+ }
+ continue
+ }
+ t.openLeg(res.leg, t.admitExempt)
+ case m := <-legC:
+ if r, done := t.onLeg(m); done {
+ return r
+ }
+ case <-timerC(t.headerT):
+ t.headerT = nil
+ if r, done := t.legEnded(); done {
+ return r
+ }
+ case <-timerC(t.reopenT):
+ t.reopenT = nil
+ t.startAdmit(t.reopenExempt)
+ case <-t.st.wakeC:
+ if t.holding() {
+ t.scheduleReopen(true, 0)
+ }
+ case now := <-tickT.C:
+ if t.committed && now.Sub(t.lastWrite) >= t.cfg.Tick {
+ if err := t.write([]byte(": ping\n")); err != nil {
+ return heldCloseWriteFailed
+ }
+ }
+ // The backstop for a lost wake signal (§3.7).
+ if t.holding() && t.e.act.HeldAdmissible(t.host) {
+ t.scheduleReopen(true, 0)
+ }
+ next := time.Until(t.lastWrite.Add(t.cfg.Tick))
+ if next <= 0 {
+ next = t.cfg.Tick
+ }
+ tickT.Reset(next)
+ }
+ }
+}
+
+// holding: no leg, no admission, no reopen pending. Only a wake signal or a
+// tick moves a holding stream.
+func (t *heldTask) holding() bool {
+ return t.leg == nil && !t.admitting && t.reopenT == nil
+}
+
+// cleanup ends whatever the task still has open. An admission in flight is
+// waited for (its context is cancelled first), so an admitted leg is always
+// Done.
+func (t *heldTask) cleanup(cancel context.CancelFunc) {
+ cancel()
+ if t.leg != nil {
+ t.retireLeg()
+ }
+ if t.admitting {
+ if res := <-t.admitC; res.leg != nil {
+ res.leg.Done()
+ }
+ t.admitting = false
+ }
+ if t.reopenT != nil {
+ t.reopenT.Stop()
+ }
+ if t.headerT != nil {
+ t.headerT.Stop()
+ }
+}
+
+func (t *heldTask) startAdmit(exempt bool) {
+ t.admitting, t.admitExempt = true, exempt
+ ctx, act, rt, out := t.ctx, t.e.act, t.rt, t.admitC
+ go func() {
+ leg, err := act.AdmitHeldLeg(ctx, rt)
+ if err == nil && leg == nil {
+ err = errHeldLegNoResponse
+ }
+ out <- heldAdmit{leg: leg, err: err}
+ }()
+}
+
+// scheduleReopen starts a reopen after backoff, never sooner than
+// ReopenSpacing after the last leg opened.
+func (t *heldTask) scheduleReopen(exempt bool, backoff time.Duration) {
+ at := time.Now().Add(backoff)
+ if s := t.lastLegStart.Add(t.cfg.ReopenSpacing); s.After(at) {
+ at = s
+ }
+ t.reopenExempt = exempt
+ t.reopenT = time.NewTimer(time.Until(at))
+}
+
+// hold commits the edge's own response if the browser has none yet; the
+// stream then waits for a wake signal or a tick.
+func (t *heldTask) hold() error {
+ if !t.committed {
+ return t.commit()
+ }
+ return nil
+}
+
+// openLeg runs the route's proxy for an admitted leg (§3.3a).
+func (t *heldTask) openLeg(leg HeldLeg, exempt bool) {
+ ctx, cancel := context.WithCancel(leg.Context())
+ 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)
+ pr, pw := io.Pipe()
+ lw := &heldLegWriter{hdr: make(http.Header), headC: make(chan heldLegHeadMsg, 1), pw: pw}
+ proxy := t.proxy
+ go func() {
+ defer lw.finish()
+ defer func() {
+ if p := recover(); p != nil && p != http.ErrAbortHandler {
+ log.Printf("edge: held leg for %s: proxy panic: %v", req.Host, p)
+ }
+ }()
+ proxy.ServeHTTP(lw, req)
+ }()
+ go readHeldLeg(run, pr, lw.headC, t.legC)
+ 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)
+ req.Method = http.MethodGet
+ req.Body, req.GetBody, req.ContentLength = http.NoBody, nil, 0
+ req.URL.RawQuery, _ = stripHoldMarker(t.r.URL.RawQuery)
+ req.RequestURI = req.URL.RequestURI()
+ removeHeldHopHeaders(req.Header)
+ req.Header.Del("X-Carlos-Sidecar")
+ req.Header.Set("Accept-Encoding", "identity")
+ if t.cursor != "" {
+ req.Header.Set("Last-Event-ID", t.cursor)
+ } else {
+ req.Header.Del("Last-Event-ID")
+ }
+ return req
+}
+
+// retireLeg ends the open leg and deregisters it with the activator.
+func (t *heldTask) retireLeg() {
+ run := t.leg
+ t.leg = nil
+ t.passThrough = false
+ if t.headerT != nil {
+ t.headerT.Stop()
+ t.headerT = nil
+ }
+ close(run.quit)
+ run.cancel()
+ run.leg.Done()
+}
+
+func (t *heldTask) onLeg(m heldLegMsg) (heldCloseReason, bool) {
+ if m.run != t.leg {
+ return 0, false // a retired leg's late message
+ }
+ switch m.kind {
+ case heldLegHead:
+ if t.headerT != nil {
+ t.headerT.Stop()
+ t.headerT = nil
+ }
+ if m.run.leg.Context().Err() != nil {
+ // Cancelled before it answered: whatever the proxy wrote (its
+ // error handler's 502) is not the app's answer.
+ return t.legEnded()
+ }
+ if t.committed {
+ // A reopen must answer an identity event stream (§3.3 step 5).
+ if !m.sse {
+ return heldCloseRefused, true
+ }
+ return 0, false
+ }
+ switch {
+ case m.sse:
+ if err := t.writeFirstHead(http.StatusOK, m.header, true); err != nil {
+ return heldCloseWriteFailed, true
+ }
+ case m.status >= 300 && m.status < 400:
+ t.w.Header().Set("Cache-Control", "no-store")
+ if err := t.writeHead(http.StatusNoContent); err != nil {
+ return heldCloseWriteFailed, true
+ }
+ return heldCloseRedirect, true
+ case m.status == http.StatusOK:
+ t.e.logThrottled("held-not-sse|"+t.host, "held stream for "+t.host+": upstream answered 200 without an identity text/event-stream; answered 502")
+ if err := t.writeHead(http.StatusBadGateway); err != nil {
+ return heldCloseWriteFailed, true
+ }
+ return heldCloseBadGateway, true
+ default:
+ if err := t.writeFirstHead(m.status, m.header, false); err != nil {
+ return heldCloseWriteFailed, true
+ }
+ t.passThrough = true
+ }
+ case heldLegBlock:
+ if m.block.CommentOnly {
+ return 0, false // the edge does its own heartbeats (§3.7)
+ }
+ if err := t.write(m.block.Raw); err != nil {
+ return heldCloseWriteFailed, true
+ }
+ if m.block.HasID {
+ t.cursor = m.block.ID
+ }
+ case heldLegChunk:
+ if err := t.write(m.chunk); err != nil {
+ return heldCloseWriteFailed, true
+ }
+ case heldLegEnd:
+ if t.passThrough {
+ return heldClosePassThrough, true
+ }
+ if errors.Is(m.err, errSSEEventTooLarge) {
+ return heldCloseEventTooLarge, true
+ }
+ return t.legEnded()
+ }
+ return 0, false
+}
+
+// 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) {
+ run := t.leg
+ byActivator := run.leg.Context().Err() != nil && t.ctx.Err() == nil
+ lasted := time.Since(run.start)
+ t.retireLeg()
+ if !t.e.act.HeldAdmissible(t.host) {
+ if err := t.hold(); err != nil {
+ return heldCloseWriteFailed, true
+ }
+ return 0, false
+ }
+ switch {
+ case byActivator, run.exempt:
+ // A swap, or the first leg after a hold: not a short leg.
+ t.scheduleReopen(false, 0)
+ case lasted < t.cfg.ShortLeg:
+ t.shortLegs++
+ if t.shortLegs >= t.cfg.ShortLegsToClose {
+ return heldCloseShortLegs, true
+ }
+ t.scheduleReopen(false, t.backoff())
+ default:
+ t.shortLegs = 0
+ t.scheduleReopen(false, 0)
+ }
+ return 0, false
+}
+
+// backoff is ReopenSpacing doubled per short leg after the first, capped.
+func (t *heldTask) backoff() time.Duration {
+ d := t.cfg.ReopenSpacing
+ for i := 1; i < t.shortLegs && d < t.cfg.BackoffCap; i++ {
+ d *= 2
+ }
+ return min(d, t.cfg.BackoffCap)
+}
+
+// commit writes the edge's own held response (§3.3 step 4).
+func (t *heldTask) commit() error {
+ h := t.w.Header()
+ h.Set("Content-Type", "text/event-stream")
+ h.Set("Cache-Control", "no-store")
+ t.committed = true
+ var seed []byte
+ if t.cursor != "" && !strings.ContainsAny(t.cursor, "\r\n\x00") {
+ seed = []byte("id: " + t.cursor + "\n\n")
+ }
+ return t.writeHeadAndBody(http.StatusOK, seed)
+}
+
+// writeFirstHead writes the first leg's status and headers as the
+// browser's. For an event stream the framing headers go and Cache-Control
+// is no-store (§3.3 step 3).
+func (t *heldTask) writeFirstHead(status int, src http.Header, sse bool) error {
+ h := src.Clone()
+ removeHeldHopHeaders(h)
+ if sse {
+ h.Del("Content-Length")
+ h.Del("Content-Encoding")
+ h.Set("Cache-Control", "no-store")
+ }
+ dst := t.w.Header()
+ for k, vs := range h {
+ dst[k] = vs
+ }
+ return t.writeHead(status)
+}
+
+func (t *heldTask) writeHead(status int) error {
+ t.committed = true
+ return t.writeHeadAndBody(status, nil)
+}
+
+// writeHeadAndBody and write are the only downstream writes. Each arms the
+// write deadline, writes, flushes and disarms it before the task waits
+// again: on HTTP/2 an armed deadline resets the stream when it expires even
+// with no write pending, so it must bound one write, never the idle time.
+func (t *heldTask) writeHeadAndBody(status int, body []byte) error {
+ _ = t.rc.SetWriteDeadline(time.Now().Add(t.cfg.WriteDeadline))
+ t.w.WriteHeader(status)
+ var err error
+ if len(body) > 0 {
+ _, err = t.w.Write(body)
+ }
+ if err == nil {
+ err = t.rc.Flush()
+ }
+ _ = t.rc.SetWriteDeadline(time.Time{})
+ if err == nil {
+ t.lastWrite = time.Now()
+ }
+ return err
+}
+
+func (t *heldTask) write(b []byte) error {
+ _ = t.rc.SetWriteDeadline(time.Now().Add(t.cfg.WriteDeadline))
+ _, err := t.w.Write(b)
+ if err == nil {
+ err = t.rc.Flush()
+ }
+ _ = t.rc.SetWriteDeadline(time.Time{})
+ if err == nil {
+ t.lastWrite = time.Now()
+ }
+ return err
+}
+
+// removeHeldHopHeaders deletes hop-by-hop headers: Connection and every
+// name it lists, Keep-Alive, Proxy-*, TE, Trailer, Transfer-Encoding and
+// Upgrade.
+func removeHeldHopHeaders(h http.Header) {
+ for _, v := range h["Connection"] {
+ for _, name := range strings.Split(v, ",") {
+ if name = strings.TrimSpace(name); name != "" {
+ h.Del(name)
+ }
+ }
+ }
+ for k := range h {
+ lk := strings.ToLower(k)
+ switch {
+ case strings.HasPrefix(lk, "proxy-"),
+ lk == "connection", lk == "keep-alive", lk == "te", lk == "trailer",
+ lk == "transfer-encoding", lk == "upgrade":
+ delete(h, k)
+ }
+ }
+}
+
+// isHeldSSE reports whether a leg's head is 200 identity text/event-stream.
+func isHeldSSE(status int, h http.Header) bool {
+ if status != http.StatusOK {
+ return false
+ }
+ mt, _, err := mime.ParseMediaType(h.Get("Content-Type"))
+ if err != nil || mt != "text/event-stream" {
+ return false
+ }
+ for _, v := range h.Values("Content-Encoding") {
+ for _, c := range strings.Split(v, ",") {
+ if c = strings.TrimSpace(c); c != "" && !strings.EqualFold(c, "identity") {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// heldLegHeadMsg is a leg's status and a copy of its headers; status 0 means
+// the proxy returned without answering.
+type heldLegHeadMsg struct {
+ status int
+ header http.Header
+}
+
+// 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.
+type heldLegWriter struct {
+ hdr http.Header
+ sent bool
+ headC chan heldLegHeadMsg
+ pw *io.PipeWriter
+}
+
+func (lw *heldLegWriter) Header() http.Header { return lw.hdr }
+
+func (lw *heldLegWriter) WriteHeader(code int) {
+ if lw.sent || (code >= 100 && code < 200 && code != http.StatusSwitchingProtocols) {
+ return // informational answers are not the leg's head
+ }
+ lw.sent = true
+ lw.headC <- heldLegHeadMsg{status: code, header: lw.hdr.Clone()}
+}
+
+func (lw *heldLegWriter) Write(b []byte) (int, error) {
+ if !lw.sent {
+ lw.WriteHeader(http.StatusOK)
+ }
+ return lw.pw.Write(b)
+}
+
+func (lw *heldLegWriter) Flush() {
+ if !lw.sent {
+ lw.WriteHeader(http.StatusOK)
+ }
+}
+
+func (lw *heldLegWriter) finish() {
+ if !lw.sent {
+ lw.sent = true
+ lw.headC <- heldLegHeadMsg{}
+ }
+ _ = lw.pw.Close()
+}
+
+// readHeldLeg reads one leg for the task: its head, then whole SSE blocks
+// (or raw chunks when the head is not an event stream), then its end. It
+// stops when the task retires the leg, and closes the pipe so the proxy
+// run's writes fail and it returns.
+func readHeldLeg(run *heldLegRun, pr *io.PipeReader, headC <-chan heldLegHeadMsg, out chan<- heldLegMsg) {
+ defer pr.CloseWithError(errHeldLegClosed)
+ send := func(m heldLegMsg) bool {
+ m.run = run
+ select {
+ case out <- m:
+ return true
+ case <-run.quit:
+ return false
+ }
+ }
+ var hd heldLegHeadMsg
+ select {
+ case hd = <-headC:
+ case <-run.quit:
+ return
+ }
+ if hd.status == 0 {
+ send(heldLegMsg{kind: heldLegEnd, err: errHeldLegNoResponse})
+ return
+ }
+ sse := isHeldSSE(hd.status, hd.header)
+ if !send(heldLegMsg{kind: heldLegHead, status: hd.status, header: hd.header, sse: sse}) {
+ return
+ }
+ if sse {
+ rd := newSSEReader(pr)
+ for {
+ b, err := rd.Next()
+ if err != nil {
+ send(heldLegMsg{kind: heldLegEnd, err: err})
+ return
+ }
+ if !send(heldLegMsg{kind: heldLegBlock, block: b}) {
+ return
+ }
+ }
+ }
+ buf := make([]byte, 32<<10)
+ for {
+ n, err := pr.Read(buf)
+ if n > 0 && !send(heldLegMsg{kind: heldLegChunk, chunk: append([]byte(nil), buf[:n]...)}) {
+ return
+ }
+ if err != nil {
+ send(heldLegMsg{kind: heldLegEnd, err: err})
+ return
+ }
+ }
+}
diff --git a/internal/edge/heldstream_sim_test.go b/internal/edge/heldstream_sim_test.go
new file mode 100644
index 000000000..4a9e68fcf
--- /dev/null
+++ b/internal/edge/heldstream_sim_test.go
@@ -0,0 +1,428 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "math/rand"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The held-stream lifecycle simulation (plan Task 5 step 2, spec §7). A model
+// activator moves one host through asleep, waking, awake, stopping,
+// probe-held and fenced at random, with overlap swaps while awake. It is
+// admissible only when awake (spec §3.5). On every transition to admissible
+// it calls the wake hook, dropped half the time and delayed at random
+// otherwise; on every transition away from admissible, and on a swap, it
+// cancels every leg it admitted, as the real activator does under a.mu.
+// N held streams run against it through serveHeld, with a fake proxy that
+// serves SSE with ids and sometimes ends a leg on its own.
+//
+// Invariants, checked every 5 ms:
+// H1: the model's ServeHTTP is never called, and no leg is admitted while
+// the model is not admissible;
+// H2: a stream not closed has an open leg once the host has been
+// admissible, the stream has been running, and its last leg has been
+// done for longer than Tick + ReopenSpacing + BackoffCap (spec G4:
+// outside a bounded reopen delay, no silent stream past one tick);
+// H3: a stream never has two legs open at once.
+// At the end of each seed every admitted leg must have been Done.
+
+type simState int
+
+const (
+ simAsleep simState = iota
+ simWaking
+ simAwake
+ simStopping
+ simProbeHeld
+ simFenced
+)
+
+var simStateNames = [...]string{"asleep", "waking", "awake", "stopping", "probeHeld", "fenced"}
+
+type simStreamKey struct{}
+
+type simLeg struct {
+ m *simModel
+ sid int
+ ctx context.Context
+ cancel context.CancelFunc
+ done bool
+}
+
+func (l *simLeg) Context() context.Context { return l.ctx }
+func (l *simLeg) Done() {
+ m := l.m
+ m.mu.Lock()
+ if !l.done {
+ l.done = true
+ m.note("done stream %d", l.sid)
+ m.open[l.sid]--
+ m.lastLegEnd[l.sid] = time.Now()
+ delete(m.legs, l)
+ }
+ m.mu.Unlock()
+ l.cancel()
+}
+
+type simModel struct {
+ mu sync.Mutex
+ rng *rand.Rand
+ state simState
+ since time.Time // admissible since (or last swap), valid while awake
+ changed chan struct{} // closed on every transition
+ legs map[*simLeg]struct{}
+ open map[int]int
+ lastLegEnd map[int]time.Time
+ admitted int
+ hook func(string)
+ served atomic.Int64
+ violations []string
+ // history, for a violation's report: transitions and admission attempts.
+ t0 time.Time
+ history []string
+}
+
+func (m *simModel) note(format string, args ...any) {
+ if len(m.history) < 400 {
+ m.history = append(m.history, fmt.Sprintf("%6.1fms ", float64(time.Since(m.t0).Microseconds())/1000)+fmt.Sprintf(format, args...))
+ }
+}
+
+func newSimModel(seed int64) *simModel {
+ return &simModel{t0: time.Now(), rng: rand.New(rand.NewSource(seed)), changed: make(chan struct{}), legs: map[*simLeg]struct{}{},
+ open: map[int]int{}, lastLegEnd: map[int]time.Time{}}
+}
+
+func (m *simModel) violate(format string, args ...any) {
+ m.violations = append(m.violations, fmt.Sprintf(format, args...))
+}
+
+func (m *simModel) ServeHTTP(http.ResponseWriter, *http.Request, registry.Route, http.Handler) bool {
+ m.served.Add(1)
+ return false
+}
+func (m *simModel) RetireExcept(map[string]bool) {}
+func (m *simModel) HeldAdmissible(string) bool {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.state == simAwake
+}
+func (m *simModel) SetHeldWakeHook(f func(string)) {
+ m.mu.Lock()
+ m.hook = f
+ m.mu.Unlock()
+}
+
+var errSimRefused = errors.New("sim: not admissible")
+
+func (m *simModel) AdmitHeldLeg(ctx context.Context, _ registry.Route) (HeldLeg, error) {
+ sid, _ := ctx.Value(simStreamKey{}).(int)
+ for {
+ m.mu.Lock()
+ m.note("admit stream %d in %s", sid, simStateNames[m.state])
+ switch m.state {
+ case simAwake:
+ if err := ctx.Err(); err != nil {
+ m.mu.Unlock()
+ return nil, err
+ }
+ if m.open[sid] > 0 {
+ m.violate("H3: stream %d admitted a leg with %d open", sid, m.open[sid])
+ }
+ c, cancel := context.WithCancel(ctx)
+ l := &simLeg{m: m, sid: sid, ctx: c, cancel: cancel}
+ m.legs[l] = struct{}{}
+ m.open[sid]++
+ m.admitted++
+ m.mu.Unlock()
+ return l, nil
+ case simWaking:
+ // Join the wake, then decide again.
+ ch := m.changed
+ m.mu.Unlock()
+ select {
+ case <-ch:
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ default:
+ m.mu.Unlock()
+ return nil, errSimRefused
+ }
+ }
+}
+
+// transition moves the model to s (s == simAwake from simAwake is a swap).
+func (m *simModel) transition(s simState) {
+ m.mu.Lock()
+ m.note("-> %s", simStateNames[s])
+ was := m.state == simAwake
+ m.state = s
+ close(m.changed)
+ m.changed = make(chan struct{})
+ now := s == simAwake
+ if was {
+ // Away from admissible, or a swap retiring the generation: cancel
+ // every admitted leg, under the lock, before anything else.
+ for l := range m.legs {
+ l.cancel()
+ }
+ }
+ var hook func(string)
+ var delay time.Duration
+ if now {
+ m.since = time.Now()
+ if !was && m.hook != nil && m.rng.Intn(2) == 0 {
+ hook, delay = m.hook, time.Duration(m.rng.Intn(30))*time.Millisecond
+ }
+ }
+ m.mu.Unlock()
+ if hook != nil {
+ time.AfterFunc(delay, func() { hook(heldTestHost) })
+ }
+}
+
+// next picks the lifecycle's next state and how long to stay in it.
+func (m *simModel) next() (simState, time.Duration) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ r := m.rng
+ dwell := func(lo, hi int) time.Duration { return time.Duration(lo+r.Intn(hi-lo)) * time.Millisecond }
+ switch m.state {
+ case simAsleep:
+ return simWaking, dwell(5, 40)
+ case simWaking:
+ if r.Intn(5) == 0 {
+ return simAsleep, dwell(10, 120) // a failed wake
+ }
+ return simAwake, dwell(60, 400)
+ case simAwake:
+ switch r.Intn(5) {
+ case 0:
+ return simAwake, dwell(60, 300) // overlap swap
+ case 1:
+ return simProbeHeld, dwell(5, 80)
+ case 2:
+ return simFenced, dwell(5, 80)
+ default:
+ return simStopping, dwell(5, 30)
+ }
+ case simStopping:
+ return simAsleep, dwell(10, 150)
+ case simProbeHeld:
+ return simAwake, dwell(60, 400) // probe released
+ default: // fenced
+ if r.Intn(2) == 0 {
+ return simAwake, dwell(60, 400) // fence lifted
+ }
+ return simAsleep, dwell(10, 150)
+ }
+}
+
+// simWriter is a concurrency-safe discarding ResponseWriter with Flush.
+type simWriter struct {
+ hdr http.Header
+ n atomic.Int64
+}
+
+func (w *simWriter) Header() http.Header { return w.hdr }
+func (w *simWriter) WriteHeader(int) {}
+func (w *simWriter) Write(b []byte) (int, error) { w.n.Add(int64(len(b))); return len(b), nil }
+func (w *simWriter) Flush() {}
+
+func TestHeldStreamLifecycleSim(t *testing.T) {
+ if testing.Short() {
+ t.Skip("simulation")
+ }
+ const (
+ seeds = 300
+ runFor = 600 * time.Millisecond
+ slack = 25 * time.Millisecond // scheduler jitter under nice -n 19
+ checkEv = 5 * time.Millisecond
+ )
+ cfg := heldTestConfig()
+ cfg.MaxHold = time.Minute
+ cfg.LegHeader = time.Second
+ bound := cfg.Tick + cfg.ReopenSpacing + cfg.BackoffCap + slack
+ var totalAdmitted, totalClosedShort, excused int
+ var maxLag time.Duration
+ for seed := int64(1); seed <= seeds; seed++ {
+ m := newSimModel(seed)
+ rng := rand.New(rand.NewSource(seed * 7919))
+ var rngMu sync.Mutex
+ intn := func(n int) int { rngMu.Lock(); defer rngMu.Unlock(); return rng.Intn(n) }
+ e := &Edge{act: m, held: newHeldSet(cfg)}
+ m.SetHeldWakeHook(e.held.wake)
+ var closedShort atomic.Int64
+ e.held.onFinish = func(_ string, r heldCloseReason) {
+ if r == heldCloseShortLegs {
+ closedShort.Add(1)
+ }
+ }
+ proxy := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ sseHead(w)
+ // Most legs run until cancelled; some end on their own, short or long.
+ var end <-chan time.Time
+ if intn(4) == 0 {
+ end = time.After(time.Duration(intn(300)) * time.Millisecond)
+ }
+ id := 0
+ tick := time.NewTicker(time.Duration(5+intn(30)) * time.Millisecond)
+ defer tick.Stop()
+ for {
+ select {
+ case <-r.Context().Done():
+ return
+ case <-end:
+ return
+ case <-tick.C:
+ id++
+ sseSend(w, fmt.Sprintf("id: %d\ndata: x\n\n", id))
+ }
+ }
+ })
+
+ n := 1 + int(seed%8)
+ start := time.Now()
+ streamStart := make([]atomic.Int64, n)
+ closed := make([]atomic.Bool, n)
+ ctx, cancel := context.WithCancel(context.Background())
+ var wg sync.WaitGroup
+ rt := registry.Route{Host: heldTestHost}
+ for i := 0; i < n; i++ {
+ delay := time.Duration(intn(100)) * time.Millisecond
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ time.Sleep(delay)
+ sctx := context.WithValue(ctx, simStreamKey{}, i)
+ req := httptest.NewRequest(http.MethodGet, "http://"+heldTestHost+"/live?carlos_hold=1", nil).WithContext(sctx)
+ req.Header.Set("Accept", "text/event-stream")
+ streamStart[i].Store(time.Now().UnixNano())
+ e.serveHeld(&simWriter{hdr: http.Header{}}, req, rt, proxy)
+ closed[i].Store(true)
+ }(i)
+ }
+
+ // Drive the lifecycle.
+ stopDrive := make(chan struct{})
+ driveDone := make(chan struct{})
+ go func() {
+ defer close(driveDone)
+ for {
+ s, d := m.next()
+ m.transition(s)
+ select {
+ case <-stopDrive:
+ return
+ case <-time.After(d):
+ }
+ }
+ }()
+
+ // Check the invariants. The checker measures its own oversleep: on
+ // a loaded box under nice -n 19 every goroutine here can lose tens
+ // of milliseconds, and H2 is a bound on the task's logic, not on the
+ // scheduler. An H2 window is excused only by the time the checker
+ // itself was starved inside it.
+ var starved []struct {
+ at time.Time
+ lag time.Duration
+ }
+ starvedIn := func(from time.Time) time.Duration {
+ var sum time.Duration
+ for _, s := range starved {
+ if s.at.After(from) {
+ sum += s.lag
+ }
+ }
+ return sum
+ }
+ for time.Since(start) < runFor {
+ before := time.Now()
+ time.Sleep(checkEv)
+ now := time.Now()
+ if lag := now.Sub(before) - checkEv; lag > time.Millisecond {
+ starved = append(starved, struct {
+ at time.Time
+ lag time.Duration
+ }{now, lag})
+ maxLag = max(maxLag, lag)
+ }
+ if m.served.Load() != 0 {
+ t.Fatalf("seed %d: H1: activator ServeHTTP called", seed)
+ }
+ m.mu.Lock()
+ if m.state == simAwake {
+ for i := 0; i < n; i++ {
+ ss := streamStart[i].Load()
+ if ss == 0 || closed[i].Load() {
+ continue
+ }
+ quiet := m.since
+ if s := time.Unix(0, ss); s.After(quiet) {
+ quiet = s
+ }
+ if le := m.lastLegEnd[i]; le.After(quiet) {
+ quiet = le
+ }
+ if q := now.Sub(quiet); q > bound && m.open[i] == 0 {
+ if ex := starvedIn(quiet); q <= bound+ex {
+ excused++
+ } else {
+ m.violate("H2: stream %d has no leg %v into an admissible window (bound %v, checker starved %v)", i, q, bound, ex)
+ }
+ }
+ }
+ }
+ for i := 0; i < n; i++ {
+ if m.open[i] > 1 {
+ m.violate("H3: stream %d has %d legs open", i, m.open[i])
+ }
+ }
+ v := append([]string(nil), m.violations...)
+ m.mu.Unlock()
+ if len(v) > 0 {
+ close(stopDrive)
+ cancel()
+ t.Fatalf("seed %d (n=%d): %v\nhistory:\n%s", seed, n, v, strings.Join(m.history, "\n"))
+ }
+ }
+
+ close(stopDrive)
+ <-driveDone
+ cancel()
+ waited := make(chan struct{})
+ go func() { wg.Wait(); close(waited) }()
+ select {
+ case <-waited:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("seed %d: stream tasks did not end", seed)
+ }
+ m.mu.Lock()
+ if len(m.legs) != 0 {
+ t.Fatalf("seed %d: %d admitted legs never Done", seed, len(m.legs))
+ }
+ totalAdmitted += m.admitted
+ m.mu.Unlock()
+ if hs := e.held.hosts(); len(hs) != 0 {
+ t.Fatalf("seed %d: held set not empty: %v", seed, hs)
+ }
+ totalClosedShort += int(closedShort.Load())
+ }
+ t.Logf("%d seeds: %d legs admitted, %d streams closed by short legs; H2 checks excused by checker starvation: %d (worst checker oversleep %v)",
+ seeds, totalAdmitted, totalClosedShort, excused, maxLag)
+ if totalAdmitted == 0 {
+ t.Fatal("no leg was ever admitted")
+ }
+}
diff --git a/internal/edge/heldstream_test.go b/internal/edge/heldstream_test.go
new file mode 100644
index 000000000..cac07ce50
--- /dev/null
+++ b/internal/edge/heldstream_test.go
@@ -0,0 +1,582 @@
+package edge
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const heldTestHost = "shop.example.com"
+
+// heldTestConfig is the brief's short config.
+func heldTestConfig() HeldConfig {
+ return HeldConfig{
+ PerHost: 64, PerBox: 4096,
+ MaxHold: 2 * time.Second, Commit: 20 * time.Millisecond, LegHeader: time.Second,
+ WriteDeadline: 30 * time.Millisecond, Tick: 50 * time.Millisecond,
+ ReopenSpacing: 10 * time.Millisecond, ShortLeg: 200 * time.Millisecond, BackoffCap: 100 * time.Millisecond,
+ ShortLegsToClose: 5,
+ }
+}
+
+// scriptLeg is one leg the scripted activator admitted.
+type scriptLeg struct {
+ ctx context.Context
+ cancel context.CancelFunc
+ done atomic.Bool
+}
+
+func (l *scriptLeg) Context() context.Context { return l.ctx }
+func (l *scriptLeg) Done() { l.done.Store(true); l.cancel() }
+
+// scriptActivator admits held legs while asleep is false.
+type scriptActivator struct {
+ asleep atomic.Bool
+ served atomic.Int64
+ admits atomic.Int64
+ mu sync.Mutex
+ legs []*scriptLeg
+}
+
+func (a *scriptActivator) ServeHTTP(http.ResponseWriter, *http.Request, registry.Route, http.Handler) bool {
+ a.served.Add(1)
+ return false
+}
+func (a *scriptActivator) RetireExcept(map[string]bool) {}
+func (a *scriptActivator) AdmitHeldLeg(ctx context.Context, _ registry.Route) (HeldLeg, error) {
+ if a.asleep.Load() {
+ return nil, errors.New("asleep")
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ a.admits.Add(1)
+ c, cancel := context.WithCancel(ctx)
+ l := &scriptLeg{ctx: c, cancel: cancel}
+ a.mu.Lock()
+ a.legs = append(a.legs, l)
+ a.mu.Unlock()
+ return l, nil
+}
+func (a *scriptActivator) HeldAdmissible(string) bool { return !a.asleep.Load() }
+func (a *scriptActivator) SetHeldWakeHook(func(string)) {}
+
+func (a *scriptActivator) lastLeg() *scriptLeg {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if len(a.legs) == 0 {
+ return nil
+ }
+ return a.legs[len(a.legs)-1]
+}
+
+// legSeen is what the fake proxy recorded about one leg request.
+type legSeen struct {
+ at time.Time
+ rawQuery string
+ lastEventID string
+ header http.Header
+}
+
+// scriptProxy serves one leg per call from serve, recording each request.
+type scriptProxy struct {
+ mu sync.Mutex
+ seen []legSeen
+ serve func(n int, w http.ResponseWriter, r *http.Request)
+}
+
+func (p *scriptProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ p.mu.Lock()
+ n := len(p.seen)
+ p.seen = append(p.seen, legSeen{at: time.Now(), rawQuery: r.URL.RawQuery, lastEventID: r.Header.Get("Last-Event-ID"), header: r.Header.Clone()})
+ p.mu.Unlock()
+ p.serve(n, w, r)
+}
+
+func (p *scriptProxy) legs() []legSeen {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return append([]legSeen(nil), p.seen...)
+}
+
+// sseHead writes a 200 identity event-stream head and flushes it.
+func sseHead(w http.ResponseWriter) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.WriteHeader(http.StatusOK)
+ w.(http.Flusher).Flush()
+}
+
+func sseSend(w http.ResponseWriter, s string) {
+ _, _ = io.WriteString(w, s)
+ w.(http.Flusher).Flush()
+}
+
+// heldHarness serves e.serveHeld on an httptest server.
+type heldHarness struct {
+ e *Edge
+ act *scriptActivator
+ proxy *scriptProxy
+ srv *httptest.Server
+ ends chan heldCloseReason
+}
+
+func newHeldHarness(t *testing.T, cfg HeldConfig, serve func(n int, w http.ResponseWriter, r *http.Request)) *heldHarness {
+ t.Helper()
+ h := &heldHarness{act: &scriptActivator{}, proxy: &scriptProxy{serve: serve}, ends: make(chan heldCloseReason, 64)}
+ h.e = &Edge{act: h.act, held: newHeldSet(cfg)}
+ h.e.held.onFinish = func(_ string, r heldCloseReason) { h.ends <- r }
+ rt := registry.Route{Host: heldTestHost}
+ h.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ h.e.serveHeld(w, r, rt, h.proxy)
+ }))
+ return h
+}
+
+func (h *heldHarness) start(t *testing.T) {
+ h.srv.Start()
+ t.Cleanup(h.srv.Close)
+}
+
+func (h *heldHarness) get(t *testing.T, path string, hdr map[string]string) *http.Response {
+ t.Helper()
+ req, _ := http.NewRequest(http.MethodGet, h.srv.URL+path, nil)
+ req.Header.Set("Accept", "text/event-stream")
+ for k, v := range hdr {
+ req.Header.Set(k, v)
+ }
+ resp, err := h.srv.Client().Do(req)
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ t.Cleanup(func() { resp.Body.Close() })
+ return resp
+}
+
+// readFor reads body for d and returns what arrived.
+func readFor(body io.Reader, d time.Duration) (string, error) {
+ var (
+ mu sync.Mutex
+ buf strings.Builder
+ err error
+ )
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ b := make([]byte, 1024)
+ for {
+ n, e := body.Read(b)
+ mu.Lock()
+ buf.Write(b[:n])
+ if e != nil {
+ err = e
+ mu.Unlock()
+ return
+ }
+ mu.Unlock()
+ }
+ }()
+ select {
+ case <-done:
+ case <-time.After(d):
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ return buf.String(), err
+}
+
+func TestHeldAsleepCommitsAndPings(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(int, http.ResponseWriter, *http.Request) { t.Error("proxy called while asleep") })
+ h.act.asleep.Store(true)
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ if resp.StatusCode != 200 || resp.Header.Get("Cache-Control") != "no-store" || resp.Header.Get("Content-Type") != "text/event-stream" {
+ t.Fatalf("status %d headers %v", resp.StatusCode, resp.Header)
+ }
+ body, _ := readFor(resp.Body, 150*time.Millisecond)
+ if !strings.Contains(body, ": ping\n") {
+ t.Fatalf("no heartbeat in %q", body)
+ }
+ if strings.Contains(body, ": ping\n\n") {
+ t.Fatalf("heartbeat followed by a blank line: %q", body)
+ }
+ if h.act.served.Load() != 0 {
+ t.Fatal("activator ServeHTTP called")
+ }
+}
+
+func TestHeldSeedsCursor(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(int, http.ResponseWriter, *http.Request) {})
+ h.act.asleep.Store(true)
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", map[string]string{"Last-Event-ID": "42"})
+ body, _ := readFor(resp.Body, 80*time.Millisecond)
+ if !strings.HasPrefix(body, "id: 42\n\n") {
+ t.Fatalf("body %q does not begin with the cursor seed", body)
+ }
+}
+
+func TestHeldResumeSendsLastEventID(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(n int, w http.ResponseWriter, r *http.Request) {
+ sseHead(w)
+ if n == 0 {
+ sseSend(w, "id: 1\ndata: a\n\n")
+ sseSend(w, "id: 2\ndata: b\n\n")
+ }
+ <-r.Context().Done()
+ })
+ h.start(t)
+ resp := h.get(t, "/live?x=1&carlos_hold=1", nil)
+ br := bufio.NewReader(resp.Body)
+ for _, want := range []string{"id: 1", "data: a", "", "id: 2", "data: b", ""} {
+ line, err := br.ReadString('\n')
+ if err != nil || strings.TrimRight(line, "\n") != want {
+ t.Fatalf("read %q (%v), want %q", line, err, want)
+ }
+ }
+ h.act.asleep.Store(true)
+ h.act.lastLeg().cancel()
+ time.Sleep(30 * time.Millisecond)
+ if n := len(h.proxy.legs()); n != 1 {
+ t.Fatalf("legs while asleep: %d", n)
+ }
+ h.act.asleep.Store(false)
+ h.e.held.wake(heldTestHost)
+ waitFor(t, time.Second, "second leg", func() bool { return len(h.proxy.legs()) == 2 })
+ l := h.proxy.legs()[1]
+ if l.lastEventID != "2" {
+ t.Fatalf("second leg Last-Event-ID %q", l.lastEventID)
+ }
+ if strings.Contains(l.rawQuery, "carlos_hold") || l.rawQuery != "x=1" {
+ t.Fatalf("second leg query %q", l.rawQuery)
+ }
+ if h.proxy.legs()[0].lastEventID != "" {
+ t.Fatalf("first leg carried Last-Event-ID %q", h.proxy.legs()[0].lastEventID)
+ }
+}
+
+func TestHeldRedirectBecomes204(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, "/login", http.StatusSeeOther)
+ })
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ if resp.StatusCode != http.StatusNoContent {
+ t.Fatalf("status %d", resp.StatusCode)
+ }
+ if resp.Header.Get("Location") != "" {
+ t.Fatal("Location passed through")
+ }
+ if h.act.served.Load() != 0 {
+ t.Fatal("activator ServeHTTP called")
+ }
+}
+
+func TestHeldPassThrough401(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/plain")
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = io.WriteString(w, "sign in again")
+ })
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ body, err := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusUnauthorized || string(body) != "sign in again" || err != nil {
+ t.Fatalf("status %d body %q err %v", resp.StatusCode, body, err)
+ }
+}
+
+func TestHeldNonSSE200Is502(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/html")
+ _, _ = io.WriteString(w, "<p>hi</p>")
+ })
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ if resp.StatusCode != http.StatusBadGateway {
+ t.Fatalf("status %d", resp.StatusCode)
+ }
+}
+
+func TestHeldFirstLegHeaders(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "public, max-age=60")
+ w.Header().Set("X-App", "yes")
+ w.Header().Set("Content-Length", "999")
+ sseHead(w)
+ <-r.Context().Done()
+ })
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ if resp.StatusCode != 200 || resp.Header.Get("X-App") != "yes" || resp.Header.Get("Cache-Control") != "no-store" || resp.ContentLength != -1 {
+ t.Fatalf("status %d headers %v len %d", resp.StatusCode, resp.Header, resp.ContentLength)
+ }
+ if got := h.proxy.legs()[0].header.Get("Accept-Encoding"); got != "identity" {
+ t.Fatalf("leg Accept-Encoding %q", got)
+ }
+}
+
+func TestHeldReopenRefusedCloses(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(n int, w http.ResponseWriter, r *http.Request) {
+ if n == 0 {
+ sseHead(w)
+ sseSend(w, "id: 1\ndata: a\n\n")
+ return
+ }
+ w.WriteHeader(http.StatusForbidden)
+ })
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ body, err := readFor(resp.Body, 2*time.Second)
+ if err != io.EOF {
+ t.Fatalf("stream did not end: %v (body %q)", err, body)
+ }
+ if body != "id: 1\ndata: a\n\n" {
+ t.Fatalf("body %q", body)
+ }
+ if r := <-h.ends; r != heldCloseRefused {
+ t.Fatalf("close reason %v", r)
+ }
+}
+
+func TestHeldShortLegsClose(t *testing.T) {
+ cfg := heldTestConfig()
+ h := newHeldHarness(t, cfg, func(n int, w http.ResponseWriter, r *http.Request) {
+ sseHead(w)
+ sseSend(w, fmt.Sprintf("id: %d\ndata: x\n\n", n))
+ })
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ if _, err := readFor(resp.Body, 3*time.Second); err != io.EOF {
+ t.Fatalf("stream did not end: %v", err)
+ }
+ if r := <-h.ends; r != heldCloseShortLegs {
+ t.Fatalf("close reason %v", r)
+ }
+ legs := h.proxy.legs()
+ if len(legs) != cfg.ShortLegsToClose {
+ t.Fatalf("legs %d, want %d", len(legs), cfg.ShortLegsToClose)
+ }
+ for i := 1; i < len(legs); i++ {
+ if gap := legs[i].at.Sub(legs[i-1].at); gap < cfg.ReopenSpacing {
+ t.Fatalf("legs %d and %d started %v apart", i-1, i, gap)
+ }
+ if legs[i].lastEventID != fmt.Sprint(i-1) {
+ t.Fatalf("leg %d Last-Event-ID %q", i, legs[i].lastEventID)
+ }
+ }
+}
+
+func TestHeldOverCapRetry(t *testing.T) {
+ cfg := heldTestConfig()
+ cfg.PerHost = 1
+ h := newHeldHarness(t, cfg, func(int, http.ResponseWriter, *http.Request) {})
+ h.act.asleep.Store(true)
+ h.start(t)
+ first := h.get(t, "/live?carlos_hold=1", nil)
+ if first.StatusCode != 200 {
+ t.Fatalf("first status %d", first.StatusCode)
+ }
+ waitFor(t, time.Second, "first held", func() bool { return len(h.e.held.hosts()) == 1 })
+ before := h.act.admits.Load()
+ second := h.get(t, "/live?carlos_hold=1", nil)
+ body, err := io.ReadAll(second.Body)
+ if err != nil || string(body) != "retry: 30000\n\n" || second.StatusCode != 200 ||
+ second.Header.Get("Content-Type") != "text/event-stream" || second.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("over cap: status %d headers %v body %q err %v", second.StatusCode, second.Header, body, err)
+ }
+ if h.act.admits.Load() != before {
+ t.Fatal("over-cap stream reached the activator")
+ }
+}
+
+func TestHeldDropsCommentOnlyBlocks(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) {
+ sseHead(w)
+ sseSend(w, ": app ping\n\n")
+ sseSend(w, "id: 3\ndata: x\n\n")
+ <-r.Context().Done()
+ })
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ body, _ := readFor(resp.Body, 40*time.Millisecond)
+ if strings.Contains(body, "app ping") || !strings.HasPrefix(body, "id: 3\ndata: x\n\n") {
+ t.Fatalf("body %q", body)
+ }
+}
+
+func TestHeldStripsSidecarHeader(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) {
+ sseHead(w)
+ <-r.Context().Done()
+ })
+ h.start(t)
+ h.get(t, "/live?carlos_hold=1", map[string]string{"X-Carlos-Sidecar": "1", "Connection": "keep-alive, X-Drop", "X-Drop": "1"})
+ waitFor(t, time.Second, "leg", func() bool { return len(h.proxy.legs()) == 1 })
+ hdr := h.proxy.legs()[0].header
+ if hdr.Get("X-Carlos-Sidecar") != "" || hdr.Get("X-Drop") != "" || hdr.Get("Connection") != "" {
+ t.Fatalf("leg headers %v", hdr)
+ }
+}
+
+func TestHeldMaxHoldCloses(t *testing.T) {
+ cfg := heldTestConfig()
+ cfg.MaxHold = 100 * time.Millisecond
+ h := newHeldHarness(t, cfg, func(int, http.ResponseWriter, *http.Request) {})
+ h.act.asleep.Store(true)
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ if _, err := readFor(resp.Body, time.Second); err != io.EOF {
+ t.Fatalf("stream did not end: %v", err)
+ }
+ if r := <-h.ends; r != heldCloseMaxHold {
+ t.Fatalf("close reason %v", r)
+ }
+}
+
+func TestHeldCloseHost(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(int, http.ResponseWriter, *http.Request) {})
+ h.act.asleep.Store(true)
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ waitFor(t, time.Second, "held", func() bool { return len(h.e.held.hosts()) == 1 })
+ h.e.held.closeHost(heldTestHost)
+ if _, err := readFor(resp.Body, time.Second); err != io.EOF {
+ t.Fatalf("stream did not end: %v", err)
+ }
+ if r := <-h.ends; r != heldCloseUnmanaged {
+ t.Fatalf("close reason %v", r)
+ }
+ if len(h.e.held.hosts()) != 0 {
+ t.Fatal("host still held")
+ }
+}
+
+func TestHeldSwapReopensAtOnce(t *testing.T) {
+ cfg := heldTestConfig()
+ cfg.Tick = time.Hour // the tick must not be what reopens
+ h := newHeldHarness(t, cfg, func(n int, w http.ResponseWriter, r *http.Request) {
+ sseHead(w)
+ sseSend(w, fmt.Sprintf("id: %d\ndata: x\n\n", n))
+ <-r.Context().Done()
+ })
+ h.start(t)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ go func() { _, _ = io.Copy(io.Discard, resp.Body) }()
+ for i := 1; i <= 7; i++ {
+ waitFor(t, time.Second, "leg", func() bool { return len(h.proxy.legs()) == i })
+ time.Sleep(5 * time.Millisecond)
+ h.act.lastLeg().cancel() // a swap: admissible throughout
+ }
+ waitFor(t, time.Second, "leg after swaps", func() bool { return len(h.proxy.legs()) == 8 })
+ if len(h.e.held.hosts()) != 1 {
+ t.Fatal("stream closed by swaps")
+ }
+}
+
+func TestHeldHTTP2IdleSurvivesWriteDeadline(t *testing.T) {
+ cfg := heldTestConfig()
+ cfg.Tick = 100 * time.Millisecond
+ cfg.WriteDeadline = 30 * time.Millisecond
+ h := newHeldHarness(t, cfg, func(int, http.ResponseWriter, *http.Request) {})
+ h.act.asleep.Store(true)
+ h.srv.EnableHTTP2 = true
+ h.srv.StartTLS()
+ t.Cleanup(h.srv.Close)
+ resp := h.get(t, "/live?carlos_hold=1", nil)
+ if resp.ProtoMajor != 2 {
+ t.Fatalf("proto %s", resp.Proto)
+ }
+ body, err := readFor(resp.Body, 550*time.Millisecond)
+ if err != nil {
+ t.Fatalf("stream ended: %v (body %q)", err, body)
+ }
+ if n := strings.Count(body, ": ping\n"); n < 4 {
+ t.Fatalf("%d heartbeats in %q", n, body)
+ }
+}
+
+func TestHeldBlockedWriteEnds(t *testing.T) {
+ cfg := heldTestConfig()
+ cfg.MaxHold = time.Minute
+ 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())
+ }
+ })
+ h.start(t)
+ addr := strings.TrimPrefix(h.srv.URL, "http://")
+ conn, err := net.Dial("tcp", addr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ 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.
+ 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):
+ t.Fatal("stream task did not end")
+ }
+ waitFor(t, time.Second, "held set empty", func() bool { return len(h.e.held.hosts()) == 0 })
+}
+
+func TestHeldConfigOnNew(t *testing.T) {
+ e := &Edge{}
+ e.SetHeldConfig(heldTestConfig())
+ if e.held == nil || e.held.cfg != heldTestConfig() {
+ t.Fatal("SetHeldConfig did not replace the held set")
+ }
+ if DefaultHeldConfig.MaxHold != time.Hour || DefaultHeldConfig.Tick != 25*time.Second || DefaultHeldConfig.PerHost != 64 ||
+ DefaultHeldConfig.PerBox != 4096 || DefaultHeldConfig.ShortLegsToClose != 5 {
+ t.Fatalf("DefaultHeldConfig %+v", DefaultHeldConfig)
+ }
+}
+
+func TestStripHoldMarker(t *testing.T) {
+ for _, c := range []struct {
+ in, out string
+ marked bool
+ }{
+ {"a=1&carlos_hold=1&b=%2F", "a=1&b=%2F", true},
+ {"carlos_hold=1", "", true},
+ {"carlos_hold=2", "carlos_hold=2", false},
+ {"x=1", "x=1", false},
+ {"", "", false},
+ {"b=%2f&a=x+y&&carlos_hold=1&c", "b=%2f&a=x+y&&c", true},
+ {"carlos_hold=1&z=%E2%9C%93", "z=%E2%9C%93", true},
+ {"carlos_hold", "carlos_hold", false},
+ } {
+ out, marked := stripHoldMarker(c.in)
+ if out != c.out || marked != c.marked {
+ t.Errorf("stripHoldMarker(%q) = %q, %v; want %q, %v", c.in, out, marked, c.out, c.marked)
+ }
+ }
+}