carlos / platform Public

edge: retry box refusals on a survivor; one snapshot for live (#511 R25, R26)

R26: replicaRoundTrip now reports three outcomes: never written (R22),
refused by the box, or may have reached it. Refused is a stream the box
reset with REFUSED_STREAM (x/net surfaces a peer reset as
http2.StreamError{Code} and never makes that code itself), or one above
the last stream of a graceful GOAWAY (x/net's errClientConnGotGoAway,
matched by its pinned text). The replica transport retries a refused
stream on a survivor whatever the method, and ejects the refusing copy.
Any other reset stays possibly reached. A body of known length up to
64 KiB (region HA §25 H2's bound) is read whole before the first
attempt, so a refused POST whose body was partly sent can be repeated;
a larger body never is.

R25: the transport takes the live copies and the handoff's risen latch
from one prober snapshot (Select, under one hold of the prober lock), so
a first rise can no longer leave an empty, risen set answering 503.

Fable M4: fleetChannelFor counts a channel that has ended or is
draining as not connected. Fable M5: tunnelConnLost documents that
x/net's Closing also covers doNotReuse. fleetProxy answers a refused
stream as a dark fleet (503 with Retry-After). TestTwoBoxFleetEndToEnd's
documented black hole is now a fall-over to the survivor.

Witnesses: TestReplicaFirstRiseAtSelection (503 with the two reads put
back), TestReplicaRefusedStreamBoundary and
TestReplicaRefusedPostServedBySurvivor against the real ClientConn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7428bf8098dd74a3b433cac5f1285fa74c12d72b parent 08da3af
9 files changed, +403 −81
  • internal/edge/edge.go +18 −9
  • internal/edge/fleet_e2e_test.go +11 −22
  • internal/edge/replica_handoff_test.go +70 −0
  • internal/edge/replica_reach_test.go +109 −8
  • internal/edge/replica_retry_test.go +2 −2
  • internal/edge/replicaprober.go +23 −4
  • internal/edge/replicaproxy.go +75 −17
  • internal/edge/replicaproxy_test.go +2 −1
  • internal/edge/tunnel.go +93 −18
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index eb40f7859..9ca5ebcb7 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -4319,16 +4319,22 @@ var errFleetDark = errors.New("edge: fleet has no connected channel")
// or "", and "" answers 503 with Retry-After (errFleetDark) until the box
// reconnects or the console relabels the record.
func fleetChannelFor(fleet, boxLabel string, authoritative bool, hub *TunnelHub) string {
+ // A channel that has ended or is draining (its box began shutting
+ // down, #511 R24) is not connected for this choice (Fable M4): the
+ // bound box's draining channel gives way to the fallback, and the
+ // fallback never picks one.
if boxLabel != "" {
- if bound := fleet + "/" + boxLabel; hub.State(bound) == "connected" {
+ if bound := fleet + "/" + boxLabel; hub.serving(bound) {
return bound
}
}
if authoritative {
return ""
}
- if names := hub.ConnectedOfFleet(fleet); len(names) > 0 {
- return names[0]
+ for _, name := range hub.ConnectedOfFleet(fleet) {
+ if hub.serving(name) {
+ return name
+ }
}
return ""
}
@@ -4363,12 +4369,15 @@ func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *htt
return nil, errFleetDark
}
// A request that never reached a channel that has ended or is
- // draining (a GOAWAY, #511 R24) answers as a dark fleet does,
- // 503 with Retry-After, never the transport's bare 502: a
- // draining box used to answer such requests with its own 503.
- // replicaRoundTrip sends exactly as transportFor would.
- resp, reached, err := hub.replicaRoundTrip(name, req)
- if err != nil && !reached && hub.replicaChannelLost(name) {
+ // draining (a GOAWAY, #511 R24), or that its box refused
+ // unprocessed (R26, R27: the box is shutting down or its app
+ // is down), answers as a dark fleet does, 503 with Retry-After,
+ // never the transport's bare 502: the box used to answer such
+ // requests with its own 503. This row has one box, so nothing
+ // is retried. replicaRoundTrip sends exactly as transportFor
+ // would.
+ resp, reach, err := hub.replicaRoundTrip(name, req)
+ if err != nil && (reach == reachRefused || (reach == reachNotWritten && hub.replicaChannelLost(name))) {
return nil, errFleetDark
}
return resp, err
diff --git a/internal/edge/fleet_e2e_test.go b/internal/edge/fleet_e2e_test.go
index 94a04565f..44fb8604b 100644
--- a/internal/edge/fleet_e2e_test.go
+++ b/internal/edge/fleet_e2e_test.go
@@ -413,31 +413,20 @@ func TestTwoBoxFleetEndToEnd(t *testing.T) {
t.Fatalf("(b) contested acquire returned %T (%v), want a *lease.HeldError", err, err)
}
- // T4 CARRY (observation, not a gate): the edge does not learn a channel
- // died from the channel dying. Nothing unregisters a dead conn except
- // pingLoop — for a fleet channel that is fleetPingEvery (5s) +
- // fleetPingTimeout (5s), so up to ~10s of black hole (spec D7 narrowed it
- // from the static channels' ~25s) in which the hub still reports the box
- // connected and rule 1 keeps dispatching to a corpse instead of falling
- // over to the healthy survivor. That window IS the venue-Wi-Fi failure
- // mode: an app stays down for up to ~10s after its box drops off the
- // network, even though another box could have served it immediately.
- // Observed here without paying the 10s: the assertions below are that the
- // channel is STILL registered and the request does NOT reach box-a.
+ // T4 CARRY, closed by #511 (Fable M4): the hub still has box-b's dead
+ // conn registered until pingLoop reaps it (fleetPingEvery 5s +
+ // fleetPingTimeout 5s), but its wire's closed notice has fired, so
+ // fleetChannelFor no longer counts it as connected: rule 2 sends the
+ // request to the survivor at once, instead of the old ~10s black hole.
+ // The lease above is still what stops a split brain: a real box-a
+ // cannot wake the app until box-b's hold lapses.
if got := hub.State(e2eFleet + "/box-b"); got != "connected" {
- t.Fatalf("(b) hub state for the dead box = %q, want %q — if the hub now reaps eagerly, the black-hole note above is stale and this test should be updated to assert the better behavior", got, "connected")
+ t.Fatalf("(b) hub state for the dead box = %q, want %q (still registered until the ping reaps it)", got, "connected")
}
- resp, err := e2eDo(srv.URL, e2eAppHost, time.Second)
- if err == nil {
- defer resp.Body.Close()
- body, _ := io.ReadAll(resp.Body)
- if resp.StatusCode == http.StatusOK && string(body) == "box-a" {
- t.Fatal("(b) the request fell over to box-a before the dead channel was reaped — good news, but it means the ~10s black-hole window this test documents is gone and the comment above needs rewriting")
- }
- t.Logf("(b) black-hole window: dead-but-registered channel answered %d %q (no fallover)", resp.StatusCode, string(body))
- } else {
- t.Logf("(b) black-hole window: dead-but-registered channel hung until the client gave up (%v)", err)
+ if code, body := e2eGet(t, srv.URL, e2eAppHost); code != http.StatusOK || body != "box-a" {
+ t.Fatalf("(b) a dead-but-registered bound channel: got %d %q, want the survivor's 200 %q", code, body, "box-a")
}
+ t.Log("(b) fell over to the survivor while the dead channel was still registered")
// pingLoop's reap, on demand — CloseChannel is exactly what it calls, so
// the rest of the sequence runs at the speed the fleet would see once the
diff --git a/internal/edge/replica_handoff_test.go b/internal/edge/replica_handoff_test.go
index 373091109..fef692608 100644
--- a/internal/edge/replica_handoff_test.go
+++ b/internal/edge/replica_handoff_test.go
@@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "net/http/httputil"
"strings"
"sync"
"testing"
@@ -230,3 +231,72 @@ func TestReplicaHandoffOnlyForTheServingBox(t *testing.T) {
t.Fatalf("disconnected handoff box: %v", err)
}
}
+
+// replicaTransportOf is the replica transport Reload installed for host.
+func replicaTransportOf(t *testing.T, e *Edge, host string) *replicaTransport {
+ t.Helper()
+ up, ok := e.lookupUpstream(host)
+ if !ok {
+ t.Fatalf("%s has no upstream", host)
+ }
+ var rp *httputil.ReverseProxy
+ switch p := up.proxy.(type) {
+ case assetScrubbedProxy:
+ rp = p.proxy
+ case *httputil.ReverseProxy:
+ rp = p
+ }
+ tr, ok := rp.Transport.(*replicaTransport)
+ if rp == nil || !ok {
+ t.Fatalf("%s is not served by a replica transport: %T", host, up.proxy)
+ }
+ return tr
+}
+
+// TestReplicaFirstRiseAtSelection is R25's witness: the set's first copy
+// rises at the latest point that can matter, right after the transport has
+// read the prober (afterSelect), with the handoff still in place. The
+// request is served (by the replaced row's box, which the one snapshot
+// chose), never 503: before R25 the transport read Live, then Risen, under
+// two locks, and a first rise between them answered "no healthy copy" with
+// a healthy copy up. The next request is the set's.
+func TestReplicaFirstRiseAtSelection(t *testing.T) {
+ f := newHandoffFixture(t)
+ single := registry.Route{Host: "shop.example.com", Kind: registry.KindForward, Region: "fleet/pi", Account: "bab", App: "shop", FleetLabel: "box-00", Stateless: true}
+ if err := f.e.reg.PutForward(single); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ set := single
+ set.FleetLabel = ""
+ set.FleetBoxes, set.Copies, set.ReplicaRevision, set.ReplicaIncarnation = `["box-00","box-01"]`, 2, 1, "life"
+ if err := f.e.reg.PutForward(set); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ replicaSettled(t, f.clock, 2)
+ tr := replicaTransportOf(t, f.e, set.Host)
+ var once sync.Once
+ rose := false
+ tr.afterSelect = func() {
+ once.Do(func() {
+ f.setReady("box-00", true)
+ f.clock.advance(time.Second)
+ replicaSettled(t, f.clock, 4)
+ f.clock.advance(time.Second)
+ replicaSettled(t, f.clock, 6)
+ rose = f.e.replicaProbes.Risen(set.Host, "life") && len(f.e.replicaProbes.Live(set.Host)) == 1
+ })
+ }
+ // TestReplicaFirstRiseAtSelection
+ if code, box := f.get(t); code != 200 || box != "box-00" || !rose {
+ t.Fatalf("a first rise right after selection: %d %q (rose %v), want the serving copy", code, box, rose)
+ }
+ if code, box := f.get(t); code != 200 || box != "box-00" {
+ t.Fatalf("after the rise: %d %q, want the set's live copy", code, box)
+ }
+}
diff --git a/internal/edge/replica_reach_test.go b/internal/edge/replica_reach_test.go
index 40100d259..2276b335c 100644
--- a/internal/edge/replica_reach_test.go
+++ b/internal/edge/replica_reach_test.go
@@ -32,6 +32,11 @@ const (
framerDieOnHeaders = "die-on-headers" // close the wire when a HEADERS frame arrives
framerHangUp = "hang-up" // close the wire once the handshake is done
framerDiesOnPick = "dies-on-pick" // like hang-up, but only once the hub has picked the copy
+ // R26: the box answers a stream's HEADERS with
+ framerRefuses = "refuses" // RST_STREAM REFUSED_STREAM
+ framerResetInternal = "reset-internal" // RST_STREAM INTERNAL_ERROR
+ framerGoAwayBelow = "goaway-below" // a graceful GOAWAY whose last stream is below it
+ framerGoAwayError = "goaway-error" // a GOAWAY with an error code, last stream below it
)
// replicaFramerBox replaces box's channel on hub with a framerBox and points
@@ -51,12 +56,17 @@ func replicaFramerBox(t *testing.T, hub *TunnelHub, p *replicaProber, host, box,
return
}
fr := http2.NewFramer(b, b)
- var wmu sync.Mutex
- write := func(f func() error) {
- // The hub reads only once NewClientConn has flushed, so the
- // box writes from its own goroutine and keeps reading.
- go func() { wmu.Lock(); defer wmu.Unlock(); _ = f() }()
- }
+ // The hub reads only once NewClientConn has flushed, so the box
+ // writes from its own goroutine and keeps reading; one goroutine,
+ // in order, so its SETTINGS is always its first frame.
+ writes := make(chan func() error, 16)
+ defer close(writes)
+ go func() {
+ for f := range writes {
+ _ = f()
+ }
+ }()
+ write := func(f func() error) { writes <- f }
write(func() error { return fr.WriteSettings() })
for {
f, err := fr.ReadFrame()
@@ -75,9 +85,23 @@ func replicaFramerBox(t *testing.T, hub *TunnelHub, p *replicaProber, host, box,
}
case *http2.HeadersFrame:
fb.headers.Add(1)
- if mode == framerDieOnHeaders {
+ id := f.StreamID
+ below := uint32(0) // the last stream the box saw before this one
+ if id > 2 {
+ below = id - 2
+ }
+ switch mode {
+ case framerDieOnHeaders:
b.Close()
return
+ case framerRefuses:
+ write(func() error { return fr.WriteRSTStream(id, http2.ErrCodeRefusedStream) })
+ case framerResetInternal:
+ write(func() error { return fr.WriteRSTStream(id, http2.ErrCodeInternal) })
+ case framerGoAwayBelow:
+ write(func() error { return fr.WriteGoAway(below, http2.ErrCodeNo, nil) })
+ case framerGoAwayError:
+ write(func() error { return fr.WriteGoAway(below, http2.ErrCodeProtocol, nil) })
}
}
}
@@ -161,7 +185,8 @@ func TestReplicaNeverReachedBoundary(t *testing.T) {
}
}
body := &replicaReadCounter{Reader: strings.NewReader("payload")}
- _, reached, err := hub.replicaRoundTrip("pi/box-00", replicaDispatchRequest(t, "POST", body))
+ _, reach, err := hub.replicaRoundTrip("pi/box-00", replicaDispatchRequest(t, "POST", body))
+ reached := reach == reachMaybe
if err == nil {
t.Fatal("a dead or refusing box answered")
}
@@ -276,3 +301,79 @@ func TestReplicaRefusedStreamKeepsHealthyCopy(t *testing.T) {
t.Fatal("a request's own failure ejected healthy copies")
}
}
+
+// TestReplicaRefusedStreamBoundary pins R26's classification against the
+// real x/net ClientConn, with a frame-level box that receives the HEADERS
+// (so R22's never-written proof does not apply) and then answers:
+// - RST_STREAM REFUSED_STREAM: refused (RFC 9113 §8.7);
+// - a graceful GOAWAY whose last stream is below this one: refused (§6.8;
+// x/net aborts it with errGracefulGoAway's text);
+// - RST_STREAM INTERNAL_ERROR, or a GOAWAY with an error code: may have
+// reached, as any other reset.
+func TestReplicaRefusedStreamBoundary(t *testing.T) {
+ for _, c := range []struct {
+ mode string
+ want replicaReach
+ }{
+ {framerRefuses, reachRefused},
+ {framerGoAwayBelow, reachRefused},
+ {framerResetInternal, reachMaybe},
+ {framerGoAwayError, reachMaybe},
+ } {
+ t.Run(c.mode, func(t *testing.T) {
+ hub, p, rt := replicaProxyFixture(t, func(http.ResponseWriter, *http.Request) {}, func(http.ResponseWriter, *http.Request) {})
+ fb := replicaFramerBox(t, hub, p, rt.Host, "box-00", c.mode)
+ _, reach, err := hub.replicaRoundTrip("pi/box-00", replicaDispatchRequest(t, "POST", strings.NewReader("payload")))
+ // TestReplicaRefusedStreamBoundary
+ if err == nil || reach != c.want || fb.headers.Load() != 1 {
+ t.Fatalf("%s: reach %d (%v) with %d HEADERS at the box, want %d", c.mode, reach, err, fb.headers.Load(), c.want)
+ }
+ })
+ }
+}
+
+// TestReplicaRefusedPostServedBySurvivor (R26): a POST whose HEADERS (and
+// body) reached a box that refused it unprocessed is sent to the survivor
+// with its body whole, and the refusing copy leaves the live set; a POST
+// reset any other way is not repeated.
+func TestReplicaRefusedPostServedBySurvivor(t *testing.T) {
+ for _, c := range []struct {
+ mode string
+ repeated bool
+ }{
+ {framerRefuses, true},
+ {framerGoAwayBelow, true},
+ {framerResetInternal, false},
+ } {
+ t.Run(c.mode, func(t *testing.T) {
+ var survivor atomic.Int32
+ hub, p, rt := replicaProxyFixture(t, func(http.ResponseWriter, *http.Request) {}, func(w http.ResponseWriter, r *http.Request) {
+ survivor.Add(1)
+ b, _ := io.ReadAll(r.Body)
+ io.WriteString(w, r.Method+" "+string(b))
+ })
+ fb := replicaFramerBox(t, hub, p, rt.Host, "box-00", c.mode)
+ body := strings.Repeat("x", 32<<10)
+ req := httptest.NewRequest("POST", "https://shop.example.com/", strings.NewReader(body))
+ resp, err := replicaProxy(rt.Host, "pi", p, hub).Transport.RoundTrip(req)
+ if !c.repeated {
+ if err == nil || survivor.Load() != 0 {
+ t.Fatalf("%s: a POST reset after its HEADERS was repeated", c.mode)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("%s: %v", c.mode, err)
+ }
+ got, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ // TestReplicaRefusedPostServedBySurvivor
+ if string(got) != "POST "+body || survivor.Load() != 1 || fb.headers.Load() != 1 {
+ t.Fatalf("%s: survivor answered %d bytes, calls %d, HEADERS at the refusing box %d", c.mode, len(got), survivor.Load(), fb.headers.Load())
+ }
+ if live := p.Live(rt.Host); len(live) != 1 || live[0].Box != "box-01" {
+ t.Fatalf("%s: the refusing copy stayed live: %+v", c.mode, live)
+ }
+ })
+ }
+}
diff --git a/internal/edge/replica_retry_test.go b/internal/edge/replica_retry_test.go
index 68116b69b..5dc21a0d5 100644
--- a/internal/edge/replica_retry_test.go
+++ b/internal/edge/replica_retry_test.go
@@ -38,8 +38,8 @@ func TestReplicaPostIsNotReplayedAfterDispatch(t *testing.T) {
hub, _, _ := replicaProxyFixture(t)
body := &replicaReadCounter{Reader: strings.NewReader("payload")}
req := replicaDispatchRequest(t, "POST", body)
- _, dispatched, err := hub.replicaRoundTrip("pi/missing", req)
- if dispatched || err == nil || body.reads != 0 || body.closed {
+ _, reach, err := hub.replicaRoundTrip("pi/missing", req)
+ if reach != reachNotWritten || err == nil || body.reads != 0 || body.closed {
t.Fatal("missing channel consumed body")
}
})
diff --git a/internal/edge/replicaprober.go b/internal/edge/replicaprober.go
index 9d7e6d60d..efa737220 100644
--- a/internal/edge/replicaprober.go
+++ b/internal/edge/replicaprober.go
@@ -339,13 +339,27 @@ func (p *replicaProber) Snapshot(host string) replicas.Snapshot {
return p.snapshotLocked(rt)
}
func (p *replicaProber) Live(host string) []replicas.Copy {
- var live []replicas.Copy
- for _, c := range p.Snapshot(host).Copies {
- if c.Healthy && !c.ObservedAt.IsZero() && p.clock.Now().Sub(c.ObservedAt) <= replicaProbeFail*replicaProbeInterval+replicaProbeTimeout {
+ live, _ := p.Select(host, "")
+ return live
+}
+
+// Select is Live and Risen(host, incarnation) from one snapshot, under one
+// hold of the prober's lock (R25): record flips a copy's health and its
+// risen latch in the same hold, so no first rise falls between them.
+func (p *replicaProber) Select(host, incarnation string) (live []replicas.Copy, risen bool) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ rt, ok := p.routes[host]
+ if !ok {
+ return nil, false
+ }
+ now := p.clock.Now()
+ for _, c := range p.snapshotLocked(rt).Copies {
+ if c.Healthy && !c.ObservedAt.IsZero() && now.Sub(c.ObservedAt) <= replicaProbeFail*replicaProbeInterval+replicaProbeTimeout {
live = append(live, c)
}
}
- return live
+ return live, incarnation != "" && p.risenLocked(rt, incarnation)
}
// Risen reports whether any copy of host's current set, in incarnation, has
@@ -358,6 +372,11 @@ func (p *replicaProber) Risen(host, incarnation string) bool {
if !ok {
return false
}
+ return p.risenLocked(rt, incarnation)
+}
+
+func (p *replicaProber) risenLocked(rt registry.Route, incarnation string) bool {
+ host := rt.Host
var boxes []string
_ = json.Unmarshal([]byte(rt.FleetBoxes), &boxes)
for _, box := range boxes {
diff --git a/internal/edge/replicaproxy.go b/internal/edge/replicaproxy.go
index 4b6360a34..505d91212 100644
--- a/internal/edge/replicaproxy.go
+++ b/internal/edge/replicaproxy.go
@@ -1,6 +1,7 @@
package edge
import (
+ "bytes"
"context"
"errors"
"io"
@@ -44,6 +45,9 @@ type replicaTransport struct {
// Test seam for the interval between selecting a copy and dispatching
// to it: a channel that dies there was chosen while it was live.
beforeAttempt func(box string)
+ // Test seam right after the one prober snapshot RoundTrip decides from
+ // (R25): a copy's first rise there must not lose the request.
+ afterSelect func()
}
func replicaProxy(host, fleet string, p *replicaProber, hub *TunnelHub) *httputil.ReverseProxy {
@@ -72,11 +76,27 @@ func replicaProxy(host, fleet string, p *replicaProber, hub *TunnelHub) *httputi
func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// Capture once: a request never cycles around or expands its retry budget.
- live := t.p.Live(t.host)
- if len(live) == 0 && t.handoff != nil && !t.p.Risen(t.host, t.handoff.incarnation) {
+ // R25: the live copies and whether the replaced forward row still
+ // serves come from ONE prober snapshot. A copy's first rise flips its
+ // health and its risen latch under the prober's lock together, so the
+ // snapshot shows either no live copy and not risen (the handoff box
+ // serves), or a live copy (the set serves); never an empty set that has
+ // risen since, which would answer 503 with a healthy copy up.
+ incarnation := ""
+ if t.handoff != nil {
+ incarnation = t.handoff.incarnation
+ }
+ live, risen := t.p.Select(t.host, incarnation)
+ if t.afterSelect != nil {
+ t.afterSelect()
+ }
+ if len(live) == 0 && t.handoff != nil && !risen {
return t.handoffRoundTrip(req)
}
- body := replicaBody(req.Body)
+ body, getBody, err := replicaReplayableBody(req)
+ if err != nil {
+ return nil, err
+ }
owned := false
defer func() {
if !owned && body != nil {
@@ -89,7 +109,9 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error)
start := (t.cursor.Add(1) - 1) % uint64(len(live))
last := errReplicaUnavailable
attempts := 0
- var dispatched, anyDispatched bool
+ // dispatched: the last attempt may have reached the box. consumed: it
+ // may have spent the body, so another attempt needs a fresh copy.
+ var dispatched, consumed, anyDispatched bool
var started atomic.Bool
for i := 0; i < len(live); i++ {
if err := req.Context().Err(); err != nil {
@@ -108,11 +130,11 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error)
continue
}
}
- if i > 0 && dispatched && body != nil {
- if req.GetBody == nil {
+ if i > 0 && consumed && body != nil {
+ if getBody == nil {
return nil, &replicaUnrepeatedError{last}
}
- next, err := req.GetBody()
+ next, err := getBody()
if err != nil {
return nil, err
}
@@ -128,7 +150,7 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error)
// Only a replayable read with another live candidate gets a header
// timer. Slow writes and the last attempt retain legacy behavior.
canTimeOut := false
- if replicas.RetryAllowed(req.Method, true, started.Load()) && (body == nil || req.GetBody != nil) {
+ if replicas.RetryAllowed(req.Method, true, started.Load()) && (body == nil || getBody != nil) {
current := t.p.Live(t.host)
for j := i + 1; j < len(live) && !canTimeOut; j++ {
next := live[(int(start)+j)%len(live)]
@@ -198,15 +220,23 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error)
if t.beforeAttempt != nil {
t.beforeAttempt(box)
}
- resp, didDispatch, err := t.hub.replicaRoundTrip(t.fleet+"/"+box, attempt)
+ resp, reach, err := t.hub.replicaRoundTrip(t.fleet+"/"+box, attempt)
if t.afterRoundTrip != nil {
t.afterRoundTrip(ctx)
}
+ bodyRead := view != nil && view.read.Load()
// A body read at all means the headers went first: never "not
- // reached", whatever the transport said.
- dispatched = didDispatch || (view != nil && view.read.Load())
+ // written", whatever the transport said.
+ if reach == reachNotWritten && bodyRead {
+ reach = reachMaybe
+ }
+ // R26: a stream the box refused unprocessed may be sent to another
+ // copy whatever its method; only its body, if the hub sent part of
+ // it, needs a fresh copy (getBody).
+ dispatched = reach == reachMaybe
+ consumed = reach == reachMaybe || bodyRead
anyDispatched = anyDispatched || dispatched
- owned = owned || dispatched
+ owned = owned || consumed
stopTimer()
// Headers already returned by RoundTrip win even if cancellation
// raced them. Never turn a successful response into a proxy 502.
@@ -226,14 +256,15 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error)
}
cancel()
last = err
- if dispatched && body != nil {
+ if consumed && body != nil {
body.Close()
}
// R22: a copy whose connection is gone or refusing streams leaves
- // the set on this failure, not on the later channel-close cleanup.
- // Any other failure (a reset stream, an invalid header) is left to
- // the health probes.
- if t.hub.replicaChannelLost(t.fleet + "/" + box) {
+ // the set on this failure, not on the later channel-close cleanup;
+ // so does one that refused the stream (R26, R27: its box is
+ // draining or its app is down). Any other failure (a reset stream,
+ // an invalid header) is left to the health probes.
+ if reach == reachRefused || t.hub.replicaChannelLost(t.fleet+"/"+box) {
t.p.Eject(t.host, box)
}
if !replicas.RetryAllowed(req.Method, dispatched, responseStarted) {
@@ -246,6 +277,33 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error)
return nil, last
}
+// replicaReplayLimit is the largest request body, of known length, the
+// transport reads whole before its first attempt, so that a stream a box
+// refuses after the hub has sent part of the body can still go to another
+// copy (R26). It is region HA §25's H2 bound for a replayable forward.
+const replicaReplayLimit = 64 << 10
+
+// replicaReplayableBody is the body the attempts send, and how to make a
+// fresh copy of it (nil when none can be made). A body with a GetBody keeps
+// it; one of known length up to replicaReplayLimit is read into memory
+// first; any other (larger, or of unknown length) streams as before, and
+// an attempt that spent part of it is never repeated.
+func replicaReplayableBody(req *http.Request) (io.ReadCloser, func() (io.ReadCloser, error), error) {
+ body := replicaBody(req.Body)
+ if body == nil || req.GetBody != nil || req.ContentLength <= 0 || req.ContentLength > replicaReplayLimit {
+ return body, req.GetBody, nil
+ }
+ buf := make([]byte, req.ContentLength)
+ _, err := io.ReadFull(body, buf)
+ body.Close()
+ if err != nil {
+ return nil, nil, err
+ }
+ getBody := func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(buf)), nil }
+ first, _ := getBody()
+ return replicaBody(first), getBody, nil
+}
+
// handoffRoundTrip serves a request through the forward row the set
// replaced (R23): to that row's own box only, as an authoritative forward
// row would, with no other copy to retry on. The box keeps the copy that was
diff --git a/internal/edge/replicaproxy_test.go b/internal/edge/replicaproxy_test.go
index e05896faf..aff35006d 100644
--- a/internal/edge/replicaproxy_test.go
+++ b/internal/edge/replicaproxy_test.go
@@ -265,7 +265,8 @@ func TestReplicaUpgradeReservationCleanup(t *testing.T) {
req = req.WithContext(withUpgradeAdmission(req.Context(), adm))
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", "websocket")
- _, dispatched, err := h.replicaRoundTrip("pi/box-00", req)
+ _, reach, err := h.replicaRoundTrip("pi/box-00", req)
+ dispatched := reach == reachMaybe
// The parent context is still live: only transport cleanup can release.
if err == nil || !dispatched || heldFor(h.edge, rt.Host) != 0 {
t.Fatal("failed upgrade retained its reservation")
diff --git a/internal/edge/tunnel.go b/internal/edge/tunnel.go
index 345bddd3f..2cea4186c 100644
--- a/internal/edge/tunnel.go
+++ b/internal/edge/tunnel.go
@@ -13,6 +13,7 @@ import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
+ "errors"
"fmt"
"io"
"log"
@@ -142,6 +143,10 @@ type TunnelHub struct {
// and captured the connection a changed hash closes, just before it
// closes that connection.
beforeLinkClose func(name string)
+ // wrapConn is a test seam, nil in production: ServeHTTP passes a
+ // registered channel's raw connection through it, after the 101 and
+ // before the h2 session is built on it.
+ wrapConn func(name string, c net.Conn) net.Conn
// linkSeenWritten is a test seam, nil in production: recordLinkSeen
// calls it after each connection record it writes.
linkSeenWritten func(linkID string, seq uint64, connected bool)
@@ -271,6 +276,9 @@ func (h *TunnelHub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn.Close()
return
}
+ if h.wrapConn != nil {
+ conn = h.wrapConn(name, conn)
+ }
wire := &tunnelWire{Conn: conn, closed: make(chan struct{})}
conn = wire
tr := &http2.Transport{}
@@ -830,10 +838,51 @@ func (h *TunnelHub) matchReplicaBoot(c *tunnelConn, boot string, learn bool) boo
return c.probeBoot == "" || c.probeBoot == boot
}
-// replicaRoundTrip sends req down channel and reports whether it may have
-// reached the box (R22). It reports false only when the request's HEADERS
-// frame was provably never handed to the connection, so the box cannot
-// have seen it:
+// replicaReach is what the hub can prove about a request it tried to send
+// down a tunnel (replicaRoundTrip).
+type replicaReach int
+
+const (
+ // reachNotWritten: the request's HEADERS were never handed to the
+ // connection, so the box cannot have seen it, and its body is untouched
+ // (R22).
+ reachNotWritten replicaReach = iota
+ // reachRefused: the box received the stream and refused it unprocessed
+ // (#511 R26): RST_STREAM REFUSED_STREAM (RFC 9113 §8.7, "not processed
+ // in any way"), or the stream was above the last-stream-id of a
+ // graceful GOAWAY (§6.8). The hub's ClientConn may have sent part of the
+ // body, so a retry needs a fresh copy of it.
+ reachRefused
+ // reachMaybe: anything else; the box may have acted on the request.
+ reachMaybe
+)
+
+// errGracefulGoAway is the message x/net v0.62.0 aborts a stream with when
+// it is above the last-stream-id of a graceful GOAWAY the box sent
+// (transport.go:611, errClientConnGotGoAway, transport_common.go:206). The
+// value is unexported, so it is matched by its text, which
+// TestReplicaRefusedStreamBoundary pins against the real ClientConn. A
+// GOAWAY with an error code aborts streams with another message, which
+// stays reachMaybe.
+const errGracefulGoAway = "http2: Transport received Server's graceful shutdown GOAWAY"
+
+// refusedByBox reports whether err is the box's refusal of the stream:
+// x/net's client surfaces a peer's RST_STREAM as StreamError{Code} (its
+// processResetStream, transport.go:2641), and itself never makes one with
+// REFUSED_STREAM; or the graceful GOAWAY abort above.
+func refusedByBox(err error) bool {
+ var se http2.StreamError
+ if errors.As(err, &se) && se.Code == http2.ErrCodeRefusedStream {
+ return true
+ }
+ return err != nil && err.Error() == errGracefulGoAway
+}
+
+// replicaRoundTrip sends req down channel and reports what the hub can
+// prove about whether it reached the box.
+//
+// reachNotWritten (R22) only when the request's HEADERS frame was provably
+// never handed to the connection:
// - the channel has no connection;
// - the connection's wire had already ended (its closed notice), or its
// ClientConn is closed or closing (a GOAWAY read, as from a draining
@@ -848,32 +897,44 @@ func (h *TunnelHub) matchReplicaBoot(c *tunnelConn, boot string, learn bool) boo
// stream on a closed or GOAWAY'd connection (errClientConnUnusable) is
// this case.
//
-// Everything else may have reached the box: a fired WroteHeaders (even if
-// the write then failed), any failure on a cancelled context (the writer
-// may still be running), stream resets, and every upgrade failure after
-// the closed-notice check, admission refusals included. None of them proves
-// an app did not act. ClientConn.RoundTrip (unlike http2.Transport) never
-// retries. TestReplicaNeverReachedBoundary pins this against the real
-// ClientConn, from both sides of the HEADERS write.
-func (h *TunnelHub) replicaRoundTrip(channel string, req *http.Request) (*http.Response, bool, error) {
+// reachRefused (R26) when no response arrived and the box refused the
+// stream (refusedByBox).
+//
+// Everything else is reachMaybe: a fired WroteHeaders (even if the write
+// then failed) with any other error, any failure on a cancelled context
+// (the writer may still be running), every other reset, and every other
+// upgrade failure after the closed-notice check, admission refusals
+// included. None of them proves an app did not act. ClientConn.RoundTrip
+// (unlike http2.Transport) never retries. TestReplicaNeverReachedBoundary
+// and TestReplicaRefusedStreamBoundary pin this against the real
+// ClientConn.
+func (h *TunnelHub) replicaRoundTrip(channel string, req *http.Request) (*http.Response, replicaReach, error) {
tc := h.channel(channel)
if tc == nil {
- return nil, false, fmt.Errorf("tunnel %q not connected", channel)
+ return nil, reachNotWritten, fmt.Errorf("tunnel %q not connected", channel)
}
if tunnelConnLost(tc) {
- return nil, false, fmt.Errorf("tunnel %q: its connection has ended or takes no new streams", channel)
+ return nil, reachNotWritten, fmt.Errorf("tunnel %q: its connection has ended or takes no new streams", channel)
}
if isUpgradeRequest(req) {
resp, err := h.roundTripUpgrade(channel, req)
- return resp, true, err
+ if err != nil && resp == nil && refusedByBox(err) {
+ return nil, reachRefused, err
+ }
+ return resp, reachMaybe, err
}
var wrote atomic.Bool
ctx := httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{WroteHeaders: func() { wrote.Store(true) }})
resp, err := tc.cc.RoundTrip(req.WithContext(ctx))
- if err != nil && resp == nil && !wrote.Load() && req.Context().Err() == nil && req.Cancel == nil {
- return nil, false, err
+ switch {
+ case err == nil || resp != nil:
+ return resp, reachMaybe, err
+ case !wrote.Load() && req.Context().Err() == nil && req.Cancel == nil:
+ return nil, reachNotWritten, err
+ case refusedByBox(err):
+ return nil, reachRefused, err
}
- return resp, true, err
+ return nil, reachMaybe, err
}
// replicaChannelLost reports whether channel's current connection can carry
@@ -887,8 +948,22 @@ func (h *TunnelHub) replicaChannelLost(channel string) bool {
return c == nil || tunnelConnLost(c)
}
+// serving reports whether name has a connection that can take a new
+// stream: connected, its wire not ended, its ClientConn neither closed nor
+// closing.
+func (h *TunnelHub) serving(name string) bool {
+ c := h.channel(name)
+ return c != nil && !tunnelConnLost(c)
+}
+
// tunnelConnLost reports whether c can carry no new request: its wire's
// closed notice has fired, or its ClientConn is closed or closing.
+// x/net's Closing (v0.62.0 ClientConnState) is broader than a GOAWAY: it
+// is also set by doNotReuse, which a request carrying Connection: close
+// (Request.Close) sets on the whole connection. No caller sends one down a
+// tunnel today (httputil.ReverseProxy clears Close on the outbound
+// request); a direct caller that did would mark its box's channel lost
+// until it reconnects, so none may.
func tunnelConnLost(c *tunnelConn) bool {
select {
case <-c.closed: