carlos / platform Public

edge: retry backhaul once after connection failure

Try one other eligible claim in the destination region after a TCP or TLS connection failure. Mark the failed box suspect for 60 seconds, without removing the only eligible claim or changing namespace ownership.

Share the two-attempt budget with holder follows and fall back to the normal home after a remembered holder fails. Keep post-connect errors terminal. Add production-wired tests for request bodies, eligibility, expiry, upgrades and attempt bounds.
Implemented-by: Astra (codex)
claude pushed by paul@keymail.dev 39417638a7aa9c07474ebf138dca632160ddada5 parent 7ac75f6
9 files changed, +564 −16
  • internal/edge/backhaul_holder.go +30 −10
  • internal/edge/backhaul_holder_wiring_test.go +1 −4
  • internal/edge/backhaul_retry.go +92 −0
  • internal/edge/backhaul_retry_export_test.go +149 −0
  • internal/edge/backhaul_retry_test.go +71 −0
  • internal/edge/backhaul_retry_wiring_test.go +205 −0
  • internal/edge/edge.go +5 −1
  • internal/edge/holderview.go +8 −1
  • internal/edge/homemap.go +3 −0

CI failed — run details

Intent

Attributed to this commit: 26.9 g CO₂e (3,082,229 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2r-fixes, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/edge/backhaul_holder.go b/internal/edge/backhaul_holder.go
index cb33855db..282af0aa5 100644
--- a/internal/edge/backhaul_holder.go
+++ b/internal/edge/backhaul_holder.go
@@ -87,9 +87,15 @@ func (e *Edge) backhaulTarget(host, dial, box string) (string, string) {
now := time.Now()
if ref := e.backhaulHolders.get(host, now); ref != "" {
if addr, ok := e.homes.Load().boxInRegionView(ref, box, now); ok {
+ dial, box = addr, ref
+ } else {
+ e.dropBackhaulHolder(host, ref, "left region view")
+ }
+ }
+ if m := e.homes.Load(); m.backhaulSuspect(box, now) {
+ if addr, ref, ok := m.backhaulAlternative(host, box, now); ok {
return addr, ref
}
- e.dropBackhaulHolder(host, ref, "left region view")
}
return dial, box
}
@@ -116,13 +122,14 @@ func (t backhaulHolderTransport) RoundTrip(r *http.Request) (*http.Response, err
return resp, nil
}
-func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dial, box string, key []byte, follow bool) {
- var nextDial, nextRef string
+func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dial, box string, key []byte, retry bool) {
+ var nextDial, nextRef, nextReason string
// Only connection failures disprove a hint. A canceled client or an
// error after connecting says nothing about which box holds the lease.
- var connectFailed atomic.Bool
+ var connectFailed, connected atomic.Bool
+ original := r
r = r.WithContext(httptrace.WithClientTrace(r.Context(), &httptrace.ClientTrace{
- GotConn: func(httptrace.GotConnInfo) { connectFailed.Store(false) },
+ GotConn: func(httptrace.GotConnInfo) { connected.Store(true) },
ConnectDone: func(_, _ string, err error) {
if err != nil {
connectFailed.Store(true)
@@ -155,8 +162,8 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
}
// HTTP/2 supplies a body object even when the request has no body.
noBody := r.ContentLength == 0 && len(r.TransferEncoding) == 0
- if follow && noBody && (r.Method == http.MethodGet || r.Method == http.MethodHead || isUpgradeRequest(r)) {
- nextDial, nextRef = addr, ref
+ if retry && noBody && (r.Method == http.MethodGet || r.Method == http.MethodHead || isUpgradeRequest(r)) {
+ nextDial, nextRef, nextReason = addr, ref, "holder"
return errBackhaulHolder
}
return nil
@@ -165,8 +172,18 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
if errors.Is(err, errBackhaulHolder) {
return
}
- if connectFailed.Load() && r.Context().Err() == nil {
+ var dialErr *forwardConnectError
+ if !connected.Load() && (connectFailed.Load() || errors.As(err, &dialErr)) && r.Context().Err() == nil {
e.dropBackhaulHolder(host, box, "connect failure")
+ m := e.homes.Load()
+ now := time.Now()
+ m.markBackhaulSuspect(box, now)
+ if retry {
+ if addr, ref, ok := m.backhaulAlternative(host, box, now); ok {
+ nextDial, nextRef, nextReason = addr, ref, "connect fallback"
+ return
+ }
+ }
}
e.logThrottled("backhaul-error "+box, fmt.Sprintf("backhaul %s to %s (%s): %v", host, box, dial, err))
w.WriteHeader(http.StatusBadGateway)
@@ -175,7 +192,10 @@ func (e *Edge) backhaulAttempt(w http.ResponseWriter, r *http.Request, host, dia
// The refused hop releases its capacity slot before the holder starts a
// response that may stream or remain upgraded indefinitely.
if nextRef != "" {
- e.logThrottled("backhaul-holder-follow "+nextRef, fmt.Sprintf("backhaul following holder for %s: %s to %s", host, box, nextRef))
- e.backhaulAttempt(w, r, host, nextDial, nextRef, key, false)
+ e.logThrottled("backhaul-retry "+nextRef, fmt.Sprintf("backhaul %s for %s: %s to %s", nextReason, host, box, nextRef))
+ // First attempt plus one retry, at most two attempts total. A connect
+ // fallback and a §6.5 holder follow spend the same retry budget.
+ // Start with the original context so trace callbacks cannot accumulate.
+ e.backhaulAttempt(w, original, host, nextDial, nextRef, key, false)
}
}
diff --git a/internal/edge/backhaul_holder_wiring_test.go b/internal/edge/backhaul_holder_wiring_test.go
index 264602913..8e2b0485b 100644
--- a/internal/edge/backhaul_holder_wiring_test.go
+++ b/internal/edge/backhaul_holder_wiring_test.go
@@ -234,9 +234,6 @@ func TestBackhaulHolderDropsMemory(t *testing.T) {
}
status, _, body := s.Request(t, "POST", "/", "once")
want := 503
- if mode == "dial failure" || mode == "tls failure" {
- want = 502
- }
if status != want {
t.Fatalf("failed holder: %d %q, want %d", status, body, want)
}
@@ -250,7 +247,7 @@ func TestBackhaulHolderDropsMemory(t *testing.T) {
}
a, _ := s.Counts()
expected := int64(2)
- if mode == "left view" || mode == "stale" {
+ if mode == "left view" || mode == "stale" || mode == "dial failure" || mode == "tls failure" {
expected = 3
}
if a != expected {
diff --git a/internal/edge/backhaul_retry.go b/internal/edge/backhaul_retry.go
new file mode 100644
index 000000000..22e0bfeea
--- /dev/null
+++ b/internal/edge/backhaul_retry.go
@@ -0,0 +1,92 @@
+package edge
+
+import (
+ "slices"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+)
+
+const backhaulSuspectTTL = 60 * time.Second
+const backhaulSuspectLimit = 50_000
+
+func (m *homeMap) markBackhaulSuspect(box string, now time.Time) {
+ if m == nil || box == "" {
+ return
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.backhaulSuspects == nil {
+ m.backhaulSuspects = make(map[string]time.Time)
+ }
+ if _, exists := m.backhaulSuspects[box]; !exists && len(m.backhaulSuspects) >= backhaulSuspectLimit {
+ // Evict the earliest expiry, including any already expired entry.
+ var oldest string
+ var until time.Time
+ for ref, expiry := range m.backhaulSuspects {
+ if oldest == "" || expiry.Before(until) {
+ oldest, until = ref, expiry
+ }
+ }
+ delete(m.backhaulSuspects, oldest)
+ }
+ m.backhaulSuspects[box] = now.Add(backhaulSuspectTTL)
+}
+
+func (m *homeMap) backhaulSuspect(box string, now time.Time) bool {
+ if m == nil {
+ return false
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ until, ok := m.backhaulSuspects[box]
+ if ok && !now.Before(until) {
+ delete(m.backhaulSuspects, box)
+ return false
+ }
+ return ok
+}
+
+// backhaulAlternative retains namespace authority while excluding a failed
+// box from service. All candidates belong to the destination's region view,
+// and the resolver still requires the same owner, name, class and target.
+func (m *homeMap) backhaulAlternative(host, failed string, now time.Time) (string, string, bool) {
+ if m == nil || m.self == "" {
+ return "", "", false
+ }
+ snap := m.snapshot()
+ original := resolveHomeName(host, nil, false, snap.hosts)
+ if original.State != edgesfile.NameDialable {
+ return "", "", false
+ }
+ owner := original.Authority
+ claims := slices.Clone(snap.hosts[owner.Name].claims)
+ // A closed wildcard of another owner may have lost to this serving
+ // wildcard. Keep that ownership decision when filtering candidates.
+ claims = slices.DeleteFunc(claims, func(c edgesfile.NameClaim) bool {
+ return c != owner && (c.Name != owner.Name || c.Class != owner.Class ||
+ c.Account == "" || c.App == "" || c.Account != owner.Account ||
+ c.App != owner.App || c.TargetHost != owner.TargetHost)
+ })
+ for i := range claims {
+ c := &claims[i]
+ dial, valid := m.boxInRegionSnapshot(snap, c.Box, failed, now)
+ c.Eligible = c.Eligible && c.Box != failed && valid
+ c.Dial = dial
+ }
+ // Resolve the matched name literally, including a wildcard, so excluding
+ // a box cannot select a different wildcard owner through eligibility.
+ chosen := edgesfile.ResolveNameAuthority(original.Authority.Name, nil, claims)
+ if chosen.State != edgesfile.NameDialable {
+ return "", "", false
+ }
+ for i := range claims {
+ if m.backhaulSuspect(claims[i].Box, now) {
+ claims[i].Eligible = false
+ }
+ }
+ if preferred := edgesfile.ResolveNameAuthority(original.Authority.Name, nil, claims); preferred.State == edgesfile.NameDialable {
+ chosen = preferred
+ }
+ return chosen.Serving.Dial, chosen.Serving.Box, true
+}
diff --git a/internal/edge/backhaul_retry_export_test.go b/internal/edge/backhaul_retry_export_test.go
new file mode 100644
index 000000000..01a948d9f
--- /dev/null
+++ b/internal/edge/backhaul_retry_export_test.go
@@ -0,0 +1,149 @@
+package edge
+
+import (
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// FailBackhaulDial leaves the real transport and its trace events in place.
+// The dial seam sends the attempt to a closed loopback listener.
+func (s *BackhaulHolderScene) FailBackhaulDial(t *testing.T, holder bool) *atomic.Int64 {
+ t.Helper()
+ ip := "127.0.0.1"
+ if holder {
+ ip = "127.0.0.2"
+ }
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ addr := ln.Addr().String()
+ ln.Close()
+ tr := s.sender.edge.backhaulTransport(ip)
+ tr.CloseIdleConnections()
+ calls := new(atomic.Int64)
+ tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ calls.Add(1)
+ var d net.Dialer
+ return d.DialContext(ctx, network, addr)
+ }
+ return calls
+}
+
+func (s *BackhaulHolderScene) EchoHolder(t *testing.T) {
+ t.Helper()
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+ fmt.Fprintf(w, "%s|%s", r.Method, b)
+ }))
+ t.Cleanup(app.Close)
+ if err := s.holder.reg.Upsert(registry.Route{Host: HAForwardHost, Kind: "service", Addr: app.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.holder.edge.Reload(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+type backhaulBrokenWrite struct{ net.Conn }
+
+func (c backhaulBrokenWrite) Write([]byte) (int, error) { return 0, io.ErrClosedPipe }
+
+func (s *BackhaulHolderScene) FailBackhaulAfterConnect(t *testing.T) *atomic.Int64 {
+ t.Helper()
+ tr := s.sender.edge.backhaulTransport("127.0.0.1")
+ tr.CloseIdleConnections()
+ calls := new(atomic.Int64)
+ tr.DialTLSContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ calls.Add(1)
+ d := tls.Dialer{Config: &tls.Config{ServerName: HAForwardHost, RootCAs: backhaulRootCAs, MinVersion: tls.VersionTLS12}}
+ c, err := d.DialContext(ctx, network, s.first.tlsAddr)
+ if err != nil {
+ return nil, err
+ }
+ return backhaulBrokenWrite{c}, nil
+ }
+ return calls
+}
+
+func (s *BackhaulHolderScene) ExpireBackhaulSuspects() {
+ m := s.sender.homes
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for ref := range m.backhaulSuspects {
+ m.backhaulSuspects[ref] = time.Now().Add(-time.Nanosecond)
+ }
+}
+
+func (s *BackhaulHolderScene) FirstTLSFailure() {
+ tr := s.sender.edge.backhaulTransport("127.0.0.1")
+ tr.CloseIdleConnections()
+ tr.TLSClientConfig = tr.TLSClientConfig.Clone()
+ tr.TLSClientConfig.RootCAs = x509.NewCertPool()
+}
+
+func (s *BackhaulHolderScene) RetryHolderClaim(t *testing.T, field string, value any) {
+ t.Helper()
+ data, _, err := s.store.Get(t.Context(), "control/edges/betty.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f map[string]any
+ if err := json.Unmarshal(data, &f); err != nil {
+ t.Fatal(err)
+ }
+ claim := f["hosts"].(map[string]any)[HAForwardHost].(map[string]any)
+ claim[field] = value
+ s.HolderFile(t, "hosts", map[string]any{HAForwardHost: claim})
+}
+
+type backhaulBrokenRead struct {
+ net.Conn
+ wrote chan struct{}
+ once sync.Once
+ bytes *atomic.Int64
+}
+
+func (c *backhaulBrokenRead) Write(b []byte) (int, error) {
+ n, err := c.Conn.Write(b)
+ c.bytes.Add(int64(n))
+ c.once.Do(func() { close(c.wrote) })
+ return n, err
+}
+func (c *backhaulBrokenRead) Read([]byte) (int, error) {
+ <-c.wrote
+ return 0, io.ErrUnexpectedEOF
+}
+func (s *BackhaulHolderScene) FailBackhaulAfterWrite(t *testing.T) (*atomic.Int64, *atomic.Int64) {
+ t.Helper()
+ tr := s.sender.edge.backhaulTransport("127.0.0.1")
+ tr.CloseIdleConnections()
+ calls, written := new(atomic.Int64), new(atomic.Int64)
+ tr.DialTLSContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ calls.Add(1)
+ d := tls.Dialer{Config: &tls.Config{ServerName: HAForwardHost, RootCAs: backhaulRootCAs, MinVersion: tls.VersionTLS12}}
+ c, err := d.DialContext(ctx, network, s.first.tlsAddr)
+ if err != nil {
+ return nil, err
+ }
+ return &backhaulBrokenRead{Conn: c, wrote: make(chan struct{}), bytes: written}, nil
+ }
+ return calls, written
+}
diff --git a/internal/edge/backhaul_retry_test.go b/internal/edge/backhaul_retry_test.go
new file mode 100644
index 000000000..27bc8eba0
--- /dev/null
+++ b/internal/edge/backhaul_retry_test.go
@@ -0,0 +1,71 @@
+package edge
+
+import (
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestBackhaulSuspectBounds(t *testing.T) {
+ m := &homeMap{}
+ now := time.Now()
+ m.markBackhaulSuspect("first", now)
+ if !m.backhaulSuspect("first", now.Add(60*time.Second-time.Nanosecond)) {
+ t.Fatal("suspect expired before 60 seconds")
+ }
+ if m.backhaulSuspect("first", now.Add(60*time.Second)) {
+ t.Fatal("suspect survived exact 60-second boundary")
+ }
+ for i := 0; i < 50_000; i++ {
+ m.markBackhaulSuspect(fmt.Sprint(i), now.Add(time.Duration(i)))
+ }
+ m.markBackhaulSuspect("0", now.Add(time.Second))
+ m.markBackhaulSuspect("extra", now.Add(2*time.Second))
+ if len(m.backhaulSuspects) != 50_000 || m.backhaulSuspect("1", now) || !m.backhaulSuspect("0", now) {
+ t.Fatal("suspect cap or refresh eviction order changed")
+ }
+}
+
+func TestBackhaulSuspectConcurrent(t *testing.T) {
+ m := &homeMap{}
+ now := time.Now()
+ var wg sync.WaitGroup
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for j := 0; j < 200; j++ {
+ ref := fmt.Sprint(j)
+ m.markBackhaulSuspect(ref, now)
+ m.backhaulSuspect(ref, now)
+ m.backhaulSuspect(ref, now.Add(time.Minute))
+ }
+ }()
+ }
+ wg.Wait()
+ if len(m.backhaulSuspects) > 200 {
+ t.Fatal("suspect map grew beyond distinct references")
+ }
+}
+
+func TestBackhaulFallbackWildcardAuthority(t *testing.T) {
+ store := release.NewDirStore(t.TempDir())
+ for _, ref := range []string{"annie", "betty", "closed"} {
+ admitted, app, stamp := true, "shop", 0
+ if ref == "closed" {
+ admitted, app, stamp = false, "other", 100
+ }
+ putJSON(t, store, "control/edges/"+ref+".json", fmt.Sprintf(`{"v":1,"box":%q,"eip":"127.0.0.1","region":"eu","placement":"p","data_bucket":"data","secrets_key_fp":"fp","box_role":"serve","admitted":%t,"drained":false,"generation":%q,"hosts":{"*.test":{"role":"home","account":"acct","app":%q,"stamp":%d}}}`, ref, admitted, time.Now().Format(time.RFC3339Nano), app, stamp))
+ }
+ m := newHomeMap(store, "sender")
+ refreshHomeMap(t, m)
+ if _, ref, ok := m.Home("app.test"); !ok || ref != "annie" {
+ t.Fatalf("normal home=%s %t", ref, ok)
+ }
+ if _, ref, ok := m.backhaulAlternative("app.test", "annie", time.Now()); !ok || ref != "betty" {
+ t.Fatalf("alternate=%s %t, want betty under original wildcard owner", ref, ok)
+ }
+}
diff --git a/internal/edge/backhaul_retry_wiring_test.go b/internal/edge/backhaul_retry_wiring_test.go
new file mode 100644
index 000000000..3a7e9207d
--- /dev/null
+++ b/internal/edge/backhaul_retry_wiring_test.go
@@ -0,0 +1,205 @@
+package edge_test
+
+import (
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+func TestBackhaulConnectFallback(t *testing.T) {
+ for _, method := range []string{"GET", "POST", "PUT", "PATCH", "DELETE"} {
+ t.Run(method, func(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ s.EchoHolder(t)
+ failed := s.FailBackhaulDial(t, false)
+ payload := ""
+ if method != "GET" {
+ payload = "send this once"
+ }
+ status, _, body := s.Request(t, method, "/", payload)
+ if status != 200 || body != method+"|"+payload {
+ t.Fatalf("fallback: %d %q, want intact %s body at second box", status, body, method)
+ }
+ if a, b := s.Counts(); a != 0 || b != 1 || failed.Load() != 1 {
+ t.Fatalf("requests=%d/%d failed dials=%d, want 0/1 and 1", a, b, failed.Load())
+ }
+ status, _, body = s.Request(t, method, "/", payload)
+ if status != 200 || body != method+"|"+payload || failed.Load() != 1 {
+ t.Fatalf("suspect preference: %d %q failed dials=%d", status, body, failed.Load())
+ }
+ })
+ }
+}
+
+func TestBackhaulNoFallbackAfterConnect(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ failed := s.FailBackhaulAfterConnect(t)
+ for i := int64(1); i <= 2; i++ {
+ status, _, body := s.Request(t, "POST", "/", "once")
+ if status != 502 {
+ t.Fatalf("after connect: %d %q, want 502", status, body)
+ }
+ if _, b := s.Counts(); b != 0 || failed.Load() != i {
+ t.Fatalf("holder requests=%d dials=%d, want 0 and %d; no retry or suspicion after connect", b, failed.Load(), i)
+ }
+ }
+}
+
+func TestBackhaulFallbackAttemptBound(t *testing.T) {
+ t.Run("fallback cannot follow", func(t *testing.T) {
+ svc, rt, bucket, second := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ s.HolderActivator(t, second("annie"), rt)
+ failed := s.FailBackhaulDial(t, false)
+ status, headers, body := s.Request(t, "GET", "/", "")
+ if status != 503 || headers.Get("X-Carlos-Holder") != "annie" {
+ t.Fatalf("second answer: %d %v %q", status, headers, body)
+ }
+ if a, b := s.Counts(); a != 0 || b != 1 || failed.Load() != 1 {
+ t.Fatalf("requests=%d/%d failed dials=%d, want two attempts total", a, b, failed.Load())
+ }
+ })
+ t.Run("follow cannot fall back", func(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ failed := s.FailBackhaulDial(t, true)
+ status, _, body := s.Request(t, "GET", "/", "")
+ if status != 502 {
+ t.Fatalf("second answer: %d %q", status, body)
+ }
+ if a, b := s.Counts(); a != 1 || b != 0 || failed.Load() != 1 {
+ t.Fatalf("requests=%d/%d failed dials=%d, want two attempts total", a, b, failed.Load())
+ }
+ })
+ t.Run("two dial failures", func(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ first, second := s.FailBackhaulDial(t, false), s.FailBackhaulDial(t, true)
+ status, _, body := s.Request(t, "POST", "/", "once")
+ if status != 502 || first.Load() != 1 || second.Load() != 1 {
+ t.Fatalf("answer=%d %q dials=%d/%d, want 502 and 1/1", status, body, first.Load(), second.Load())
+ }
+ })
+}
+
+func TestBackhaulRememberedConnectFallback(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ if status, _, _ := s.Request(t, "GET", "/", ""); status != 200 {
+ t.Fatal(status)
+ }
+ s.FirstApp(t)
+ failed := s.FailBackhaulDial(t, true)
+ status, _, body := s.Request(t, "POST", "/", "once")
+ if status != 200 || body != "first|"+rt.Host+"|/" {
+ t.Fatalf("normal home fallback: %d %q", status, body)
+ }
+ s.Request(t, "POST", "/", "once")
+ if a, b := s.Counts(); a != 3 || b != 1 || failed.Load() != 1 {
+ t.Fatalf("requests=%d/%d failed dials=%d, want 3/1 and 1", a, b, failed.Load())
+ }
+}
+
+func TestBackhaulSuspectExpires(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ failed := s.FailBackhaulDial(t, false)
+ for i := 0; i < 2; i++ {
+ if status, _, _ := s.Request(t, "GET", "/", ""); status != 200 {
+ t.Fatal(status)
+ }
+ }
+ if failed.Load() != 1 {
+ t.Fatalf("suspect dialed %d times", failed.Load())
+ }
+ s.ExpireBackhaulSuspects()
+ if status, _, _ := s.Request(t, "GET", "/", ""); status != 200 {
+ t.Fatal(status)
+ }
+ if failed.Load() != 2 {
+ t.Fatalf("expired suspect dialed %d times, want 2", failed.Load())
+ }
+}
+
+func TestBackhaulTLSConnectFallback(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ s.EchoHolder(t)
+ s.FirstTLSFailure()
+ status, _, body := s.Request(t, "POST", "/", "once")
+ if status != 200 || body != "POST|once" {
+ t.Fatalf("TLS fallback: %d %q", status, body)
+ }
+ if a, b := s.Counts(); a != 0 || b != 1 {
+ t.Fatalf("requests=%d/%d", a, b)
+ }
+}
+
+func TestBackhaulFallbackViewRefusals(t *testing.T) {
+ for _, tc := range []struct {
+ name, field string
+ value any
+ claim bool
+ }{
+ {"region", "region", "other", false}, {"placement", "placement", "elsewhere", false},
+ {"null placement", "placement", nil, false}, {"bucket", "data_bucket", "other", false},
+ {"key", "secrets_key_fp", "other", false}, {"booting", "box_role", "booting", false},
+ {"unadmitted", "admitted", false, false}, {"drained", "drained", true, false},
+ {"stale", "generation", time.Now().Add(-16 * time.Minute).Format(time.RFC3339), false},
+ {"future", "generation", time.Now().Add(2 * time.Minute).Format(time.RFC3339), false},
+ {"no dial", "eip", "", false}, {"no claim", "hosts", map[string]any{}, false},
+ {"other account", "account", "other", true}, {"other app", "app", "other", true},
+ {"other class", "alias", true, true}, {"other target", "target_host", "other.test", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ if tc.claim {
+ s.RetryHolderClaim(t, tc.field, tc.value)
+ } else {
+ s.HolderFile(t, tc.field, tc.value)
+ }
+ failed := s.FailBackhaulDial(t, false)
+ for i := int64(1); i <= 2; i++ {
+ status, _, body := s.Request(t, "POST", "/", "once")
+ if status != 502 {
+ t.Fatalf("no eligible fallback: %d %q", status, body)
+ }
+ if a, b := s.Counts(); a != 0 || b != 0 || failed.Load() != i {
+ t.Fatalf("requests=%d/%d failed dials=%d, want only remaining claim on request %d", a, b, failed.Load(), i)
+ }
+ }
+ })
+ }
+}
+
+func TestBackhaulConnectFallbackUpgrade(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ failed := s.FailBackhaulDial(t, false)
+ s.Upgrade(t)
+ if a, b := s.Counts(); a != 0 || b != 1 || failed.Load() != 1 {
+ t.Fatalf("requests=%d/%d failed dials=%d", a, b, failed.Load())
+ }
+}
+
+func TestBackhaulNoFallbackAfterWrite(t *testing.T) {
+ for _, method := range []string{"GET", "POST"} {
+ t.Run(method, func(t *testing.T) {
+ svc, rt, bucket, _ := backhaulHeldService(t, "betty")
+ s := edge.NewBackhaulHolderScene(t, bucket, svc, rt)
+ s.FirstApp(t)
+ calls, written := s.FailBackhaulAfterWrite(t)
+ status, _, body := s.Request(t, method, "/", "")
+ if status != 502 || calls.Load() != 1 || written.Load() == 0 {
+ t.Fatalf("answer=%d %q dials=%d bytes=%d", status, body, calls.Load(), written.Load())
+ }
+ if _, b := s.Counts(); b != 0 {
+ t.Fatalf("holder requests=%d after request bytes sent", b)
+ }
+ })
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 639ee2f3e..0b3b92c47 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -4352,7 +4352,11 @@ func (e *Edge) backhaulTransport(eip string) *http.Transport {
// authority, which is the HOST (for SNI, verification and pooling) and
// never where the bytes go. The home edge is at its EIP.
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
- return dialer.DialContext(ctx, network, net.JoinHostPort(eip, backhaulPort))
+ conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(eip, backhaulPort))
+ if err != nil {
+ return nil, &forwardConnectError{err}
+ }
+ return conn, nil
},
// No ServerName: the stdlib fills it from the outbound URL's authority,
// which is exactly the host being asked for. RootCAs nil is the system
diff --git a/internal/edge/holderview.go b/internal/edge/holderview.go
index fef7bbad8..7c9284ada 100644
--- a/internal/edge/holderview.go
+++ b/internal/edge/holderview.go
@@ -67,9 +67,16 @@ func (m *homeMap) boxInRegionView(ref, destination string, now time.Time) (strin
if m == nil || ref == "" || ref == "none" || ref == m.self {
return "", false
}
+ return m.boxInRegionSnapshot(m.snapshot(), ref, destination, now)
+}
+
+func (m *homeMap) boxInRegionSnapshot(snap *homeSnapshot, ref, destination string, now time.Time) (string, bool) {
+ if ref == "" || ref == "none" || ref == m.self {
+ return "", false
+ }
var own, target, peer edgesFileView
var ownKnown, targetKnown, peerKnown bool
- for _, f := range m.snapshot().files {
+ for _, f := range snap.files {
if f.Box == m.self {
own, ownKnown = f, true
}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 6643074d5..2de1286d8 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -337,6 +337,9 @@ type homeMap struct {
// logThrottled to inherit the cap from, so it gets its own.
staleHopN map[string]int
+ // Backhaul suspicion changes preference only; it never removes a claim.
+ backhaulSuspects map[string]time.Time // guarded by mu
+
// The mirrored mesh keys, read on the same refresh. Replaced only on a
// SUCCESSFUL load: a bucket blip leaves the last good key verifying hops,
// exactly as a blip leaves the last good host map routing them.