host: link revocation without reloads; bind handler to its link
Astra's final review, Critical 1 and 2. The link loop now reads the registry on its own watch (2 s) while a tunnel runs, so a committed unpublish or unlink ends the open streams within the bound even while every edge reload fails. Reloads still kick a pass at once. The watch reads only home_link and home_link_apps. The link handler carries the link ID its connection was dialed for, and HomeLinkAppByName(linkID, name) joins home_link on that ID in the same read, so an old link's connection never resolves a replacement link's publications. HomeLinkConnGen had no production caller (the loop reads conn_gen from HomeLink) and is removed with its remote dispatch entry. Witnesses: TestLinkRevocationDoesNotWaitOnReload (reloads failing, stream ends within one watch), TestLinkHandlerBoundToItsLink. The home simulation leaves half its ticks unreloaded and checks each revoked stream's end against its revocation time.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+299
−107
internal/console/homelink_test.go+9 −8internal/host/link_client.go+44 −13internal/host/link_e2e_test.go+128 −4internal/host/link_handler.go+16 −10internal/host/link_sim_test.go+74 −32internal/registry/homelink.go+16 −27internal/registry/homelink_test.go+11 −8internal/registry/remote_dispatch.go+1 −5
diff --git a/internal/console/homelink_test.go b/internal/console/homelink_test.go| index 2b301c9a0..9254d0002 100644 |
| --- a/internal/console/homelink_test.go |
| +++ b/internal/console/homelink_test.go |
| @@ -414,7 +414,7 @@ func TestHomePublishRefusesGatedApp(t *testing.T) { |
| out["app"] != "demo" || out["url"] != "https://demo.bab.apps.example.com" || out["home_app"] != "shop" || out["home_account"] != home.sqid { |
| t.Fatalf("publish shop = %d %s", status, body) |
| } |
| - got, err := homeRegistry(t, home).HomeLinkAppByName("demo") |
| + got, err := homeRegistry(t, home).HomeLinkAppByName(homeTestLinkID, "demo") |
| want := registry.HomeLinkApp{Name: "demo", HomeAccount: home.sqid, HomeApp: "shop", HomeHost: "shop.home.example.com"} |
| if err != nil || got == nil || *got != want { |
| t.Fatalf("HomeLinkAppByName(demo) = %+v, %v; want %+v", got, err, want) |
| @@ -478,10 +478,11 @@ func TestHomeUnpublishDropsHomeSetFirst(t *testing.T) { |
| t.Fatalf("publish = %d %s", status, body) |
| } |
| reg := homeRegistry(t, home) |
| - gen, err := reg.HomeLinkConnGen() |
| - if err != nil { |
| - t.Fatal(err) |
| + held, err := reg.HomeLink() |
| + if err != nil || held == nil { |
| + t.Fatal(held, err) |
| } |
| + gen := held.ConnGen |
| var seenAtDelete []registry.HomeLinkApp |
| deletes := 0 |
| @@ -506,8 +507,8 @@ func TestHomeUnpublishDropsHomeSetFirst(t *testing.T) { |
| if len(seenAtDelete) != 0 { |
| t.Fatalf("the home set still held %v when the serving console was told", seenAtDelete) |
| } |
| - if g, _ := reg.HomeLinkConnGen(); g != gen+1 { |
| - t.Fatalf("conn_gen = %d; want %d", g, gen+1) |
| + if l, _ := reg.HomeLink(); l == nil || l.ConnGen != gen+1 { |
| + t.Fatalf("link after unpublish = %+v; want conn_gen %d", l, gen+1) |
| } |
| // Neither side holds it now. |
| if status, body := homeReq(t, home, http.MethodDelete, "/api/cli/link/publications/shop", op, ""); status != http.StatusNotFound || linkJSONErr(body) != linkCopy(copyLD48, "app", "shop") { |
| @@ -739,7 +740,7 @@ var claimHomeLinkNonAppProbes = map[string]claimProbe{ |
| status: http.StatusCreated, |
| body: []string{`"app":"kass"`}, |
| effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| - a, err := homeRegistry(t, cx.consoleFixture).HomeLinkAppByName("kass") |
| + a, err := homeRegistry(t, cx.consoleFixture).HomeLinkAppByName(homeTestLinkID, "kass") |
| if err != nil || a == nil || a.HomeHost != "kass.carlosapp.dev" { |
| return fmt.Sprintf("the published set holds %+v (%v)", a, err) |
| } |
| @@ -754,7 +755,7 @@ var claimHomeLinkNonAppProbes = map[string]claimProbe{ |
| do: claimAPIReply(http.MethodDelete, "/api/cli/link/publications/kass", ""), |
| body: []string{`"app":"kass"`}, |
| effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| - if a, err := homeRegistry(t, cx.consoleFixture).HomeLinkAppByName("kass"); err != nil || a != nil { |
| + if a, err := homeRegistry(t, cx.consoleFixture).HomeLinkAppByName(homeTestLinkID, "kass"); err != nil || a != nil { |
| return fmt.Sprintf("the published set still holds %+v (%v)", a, err) |
| } |
| return "" |
diff --git a/internal/host/link_client.go b/internal/host/link_client.go| index e6b96cd6d..1d2f70b8a 100644 |
| --- a/internal/host/link_client.go |
| +++ b/internal/host/link_client.go |
| @@ -11,12 +11,22 @@ package host |
| // (tunnelEnvComplete) never claims and never dials. |
| // |
| // The loop follows the registry. It reads the link and the published set |
| -// when it starts and after every edge reload (Edge.OnReload; the edge |
| -// reloads when the registry's fingerprint moves, which covers the link's |
| -// token, claim and conn_gen and the published set). It runs one |
| -// tunnelclient.Loop with the link's channel name, token and tunnel URL, |
| -// serving linkHandler, and cancels it on unlink, on rotation (a new token), |
| -// on a new tunnel URL or link, and on loss of the claim. |
| +// when it starts, after every edge reload (Edge.OnReload; the edge reloads |
| +// when the registry's fingerprint moves, which covers the link's token, |
| +// claim and conn_gen and the published set), and, while a tunnel runs, on |
| +// its own watch every linkWatchInterval (2 s, the registry watch's poll), |
| +// whatever the reloads do. It runs one tunnelclient.Loop with the link's |
| +// channel name, token and tunnel URL, serving linkHandler, and cancels it |
| +// on unlink, on rotation (a new token), on a new tunnel URL or link, and |
| +// on loss of the claim. |
| +// |
| +// Why its own watch. A reload is the edge's whole route-map publication, |
| +// and it can keep failing for reasons that have nothing to do with the |
| +// link (another table unreadable, a refused row). Revocation must not wait |
| +// on it: an unpublish or an unlink the console committed ends the open |
| +// streams within the watch bound even while every reload fails. The watch |
| +// reads only the home registry (HomeLink, which carries conn_gen, and the |
| +// published set), never the object store. |
| // |
| // Connection replacement. Nothing tracks the streams of each published app. |
| // Every unpublish and every retarget bumps the link's conn_gen in the same |
| @@ -26,8 +36,9 @@ package host |
| // with it every in-flight request and stream (WebSockets, event streams, |
| // long downloads), and starts a new one. Other published apps are back |
| // within about a second. An unpublished app's open streams therefore end |
| -// within one registry watch (2 s) plus the cancel; its new requests are |
| -// refused from the next one, by linkHandler's per-request read. |
| +// within one watch interval (2 s) plus the cancel, reloads or not; its new |
| +// requests are refused from the next one, by linkHandler's per-request |
| +// read. |
| import ( |
| "context" |
| @@ -44,9 +55,14 @@ import ( |
| ) |
| // linkRetry is how soon a pass that could not read or claim the link runs |
| -// again without waiting for a reload. |
| +// again without waiting for a reload, when no tunnel runs. |
| const linkRetry = 5 * time.Second |
| +// linkWatchInterval is the loop's own registry watch while a tunnel runs: |
| +// the bound within which a committed revocation ends the open streams, |
| +// independent of the edge's reloads. |
| +const linkWatchInterval = 2 * time.Second |
| + |
| // linkEdge is what the loop needs of the edge: reload notices and the |
| // pinned pipeline. |
| type linkEdge interface { |
| @@ -55,7 +71,8 @@ type linkEdge interface { |
| } |
| // linkLoopDeps is runLinkLoop's wiring. getenv decides whether this is a |
| -// fleet box; onPass, when set, runs after every pass (tests). |
| +// fleet box; onPass, when set, runs after every pass (tests); watch, when |
| +// non-zero, replaces linkWatchInterval (tests). |
| type linkLoopDeps struct { |
| edge linkEdge |
| reg linkRegistry |
| @@ -63,6 +80,7 @@ type linkLoopDeps struct { |
| getenv func(string) string |
| onPass func() |
| logf func(format string, args ...any) |
| + watch time.Duration |
| } |
| // linkLoop runs the link loop for the life of the agent. label is the box |
| @@ -86,6 +104,9 @@ func runLinkLoop(ctx context.Context, d linkLoopDeps) { |
| if d.logf == nil { |
| d.logf = log.Printf |
| } |
| + if d.watch <= 0 { |
| + d.watch = linkWatchInterval |
| + } |
| kick := make(chan struct{}, 1) |
| d.edge.OnReload(func() { |
| select { |
| @@ -107,10 +128,19 @@ func runLinkLoop(ctx context.Context, d linkLoopDeps) { |
| if d.onPass != nil { |
| d.onPass() |
| } |
| + // The next pass comes with the next reload, or sooner: on the |
| + // watch while a tunnel runs (a revocation must not wait on a |
| + // reload that may keep failing), after linkRetry when a read or a |
| + // claim failed. cur is written only on this goroutine. |
| var again <-chan time.Time |
| var timer *time.Timer |
| - if retry { |
| + switch { |
| + case l.cur != nil: |
| + timer = time.NewTimer(d.watch) |
| + case retry: |
| timer = time.NewTimer(linkRetry) |
| + } |
| + if timer != nil { |
| again = timer.C |
| } |
| select { |
| @@ -152,7 +182,8 @@ const ( |
| ) |
| // pass brings the running tunnel in line with the registry. It reports |
| -// whether to run again soon without a reload (a read or claim failed). |
| +// whether to run again soon without a reload (a read or claim failed); a |
| +// running tunnel is checked again on the watch in any case. |
| func (l *linkLoopState) pass() (retry bool) { |
| d := l.d |
| if tunnelEnvComplete(d.getenv) { |
| @@ -272,7 +303,7 @@ func (l *linkLoopState) start(link *registry.HomeLink, set map[string]registry.H |
| URL: link.TunnelURL, |
| Name: name, |
| Token: link.Token, |
| - Handler: linkHandler{reg: d.reg, serve: d.edge.ServeLinked}, |
| + Handler: linkHandler{reg: d.reg, linkID: link.ID, serve: d.edge.ServeLinked}, |
| // Only the run the loop holds reports (reportState): a replaced |
| // or stopped one must not write over its successor's state, or |
| // another box's. |
diff --git a/internal/host/link_e2e_test.go b/internal/host/link_e2e_test.go| index 790cb15d1..292bbda10 100644 |
| --- a/internal/host/link_e2e_test.go |
| +++ b/internal/host/link_e2e_test.go |
| @@ -53,9 +53,10 @@ const ( |
| linkServingAcct = "bah" // the Carloku account that owns the link |
| linkHomeAcct = "bab" // the home account the apps live in |
| linkE2ELabel = "home-box" |
| - // linkWatch is the registry watch's interval (edge.Watch's 2 s poll): |
| - // the bound within which an unpublished app's open streams must end |
| - // once reloads resume. |
| + // linkWatch is the registry watch's interval (edge.Watch's 2 s poll, |
| + // and the link loop's own watch, linkWatchInterval): the bound within |
| + // which an unpublished app's open streams must end once reloads |
| + // resume. |
| linkWatch = 2 * time.Second |
| // The approved deck's words for the two home refusals, verbatim. |
| deckLD50 = "This app is not published from here." |
| @@ -211,6 +212,9 @@ type linkWorld struct { |
| loopReg linkRegistry |
| getenv func(string) string |
| stopLoop func() |
| + // watch, when non-zero, is the loop's own registry watch |
| + // (linkLoopDeps.watch); else linkWatchInterval. |
| + watch time.Duration |
| } |
| // newLinkWorld builds the hub and the home. Home apps shop, admin and blog |
| @@ -334,7 +338,7 @@ func (w *linkWorld) startLoop(t *testing.T) { |
| go func() { |
| defer close(done) |
| runLinkLoop(ctx, linkLoopDeps{edge: w.home, reg: w.loopReg, label: linkE2ELabel, getenv: w.getenv, |
| - onPass: func() { w.passes.Add(1) }, logf: t.Logf}) |
| + onPass: func() { w.passes.Add(1) }, logf: t.Logf, watch: w.watch}) |
| }() |
| var once sync.Once |
| w.stopLoop = func() { |
| @@ -1225,3 +1229,123 @@ func TestLinkReplacedDoesNotWaitOnClaim(t *testing.T) { |
| t.Fatalf("HomeLink = %+v, %v; want the new link, unclaimed", l, err) |
| } |
| } |
| + |
| +// linkBreakHomeReloads makes every later Reload of the home edge fail, as an |
| +// unrelated registry read failing would (its alias table is renamed away), |
| +// and checks that it does. The link loop reads none of that table. |
| +func (w *linkWorld) linkBreakHomeReloads(t *testing.T) { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", w.homePath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + if _, err := db.Exec(`ALTER TABLE route_aliases RENAME TO route_aliases_away`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := w.home.Reload(); err == nil { |
| + t.Fatal("the home edge still reloads: the test would prove nothing") |
| + } |
| +} |
| + |
| +// A committed revocation ends the open streams within the loop's own watch |
| +// while every home edge reload keeps failing (Astra final review, Critical |
| +// 1): the loop's pass must not wait on a successful reload. |
| +func TestLinkRevocationDoesNotWaitOnReload(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + revoke func(t *testing.T, w *linkWorld) |
| + }{ |
| + {"unpublish", func(t *testing.T, w *linkWorld) { |
| + if ok, err := w.homeReg.DeleteHomeLinkApp("shop"); err != nil || !ok { |
| + t.Fatalf("DeleteHomeLinkApp = %v, %v", ok, err) |
| + } |
| + }}, |
| + {"unlink", func(t *testing.T, w *linkWorld) { |
| + if err := w.homeReg.DeleteHomeLink(); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + w := newLinkedWorld(t, map[string]string{"shop": "shop", "blog": "blog"}) |
| + sse := w.openSSE(t, "shop") |
| + ws := w.openWS(t, "shop") |
| + w.linkBreakHomeReloads(t) |
| + // Whenever the loop's watch timer started, it fires within one |
| + // interval of the revocation. |
| + tc.revoke(t, w) |
| + revoked := time.Now() |
| + // Reloads keep being tried, and keep failing. |
| + stop := make(chan struct{}) |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + for { |
| + select { |
| + case <-stop: |
| + return |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + if err := w.home.Reload(); err == nil { |
| + t.Error("a home reload succeeded") |
| + } |
| + } |
| + }() |
| + defer func() { close(stop); <-done }() |
| + bound := linkWatch + time.Second // one watch, plus the cancel |
| + linkEndsWithin(t, "shop's SSE response with reloads failing", sse, revoked, bound) |
| + linkEndsWithin(t, "shop's WebSocket with reloads failing", ws, revoked, bound) |
| + if resp, body := w.via(t, "GET", "shop", "/after", nil, ""); resp.StatusCode == http.StatusOK { |
| + t.Fatalf("shop answered after the revocation: %d %q", resp.StatusCode, body) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A link's connection reaches only its own link's publications (Astra final |
| +// review, Critical 2): the handler built for link A, still serving after the |
| +// home replaced A with link B, finds none of B's published names, whatever |
| +// they are called, while B's own handler does. |
| +func TestLinkHandlerBoundToItsLink(t *testing.T) { |
| + w := newLinkWorld(t, true, map[string]string{"shop": "shop"}) |
| + var served []edge.LinkedTarget |
| + serve := func(rw http.ResponseWriter, r *http.Request, want edge.LinkedTarget) { |
| + served = append(served, want) |
| + rw.WriteHeader(http.StatusOK) |
| + } |
| + ask := func(h linkHandler, name string) (int, string) { |
| + req := httptest.NewRequest("GET", "/", nil) |
| + req.Header.Set(tunnelclient.LinkAppHeader, name) |
| + req.Header.Set("X-Forwarded-Host", linkPublicHost(name)) |
| + rec := httptest.NewRecorder() |
| + h.ServeHTTP(rec, req) |
| + return rec.Code, rec.Body.String() |
| + } |
| + const linkB = "ba9876543210" |
| + a := linkHandler{reg: w.homeReg, linkID: linkE2EID, serve: serve} |
| + b := linkHandler{reg: w.homeReg, linkID: linkB, serve: serve} |
| + if code, body := ask(a, "shop"); code != http.StatusOK || len(served) != 1 { |
| + t.Fatalf("link A's own publication: %d %q", code, body) |
| + } |
| + |
| + // The home replaces A with B, which publishes shop again (another app) |
| + // and admin: A's connection has not been closed yet. |
| + if err := w.homeReg.PutHomeLink(registry.HomeLink{ID: linkB, ServingURL: "https://console.example.com", |
| + TunnelURL: w.hubURL, Token: "other-token", Account: linkServingAcct, AppsDomain: "apps.example.com"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.publish(t, "shop", "blog") |
| + w.publish(t, "admin", "admin") |
| + for _, name := range []string{"shop", "admin"} { |
| + if code, body := ask(a, name); code != http.StatusNotFound || !strings.Contains(body, deckLD50) { |
| + t.Fatalf("link A's connection asking for B's %s: %d %q, want 404 %q", name, code, body, deckLD50) |
| + } |
| + } |
| + if len(served) != 1 { |
| + t.Fatalf("link A's connection reached link B's publications: %+v", served[1:]) |
| + } |
| + if code, _ := ask(b, "admin"); code != http.StatusOK || len(served) != 2 || served[1].App != "admin" { |
| + t.Fatalf("link B's own publication: %d, served %+v", code, served) |
| + } |
| +} |
diff --git a/internal/host/link_handler.go b/internal/host/link_handler.go| index 30e957dfe..b8541f76f 100644 |
| --- a/internal/host/link_handler.go |
| +++ b/internal/host/link_handler.go |
| @@ -9,8 +9,9 @@ package host |
| // publication in tunnelclient.LinkAppHeader, which it sets on every request |
| // down a link channel and strips from every client's. This handler looks |
| // that name up in the home's own published set, in the registry, on every |
| -// request, so an unpublish is refused from the very next request without |
| -// waiting for a reload. A name that is missing, repeated or not published is |
| +// request and under the link its connection was dialed for, so an |
| +// unpublish (or the link's replacement) is refused from the very next |
| +// request without waiting for a reload. A name that is missing, repeated or not published is |
| // refused here, before the edge sees the request. A published one is handed |
| // to the edge's pinned pipeline (edge.ServeLinked) with the home account, |
| // app and host from the registry row: the request's own Host is never used |
| @@ -43,22 +44,27 @@ const ( |
| // linkRegistry is what the link loop and its handler read and write in the |
| // home registry (registry.Registry's home link methods, Task 7). The loop |
| -// reads conn_gen from the HomeLink row itself (HomeLink.ConnGen, the value |
| -// HomeLinkConnGen returns), so the token, the claim and conn_gen it acts on |
| -// come from one read. |
| +// reads conn_gen from the HomeLink row itself (HomeLink.ConnGen), so the |
| +// token, the claim and conn_gen it acts on come from one read. |
| type linkRegistry interface { |
| HomeLink() (*registry.HomeLink, error) |
| HomeLinkApps() ([]registry.HomeLinkApp, error) |
| - HomeLinkAppByName(name string) (*registry.HomeLinkApp, error) |
| + HomeLinkAppByName(linkID, name string) (*registry.HomeLinkApp, error) |
| ClaimHomeLink(label string) (bool, error) |
| SetHomeLinkState(state string) error |
| } |
| -// linkHandler serves one link channel. serve is the edge's pinned pipeline |
| +// linkHandler serves one link channel: the connection the loop dialed for |
| +// link linkID. Every request is looked up under that link ID as well as its |
| +// name (HomeLinkAppByName), in one read, so a connection the loop has not |
| +// closed yet after the link was replaced can never reach the replacement's |
| +// publications: publication authority belongs to a link, not to whatever |
| +// link the registry holds now. serve is the edge's pinned pipeline |
| // (edge.ServeLinked) in production. |
| type linkHandler struct { |
| - reg linkRegistry |
| - serve func(w http.ResponseWriter, r *http.Request, want edge.LinkedTarget) |
| + reg linkRegistry |
| + linkID string |
| + serve func(w http.ResponseWriter, r *http.Request, want edge.LinkedTarget) |
| } |
| // linkPublicHostRE is the shape a public host may take: a lowercase |
| @@ -74,7 +80,7 @@ func (h linkHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| linkNotPublished(w) |
| return |
| } |
| - app, err := h.reg.HomeLinkAppByName(names[0]) |
| + app, err := h.reg.HomeLinkAppByName(h.linkID, names[0]) |
| if err != nil { |
| log.Printf("agent: link: reading the published set: %v", err) |
| w.Header().Set("Cache-Control", "no-store") |
diff --git a/internal/host/link_sim_test.go b/internal/host/link_sim_test.go| index e44fa99db..0448594ed 100644 |
| --- a/internal/host/link_sim_test.go |
| +++ b/internal/host/link_sim_test.go |
| @@ -4,8 +4,7 @@ package host |
| // side, checked by seeded random sequences. |
| // |
| // Each sequence publishes, unpublishes, retargets and reuses public names |
| -// in the home registry between watch ticks (a tick is the home edge's |
| -// reload, which the link loop follows), with event streams (SSE) and |
| +// in the home registry between ticks, with event streams (SSE) and |
| // WebSockets held open through the hub and plain visitor requests in |
| // between. A name may be retargeted to another app, or to an app of the |
| // same name in another home account, so the published target is the whole |
| @@ -17,15 +16,19 @@ package host |
| // moment it is sent, or by no app: a request sent after an unpublish of |
| // its name, or after a retarget away from an app, never reaches that |
| // app (linkHandler's per-request read; no tick needed); |
| -// - after a tick, every stream opened for a (name, account, app) that is |
| -// no longer published ends within one watch interval (the link loop |
| -// replaces the connection on conn_gen; Paul's choice 3). |
| +// - every stream opened for a (name, account, app) that is no longer |
| +// published ends within homeSimBound of the change that took it away |
| +// (the link loop replaces the connection on conn_gen; Paul's choice 3), |
| +// whether or not the home edge reloads in between: half the ticks |
| +// reload it, the other half leave it unreloaded, as a reload that keeps |
| +// failing would (Astra final review, Critical 1), and the loop's own |
| +// registry watch must end the streams. |
| // |
| // The whole home is real: the home registry (0640), the home Edge and its |
| // pinned pipeline (ServeLinked), runLinkLoop with the real tunnelclient.Loop, |
| -// the hub Edge and TunnelHub, and Unix-socket apps (newLinkWorld). The only |
| -// stand-in is the watch: the test reloads the home edge itself, so "between |
| -// watch ticks" is exact. |
| +// the hub Edge and TunnelHub, and Unix-socket apps (newLinkWorld). The |
| +// test drives the home edge's reloads itself, and runs the loop's own |
| +// watch at homeSimWatch rather than 2 s, so a run stays short. |
| // |
| // Seeds: LINKSIM_SEEDS=n runs n seeds (default linkSimDefaultSeeds), |
| // LINKSIM_SEED=s runs seed s alone in a fresh world (the reproduction of a |
| @@ -95,6 +98,14 @@ func linkSimSteps(t *testing.T, def int) int { |
| // and the first event or echo. |
| const homeSimOpenBound = 5 * time.Second |
| +// homeSimWatch is the link loop's own registry watch in the simulation, |
| +// and homeSimBound the time a revoked stream has to end after the change |
| +// that revoked it: one watch, plus the cancel (the e2e tests' linkWatch). |
| +const ( |
| + homeSimWatch = 25 * time.Millisecond |
| + homeSimBound = homeSimWatch + linkWatch |
| +) |
| + |
| // homeSimTarget is one home app a name can be published to. |
| type homeSimTarget struct { |
| key string // the app's linkTestApp name |
| @@ -110,12 +121,17 @@ type homeSimStream struct { |
| name string |
| target string // the target key that served it |
| ended chan struct{} |
| - close func() |
| + // endedAt is when the stream was seen to end, written before ended |
| + // is closed. |
| + endedAt time.Time |
| + close func() |
| // revoked is the mutation that unpublished or retargeted the |
| - // (name, account, app) this stream serves, "" while none has. Set |
| - // when the mutation happens, and kept even if the same target is |
| - // published under the name again before the tick. |
| - revoked string |
| + // (name, account, app) this stream serves, "" while none has, and |
| + // revokedAt when (just before it was committed). Set when the |
| + // mutation happens, and kept even if the same target is published |
| + // under the name again before the tick. |
| + revoked string |
| + revokedAt time.Time |
| } |
| func (st *homeSimStream) isEnded() bool { |
| @@ -130,6 +146,9 @@ func (st *homeSimStream) isEnded() bool { |
| // homeSimStats counts what a run exercised, so a pass is not vacuous. |
| type homeSimStats struct { |
| served, refused, refusedPublished, streams, revokedEnded, ticks, retargets int |
| + // unreloaded: ticks that left the home edge unreloaded; revokedUnreloaded: |
| + // revoked streams those ticks checked. |
| + unreloaded, revokedUnreloaded int |
| // transient: revoked streams whose (name, account, app) was published |
| // again by the tick that had to end them. |
| transient int |
| @@ -220,7 +239,7 @@ func (s *homeSim) admitted(name, reached, what string, status int) { |
| func (s *homeSim) revoke(name, why string) { |
| for _, st := range s.streams { |
| if st.name == name && st.revoked == "" && !st.isEnded() { |
| - st.revoked = why |
| + st.revoked, st.revokedAt = why, time.Now() |
| } |
| } |
| } |
| @@ -319,6 +338,7 @@ func (s *homeSim) openSSE(name string) { |
| st := &homeSimStream{n: len(s.streams), kind: "sse", name: name, target: got, ended: make(chan struct{}), close: func() { cancel(); resp.Body.Close() }} |
| go func() { |
| io.Copy(io.Discard, br) |
| + st.endedAt = time.Now() |
| close(st.ended) |
| }() |
| s.streams = append(s.streams, st) |
| @@ -367,6 +387,7 @@ func (s *homeSim) openWS(name string) { |
| st := &homeSimStream{n: len(s.streams), kind: "ws", name: name, target: got, ended: make(chan struct{}), close: func() { conn.Close() }} |
| go func() { |
| io.Copy(io.Discard, br) |
| + st.endedAt = time.Now() |
| close(st.ended) |
| }() |
| s.streams = append(s.streams, st) |
| @@ -375,14 +396,19 @@ func (s *homeSim) openWS(name string) { |
| s.admitted(name, got, "a WebSocket open", http.StatusSwitchingProtocols) |
| } |
| -// tick is one watch tick: the home edge reloads and the link loop follows. |
| -// Then every open stream whose (name, account, app) is no longer published |
| -// must end within one watch interval. |
| -func (s *homeSim) tick() { |
| +// tick checks the revocation bound. With reload, the home edge reloads |
| +// first (and must succeed); without, it is left unreloaded, as a reload |
| +// that keeps failing would leave it, and only the link loop's own watch |
| +// can act. Either way every open stream whose (name, account, app) is no |
| +// longer published must end within homeSimBound of the change that took |
| +// it away. |
| +func (s *homeSim) tick(reload bool) { |
| passes := s.w.passes.Load() |
| at := time.Now() |
| - if err := s.w.home.Reload(); err != nil { |
| - s.t.Fatal(err) |
| + if reload { |
| + if err := s.w.home.Reload(); err != nil { |
| + s.t.Fatal(err) |
| + } |
| } |
| // Revoked: every stream whose target an unpublish or retarget since it |
| // opened took away, even if the same target is back under the name |
| @@ -395,11 +421,20 @@ func (s *homeSim) tick() { |
| } |
| } |
| for _, st := range revoked { |
| + from := st.revokedAt |
| + if from.IsZero() { |
| + from = at |
| + } |
| + deadline := from.Add(homeSimBound) |
| select { |
| case <-st.ended: |
| - case <-time.After(time.Until(at.Add(linkWatch))): |
| - s.failf("stream %d (%s %s served by %s, revoked: %q) still open %s after the tick; %s is now published to %q", |
| - st.n, st.kind, st.name, st.target, st.revoked, linkWatch, st.name, s.pub[st.name]) |
| + if st.endedAt.After(deadline) { |
| + s.failf("stream %d (%s %s served by %s, revoked: %q) ended %s after its revocation, past %s (reload %v)", |
| + st.n, st.kind, st.name, st.target, st.revoked, st.endedAt.Sub(from).Round(time.Millisecond), homeSimBound, reload) |
| + } |
| + case <-time.After(time.Until(deadline)): |
| + s.failf("stream %d (%s %s served by %s, revoked: %q) still open %s after its revocation (reload %v); %s is now published to %q", |
| + st.n, st.kind, st.name, st.target, st.revoked, homeSimBound, reload, st.name, s.pub[st.name]) |
| } |
| } |
| for _, st := range revoked { |
| @@ -410,16 +445,20 @@ func (s *homeSim) tick() { |
| took := time.Since(at) |
| s.stats.ticks++ |
| s.stats.revokedEnded += len(revoked) |
| + if !reload { |
| + s.stats.unreloaded++ |
| + s.stats.revokedUnreloaded += len(revoked) |
| + } |
| s.settled(passes) |
| - s.logf("tick: %d revoked stream(s) ended within %s", len(revoked), took.Round(time.Millisecond)) |
| + s.logf("tick (reload %v): %d revoked stream(s) ended within %s", reload, len(revoked), took.Round(time.Millisecond)) |
| } |
| -// settled waits for the link loop's pass after a reload (one more than |
| -// passes) and then for its run to report connected: the connection is |
| +// settled waits for the link loop's next pass (one more than passes: the |
| +// reload's, or the watch's) and then for its run to report connected: the connection is |
| // replaced on every unpublish and retarget, and the next opens should go |
| // down the new one rather than be refused by the old one's teardown. |
| func (s *homeSim) settled(passes int64) { |
| - linkWait(s.t, "the link loop's pass after the reload", func() bool { return s.w.passes.Load() > passes }) |
| + linkWait(s.t, "the link loop's next pass (a reload's or its own watch's)", func() bool { return s.w.passes.Load() > passes }) |
| linkWait(s.t, "the link connected after the reload", func() bool { |
| l, err := s.w.homeReg.HomeLink() |
| return err == nil && l != nil && l.State == registry.HomeLinkConnected && s.w.tunnels.State(linkE2EChannel) == "connected" |
| @@ -452,7 +491,7 @@ func (s *homeSim) step(rng *rand.Rand) { |
| case r < 86: |
| s.request(name) |
| default: |
| - s.tick() |
| + s.tick(rng.Intn(2) == 0) |
| } |
| } |
| @@ -493,6 +532,7 @@ func newHomeSimWorld(t *testing.T) (*linkWorld, []homeSimTarget) { |
| pub[name] = "shop" |
| } |
| w := newLinkWorld(t, true, pub) |
| + w.watch = homeSimWatch |
| other := startLinkApp(t, "shopbac") |
| if err := w.homeReg.Upsert(registry.Route{Host: other.host, Slug: "shop", Kind: "instance", Socket: other.sock, Status: "ready", |
| App: "shop", Account: "bac", Channel: "production"}); err != nil { |
| @@ -553,7 +593,7 @@ func TestLinkSimHomeSide(t *testing.T) { |
| s.step(rng) |
| } |
| if len(s.fails) == 0 { |
| - s.tick() |
| + s.tick(rng.Intn(2) == 0) |
| } |
| if len(s.fails) != 0 { |
| failed++ |
| @@ -566,13 +606,15 @@ func TestLinkSimHomeSide(t *testing.T) { |
| } |
| s.cleanup() |
| } |
| - t.Logf("%d seeds, up to %d steps each, in %s: %d requests and opens served, %d refused (%d of them published), %d streams opened, %d revoked streams ended at %d ticks (%d transient), %d retargets", |
| + t.Logf("%d seeds, up to %d steps each, in %s: %d requests and opens served, %d refused (%d of them published), %d streams opened, %d revoked streams ended at %d ticks (%d transient; %d at %d ticks with no reload), %d retargets", |
| len(seeds), maxSteps, time.Since(start).Round(time.Millisecond), |
| - stats.served, stats.refused, stats.refusedPublished, stats.streams, stats.revokedEnded, stats.ticks, stats.transient, stats.retargets) |
| + stats.served, stats.refused, stats.refusedPublished, stats.streams, stats.revokedEnded, stats.ticks, stats.transient, |
| + stats.revokedUnreloaded, stats.unreloaded, stats.retargets) |
| if !one && len(seeds) >= linkSimDefaultSeeds { |
| // A full run that reached none of these proves nothing. |
| for what, n := range map[string]int{"served": stats.served, "refused": stats.refused, "streams opened": stats.streams, |
| - "revoked streams ended": stats.revokedEnded, "transient revocations": stats.transient, "retargets": stats.retargets} { |
| + "revoked streams ended": stats.revokedEnded, "transient revocations": stats.transient, "retargets": stats.retargets, |
| + "revoked streams ended with no reload": stats.revokedUnreloaded} { |
| if n == 0 { |
| t.Errorf("coverage: %d seeds had no %s", len(seeds), what) |
| } |
diff --git a/internal/registry/homelink.go b/internal/registry/homelink.go| index 90a8577ac..3c79b3b66 100644 |
| --- a/internal/registry/homelink.go |
| +++ b/internal/registry/homelink.go |
| @@ -293,26 +293,6 @@ func (r *Registry) SetHomeLinkUnlinkPending(id string, pending bool) error { |
| return err |
| } |
| -// HomeLinkConnGen returns the link's conn_gen, 0 when there is no link. |
| -// Fresh connection. |
| -func (r *Registry) HomeLinkConnGen() (uint64, error) { |
| - if r.remote != nil { |
| - out, err := r.remote.call(nil, remoteRequest{Method: "HomeLinkConnGen"}, nil) |
| - return uint64(out.Number64), err |
| - } |
| - db, err := r.freshFleetsConn() |
| - if err != nil { |
| - return 0, err |
| - } |
| - defer db.Close() |
| - var gen int64 |
| - err = db.QueryRow(`SELECT conn_gen FROM home_link ORDER BY id LIMIT 1`).Scan(&gen) |
| - if errors.Is(err, sql.ErrNoRows) { |
| - return 0, nil |
| - } |
| - return uint64(gen), err |
| -} |
| - |
| // HomeLinkApps returns the published set, ordered by name. Fresh |
| // connection. |
| func (r *Registry) HomeLinkApps() ([]HomeLinkApp, error) { |
| @@ -341,22 +321,31 @@ func (r *Registry) HomeLinkApps() ([]HomeLinkApp, error) { |
| return out, rows.Err() |
| } |
| -// HomeLinkAppByName returns the published app called name, or nil when no |
| -// app is published under it. The home agent's link handler calls it on |
| -// every request, so it reads over a fresh connection: an unpublish the |
| -// console committed is seen by the next request, never a stale snapshot. |
| -func (r *Registry) HomeLinkAppByName(name string) (*HomeLinkApp, error) { |
| +// HomeLinkAppByName returns the app published under name through link |
| +// linkID, or nil when no app is published under it or this deployment no |
| +// longer holds linkID. The home agent's link handler calls it on every |
| +// request with the link ID its connection was dialed for, so a connection |
| +// of a link that has been replaced (PutHomeLink of another ID, which clears |
| +// the published set in the same transaction) never resolves the |
| +// replacement's publications: the name and the link are read in one query. |
| +// It reads over a fresh connection: an unpublish the console committed is |
| +// seen by the next request, never a stale snapshot. |
| +func (r *Registry) HomeLinkAppByName(linkID, name string) (*HomeLinkApp, error) { |
| if r.remote != nil { |
| - out, err := r.remote.call(nil, remoteRequest{Method: "HomeLinkAppByName", Name: name}, nil) |
| + out, err := r.remote.call(nil, remoteRequest{Method: "HomeLinkAppByName", LinkID: linkID, Name: name}, nil) |
| return out.HomeLinkApp, err |
| } |
| + if !ValidLinkID(linkID) { |
| + return nil, nil |
| + } |
| db, err := r.freshFleetsConn() |
| if err != nil { |
| return nil, err |
| } |
| defer db.Close() |
| var a HomeLinkApp |
| - err = db.QueryRow(`SELECT name, home_account, home_app, home_host FROM home_link_apps WHERE name = ?`, name). |
| + err = db.QueryRow(`SELECT a.name, a.home_account, a.home_app, a.home_host FROM home_link_apps a |
| +JOIN home_link l ON l.id = ? WHERE a.name = ?`, linkID, name). |
| Scan(&a.Name, &a.HomeAccount, &a.HomeApp, &a.HomeHost) |
| if errors.Is(err, sql.ErrNoRows) { |
| return nil, nil |
diff --git a/internal/registry/homelink_test.go b/internal/registry/homelink_test.go| index ba59c33ce..911c82105 100644 |
| --- a/internal/registry/homelink_test.go |
| +++ b/internal/registry/homelink_test.go |
| @@ -48,11 +48,14 @@ func mustPutHomeLink(t *testing.T, reg *Registry, l HomeLink) { |
| func connGen(t *testing.T, reg *Registry) uint64 { |
| t.Helper() |
| - g, err := reg.HomeLinkConnGen() |
| + l, err := reg.HomeLink() |
| if err != nil { |
| t.Fatal(err) |
| } |
| - return g |
| + if l == nil { |
| + return 0 |
| + } |
| + return l.ConnGen |
| } |
| func TestHomeLinkClaimOnce(t *testing.T) { |
| @@ -190,7 +193,7 @@ func TestHomeLinkConnGenBumps(t *testing.T) { |
| if g := connGen(t, reg); g != uint64(i+1) { |
| t.Fatalf("retarget %d: conn_gen = %d; want %d", i, g, i+1) |
| } |
| - got, err := reg.HomeLinkAppByName("shop") |
| + got, err := reg.HomeLinkAppByName(testLinkA, "shop") |
| if err != nil || got == nil || *got != retarget { |
| t.Fatalf("HomeLinkAppByName = %+v, %v; want %+v", got, err, retarget) |
| } |
| @@ -201,7 +204,7 @@ func TestHomeLinkConnGenBumps(t *testing.T) { |
| if g := connGen(t, reg); g != 4 { |
| t.Fatalf("unpublish: conn_gen = %d; want 4", g) |
| } |
| - if got, err := reg.HomeLinkAppByName("shop"); err != nil || got != nil { |
| + if got, err := reg.HomeLinkAppByName(testLinkA, "shop"); err != nil || got != nil { |
| t.Fatalf("after unpublish HomeLinkAppByName = %+v, %v", got, err) |
| } |
| if deleted, err := reg.DeleteHomeLinkApp("shop"); err != nil || deleted { |
| @@ -443,17 +446,17 @@ func TestHomeLinkCallsOverRemote(t *testing.T) { |
| if apps, err := reg.HomeLinkApps(); err != nil || len(apps) != 1 || apps[0] != shop { |
| t.Fatalf("remote HomeLinkApps = %v, %v", apps, err) |
| } |
| - if a, err := reg.HomeLinkAppByName("shop"); err != nil || a == nil || *a != shop { |
| + if a, err := reg.HomeLinkAppByName(testLinkA, "shop"); err != nil || a == nil || *a != shop { |
| t.Fatalf("remote HomeLinkAppByName = %+v, %v", a, err) |
| } |
| - if a, err := reg.HomeLinkAppByName("blog"); err != nil || a != nil { |
| + if a, err := reg.HomeLinkAppByName(testLinkA, "blog"); err != nil || a != nil { |
| t.Fatalf("remote HomeLinkAppByName(blog) = %+v, %v", a, err) |
| } |
| if deleted, err := reg.DeleteHomeLinkApp("shop"); err != nil || !deleted { |
| t.Fatalf("remote DeleteHomeLinkApp = %v, %v", deleted, err) |
| } |
| - if g, err := reg.HomeLinkConnGen(); err != nil || g != 1 { |
| - t.Fatalf("remote HomeLinkConnGen = %d, %v", g, err) |
| + if l, err := reg.HomeLink(); err != nil || l == nil || l.ConnGen != 1 { |
| + t.Fatalf("remote HomeLink after unpublish = %+v, %v; want conn_gen 1", l, err) |
| } |
| if l, _ := reg.HomeLink(); l.BoxLabel != "box-a" || l.State != HomeLinkConnected { |
| t.Fatalf("remote HomeLink = %+v", l) |
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go| index 5bb4c2e7d..3bba7de2e 100644 |
| --- a/internal/registry/remote_dispatch.go |
| +++ b/internal/registry/remote_dispatch.go |
| @@ -301,14 +301,10 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback |
| err = r.SetHomeLinkState(q.Status) |
| case "SetHomeLinkUnlinkPending": |
| err = r.SetHomeLinkUnlinkPending(q.LinkID, q.On) |
| - case "HomeLinkConnGen": |
| - var gen uint64 |
| - gen, err = r.HomeLinkConnGen() |
| - out.Number64 = int64(gen) |
| case "HomeLinkApps": |
| out.HomeLinkApps, err = r.HomeLinkApps() |
| case "HomeLinkAppByName": |
| - out.HomeLinkApp, err = r.HomeLinkAppByName(q.Name) |
| + out.HomeLinkApp, err = r.HomeLinkAppByName(q.LinkID, q.Name) |
| case "PutHomeLinkApp": |
| err = r.PutHomeLinkApp(q.HomeLinkApp) |
| case "DeleteHomeLinkApp": |