carlos / platform Public

edge: one reload mutex, and the sweep of open upgrades (#471 Task 4)

Reload takes e.reloadMu first (after the nil-in-production enter hook)
and holds it to return, so Reloads run one at a time and publish maps in
the order they read the registry. Right after the swap, sweepUpgrades
takes every reservation whose host and path no longer resolve to its
recorded tenancy out of the registry, then releases each on its own
goroutine outside every lock. Watch records a fingerprint only after its
own Reload swapped and swept.

Test seams, nil in production: reloadHooks at enter, afterRead,
beforePublish, afterPublish, afterSweep and around Watch's record;
Edge.watchTick; reserveUpgrade's beforeReserve and afterInsert.

Tests: the two-Reload witness (spec §8.2 case 18, items 1-9 at the
registry level, decided by TryLock and an ordered event log), a failed
Reload sweeps nothing, no false closes across 20 Reloads, each lost
tenancy closes, a reservation racing the swap, the sweep releases off
the Reload, and the go/ast guard that Reload is the only publisher.
Spec §7 gains the Task 4 census paragraph (no new unit on the card).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev f7754746f3ea631650603cd87b4ee05d52e632cc parent e5d2d14
5 files changed, +1,270 −3
  • docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md +27 −0
  • internal/edge/edge.go +85 −3
  • internal/edge/reload_guard_test.go +236 −0
  • internal/edge/reload_serial_test.go +878 −0
  • internal/edge/upgrades.go +44 −0
diff --git a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
index b5b8cc269..50b7da731 100644
--- a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
+++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
@@ -1011,6 +1011,33 @@ They have no row, so the `internal/edge` envelope re-pin covers them. The
`RoundTripUpgrade`: the marker counts only on a 200 (Task 2 review). The
seal is unchanged.
+Task 4's card (`make census-card`) shows no new unit and no new class: the
+same three rows as Task 3 (`body` `Edge.ServeHTTP`, read sites unchanged at
+29; `reads` `Edge.Reload` with Task 3's `+registry:Account`, `App` and
+`Tunnel`; the two `new` tunnelclient `Read` units) and the same two
+envelopes re-pinned. What Task 4 changed, and why the card has no row
+for it:
+
+- `Edge.Reload`: the reload mutex (`e.reloadMu`, taken first, held to
+ return), the five nil-in-production test hooks and the `sweepUpgrades`
+ call right after the swap. No registry query, file or root-owned state
+ is added: the hooks run only when a test sets `Edge.hooks`, and the
+ sweep reads the map Reload has just built. The card's row for `Reload`
+ stays Task 3's `reads`; the lock and the sweep call are the `body`
+ change this section lists, which the scanner does not show separately
+ for a unit already listed.
+- `Edge.Watch`: a test tick channel in place of its ticker when
+ `Edge.watchTick` is set, and the two record hooks around `last = fp`.
+ It reads the same `Fingerprint` as before; no row.
+- New, with no row because they read nothing: `Edge.sweepUpgrades` (map
+ operations and `lookupUpstreamPath` under `openUpgrades.mu`, then one
+ `release` goroutine per lost reservation), `reloadHooks`, the
+ `reloadMu`, `hooks`, `reloadSeq` and `watchTick` fields, and the two
+ `reserveUpgrade` seams (`openUpgrades.beforeReserve` and `afterInsert`).
+ The `internal/edge` envelope re-pin covers them.
+
+The seal is unchanged. No overlay is proposed here (Task 9).
+
The reviewer is Astra (Claude author), recorded on #280.
Copy. Two new cause descriptions in `internal/apperr/availability.go`
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 99bfcd2d6..6096499da 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -364,6 +364,38 @@ type Edge struct {
// (upgrades.go, #471): reservations by host and counts per channel
// connection. Its lock is never held with upgradesMu.
open openUpgrades
+ // reloadMu makes Reloads run one at a time (#471 spec §4.6.1): Reload
+ // takes it first and holds it to return, through its registry reads,
+ // the build, SetDynamicAuth, the swap and the sweep of open upgrades.
+ // So maps are published in the order their registry reads were made.
+ // It is the outermost lock: request serving and upgrade admission never
+ // take it, and nothing holding openUpgrades.mu or TunnelHub.mu waits
+ // for it.
+ reloadMu sync.Mutex
+ // hooks, reloadSeq and watchTick are test seams, nil and unused in
+ // production: Reload's and Watch's hooks at fixed points (reloadHooks),
+ // the counter that numbers each Reload for them, and a tick channel
+ // that stands in for Watch's 2 s ticker.
+ hooks *reloadHooks
+ reloadSeq atomic.Uint64
+ watchTick <-chan time.Time
+}
+
+// reloadHooks are Reload's and Watch's test hooks (#471 spec §8.2 case
+// 18). Edge.hooks is nil in production, so none runs. Each Reload numbers
+// itself and passes its id. enter runs before Reload takes reloadMu;
+// afterRead after its last registry read, and an error from it is returned
+// as the Reload's, before anything is applied; beforePublish just before
+// the swap, and an error from it is returned before the swap; afterPublish
+// after the swap and afterSweep after the sweep. Errors from enter,
+// afterPublish and afterSweep are ignored: nothing may come between a
+// swap and its sweep. Watch calls beforeRecord and afterRecord around
+// recording a fingerprint as handled.
+//
+// The type shares its name with Edge's OnReload field; they are unrelated.
+type reloadHooks struct {
+ enter, afterRead, beforePublish, afterPublish, afterSweep func(id uint64) error
+ beforeRecord, afterRecord func(fp string)
}
// RunOption configures the Edge that Run/RunWithActivator* builds, before it
@@ -737,7 +769,23 @@ func (e *Edge) statusHandlerFor(rt registry.Route) http.Handler {
// Reload rebuilds the host→backend map from the registry and swaps it in
// atomically. Safe to call while serving.
+//
+// Reloads run one at a time, under e.reloadMu (#471 spec §4.6.1), so each
+// reads the registry after the previous one published and maps are
+// published in the order they were read. Every caller (New, EnableStatic,
+// enableTunnelsFromEnv, Watch, SIGHUP, the agent's layout pass) takes the
+// lock by calling Reload. Right after the swap, sweepUpgrades closes every
+// open upgrade the new map no longer serves for its tenancy.
func (e *Edge) Reload() error {
+ var id uint64
+ if h := e.hooks; h != nil {
+ id = e.reloadSeq.Add(1)
+ if h.enter != nil {
+ _ = h.enter(id)
+ }
+ }
+ e.reloadMu.Lock()
+ defer e.reloadMu.Unlock()
routes, err := e.reg.List()
if err != nil {
return err
@@ -1217,6 +1265,12 @@ func (e *Edge) Reload() error {
if err != nil {
return err
}
+ // The last registry read: nothing has been applied yet.
+ if h := e.hooks; h != nil && h.afterRead != nil {
+ if err := h.afterRead(id); err != nil {
+ return err
+ }
+ }
e.foldRegional(m, routes, regionalRows)
// Refusals hold through every fold above: last, so nothing re-adds them.
refusedHosts(m, verdict.Refused)
@@ -1245,7 +1299,22 @@ func (e *Edge) Reload() error {
// host being deleted is a moment early, a 503 for a host being added is
// simply wrong.
e.probers.Sync(probeSpecs)
+ if h := e.hooks; h != nil && h.beforePublish != nil {
+ if err := h.beforePublish(id); err != nil {
+ return err
+ }
+ }
+ // The one publication of the map (guarded by TestReloadIsTheOnlyPublisher),
+ // then at once the sweep: every open upgrade is judged against the map
+ // just published, under reloadMu, so no older map can replace it first.
e.upstreams.Store(&m)
+ if h := e.hooks; h != nil && h.afterPublish != nil {
+ _ = h.afterPublish(id)
+ }
+ e.sweepUpgrades()
+ if h := e.hooks; h != nil && h.afterSweep != nil {
+ _ = h.afterSweep(id)
+ }
// Reconcile the activator with the new route set: a host un-flagged (or
// removed) since the last reload may still have a live child holding its
// socket and lease — retire it so a systemd unit can take over cleanly.
@@ -2846,13 +2915,17 @@ func (e *Edge) Watch(stop <-chan struct{}) {
var last string
errs := 0
reloadErrs := 0
- tick := time.NewTicker(2 * time.Second)
- defer tick.Stop()
+ tickC := e.watchTick // a test's ticks; nil in production
+ if tickC == nil {
+ tick := time.NewTicker(2 * time.Second)
+ defer tick.Stop()
+ tickC = tick.C
+ }
for {
select {
case <-stop:
return
- case <-tick.C:
+ case <-tickC:
}
fp, err := e.reg.Fingerprint()
if err != nil {
@@ -2888,7 +2961,16 @@ func (e *Edge) Watch(stop <-chan struct{}) {
continue
}
reloadErrs = 0
+ // Reload returned nil, so it has swapped and swept (it holds
+ // reloadMu to return), and fp was read before it took the lock: the
+ // state fp names is never newer than the map it published.
+ if h := e.hooks; h != nil && h.beforeRecord != nil {
+ h.beforeRecord(fp)
+ }
last = fp
+ if h := e.hooks; h != nil && h.afterRecord != nil {
+ h.afterRecord(fp)
+ }
log.Printf("edge: registry changed — reloaded (%d route(s))", len(e.current()))
}
}
diff --git a/internal/edge/reload_guard_test.go b/internal/edge/reload_guard_test.go
new file mode 100644
index 000000000..57e6895bf
--- /dev/null
+++ b/internal/edge/reload_guard_test.go
@@ -0,0 +1,236 @@
+package edge
+
+// Tunnel WebSockets (#471) Task 4, spec §8.2 case 19: Reload is the only
+// publisher of the hub's map, it publishes under e.reloadMu, and the sweep
+// follows its swap. A source check over this package's non-test files, so
+// a future publisher, an early registry read or a sweep moved elsewhere
+// fails here by name.
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// funcName is fd's name as "(*Recv).Name" or "Name".
+func funcName(fd *ast.FuncDecl) string {
+ if fd.Recv == nil || len(fd.Recv.List) == 0 {
+ return fd.Name.Name
+ }
+ switch t := fd.Recv.List[0].Type.(type) {
+ case *ast.StarExpr:
+ if id, ok := t.X.(*ast.Ident); ok {
+ return "(*" + id.Name + ")." + fd.Name.Name
+ }
+ case *ast.Ident:
+ return "(" + t.Name + ")." + fd.Name.Name
+ }
+ return fd.Name.Name
+}
+
+// selChain is a selector chain as text ("e.upstreams.Store"), or "".
+func selChain(x ast.Expr) string {
+ switch v := x.(type) {
+ case *ast.Ident:
+ return v.Name
+ case *ast.SelectorExpr:
+ if base := selChain(v.X); base != "" {
+ return base + "." + v.Sel.Name
+ }
+ }
+ return ""
+}
+
+// callSel is the selector chain a statement calls, or "".
+func callSel(s ast.Stmt) string {
+ var call *ast.CallExpr
+ switch v := s.(type) {
+ case *ast.ExprStmt:
+ call, _ = v.X.(*ast.CallExpr)
+ case *ast.DeferStmt:
+ call = v.Call
+ }
+ if call == nil {
+ return ""
+ }
+ return selChain(call.Fun)
+}
+
+// isHookIf reports whether s is one of Reload's test-hook guards:
+// `if h := e.hooks; h != nil ...`.
+func isHookIf(s ast.Stmt) bool {
+ is, ok := s.(*ast.IfStmt)
+ if !ok {
+ return false
+ }
+ as, ok := is.Init.(*ast.AssignStmt)
+ return ok && len(as.Rhs) == 1 && selChain(as.Rhs[0]) == "e.hooks" &&
+ strings.HasPrefix(condText(is.Cond), "h != nil")
+}
+
+// condText renders a condition crudely enough to recognise its first clause.
+func condText(x ast.Expr) string {
+ switch v := x.(type) {
+ case *ast.BinaryExpr:
+ l, r := condText(v.X), condText(v.Y)
+ return l + " " + v.Op.String() + " " + r
+ case *ast.Ident:
+ return v.Name
+ case *ast.SelectorExpr:
+ return selChain(v)
+ }
+ return "?"
+}
+
+func TestReloadIsTheOnlyPublisher(t *testing.T) {
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ type site struct {
+ fn string
+ pos token.Position
+ }
+ var stores, dynAuth, sweeps, reloadMu []site
+ var reload *ast.FuncDecl
+ for _, f := range files {
+ if strings.HasSuffix(f, "_test.go") {
+ continue
+ }
+ af, err := parser.ParseFile(fset, f, nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range af.Decls {
+ fd, ok := d.(*ast.FuncDecl)
+ if !ok || fd.Body == nil {
+ continue
+ }
+ name := funcName(fd)
+ if name == "(*Edge).Reload" {
+ reload = fd
+ }
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ switch v := n.(type) {
+ case *ast.CallExpr:
+ sel, ok := v.Fun.(*ast.SelectorExpr)
+ if !ok {
+ return true
+ }
+ at := site{name, fset.Position(v.Pos())}
+ switch {
+ case sel.Sel.Name == "Store" && strings.HasSuffix(selChain(sel.X), ".upstreams"):
+ stores = append(stores, at)
+ case sel.Sel.Name == "SetDynamicAuth":
+ dynAuth = append(dynAuth, at)
+ case sel.Sel.Name == "sweepUpgrades":
+ sweeps = append(sweeps, at)
+ }
+ case *ast.SelectorExpr:
+ if v.Sel.Name == "reloadMu" {
+ reloadMu = append(reloadMu, site{name, fset.Position(v.Pos())})
+ }
+ }
+ return true
+ })
+ }
+ }
+ if reload == nil {
+ t.Fatal("no (*Edge).Reload in the package")
+ }
+ only := func(what string, sites []site, n int) {
+ t.Helper()
+ for _, s := range sites {
+ if s.fn != "(*Edge).Reload" {
+ t.Errorf("%s called in %s (%s), want only in (*Edge).Reload", what, s.fn, s.pos)
+ }
+ }
+ if n > 0 && len(sites) != n {
+ t.Errorf("%s: %d call sites, want %d", what, len(sites), n)
+ }
+ }
+ only("e.upstreams.Store", stores, 1)
+ only("SetDynamicAuth", dynAuth, 0)
+ only("sweepUpgrades", sweeps, 1)
+ only("reloadMu", reloadMu, 0)
+ if t.Failed() {
+ return
+ }
+
+ // Reload's own body: before the lock only the enter hook's guarded
+ // call; the lock, then at once its deferred unlock; the Store and the
+ // sweep as statements of the body itself (not in a closure or a
+ // branch), the sweep after the Store with only test hooks between.
+ body := reload.Body.List
+ lock, store, sweep := -1, -1, -1
+ for i, s := range body {
+ switch callSel(s) {
+ case "e.reloadMu.Lock":
+ if lock < 0 {
+ lock = i
+ }
+ case "e.upstreams.Store":
+ store = i
+ case "e.sweepUpgrades":
+ sweep = i
+ }
+ }
+ if lock < 0 {
+ t.Fatal("Reload does not call e.reloadMu.Lock() as a statement of its body")
+ }
+ pre := body[:lock]
+ okPre := len(pre) == 2
+ if okPre {
+ ds, isDecl := pre[0].(*ast.DeclStmt)
+ okPre = isDecl
+ if okPre {
+ gd := ds.Decl.(*ast.GenDecl)
+ vs, isVal := gd.Specs[0].(*ast.ValueSpec)
+ okPre = gd.Tok == token.VAR && len(gd.Specs) == 1 && isVal && len(vs.Names) == 1 && vs.Names[0].Name == "id" && len(vs.Values) == 0
+ }
+ okPre = okPre && isHookIf(pre[1])
+ }
+ if !okPre {
+ t.Fatalf("Reload's statements before e.reloadMu.Lock() must be `var id uint64` and the enter hook's `if h := e.hooks; h != nil {...}`; found %d statement(s) starting at %s",
+ len(pre), fset.Position(reload.Body.Lbrace))
+ }
+ // Inside the enter guard: no registry read, no map use, and no call but
+ // the counter and the hook.
+ ast.Inspect(pre[1], func(n ast.Node) bool {
+ switch v := n.(type) {
+ case *ast.SelectorExpr:
+ if c := selChain(v); c == "e.reg" || c == "e.upstreams" {
+ t.Errorf("Reload uses %s before taking reloadMu (%s)", c, fset.Position(v.Pos()))
+ }
+ case *ast.CallExpr:
+ if c := selChain(v.Fun); c != "e.reloadSeq.Add" && c != "h.enter" {
+ t.Errorf("Reload calls %s before taking reloadMu (%s)", c, fset.Position(v.Pos()))
+ }
+ }
+ return true
+ })
+ if lock+1 >= len(body) || callSel(body[lock+1]) != "e.reloadMu.Unlock" {
+ t.Fatal("e.reloadMu.Lock() in Reload is not followed at once by defer e.reloadMu.Unlock()")
+ }
+ if _, isDefer := body[lock+1].(*ast.DeferStmt); !isDefer {
+ t.Fatal("the unlock after e.reloadMu.Lock() in Reload is not deferred")
+ }
+ if store < 0 {
+ t.Fatal("e.upstreams.Store is not a statement of Reload's body")
+ }
+ if sweep < 0 {
+ t.Fatal("e.sweepUpgrades() is not a statement of Reload's body")
+ }
+ if store < lock || sweep < store {
+ t.Fatalf("Reload's order is lock %d, Store %d, sweep %d; want lock, then Store, then sweep", lock, store, sweep)
+ }
+ for _, s := range body[store+1 : sweep] {
+ if !isHookIf(s) {
+ t.Fatalf("Reload runs something other than a test hook between its Store and its sweep, at %s", fset.Position(s.Pos()))
+ }
+ }
+}
diff --git a/internal/edge/reload_serial_test.go b/internal/edge/reload_serial_test.go
new file mode 100644
index 000000000..bbd1e0486
--- /dev/null
+++ b/internal/edge/reload_serial_test.go
@@ -0,0 +1,878 @@
+package edge
+
+// Tunnel WebSockets (#471) Task 4: Reloads run one at a time under
+// e.reloadMu, and the sweep after each swap closes every open upgrade the
+// new map no longer serves for its tenancy (spec §4.6.1, §8.2 cases 15 to
+// 18 at the registry level; Task 6 repeats them with real sockets).
+//
+// Every interleaving here is driven by the nil-in-production hooks
+// (reloadHooks, Edge.watchTick, openUpgrades.beforeReserve/afterInsert)
+// and decided by a TryLock or an ordered event log, never by a sleep. The
+// only waits are failure bounds.
+//
+// Accounts: fwdOwner ("bah") owns fleets home and away; fwdOther ("baj")
+// is the second account an owner change hands a fleet to.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "slices"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// upAdm is an admission for the forward row upgradeScene serves.
+var upAdm = upgradeAdmission{Host: upHost, Path: "/cable", Tenancy: upTenancy}
+
+// reloadScript drives Reload's and Watch's test hooks. Each hook appends
+// "<name>:<point>" to an ordered log (names are given to Reloads in the
+// order they enter), then waits at a barrier the test installed for that
+// event, if any, and returns the error the test set for it, if any.
+type reloadScript struct {
+ t *testing.T
+ mu sync.Mutex
+ log []string
+ names map[uint64]string
+ order []string
+ holds map[string]chan struct{}
+ fail map[string]error
+ fps []string
+ changed chan struct{}
+}
+
+// newReloadScript installs the hooks on e. order names the Reloads in the
+// order they will enter.
+func newReloadScript(t *testing.T, e *Edge, order ...string) *reloadScript {
+ t.Helper()
+ s := &reloadScript{
+ t: t, names: map[uint64]string{}, order: order,
+ holds: map[string]chan struct{}{}, fail: map[string]error{},
+ changed: make(chan struct{}, 1),
+ }
+ point := func(p string) func(uint64) error {
+ return func(id uint64) error { return s.at(id, p) }
+ }
+ e.hooks = &reloadHooks{
+ enter: point("enter"),
+ afterRead: point("afterRead"),
+ beforePublish: point("beforePublish"),
+ afterPublish: point("afterPublish"),
+ afterSweep: point("afterSweep"),
+ beforeRecord: func(fp string) {
+ s.mu.Lock()
+ s.fps = append(s.fps, fp)
+ s.mu.Unlock()
+ s.at(0, "record:before")
+ },
+ afterRecord: func(string) { s.at(0, "record:after") },
+ }
+ t.Cleanup(s.releaseAll)
+ return s
+}
+
+// hold installs a barrier at each event, before the run that reaches it.
+func (s *reloadScript) hold(evs ...string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for _, ev := range evs {
+ s.holds[ev] = make(chan struct{})
+ }
+}
+
+// failAt makes the hook at ev return err.
+func (s *reloadScript) failAt(ev string, err error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.fail[ev] = err
+}
+
+// at is every hook: id 0 is Watch's, whose events are named in full.
+func (s *reloadScript) at(id uint64, p string) error {
+ s.mu.Lock()
+ ev := p
+ if id != 0 {
+ name, ok := s.names[id]
+ if !ok {
+ name = fmt.Sprintf("R%d", id)
+ if n := len(s.names); n < len(s.order) {
+ name = s.order[n]
+ }
+ s.names[id] = name
+ }
+ ev = name + ":" + p
+ }
+ s.log = append(s.log, ev)
+ hold, err := s.holds[ev], s.fail[ev]
+ s.mu.Unlock()
+ select {
+ case s.changed <- struct{}{}:
+ default:
+ }
+ if hold != nil {
+ select {
+ case <-hold:
+ case <-time.After(10 * time.Second):
+ s.t.Errorf("%s was held for 10 s: the test never released it", ev)
+ }
+ }
+ return err
+}
+
+// release lets the run held at ev go on.
+func (s *reloadScript) release(ev string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if ch, ok := s.holds[ev]; ok {
+ close(ch)
+ delete(s.holds, ev)
+ }
+}
+
+func (s *reloadScript) releaseAll() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for ev, ch := range s.holds {
+ close(ch)
+ delete(s.holds, ev)
+ }
+}
+
+func (s *reloadScript) snapshot() []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return slices.Clone(s.log)
+}
+
+func (s *reloadScript) has(ev string) bool { return slices.Contains(s.snapshot(), ev) }
+
+// wait returns once ev is in the log; failing after 5 s.
+func (s *reloadScript) wait(ev string) {
+ s.t.Helper()
+ deadline := time.After(5 * time.Second)
+ for !s.has(ev) {
+ select {
+ case <-s.changed:
+ case <-deadline:
+ s.t.Fatalf("waited 5 s for %s; log %v", ev, s.snapshot())
+ }
+ }
+}
+
+// logIs asserts the whole log, in order.
+func (s *reloadScript) logIs(want ...string) {
+ s.t.Helper()
+ if got := s.snapshot(); !slices.Equal(got, want) {
+ s.t.Fatalf("event log:\n got %v\nwant %v", got, want)
+ }
+}
+
+// recorded is the fingerprints Watch recorded as handled.
+func (s *reloadScript) recorded() []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return slices.Clone(s.fps)
+}
+
+// startTickedWatch runs e.Watch on a test tick channel and returns it. Cleanup
+// releases every barrier, then stops Watch and waits for it to return.
+func startTickedWatch(t *testing.T, e *Edge, s *reloadScript) chan<- time.Time {
+ t.Helper()
+ tick := make(chan time.Time)
+ e.watchTick = tick
+ stop, done := make(chan struct{}), make(chan struct{})
+ go func() {
+ e.Watch(stop)
+ close(done)
+ }()
+ t.Cleanup(func() {
+ s.releaseAll()
+ close(stop)
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Error("Watch did not stop within 10 s")
+ }
+ })
+ return tick
+}
+
+// sendTick ticks Watch. The tick channel is unbuffered, so this returns
+// only once Watch is back at its select: its previous tick is handled.
+func sendTick(t *testing.T, tick chan<- time.Time) {
+ t.Helper()
+ select {
+ case tick <- time.Now():
+ case <-time.After(5 * time.Second):
+ t.Fatal("Watch did not take a tick within 5 s")
+ }
+}
+
+// goReload runs e.Reload on its own goroutine, standing in for SIGHUP.
+func goReload(e *Edge) <-chan error {
+ done := make(chan error, 1)
+ go func() { done <- e.Reload() }()
+ return done
+}
+
+func awaitReload(t *testing.T, done <-chan error, name string) {
+ t.Helper()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("Reload %s: %v", name, err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatalf("Reload %s did not return within 5 s", name)
+ }
+}
+
+// heldByAnother asserts that something holds e.reloadMu: TryLock fails.
+func heldByAnother(t *testing.T, e *Edge, who string) {
+ t.Helper()
+ if e.reloadMu.TryLock() {
+ e.reloadMu.Unlock()
+ t.Fatalf("TryLock succeeded while %s holds the reload", who)
+ }
+}
+
+// setFleetOwner changes fleet's owner through the console's writer and
+// reads it back through the production reader before going on.
+func setFleetOwner(t *testing.T, e *Edge, fleet, account string) {
+ t.Helper()
+ if err := e.reg.UpsertFleet(registry.Fleet{Name: fleet, Account: account, Bucket: fleet + "-data"}); err != nil {
+ t.Fatalf("UpsertFleet(%s, %s): %v", fleet, account, err)
+ }
+ owners, err := e.reg.FleetOwners()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if owners[fleet] != account {
+ t.Fatalf("read back: fleet %s owned by %q, want %q", fleet, owners[fleet], account)
+ }
+}
+
+func fingerprint(t *testing.T, e *Edge) string {
+ t.Helper()
+ fp, err := e.reg.Fingerprint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fp
+}
+
+// tenancyAt is the tenancy the current map serves host's /cable under.
+func tenancyAt(e *Edge, host string) (tenancy, bool) {
+ up, ok := e.lookupUpstreamPath(host, "/cable")
+ return up.tenancy, ok
+}
+
+// heldReservation is a reservation with a recording pipe and body.
+type heldReservation struct {
+ r *upgradeReservation
+ stream context.Context
+ pipe, body *countingCloser
+}
+
+func reserveHeld(t *testing.T, e *Edge, tc *tunnelConn, a upgradeAdmission) heldReservation {
+ t.Helper()
+ r, sctx, err := e.reserveUpgrade(context.Background(), a, tc, 10)
+ if err != nil {
+ t.Fatalf("reserve %s: %v", a.Host, err)
+ }
+ h := heldReservation{r: r, stream: sctx, pipe: &countingCloser{}, body: &countingCloser{}}
+ r.attach(h.pipe, h.body)
+ t.Cleanup(func() { r.release(relBody) })
+ return h
+}
+
+// open asserts the reservation is untouched: still in the registry, never
+// released, nothing closed.
+func (h heldReservation) open(t *testing.T, e *Edge, when string) {
+ t.Helper()
+ e.open.mu.Lock()
+ _, in := e.open.byHost[h.r.host][h.r]
+ e.open.mu.Unlock()
+ if !in || h.r.firstReleaser() != relNone || h.pipe.n.Load() != 0 || h.body.n.Load() != 0 || h.stream.Err() != nil {
+ t.Fatalf("%s: reservation for %s in the registry %v, firstReleaser %v, pipe closed %d, body %d, stream %v; want open",
+ when, h.r.host, in, h.r.firstReleaser(), h.pipe.n.Load(), h.body.n.Load(), h.stream.Err())
+ }
+}
+
+// swept asserts the reservation is out of the registry now and is
+// released by the sweep, its pipe and body closed once, within 2 s (the
+// sweep releases on its own goroutine).
+func (h heldReservation) swept(t *testing.T, e *Edge, when string) {
+ t.Helper()
+ e.open.mu.Lock()
+ _, in := e.open.byHost[h.r.host][h.r]
+ e.open.mu.Unlock()
+ if in {
+ t.Fatalf("%s: the reservation for %s is still in the registry", when, h.r.host)
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for h.r.firstReleaser() == relNone || h.pipe.n.Load() == 0 || h.body.n.Load() == 0 {
+ if time.Now().After(deadline) {
+ t.Fatalf("%s: 2 s after the sweep, firstReleaser %v, pipe closed %d, body %d", when, h.r.firstReleaser(), h.pipe.n.Load(), h.body.n.Load())
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if got := h.r.firstReleaser(); got != relSweep {
+ t.Fatalf("%s: firstReleaser %v, want relSweep", when, got)
+ }
+ if h.pipe.n.Load() != 1 || h.body.n.Load() != 1 || h.stream.Err() == nil {
+ t.Fatalf("%s: pipe closed %d, body %d, stream %v; want 1, 1 and ended", when, h.pipe.n.Load(), h.body.n.Load(), h.stream.Err())
+ }
+}
+
+// TestTwoReloadsInterleave is spec §8.2 case 18 at the registry level.
+func TestTwoReloadsInterleave(t *testing.T) {
+ // Items 1 to 7: A (a direct call, standing in for SIGHUP) read the
+ // registry while the owner still authorised the row; the owner changes;
+ // Watch's B must wait for A, then read, publish, sweep and record.
+ t.Run("in order", func(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ res := reserveHeld(t, hub, tc, upAdm)
+ s := newReloadScript(t, hub, "A", "B")
+ s.hold("A:afterRead", "A:beforePublish", "A:afterPublish", "A:afterSweep", "B:afterPublish", "B:afterSweep")
+ tick := startTickedWatch(t, hub, s)
+
+ // 1. A stops after its registry reads.
+ aDone := goReload(hub)
+ s.wait("A:afterRead")
+ // 2. The owner changes, read back.
+ before := fingerprint(t, hub)
+ setFleetOwner(t, hub, "home", fwdOther)
+ fp := fingerprint(t, hub)
+ if fp == before {
+ t.Fatal("the owner change did not move the fingerprint")
+ }
+ // 3. Contention, decided before anything that depends on scheduling.
+ heldByAnother(t, hub, "A")
+ // 4. Watch reads the new fingerprint and calls B, which waits.
+ sendTick(t, tick)
+ s.wait("B:enter")
+ heldByAnother(t, hub, "A")
+ if s.has("B:afterRead") {
+ t.Fatalf("B read the registry while A holds the reload: %v", s.snapshot())
+ }
+ // 5. A's barriers, one at a time.
+ s.release("A:afterRead")
+ s.wait("A:beforePublish")
+ s.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish")
+ s.release("A:beforePublish")
+ s.wait("A:afterPublish")
+ s.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish")
+ if ten, ok := tenancyAt(hub, upHost); !ok || ten != upTenancy {
+ t.Fatalf("after A's swap: %s tenancy %+v (served %v), want A's map, %+v", upHost, ten, ok, upTenancy)
+ }
+ s.release("A:afterPublish")
+ s.wait("A:afterSweep")
+ s.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep")
+ res.open(t, hub, "after A's sweep")
+ heldByAnother(t, hub, "A")
+ s.release("A:afterSweep")
+ awaitReload(t, aDone, "A")
+
+ // 6. B reads the new registry, publishes and sweeps.
+ s.wait("B:afterPublish")
+ if _, ok := tenancyAt(hub, upHost); ok {
+ t.Fatalf("after B's swap: %s is still served", upHost)
+ }
+ res.open(t, hub, "after B's swap, before its sweep")
+ s.release("B:afterPublish")
+ s.wait("B:afterSweep")
+ if s.has("record:before") {
+ t.Fatalf("Watch recorded before B returned: %v", s.snapshot())
+ }
+ res.swept(t, hub, "after B's sweep")
+ s.release("B:afterSweep")
+ s.wait("record:after")
+ s.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep",
+ "B:afterRead", "B:beforePublish", "B:afterPublish", "B:afterSweep", "record:before", "record:after")
+ if got := s.recorded(); !slices.Equal(got, []string{fp}) {
+ t.Fatalf("Watch recorded %q, want the fingerprint read after the owner change, %q", got, fp)
+ }
+ // 7. A new reservation is refused (the first, on the same fixture,
+ // was admitted).
+ if _, _, err := hub.reserveUpgrade(context.Background(), upAdm, tc, 10); !errors.Is(err, errTenancyStale) {
+ t.Fatalf("a new reservation after B: %v, want errTenancyStale", err)
+ }
+ })
+
+ // Item 8: B's registry read fails. Nothing of B is published or
+ // recorded; the next tick's C swaps, sweeps and only then records.
+ t.Run("B fails", func(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ res := reserveHeld(t, hub, tc, upAdm)
+ s := newReloadScript(t, hub, "A", "B", "C")
+ s.hold("A:afterRead", "C:enter")
+ s.failAt("B:afterRead", errors.New("registry read failed (test)"))
+ tick := startTickedWatch(t, hub, s)
+
+ aDone := goReload(hub)
+ s.wait("A:afterRead")
+ setFleetOwner(t, hub, "home", fwdOther)
+ fp := fingerprint(t, hub)
+ heldByAnother(t, hub, "A")
+ sendTick(t, tick)
+ s.wait("B:enter")
+ heldByAnother(t, hub, "A")
+ s.release("A:afterRead")
+ awaitReload(t, aDone, "A")
+ s.wait("B:afterRead")
+ // Watch takes this tick only after B returned its error.
+ sendTick(t, tick)
+ s.wait("C:enter")
+ s.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep",
+ "B:afterRead", "C:enter")
+ if got := s.recorded(); len(got) != 0 {
+ t.Fatalf("Watch recorded %q after B failed", got)
+ }
+ if ten, ok := tenancyAt(hub, upHost); !ok || ten != upTenancy {
+ t.Fatalf("after B failed: %s tenancy %+v (served %v), want A's map still current", upHost, ten, ok)
+ }
+ res.open(t, hub, "after B failed")
+ s.release("C:enter")
+ s.wait("record:after")
+ s.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep",
+ "B:afterRead", "C:enter", "C:afterRead", "C:beforePublish", "C:afterPublish", "C:afterSweep",
+ "record:before", "record:after")
+ res.swept(t, hub, "after C")
+ if got := s.recorded(); !slices.Equal(got, []string{fp}) {
+ t.Fatalf("Watch recorded %q, want %q", got, fp)
+ }
+ })
+
+ // Item 9: the revoking B runs to its sweep first; A, started after the
+ // owner change, reads only after B returned, and the host stays refused.
+ t.Run("reversed", func(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ res := reserveHeld(t, hub, tc, upAdm)
+ s := newReloadScript(t, hub, "B", "A")
+ s.hold("B:afterSweep")
+ tick := startTickedWatch(t, hub, s)
+
+ setFleetOwner(t, hub, "home", fwdOther)
+ fp := fingerprint(t, hub)
+ sendTick(t, tick)
+ s.wait("B:afterSweep")
+ res.swept(t, hub, "after B's sweep")
+ aDone := goReload(hub)
+ s.wait("A:enter")
+ heldByAnother(t, hub, "B")
+ if s.has("A:afterRead") {
+ t.Fatalf("A read the registry while B holds the reload: %v", s.snapshot())
+ }
+ s.release("B:afterSweep")
+ awaitReload(t, aDone, "A")
+ s.wait("record:after")
+
+ // B's run and Watch's record are one ordered sequence, and so is A's;
+ // A entered after B's sweep and read only after B returned. (Watch's
+ // record and A's run race once B has returned, so their relative
+ // order is not asserted.)
+ log := s.snapshot()
+ var bw, a []string
+ for _, ev := range log {
+ if ev[0] == 'A' {
+ a = append(a, ev)
+ } else {
+ bw = append(bw, ev)
+ }
+ }
+ if want := []string{"B:enter", "B:afterRead", "B:beforePublish", "B:afterPublish", "B:afterSweep", "record:before", "record:after"}; !slices.Equal(bw, want) {
+ t.Fatalf("B and Watch: %v, want %v (log %v)", bw, want, log)
+ }
+ if want := []string{"A:enter", "A:afterRead", "A:beforePublish", "A:afterPublish", "A:afterSweep"}; !slices.Equal(a, want) {
+ t.Fatalf("A: %v, want %v (log %v)", a, want, log)
+ }
+ if slices.Index(log, "A:enter") < slices.Index(log, "B:afterSweep") {
+ t.Fatalf("A entered before B's sweep: %v", log)
+ }
+ if _, ok := tenancyAt(hub, upHost); ok {
+ t.Fatalf("after A: %s is served again", upHost)
+ }
+ if got := s.recorded(); !slices.Equal(got, []string{fp}) {
+ t.Fatalf("Watch recorded %q, want %q", got, fp)
+ }
+ if _, _, err := hub.reserveUpgrade(context.Background(), upAdm, tc, 10); !errors.Is(err, errTenancyStale) {
+ t.Fatalf("a new reservation after A: %v, want errTenancyStale", err)
+ }
+ })
+}
+
+// TestFailedReloadSweepsNothing is Review Focus 5: a Reload that fails
+// after its registry reads applies nothing and sweeps nothing; the next
+// good Reload judges the reservation.
+func TestFailedReloadSweepsNothing(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ res := reserveHeld(t, hub, tc, upAdm)
+ errRead := errors.New("registry read failed (test)")
+
+ // The owner changes, so a good Reload now would sweep; this one fails.
+ setFleetOwner(t, hub, "home", fwdOther)
+ hub.hooks = &reloadHooks{afterRead: func(uint64) error { return errRead }}
+ if err := hub.Reload(); !errors.Is(err, errRead) {
+ t.Fatalf("Reload: %v, want the hook's read error", err)
+ }
+ hub.hooks = nil
+ res.open(t, hub, "after the failed Reload")
+ if ten, ok := tenancyAt(hub, upHost); !ok || ten != upTenancy {
+ t.Fatalf("after the failed Reload: %s tenancy %+v (served %v), want the old map's %+v", upHost, ten, ok, upTenancy)
+ }
+ if owners := hub.fleetAccounts.Load(); owners == nil || (*owners)["home"] != fwdOwner {
+ t.Fatalf("after the failed Reload the door's owners map changed: %v", owners)
+ }
+
+ // Control: the owner restored (read back), a good Reload judges the
+ // unchanged tenancy current and keeps the reservation.
+ setFleetOwner(t, hub, "home", fwdOwner)
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ res.open(t, hub, "after a good Reload with the tenancy unchanged")
+
+ // Positive control on the same fixture: a good Reload after the owner
+ // change sweeps it.
+ setFleetOwner(t, hub, "home", fwdOther)
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ res.swept(t, hub, "after a good Reload with the owner changed")
+}
+
+// TestSweepKeepsCurrentReservations is spec §8.2 case 16 at the registry
+// level: no false closes.
+func TestSweepKeepsCurrentReservations(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ res := reserveHeld(t, hub, tc, upAdm)
+ prev := ""
+ for i := range 20 {
+ // Another host comes, the previous one goes.
+ host := fmt.Sprintf("other-%d.example.com", i)
+ if err := hub.reg.Upsert(registry.Route{Host: host, Kind: "instance", Status: "ready",
+ Socket: "/run/carlos/other.sock", Account: fwdOwner, App: "other"}); err != nil {
+ t.Fatal(err)
+ }
+ if prev != "" {
+ if err := hub.reg.Delete(prev); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // box-1's token rotates (read back), the path SetDynamicAuth applies.
+ hash := sha256Hex(fmt.Sprintf("box-1-token-%d", i))
+ if err := hub.reg.SetFleetBoxToken("home", "box-1", hash); err != nil {
+ t.Fatal(err)
+ }
+ auth, err := hub.reg.FleetChannelAuth()
+ if err != nil || auth["home/box-1"] != hash {
+ t.Fatalf("read back: home/box-1 hash %q (%v), want the rotated one", auth["home/box-1"], err)
+ }
+ // The same forward row is re-minted unchanged.
+ if err := hub.reg.PutForward(forwardRow(upHost, "home", fwdOwner)); err != nil {
+ t.Fatal(err)
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ hub.tunnels.mu.Lock()
+ applied := hub.tunnels.dynamicAuth["home/box-1"]
+ hub.tunnels.mu.Unlock()
+ if applied != hash {
+ t.Fatalf("Reload %d: the hub's auth for home/box-1 was not rotated", i)
+ }
+ if _, ok := hub.lookupUpstreamPath(host, "/"); !ok {
+ t.Fatalf("Reload %d: %s is not served", i, host)
+ }
+ if prev != "" {
+ if _, ok := hub.lookupUpstreamPath(prev, "/"); ok {
+ t.Fatalf("Reload %d: %s is still served", i, prev)
+ }
+ }
+ res.open(t, hub, fmt.Sprintf("after Reload %d", i))
+ prev = host
+ }
+ // Positive control on the same fixture: an owner change is swept.
+ setFleetOwner(t, hub, "home", fwdOther)
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ res.swept(t, hub, "after the owner change")
+}
+
+// TestSweepClosesEachLostTenancy is spec §8.2 case 15 at the registry
+// level: each way a host stops being served for its tenancy closes its
+// reservation in the next Reload, and an unchanged row's stays.
+func TestSweepClosesEachLostTenancy(t *testing.T) {
+ const sock = "/run/carlos/src-home.sock"
+ rows := []registry.Route{
+ forwardRow("gone.example.com", "home", fwdOwner),
+ forwardRow("moved.example.com", "home", fwdOwner),
+ forwardRow("away.example.com", "away", fwdOwner),
+ forwardRow("keep.example.com", "home", fwdOwner),
+ {Host: "t.example.com", Kind: "instance", Status: "ready", Tunnel: "t1", Account: fwdOther, App: "blog"},
+ {Host: "src.example.com", Kind: "instance", Status: "ready", Socket: sock,
+ Region: registry.PlacementTarget("home"), Account: fwdOwner, App: "shop"},
+ {Host: "alias.example.com", Kind: "instance", Status: "ready", Socket: sock,
+ Region: registry.PlacementTarget("home"), Account: fwdOwner, App: "shop", Platform: true},
+ }
+ getRow := func(t *testing.T, e *Edge, host string) *registry.Route {
+ t.Helper()
+ rt, err := e.reg.Get(host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rt
+ }
+ for _, tc := range []struct {
+ name, host string
+ change func(t *testing.T, e *Edge)
+ }{
+ {"the row's fleet changed owner", "away.example.com", func(t *testing.T, e *Edge) {
+ setFleetOwner(t, e, "away", fwdOther)
+ }},
+ {"the row was deleted", "gone.example.com", func(t *testing.T, e *Edge) {
+ if ok, err := e.reg.DeleteForward("gone.example.com"); err != nil || !ok {
+ t.Fatalf("DeleteForward: %v, %v", ok, err)
+ }
+ if rt := getRow(t, e, "gone.example.com"); rt != nil {
+ t.Fatalf("read back: the row is still there: %+v", rt)
+ }
+ }},
+ {"the row was re-minted on fleet away", "moved.example.com", func(t *testing.T, e *Edge) {
+ if err := e.reg.PutForward(forwardRow("moved.example.com", "away", fwdOwner)); err != nil {
+ t.Fatal(err)
+ }
+ if rt := getRow(t, e, "moved.example.com"); rt == nil || rt.Region != registry.PlacementTarget("away") {
+ t.Fatalf("read back: %+v, want region %s", rt, registry.PlacementTarget("away"))
+ }
+ }},
+ {"the -tunnel row was re-pointed to t2", "t.example.com", func(t *testing.T, e *Edge) {
+ rt := getRow(t, e, "t.example.com")
+ rt.Tunnel = "t2"
+ if err := e.reg.Upsert(*rt); err != nil {
+ t.Fatal(err)
+ }
+ if rt := getRow(t, e, "t.example.com"); rt == nil || rt.Tunnel != "t2" {
+ t.Fatalf("read back: %+v, want tunnel t2", rt)
+ }
+ }},
+ {"the platform alias's source is refused", "alias.example.com", func(t *testing.T, e *Edge) {
+ rt := getRow(t, e, "src.example.com")
+ rt.Account = fwdOther // not the fleet's owner
+ if err := e.reg.Upsert(*rt); err != nil {
+ t.Fatal(err)
+ }
+ if rt := getRow(t, e, "src.example.com"); rt == nil || rt.Account != fwdOther {
+ t.Fatalf("read back: %+v, want account %s", rt, fwdOther)
+ }
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ _, hub, _ := forwardHubAndBox(t, rows, nil, namedHandler("box-1"))
+ ch := hub.tunnels.channel("home/box-1")
+ if ch == nil {
+ t.Fatal("home/box-1 has no channel connection")
+ }
+ admit := func(host string) upgradeAdmission {
+ ten, ok := tenancyAt(hub, host)
+ if !ok || ten.Arm == ArmNone {
+ t.Fatalf("%s: served %v with tenancy %+v, want a tunnel arm", host, ok, ten)
+ }
+ return upgradeAdmission{Host: host, Path: "/cable", Tenancy: ten}
+ }
+ target := reserveHeld(t, hub, ch, admit(tc.host))
+ control := reserveHeld(t, hub, ch, admit("keep.example.com"))
+ tc.change(t, hub)
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ target.swept(t, hub, "after the Reload")
+ control.open(t, hub, "the unchanged row, after the Reload")
+ })
+ }
+}
+
+// TestReservationRacesTheSwap is spec §8.2 case 17 at the registry level:
+// a reservation racing a revoking Reload is either refused at reservation
+// or swept, whichever side of the swap it falls.
+func TestReservationRacesTheSwap(t *testing.T) {
+ type result struct {
+ r *upgradeReservation
+ stream context.Context
+ err error
+ }
+ // pause makes the seam it is installed in block once, until resumed.
+ pause := func() (seam func(), paused <-chan struct{}, resume func()) {
+ p, r := make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ return func() {
+ once.Do(func() {
+ close(p)
+ <-r
+ })
+ }, p, func() { close(r) }
+ }
+ reserveAsync := func(e *Edge, tc *tunnelConn) <-chan result {
+ out := make(chan result, 1)
+ go func() {
+ r, sctx, err := e.reserveUpgrade(context.Background(), upAdm, tc, 10)
+ out <- result{r, sctx, err}
+ }()
+ return out
+ }
+ await := func(t *testing.T, ch <-chan struct{}, what string) {
+ t.Helper()
+ select {
+ case <-ch:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("%s did not happen within 5 s", what)
+ }
+ }
+ get := func(t *testing.T, ch <-chan result) result {
+ t.Helper()
+ select {
+ case r := <-ch:
+ return r
+ case <-time.After(5 * time.Second):
+ t.Fatal("reserveUpgrade did not return within 5 s")
+ }
+ return result{}
+ }
+
+ // Dispatched on the old map, paused before the lock; a revoking Reload
+ // runs to completion; the reservation is refused and holds nothing.
+ t.Run("refused at reservation", func(t *testing.T) {
+ for _, revoke := range []bool{false, true} {
+ hub, tc := upgradeScene(t)
+ seam, paused, resume := pause()
+ hub.open.beforeReserve = seam
+ out := reserveAsync(hub, tc)
+ await(t, paused, "the pause before the reservation")
+ if revoke {
+ setFleetOwner(t, hub, "home", fwdOther)
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ resume()
+ got := get(t, out)
+ if !revoke {
+ // Control: with nothing revoked, the same schedule admits.
+ if got.err != nil {
+ t.Fatalf("control: %v, want admitted", got.err)
+ }
+ got.r.release(relBody)
+ continue
+ }
+ if !errors.Is(got.err, errTenancyStale) {
+ t.Fatalf("after the revoking Reload: %v, want errTenancyStale", got.err)
+ }
+ if n, ok := openCount(hub, tc); ok || n != 0 || heldFor(hub, upHost) != 0 {
+ t.Fatalf("after the refusal: count %d (entry %v), held %d; want nothing", n, ok, heldFor(hub, upHost))
+ }
+ }
+ })
+
+ // Reserved on the old map, paused after the insert and before return;
+ // the revoking Reload's sweep releases it.
+ t.Run("swept after the insert", func(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ seam, paused, resume := pause()
+ hub.open.afterInsert = seam
+ out := reserveAsync(hub, tc)
+ await(t, paused, "the pause after the insert")
+ if heldFor(hub, upHost) != 1 {
+ t.Fatalf("held %d at the pause, want 1", heldFor(hub, upHost))
+ }
+ setFleetOwner(t, hub, "home", fwdOther)
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if heldFor(hub, upHost) != 0 {
+ t.Fatal("the revoking Reload's sweep left the reservation in the registry")
+ }
+ resume()
+ got := get(t, out)
+ if got.err != nil {
+ t.Fatalf("reserveUpgrade: %v, want the reservation it inserted", got.err)
+ }
+ // The sweep releases on its own goroutine; release cancels the
+ // stream's context first, then gives the slot back.
+ select {
+ case <-got.stream.Done():
+ case <-time.After(2 * time.Second):
+ t.Fatal("2 s after the sweep the stream's context has not ended")
+ }
+ if r := got.r.firstReleaser(); r != relSweep {
+ t.Fatalf("firstReleaser %v, want relSweep", r)
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ n, ok := openCount(hub, tc)
+ if !ok && n == 0 {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("2 s after the sweep: count %d (entry %v), want no entry", n, ok)
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ })
+}
+
+// blockingCloser's Close blocks until unblock is closed, like a stream
+// whose teardown waits on a stuck tunnel.
+type blockingCloser struct {
+ entered, unblock chan struct{}
+ once sync.Once
+}
+
+func (c *blockingCloser) Close() error {
+ c.once.Do(func() { close(c.entered) })
+ <-c.unblock
+ return nil
+}
+
+// TestSweepReleasesOffTheReload: the sweep closes streams outside every
+// lock and off the Reload (spec §4.6.1), so a teardown that blocks neither
+// holds up the Reload nor reloadMu, nor the registry's lock.
+func TestSweepReleasesOffTheReload(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ r, _, err := hub.reserveUpgrade(context.Background(), upAdm, tc, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stuck := &blockingCloser{entered: make(chan struct{}), unblock: make(chan struct{})}
+ defer close(stuck.unblock)
+ r.attach(nil, stuck)
+
+ setFleetOwner(t, hub, "home", fwdOther)
+ done := goReload(hub)
+ select {
+ case <-stuck.entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the sweep did not close the stream within 5 s")
+ }
+ // The close is blocked now; the Reload has returned regardless.
+ awaitReload(t, done, "with a stream close blocked")
+ if !hub.reloadMu.TryLock() {
+ t.Fatal("reloadMu is held while a swept stream's close is blocked")
+ }
+ hub.reloadMu.Unlock()
+ if !hub.open.mu.TryLock() {
+ t.Fatal("the registry's lock is held while a swept stream's close is blocked")
+ }
+ hub.open.mu.Unlock()
+ // Control: the next Reload is not held up either.
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if got := r.firstReleaser(); got != relSweep {
+ t.Fatalf("firstReleaser %v, want relSweep", got)
+ }
+}
diff --git a/internal/edge/upgrades.go b/internal/edge/upgrades.go
index 8e34f41b4..4e52f168d 100644
--- a/internal/edge/upgrades.go
+++ b/internal/edge/upgrades.go
@@ -83,6 +83,11 @@ type openUpgrades struct {
mu sync.Mutex
byHost map[string]map[*upgradeReservation]struct{}
perConn map[*tunnelConn]int
+
+ // beforeReserve and afterInsert are test seams in reserveUpgrade, nil
+ // in production: one runs before it takes mu, the other after it has
+ // inserted a reservation and dropped mu, before it returns.
+ beforeReserve, afterInsert func()
}
// releaser names who released a reservation first. Tests read it;
@@ -197,6 +202,9 @@ func (o *openUpgrades) remove(r *upgradeReservation) {
// whatever happened to the response.
func (e *Edge) reserveUpgrade(inbound context.Context, a upgradeAdmission, tc *tunnelConn, capN int) (*upgradeReservation, context.Context, error) {
o := &e.open
+ if o.beforeReserve != nil {
+ o.beforeReserve()
+ }
o.mu.Lock()
up, ok := e.lookupUpstreamPath(a.Host, a.Path)
if !ok || a.Tenancy.Arm == ArmNone || up.tenancy != a.Tenancy {
@@ -221,6 +229,9 @@ func (e *Edge) reserveUpgrade(inbound context.Context, a upgradeAdmission, tc *t
o.byHost[a.Host][r] = struct{}{}
o.perConn[tc]++
o.mu.Unlock()
+ if o.afterInsert != nil {
+ o.afterInsert()
+ }
stop := context.AfterFunc(inbound, func() { r.release(relBackstop) })
r.mu.Lock()
@@ -233,3 +244,36 @@ func (e *Edge) reserveUpgrade(inbound context.Context, a upgradeAdmission, tc *t
}
return r, ctx, nil
}
+
+// sweepUpgrades closes every open upgrade the current map no longer serves
+// for the tenancy it was admitted under (spec §4.6.1): its host and path no
+// longer resolve, or resolve to an upstream with another tenancy. Reload
+// calls it right after its swap, under reloadMu, so it judges against the
+// map that Reload published.
+//
+// Under the registry's lock it only looks up and deletes; each lost
+// reservation is then released on its own goroutine, after the lock is
+// dropped, because a release closes streams and a Reload must never wait
+// on the network. release's own remove tolerates the byHost entry being
+// gone and gives the channel's slot back once.
+func (e *Edge) sweepUpgrades() {
+ o := &e.open
+ var lost []*upgradeReservation
+ o.mu.Lock()
+ for host, set := range o.byHost {
+ for r := range set {
+ if up, ok := e.lookupUpstreamPath(r.host, r.path); ok && up.tenancy == r.ten {
+ continue
+ }
+ delete(set, r)
+ lost = append(lost, r)
+ }
+ if len(set) == 0 {
+ delete(o.byHost, host)
+ }
+ }
+ o.mu.Unlock()
+ for _, r := range lost {
+ go r.release(relSweep)
+ }
+}