| 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) |
| + } |
| +} |