edge: follow and remember cross-region holders
Consume one validated holder refusal before sending the final response. Keep ten-minute host hints with a 50,000-entry cap for later requests. Validate the holder against the destination region and release the first hop's capacity slot before starting the holder attempt. Cover real activator refusals, replay safety, invalidation, upgrades, header spoofing, cache bounds and the original-behavior mutation.
Implemented-by: Astra (codex)
internal/edge/backhaul_holder.go+146 −0internal/edge/backhaul_holder_export_test.go+177 −0internal/edge/backhaul_holder_test.go+63 −0internal/edge/backhaul_holder_wiring_test.go+251 −0internal/edge/edge.go+3 −1internal/edge/holderview.go+37 −0
Intent
<task-notification> <task-id>b7duan189</task-id> <tool-use-id>toolu_01VsMK7vFSPSnLjFJiGb11kb</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/87a21814-5655-4016-9e7e-41935ee8e96e/tasks/b7duan189.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/.superpowers/sdd/2026-11-06-region-ha-g2r-fixes; echo "Task 4: dispatched (Astra, parallel with T1 review; base $(git -C $W/../../.. rev-parse --short HEAD))" >> $W/progress.md; for i in $(seq 1 340); do [ -f $W/t4.done ] && break; sleep 10; done; cat $W/t4.done 2>/dev/null; tail -2 $W/t4.log" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a62270437c0d3df52</task-id> <tool-use-id>toolu_01Nv7D42NhWHjBECoDALbiLV</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/87a21814-5655-4016-9e7e-41935ee8e96e/tasks/a62270437c0d3df52.output</output-file> <status>completed</status> <summary>Agent "Review Task 4 W3 departure nudge" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Task 4 review (commit 68082f7b, W3 departure inventory nudge)** **Spec compliance: ✅ on the letter, ❌ on one binding constraint.** The constraint is "no unbounded rebuild loop" (Important #1 below). - **I3 preserved ✅.** `FreshAfter` is unchanged, at internal/provision/departure_inventory.go:25. The nudge only calls the existing `recordViewBackstop`. `sourceStarted` is taken inside `rebuildLocked`, after `ObservedAt` was set in the same pass, so the freshness is real. A stale state still returns to retry. `complete` still resets to scanning on a stale or changed digest (hadepartures_scan.go:436-443). - **Refresh and `SourceReadStartedAt` contract unchanged ✅.** No change in provision/. - **Rate limit ✅.** It allows one nudge per departure per 60 s. The timestamp is recorded before the hook runs, and the map is guarded by `scanMu`. - **Deadlocks: none found ✅.** `RecordView.mu` is a leaf, and nothing that holds it calls back into the controller. `publishHAIngressSnapshot` runs after `mu` is released. `scanMu` is only taken by `ScanPass` and `Complete`. The order controller (`scanMu`) → `v.mu` cannot form a cycle with `w.pass` → `reconcileMu` → `v.mu`. - **Change index off ✅.** The nudge only sets `backstopFullDue`, which requests the existing full pass. There is no new steady polling. - **Tests production-wired ✅.** They use `armHADepartures`, the real registry, `RecordView` over a dir store, and `reconcileSerializedAuth`. The implementer's mutation run shows all three fail on the base. **Important** 1. **A rebuild that never succeeds turns into a polling loop, which the brief forbids** (hadepartures_scan.go:139 and :545-557, changeindex.go:184-190). The limiter is per departure with no cap, and its entry is only cleared on `complete`. If the inventory never becomes fresh, every stuck departure triggers a full bucket walk every 60 s, indefinitely. Causes include a failing walk, a `dirErrs` account, a walk that always times out (see #2), or a departure blocked elsewhere while `FreshAfter` stays false. - Cost: N stuck departures give N full walks per minute, against one per 30 min from the backstop. - The report says the cost is bounded per departure. It is not; it is bounded per departure per minute. - Fix: cap nudges per departure (for example 2 or 3 per evidence), then fall back to the backstop. Or rate-limit globally, since one rebuild serves every departure observed before it. 2. **The rebuild runs synchronously on the controller's short, cancellable context** (changeindex.go:186, called with the `ScanPass`/`step` context). - That context has at most 25 s from the start of `step` (hadepartures.go:327) or 30 s in `ScanPass` (hadepartures_scan.go:85). It is already reduced by `PendingDepartures`, `RetryDeparture`, `Resolve`, `Enqueue` and `ReobserveDeparture`. - It is also a child of the admission `workCtx` (group_admission.go:253-256), which is cancelled when admission is revoked. - The backstop loop, by contrast, runs on the unbounded `agentCtx`, and the walk is sequential (recordview.go:438+). - Failure scenario: on a bucket whose full walk takes longer than about 15-20 s, the walk is cut short. `rebuildLocked` then publishes an incomplete snapshot, with "dead reads cached as failures" (recordview.go:255-262). - The box's whole view then stops vouching, so every reconcile and steering walk reads the bucket until a later `Refresh` heals it. - The departure is still stale, so it nudges again 60 s later with the same result. The nudge makes the box worse, and the departure still waits for the backstop. This is self-inflicted case of #1. - While the walk runs it also holds `scanMu` and a departure work slot, and blocks every reconcile's `viewStore` `Refresh` on `v.mu`. The backstop loop does the same, but now it can happen once a minute. - Fix: run the rebuild on a detached context with the backstop's lifetime, for example by signalling `recordViewBackstopLoop` to run a round early. Do not walk inside the step. **Minor** - hadepartures_scan.go:534. `inventoryRequests` entries are deleted only on successful `complete`. A departure acked or abandoned by any other path leaves its entry in the map. The leak is tiny, but it is unbounded over the process's life. - The tests cover only the fast in-process walk. Nothing checks that a timed-out or failed nudge leaves the view's completeness unchanged, which is the case that matters for #2. - The cost comment at changeindex.go:177 says "per departure". In the failure case it is per departure per minute; it should say so. **⚠️ Cannot verify from diff** - How long a full `RecordView` walk takes on dev or flagship today, compared with the remaining 15-20 s budget. This decides whether #2 is theoretical or the common case. Check backstop log timings on a dev box. - Whether the fast converge loop has `fullDue` armed on boxes without the change index (agent.go:3584 is conditional). If it is not, the nudge does nothing there and those boxes keep the old latency. - I could not run the tests: the sandbox makes `~/.cache/go-build` read-only, so the build failed at setup. Pass and fail status rests on the implementer's report and its mutation run. **Task quality: Not approved.** The I3 handling and the test wiring are sound. #1 breaks the brief's "no unbounded rebuild loop" constraint, and #2 can make the view worse on large buckets. Both can be fixed by running the nudge as an early backstop round on the backstop's own context, with a per-departure cap or a global limit.</result> <usage><subagent_tokens>66134</subagent_tokens><tool_uses>13</tool_uses><duration_ms>113128</duration_ms></usage> </task-notification>
Attributed to this commit: 4.52 g CO₂e (537,782 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| new file mode 100644 |
| index 000000000..c66cb65e5 |
| --- /dev/null |
| +++ b/internal/edge/backhaul_holder.go |
| @@ -0,0 +1,146 @@ |
| +package edge |
| + |
| +import ( |
| + "container/list" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "sync" |
| + "time" |
| +) |
| + |
| +const backhaulHolderTTL = 10 * time.Minute |
| +const backhaulHolderLimit = 50_000 |
| + |
| +type backhaulHolderEntry struct { |
| + host, ref string |
| + until time.Time |
| +} |
| + |
| +type backhaulHolderCache struct { |
| + mu sync.Mutex |
| + entries map[string]*list.Element |
| + order list.List |
| +} |
| + |
| +func (c *backhaulHolderCache) get(host string, now time.Time) string { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + el := c.entries[host] |
| + if el == nil { |
| + return "" |
| + } |
| + entry := el.Value.(backhaulHolderEntry) |
| + if !now.Before(entry.until) { |
| + delete(c.entries, host) |
| + c.order.Remove(el) |
| + return "" |
| + } |
| + return entry.ref |
| +} |
| + |
| +func (c *backhaulHolderCache) remember(host, ref string, now time.Time) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.entries == nil { |
| + c.entries = make(map[string]*list.Element) |
| + } |
| + entry := backhaulHolderEntry{host: host, ref: ref, until: now.Add(backhaulHolderTTL)} |
| + if el := c.entries[host]; el != nil { |
| + el.Value = entry |
| + c.order.MoveToBack(el) |
| + return |
| + } |
| + if len(c.entries) >= backhaulHolderLimit { |
| + el := c.order.Front() |
| + delete(c.entries, el.Value.(backhaulHolderEntry).host) |
| + c.order.Remove(el) |
| + } |
| + c.entries[host] = c.order.PushBack(entry) |
| +} |
| + |
| +func (c *backhaulHolderCache) drop(host, ref string) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if el := c.entries[host]; el != nil && el.Value.(backhaulHolderEntry).ref == ref { |
| + delete(c.entries, host) |
| + c.order.Remove(el) |
| + } |
| +} |
| + |
| +// backhaulTarget is the initial choice for this request. Every cache hit is |
| +// checked against the current destination view before it can change the dial. |
| +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 { |
| + return addr, ref |
| + } |
| + e.backhaulHolders.drop(host, ref) |
| + } |
| + return dial, box |
| +} |
| + |
| +var errBackhaulHolder = errors.New("backhaul holder follow") |
| + |
| +// backhaulHolderTransport consumes a followed refusal before the proxy can |
| +// copy its status, headers or body. The normal proxy still owns every other |
| +// response, including upgrades and the second attempt's refusal. |
| +type backhaulHolderTransport struct { |
| + http.RoundTripper |
| + response func(*http.Response) error |
| +} |
| + |
| +func (t backhaulHolderTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| + resp, err := t.RoundTripper.RoundTrip(r) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if err := t.response(resp); err != nil { |
| + resp.Body.Close() |
| + return nil, 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 |
| + tr := backhaulHolderTransport{RoundTripper: e.backhaulTransport(dial), response: func(resp *http.Response) error { |
| + if resp.StatusCode != http.StatusServiceUnavailable { |
| + return nil |
| + } |
| + ref := resp.Header.Get(holderHeader) |
| + if ref != box { |
| + e.backhaulHolders.drop(host, box) |
| + } |
| + if ref == "" || ref == "none" || ref == box { |
| + return nil |
| + } |
| + now := time.Now() |
| + addr, ok := e.homes.Load().boxInRegionView(ref, box, now) |
| + if !ok { |
| + return nil |
| + } |
| + e.backhaulHolders.remember(host, ref, now) |
| + noBody := (r.Body == nil || r.Body == http.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 |
| + return errBackhaulHolder |
| + } |
| + return nil |
| + }} |
| + onError := func(w http.ResponseWriter, _ *http.Request, err error) { |
| + if errors.Is(err, errBackhaulHolder) { |
| + return |
| + } |
| + e.backhaulHolders.drop(host, box) |
| + e.logThrottled("backhaul-error "+box, fmt.Sprintf("backhaul %s to %s (%s): %v", host, box, dial, err)) |
| + w.WriteHeader(http.StatusBadGateway) |
| + } |
| + e.hopTo(w, r, host, dial, box, key, "backhaul", tr, onError, nil) |
| + // The refused hop releases its capacity slot before the holder starts a |
| + // response that may stream or remain upgraded indefinitely. |
| + if nextRef != "" { |
| + e.backhaulAttempt(w, r, host, nextDial, nextRef, key, false) |
| + } |
| +} |
diff --git a/internal/edge/backhaul_holder_export_test.go b/internal/edge/backhaul_holder_export_test.go| new file mode 100644 |
| index 000000000..f7546cddf |
| --- /dev/null |
| +++ b/internal/edge/backhaul_holder_export_test.go |
| @@ -0,0 +1,177 @@ |
| +package edge |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/tls" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type BackhaulHolderScene struct { |
| + sender, first, holder *backhaulEdge |
| + store release.Store |
| +} |
| + |
| +func NewBackhaulHolderScene(t *testing.T, bucket string, act Activator, rt registry.Route) *BackhaulHolderScene { |
| + t.Helper() |
| + t.Setenv("CARLOS_REGION_HA", "true") |
| + t.Setenv("CARLOS_RATE_LIMIT", "observe") |
| + s := &BackhaulHolderScene{store: release.NewDirStore(bucket)} |
| + ca := newE2ECA(t) |
| + ca.publish(t, s.store, rt.Host) |
| + if err := MintMeshKey(t.Context(), s.store); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.first = newBackhaulEdgeWith(t, bucket, "annie", ca, nil, act, []registry.Route{rt}) |
| + app := fwApp(t, "holder") |
| + s.holder = newBackhaulEdge(t, bucket, "betty", ca, nil, map[string]string{rt.Host: app.srv.Listener.Addr().String()}) |
| + s.sender = newBackhaulEdge(t, bucket, "dennis", ca, nil, nil) |
| + old := backhaulRootCAs |
| + backhaulRootCAs = ca.pool |
| + t.Cleanup(func() { backhaulRootCAs = old }) |
| + for i, be := range []*backhaulEdge{s.first, s.holder, s.sender} { |
| + region := "eu" |
| + if be == s.sender { |
| + region = "us" |
| + } |
| + ip := fmt.Sprintf("127.0.0.%d", i+1) |
| + putJSON(t, s.store, "control/edges/"+be.box+".json", fmt.Sprintf(`{"v":1,"box":%q,"eip":%q,"region":%q,"placement":"p","data_bucket":"data","secrets_key_fp":"fp","box_role":"serve","admitted":true,"drained":false,"generation":%q,"hosts":{%q:{"role":"home","account":%q,"app":%q}}}`, be.box, ip, region, time.Now().UTC().Format(time.RFC3339Nano), rt.Host, rt.Account, rt.App)) |
| + addr := be.tlsAddr |
| + tr := s.sender.edge.backhaulTransport(ip) |
| + tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, addr) |
| + } |
| + t.Cleanup(tr.CloseIdleConnections) |
| + } |
| + for _, be := range []*backhaulEdge{s.first, s.holder, s.sender} { |
| + refreshHomeMap(t, be.homes) |
| + if err := be.mirror.Refresh(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return s |
| +} |
| + |
| +func (s *BackhaulHolderScene) Request(t *testing.T, method, path, body string) (int, http.Header, string) { |
| + t.Helper() |
| + req, err := http.NewRequest(method, "https://"+HAForwardHost+path, strings.NewReader(body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp, err := s.sender.client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + b, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return resp.StatusCode, resp.Header, string(b) |
| +} |
| + |
| +func (s *BackhaulHolderScene) Counts() (int64, int64) { |
| + return s.first.calls.Load(), s.holder.calls.Load() |
| +} |
| + |
| +func (s *BackhaulHolderScene) HolderFile(t *testing.T, field string, value any) { |
| + t.Helper() |
| + key := "control/edges/betty.json" |
| + data, _, err := s.store.Get(t.Context(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var f map[string]any |
| + if err := json.Unmarshal(data, &f); err != nil { |
| + t.Fatal(err) |
| + } |
| + f[field] = value |
| + b, err := json.Marshal(f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + putJSON(t, s.store, key, string(b)) |
| + refreshHomeMap(t, s.sender.homes) |
| +} |
| + |
| +func (s *BackhaulHolderScene) HolderActivator(t *testing.T, act Activator, rt registry.Route) { |
| + t.Helper() |
| + s.holder.edge.act = act |
| + if err := s.holder.reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.holder.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (s *BackhaulHolderScene) HolderDown() { |
| + s.holder.door.Listener.Close() |
| + s.holder.door.CloseClientConnections() |
| + s.sender.edge.backhaulTransport("127.0.0.2").CloseIdleConnections() |
| +} |
| + |
| +func (s *BackhaulHolderScene) FirstApp(t *testing.T) { |
| + t.Helper() |
| + app := fwApp(t, "first") |
| + s.first.edge.act = nil |
| + if err := s.first.reg.Delete(HAForwardHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.first.reg.Upsert(registry.Route{Host: HAForwardHost, Kind: "service", Addr: app.srv.Listener.Addr().String(), Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.first.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (s *BackhaulHolderScene) Upgrade(t *testing.T) { |
| + t.Helper() |
| + raw, err := net.DialTimeout("tcp", s.sender.tlsAddr, 5*time.Second) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := tls.Client(raw, &tls.Config{ServerName: HAForwardHost, RootCAs: backhaulRootCAs, MinVersion: tls.VersionTLS12}) |
| + defer c.Close() |
| + c.SetDeadline(time.Now().Add(5 * time.Second)) |
| + fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", HAForwardHost) |
| + br := bufio.NewReader(c) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != 101 { |
| + t.Fatalf("upgrade: %d", resp.StatusCode) |
| + } |
| + if v, ok := s.sender.edge.backhaulInflight.Load("annie"); !ok || v.(*atomic.Int64).Load() != 0 { |
| + t.Fatal("completed first hop retained its capacity slot during the upgrade") |
| + } |
| + fmt.Fprint(c, "ping\n") |
| + if line, err := br.ReadString('\n'); err != nil || line != "holder:ping\n" { |
| + t.Fatalf("echo=%q %v", line, err) |
| + } |
| +} |
| + |
| +func (s *BackhaulHolderScene) ExpireMemory() { |
| + c := &s.sender.edge.backhaulHolders |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if el := c.entries[HAForwardHost]; el != nil { |
| + entry := el.Value.(backhaulHolderEntry) |
| + entry.until = time.Now().Add(-time.Nanosecond) |
| + el.Value = entry |
| + } |
| +} |
diff --git a/internal/edge/backhaul_holder_test.go b/internal/edge/backhaul_holder_test.go| new file mode 100644 |
| index 000000000..f4a54dd61 |
| --- /dev/null |
| +++ b/internal/edge/backhaul_holder_test.go |
| @@ -0,0 +1,63 @@ |
| +package edge |
| + |
| +import ( |
| + "fmt" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestBackhaulHolderMemoryBounds(t *testing.T) { |
| + now := time.Date(2026, 11, 6, 12, 0, 0, 0, time.UTC) |
| + var c backhaulHolderCache |
| + c.remember("first", "a", now) |
| + if got := c.get("first", now.Add(10*time.Minute-time.Nanosecond)); got != "a" { |
| + t.Fatalf("before TTL: %q", got) |
| + } |
| + if got := c.get("first", now.Add(10*time.Minute)); got != "" { |
| + t.Fatalf("at TTL: %q", got) |
| + } |
| + for i := 0; i < 50_001; i++ { |
| + c.remember(fmt.Sprint(i), "a", now) |
| + } |
| + if len(c.entries) != 50_000 || c.order.Len() != 50_000 { |
| + t.Fatalf("size=%d order=%d", len(c.entries), c.order.Len()) |
| + } |
| + if c.get("0", now) != "" || c.get("50000", now) != "a" { |
| + t.Fatal("oldest hint was not evicted") |
| + } |
| + c.remember("1", "b", now.Add(time.Minute)) |
| + c.remember("last", "a", now.Add(time.Minute)) |
| + if c.get("1", now) != "b" || c.get("2", now) != "" { |
| + t.Fatal("refresh did not move eviction order") |
| + } |
| + c.drop("1", "a") |
| + if c.get("1", now) != "b" { |
| + t.Fatal("old holder's failure dropped its replacement") |
| + } |
| + c.drop("1", "b") |
| + if c.get("1", now) != "" { |
| + t.Fatal("holder failure retained its hint") |
| + } |
| +} |
| + |
| +func TestBackhaulHolderMemoryConcurrent(t *testing.T) { |
| + var c backhaulHolderCache |
| + var wg sync.WaitGroup |
| + for i := 0; i < 20; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + for j := 0; j < 100; j++ { |
| + host := fmt.Sprint(j) |
| + c.remember(host, "a", time.Now()) |
| + c.get(host, time.Now()) |
| + c.drop(host, "a") |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + if len(c.entries) != c.order.Len() { |
| + t.Fatalf("map/list diverged: %d/%d", len(c.entries), c.order.Len()) |
| + } |
| +} |
diff --git a/internal/edge/backhaul_holder_wiring_test.go b/internal/edge/backhaul_holder_wiring_test.go| new file mode 100644 |
| index 000000000..03c0bb359 |
| --- /dev/null |
| +++ b/internal/edge/backhaul_holder_wiring_test.go |
| @@ -0,0 +1,251 @@ |
| +package edge_test |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func backhaulHeldService(t *testing.T, holder string) (*activator.Service, registry.Route, string, func(string) *activator.Service) { |
| + t.Helper() |
| + fx := locktest.NewLockFixture(t) |
| + t.Cleanup(lease.ProcessStateForTest()) |
| + if err := lease.SetObligationDir(t.TempDir()); err != nil { |
| + t.Fatal(err) |
| + } |
| + self := hafresh.Self{Ref: "annie", IID: "i-a", Account: "111122223333", Region: "eu-west-1"} |
| + lease.SetSelf(self) |
| + body, _ := json.Marshal(hafresh.Lock{Generation: 9, ExpiresAt: time.Now().Add(time.Hour), Owner: hafresh.OwnerFor(hafresh.Self{Ref: holder, IID: "i-b"}, 7, true)}) |
| + fx.PutLock(activator.HibernatePrefix("", edge.HAForwardHost), body) |
| + bucket := t.TempDir() |
| + store := release.NewDirStore(bucket) |
| + rec := provision.Record{Schema: 1, Host: edge.HAForwardHost, Slug: "ha", App: "shop", Account: release.OpsAccount, Channel: "stable", Region: "eu", Pool: "ha", HA: true} |
| + if err := provision.PutManifest(t.Context(), store, rec.Account, rec.App, provision.Manifest{Schema: 1, App: rec.App, Domain: "forward.test"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.CreateRecord(t.Context(), store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + view := provision.NewRecordView(store, release.NewChangeWatch(store)) |
| + if err := view.Rebuild(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := activator.Config{Bucket: fx.Bucket, Region: "eu-west-1", Self: func() hafresh.Self { return self }, Record: func(ctx context.Context, rt registry.Route) (activator.RecordFacts, error) { |
| + rec, err := provision.GetRecord(ctx, view.Snapshot().Store(store), rt.Account, rt.App, rt.Host) |
| + if err != nil { |
| + return activator.RecordFacts{}, err |
| + } |
| + return activator.RecordFactsOf(*rec) |
| + }} |
| + root := t.TempDir() |
| + b := &activator.ExecBackend{Cfg: cfg, DataDir: filepath.Join(root, "data"), RunDirOverride: filepath.Join(root, "run"), Control: instancectl.NewClient(filepath.Join(root, "control.sock")), ServedPools: (provision.ReconcileConfig{Pools: []string{"ha"}}).ServedPools} |
| + rt := registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Pool: rec.Pool, Region: rec.Region, Kind: "instance", Status: "ready", HA: true, Provisioned: true, Hibernate: true, DBPath: provision.NestedDBPath(b.DataDir, rec.Host), Socket: filepath.Join(b.RunDirOverride, "instances", provision.InstanceID(rec.Host), "app.sock")} |
| + svc := activator.New(cfg, b, nil) |
| + t.Cleanup(func() { svc.Shutdown(context.Background()) }) |
| + return svc, rt, bucket, func(owner string) *activator.Service { |
| + other := cfg |
| + other.Prefix = "second" |
| + body, _ := json.Marshal(hafresh.Lock{Generation: 9, ExpiresAt: time.Now().Add(time.Hour), Owner: hafresh.OwnerFor(hafresh.Self{Ref: owner, IID: "i-c"}, 7, true)}) |
| + fx.PutLock(activator.HibernatePrefix(other.Prefix, edge.HAForwardHost), body) |
| + backend := &activator.ExecBackend{Cfg: other, DataDir: b.DataDir, RunDirOverride: b.RunDirOverride, Control: b.Control, ServedPools: b.ServedPools} |
| + next := activator.New(other, backend, nil) |
| + t.Cleanup(func() { next.Shutdown(context.Background()) }) |
| + return next |
| + } |
| +} |
| + |
| +func TestBackhaulFollowsHolderOnce(t *testing.T) { |
| + svc, rt, bucket, _ := backhaulHeldService(t, "betty") |
| + s := edge.NewBackhaulHolderScene(t, bucket, svc, rt) |
| + status, headers, body := s.Request(t, "GET", "/", "") |
| + if status != 200 || body != "holder|"+rt.Host+"|/" || headers.Get("Retry-After") != "" { |
| + t.Fatalf("GET: %d %v %q; want holder's 200", status, headers, body) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 1 { |
| + t.Fatalf("calls=%d/%d, want 1/1", a, b) |
| + } |
| + status, _, body = s.Request(t, "POST", "/", "once") |
| + if status != 200 || !strings.HasPrefix(body, "holder|") { |
| + t.Fatalf("remembered POST: %d %q", status, body) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 2 { |
| + t.Fatalf("calls=%d/%d, want 1/2", a, b) |
| + } |
| +} |
| + |
| +func TestBackhaulHolderReplaySafety(t *testing.T) { |
| + for _, tc := range []struct { |
| + method, body string |
| + status int |
| + }{ |
| + {"HEAD", "", 200}, {"POST", "once", 503}, {"GET", "body", 503}, {"HEAD", "body", 503}, {"PUT", "", 503}, |
| + } { |
| + t.Run(tc.method+tc.body, func(t *testing.T) { |
| + svc, rt, bucket, _ := backhaulHeldService(t, "betty") |
| + s := edge.NewBackhaulHolderScene(t, bucket, svc, rt) |
| + status, _, body := s.Request(t, tc.method, "/", tc.body) |
| + if status != tc.status { |
| + t.Fatalf("first request: %d %q, want %d", status, body, tc.status) |
| + } |
| + wantHolder := int64(0) |
| + if tc.status == 200 { |
| + wantHolder = 1 |
| + } |
| + if a, b := s.Counts(); a != 1 || b != wantHolder { |
| + t.Fatalf("calls=%d/%d", a, b) |
| + } |
| + status, _, body = s.Request(t, "POST", "/", "once") |
| + if status != 200 || !strings.HasPrefix(body, "holder|") { |
| + t.Fatalf("next POST: %d %q", status, body) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != wantHolder+1 { |
| + t.Fatalf("remembered calls=%d/%d", a, b) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestBackhaulHolderViewRefusals(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, field string |
| + value any |
| + }{ |
| + {"region", "region", "us"}, {"placement", "placement", "elsewhere"}, {"null placement", "placement", nil}, |
| + {"bucket", "data_bucket", "other"}, {"no bucket", "data_bucket", ""}, {"key", "secrets_key_fp", "other"}, |
| + {"stale", "generation", time.Now().Add(-16 * time.Minute).Format(time.RFC3339)}, |
| + {"future", "generation", time.Now().Add(2 * time.Minute).Format(time.RFC3339)}, |
| + {"bad generation", "generation", false}, {"booting", "box_role", "booting"}, {"unadmitted", "admitted", false}, |
| + {"drained", "drained", true}, {"no dial", "eip", ""}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + svc, rt, bucket, _ := backhaulHeldService(t, "betty") |
| + s := edge.NewBackhaulHolderScene(t, bucket, svc, rt) |
| + s.HolderFile(t, tc.field, tc.value) |
| + status, headers, body := s.Request(t, "GET", "/", "") |
| + if status != 503 || headers.Get("X-Carlos-Holder") != "betty" || body != unreachableBody { |
| + t.Fatalf("refusal: %d %v %q", status, headers, body) |
| + } |
| + s.Request(t, "POST", "/", "once") |
| + if a, b := s.Counts(); a != 2 || b != 0 { |
| + t.Fatalf("calls=%d/%d; invalid holder was followed or remembered", a, b) |
| + } |
| + }) |
| + } |
| + for _, ref := range []string{"", "unknown", "annie"} { |
| + t.Run("ref="+ref, func(t *testing.T) { |
| + svc, rt, bucket, _ := backhaulHeldService(t, ref) |
| + s := edge.NewBackhaulHolderScene(t, bucket, svc, rt) |
| + status, headers, body := s.Request(t, "GET", "/", "") |
| + if status != 503 { |
| + t.Fatalf("refusal: %d %v %q", status, headers, body) |
| + } |
| + if ref == "" && headers.Get("X-Carlos-Holder") != "none" { |
| + t.Fatalf("missing none: %v", headers) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 0 { |
| + t.Fatalf("calls=%d/%d", a, b) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestBackhaulHolderStopsAfterSecondAttempt(t *testing.T) { |
| + svc, rt, bucket, second := backhaulHeldService(t, "betty") |
| + s := edge.NewBackhaulHolderScene(t, bucket, svc, rt) |
| + s.HolderActivator(t, second("annie"), rt) |
| + status, headers, body := s.Request(t, "GET", "/", "") |
| + if status != 503 || headers.Get("X-Carlos-Holder") != "annie" || headers.Get("Retry-After") != "1" || body != unreachableBody { |
| + t.Fatalf("second answer: %d %v %q", status, headers, body) |
| + } |
| + if a, b := s.Counts(); a != 1 || b != 1 { |
| + t.Fatalf("calls=%d/%d; want exactly two attempts", a, b) |
| + } |
| +} |
| + |
| +func TestBackhaulHolderDropsMemory(t *testing.T) { |
| + for _, mode := range []string{"none", "other", "left view", "stale", "expired", "dial failure"} { |
| + t.Run(mode, func(t *testing.T) { |
| + svc, rt, bucket, second := backhaulHeldService(t, "betty") |
| + s := edge.NewBackhaulHolderScene(t, bucket, svc, rt) |
| + if status, _, body := s.Request(t, "GET", "/", ""); status != 200 { |
| + t.Fatalf("warm: %d %q", status, body) |
| + } |
| + switch mode { |
| + case "none": |
| + s.HolderActivator(t, second(""), rt) |
| + case "other": |
| + s.HolderActivator(t, second("unknown"), rt) |
| + case "left view": |
| + s.HolderFile(t, "region", "other") |
| + case "stale": |
| + s.HolderFile(t, "generation", time.Now().Add(-16*time.Minute).Format(time.RFC3339)) |
| + case "expired": |
| + s.ExpireMemory() |
| + case "dial failure": |
| + s.HolderDown() |
| + } |
| + status, _, body := s.Request(t, "POST", "/", "once") |
| + want := 503 |
| + if mode == "dial failure" { |
| + want = 502 |
| + } |
| + if status != want { |
| + t.Fatalf("failed holder: %d %q, want %d", status, body, want) |
| + } |
| + if mode == "expired" { |
| + status, _, body = s.Request(t, "POST", "/", "once") |
| + if status != 200 { |
| + t.Fatalf("relearned POST: %d %q", status, body) |
| + } |
| + } else { |
| + s.Request(t, "POST", "/", "once") |
| + } |
| + a, _ := s.Counts() |
| + expected := int64(2) |
| + if mode == "left view" || mode == "stale" { |
| + expected = 3 |
| + } |
| + if a != expected { |
| + t.Fatalf("first box calls=%d, want %d after dropping memory", a, expected) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestBackhaulAppHolderCannotSteer(t *testing.T) { |
| + svc, rt, bucket, _ := backhaulHeldService(t, "betty") |
| + s := edge.NewBackhaulHolderScene(t, bucket, svc, rt) |
| + s.FirstApp(t) |
| + for _, path := range []string{"/holder?ref=betty", "/trailer-holder?announced=1", "/trailer-holder"} { |
| + _, headers, _ := s.Request(t, "GET", path, "") |
| + if headers.Get("X-Carlos-Holder") != "" { |
| + t.Fatalf("app header escaped: %v", headers) |
| + } |
| + } |
| + s.Request(t, "POST", "/", "once") |
| + if a, b := s.Counts(); a != 4 || b != 0 { |
| + t.Fatalf("app steered calls=%d/%d", a, b) |
| + } |
| +} |
| + |
| +func TestBackhaulHolderUpgrade(t *testing.T) { |
| + svc, rt, bucket, _ := backhaulHeldService(t, "betty") |
| + s := edge.NewBackhaulHolderScene(t, bucket, svc, rt) |
| + s.Upgrade(t) |
| + if a, b := s.Counts(); a != 1 || b != 1 { |
| + t.Fatalf("upgrade calls=%d/%d", a, b) |
| + } |
| +} |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 26653d15d..639ee2f3e 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -362,6 +362,7 @@ type Edge struct { |
| // backhaul target, and keying per host would let a stranger's stream of |
| // invented hostnames grow this map without limit. |
| backhaulTransports sync.Map |
| + backhaulHolders backhaulHolderCache |
| // forwardTransports is the same for region HA forwards (forwardha.go), |
| // keyed by the holder's dial address: their own cache, with their own |
| // 2 s connect bound, so backhaulTo's transports never change. |
| @@ -4220,7 +4221,8 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box |
| e.logThrottled("backhaul-no-mesh-key", fmt.Sprintf("%s is homed on %s but no mesh key is mirrored — not dialling (the request gets the unknown-host answer until the key lands)", host, box)) |
| return false |
| } |
| - e.hopTo(w, r, host, eip, box, key, "backhaul", e.backhaulTransport(eip), nil, nil) |
| + eip, box = e.backhaulTarget(host, eip, box) |
| + e.backhaulAttempt(w, r, host, eip, box, key, true) |
| return true |
| } |
diff --git a/internal/edge/holderview.go b/internal/edge/holderview.go| index 204bcabdf..fef7bbad8 100644 |
| --- a/internal/edge/holderview.go |
| +++ b/internal/edge/holderview.go |
| @@ -1,8 +1,10 @@ |
| package edge |
| import ( |
| + "encoding/json" |
| "time" |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| "github.com/carlosframework/platform/internal/edgesfile" |
| ) |
| @@ -57,3 +59,38 @@ func (m *homeMap) boxInView(ref string, now time.Time) (dial string, ok bool) { |
| dial = reader.Dial(peer.dialPoint()) |
| return dial, dial != "" |
| } |
| + |
| +// boxInRegionView validates a holder against the destination box's region. |
| +// The sender's file chooses public or private dialing; it does not define |
| +// the destination's placement or data store. |
| +func (m *homeMap) boxInRegionView(ref, destination string, now time.Time) (string, bool) { |
| + if m == nil || ref == "" || ref == "none" || ref == m.self { |
| + return "", false |
| + } |
| + var own, target, peer edgesFileView |
| + var ownKnown, targetKnown, peerKnown bool |
| + for _, f := range m.snapshot().files { |
| + if f.Box == m.self { |
| + own, ownKnown = f, true |
| + } |
| + if f.Box == destination { |
| + target, targetKnown = f, true |
| + } |
| + if f.Box == ref { |
| + peer, peerKnown = f, true |
| + } |
| + } |
| + if !targetKnown || !peerKnown || target.Region == "" || peer.Region != target.Region || peer.Placement != target.Placement || peer.placementNull || target.placementNull { |
| + return "", false |
| + } |
| + if peer.DataBucket == "" || peer.DataBucket != target.DataBucket || peer.SecretsKeyFP != target.SecretsKeyFP || !peer.HomeEligible() { |
| + return "", false |
| + } |
| + var generation string |
| + if json.Unmarshal(peer.Generation, &generation) != nil || !boxchoice.HeadroomFresh(generation, now) { |
| + return "", false |
| + } |
| + reader := edgesfile.Reader{Box: m.self, Self: own.dialPoint(), SelfKnown: ownKnown, PrivateDial: m.privateDial} |
| + dial := reader.Dial(peer.dialPoint()) |
| + return dial, dial != "" |
| +} |