edge, registry: hold refused hosts out of remote; epoch generation
Review fix round 1 for Task 5 (#186).
I1: buildRemotePaths takes a held set (heldNames): hosts the fleet arm
refused, routes demoRouteOK refuses, demo identities, and names the
filters took out of the map after the folds. None gets a remote map.
G1: PathsGeneration checks the three route_paths triggers and errors
with ErrPathsGenerationUnavailable when any is missing (or the epoch is
empty), so neither the Reload row reuse nor the reconcile memo keys on
a counter that has stopped moving.
G2: the counter row carries a random epoch, written once when the row
is created (an older table gains the column and an epoch on open). The
generation is PathsGen{Epoch, N}; the Reload cache, the reconcile memo
and ApplyPaths use the pair, the remote transport carries it, and
Fingerprint's route_paths section hashes the epoch (an empty table
still digests as before).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+329
−61
internal/domains/pathwrite.go+1 −1internal/edge/edge.go+2 −2internal/edge/pathremote.go+45 −10internal/edge/pathremote_test.go+93 −2internal/registry/pathsgen.go+92 −35internal/registry/pathsgen_test.go+93 −9internal/registry/registry.go+1 −1internal/registry/remote_dispatch.go+2 −1
CI failed — run details
diff --git a/internal/domains/pathwrite.go b/internal/domains/pathwrite.go| index dd37637ab..f137c9677 100644 |
| --- a/internal/domains/pathwrite.go |
| +++ b/internal/domains/pathwrite.go |
| @@ -53,7 +53,7 @@ func (s *pathSet) sum() (d [sha256.Size]byte) { |
| // because a pass compared or wrote it so. |
| type pathMemo struct { |
| digest [sha256.Size]byte |
| - gen int64 |
| + gen registry.PathsGen // the counter and the registry file's epoch |
| } |
| // pathMemos holds a pathMemo per *registry.Registry. Production holds one |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 8835a1cd1..90a45009b 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -1513,12 +1513,12 @@ func (e *Edge) Reload() error { |
| } |
| } |
| e.foldRegional(m, routes, regionalRows) |
| - regional := regionalNamesOf(m) |
| + folded, regional := foldedNames(m) |
| demoNames := demoRefusalNames(m, routes, aliases) |
| e.filterDemoRoutes(m, routes) |
| // Refusals hold through every fold above: last, so nothing re-adds them. |
| refusedHosts(m, verdict.Refused) |
| - remote := buildRemotePaths(m, paths, forwardHostsOf(routes), regional, e.demoReserved) |
| + remote := buildRemotePaths(m, paths, forwardHostsOf(routes), regional, e.heldNames(routes, verdict.Refused, demoNames, folded, m), e.demoReserved) |
| // Fleet channel auth and the door's tenancy map, read before the routes |
| // loop (above), applied here as they always were. The link half of the |
| // set is the map SetLinkAuth already applied at the top, so for links |
diff --git a/internal/edge/pathremote.go b/internal/edge/pathremote.go| index 10d0aed44..42daff419 100644 |
| --- a/internal/edge/pathremote.go |
| +++ b/internal/edge/pathremote.go |
| @@ -13,6 +13,7 @@ package edge |
| import ( |
| "log" |
| + "maps" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| @@ -45,7 +46,7 @@ func (e *Edge) table() *routeTable { |
| // because those also depend on the routes, aliases, regional rows and demo |
| // settings the same Reload reads. |
| type pathRowCache struct { |
| - gen int64 |
| + gen registry.PathsGen // the counter and the registry file's epoch |
| rows []registry.RoutePath |
| ok bool // gen and rows are a pair this cache may reuse |
| // reads counts the reads load made: the test seam that shows a reuse. |
| @@ -57,8 +58,11 @@ type pathRowCache struct { |
| // before the rows: a write between the two leaves newer rows under an older |
| // generation, which the next load reads again; the other order could keep |
| // older rows under a newer generation for good. A generation that cannot be |
| -// read (a registry no read-write open has migrated) is never reused. |
| -func (c *pathRowCache) load(generation func() (int64, error), read func() ([]registry.RoutePath, error)) ([]registry.RoutePath, error) { |
| +// read or trusted (a registry no read-write open has migrated, a missing |
| +// trigger: registry.ErrPathsGenerationUnavailable) is never reused. The |
| +// generation carries the registry file's epoch, so rows read from one file |
| +// are never reused for another whose counter happens to match. |
| +func (c *pathRowCache) load(generation func() (registry.PathsGen, error), read func() ([]registry.RoutePath, error)) ([]registry.RoutePath, error) { |
| gen, genErr := generation() |
| if genErr == nil && c.ok && gen == c.gen { |
| return c.rows, nil |
| @@ -114,11 +118,41 @@ func forwardHostsOf(routes []registry.Route) map[string]bool { |
| return out |
| } |
| -// regionalNamesOf is the names the regional fold put in m, serve or deny. |
| -func regionalNamesOf(m map[string]upstream) map[string]bool { |
| - out := map[string]bool{} |
| +// foldedNames is every name m holds after the folds and before the filters |
| +// (filterDemoRoutes, refusedHosts), and of those the names the regional fold |
| +// put in m, serve or deny. |
| +func foldedNames(m map[string]upstream) (all, regional map[string]bool) { |
| + all, regional = make(map[string]bool, len(m)), map[string]bool{} |
| for host, up := range m { |
| + all[host] = true |
| if up.regional != regionalNone { |
| + regional[host] = true |
| + } |
| + } |
| + return all, regional |
| +} |
| + |
| +// heldNames is the names this Reload holds out of its map on purpose, which |
| +// no remote map may serve either: every host the fleet arm refused (held |
| +// out through every fold, FleetVerdict.Refused), every route the demo rules |
| +// refuse (demoRouteOK: the loop builds no entry for it), every demo |
| +// identity (demoNames), and every name of folded that the filters then took |
| +// out of m. |
| +func (e *Edge) heldNames(routes []registry.Route, refused map[string]string, demoNames, folded map[string]bool, m map[string]upstream) map[string]bool { |
| + out := maps.Clone(demoNames) |
| + if out == nil { |
| + out = map[string]bool{} |
| + } |
| + for host := range refused { |
| + out[host] = true |
| + } |
| + for _, rt := range routes { |
| + if !e.demoRouteOK(rt.Host, rt) { |
| + out[rt.Host] = true |
| + } |
| + } |
| + for host := range folded { |
| + if _, kept := m[host]; !kept { |
| out[host] = true |
| } |
| } |
| @@ -129,17 +163,18 @@ func regionalNamesOf(m map[string]upstream) map[string]bool { |
| // maps of the hosts m does not hold, with the same filters as the local |
| // fold. A row is skipped when its host is in m (it folded locally), is a |
| // forward host, is a regional name on this box (Review Focus 3: no |
| -// cross-box selection for it), or when its host or target is demo-reserved |
| -// (filterDemoRoutes' rules). Only a claim's own host is keyed: the rows are |
| +// cross-box selection for it), is held out of m on purpose (held: |
| +// heldNames), or when its host or target is demo-reserved (filterDemoRoutes' |
| +// rules). Only a claim's own host is keyed: the rows are |
| // keyed by it, and aliases and catch-alls have none. |
| // |
| // One host's rows come from one claim. A host whose rows name two owners is |
| // dropped, and logged, rather than routed for either. |
| -func buildRemotePaths(m map[string]upstream, rows []registry.RoutePath, forwardHosts, regional map[string]bool, demoReserved func(string) bool) map[string]remotePathMap { |
| +func buildRemotePaths(m map[string]upstream, rows []registry.RoutePath, forwardHosts, regional, held map[string]bool, demoReserved func(string) bool) map[string]remotePathMap { |
| out := map[string]remotePathMap{} |
| split := map[string]bool{} |
| for _, p := range rows { |
| - if _, served := m[p.Host]; served || forwardHosts[p.Host] || regional[p.Host] || split[p.Host] || |
| + if _, served := m[p.Host]; served || forwardHosts[p.Host] || regional[p.Host] || held[p.Host] || split[p.Host] || |
| demoReserved(p.Host) || demoReserved(p.Target) { |
| continue |
| } |
diff --git a/internal/edge/pathremote_test.go b/internal/edge/pathremote_test.go| index 18556cd34..bd6ea9fe2 100644 |
| --- a/internal/edge/pathremote_test.go |
| +++ b/internal/edge/pathremote_test.go |
| @@ -1,6 +1,7 @@ |
| package edge |
| import ( |
| + "database/sql" |
| "maps" |
| "strings" |
| "sync/atomic" |
| @@ -85,7 +86,7 @@ func TestRemotePathsDropDisagreeingClaim(t *testing.T) { |
| {Host: "hub.example", Prefix: "b", Target: "t2.example", Account: "other", App: "hub"}, |
| {Host: "ok.example", Prefix: "a", Target: "t1.example", Account: "acct", App: "ok"}, |
| } |
| - remote := buildRemotePaths(map[string]upstream{}, rows, nil, nil, func(string) bool { return false }) |
| + remote := buildRemotePaths(map[string]upstream{}, rows, nil, nil, nil, func(string) bool { return false }) |
| if _, ok := remote["hub.example"]; ok { |
| t.Error("a host whose rows disagree on the claim has a remote map") |
| } |
| @@ -113,7 +114,7 @@ func TestRemotePathsSkipRegionalName(t *testing.T) { |
| } |
| rows := []registry.RoutePath{{Host: "hub.example", Prefix: "paulca", Target: "t1.example", Account: "acct", App: "hub"}} |
| - remote := buildRemotePaths(map[string]upstream{}, rows, nil, map[string]bool{"hub.example": true}, func(string) bool { return false }) |
| + remote := buildRemotePaths(map[string]upstream{}, rows, nil, map[string]bool{"hub.example": true}, nil, func(string) bool { return false }) |
| if _, ok := remote["hub.example"]; ok { |
| t.Error("buildRemotePaths built a map for a regional name") |
| } |
| @@ -254,3 +255,93 @@ func TestReloadReusesPathsWhileGenerationUnchanged(t *testing.T) { |
| t.Error("the new row is not in the published map") |
| } |
| } |
| + |
| +// TestRemotePathsSkipRefusedHost: a host the fleet arm refuses is held out |
| +// through every fold (FleetVerdict.Refused), the remote map included. Here a |
| +// fleet-placed route on a fleet this box does not know. |
| +func TestRemotePathsSkipRefusedHost(t *testing.T) { |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "shop.example", Account: "acct", App: "shop", Kind: "instance", Status: "ready", |
| + Region: registry.PlacementTarget("nowhere"), Addr: "127.0.0.1:1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + remotePathRow(t, reg, "shop.example", "a", "t1.example", "acct", "shop") |
| + e := remoteEdge(t, reg) |
| + e.EnableTunnels(NewTunnelHub("127.0.0.1", nil)) |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb := e.table() |
| + if _, served := tb.hosts["shop.example"]; served { |
| + t.Fatal("fixture: this box serves the refused route") |
| + } |
| + if _, ok := tb.remote["shop.example"]; ok { |
| + t.Error("a host the fleet arm refuses has a remote map") |
| + } |
| +} |
| + |
| +// TestRemotePathsSkipDemoDroppedHost: a route the demo rules drop on this |
| +// box (a non-demo route in the demo account, demoRouteOK) gets no remote map. |
| +func TestRemotePathsSkipDemoDroppedHost(t *testing.T) { |
| + reg := openReg(t) |
| + readyRoute(t, reg, "shop.example", "demoacct", "shop") |
| + remotePathRow(t, reg, "shop.example", "a", "t1.example", "demoacct", "shop") |
| + e := remoteEdge(t, reg) |
| + e.demo = demo.Config{Account: "demoacct"} |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb := e.table() |
| + if _, served := tb.hosts["shop.example"]; served { |
| + t.Fatal("fixture: this box serves the demo-dropped route") |
| + } |
| + if _, ok := tb.remote["shop.example"]; ok { |
| + t.Error("a host the demo rules drop has a remote map") |
| + } |
| +} |
| + |
| +// TestReloadRereadsWithoutPathsGeneration: with a generation trigger missing |
| +// the counter is not trustworthy, so every Reload reads the rows. |
| +func TestReloadRereadsWithoutPathsGeneration(t *testing.T) { |
| + reg := openReg(t) |
| + remotePathRow(t, reg, "hub.example", "paulca", "t1.example", "acct", "hub") |
| + e := remoteEdge(t, reg) |
| + db, err := sql.Open("sqlite", reg.Path()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { db.Close() }) |
| + if _, err := db.Exec(`DROP TRIGGER route_paths_gen_update`); err != nil { |
| + t.Fatal(err) |
| + } |
| + reads := e.pathRows.reads |
| + for i := 1; i <= 2; i++ { |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := e.pathRows.reads; got != reads+i { |
| + t.Fatalf("Reload %d without a trigger: %d reads, want %d", i, got, reads+i) |
| + } |
| + } |
| +} |
| + |
| +// TestPathRowCacheIsPerFile: two registry files whose counters are equal |
| +// never share a reuse: the generation carries each file's epoch. |
| +func TestPathRowCacheIsPerFile(t *testing.T) { |
| + a, b := openReg(t), openReg(t) |
| + remotePathRow(t, a, "hub.example", "a", "t1.example", "acct", "hub") |
| + remotePathRow(t, b, "hub.example", "b", "t2.example", "acct", "hub") |
| + var c pathRowCache |
| + load := func(reg *registry.Registry) []registry.RoutePath { |
| + t.Helper() |
| + rows, err := c.load(reg.PathsGeneration, reg.ListPaths) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return rows |
| + } |
| + load(a) |
| + if rows := load(b); c.reads != 2 || len(rows) != 1 || rows[0].Prefix != "b" { |
| + t.Fatalf("after switching files: %d reads, rows %v; want 2 reads and b's row", c.reads, rows) |
| + } |
| +} |
diff --git a/internal/registry/pathsgen.go b/internal/registry/pathsgen.go| index 6eae72682..5b8ec5e1e 100644 |
| --- a/internal/registry/pathsgen.go |
| +++ b/internal/registry/pathsgen.go |
| @@ -3,6 +3,7 @@ package registry |
| import ( |
| "context" |
| "database/sql" |
| + "errors" |
| "fmt" |
| "io" |
| "slices" |
| @@ -19,16 +20,19 @@ import ( |
| // writer can forget it: not a new registry method, not an older binary, not |
| // a hand edit in the sqlite3 shell. |
| // |
| -// The schema is additive (CREATE ... IF NOT EXISTS, INSERT OR IGNORE), so an |
| -// existing registry migrates on open. Its counter starts at 0 with whatever |
| -// rows it already holds, which is fine: the generation only has to MOVE |
| -// when a row changes, never to equal anything on another box. |
| +// The counter row also carries an epoch: a random value written once, when |
| +// the row is created, so a generation names one registry file as well as a |
| +// point in its history. Two files whose counters happen to be equal (a |
| +// replaced or restored file, a reconnect by path) never answer the same |
| +// generation, and a reuse keyed on it cannot carry one file's rows over to |
| +// the other. |
| +// |
| +// The schema is additive (CREATE ... IF NOT EXISTS, INSERT OR IGNORE, and |
| +// migratePathsGen's epoch column), so an existing registry migrates on |
| +// open. Its counter starts at 0 with whatever rows it already holds, which |
| +// is fine: the generation only has to MOVE when a row changes, never to |
| +// equal anything on another box. |
| const routePathsGenSchema = ` |
| -CREATE TABLE IF NOT EXISTS route_paths_gen ( |
| - id INTEGER PRIMARY KEY CHECK (id = 1), |
| - gen INTEGER NOT NULL |
| -); |
| -INSERT OR IGNORE INTO route_paths_gen (id, gen) VALUES (1, 0); |
| CREATE TRIGGER IF NOT EXISTS route_paths_gen_insert AFTER INSERT ON route_paths |
| BEGIN UPDATE route_paths_gen SET gen = gen + 1 WHERE id = 1; END; |
| CREATE TRIGGER IF NOT EXISTS route_paths_gen_update AFTER UPDATE ON route_paths |
| @@ -36,6 +40,9 @@ BEGIN UPDATE route_paths_gen SET gen = gen + 1 WHERE id = 1; END; |
| CREATE TRIGGER IF NOT EXISTS route_paths_gen_delete AFTER DELETE ON route_paths |
| BEGIN UPDATE route_paths_gen SET gen = gen + 1 WHERE id = 1; END;` |
| +// newEpochSQL is a fresh epoch: 128 random bits, in hex. |
| +const newEpochSQL = `lower(hex(randomblob(16)))` |
| + |
| const ( |
| upsertPathSQL = ` |
| INSERT INTO route_paths (host, prefix, target, account, app) |
| @@ -43,22 +50,71 @@ VALUES (?, ?, ?, ?, ?) |
| ON CONFLICT(host, prefix) DO UPDATE SET |
| target=excluded.target, account=excluded.account, app=excluded.app` |
| deletePathSQL = `DELETE FROM route_paths WHERE host = ? AND prefix = ?` |
| - pathsGenSQL = `SELECT gen FROM route_paths_gen WHERE id = 1` |
| + pathsGenSQL = `SELECT gen, epoch FROM route_paths_gen WHERE id = 1` |
| pathsTriggerSQL = `SELECT count(*) FROM sqlite_master WHERE type = 'trigger' |
| AND name IN ('route_paths_gen_insert', 'route_paths_gen_update', 'route_paths_gen_delete')` |
| ) |
| -// PathsGeneration returns route_paths' generation: a counter that moves on |
| -// every row insert, update and delete, by any writer. |
| -func (r *Registry) PathsGeneration() (int64, error) { |
| +// migratePathsGen creates route_paths' counter table, row and triggers, and |
| +// gives a counter row from before the epoch column one. Run by migrate, |
| +// after route_paths exists. |
| +func migratePathsGen(ctx context.Context, db *sql.DB) error { |
| + if _, err := db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS route_paths_gen ( |
| + id INTEGER PRIMARY KEY CHECK (id = 1), |
| + gen INTEGER NOT NULL, |
| + epoch TEXT NOT NULL DEFAULT '' |
| +)`); err != nil { |
| + return err |
| + } |
| + var hasEpoch int |
| + if err := db.QueryRowContext(ctx, `SELECT count(*) FROM pragma_table_info('route_paths_gen') WHERE name = 'epoch'`).Scan(&hasEpoch); err != nil { |
| + return err |
| + } |
| + if hasEpoch == 0 { |
| + if _, err := db.ExecContext(ctx, `ALTER TABLE route_paths_gen ADD COLUMN epoch TEXT NOT NULL DEFAULT ''`); err != nil { |
| + return err |
| + } |
| + } |
| + if _, err := db.ExecContext(ctx, `INSERT OR IGNORE INTO route_paths_gen (id, gen, epoch) VALUES (1, 0, `+newEpochSQL+`); |
| +UPDATE route_paths_gen SET epoch = `+newEpochSQL+` WHERE id = 1 AND epoch = '';`+routePathsGenSchema); err != nil { |
| + return err |
| + } |
| + return nil |
| +} |
| + |
| +// PathsGen is route_paths' generation: N moves on every row insert, update |
| +// and delete, by any writer; Epoch names the registry file (see above). |
| +// Equal generations mean the same rows. |
| +type PathsGen struct { |
| + Epoch string |
| + N int64 |
| +} |
| + |
| +// ErrPathsGenerationUnavailable is PathsGeneration's answer when the |
| +// registry cannot vouch for its generation: a trigger is missing, so the |
| +// counter does not move on every write, or the counter row has no epoch. |
| +// A caller then reads the rows. |
| +var ErrPathsGenerationUnavailable = errors.New("route_paths generation unavailable") |
| + |
| +// PathsGeneration returns route_paths' generation. It errors when the |
| +// generation cannot be trusted (ErrPathsGenerationUnavailable) or read; a |
| +// caller never keys a reuse on an error. |
| +func (r *Registry) PathsGeneration() (PathsGen, error) { |
| if r.remote != nil { |
| out, err := r.remote.call(context.Background(), remoteRequest{Method: "PathsGeneration"}, nil) |
| - return out.Number64, err |
| + return out.PathGen, err |
| } |
| - var gen int64 |
| + var g PathsGen |
| + var triggers int |
| // No caller context: like every other registry read without one. |
| - err := r.sql.QueryRowContext(context.Background(), pathsGenSQL).Scan(&gen) |
| - return gen, err |
| + err := r.sql.QueryRowContext(context.Background(), `SELECT (`+pathsTriggerSQL+`), gen, epoch FROM route_paths_gen WHERE id = 1`).Scan(&triggers, &g.N, &g.Epoch) |
| + if err != nil { |
| + return PathsGen{}, err |
| + } |
| + if triggers != 3 || g.Epoch == "" { |
| + return PathsGen{}, fmt.Errorf("%w: %d of 3 triggers, epoch %q", ErrPathsGenerationUnavailable, triggers, g.Epoch) |
| + } |
| + return g, nil |
| } |
| // ApplyPaths writes one reconcile pass's route_paths changes, the upserts |
| @@ -72,7 +128,7 @@ func (r *Registry) PathsGeneration() (int64, error) { |
| // before deciding these writes knows, when its reading equals before, that |
| // no other writer moved the table in between, and that after names exactly |
| // the table it decided. |
| -func (r *Registry) ApplyPaths(upserts []RoutePath, deletes [][2]string) (before, after int64, err error) { |
| +func (r *Registry) ApplyPaths(upserts []RoutePath, deletes [][2]string) (before, after PathsGen, err error) { |
| if r.remote != nil { |
| out, err := r.remote.call(context.Background(), remoteRequest{Method: "ApplyPaths", PathUpserts: upserts, PathDeletes: deletes}, nil) |
| return out.PathGens[0], out.PathGens[1], err |
| @@ -80,11 +136,11 @@ func (r *Registry) ApplyPaths(upserts []RoutePath, deletes [][2]string) (before, |
| ctx := context.Background() // no caller context: as PathsGeneration |
| tx, err := r.beginClaimTransaction(ctx, false) |
| if err != nil { |
| - return 0, 0, err |
| + return before, after, err |
| } |
| defer tx.Rollback() |
| - if err := tx.QueryRowContext(ctx, pathsGenSQL).Scan(&before); err != nil { |
| - return 0, 0, err |
| + if err := tx.QueryRowContext(ctx, pathsGenSQL).Scan(&before.N, &before.Epoch); err != nil { |
| + return PathsGen{}, PathsGen{}, err |
| } |
| // Many rows per statement: each statement costs a prepare and, because |
| // the generation triggers fire inside it, a statement journal of every |
| @@ -99,7 +155,7 @@ func (r *Registry) ApplyPaths(upserts []RoutePath, deletes [][2]string) (before, |
| ON CONFLICT(host, prefix) DO UPDATE SET |
| target=excluded.target, account=excluded.account, app=excluded.app` |
| if _, err := tx.ExecContext(ctx, q, args...); err != nil { |
| - return 0, 0, fmt.Errorf("upsert %d path rows from %s/%s: %w", len(chunk), chunk[0].Host, chunk[0].Prefix, err) |
| + return PathsGen{}, PathsGen{}, fmt.Errorf("upsert %d path rows from %s/%s: %w", len(chunk), chunk[0].Host, chunk[0].Prefix, err) |
| } |
| } |
| for chunk := range slices.Chunk(deletes, applyPathsChunk) { |
| @@ -109,11 +165,11 @@ ON CONFLICT(host, prefix) DO UPDATE SET |
| } |
| q := `DELETE FROM route_paths WHERE (host, prefix) IN (VALUES ` + groupPlaceholders("(?, ?)", len(chunk)) + `)` |
| if _, err := tx.ExecContext(ctx, q, args...); err != nil { |
| - return 0, 0, fmt.Errorf("remove %d path rows from %s/%s: %w", len(chunk), chunk[0][0], chunk[0][1], err) |
| + return PathsGen{}, PathsGen{}, fmt.Errorf("remove %d path rows from %s/%s: %w", len(chunk), chunk[0][0], chunk[0][1], err) |
| } |
| } |
| - if err := tx.QueryRowContext(ctx, pathsGenSQL).Scan(&after); err != nil { |
| - return 0, 0, err |
| + if err := tx.QueryRowContext(ctx, pathsGenSQL).Scan(&after.N, &after.Epoch); err != nil { |
| + return PathsGen{}, PathsGen{}, err |
| } |
| return before, after, tx.Commit() |
| } |
| @@ -130,7 +186,7 @@ func (r *Registry) dispatchRemotePaths(q remoteRequest, out *remoteResponse) (er |
| case "ApplyPaths": |
| out.PathGens[0], out.PathGens[1], err = r.ApplyPaths(q.PathUpserts, q.PathDeletes) |
| case "PathsGeneration": |
| - out.Number64, err = r.PathsGeneration() |
| + out.PathGen, err = r.PathsGeneration() |
| default: |
| err = errRemoteMethod |
| } |
| @@ -148,30 +204,31 @@ func groupPlaceholders(group string, n int) string { |
| // hashRoutePaths writes Fingerprint's route_paths section to h. |
| // |
| -// With the generation triggers in place it hashes the generation and the row |
| -// count (a belt), not the rows: every row change moves the generation, so the |
| +// With the generation triggers in place it hashes the generation, its epoch |
| +// and the row count (a belt), not the rows: every row change moves the generation, so the |
| // digest moves with it. A registry with no rows and a generation of 0 adds |
| // nothing after the marker, so it digests exactly as an empty table always |
| // has (the pinned digests in ratelimit_fingerprint_test.go). |
| // |
| // Without them (a read-only reader on a registry no read-write open has |
| -// migrated yet, or a counter row someone deleted) it hashes every row, as |
| +// migrated yet, a counter row someone deleted, a missing epoch) it hashes every row, as |
| // before the counter existed: slower, never blind. |
| func hashRoutePaths(ctx context.Context, db *sql.DB, h io.Writer) error { |
| fmt.Fprint(h, "\x1droute_paths\x1e") |
| - var triggers int |
| - if err := db.QueryRowContext(ctx, pathsTriggerSQL).Scan(&triggers); err != nil { |
| + var triggers, epochColumn int |
| + if err := db.QueryRowContext(ctx, `SELECT (`+pathsTriggerSQL+`), (SELECT count(*) FROM pragma_table_info('route_paths_gen') WHERE name = 'epoch')`).Scan(&triggers, &epochColumn); err != nil { |
| return err |
| } |
| - if triggers == 3 { |
| + if triggers == 3 && epochColumn == 1 { |
| var gen sql.NullInt64 |
| + var epoch sql.NullString |
| var n int64 |
| - if err := db.QueryRowContext(ctx, `SELECT (`+pathsGenSQL+`), (SELECT count(*) FROM route_paths)`).Scan(&gen, &n); err != nil { |
| + if err := db.QueryRowContext(ctx, `SELECT (SELECT gen FROM route_paths_gen WHERE id = 1), (SELECT epoch FROM route_paths_gen WHERE id = 1), (SELECT count(*) FROM route_paths)`).Scan(&gen, &epoch, &n); err != nil { |
| return err |
| } |
| - if gen.Valid { |
| + if gen.Valid && epoch.String != "" { |
| if gen.Int64 != 0 || n != 0 { |
| - fmt.Fprintf(h, "gen=%d\x1fcount=%d\x1e", gen.Int64, n) |
| + fmt.Fprintf(h, "gen=%d\x1fepoch=%s\x1fcount=%d\x1e", gen.Int64, epoch.String, n) |
| } |
| return nil |
| } |
diff --git a/internal/registry/pathsgen_test.go b/internal/registry/pathsgen_test.go| index 3db67838b..726e94b8d 100644 |
| --- a/internal/registry/pathsgen_test.go |
| +++ b/internal/registry/pathsgen_test.go |
| @@ -2,6 +2,7 @@ package registry |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "testing" |
| ) |
| @@ -106,7 +107,7 @@ func TestPathsGenerationMovesOnEveryWrite(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - return g |
| + return g.N |
| } |
| g0 := gen() |
| p := RoutePath{Host: "shop.example.com", Prefix: "a", Target: "one.example.com", Account: "shop", App: "front"} |
| @@ -164,11 +165,11 @@ func TestApplyPathsIsOneTransaction(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if before != g0 || after != g0+3 { |
| - t.Fatalf("ApplyPaths generations %d -> %d, want %d -> %d (two upserts, one row deleted)", before, after, g0, g0+3) |
| + if before != g0 || after.Epoch != g0.Epoch || after.N != g0.N+3 { |
| + t.Fatalf("ApplyPaths generations %+v -> %+v, want %+v -> N+3 (two upserts, one row deleted)", before, after, g0) |
| } |
| if g, _ := reg.PathsGeneration(); g != after { |
| - t.Fatalf("generation after commit %d, ApplyPaths said %d", g, after) |
| + t.Fatalf("generation after commit %+v, ApplyPaths said %+v", g, after) |
| } |
| rows, err := reg.ListPaths() |
| if err != nil { |
| @@ -203,7 +204,7 @@ BEGIN SELECT RAISE(ABORT, 'refused'); END`) |
| t.Fatal("ApplyPaths succeeded over a refused row") |
| } |
| if g, _ := reg.PathsGeneration(); g != g0 { |
| - t.Fatalf("generation moved from %d to %d on a failed ApplyPaths", g0, g) |
| + t.Fatalf("generation moved from %+v to %+v on a failed ApplyPaths", g0, g) |
| } |
| if fp := mustFingerprint(t, reg); fp != fp0 { |
| t.Fatal("fingerprint moved on a failed ApplyPaths") |
| @@ -226,8 +227,8 @@ func TestApplyPathsAcrossChunks(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if rows, _ := reg.ListPaths(); len(rows) != n || after-before != int64(n) { |
| - t.Fatalf("after upserting %d rows: %d rows, generation moved %d", n, len(rows), after-before) |
| + if rows, _ := reg.ListPaths(); len(rows) != n || after.N-before.N != int64(n) { |
| + t.Fatalf("after upserting %d rows: %d rows, generation moved %d", n, len(rows), after.N-before.N) |
| } |
| keep := dels[n-1] |
| before, after, err = reg.ApplyPaths(nil, dels[:n-1]) |
| @@ -235,7 +236,90 @@ func TestApplyPathsAcrossChunks(t *testing.T) { |
| t.Fatal(err) |
| } |
| rows, _ := reg.ListPaths() |
| - if len(rows) != 1 || rows[0].Prefix != keep[1] || after-before != int64(n-1) { |
| - t.Fatalf("after deleting %d rows: %v, generation moved %d", n-1, rows, after-before) |
| + if len(rows) != 1 || rows[0].Prefix != keep[1] || after.N-before.N != int64(n-1) { |
| + t.Fatalf("after deleting %d rows: %v, generation moved %d", n-1, rows, after.N-before.N) |
| + } |
| +} |
| + |
| +// TestPathsGenerationErrorsWithoutTriggers: with any of the three triggers |
| +// missing the counter no longer moves on every write, so the generation is |
| +// not something a reader may key a reuse on. PathsGeneration says so with an |
| +// error, and every caller treats an error as "read the rows". |
| +func TestPathsGenerationErrorsWithoutTriggers(t *testing.T) { |
| + for _, name := range []string{"route_paths_gen_insert", "route_paths_gen_update", "route_paths_gen_delete"} { |
| + t.Run(name, func(t *testing.T) { |
| + reg := openTestRegistry(t) |
| + seedPaths(t, reg) |
| + if _, err := reg.PathsGeneration(); err != nil { |
| + t.Fatalf("with every trigger: %v", err) |
| + } |
| + mustExec(t, reg, `DROP TRIGGER `+name) |
| + if _, err := reg.PathsGeneration(); !errors.Is(err, ErrPathsGenerationUnavailable) { |
| + t.Fatalf("without %s: err = %v, want ErrPathsGenerationUnavailable", name, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestPathsGenerationIsPerFile: two registry files whose counters are equal |
| +// never answer the same generation, so a reuse keyed on it cannot carry one |
| +// file's rows over to another (a restored or replaced file, a reconnect by |
| +// path). The same file reopened answers the same epoch. |
| +func TestPathsGenerationIsPerFile(t *testing.T) { |
| + a, b := openTestRegistry(t), openTestRegistry(t) |
| + seedPaths(t, a) |
| + seedPaths(t, b) |
| + ga, err := a.PathsGeneration() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + gb, err := b.PathsGeneration() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if ga.N != gb.N { |
| + t.Fatalf("fixture: counters %d and %d, want equal", ga.N, gb.N) |
| + } |
| + if ga.Epoch == "" || gb.Epoch == "" || ga == gb { |
| + t.Fatalf("generations %+v and %+v: want distinct non-empty epochs", ga, gb) |
| + } |
| + if mustFingerprint(t, a) == mustFingerprint(t, b) { |
| + t.Error("two files with equal counters and rows digest the same: Fingerprint does not hash the epoch") |
| + } |
| + path := a.Path() |
| + if err := a.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + again, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { again.Close() }) |
| + if g, err := again.PathsGeneration(); err != nil || g != ga { |
| + t.Fatalf("reopened: %+v, %v; want %+v", g, err, ga) |
| + } |
| +} |
| + |
| +// TestPathsGenerationEpochMigrates: a counter table from before the epoch |
| +// gains one on the next read-write open. |
| +func TestPathsGenerationEpochMigrates(t *testing.T) { |
| + reg := openTestRegistry(t) |
| + seedPaths(t, reg) |
| + mustExec(t, reg, `ALTER TABLE route_paths_gen DROP COLUMN epoch`) |
| + if _, err := reg.PathsGeneration(); err == nil { |
| + t.Fatal("a counter table with no epoch answered a generation") |
| + } |
| + path := reg.Path() |
| + if err := reg.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + again, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { again.Close() }) |
| + g, err := again.PathsGeneration() |
| + if err != nil || g.Epoch == "" || g.N != 2 { |
| + t.Fatalf("after migration: %+v, %v; want an epoch and the counter kept at 2", g, err) |
| } |
| } |
diff --git a/internal/registry/registry.go b/internal/registry/registry.go| index 6efdfd30f..95c3c21bf 100644 |
| --- a/internal/registry/registry.go |
| +++ b/internal/registry/registry.go |
| @@ -896,7 +896,7 @@ CREATE TABLE IF NOT EXISTS route_paths ( |
| } |
| // Its generation counter and triggers (pathsgen.go), with the table. |
| // No caller context: migrate runs inside Open, which takes none. |
| - if _, err := r.sql.ExecContext(context.Background(), routePathsGenSchema); err != nil { |
| + if err := migratePathsGen(context.Background(), r.sql); err != nil { |
| return err |
| } |
| if _, err := r.sql.Exec(`CREATE TABLE IF NOT EXISTS timers ( |
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go| index a45cc1559..6f5df641a 100644 |
| --- a/internal/registry/remote_dispatch.go |
| +++ b/internal/registry/remote_dispatch.go |
| @@ -163,7 +163,8 @@ type remoteResponse struct { |
| Wildcards []WildcardDomain |
| Regional []RegionalDomain |
| Paths []RoutePath |
| - PathGens [2]int64 // ApplyPaths: the generation before and after |
| + PathGens [2]PathsGen // ApplyPaths: the generation before and after |
| + PathGen PathsGen // PathsGeneration |
| Timers []Timer |
| Number int |
| Times map[string]int64 |