carlos / platform Public

region-ha p1b-2: the edge forwards an HA host's request at the front door

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 84b522999c9658762d16cbf38208ce9a07108f6a parent 436b33c
5 files changed, +1,073 −7
  • internal/edge/backhaul_e2e_test.go +3 −3
  • internal/edge/edge.go +44 −3
  • internal/edge/forwardha.go +207 −0
  • internal/edge/forwardha_test.go +817 −0
  • internal/edge/regional.go +2 −1

Intent

Human

<task-notification> <task-id>aeaddb52a687c98b4</task-id> <tool-use-id>toolu_01BmAsKgXNkSee99YSNjGPzi</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/aeaddb52a687c98b4.output</output-file> <status>completed</status> <summary>Agent "Implement Task 1: edge view" 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>Status: DONE Commit: 436b33c9 "region-ha p1b-2: the edge's view of a box". The commit printed a `packed-refs.lock` error, but `git log` shows the commit on the branch and the tree is clean. Tests: the new `TestHolderViewRules`, `TestHolderViewDialsPrivateWithRegionHA` and `TestHopVerifiedExported` pass, and the existing `TestHomeMap*` tests still pass. They failed to build first (`boxInView` and `HopVerified` undefined). `go vet ./internal/edge` is clean, and `go build ./...` passes for linux, darwin and windows. Concerns (both are my reading where the brief was silent): - `boxInView` returns `ok=false` when the peer meets the View rule but has no dialable address, because there is nothing to dial. - If both this box and the peer have an empty `region`, they count as equal. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b2/.superpowers/sdd/2026-10-29-region-ha-p1b2-forwarding/task-1-report.md</result> <usage><subagent_tokens>59997</subagent_tokens><tool_uses>11</tool_uses><duration_ms>141842</duration_ms></usage> </task-notification>

Attributed to this commit: 65.6 g CO₂e (8,649,341 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p1b2-forwarding, 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_e2e_test.go b/internal/edge/backhaul_e2e_test.go
index 1ed30579c..909491b1e 100644
--- a/internal/edge/backhaul_e2e_test.go
+++ b/internal/edge/backhaul_e2e_test.go
@@ -510,13 +510,13 @@ type backhaulScene struct {
}
// backhaulSceneExtra is what a scene adds to the standard two edges: more
-// route rows on either edge, the home edge's activator, more certificates in
+// route rows on either edge, either edge's activator, more certificates in
// the bucket, and more entries in the home edge's and the sending edge's
// edges files (host → the JSON of its entry, edgesHostView's shape). The zero
// value is the standard scene.
type backhaulSceneExtra struct {
homeRoutes, farRoutes []registry.Route
- homeAct Activator
+ homeAct, farAct Activator
certs []string
homeEntries, farEntries map[string]string
}
@@ -554,7 +554,7 @@ func newBackhaulSceneWith(t *testing.T, x backhaulSceneExtra) *backhaulScene {
s.a = newBackhaulEdgeWith(t, bucket, "annie", s.ca, from, x.homeAct, append([]registry.Route{{
Host: e2eHomedHost, Kind: "service", Addr: e2eApp(t, e2eHomeMarker).Listener.Addr().String(), Status: "ready",
}}, x.homeRoutes...))
- s.b = newBackhaulEdgeWith(t, bucket, "betty", s.ca, from, nil, append([]registry.Route{{
+ s.b = newBackhaulEdgeWith(t, bucket, "betty", s.ca, from, x.farAct, append([]registry.Route{{
Host: e2eSenderHost, Kind: "service", Addr: e2eApp(t, e2eSenderMarker).Listener.Addr().String(), Status: "ready",
}}, x.farRoutes...))
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 0a8cb6e54..7098c8997 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -307,6 +307,10 @@ 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
+ // 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.
+ forwardTransports sync.Map
// backhaulInflight counts the hops currently in flight toward each home
// box — the containment half of the egress ruling (backhaulAcquire).
// Keyed by BOX for the same reason backhaulTransports is keyed by EIP: a
@@ -1771,6 +1775,17 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
+ // Region HA forwarding (forwardha.go): a visitor's request for a born-HA
+ // host whose lease another box in this region holds goes to that box
+ // HERE, before any per-request step below runs on this box, so the
+ // holder runs each of them once. After the lookup and its !ok branch,
+ // which a forward never needs, and before the login POST reads the body
+ // (the hop proxies it). A verified hop, a door call and a tunnel
+ // delivery are never forwarded; nor is a regional name.
+ if e.frontForwardHA(w, r, host, up, hopped, isDoor) {
+ return
+ }
+
// A login POST re-resolves its upstream by the path in `next`, not by
// its own (spec §4.2). On a hostname that routes by path prefix,
// lookupUpstreamPath keys on the first segment; "/.carlos/gate" has no
@@ -3413,11 +3428,26 @@ 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)
+ return true
+}
+
+// hopTo is the sign-admit-proxy core backhaulTo and a region HA forward
+// (forwardHA) share: admit the hop toward box, sign it for host with key, and
+// proxy r to eip over tr. It reports whether the hop was admitted; a refusal
+// has been answered on w.
+//
+// onError, when non-nil, replaces backhaulProxy's error answer (the 502),
+// and onResponse, when non-nil, sees each upstream response before
+// backhaulProxy's own scrub. event is the regionalObserve test hook's name
+// for the dial.
+func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box string, key []byte, event string, tr http.RoundTripper,
+ onError func(http.ResponseWriter, *http.Request, error), onResponse func(*http.Response)) bool {
// Containment (the egress ruling, 2026-08-24), between the last guard and
// the dial: backhaulAdmit answers a refused hop itself.
releaseSlot, ok := e.backhaulAdmit(w, r, eip, box)
if !ok {
- return true
+ return false
}
// Held until the hop's ServeHTTP returns, which for a stream or an
// upgraded connection is the life of the stream (backhaulAcquire).
@@ -3433,11 +3463,22 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box
if _, ok := doorCallerFrom(r.Context()); ok {
doorAuth = signHopDoor(key, host, now)
}
+ p := backhaulProxy(host, eip, box, auth, doorAuth, false, tr, e.logThrottled)
+ if onError != nil {
+ p.ErrorHandler = onError
+ }
+ if onResponse != nil {
+ scrub := p.ModifyResponse
+ p.ModifyResponse = func(resp *http.Response) error {
+ onResponse(resp)
+ return scrub(resp)
+ }
+ }
// The client boundary for informational responses: a 1xx from the home
// reaches w through the proxy's trace hook, past ModifyResponse, so the
// asset vocabulary comes off it here (assetInformationalScrub).
- observeRegional("backhaul", host)
- backhaulProxy(host, eip, box, auth, doorAuth, false, e.backhaulTransport(eip), e.logThrottled).ServeHTTP(assetInformationalScrub{w}, r)
+ observeRegional(event, host)
+ p.ServeHTTP(assetInformationalScrub{w}, r)
return true
}
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go
new file mode 100644
index 000000000..54c47fcb8
--- /dev/null
+++ b/internal/edge/forwardha.go
@@ -0,0 +1,207 @@
+package edge
+
+// Region HA forwarding at the front door (region HA P1b-2; spec 2026-10-26
+// §6.2, §6.4). A visitor's request for a born-HA host that reaches a box
+// which does not hold the host's lease goes to the box that does, over the
+// signed backhaul hop, before this box runs any per-request step: the gate,
+// the door scope, the import and plan gates, the guards, request records,
+// rate limits, assets, compression, the cache, usage and analytics. A
+// forwarded request therefore has one box doing every one of them, the
+// holder, exactly as a cross-region backhaul does today.
+//
+// The activator says WHETHER and to WHICH box (HAForwarder, found on the
+// edge's own Activator); the edge says whether that box is in its view
+// (boxInView) and owns the hop and its failure answers. One hop, ever: a
+// verified hop is never forwarded (frontForwardHA's first test, and
+// forwardHA's own), and the holder answers what it cannot serve itself.
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// HAForwarder is the activator's half of region HA forwarding. The edge finds
+// it with a type assertion on its Activator; an activator without it, or no
+// activator, forwards nothing.
+//
+// ForwardTarget names the box a request for rt should go to, or "" to serve
+// it here. NoteForward reports how the forward went, so the activator's
+// holder cache can follow it. host is rt.Host, the route's own host, never an
+// alias the request named.
+type HAForwarder interface {
+ ForwardTarget(ctx context.Context, rt registry.Route) string
+ NoteForward(host string, res ForwardResult)
+}
+
+// ForwardOutcome is how one forward ended.
+type ForwardOutcome int
+
+const (
+ // ForwardNotInView: the named box is not in this box's view, or no mesh
+ // key is mirrored. Nothing was written; the request is served here.
+ ForwardNotInView ForwardOutcome = iota
+ // ForwardUnreachable: the named box could not be connected to within
+ // forwardDialTimeout. This box answered 503, Retry-After: 10.
+ ForwardUnreachable
+ // ForwardDone: the request went to the named box and its answer, whatever
+ // it was, was relayed, or this box refused the hop itself (Status 0).
+ ForwardDone
+)
+
+// ForwardResult is what NoteForward is told. Status is the upstream's status,
+// 0 when no answer came back from it (a hop this box refused, or a failure
+// after connecting). Holder is the upstream's X-Carlos-Holder, "" when absent.
+type ForwardResult struct {
+ Outcome ForwardOutcome
+ Status int
+ Holder string
+}
+
+// holderHeader is the holder's diagnostic on an answer to a forwarded
+// request: the box that holds the lease, or "none".
+const holderHeader = "X-Carlos-Holder"
+
+// forwardDialTimeout bounds connecting to the holder, TCP and TLS together.
+// Shorter than backhaulDialTimeout: the holder is in this box's own region,
+// and a holder that does not answer in 2 s is treated as gone (the 503 tells
+// the visitor to come back once the activator has looked again).
+const forwardDialTimeout = 2 * time.Second
+
+// forwardDial makes the TCP connection to a holder at addr. A var only so a
+// test can point it at another listener or make it stall; the deadline is on
+// ctx.
+var forwardDial = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, network, addr)
+}
+
+// forwardConnectError marks a failure to connect to the holder, as against a
+// failure after connecting, so the error answer can tell them apart.
+type forwardConnectError struct{ err error }
+
+func (e *forwardConnectError) Error() string { return "connect: " + e.err.Error() }
+func (e *forwardConnectError) Unwrap() error { return e.err }
+
+// frontForwardHA is the front-door decision, called in ServeHTTP right after
+// route lookup. It reports whether it answered. False, serve here, unless the
+// request has a local route (the caller's ok), is not a verified hop, a door
+// call or a tunnel delivery, its route is born HA, activator-managed and not
+// reached through a regional name, and the activator names a box. Then the
+// request is forwarded, the activator is told how it went, and it is answered
+// unless the box was not in view.
+func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host string, up upstream, hopped, isDoor bool) bool {
+ if hopped || isDoor || hopVerified(r.Context()) || fromTunnel(r.Context()) {
+ return false
+ }
+ if !up.route.HA || !up.hibernating || up.regional != regionalNone {
+ return false
+ }
+ fw, ok := e.act.(HAForwarder)
+ if !ok {
+ return false
+ }
+ ref := fw.ForwardTarget(r.Context(), up.route)
+ if ref == "" {
+ return false
+ }
+ res := e.forwardHA(w, r, host, ref)
+ fw.NoteForward(up.route.Host, res)
+ return res.Outcome != ForwardNotInView
+}
+
+// forwardHA sends r to the box labelled ref over a signed hop for host. A box
+// out of view, or no mesh key, writes nothing and answers ForwardNotInView.
+// Otherwise the hop is admitted and signed as backhaulTo's is, over this
+// edge's forward transport to ref. A failure to connect is answered 503,
+// Retry-After: 10; every other answer is the holder's, relayed as is.
+//
+// It repeats the arrived-hop guard: a verified hop is never forwarded, so a
+// forwarding loop needs this line and frontForwardHA's to be wrong at once.
+func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host, ref string) ForwardResult {
+ m := e.homes.Load()
+ if m == nil || hopVerified(r.Context()) {
+ return ForwardResult{Outcome: ForwardNotInView}
+ }
+ dial, ok := m.boxInView(ref, time.Now())
+ if !ok {
+ return ForwardResult{Outcome: ForwardNotInView}
+ }
+ key := signingKey(m.meshKeys())
+ if len(key) == 0 {
+ e.logThrottled("forward-no-mesh-key", fmt.Sprintf("%s is held on %s but no mesh key is mirrored; serving here", host, ref))
+ return ForwardResult{Outcome: ForwardNotInView}
+ }
+ res := ForwardResult{Outcome: ForwardDone}
+ onError := func(w http.ResponseWriter, r *http.Request, err error) {
+ var connect *forwardConnectError
+ if errors.As(err, &connect) && r.Context().Err() == nil {
+ e.logThrottled("forward-unreachable "+ref, fmt.Sprintf("forward %s → %s (%s): %v; answering 503 + Retry-After: 10", host, ref, dial, err))
+ res.Outcome = ForwardUnreachable
+ w.Header().Set("Retry-After", "10")
+ MarkAnswered(r)
+ http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable)
+ return
+ }
+ // After connecting, or the client left: backhaul's bad gateway.
+ e.logThrottled("forward-error "+ref, fmt.Sprintf("forward %s → %s (%s): %v", host, ref, dial, err))
+ w.WriteHeader(http.StatusBadGateway)
+ }
+ onResponse := func(resp *http.Response) {
+ res.Status = resp.StatusCode
+ res.Holder = resp.Header.Get(holderHeader)
+ }
+ e.hopTo(w, r, host, dial, ref, key, "forward", e.forwardTransport(dial), onError, onResponse)
+ return res
+}
+
+// forwardTransport is the cached transport to the holder at dial, as
+// backhaulTransport is per EIP and for the same reasons, with one difference:
+// connecting (TCP and TLS) has forwardDialTimeout in all, and a failure there
+// is a forwardConnectError. A separate cache, so backhaulTo's 5 s transports
+// to the same address are never this one.
+//
+// It does the TLS itself (DialTLSContext) so that the deadline and the error
+// mark cover the handshake too. Verification is backhaulTransport's: the
+// system roots (backhaulRootCAs) and the host from the outbound URL's
+// authority. No ALPN is offered, so the hop speaks HTTP/1.1 and an upgrade
+// passes through.
+func (e *Edge) forwardTransport(dial string) *http.Transport {
+ if tr, ok := e.forwardTransports.Load(dial); ok {
+ return tr.(*http.Transport)
+ }
+ tr := &http.Transport{
+ DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
+ name, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ return nil, &forwardConnectError{err}
+ }
+ ctx, cancel := context.WithTimeout(ctx, forwardDialTimeout)
+ defer cancel()
+ raw, err := forwardDial(ctx, network, net.JoinHostPort(dial, backhaulPort))
+ if err != nil {
+ return nil, &forwardConnectError{err}
+ }
+ conn := tls.Client(raw, &tls.Config{ServerName: name, RootCAs: backhaulRootCAs, MinVersion: tls.VersionTLS12})
+ if err := conn.HandshakeContext(ctx); err != nil {
+ raw.Close()
+ return nil, &forwardConnectError{err}
+ }
+ return conn, nil
+ },
+ ResponseHeaderTimeout: backhaulHeaderTimeout,
+ MaxIdleConns: 32,
+ MaxIdleConnsPerHost: 32,
+ IdleConnTimeout: 90 * time.Second,
+ }
+ if existing, loaded := e.forwardTransports.LoadOrStore(dial, tr); loaded {
+ return existing.(*http.Transport)
+ }
+ return tr
+}
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go
new file mode 100644
index 000000000..9e5189081
--- /dev/null
+++ b/internal/edge/forwardha_test.go
@@ -0,0 +1,817 @@
+package edge
+
+// Region HA P1b-2 Task 2: the front-door forward. The scene is the
+// multi-region backhaul's (newBackhaulSceneWith): two real Edges over one
+// DirStore, real TLS on both doors, the mesh key minted into the bucket and
+// real hop auth. Here both boxes serve the same born-HA hosts, both are in
+// region "ie" and placement "p" with the same data bucket and secrets key,
+// and annie's activator is a fake HAForwarder naming betty as the holder.
+// Every request below is a real client's, handshaken with annie by name.
+//
+// One seam stands in for the network: every box in a scene is dialled on
+// one port (backhaulPort), so forwardDial sends annie's forwards to betty's
+// door, where the dial address would be betty's EIP in production.
+
+import (
+ "bufio"
+ "context"
+ "crypto/tls"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/analytics"
+ "github.com/carlosframework/platform/internal/assetcache"
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/reqrec"
+ "github.com/carlosframework/platform/internal/usage"
+)
+
+const (
+ // fwHost is the plain born-HA instance both boxes serve.
+ fwHost = "ha.forward.test"
+ // fwGatedHost is the same behind the password gate.
+ fwGatedHost = "gated.forward.test"
+ // fwAssetHost is an ungated HA instance whose /assets/ the asset cache
+ // catches on both boxes.
+ fwAssetHost = "assets.forward.test"
+ // fwRateHost is an HA instance with a one-request backstop.
+ fwRateHost = "rate.forward.test"
+ // fwLegacyHost is an activator-managed instance that is not HA.
+ fwLegacyHost = "legacy.forward.test"
+
+ fwAssetBody = "console.log('forwarded');\n"
+ fwPassword = "correct horse"
+)
+
+var fwHosts = []string{fwHost, fwGatedHost, fwAssetHost, fwRateHost, fwLegacyHost}
+
+// fwAct is a box's activator: it wakes nothing (the route's TCP upstream
+// answers) and, as an HAForwarder, names target and keeps every note.
+type fwAct struct {
+ target string
+ asked atomic.Int64
+ mu sync.Mutex
+ notes []fwNote
+}
+
+type fwNote struct {
+ host string
+ res ForwardResult
+}
+
+var _ HAForwarder = (*fwAct)(nil)
+
+func (a *fwAct) ServeHTTP(http.ResponseWriter, *http.Request, registry.Route, http.Handler) bool {
+ return false
+}
+func (a *fwAct) RetireExcept(map[string]bool) {}
+func (a *fwAct) ForwardTarget(_ context.Context, _ registry.Route) string {
+ a.asked.Add(1)
+ return a.target
+}
+func (a *fwAct) NoteForward(host string, res ForwardResult) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.notes = append(a.notes, fwNote{host, res})
+}
+
+func (a *fwAct) noted() []fwNote {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return append([]fwNote(nil), a.notes...)
+}
+
+// fwPlainAct is an activator without the forwarding interface.
+type fwPlainAct struct{}
+
+func (fwPlainAct) ServeHTTP(http.ResponseWriter, *http.Request, registry.Route, http.Handler) bool {
+ return false
+}
+func (fwPlainAct) RetireExcept(map[string]bool) {}
+
+// fwApp is one box's app behind every forward host. Its ordinary body names
+// the box, the host and the path; /missing is a 404; /holder answers 503 with
+// X-Carlos-Holder set to its ref query (none when the query is empty);
+// /assets/ is a cacheable script, and /assets/held.js waits on the first
+// request until the test releases it; an upgrade echoes with the box's name.
+type fwAppServer struct {
+ srv *httptest.Server
+ n atomic.Int64
+ first func() bool
+ started chan struct{}
+ wait, release func()
+ heldRequests, assetRequests atomic.Int64
+}
+
+func fwApp(t *testing.T, box string) *fwAppServer {
+ t.Helper()
+ a := &fwAppServer{}
+ a.first, a.started, a.wait, a.release = fillGate()
+ t.Cleanup(a.release)
+ echo := upgradeEchoHandler(box)
+ a.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ a.n.Add(1)
+ switch {
+ case isUpgradeRequest(r):
+ echo.ServeHTTP(w, r)
+ case r.URL.Path == "/missing":
+ http.NotFound(w, r)
+ case r.URL.Path == "/holder":
+ if ref := r.URL.Query().Get("ref"); ref != "" {
+ w.Header().Set(holderHeader, ref)
+ }
+ w.Header().Set("Retry-After", "1")
+ http.Error(w, "held", http.StatusServiceUnavailable)
+ case r.URL.Path == "/assets/held.js":
+ a.heldRequests.Add(1)
+ if a.first() {
+ close(a.started)
+ a.wait()
+ }
+ assetOK(fwAssetBody, "ETag", `"f1"`)(w, r)
+ case strings.HasPrefix(r.URL.Path, "/assets/"):
+ a.assetRequests.Add(1)
+ assetOK(fwAssetBody, "ETag", `"f1"`)(w, r)
+ default:
+ fmt.Fprintf(w, "%s|%s|%s", box, r.Host, r.URL.Path)
+ }
+ }))
+ t.Cleanup(a.srv.Close)
+ return a
+}
+
+// fwScene is the armed two-edge scene: annie forwards, betty holds.
+type fwScene struct {
+ *backhaulScene
+ aAct, bAct *fwAct
+ aApp, bApp *fwAppServer
+ aMeter, bMeter *UsageMeter
+ aObs, bObs *memAnalytics
+ aRec, bRec *lockedRecorder
+ aStore, bStore *assetcache.Store
+ hash string
+ // seen are the record and observation counts the last take returned up to.
+ seen map[*lockedRecorder][2]int
+ obs map[*memAnalytics]int
+}
+
+type fwOpts struct {
+ // aAct replaces annie's forwarding fake (nil keeps it).
+ aAct Activator
+ // aTarget is the box annie's fake names ("" is betty).
+ aTarget string
+ // bettyLacks leaves betty without the HA hosts: in view, not serving.
+ bettyLacks bool
+}
+
+func newFwScene(t *testing.T, o fwOpts) *fwScene {
+ t.Helper()
+ t.Setenv("CARLOS_RATE_LIMIT", "observe")
+ t.Setenv("CARLOS_REGION_HA", "")
+ hash, err := gate.Hash(fwPassword)
+ if err != nil {
+ t.Fatal(err)
+ }
+ x := &fwScene{
+ aAct: &fwAct{target: "betty"}, bAct: &fwAct{target: "annie"},
+ aApp: fwApp(t, "annie"), bApp: fwApp(t, "betty"),
+ aMeter: NewUsageMeter(), bMeter: NewUsageMeter(),
+ aObs: &memAnalytics{}, bObs: &memAnalytics{},
+ aRec: &lockedRecorder{}, bRec: &lockedRecorder{},
+ hash: hash, seen: map[*lockedRecorder][2]int{}, obs: map[*memAnalytics]int{},
+ }
+ routes := func(addr string) []registry.Route {
+ base := registry.Route{Kind: "instance", Hibernate: true, Addr: addr, Status: "ready", Account: "abc", App: "shop"}
+ rs := make([]registry.Route, 0, len(fwHosts))
+ for _, h := range fwHosts {
+ rt := base
+ rt.Host = h
+ switch h {
+ case fwGatedHost:
+ rt.Gate = hash
+ case fwAssetHost:
+ rt.AssetGen, rt.Version = laGen, laBuild
+ case fwRateHost:
+ rt.RateLimit = `{"rate":1,"burst":1}`
+ }
+ rs = append(rs, rt)
+ }
+ return rs
+ }
+ if o.aTarget != "" {
+ x.aAct.target = o.aTarget
+ }
+ var aAct Activator = x.aAct
+ if o.aAct != nil {
+ aAct = o.aAct
+ }
+ extra := backhaulSceneExtra{
+ homeRoutes: routes(x.aApp.srv.Listener.Addr().String()),
+ homeAct: aAct,
+ farAct: x.bAct,
+ certs: fwHosts,
+ }
+ if !o.bettyLacks {
+ extra.farRoutes = routes(x.bApp.srv.Listener.Addr().String())
+ }
+ x.backhaulScene = newBackhaulSceneWith(t, extra)
+ for _, be := range []*backhaulEdge{x.a, x.b} {
+ for _, h := range fwHosts {
+ if h == fwLegacyHost {
+ continue
+ }
+ if _, ok := be.edge.lookupUpstream(h); !ok {
+ continue
+ }
+ if err := be.reg.SetHA(h); err != nil {
+ t.Fatalf("SetHA %s: %v", h, err)
+ }
+ }
+ if err := be.edge.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ x.publishViewFiles(t, time.Now())
+ x.converge(t)
+ fwDialTo(t, x.b.tlsAddr)
+
+ x.aStore = openStoreAt(t, filepath.Join(t.TempDir(), "asset-cache"))
+ x.bStore = openStoreAt(t, filepath.Join(t.TempDir(), "asset-cache"))
+ for _, w := range []struct {
+ be *backhaulEdge
+ meter *UsageMeter
+ obs *memAnalytics
+ rec *lockedRecorder
+ store *assetcache.Store
+ }{{x.a, x.aMeter, x.aObs, x.aRec, x.aStore}, {x.b, x.bMeter, x.bObs, x.bRec, x.bStore}} {
+ e := w.be.edge
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+ e.EnableUsage(w.meter)
+ e.EnableAnalytics(w.obs)
+ e.SetAnalyticsOn(map[string]bool{"abc/shop": true})
+ e.EnableRequestRecords(w.rec)
+ e.guard = guardWatch
+ armForTest(t, e, w.store, &fakeLocalAssets{
+ hosts: map[string]HostAssets{fwAssetHost: {Account: "abc", App: "shop", Paths: []string{"/assets/"},
+ Gen: laGen, At: time.Now(), Primary: fwAssetHost}},
+ builds: map[string]bool{laBuild: true},
+ })
+ }
+ return x
+}
+
+// publishViewFiles rewrites both boxes' edges files with the holder view's
+// fields: one region and placement, one data bucket and secrets key, written
+// at gen.
+func (x *fwScene) publishViewFiles(t *testing.T, gen time.Time) {
+ t.Helper()
+ for _, f := range []struct {
+ box, eip string
+ hosts []string
+ }{{"annie", x.aEIP, []string{e2eHomedHost, e2eMovedHost}}, {"betty", x.bEIP, []string{e2eSenderHost}}} {
+ parts := make([]string, 0, len(f.hosts))
+ for _, h := range f.hosts {
+ parts = append(parts, fmt.Sprintf(`%q:{"role":"home"}`, h))
+ }
+ putJSON(t, x.seed, "control/edges/"+f.box+".json", fmt.Sprintf(
+ `{"v":1,"box":%q,"eip":%q,"region":"ie","placement":"p","generation":%q,"data_bucket":"bkt","secrets_key_fp":"fp","hosts":{%s}}`,
+ f.box, f.eip, gen.UTC().Format(time.RFC3339), strings.Join(parts, ",")))
+ }
+}
+
+// fwDialTo points every forward dial at addr for the test's lifetime.
+func fwDialTo(t *testing.T, addr string) {
+ t.Helper()
+ old := forwardDial
+ forwardDial = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, network, addr)
+ }
+ t.Cleanup(func() { forwardDial = old })
+}
+
+func (x *fwScene) fetch(t *testing.T, host, path string, hdr ...string) (*http.Response, string) {
+ t.Helper()
+ return x.get(t, x.a, "https://"+host+path, e2eHeaders(hdr), true)
+}
+
+func (x *fwScene) fetchAsync(host, path string) <-chan e2eResult {
+ ch := make(chan e2eResult, 1)
+ go func() {
+ resp, err := x.try(x.a, "https://"+host+path, e2eHeaders(nil), true)
+ if err != nil {
+ ch <- e2eResult{err: err}
+ return
+ }
+ b, err := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ ch <- e2eResult{resp: resp, body: string(b), err: err}
+ }()
+ return ch
+}
+
+// fwBox is what one box recorded for a host since the last take.
+type fwBox struct {
+ use usage.EdgeRow
+ obs []analytics.Obs
+ resp []reqrec.Response
+ match []reqrec.Match
+}
+
+// take waits for every handler on both boxes to return, then drains both
+// meters for host and returns each box's new observations and records.
+func (x *fwScene) take(t *testing.T, host string) (annie, betty fwBox) {
+ t.Helper()
+ laWaitFor(t, "both edges' handlers to return", func() bool {
+ return x.a.served.Load() == x.a.calls.Load() && x.b.served.Load() == x.b.calls.Load()
+ })
+ box := func(m *UsageMeter, obs *memAnalytics, rec *lockedRecorder) fwBox {
+ var b fwBox
+ b.use = m.Drain()[host]
+ all := obs.snap()
+ b.obs = all[x.obs[obs]:]
+ x.obs[obs] = len(all)
+ rec.mu.Lock()
+ seen := x.seen[rec]
+ b.resp = append([]reqrec.Response(nil), rec.resp[seen[0]:]...)
+ b.match = append([]reqrec.Match(nil), rec.match[seen[1]:]...)
+ x.seen[rec] = [2]int{len(rec.resp), len(rec.match)}
+ rec.mu.Unlock()
+ return b
+ }
+ return box(x.aMeter, x.aObs, x.aRec), box(x.bMeter, x.bObs, x.bRec)
+}
+
+// wantNothing: the box recorded nothing at all.
+func wantNothing(t *testing.T, step string, b fwBox) {
+ t.Helper()
+ if b.use.Requests != 0 || b.use.BytesOut != 0 || b.use.RateCeiling != 0 || b.use.RateShed != 0 ||
+ len(b.obs) != 0 || len(b.resp) != 0 || len(b.match) != 0 {
+ t.Fatalf("%s: the forwarding box recorded usage %+v, %d observations, %d responses, %d matches; want nothing",
+ step, b.use, len(b.obs), len(b.resp), len(b.match))
+ }
+}
+
+// wantOneDelivery: the box recorded one request of n bytes, as a hop, in
+// usage, analytics and one response record of status.
+func wantOneDelivery(t *testing.T, step string, b fwBox, n int, status int) {
+ t.Helper()
+ if b.use.Requests != 1 || b.use.BytesOut != int64(n) || b.use.HopRequests != 1 {
+ t.Fatalf("%s: the holder metered %+v, want one hop request of %d bytes", step, b.use, n)
+ }
+ if len(b.obs) != 1 || b.obs[0].Bytes != int64(n) || b.obs[0].Status != status {
+ t.Fatalf("%s: the holder observed %+v, want one observation of %d bytes, status %d", step, b.obs, n, status)
+ }
+ if len(b.resp) != 1 || b.resp[0].Status != status || len(b.match) != 0 {
+ t.Fatalf("%s: the holder recorded responses %+v matches %+v, want one response %d", step, b.resp, b.match, status)
+ }
+}
+
+func (x *fwScene) wantNote(t *testing.T, want ...fwNote) {
+ t.Helper()
+ got := x.aAct.noted()
+ if len(got) != len(want) {
+ t.Fatalf("notes = %+v, want %+v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("note %d = %+v, want %+v", i, got[i], want[i])
+ }
+ }
+}
+
+// ---- the forward -------------------------------------------------------------
+
+func TestFrontForwardReachesTheHolder(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+ resp, body := x.fetch(t, fwHost, "/deep?q=1")
+ if resp.StatusCode != http.StatusOK || body != "betty|"+fwHost+"|/deep" {
+ t.Fatalf("GET = %d %q, want betty's 200", resp.StatusCode, body)
+ }
+ annie, betty := x.take(t, fwHost)
+ wantNothing(t, "a forward", annie)
+ // Metered as a hop: betty saw a verified one.
+ wantOneDelivery(t, "a forward", betty, len(body), http.StatusOK)
+ if n := x.aApp.n.Load(); n != 0 {
+ t.Fatalf("annie's app saw %d requests", n)
+ }
+ if got := x.aAct.asked.Load(); got != 1 {
+ t.Fatalf("annie asked its activator %d times, want 1", got)
+ }
+ // One hop: betty never asks where to send a hop.
+ if got := x.bAct.asked.Load(); got != 0 {
+ t.Fatalf("betty asked its activator %d times for a hop, want 0", got)
+ }
+ x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusOK}})
+}
+
+func TestFrontForwardRunsNoLocalStep(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+
+ t.Run("a gate", func(t *testing.T) {
+ cookie := gate.CookieName + "=" + gate.Mint(fwGatedHost, x.hash, time.Now().Add(time.Hour))
+ resp, body := x.fetch(t, fwGatedHost, "/in", "Cookie", cookie)
+ if resp.StatusCode != http.StatusOK || body != "betty|"+fwGatedHost+"|/in" {
+ t.Fatalf("with the cookie = %d %q, want betty's 200", resp.StatusCode, body)
+ }
+ annie, betty := x.take(t, fwGatedHost)
+ wantNothing(t, "a gated pass", annie)
+ wantOneDelivery(t, "a gated pass", betty, len(body), http.StatusOK)
+
+ calls := x.b.calls.Load()
+ resp, body = x.fetch(t, fwGatedHost, "/in")
+ if resp.StatusCode != http.StatusUnauthorized || !strings.Contains(body, gate.LoginPath) {
+ t.Fatalf("without the cookie = %d %q, want the login page", resp.StatusCode, body)
+ }
+ if got := x.b.calls.Load() - calls; got != 1 {
+ t.Fatalf("betty saw %d requests for the refusal, want 1: annie's gate answered", got)
+ }
+ annie, betty = x.take(t, fwGatedHost)
+ wantNothing(t, "a gated refusal", annie)
+ wantOneDelivery(t, "a gated refusal", betty, len(body), http.StatusUnauthorized)
+ })
+
+ t.Run("b assets", func(t *testing.T) {
+ step := func(name, path string, wantStatus int, hdr ...string) *http.Response {
+ t.Helper()
+ resp, body := x.fetch(t, fwAssetHost, path, hdr...)
+ if resp.StatusCode != wantStatus {
+ t.Fatalf("%s = %d %q, want %d", name, resp.StatusCode, body, wantStatus)
+ }
+ annie, betty := x.take(t, fwAssetHost)
+ wantNothing(t, name, annie)
+ wantOneDelivery(t, name, betty, len(body), wantStatus)
+ return resp
+ }
+ // Carlos-Cache does not cross a hop (scrubBackhaulResponse), so the
+ // catch is read off betty's store and app.
+ get := step("GET", "/assets/app.js", http.StatusOK)
+ appKey := assetcache.Key{Account: "abc", App: "shop", Gen: laGen, Host: fwAssetHost, Path: "/assets/app.js"}
+ if _, ok := x.bStore.Get(appKey); !ok {
+ t.Fatal("betty's asset cache did not catch the GET")
+ }
+ step("HEAD", "/assets/app.js", http.StatusOK)
+ step("range", "/assets/app.js", http.StatusPartialContent, "Range", "bytes=0-4")
+ step("conditional", "/assets/app.js", http.StatusNotModified, "If-None-Match", get.Header.Get("ETag"))
+ if n := x.bApp.assetRequests.Load(); n != 1 {
+ t.Fatalf("betty's app saw %d asset requests, want the one fill", n)
+ }
+
+ // Two coalesced GETs: the second waits on betty's fill.
+ lead := x.fetchAsync(fwAssetHost, "/assets/held.js")
+ e2eStarted(t, x.bApp.started, lead)
+ rest := x.fetchAsync(fwAssetHost, "/assets/held.js")
+ key := assetcache.Key{Account: "abc", App: "shop", Gen: laGen, Host: fwAssetHost, Path: "/assets/held.js"}
+ laWaitFor(t, "the second GET to join betty's fill", func() bool { return flightWaitersOf(x.b.edge, key.ID()) == 1 })
+ x.bApp.release()
+ for _, ch := range []<-chan e2eResult{lead, rest} {
+ if r := e2eAwait(t, ch); r.resp.StatusCode != http.StatusOK || r.body != fwAssetBody {
+ t.Fatalf("coalesced GET = %d %q", r.resp.StatusCode, r.body)
+ }
+ }
+ annie, betty := x.take(t, fwAssetHost)
+ wantNothing(t, "coalesced", annie)
+ if betty.use.Requests != 2 || betty.use.BytesOut != int64(2*len(fwAssetBody)) || len(betty.obs) != 2 || len(betty.resp) != 2 {
+ t.Fatalf("coalesced: the holder metered %+v, %d observations, %d records; want two of %d bytes each",
+ betty.use, len(betty.obs), len(betty.resp), len(fwAssetBody))
+ }
+ if n := x.bApp.heldRequests.Load(); n != 1 {
+ t.Fatalf("betty's app saw %d requests for the coalesced path, want one fill", n)
+ }
+
+ // Annie filled nothing and asked its app nothing.
+ if s := x.aStore.Stats(); s.Entries != 0 || s.Reserved != 0 {
+ t.Fatalf("annie's asset store holds %+v", s)
+ }
+ if n := x.aApp.n.Load(); n != 0 {
+ t.Fatalf("annie's app saw %d requests", n)
+ }
+ if s := x.bStore.Stats(); s.Entries != 2 {
+ t.Fatalf("betty's asset store holds %+v, want the two paths", s)
+ }
+ })
+
+ t.Run("c guard and not found", func(t *testing.T) {
+ resp, body := x.fetch(t, fwHost, "/.env")
+ if resp.StatusCode != http.StatusOK || !strings.HasPrefix(body, "betty|") {
+ t.Fatalf("watched = %d %q, want betty's 200", resp.StatusCode, body)
+ }
+ annie, betty := x.take(t, fwHost)
+ wantNothing(t, "watched", annie)
+ if len(betty.match) != 1 || betty.match[0].Kind != reqrec.KindWatch || len(betty.resp) != 0 {
+ t.Fatalf("watched: the holder recorded matches %+v responses %+v, want one watch match", betty.match, betty.resp)
+ }
+
+ resp, body = x.fetch(t, fwHost, "/missing")
+ if resp.StatusCode != http.StatusNotFound {
+ t.Fatalf("missing = %d %q, want 404", resp.StatusCode, body)
+ }
+ annie, betty = x.take(t, fwHost)
+ wantNothing(t, "not found", annie)
+ wantOneDelivery(t, "not found", betty, len(body), http.StatusNotFound)
+ })
+
+ t.Run("d rate limit observed", func(t *testing.T) {
+ x.fetch(t, fwRateHost, "/") // spends the backstop's one token, at betty
+ x.take(t, fwRateHost)
+ for i := range 3 {
+ if resp, _ := x.fetch(t, fwRateHost, "/"); resp.StatusCode != http.StatusOK {
+ t.Fatalf("request %d = %d, want observe mode to serve", i, resp.StatusCode)
+ }
+ annie, betty := x.take(t, fwRateHost)
+ wantNothing(t, fmt.Sprintf("rate %d", i), annie)
+ if betty.use.RateCeiling != 1 || betty.use.Requests != 1 {
+ t.Fatalf("rate %d: the holder counted %+v, want one request over the backstop", i, betty.use)
+ }
+ }
+ if n := x.aApp.n.Load(); n != 0 {
+ t.Fatalf("annie's app saw %d requests", n)
+ }
+ })
+}
+
+func TestForwardHAHolderLostHost(t *testing.T) {
+ x := newFwScene(t, fwOpts{bettyLacks: true})
+ resp, body := x.fetch(t, fwHost, "/")
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" {
+ t.Fatalf("GET = %d Retry-After %q %q, want betty's no-route 503", resp.StatusCode, resp.Header.Get("Retry-After"), body)
+ }
+ if v := resp.Header.Values(holderHeader); len(v) != 0 {
+ t.Fatalf("%s = %q, want none", holderHeader, v)
+ }
+ x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusServiceUnavailable}})
+ if n := x.aApp.n.Load(); n != 0 {
+ t.Fatalf("annie's app saw %d requests", n)
+ }
+}
+
+func TestFrontForwardSkips(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+ local := func(t *testing.T, host, body string) {
+ t.Helper()
+ if !strings.HasPrefix(body, "annie|"+host+"|") {
+ t.Fatalf("%s: body %q, want annie's own app", host, body)
+ }
+ }
+ wantNotAsked := func(t *testing.T) {
+ t.Helper()
+ if n := x.aAct.asked.Load(); n != 0 {
+ t.Fatalf("the activator was asked %d times", n)
+ }
+ if notes := x.aAct.noted(); len(notes) != 0 {
+ t.Fatalf("notes = %+v", notes)
+ }
+ }
+ direct := func(t *testing.T, r *http.Request, up upstream, hopped, isDoor bool) {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ if x.a.edge.frontForwardHA(rec, r, fwHost, up, hopped, isDoor) {
+ t.Fatal("frontForwardHA answered")
+ }
+ if rec.Code != http.StatusOK || rec.Body.Len() != 0 || len(rec.Header()) != 0 {
+ t.Fatalf("frontForwardHA wrote %d %q %v", rec.Code, rec.Body.String(), rec.Header())
+ }
+ }
+ haUp, ok := x.a.edge.lookupUpstream(fwHost)
+ if !ok || !haUp.route.HA || !haUp.hibernating || haUp.regional != regionalNone {
+ t.Fatalf("test bug: %s is not a local HA activator route: %+v", fwHost, haUp)
+ }
+ newReq := func() *http.Request {
+ r := httptest.NewRequest(http.MethodGet, "https://"+fwHost+"/", nil)
+ r.RemoteAddr = "203.0.113.9:4000"
+ return r
+ }
+
+ t.Run("verified hop", func(t *testing.T) {
+ resp, body := x.fetch(t, fwHost, "/hop", hopHeader, "1", hopAuthHeader, signHop(x.key, fwHost, time.Now()))
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("hop = %d %q", resp.StatusCode, body)
+ }
+ local(t, fwHost, body)
+ r := newReq()
+ direct(t, r.WithContext(withHopVerified(r.Context())), haUp, false, false)
+ direct(t, newReq(), haUp, true, false)
+ wantNotAsked(t)
+ })
+ t.Run("door call", func(t *testing.T) {
+ r := newReq()
+ r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{Account: "abc", App: "shop"}))
+ rec := httptest.NewRecorder()
+ x.a.edge.ServeHTTP(rec, r)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("door call = %d %q", rec.Code, rec.Body.String())
+ }
+ local(t, fwHost, rec.Body.String())
+ direct(t, newReq(), haUp, false, true)
+ wantNotAsked(t)
+ })
+ t.Run("from a tunnel", func(t *testing.T) {
+ old := fromTunnel
+ fromTunnel = func(context.Context) bool { return true }
+ defer func() { fromTunnel = old }()
+ direct(t, newReq(), haUp, false, false)
+ wantNotAsked(t)
+ })
+ t.Run("regional name", func(t *testing.T) {
+ for _, mode := range []regionalMode{regionalServe, regionalDeny} {
+ up := haUp
+ up.regional = mode
+ direct(t, newReq(), up, false, false)
+ }
+ wantNotAsked(t)
+ })
+ t.Run("not HA", func(t *testing.T) {
+ _, body := x.fetch(t, fwLegacyHost, "/")
+ local(t, fwLegacyHost, body)
+ up := haUp
+ up.route.HA = false
+ direct(t, newReq(), up, false, false)
+ wantNotAsked(t)
+ })
+ t.Run("not activator-managed", func(t *testing.T) {
+ if err := x.a.reg.SetHA(e2eHomedHost); err != nil {
+ t.Fatal(err)
+ }
+ if err := x.a.edge.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if up, ok := x.a.edge.lookupUpstream(e2eHomedHost); !ok || !up.route.HA || up.hibernating {
+ t.Fatalf("test bug: %s is not an HA service route: %+v", e2eHomedHost, up)
+ }
+ resp, body := x.fetch(t, e2eHomedHost, "/")
+ if resp.StatusCode != http.StatusOK || e2eParseApp(t, body).marker != e2eHomeMarker {
+ t.Fatalf("service = %d %q, want annie's own", resp.StatusCode, body)
+ }
+ up := haUp
+ up.hibernating = false
+ direct(t, newReq(), up, false, false)
+ wantNotAsked(t)
+ })
+ t.Run("an activator without the interface", func(t *testing.T) {
+ y := newFwScene(t, fwOpts{aAct: fwPlainAct{}})
+ calls := y.b.calls.Load()
+ _, body := y.fetch(t, fwHost, "/")
+ local(t, fwHost, body)
+ if n := y.b.calls.Load() - calls; n != 0 {
+ t.Fatalf("betty saw %d requests", n)
+ }
+ })
+ if n := x.bApp.n.Load(); n != 0 {
+ t.Fatalf("betty's app saw %d requests", n)
+ }
+}
+
+func TestForwardHANotInView(t *testing.T) {
+ x := newFwScene(t, fwOpts{aTarget: "carol"})
+ if err := x.seed.Delete(context.Background(), "control/edges/carol.json"); err != nil {
+ t.Fatal(err)
+ }
+ x.converge(t)
+ if _, ok := x.a.homes.boxInView("carol", time.Now()); ok {
+ t.Fatal("test bug: carol is in view")
+ }
+ calls := x.b.calls.Load()
+ resp, body := x.fetch(t, fwHost, "/")
+ if resp.StatusCode != http.StatusOK || !strings.HasPrefix(body, "annie|") {
+ t.Fatalf("GET = %d %q, want annie's own 200", resp.StatusCode, body)
+ }
+ if n := x.b.calls.Load() - calls; n != 0 {
+ t.Fatalf("betty saw %d requests", n)
+ }
+ x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardNotInView}})
+ // Served here, it is recorded here.
+ annie, _ := x.take(t, fwHost)
+ if annie.use.Requests != 1 || annie.use.HopRequests != 0 {
+ t.Fatalf("annie metered %+v, want its own one request", annie.use)
+ }
+}
+
+func TestForwardHADialFailureIs503RetryTen(t *testing.T) {
+ stall := func(t *testing.T) {
+ t.Helper()
+ old := forwardDial
+ forwardDial = func(ctx context.Context, _, _ string) (net.Conn, error) {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ t.Cleanup(func() { forwardDial = old })
+ }
+ forward := func(t *testing.T, x *fwScene) {
+ t.Helper()
+ start := time.Now()
+ resp, body := x.fetch(t, fwHost, "/")
+ took := time.Since(start)
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "10" ||
+ body != "instance is waking elsewhere; retry shortly\n" {
+ t.Fatalf("GET = %d Retry-After %q %q, want the unreachable 503", resp.StatusCode, resp.Header.Get("Retry-After"), body)
+ }
+ if took < forwardDialTimeout-100*time.Millisecond || took >= backhaulDialTimeout {
+ t.Fatalf("the unreachable answer took %v, want about %v", took, forwardDialTimeout)
+ }
+ notes := x.aAct.noted()
+ if len(notes) == 0 || notes[len(notes)-1] != (fwNote{fwHost, ForwardResult{Outcome: ForwardUnreachable}}) {
+ t.Fatalf("notes = %+v, want ForwardUnreachable last", notes)
+ }
+ if n := x.bApp.n.Load(); n != 0 {
+ t.Fatalf("betty's app saw %d requests", n)
+ }
+ }
+ // backhaulTo the same address: every box here is dialled on annie's
+ // port, so the hop lands on annie, which serves it itself (a verified
+ // hop is never forwarded). It succeeds whatever the forward's dial seam
+ // does, because it dials through its own 5 s transport.
+ backhaul := func(t *testing.T, x *fwScene) {
+ t.Helper()
+ dial, ok := x.a.homes.boxInView("betty", time.Now())
+ if !ok {
+ t.Fatal("test bug: betty is out of view")
+ }
+ r := httptest.NewRequest(http.MethodGet, "https://"+fwHost+"/hopped", nil)
+ r.RemoteAddr = "203.0.113.9:4000"
+ rec := httptest.NewRecorder()
+ if !x.a.edge.backhaulTo(rec, r, fwHost, dial, "betty") {
+ t.Fatal("backhaulTo did not answer")
+ }
+ if rec.Code != http.StatusOK || rec.Body.String() != "annie|"+fwHost+"|/hopped" {
+ t.Fatalf("backhaulTo = %d %q, want the hop served", rec.Code, rec.Body.String())
+ }
+ bt, ok := x.a.edge.backhaulTransports.Load(dial)
+ if !ok || bt.(*http.Transport).TLSHandshakeTimeout != backhaulDialTimeout {
+ t.Fatalf("backhaul transport for %s = %v, want its 5 s one", dial, bt)
+ }
+ }
+ wantTwoTransports := func(t *testing.T, x *fwScene) {
+ t.Helper()
+ dial, _ := x.a.homes.boxInView("betty", time.Now())
+ bt, _ := x.a.edge.backhaulTransports.Load(dial)
+ ft, ok := x.a.edge.forwardTransports.Load(dial)
+ if !ok || ft == bt {
+ t.Fatalf("forward transport %v, backhaul transport %v: want two", ft, bt)
+ }
+ }
+ t.Run("forward then backhaul", func(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+ stall(t)
+ forward(t, x)
+ backhaul(t, x)
+ wantTwoTransports(t, x)
+ })
+ t.Run("backhaul then forward", func(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+ stall(t)
+ backhaul(t, x)
+ forward(t, x)
+ wantTwoTransports(t, x)
+ })
+}
+
+func TestForwardHAReadsHolderHeader(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+ for i, ref := range []string{"carol", "none"} {
+ resp, _ := x.fetch(t, fwHost, "/holder?ref="+ref)
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get(holderHeader) != ref {
+ t.Fatalf("GET = %d %s %q, want betty's 503 naming %s", resp.StatusCode, holderHeader, resp.Header.Get(holderHeader), ref)
+ }
+ notes := x.aAct.noted()
+ if len(notes) != i+1 || notes[i] != (fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusServiceUnavailable, Holder: ref}}) {
+ t.Fatalf("notes = %+v, want ForwardDone 503 %q", notes, ref)
+ }
+ }
+}
+
+func TestForwardHAUpgradeSwitchesProtocols(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+ raw, err := net.DialTimeout("tcp", x.a.tlsAddr, 10*time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := tls.Client(raw, &tls.Config{ServerName: fwHost, RootCAs: x.ca.pool, MinVersion: tls.VersionTLS12})
+ defer c.Close()
+ c.SetDeadline(time.Now().Add(10 * time.Second))
+ fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", fwHost)
+ br := bufio.NewReader(c)
+ resp, err := http.ReadResponse(br, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("handshake = %d, want 101", resp.StatusCode)
+ }
+ fmt.Fprint(c, "ping\n")
+ if line, err := br.ReadString('\n'); err != nil || line != "betty:ping\n" {
+ t.Fatalf("echo = %q %v, want betty's", line, err)
+ }
+ c.Close()
+ laWaitFor(t, "the forward's note", func() bool { return len(x.aAct.noted()) == 1 })
+ x.wantNote(t, fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Status: http.StatusSwitchingProtocols}})
+}
diff --git a/internal/edge/regional.go b/internal/edge/regional.go
index 7009ac93a..76b7ad258 100644
--- a/internal/edge/regional.go
+++ b/internal/edge/regional.go
@@ -34,7 +34,8 @@ const (
)
// regionalObserve is a test hook: nil in production, an atomic load per call.
-// Events: "backhaul" (backhaulTo, before dialling), "asset-fill"
+// Events: "backhaul" (backhaulTo, before dialling), "forward" (a region HA
+// forward, forwardHA, before dialling), "asset-fill"
// (serveAssetFar, when the far catch takes a request, before any fill or
// forward), "home" and "exact-home" (Home and ExactHome returning a dial
// target).