Fleet public routes Task 3: every other routes writer refuses a forward row
The writer rule (spec §4.2, R3-1): only PutForward, DeleteForward, SetFleetBoxIf, SetDNSStatus and SetCertExpiresAt write a forward row. - Every other routes statement in internal/registry carries kind <> 'forward' (the upsert's conflict arm as routes.kind). - Writers taking a Route, claim row or ColdRows input refuse a forward one with ErrForwardRow before anything: Upsert, UpsertUnlessRootfs, upsertRoute, DeleteIfUnchanged, AdoptClaimRoute, RestoreClaimRows, RebindClaimRows, SwapForImport, insertRouteTx, RestoreImportRoute's journaled original. - Transactional writers check the host's kind first (forwardAt) and answer ErrForwardRow before their first write: SwapForImport before the journal row, RetireClaimRows before archive and claim_row_retirements, RestoreClaimRows and RebindClaimRows before cold_handovers and recovery_rows (whose CREATE TABLE moved inside the transaction, after the check), CommitImport, SetClaimHold, RepointPlatformSocket. - Setters that error on an unmatched host, and Delete, now tell a forward row (ErrForwardRow) from no row (noRoute), so carlos add, route and remove exit 1 over a forward host instead of rewriting or deleting it. Tests: TestEveryRouteWriterRefusesAForwardRow (65 entries, each with a live positive arm and a whole-database comparison on the forward arm), TestRestoreWritersRefuseForwardInputsAtAbsentHosts, TestHealthPassStampsAForwardRow, TestRouteWriterInventoryIsComplete (go/types, every routes statement mapped to a writer entry or an exception, the guard text checked, 18 unresolved arguments classified), TestForwardHostRefusedByTheCLI. Record-write census: fleetPublicRoutesWriteCensusInventory layered on rootfsFleetFollowupsWriteCensusInventory, re-pinning SwapForImport. Spec §7 records Task 3's card. The FPR-C01 wording is not written: the copy row is not approved yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+1,374
−102
docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md+59 −0forward_cli_test.go+95 −0internal/provision/fleet_public_routes_census_test.go+39 −0internal/provision/plan9_b8_census_test.go+1 −1internal/registry/aliassocket.go+13 −4internal/registry/claimhold.go+5 −1internal/registry/claimrows.go+18 −3internal/registry/coldhandover.go+16 −3internal/registry/forward.go+31 −0internal/registry/forward_inventory_test.go+228 −0internal/registry/forward_writers_test.go+684 −0internal/registry/importjournal.go+35 −7internal/registry/recoveryhandover.go+19 −4internal/registry/registry.go+123 −78internal/registry/routecas.go+8 −1
Intent
Attributed to this commit: 36.1 g CO₂e (4,543,565 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-public-routes, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md| index 5c9c531d7..470779333 100644 |
| --- a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md |
| +++ b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md |
| @@ -836,6 +836,53 @@ Units, by file (N = new, R = removed, otherwise a changed body or sites): |
| `carryAliasesTx`. Those with read sites appear on the card as `body` or |
| `sites`; the rest move only the `internal/registry` envelope. Callers in |
| other packages are unchanged (§4.2). |
| + |
| + Task 3's card, reconciled with this list. Every declaration named above |
| + is on it except `SetDNSStatus` and `SetCertExpiresAt` (exceptions, |
| + unchanged). `body` (sites unchanged): `RepointPlatformSocket`, |
| + `carryAliasesTx`, `AdoptClaimRoute`, `RetireClaimRows`, |
| + `CloseImportGate`, `CommitImport`, `insertRouteTx`, `ClearNextDueIf`, |
| + `DeleteIfHold`, `DeleteIfHoldWithTimers`, `HandHold`, |
| + `InstallLifetimeIf`, `ReleaseHold`, `ReleaseHoldSeq`, `SetAccount`, |
| + `SetArgs`, `SetHoldIf`, `SetHoldIfSeq`, `SetInstancePaths`, |
| + `SetNextDue`, `SetServingVersion`, `SetVersions`, `SetWorkerLimits`, |
| + `Upsert`, `UpsertUnlessRootfs`, `DeleteIfUnchanged` (`IsForward()` is a |
| + method call, not a field read). `sites`, each `+registry:sql`: `Delete` |
| + and every setter that errors on an unmatched host (`SetAssets`, |
| + `SetBacking`, `SetBuildState`, `SetCaps`, `SetChannel`, `SetChannels`, |
| + `SetChannelsAndEnvironments`, `SetDBPath`, `SetEnvironment`, |
| + `SetEnvironments`, `SetGate`, `SetGoodBuild`, `SetHA`, `SetHold`, |
| + `SetPolicy`, `SetProvisioned`, `SetRateLimit`, `SetReplica`, |
| + `SetReplicas`, `SetReplication`, `SetSeed`, `SetSeedSource`, |
| + `SetStatus`, `SetStatusNamed`, `SetSteering`, `SetTunnel`, `SetUnit`, |
| + `SetUpdateSettings`, `SetUpstreams`): the no-match answer now reads |
| + `r.sql` once more, to tell a forward row (`ErrForwardRow`) from no row; |
| + that read decides the error, never a write. `SetHibernate` and |
| + `SetPlacement`: `+whole:Route` (their existing follow-up `Get` now also |
| + answers `ErrForwardRow`). `SwapForImport`: `+registry:Host`, |
| + `+registry:Original`, `+whole:Route`; `RestoreImportRoute`: |
| + `+registry:Original`, `+whole:Route` (each refuses a forward original |
| + or next before anything). `reads`: `upsertRoute` (`+registry:Host`, the |
| + forward check on a refused conflict); `SetClaimHold` |
| + (`+whole:claimTransaction`, the forward check on its transaction); |
| + `RestoreClaimRows` and `RebindClaimRows` (`+registry:Host`, |
| + `+registry:Route`, `+whole:Route`, `+whole:claimTransaction`, and |
| + `-registry:sql`: their `CREATE TABLE IF NOT EXISTS cold_handovers` and |
| + `recovery_rows` moved from `r.sql` into the claim transaction, after |
| + the forward check, so a refusal leaves no table behind). |
| + Differences from the list above, all recorded here: `importRowTx` |
| + (`importjournal.go`, `+whole:Route`) is a changed unit the list did not |
| + name: the import's own-row check now answers `ErrForwardRow` for a |
| + forward row, for `CloseImportGate` and `RestoreImportRoute`. |
| + `forwardAt` (`forward.go`, N, `+file:QueryRow`) is a new unit the list |
| + did not name: the one `SELECT kind` every guarded writer uses. |
| + `noRoute` (`forward.go`) has no read site and moves only the envelope. |
| + The root package's `runAdd`, `runRemove` and `runRoute` are NOT on |
| + Task 3's card: they change no code yet. `carlos add` and `carlos remove` |
| + (and `carlos route` on an axis that reaches the registry) already exit 1 |
| + with `ErrForwardRow` from the registry; the refusal wording (FPR-C01) |
| + lands in the same three functions once that copy row is approved, and |
| + they appear on that commit's card. |
| - `internal/registry/forward.go` (a new file; the plan puts the forward |
| row's writers here rather than in `registry.go`): `Registry.SetFleetBoxIf` |
| (N, Task 1). Task 1's card shows it with `+file:Exec`, |
| @@ -932,6 +979,18 @@ digest changes and is re-reviewed with the card. The console changes |
| (`placeAppTarget`, instance health, the floor judge, `fleetFloorMu`, the |
| fleet-create barrier) are outside the root scope. |
| +They are not outside the record-write census, which pins by digest |
| +(preflight 1.20, 4.3): `TestPlan9B8RecordWriteCensus` now reads one layer, |
| +`fleetPublicRoutesWriteCensusInventory` |
| +(`internal/provision/fleet_public_routes_census_test.go`), on main's |
| +`rootfsFleetFollowupsWriteCensusInventory`. Task 3 re-pins |
| +`internal/registry/importjournal.go` `Registry.SwapForImport` (key-site, |
| +`key:RecordKey`, class and kinds unchanged: the forward refusals; the |
| +journal row and its record key are written as before). The C01 step |
| +re-pins `cli.go` `runRoute` there; Task 10 `reconcile.go` `Reconcile`; |
| +Task 11 `fleets.go` `Server.placeAppTarget` and `apiinstances.go` |
| +`Server.handleAPIInstanceList`. |
| + |
| Reviewer: Astra, verdict on #280. |
| ## 8. Tests |
diff --git a/forward_cli_test.go b/forward_cli_test.go| new file mode 100644 |
| index 000000000..d936e8354 |
| --- /dev/null |
| +++ b/forward_cli_test.go |
| @@ -0,0 +1,95 @@ |
| +package main |
| + |
| +import ( |
| + "errors" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// A forward row is the hub's forward phase's (fleet public routes spec §4.2): |
| +// `carlos add`, `carlos route` and `carlos remove` over a forward host exit 1 |
| +// and leave the row exactly as it was. add, route -tunnel and remove reach |
| +// the registry and fail there with ErrForwardRow; route -channel is refused |
| +// before any write by its record-owned rail (a forward row is Provisioned). |
| +// The registry-reaching verbs succeed on an ordinary host, so the refusal is |
| +// the forward row's, not the fixture's. (route -channel on an ordinary host |
| +// needs a release key to compare channels, so it has no positive arm here.) |
| +func TestForwardHostRefusedByTheCLI(t *testing.T) { |
| + bin := buildCarlos(t) |
| + regPath := filepath.Join(t.TempDir(), "registry.db") |
| + scratch := t.TempDir() |
| + run := func(args ...string) (string, int) { |
| + t.Helper() |
| + cmd := exec.Command(bin, args...) |
| + cmd.Env = carlosTestEnv(t) |
| + // pick() walks cwd ancestors for .carlos/config, so the subprocess must not run from the real checkout. |
| + cmd.Dir = scratch |
| + out, err := cmd.CombinedOutput() |
| + var exit *exec.ExitError |
| + switch { |
| + case err == nil: |
| + return string(out), 0 |
| + case errors.As(err, &exit): |
| + return string(out), exit.ExitCode() |
| + } |
| + t.Fatalf("carlos %v: %v", args, err) |
| + return "", 0 |
| + } |
| + |
| + reg, err := registry.Open(regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + |
| + const host = "shop.example.com" |
| + if err := reg.PutForward(registry.Route{Host: host, Kind: registry.KindForward, Slug: "shop", App: "shop", |
| + Account: "bah", Region: registry.PlacementTarget("home"), Channel: "stable"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + before, err := reg.Get(host) |
| + if err != nil || before == nil || !before.InertForward() { |
| + t.Fatalf("fixture: %+v, %v", before, err) |
| + } |
| + |
| + // The verbs that reach a registry write. |
| + verbs := func(h string) [][]string { |
| + return [][]string{ |
| + {"add", "-registry", regPath, "-app", "shop", h}, |
| + {"route", "-registry", regPath, "-host", h, "-tunnel", "t1"}, |
| + {"remove", "-registry", regPath, h}, |
| + } |
| + } |
| + |
| + // Positive control: an ordinary host goes through all three. |
| + const other = "blog.example.com" |
| + for _, args := range verbs(other) { |
| + if out, code := run(args...); code != 0 { |
| + t.Fatalf("carlos %v on an ordinary host: exit %d\n%s", args, code, out) |
| + } |
| + if args[0] == "route" { |
| + if rt, err := reg.Get(other); err != nil || rt == nil || rt.Tunnel != "t1" { |
| + t.Fatalf("after carlos route on an ordinary host: %+v, %v", rt, err) |
| + } |
| + } |
| + } |
| + |
| + channel := []string{"route", "-registry", regPath, "-host", host, "-channel", "x"} |
| + for _, args := range append(verbs(host), channel) { |
| + out, code := run(args...) |
| + if code != 1 { |
| + t.Errorf("carlos %v over a forward row: exit %d, want 1\n%s", args, code, out) |
| + } |
| + if args[len(args)-2] != "-channel" && !strings.Contains(out, registry.ErrForwardRow.Error()) { |
| + t.Errorf("carlos %v over a forward row did not fail in the registry:\n%s", args, out) |
| + } |
| + after, err := reg.Get(host) |
| + if err != nil || after == nil || *after != *before { |
| + t.Fatalf("carlos %v changed the forward row:\n before %+v\n after %+v (%v)", args, before, after, err) |
| + } |
| + } |
| +} |
diff --git a/internal/provision/fleet_public_routes_census_test.go b/internal/provision/fleet_public_routes_census_test.go| new file mode 100644 |
| index 000000000..355dab9d8 |
| --- /dev/null |
| +++ b/internal/provision/fleet_public_routes_census_test.go |
| @@ -0,0 +1,39 @@ |
| +package provision |
| + |
| +// Record-write census entries for fleet public routes (branch |
| +// design-fleet-public-routes; spec docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md |
| +// §7, preflight 1.20 and 4.3), layered on |
| +// rootfsFleetFollowupsWriteCensusInventory (main's newest, merged into the |
| +// branch). Reviewed by the task author against the source; the census |
| +// approval is recorded on #280 with the root-read card. Tasks 10 and 11 |
| +// append their re-pins to this same function. |
| +// |
| +// Task 3, one re-pin, no new unit: |
| +// - internal/registry/importjournal.go Registry.SwapForImport (key-site): |
| +// the writer rule (spec §4.2). A forward next or original is |
| +// ErrForwardRow before anything; inside the transaction a forward row at |
| +// the host is ErrForwardRow before the journal row is written; the |
| +// route DELETE carries kind <> 'forward'. The journal row and its record |
| +// key are written exactly as before. |
| +func fleetPublicRoutesWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), rootfsFleetFollowupsWriteCensusInventory()...) |
| + repins := []censusEntry{ |
| + // Task 3: the forward-row refusals; the same journal row and record key. |
| + {"internal/registry/importjournal.go", "Registry.SwapForImport", "key-site", "key:RecordKey", "ce455c5e25b3534423b4a7113c8429ce8f57057b04a298abe8f8ca839ccd0162"}, |
| + } |
| + for _, r := range repins { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + if e.Class != r.Class || e.Kinds != r.Kinds { |
| + panic("fleet-public-routes re-pin changes the class or kinds of " + r.File + ":" + r.Unit) |
| + } |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + panic("fleet-public-routes re-pin of an unlisted unit " + r.File + ":" + r.Unit) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 0098f6133..893794f4d 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := rootfsFleetFollowupsWriteCensusInventory() |
| + inventory := fleetPublicRoutesWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/registry/aliassocket.go b/internal/registry/aliassocket.go| index 3c0fb0e6a..139b03657 100644 |
| --- a/internal/registry/aliassocket.go |
| +++ b/internal/registry/aliassocket.go |
| @@ -74,8 +74,14 @@ func sameTenant(a, b Route) bool { |
| } |
| // carryAliasesTx points every platform row of src's tenant that names one |
| -// of olds at src's socket. It runs inside the transaction that moved src. |
| +// of olds at src's socket. It runs inside the transaction that moved src. A |
| +// forward row neither carries aliases nor is carried as one (fleet public |
| +// routes spec §4.2): a forward src is ErrForwardRow, and the statement never |
| +// matches a forward row. |
| func carryAliasesTx(tx txer, src Route, olds ...string) error { |
| + if src.IsForward() { |
| + return ErrForwardRow |
| + } |
| if !carriesAliases(src) { |
| return nil |
| } |
| @@ -84,7 +90,7 @@ func carryAliasesTx(tx txer, src Route, olds ...string) error { |
| if old == "" || old == src.Socket { |
| continue |
| } |
| - res, err := tx.Exec(`UPDATE routes SET socket = ? WHERE platform = 1 AND host != ? AND app = ? AND `+ |
| + res, err := tx.Exec(`UPDATE routes SET socket = ? WHERE platform = 1 AND kind <> 'forward' AND host != ? AND app = ? AND `+ |
| effectiveAccountSQL("account")+` = ? AND socket = ?`, src.Socket, src.Host, src.App, acct, old) |
| if err != nil { |
| return err |
| @@ -125,7 +131,8 @@ func (r *Registry) inImmediateTx(fn func(tx txer) error) error { |
| // source's socket, or anything else, is no change. A refusal is an error. |
| // Whether either socket exists is the caller's question: the registry does |
| // not look at the filesystem. The agent's own handle only, like the import |
| -// journal's doors: root never repairs. |
| +// journal's doors: root never repairs. Either row being a forward row is |
| +// ErrForwardRow (fleet public routes spec §4.2). |
| func (r *Registry) RepointPlatformSocket(alias, source string) (bool, error) { |
| changed := false |
| err := r.inImmediateTx(func(tx txer) error { |
| @@ -140,6 +147,8 @@ func (r *Registry) RepointPlatformSocket(alias, source string) (bool, error) { |
| switch { |
| case a == nil || s == nil: |
| return fmt.Errorf("registry: repoint %s onto %s: no such route", alias, source) |
| + case a.IsForward() || s.IsForward(): |
| + return ErrForwardRow |
| case !a.Platform: |
| return fmt.Errorf("registry: repoint %s: not a platform alias", alias) |
| case !carriesAliases(*s): |
| @@ -149,7 +158,7 @@ func (r *Registry) RepointPlatformSocket(alias, source string) (bool, error) { |
| case a.Socket == s.Socket || a.Socket != LayoutSibling(s.Host, s.Socket): |
| return nil |
| } |
| - res, err := tx.Exec(`UPDATE routes SET socket = ? WHERE host = ? AND platform = 1 AND socket = ?`, s.Socket, a.Host, a.Socket) |
| + res, err := tx.Exec(`UPDATE routes SET socket = ? WHERE host = ? AND kind <> 'forward' AND platform = 1 AND socket = ?`, s.Socket, a.Host, a.Socket) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/registry/claimhold.go b/internal/registry/claimhold.go| index 5f8f87b5f..897594eb3 100644 |
| --- a/internal/registry/claimhold.go |
| +++ b/internal/registry/claimhold.go |
| @@ -19,7 +19,11 @@ func (r *Registry) SetClaimHold(ctx context.Context, host string, owner ClaimOwn |
| return err |
| } |
| defer tx.Rollback() |
| - result, err := tx.ExecContext(ctx, `UPDATE routes SET hold_op=? WHERE host=? AND claim_incarnation=? AND claim_stamp=? AND claim_owner=? AND claim_row_id=? AND hold_op=?`, next, host, owner.ClaimIncarnation, owner.ClaimStamp, owner.ClaimOwner, owner.ClaimRowID, expected) |
| + // A forward row is never claim-held (fleet public routes spec §4.2). |
| + if err := forwardAt(tx, host); err != nil { |
| + return err |
| + } |
| + result, err := tx.ExecContext(ctx, `UPDATE routes SET hold_op=? WHERE host=? AND kind <> 'forward' AND claim_incarnation=? AND claim_stamp=? AND claim_owner=? AND claim_row_id=? AND hold_op=?`, next, host, owner.ClaimIncarnation, owner.ClaimStamp, owner.ClaimOwner, owner.ClaimRowID, expected) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/registry/claimrows.go b/internal/registry/claimrows.go| index 237b2e91d..121d05fda 100644 |
| --- a/internal/registry/claimrows.go |
| +++ b/internal/registry/claimrows.go |
| @@ -55,8 +55,14 @@ func (r *Registry) migrateClaimOwnership() error { |
| } |
| // AdoptClaimRoute is called only by the complete-census backfill coordinator. |
| -// The full observed row is compared inside the write transaction. |
| +// The full observed row is compared inside the write transaction. A forward |
| +// row is never claim-owned (its claim columns are forbidden, fleet public |
| +// routes spec §4.2): an observed forward row, or a forward row at the host, |
| +// is ErrForwardRow. |
| func (r *Registry) AdoptClaimRoute(ctx context.Context, observed Route, owner ClaimOwnership) error { |
| + if observed.IsForward() { |
| + return ErrForwardRow |
| + } |
| if r.remote != nil { |
| _, err := r.remote.call(ctx, remoteRequest{Method: "AdoptClaimRoute", Observed: observed, Owner: owner}, nil) |
| return err |
| @@ -74,12 +80,15 @@ func (r *Registry) AdoptClaimRoute(ctx context.Context, observed Route, owner Cl |
| if err != nil { |
| return err |
| } |
| + if current.IsForward() { |
| + return ErrForwardRow |
| + } |
| a, _ := json.Marshal(current) |
| b, _ := json.Marshal(observed) |
| if !bytes.Equal(a, b) { |
| return ErrClaimOwnership |
| } |
| - res, err := tx.ExecContext(ctx, `UPDATE routes SET claim_incarnation=?,claim_stamp=?,claim_owner=?,claim_row_id=? WHERE host=? AND claim_owner='' AND claim_stamp=0 AND claim_incarnation='' AND claim_row_id=''`, owner.ClaimIncarnation, owner.ClaimStamp, owner.ClaimOwner, owner.ClaimRowID, observed.Host) |
| + res, err := tx.ExecContext(ctx, `UPDATE routes SET claim_incarnation=?,claim_stamp=?,claim_owner=?,claim_row_id=? WHERE host=? AND kind <> 'forward' AND claim_owner='' AND claim_stamp=0 AND claim_incarnation='' AND claim_row_id=''`, owner.ClaimIncarnation, owner.ClaimStamp, owner.ClaimOwner, owner.ClaimRowID, observed.Host) |
| if err != nil { |
| return err |
| } |
| @@ -96,6 +105,9 @@ func (r *Registry) AdoptClaimRoute(ctx context.Context, observed Route, owner Cl |
| // RetireClaimRows archives the exact transaction snapshot before deletion. |
| // A missing or replacement row is successful only when this journal's committed |
| // archive proves the predecessor was already removed by an earlier attempt. |
| +// A route target that is a forward row is ErrForwardRow, answered before |
| +// archive is called and before claim_row_retirements is written (fleet |
| +// public routes spec §4.2); the routes DELETE never matches one either. |
| func (r *Registry) RetireClaimRows(ctx context.Context, journal string, targets []ClaimRow, archive func([]ClaimRowArchive) error) error { |
| if archive == nil { |
| return ErrClaimOwnership |
| @@ -148,6 +160,9 @@ func (r *Registry) RetireClaimRows(ctx context.Context, journal string, targets |
| if e != nil { |
| return fmt.Errorf("%w: %v", ErrClaimOwnership, e) |
| } |
| + if row.IsForward() { |
| + return ErrForwardRow |
| + } |
| if row.ClaimOwnership != t.Ownership { |
| return ErrClaimOwnership |
| } |
| @@ -190,7 +205,7 @@ func (r *Registry) RetireClaimRows(ctx context.Context, journal string, targets |
| return err |
| } |
| table := "routes" |
| - q := "" |
| + q := " AND kind <> 'forward'" |
| args := []any{t.Host, t.Ownership.ClaimIncarnation, t.Ownership.ClaimStamp, t.Ownership.ClaimOwner, t.Ownership.ClaimRowID} |
| if t.Kind == "timer" { |
| table = "timers" |
diff --git a/internal/registry/coldhandover.go b/internal/registry/coldhandover.go| index e7459a2f3..4b81e7287 100644 |
| --- a/internal/registry/coldhandover.go |
| +++ b/internal/registry/coldhandover.go |
| @@ -50,7 +50,15 @@ func coldRowsWithoutBuildStateCopy(c ColdRows) ColdRows { |
| return c |
| } |
| +// RestoreClaimRows puts a retired cold installation's rows back under its |
| +// successor's ownership. A forward row is never restored (fleet public routes |
| +// spec §4.2): old or next of kind forward is ErrForwardRow before anything, |
| +// and a forward row at the host is ErrForwardRow inside the transaction |
| +// before its first write, cold_handovers' creation included. |
| func (r *Registry) RestoreClaimRows(ctx context.Context, id, retirement string, old ColdRows, next ColdRows) error { |
| + if old.Route.IsForward() || next.Route.IsForward() { |
| + return ErrForwardRow |
| + } |
| if r.remote != nil { |
| _, err := r.remote.call(ctx, remoteRequest{Method: "RestoreClaimRows", Id: id, Retirement: retirement, Old: old, NextValue: next}, nil) |
| return err |
| @@ -73,14 +81,19 @@ func (r *Registry) RestoreClaimRows(ctx context.Context, id, retirement string, |
| return ErrClaimOwnership |
| } |
| } |
| - if _, err := r.sql.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS cold_handovers(id TEXT PRIMARY KEY,body BLOB NOT NULL)`); err != nil { |
| - return err |
| - } |
| tx, err := r.beginClaimTransaction(ctx, true) |
| if err != nil { |
| return err |
| } |
| defer tx.Rollback() |
| + if err := forwardAt(tx, next.Route.Host); err != nil { |
| + return err |
| + } |
| + // Created inside the transaction, after the forward check, so a refusal |
| + // leaves no trace. |
| + if _, err := tx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS cold_handovers(id TEXT PRIMARY KEY,body BLOB NOT NULL)`); err != nil { |
| + return err |
| + } |
| encoded, err := json.Marshal(next) |
| if err != nil { |
| return err |
diff --git a/internal/registry/forward.go b/internal/registry/forward.go| index b83e85f0d..437c16cfa 100644 |
| --- a/internal/registry/forward.go |
| +++ b/internal/registry/forward.go |
| @@ -341,3 +341,34 @@ func (r *Registry) DeleteForward(host string) (bool, error) { |
| n, err := res.RowsAffected() |
| return n > 0, err |
| } |
| + |
| +// forwardAt is ErrForwardRow when host's row is a forward row, and nil when |
| +// the row is of another kind or there is none (spec §4.2, the writer rule). |
| +// A writer inside a transaction calls it on its own transaction before its |
| +// first write, so the check and the write see one state. A setter whose |
| +// guarded statement matched nothing calls it afterwards to tell a forward |
| +// row from no row (noRoute); that read decides only the error, never a |
| +// write. |
| +func forwardAt(db queryer, host string) error { |
| + var kind string |
| + err := db.QueryRow(`SELECT kind FROM routes WHERE host = ?`, host).Scan(&kind) |
| + switch { |
| + case errors.Is(err, sql.ErrNoRows): |
| + return nil |
| + case err != nil: |
| + return err |
| + case kind == KindForward: |
| + return ErrForwardRow |
| + } |
| + return nil |
| +} |
| + |
| +// noRoute is a narrow setter's answer when its statement, guarded by |
| +// kind <> 'forward', matched no row: ErrForwardRow when the host is a |
| +// forward row, otherwise the setter's usual "no route for host" error. |
| +func noRoute(db queryer, host string) error { |
| + if err := forwardAt(db, host); err != nil { |
| + return err |
| + } |
| + return fmt.Errorf("no route for host %q", host) |
| +} |
diff --git a/internal/registry/forward_inventory_test.go b/internal/registry/forward_inventory_test.go| new file mode 100644 |
| index 000000000..0a622f2e6 |
| --- /dev/null |
| +++ b/internal/registry/forward_inventory_test.go |
| @@ -0,0 +1,228 @@ |
| +package registry |
| + |
| +import ( |
| + "go/ast" |
| + "go/constant" |
| + "go/importer" |
| + "go/parser" |
| + "go/token" |
| + "go/types" |
| + "path/filepath" |
| + "regexp" |
| + "sort" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// routeWriteSQL matches a statement that writes the routes table. |
| +var routeWriteSQL = regexp.MustCompile(`(?i)\b(insert(\s+or\s+\w+)?\s+into|replace\s+into|update|delete\s+from)\s+routes\b`) |
| + |
| +// forwardRowWriters are the writer rule's five exceptions (spec §4.2): the |
| +// only functions whose routes statements may touch a forward row. |
| +var forwardRowWriters = map[string]bool{ |
| + "PutForward": true, "DeleteForward": true, "SetFleetBoxIf": true, "SetDNSStatus": true, "SetCertExpiresAt": true, |
| +} |
| + |
| +// unresolvedRouteSQL classifies every SQL argument in internal/registry that |
| +// has no constant value and whose constant fragments do not name a routes |
| +// write, keyed "<file>:<enclosing function>". A new one fails the inventory |
| +// until it is read and classified here; a key that no longer matches a call |
| +// fails too. |
| +var unresolvedRouteSQL = map[string]string{ |
| + "claimtransaction.go:ExecContext": "claimTransaction's pass-through to its connection; the SQL is its caller's, inventoried at the caller", |
| + "claimtransaction.go:QueryRowContext": "claimTransaction's pass-through to its connection; the SQL is its caller's, inventoried at the caller", |
| + "claimtransaction.go:Exec": "claimTransaction's pass-through (txer); the SQL is its caller's, inventoried at the caller", |
| + "claimtransaction.go:QueryRow": "claimTransaction's pass-through (queryer); the SQL is its caller's, inventoried at the caller", |
| + "claimrows.go:migrateClaimOwnership": "ALTER TABLE routes|timers ADD COLUMN: a schema migration, writes no row", |
| + "fleets.go:migrateFleets": "ALTER TABLE fleets ADD COLUMN: a schema migration of the fleets table", |
| + "registry.go:Get": "SELECT <readCols> FROM routes WHERE host = ?: a read", |
| + "registry.go:List": "SELECT <readCols> FROM routes ORDER BY host: a read", |
| + "claimrows.go:RetireClaimRows": "DELETE FROM routes|timers built at run time; the routes arm carries kind <> 'forward', and the forward check runs before archive", |
| + "registry.go:applyRegistryPragmas": "the connection pragmas (registryPragmas): busy_timeout, journal_mode, synchronous", |
| + "registry.go:migrate": "ALTER TABLE routes ADD COLUMN from routeAddedColumns: a schema migration, writes no row", |
| + "registry.go:SetChannels": "stmt.Exec(channel, host): the prepared UPDATE above it in SetChannels, which is inventoried", |
| + "registry.go:SetEnvironments": "stmt.Exec(env, host): the prepared UPDATE above it in SetEnvironments, which is inventoried", |
| + "registry.go:SetChannelsAndEnvironments": "stmt.Exec(channel, env, host): the prepared UPDATE above it, which is inventoried", |
| + "timers.go:queryTimers": "a SELECT over timers, built by its callers", |
| + "timers.go:PruneTimers": "DELETE FROM timers built at run time; timers only", |
| + "timers.go:DeleteTimersExcept": "DELETE FROM timers built at run time; timers only", |
| + "forward.go:PutForward": "putForwardSQL, the forward row's own writer (an exception), built once from ForwardForbidden", |
| +} |
| + |
| +// sqlMethods are the database calls whose argument at the index is SQL. |
| +var sqlMethods = map[string]int{ |
| + "Exec": 0, "Query": 0, "QueryRow": 0, "Prepare": 0, |
| + "ExecContext": 1, "QueryContext": 1, "QueryRowContext": 1, "PrepareContext": 1, |
| +} |
| + |
| +type routeSQLSite struct { |
| + file, fn, text string |
| + pos token.Position |
| +} |
| + |
| +// sqlText is e's SQL with every constant fragment resolved (go/types folds |
| +// "UPDATE " + "routes SET x = ?" into one constant) and every other piece |
| +// as \x00. whole reports that the whole argument was a constant. |
| +func sqlText(info *types.Info, e ast.Expr) (text string, whole bool) { |
| + if tv, ok := info.Types[e]; ok && tv.Value != nil { |
| + if tv.Value.Kind() == constant.String { |
| + return constant.StringVal(tv.Value), true |
| + } |
| + return "\x00", false |
| + } |
| + switch x := e.(type) { |
| + case *ast.ParenExpr: |
| + return sqlText(info, x.X) |
| + case *ast.BinaryExpr: |
| + if x.Op == token.ADD { |
| + l, _ := sqlText(info, x.X) |
| + r, _ := sqlText(info, x.Y) |
| + return l + r, false |
| + } |
| + } |
| + return "\x00", false |
| +} |
| + |
| +// routeSQLSites loads internal/registry's non-test files with go/parser and |
| +// go/types and returns every SQL argument that writes routes, and the |
| +// "<file>:<func>" keys of every argument it cannot resolve. |
| +func routeSQLSites(t *testing.T) (sites []routeSQLSite, unresolved map[string][]token.Position) { |
| + t.Helper() |
| + paths, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fset := token.NewFileSet() |
| + var files []*ast.File |
| + for _, p := range paths { |
| + if strings.HasSuffix(p, "_test.go") { |
| + continue |
| + } |
| + f, err := parser.ParseFile(fset, p, nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + files = append(files, f) |
| + } |
| + if len(files) < 10 { |
| + t.Fatalf("parsed %d files; the walk is broken", len(files)) |
| + } |
| + info := &types.Info{Types: map[ast.Expr]types.TypeAndValue{}} |
| + conf := types.Config{Importer: importer.ForCompiler(fset, "source", nil)} |
| + if _, err := conf.Check("github.com/carlosframework/platform/internal/registry", fset, files, info); err != nil { |
| + t.Fatalf("type-check internal/registry: %v", err) |
| + } |
| + unresolved = map[string][]token.Position{} |
| + for _, f := range files { |
| + file := filepath.Base(fset.Position(f.Pos()).Filename) |
| + for _, decl := range f.Decls { |
| + fn := "" |
| + switch d := decl.(type) { |
| + case *ast.FuncDecl: |
| + fn = d.Name.Name |
| + case *ast.GenDecl: |
| + fn = "<package " + d.Tok.String() + ">" |
| + } |
| + ast.Inspect(decl, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + sel, ok := call.Fun.(*ast.SelectorExpr) |
| + if !ok { |
| + return true |
| + } |
| + idx, ok := sqlMethods[sel.Sel.Name] |
| + if !ok || len(call.Args) <= idx { |
| + return true |
| + } |
| + arg := call.Args[idx] |
| + text, whole := sqlText(info, arg) |
| + pos := fset.Position(arg.Pos()) |
| + switch { |
| + case routeWriteSQL.MatchString(text): |
| + sites = append(sites, routeSQLSite{file: file, fn: fn, text: text, pos: pos}) |
| + case !whole: |
| + key := file + ":" + fn |
| + unresolved[key] = append(unresolved[key], pos) |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + return sites, unresolved |
| +} |
| + |
| +// TestRouteWriterInventoryIsComplete keeps TestEveryRouteWriterRefusesAForwardRow's |
| +// table whole: every statement in internal/registry that writes routes sits in |
| +// a function that some entry of the table reaches (its encloses list), or in |
| +// one of the five exceptions. Every non-exception UPDATE, DELETE and upsert on |
| +// routes carries kind <> 'forward' in its text. A SQL argument with no constant |
| +// value is classified in unresolvedRouteSQL. |
| +func TestRouteWriterInventoryIsComplete(t *testing.T) { |
| + sites, unresolved := routeSQLSites(t) |
| + if len(sites) < 60 { |
| + t.Fatalf("found only %d routes writes; the walk is broken", len(sites)) |
| + } |
| + |
| + reached := map[string][]string{} |
| + for _, c := range routeWriterCases() { |
| + for _, fn := range c.encloses { |
| + reached[fn] = append(reached[fn], c.name) |
| + } |
| + } |
| + // A function whose only routes write is classified in |
| + // unresolvedRouteSQL (RetireClaimRows' DELETE FROM <table>, PutForward's |
| + // putForwardSQL) is still the writer its entry names. |
| + seen := map[string]bool{} |
| + for k := range unresolved { |
| + seen[k[strings.Index(k, ":")+1:]] = true |
| + } |
| + guard := regexp.MustCompile(`(?i)\bkind\s*<>\s*'forward'`) |
| + for _, s := range sites { |
| + seen[s.fn] = true |
| + if forwardRowWriters[s.fn] { |
| + continue |
| + } |
| + if len(reached[s.fn]) == 0 { |
| + t.Errorf("%s: %s writes routes and no entry of the writer table reaches it (nor is it one of the five exceptions):\n %q", s.pos, s.fn, s.text) |
| + continue |
| + } |
| + verb := strings.ToLower(routeWriteSQL.FindStringSubmatch(s.text)[1]) |
| + upsert := regexp.MustCompile(`(?is)on\s+conflict.*do\s+update`).MatchString(s.text) |
| + if (strings.HasPrefix(verb, "update") || strings.HasPrefix(verb, "delete") || upsert) && !guard.MatchString(s.text) { |
| + t.Errorf("%s: %s's routes statement does not carry kind <> 'forward':\n %q", s.pos, s.fn, s.text) |
| + } |
| + } |
| + for fn, names := range reached { |
| + if !seen[fn] { |
| + t.Errorf("writer table entries %v name %s, which holds no routes write", names, fn) |
| + } |
| + } |
| + for fn := range forwardRowWriters { |
| + if !seen[fn] { |
| + t.Errorf("exception %s holds no routes write", fn) |
| + } |
| + } |
| + |
| + var keys []string |
| + for k := range unresolved { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + for _, k := range keys { |
| + if _, ok := unresolvedRouteSQL[k]; !ok { |
| + t.Errorf("unclassified SQL argument with no constant value at %s (%v): read it and add it to unresolvedRouteSQL", k, unresolved[k]) |
| + } |
| + } |
| + for k := range unresolvedRouteSQL { |
| + if _, ok := unresolved[k]; !ok { |
| + t.Errorf("unresolvedRouteSQL key %s matches no call: remove it", k) |
| + } |
| + } |
| + fns := map[string]bool{} |
| + for _, s := range sites { |
| + fns[s.fn] = true |
| + } |
| + t.Logf("%d routes writes in %d functions; %d unresolved SQL arguments classified", len(sites), len(fns), len(unresolved)) |
| +} |
diff --git a/internal/registry/forward_writers_test.go b/internal/registry/forward_writers_test.go| new file mode 100644 |
| index 000000000..93dc73818 |
| --- /dev/null |
| +++ b/internal/registry/forward_writers_test.go |
| @@ -0,0 +1,684 @@ |
| +package registry |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "reflect" |
| + "sort" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The writer rule (fleet public routes spec §4.2, R3-1): only PutForward, |
| +// DeleteForward, SetFleetBoxIf, SetDNSStatus and SetCertExpiresAt write a |
| +// forward row. Every other routes writer refuses a forward input before any |
| +// side effect, checks a forward host first inside its transaction, and runs |
| +// every routes statement under kind <> 'forward'. These tests run each writer |
| +// of the inventory (TestRouteWriterInventoryIsComplete keeps the list whole) |
| +// twice: once on a fixture it changes, which proves the fixture is live, and |
| +// once on the same fixture with the host turned into a forward row, where |
| +// nothing in the database may change. |
| + |
| +// dumpDB is the whole database: every table named in sqlite_master, each row |
| +// rendered as its column values joined, sorted. An empty table is present |
| +// with no rows, so a table created by a refused write shows as a difference. |
| +func dumpDB(t *testing.T, r *Registry) map[string][]string { |
| + t.Helper() |
| + rows, err := r.sql.Query(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var tables []string |
| + for rows.Next() { |
| + var name string |
| + if err := rows.Scan(&name); err != nil { |
| + t.Fatal(err) |
| + } |
| + tables = append(tables, name) |
| + } |
| + rows.Close() |
| + if err := rows.Err(); err != nil { |
| + t.Fatal(err) |
| + } |
| + out := map[string][]string{} |
| + for _, table := range tables { |
| + rs, err := r.sql.Query(`SELECT * FROM "` + table + `"`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cols, err := rs.Columns() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + lines := []string{} |
| + for rs.Next() { |
| + vals := make([]any, len(cols)) |
| + ptrs := make([]any, len(cols)) |
| + for i := range vals { |
| + ptrs[i] = &vals[i] |
| + } |
| + if err := rs.Scan(ptrs...); err != nil { |
| + t.Fatal(err) |
| + } |
| + parts := make([]string, len(vals)) |
| + for i, v := range vals { |
| + if b, ok := v.([]byte); ok { |
| + v = string(b) |
| + } |
| + parts[i] = fmt.Sprint(v) |
| + } |
| + lines = append(lines, strings.Join(parts, "\x1f")) |
| + } |
| + rs.Close() |
| + if err := rs.Err(); err != nil { |
| + t.Fatal(err) |
| + } |
| + sort.Strings(lines) |
| + out[table] = lines |
| + } |
| + return out |
| +} |
| + |
| +// withoutHost is d with host's routes row left out: the carry entries' |
| +// source row, which the forward arm legitimately changes. |
| +func withoutHost(d map[string][]string, host string) map[string][]string { |
| + if host == "" { |
| + return d |
| + } |
| + out := map[string][]string{} |
| + for table, lines := range d { |
| + kept := []string{} |
| + for _, l := range lines { |
| + if table == "routes" && strings.HasPrefix(l, host+"\x1f") { |
| + continue |
| + } |
| + kept = append(kept, l) |
| + } |
| + out[table] = kept |
| + } |
| + return out |
| +} |
| + |
| +// dumpDiff names the tables whose rows differ between a and b. |
| +func dumpDiff(a, b map[string][]string) string { |
| + var out []string |
| + seen := map[string]bool{} |
| + for table := range a { |
| + seen[table] = true |
| + } |
| + for table := range b { |
| + seen[table] = true |
| + } |
| + for table := range seen { |
| + la, oka := a[table] |
| + lb, okb := b[table] |
| + if oka != okb || !reflect.DeepEqual(la, lb) { |
| + out = append(out, fmt.Sprintf("%s (present %v/%v):\n before %q\n after %q", table, oka, okb, la, lb)) |
| + } |
| + } |
| + sort.Strings(out) |
| + return strings.Join(out, "\n ") |
| +} |
| + |
| +const ( |
| + fwHost = "shop.example.com" |
| + fwAlias = "shop.bah.apps.example.com" |
| + fwSock = "/run/carlos/" + fwHost + ".sock" |
| + fwNested = "/run/carlos/instances/" + fwHost + "/app.sock" |
| + fwDB = "/data/" + fwHost + ".db" |
| + fwNestDB = "/data/instances/" + fwHost + "/" + fwHost + ".db" |
| +) |
| + |
| +var ( |
| + fwOwner = ClaimOwnership{"inc", 7, "installation-7", "route-7"} |
| + fwNextOwner = ClaimOwnership{"inc", 8, "installation-8", "route-8"} |
| +) |
| + |
| +// fwRow is an ordinary instance row of app shop, account bah (domains.Sqid(7)). |
| +func fwRow() Route { |
| + return Route{Host: fwHost, Kind: "instance", App: "shop", Account: "bah", Socket: fwSock, DBPath: fwDB, |
| + Channel: "stable", Status: "ready", CreatedAt: 1700000000} |
| +} |
| + |
| +// writerCall runs the writer. changed is the writer's own answer where it |
| +// has one (a bool result), and false where it has none. |
| +type writerCall func(forward bool) (changed bool, err error) |
| + |
| +type writerCase struct { |
| + name string |
| + // encloses names the functions holding the routes statements this |
| + // writer reaches (TestRouteWriterInventoryIsComplete). |
| + encloses []string |
| + // setup builds the state the writer needs to act at all, and returns |
| + // the host to turn forward and the call. |
| + setup func(t *testing.T, r *Registry) (string, writerCall) |
| + // forward turns the fixture's host into a forward row; nil flips the |
| + // stored row's kind and leaves every other column as the fixture set it. |
| + forward func(t *testing.T, r *Registry, host string) |
| + // refuses: on a forward host the writer answers ErrForwardRow. Otherwise |
| + // it answers no error and reports no change. |
| + refuses bool |
| + // moves is a host whose row the forward arm may change (the carry |
| + // entries' non-forward source); every other row must stay. |
| + moves string |
| + // check is the positive arm's extra assertion. |
| + check func(t *testing.T, r *Registry) |
| +} |
| + |
| +func flipForward(t *testing.T, r *Registry, host string) { |
| + t.Helper() |
| + res, err := r.sql.Exec(`UPDATE routes SET kind = 'forward' WHERE host = ?`, host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if n, _ := res.RowsAffected(); n != 1 { |
| + t.Fatalf("turning %s forward changed %d rows", host, n) |
| + } |
| +} |
| + |
| +// plainRow is the fixture of most writers: one ordinary row. |
| +func plainRow(t *testing.T, r *Registry, edit func(*Route)) string { |
| + t.Helper() |
| + rt := fwRow() |
| + if edit != nil { |
| + edit(&rt) |
| + } |
| + mustUpsert(t, r, rt) |
| + return rt.Host |
| +} |
| + |
| +func heldRow(t *testing.T, r *Registry) string { |
| + t.Helper() |
| + host := plainRow(t, r, nil) |
| + if err := r.SetHold(host, "moving", "op-1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + return host |
| +} |
| + |
| +// errCase is a writer with no bool answer, on one ordinary row. |
| +func errCase(name string, refuses bool, edit func(*Route), f func(r *Registry, host string) error) writerCase { |
| + return writerCase{name: name, encloses: []string{name}, refuses: refuses, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + host := plainRow(t, r, edit) |
| + return host, func(bool) (bool, error) { return false, f(r, host) } |
| + }} |
| +} |
| + |
| +// boolCase is a writer answering whether it changed a row; on a forward host |
| +// it answers false with no error. |
| +func boolCase(name string, held bool, f func(r *Registry, host string) (bool, error)) writerCase { |
| + return writerCase{name: name, encloses: []string{name}, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + host := "" |
| + if held { |
| + host = heldRow(t, r) |
| + } else { |
| + host = plainRow(t, r, nil) |
| + } |
| + return host, func(bool) (bool, error) { return f(r, host) } |
| + }} |
| +} |
| + |
| +// importFixture is legacyRow swapped for the import's row; closed adds the |
| +// rollback's step 1. |
| +func importFixture(t *testing.T, r *Registry, closed bool) { |
| + t.Helper() |
| + mustUpsert(t, r, legacyRow()) |
| + stored := mustRoute(t, r, importHost) |
| + j := ImportJournal{Host: importHost, SeedID: importSeedID, RecordKey: importRecordKey, Original: stored, At: 1} |
| + if err := r.SwapForImport(j, swapRow()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if closed { |
| + if err := r.CloseImportGate(importHost, importSeedID, 1); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// aliasFixture is a source row on the flat socket and its platform alias |
| +// naming the same socket, one tenant. |
| +func aliasFixture(t *testing.T, r *Registry) { |
| + t.Helper() |
| + mustUpsert(t, r, fwRow(), Route{Host: fwAlias, Kind: "instance", App: "shop", Account: "bah", Platform: true, Socket: fwSock}) |
| +} |
| + |
| +func aliasMoved(t *testing.T, r *Registry) { |
| + t.Helper() |
| + if got := socketOf(t, r, fwAlias); got != fwNested { |
| + t.Fatalf("the alias names %q, want it carried to %q", got, fwNested) |
| + } |
| +} |
| + |
| +// claimedRow is fwRow owned by the claim fwOwner. |
| +func claimedRow(t *testing.T, r *Registry) Route { |
| + t.Helper() |
| + rt := fwRow() |
| + rt.ClaimOwnership = fwOwner |
| + mustUpsert(t, r, rt) |
| + return mustRoute(t, r, rt.Host) |
| +} |
| + |
| +// repointFixture is a nested source and its alias left on the flat sibling |
| +// (the shape the repair fixes). The source goes in first: its own Upsert |
| +// would carry an alias already there. |
| +func repointFixture(t *testing.T, r *Registry) { |
| + t.Helper() |
| + plainRow(t, r, func(rt *Route) { rt.Socket = fwNested }) |
| + mustUpsert(t, r, Route{Host: fwAlias, Kind: "instance", App: "shop", Account: "bah", Platform: true, Socket: fwSock}) |
| +} |
| + |
| +func routeWriterCases() []writerCase { |
| + ctx := context.Background() |
| + cases := []writerCase{ |
| + {name: "Upsert", encloses: []string{"upsertRoute"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + host := plainRow(t, r, nil) |
| + return host, func(bool) (bool, error) { |
| + rt := fwRow() |
| + rt.Channel = "beta" |
| + return false, r.Upsert(rt) |
| + } |
| + }}, |
| + {name: "UpsertUnlessRootfs", encloses: []string{"upsertRoute"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + host := plainRow(t, r, nil) |
| + return host, func(bool) (bool, error) { |
| + rt := fwRow() |
| + rt.Channel = "beta" |
| + return false, r.UpsertUnlessRootfs(rt) |
| + } |
| + }}, |
| + // Upsert moves the source's socket and carries the tenant's alias |
| + // (carryAliasesTx, registry.go's upsert). The forward row is the alias. |
| + {name: "Upsert carrying an alias", encloses: []string{"carryAliasesTx"}, moves: fwHost, check: aliasMoved, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + aliasFixture(t, r) |
| + return fwAlias, func(bool) (bool, error) { |
| + rt := fwRow() |
| + rt.Socket = fwNested |
| + return false, r.Upsert(rt) |
| + } |
| + }}, |
| + // SetInstancePaths nests the source and carries the alias with it. |
| + {name: "SetInstancePaths carrying an alias", encloses: []string{"carryAliasesTx"}, moves: fwHost, check: aliasMoved, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + aliasFixture(t, r) |
| + return fwAlias, func(bool) (bool, error) { |
| + return false, r.SetInstancePaths(fwHost, fwDB, fwSock, fwNestDB, fwNested) |
| + } |
| + }}, |
| + errCase("Delete", true, nil, func(r *Registry, h string) error { return r.Delete(h) }), |
| + boolCase("InstallLifetimeIf", false, func(r *Registry, h string) (bool, error) { |
| + return r.InstallLifetimeIf(h, Pair{}, Pair{Incarnation: 1, ServingSeq: 1}) |
| + }), |
| + errCase("SetHold", true, nil, func(r *Registry, h string) error { return r.SetHold(h, "moving", "op-1") }), |
| + boolCase("SetHoldIf", false, func(r *Registry, h string) (bool, error) { return r.SetHoldIf(h, "moving", "op-1", "") }), |
| + boolCase("SetHoldIfSeq", false, func(r *Registry, h string) (bool, error) { |
| + return r.SetHoldIfSeq(h, "moving", "op-1", "", Pair{Incarnation: 1, ServingSeq: 1}) |
| + }), |
| + boolCase("HandHold", true, func(r *Registry, h string) (bool, error) { return r.HandHold(h, "moving", "op-2", "op-1") }), |
| + boolCase("ReleaseHold", true, func(r *Registry, h string) (bool, error) { return r.ReleaseHold(h, "op-1") }), |
| + boolCase("ReleaseHoldSeq", true, func(r *Registry, h string) (bool, error) { |
| + return r.ReleaseHoldSeq(h, "op-1", Pair{Incarnation: 1, ServingSeq: 1}) |
| + }), |
| + boolCase("DeleteIfHold", true, func(r *Registry, h string) (bool, error) { return r.DeleteIfHold(h, "op-1") }), |
| + {name: "DeleteIfHoldWithTimers", encloses: []string{"DeleteIfHoldWithTimers"}, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + host := heldRow(t, r) |
| + if err := r.UpsertTimer(Timer{Host: host, Name: "nightly", Kind: "cron", Spec: "0 3 * * *"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + return host, func(bool) (bool, error) { return r.DeleteIfHoldWithTimers(host, "op-1") } |
| + }}, |
| + {name: "ClearNextDueIf", encloses: []string{"ClearNextDueIf"}, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + host := plainRow(t, r, func(rt *Route) { rt.NextDue = 99 }) |
| + return host, func(bool) (bool, error) { return false, r.ClearNextDueIf(host, 99) } |
| + }}, |
| + errCase("SetSeedSource", true, nil, func(r *Registry, h string) error { return r.SetSeedSource(h, `{"id":"sd_x"}`) }), |
| + errCase("SetAccount", false, nil, func(r *Registry, h string) error { return r.SetAccount(h, "baj") }), |
| + errCase("SetChannel", true, nil, func(r *Registry, h string) error { return r.SetChannel(h, "beta") }), |
| + errCase("SetStatus", true, nil, func(r *Registry, h string) error { return r.SetStatus(h, "failed") }), |
| + errCase("SetCaps", true, nil, func(r *Registry, h string) error { return r.SetCaps(h, "", "smtp") }), |
| + errCase("SetDBPath", true, nil, func(r *Registry, h string) error { return r.SetDBPath(h, fwDB, fwNestDB) }), |
| + errCase("SetInstancePaths", true, nil, func(r *Registry, h string) error { |
| + return r.SetInstancePaths(h, fwDB, fwSock, fwNestDB, fwNested) |
| + }), |
| + errCase("SetBacking", true, nil, func(r *Registry, h string) error { return r.SetBacking(h, BackingUnit) }), |
| + errCase("SetUnit", true, nil, func(r *Registry, h string) error { return r.SetUnit(h, "shop.service") }), |
| + errCase("SetReplication", true, nil, func(r *Registry, h string) error { return r.SetReplication(h, ReplicationDaily) }), |
| + errCase("SetUpstreams", true, nil, func(r *Registry, h string) error { return r.SetUpstreams(h, "127.0.0.1:9000", "", "") }), |
| + errCase("SetSteering", true, nil, func(r *Registry, h string) error { return r.SetSteering(h, "latency") }), |
| + errCase("SetAssets", true, nil, func(r *Registry, h string) error { return r.SetAssets(h, true, "g1") }), |
| + errCase("SetUpdateSettings", true, nil, func(r *Registry, h string) error { return r.SetUpdateSettings(h, `{"x":1}`) }), |
| + errCase("SetPolicy", true, nil, func(r *Registry, h string) error { |
| + return r.SetPolicy(h, "api.example.com", "small", "2026-12-01T00:00:00Z") |
| + }), |
| + errCase("SetBuildState", true, nil, func(r *Registry, h string) error { return r.SetBuildState(h, `{"state":"built"}`) }), |
| + errCase("SetReplicas", true, nil, func(r *Registry, h string) error { return r.SetReplicas(h, "away") }), |
| + errCase("SetReplica", true, nil, func(r *Registry, h string) error { return r.SetReplica(h, true) }), |
| + errCase("SetHA", true, nil, func(r *Registry, h string) error { return r.SetHA(h) }), |
| + errCase("SetGate", true, nil, func(r *Registry, h string) error { return r.SetGate(h, "hash") }), |
| + errCase("SetRateLimit", true, nil, func(r *Registry, h string) error { return r.SetRateLimit(h, `{"rps":5}`) }), |
| + errCase("SetChannels", true, nil, func(r *Registry, h string) error { return r.SetChannels([]string{h}, "beta") }), |
| + errCase("SetEnvironment", true, nil, func(r *Registry, h string) error { return r.SetEnvironment(h, "staging") }), |
| + errCase("SetTunnel", true, nil, func(r *Registry, h string) error { return r.SetTunnel(h, "t1") }), |
| + errCase("SetPlacement", true, nil, func(r *Registry, h string) error { return r.SetPlacement(h, PlacementTarget("home")) }), |
| + errCase("SetEnvironments", true, nil, func(r *Registry, h string) error { return r.SetEnvironments([]string{h}, "staging") }), |
| + errCase("SetChannelsAndEnvironments", true, nil, func(r *Registry, h string) error { |
| + return r.SetChannelsAndEnvironments([]string{h}, "beta", "staging") |
| + }), |
| + errCase("SetVersions", false, nil, func(r *Registry, h string) error { return r.SetVersions(h, "v2", "v1") }), |
| + errCase("SetGoodBuild", true, nil, func(r *Registry, h string) error { |
| + return r.SetGoodBuild(h, GoodBuild{}, GoodBuild{Version: "v1", Digest: "aa", Demand: "swap"}) |
| + }), |
| + errCase("SetServingVersion", false, nil, func(r *Registry, h string) error { return r.SetServingVersion(h, "v1") }), |
| + errCase("SetHibernate", true, nil, func(r *Registry, h string) error { return r.SetHibernate(h, true) }), |
| + {name: "SetHibernate off", encloses: []string{"SetHibernate"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + host := plainRow(t, r, func(rt *Route) { rt.Hibernate, rt.Replication = true, ReplicationDaily }) |
| + return host, func(bool) (bool, error) { return false, r.SetHibernate(host, false) } |
| + }}, |
| + errCase("SetNextDue", false, nil, func(r *Registry, h string) error { return r.SetNextDue(h, 42) }), |
| + errCase("SetSeed", true, nil, func(r *Registry, h string) error { return r.SetSeed(h, "seed.sql") }), |
| + errCase("SetArgs", false, nil, func(r *Registry, h string) error { return r.SetArgs(h, "--fast") }), |
| + errCase("SetWorkerLimits", false, nil, func(r *Registry, h string) error { return r.SetWorkerLimits(h, 60, 600) }), |
| + errCase("SetProvisioned", true, nil, func(r *Registry, h string) error { return r.SetProvisioned(h, true) }), |
| + errCase("SetStatusNamed", true, nil, func(r *Registry, h string) error { return r.SetStatusNamed(h, true) }), |
| + |
| + // routecas.go: the listed row is read when the pass runs, so on a |
| + // forward host the input itself is a forward row. |
| + {name: "DeleteIfUnchanged", encloses: []string{"DeleteIfUnchanged"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + host := plainRow(t, r, nil) |
| + return host, func(bool) (bool, error) { |
| + return r.DeleteIfUnchanged(mustRoute(t, r, host)) |
| + } |
| + }}, |
| + |
| + // claimhold.go |
| + {name: "SetClaimHold", encloses: []string{"SetClaimHold"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + rt := claimedRow(t, r) |
| + return rt.Host, func(bool) (bool, error) { return false, r.SetClaimHold(ctx, rt.Host, fwOwner, "", "op-1") } |
| + }}, |
| + |
| + // claimrows.go. The observed row is read before the host turns |
| + // forward, so the refusal is the transaction's own check. |
| + {name: "AdoptClaimRoute", encloses: []string{"AdoptClaimRoute"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + host := plainRow(t, r, nil) |
| + observed := mustRoute(t, r, host) |
| + return host, func(bool) (bool, error) { return false, r.AdoptClaimRoute(ctx, observed, fwOwner) } |
| + }}, |
| + {name: "RetireClaimRows", encloses: []string{"RetireClaimRows"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + rt := claimedRow(t, r) |
| + targets := []ClaimRow{{Kind: "route", Host: rt.Host, Ownership: fwOwner}} |
| + return rt.Host, func(forward bool) (bool, error) { |
| + return false, r.RetireClaimRows(ctx, "ret", targets, func([]ClaimRowArchive) error { |
| + if forward { |
| + t.Errorf("RetireClaimRows called archive for a forward row") |
| + } |
| + return nil |
| + }) |
| + } |
| + }}, |
| + |
| + // coldhandover.go: the retired route goes back at a host that a |
| + // forward row now holds. |
| + {name: "RestoreClaimRows", encloses: []string{"RestoreClaimRows"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + rt := claimedRow(t, r) |
| + old, next := ColdRows{Route: rt}, ColdRows{Route: rt} |
| + next.Route.ClaimOwnership = fwNextOwner |
| + targets := []ClaimRow{{Kind: "route", Host: rt.Host, Ownership: fwOwner}} |
| + if err := r.RetireClaimRows(ctx, "ret", targets, func([]ClaimRowArchive) error { return nil }); err != nil { |
| + t.Fatal(err) |
| + } |
| + return rt.Host, func(bool) (bool, error) { return false, r.RestoreClaimRows(ctx, "h1", "ret", old, next) } |
| + }, |
| + forward: func(t *testing.T, r *Registry, host string) { |
| + if err := r.PutForward(validForward(host, "home")); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + |
| + // recoveryhandover.go |
| + {name: "RebindClaimRows", encloses: []string{"RebindClaimRows"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + rt := claimedRow(t, r) |
| + old, next := ColdRows{Route: rt}, ColdRows{Route: rt} |
| + next.Route.ClaimOwnership = fwNextOwner |
| + return rt.Host, func(bool) (bool, error) { return false, r.RebindClaimRows(ctx, old, next) } |
| + }}, |
| + |
| + // importjournal.go |
| + {name: "SwapForImport", encloses: []string{"SwapForImport", "insertRouteTx"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + mustUpsert(t, r, legacyRow()) |
| + stored := mustRoute(t, r, importHost) |
| + j := ImportJournal{Host: importHost, SeedID: importSeedID, RecordKey: importRecordKey, Original: stored, At: 1} |
| + return importHost, func(bool) (bool, error) { return false, r.SwapForImport(j, swapRow()) } |
| + }}, |
| + {name: "CloseImportGate", encloses: []string{"CloseImportGate"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + importFixture(t, r, false) |
| + return importHost, func(bool) (bool, error) { return false, r.CloseImportGate(importHost, importSeedID, 1) } |
| + }}, |
| + {name: "CommitImport", encloses: []string{"CommitImport"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + importFixture(t, r, false) |
| + return importHost, func(bool) (bool, error) { return false, r.CommitImport(importHost, importSeedID) } |
| + }}, |
| + {name: "RestoreImportRoute", encloses: []string{"RestoreImportRoute", "insertRouteTx"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + importFixture(t, r, true) |
| + return importHost, func(bool) (bool, error) { return false, r.RestoreImportRoute(importHost, importSeedID) } |
| + }}, |
| + |
| + // aliassocket.go: the repair moves a flat alias onto its nested |
| + // source. Either row being forward refuses. |
| + {name: "RepointPlatformSocket (alias forward)", encloses: []string{"RepointPlatformSocket"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + repointFixture(t, r) |
| + return fwAlias, func(bool) (bool, error) { return r.RepointPlatformSocket(fwAlias, fwHost) } |
| + }}, |
| + {name: "RepointPlatformSocket (source forward)", encloses: []string{"RepointPlatformSocket"}, refuses: true, |
| + setup: func(t *testing.T, r *Registry) (string, writerCall) { |
| + repointFixture(t, r) |
| + return fwHost, func(bool) (bool, error) { return r.RepointPlatformSocket(fwAlias, fwHost) } |
| + }}, |
| + } |
| + return cases |
| +} |
| + |
| +// boolWriters are the cases whose writer answers with a bool: the positive |
| +// arm must see true. |
| +var boolWriters = map[string]bool{ |
| + "InstallLifetimeIf": true, "SetHoldIf": true, "SetHoldIfSeq": true, "HandHold": true, "ReleaseHold": true, |
| + "ReleaseHoldSeq": true, "DeleteIfHold": true, "DeleteIfHoldWithTimers": true, "DeleteIfUnchanged": true, |
| + "RepointPlatformSocket (alias forward)": true, "RepointPlatformSocket (source forward)": true, |
| +} |
| + |
| +func TestEveryRouteWriterRefusesAForwardRow(t *testing.T) { |
| + for _, c := range routeWriterCases() { |
| + t.Run(c.name, func(t *testing.T) { |
| + // Positive arm: the fixture is live, the writer changes a row. |
| + r := openTestRegistry(t) |
| + t.Cleanup(func() { r.Close() }) |
| + _, call := c.setup(t, r) |
| + before := dumpDB(t, r) |
| + changed, err := call(false) |
| + if err != nil { |
| + t.Fatalf("on an ordinary row: %v", err) |
| + } |
| + if boolWriters[c.name] && !changed { |
| + t.Fatalf("on an ordinary row: reported no change") |
| + } |
| + after := dumpDB(t, r) |
| + if reflect.DeepEqual(before["routes"], after["routes"]) { |
| + t.Fatalf("on an ordinary row the routes table did not change: the fixture does not reach the writer") |
| + } |
| + if c.check != nil { |
| + c.check(t, r) |
| + } |
| + |
| + // Forward arm: the same fixture, its host a forward row. |
| + r = openTestRegistry(t) |
| + t.Cleanup(func() { r.Close() }) |
| + host, call := c.setup(t, r) |
| + if c.forward != nil { |
| + c.forward(t, r, host) |
| + } else { |
| + flipForward(t, r, host) |
| + } |
| + if rt := mustRoute(t, r, host); !rt.IsForward() { |
| + t.Fatalf("fixture: %s is not a forward row", host) |
| + } |
| + before = dumpDB(t, r) |
| + changed, err = call(true) |
| + after = dumpDB(t, r) |
| + if d := dumpDiff(withoutHost(before, c.moves), withoutHost(after, c.moves)); d != "" { |
| + t.Errorf("on a forward row the database changed (err %v):\n %s", err, d) |
| + } |
| + if c.refuses { |
| + if !errors.Is(err, ErrForwardRow) { |
| + t.Errorf("on a forward row: err = %v, want ErrForwardRow", err) |
| + } |
| + } else if err != nil || changed { |
| + t.Errorf("on a forward row: changed %v, err %v; want no change and no error", changed, err) |
| + } |
| + if c.moves != "" { |
| + // The carry's source did move: the write it carries landed. |
| + if got := socketOf(t, r, c.moves); got != fwNested { |
| + t.Errorf("the source %s names %q, want %q", c.moves, got, fwNested) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The forward row's observational columns are the domains health pass's: |
| +// SetDNSStatus and SetCertExpiresAt stamp a forward row (two of the five |
| +// exceptions; PutForward, DeleteForward and SetFleetBoxIf have their own |
| +// tests). |
| +func TestHealthPassStampsAForwardRow(t *testing.T) { |
| + r := openTestRegistry(t) |
| + defer r.Close() |
| + if err := r.PutForward(validForward(fwHost, "home")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := r.SetDNSStatus(fwHost, "pointing", 1234); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := r.SetCertExpiresAt(fwHost, 5678); err != nil { |
| + t.Fatal(err) |
| + } |
| + got := mustRoute(t, r, fwHost) |
| + if got.DNSStatus != "pointing" || got.DNSCheckedAt != 1234 || got.CertExpiresAt != 5678 || !got.InertForward() { |
| + t.Fatalf("after the health pass: %+v", got) |
| + } |
| +} |
| + |
| +// A writer handed a forward row as its input refuses it before anything is |
| +// written, at a host that has no row at all: nothing but PutForward mints |
| +// one. The restore writers are the ones the spec names (§4.2): their input |
| +// is a row from a journal or a handover, not from the routes table. |
| +func TestRestoreWritersRefuseForwardInputsAtAbsentHosts(t *testing.T) { |
| + ctx := context.Background() |
| + fwd := validForward(fwHost, "home") |
| + claimed := fwd |
| + claimed.ClaimOwnership = fwOwner |
| + claimedNext := fwd |
| + claimedNext.ClaimOwnership = fwNextOwner |
| + |
| + // forwardOriginal rewrites the journal's original route as a forward |
| + // row of the same host. |
| + forwardOriginal := func(t *testing.T, r *Registry) { |
| + t.Helper() |
| + orig := validForward(importHost, "home") |
| + b, err := json.Marshal(orig) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := r.sql.Exec(`UPDATE import_journal SET original = ? WHERE host = ?`, string(b), importHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + if j := mustJournal(t, r, importHost); j == nil || !j.Original.IsForward() { |
| + t.Fatalf("fixture: journal original = %+v", j) |
| + } |
| + } |
| + |
| + for _, c := range []struct { |
| + name string |
| + host string |
| + absent bool // the host has no row before or after |
| + setup func(t *testing.T, r *Registry) |
| + call func(t *testing.T, r *Registry) error |
| + }{ |
| + {name: "RestoreClaimRows", host: fwHost, absent: true, |
| + call: func(t *testing.T, r *Registry) error { |
| + return r.RestoreClaimRows(ctx, "h1", "ret", ColdRows{Route: claimed}, ColdRows{Route: claimedNext}) |
| + }}, |
| + {name: "RebindClaimRows", host: fwHost, absent: true, |
| + call: func(t *testing.T, r *Registry) error { |
| + return r.RebindClaimRows(ctx, ColdRows{Route: claimed}, ColdRows{Route: claimedNext}) |
| + }}, |
| + {name: "RestoreImportRoute", host: importHost, absent: true, |
| + setup: func(t *testing.T, r *Registry) { |
| + importFixture(t, r, true) |
| + if _, err := r.sql.Exec(`DELETE FROM routes WHERE host = ?`, importHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + forwardOriginal(t, r) |
| + }, |
| + call: func(t *testing.T, r *Registry) error { return r.RestoreImportRoute(importHost, importSeedID) }}, |
| + // insertRouteTx through its caller: the import's row is there, so |
| + // the rollback would delete it and insert the original. |
| + {name: "insertRouteTx via RestoreImportRoute", host: importHost, |
| + setup: func(t *testing.T, r *Registry) { |
| + importFixture(t, r, true) |
| + forwardOriginal(t, r) |
| + }, |
| + call: func(t *testing.T, r *Registry) error { return r.RestoreImportRoute(importHost, importSeedID) }}, |
| + {name: "Upsert", host: fwHost, absent: true, call: func(t *testing.T, r *Registry) error { return r.Upsert(fwd) }}, |
| + {name: "UpsertUnlessRootfs", host: fwHost, absent: true, call: func(t *testing.T, r *Registry) error { return r.UpsertUnlessRootfs(fwd) }}, |
| + {name: "AdoptClaimRoute", host: fwHost, absent: true, call: func(t *testing.T, r *Registry) error { return r.AdoptClaimRoute(ctx, fwd, fwOwner) }}, |
| + {name: "DeleteIfUnchanged", host: fwHost, absent: true, |
| + call: func(t *testing.T, r *Registry) error { _, err := r.DeleteIfUnchanged(fwd); return err }}, |
| + {name: "SwapForImport", host: importHost, |
| + setup: func(t *testing.T, r *Registry) { mustUpsert(t, r, legacyRow()) }, |
| + call: func(t *testing.T, r *Registry) error { |
| + stored := mustRoute(t, r, importHost) |
| + next := swapRow() |
| + next.Kind = KindForward |
| + return r.SwapForImport(ImportJournal{Host: importHost, SeedID: importSeedID, RecordKey: importRecordKey, Original: stored, At: 1}, next) |
| + }}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + r := openTestRegistry(t) |
| + defer r.Close() |
| + if c.setup != nil { |
| + c.setup(t, r) |
| + } |
| + before := dumpDB(t, r) |
| + err := c.call(t, r) |
| + if !errors.Is(err, ErrForwardRow) { |
| + t.Errorf("err = %v, want ErrForwardRow", err) |
| + } |
| + if d := dumpDiff(before, dumpDB(t, r)); d != "" { |
| + t.Errorf("a refused forward input changed the database:\n %s", d) |
| + } |
| + if c.absent { |
| + if rt, err := r.Get(c.host); err != nil || rt != nil { |
| + t.Errorf("row at %s = %+v, %v; want none", c.host, rt, err) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/registry/importjournal.go b/internal/registry/importjournal.go| index 64f930e06..b2db50bd3 100644 |
| --- a/internal/registry/importjournal.go |
| +++ b/internal/registry/importjournal.go |
| @@ -244,8 +244,12 @@ func getRouteTx(tx txer, host string) (*Route, error) { |
| return &t, nil |
| } |
| -// insertRouteTx inserts t exactly as given (no Upsert defaults). |
| +// insertRouteTx inserts t exactly as given (no Upsert defaults). It never |
| +// inserts a forward row (fleet public routes spec §4.2): ErrForwardRow. |
| func insertRouteTx(tx txer, t Route) error { |
| + if t.IsForward() { |
| + return ErrForwardRow |
| + } |
| _, err := tx.Exec(`INSERT INTO routes (`+routeCols+`) VALUES (`+placeholders(routeColCount)+`)`, routeArgs(t)...) |
| return err |
| } |
| @@ -288,7 +292,15 @@ func seedColumnID(col string) string { |
| // spec §3.4), not held by an operation, not itself gated, and unchanged by |
| // its JSON round trip. j.EnvBefore is stored as given: one of the EnvBefore |
| // values, or "" when the caller could not say. |
| +// |
| +// An import never replaces or becomes a forward row (fleet public routes spec |
| +// §4.2): next or the original of kind forward is ErrForwardRow before |
| +// anything, and a forward row at the host is ErrForwardRow before the journal |
| +// row is written. |
| func (r *Registry) SwapForImport(j ImportJournal, next Route) error { |
| + if next.IsForward() || j.Original.IsForward() { |
| + return ErrForwardRow |
| + } |
| if j.Host == "" || j.SeedID == "" || j.RecordKey == "" || j.Original.Host != j.Host || !IsImportRow(normalizeRoute(next), j) { |
| return fmt.Errorf("%w: the swap for %s is not well formed", ErrImportJournal, j.Host) |
| } |
| @@ -314,6 +326,9 @@ func (r *Registry) SwapForImport(j ImportJournal, next Route) error { |
| } else if cur != nil { |
| return fmt.Errorf("%w: %s already has a journal row for seed %s", ErrImportJournal, j.Host, cur.SeedID) |
| } |
| + if err := forwardAt(tx, j.Host); err != nil { |
| + return err |
| + } |
| stored, err := getRouteTx(tx, j.Host) |
| if err != nil { |
| return err |
| @@ -321,7 +336,7 @@ func (r *Registry) SwapForImport(j ImportJournal, next Route) error { |
| if stored == nil || !reflect.DeepEqual(*stored, j.Original) { |
| return fmt.Errorf("%w: the route at %s changed since it was checked", ErrImportJournal, j.Host) |
| } |
| - if _, err := tx.Exec(`DELETE FROM routes WHERE host = ?`, j.Host); err != nil { |
| + if _, err := tx.Exec(`DELETE FROM routes WHERE host = ? AND kind <> 'forward'`, j.Host); err != nil { |
| return err |
| } |
| if err := insertRouteTx(tx, normalizeRoute(next)); err != nil { |
| @@ -352,12 +367,16 @@ func journalFor(tx txer, host, seedID string, states ...string) (*ImportJournal, |
| } |
| // importRowTx is host's row when it is j's import row, nil when the host |
| -// has no row, and ErrImportJournal when the row there is anyone else's. |
| +// has no row, ErrForwardRow when it is a forward row (fleet public routes |
| +// spec §4.2), and ErrImportJournal when the row there is anyone else's. |
| func importRowTx(tx txer, j *ImportJournal) (*Route, error) { |
| cur, err := getRouteTx(tx, j.Host) |
| if err != nil { |
| return nil, err |
| } |
| + if cur != nil && cur.IsForward() { |
| + return nil, ErrForwardRow |
| + } |
| if cur != nil && !IsImportRow(*cur, *j) { |
| return nil, fmt.Errorf("%w: the route at %s is not import %s's", ErrImportJournal, j.Host, j.SeedID) |
| } |
| @@ -388,7 +407,7 @@ func (r *Registry) CloseImportGate(host, seedID string, fenceGen uint64) error { |
| return err |
| } |
| } |
| - _, err = tx.Exec(`UPDATE routes SET import_gate = ? WHERE host = ?`, ImportGateClosed, host) |
| + _, err = tx.Exec(`UPDATE routes SET import_gate = ? WHERE host = ? AND kind <> 'forward'`, ImportGateClosed, host) |
| return err |
| }) |
| } |
| @@ -409,12 +428,17 @@ func (r *Registry) RestoreImportRoute(host, seedID string) error { |
| if err != nil { |
| return err |
| } |
| + // The original goes back exactly as stored, and a forward row is |
| + // never put back (fleet public routes spec §4.2). |
| + if j.Original.IsForward() { |
| + return ErrForwardRow |
| + } |
| cur, err := importRowTx(tx, j) |
| if err != nil { |
| return err |
| } |
| if cur != nil { |
| - if _, err := tx.Exec(`DELETE FROM routes WHERE host = ?`, host); err != nil { |
| + if _, err := tx.Exec(`DELETE FROM routes WHERE host = ? AND kind <> 'forward'`, host); err != nil { |
| return err |
| } |
| if err := insertRouteTx(tx, j.Original); err != nil { |
| @@ -427,13 +451,17 @@ func (r *Registry) RestoreImportRoute(host, seedID string) error { |
| } |
| // CommitImport clears the gate and retires the journal in one transaction |
| -// (spec §5.4 "Commit"). |
| +// (spec §5.4 "Commit"). A forward row at the host is ErrForwardRow, and the |
| +// journal stays (fleet public routes spec §4.2). |
| func (r *Registry) CommitImport(host, seedID string) error { |
| return r.inTx(func(tx txer) error { |
| if _, err := journalFor(tx, host, seedID, JournalSwapped); err != nil { |
| return err |
| } |
| - if _, err := tx.Exec(`UPDATE routes SET import_gate = '' WHERE host = ?`, host); err != nil { |
| + if err := forwardAt(tx, host); err != nil { |
| + return err |
| + } |
| + if _, err := tx.Exec(`UPDATE routes SET import_gate = '' WHERE host = ? AND kind <> 'forward'`, host); err != nil { |
| return err |
| } |
| _, err := tx.Exec(`DELETE FROM import_journal WHERE host = ?`, host) |
diff --git a/internal/registry/recoveryhandover.go b/internal/registry/recoveryhandover.go| index 2acfb3738..277c0e691 100644 |
| --- a/internal/registry/recoveryhandover.go |
| +++ b/internal/registry/recoveryhandover.go |
| @@ -12,19 +12,34 @@ import ( |
| // RebindClaimRows transfers an exact stopped installation's registry rows. |
| // The caller holds hostguard and proves the source cut and successor admission. |
| // A transaction preserves row contents and refuses any concurrent replacement. |
| +// A forward row is never rebound (fleet public routes spec §4.2): old or next |
| +// of kind forward is ErrForwardRow before anything, and a forward row at the |
| +// host is ErrForwardRow inside the transaction before its first write, |
| +// recovery_rows' creation included. |
| func (r *Registry) RebindClaimRows(ctx context.Context, old, next ColdRows) error { |
| + if old.Route.IsForward() || next.Route.IsForward() { |
| + return ErrForwardRow |
| + } |
| if r.remote != nil { |
| _, err := r.remote.call(ctx, remoteRequest{Method: "RebindClaimRows", Old: old, NextValue: next}, nil) |
| return err |
| } |
| - if _, err := r.sql.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS recovery_rows(id TEXT PRIMARY KEY,body BLOB NOT NULL)`); err != nil { |
| - return err |
| - } |
| tx, err := r.beginClaimTransaction(ctx, true) |
| if err != nil { |
| return err |
| } |
| defer tx.Rollback() |
| + if err := forwardAt(tx, old.Route.Host); err != nil { |
| + return err |
| + } |
| + if err := forwardAt(tx, next.Route.Host); err != nil { |
| + return err |
| + } |
| + // Created inside the transaction, after the forward check, so a refusal |
| + // leaves no trace. |
| + if _, err := tx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS recovery_rows(id TEXT PRIMARY KEY,body BLOB NOT NULL)`); err != nil { |
| + return err |
| + } |
| id := fmt.Sprintf("%s/%s/%d", next.Route.Host, next.Route.ClaimIncarnation, next.Route.ClaimStamp) |
| var saved []byte |
| err = tx.QueryRowContext(ctx, `SELECT body FROM recovery_rows WHERE id=?`, id).Scan(&saved) |
| @@ -110,7 +125,7 @@ func (r *Registry) RebindClaimRows(ctx context.Context, old, next ColdRows) erro |
| return nil |
| } |
| o := next.Route.ClaimOwnership |
| - if _, err = tx.ExecContext(ctx, `UPDATE routes SET claim_incarnation=?,claim_stamp=?,claim_owner=?,claim_row_id=? WHERE host=?`, o.ClaimIncarnation, o.ClaimStamp, o.ClaimOwner, o.ClaimRowID, next.Route.Host); err != nil { |
| + if _, err = tx.ExecContext(ctx, `UPDATE routes SET claim_incarnation=?,claim_stamp=?,claim_owner=?,claim_row_id=? WHERE host=? AND kind <> 'forward'`, o.ClaimIncarnation, o.ClaimStamp, o.ClaimOwner, o.ClaimRowID, next.Route.Host); err != nil { |
| return err |
| } |
| for _, t := range next.Timers { |
diff --git a/internal/registry/registry.go b/internal/registry/registry.go| index 443045b59..3c0cdda57 100644 |
| --- a/internal/registry/registry.go |
| +++ b/internal/registry/registry.go |
| @@ -1205,15 +1205,23 @@ func (r *Registry) Get(host string) (*Route, error) { |
| } |
| // Delete removes a route by host (data-safe: it stops routing the host but |
| -// never touches its DB). |
| +// never touches its DB). A forward row is the forward phase's (DeleteForward): |
| +// it is not deleted, and the answer is ErrForwardRow. No row at all is no |
| +// error, as before. |
| func (r *Registry) Delete(host string) error { |
| if r.remote != nil { |
| _, err := r.remote.call(nil, remoteRequest{Method: "Delete", Host: host}, nil) |
| return err |
| } |
| - _, err := r.sql.Exec(`DELETE FROM routes WHERE host = ?`, host) |
| - return err |
| + res, err := r.sql.Exec(`DELETE FROM routes WHERE host = ? AND kind <> 'forward'`, host) |
| + if err != nil { |
| + return err |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 0 { |
| + return err |
| + } |
| + return forwardAt(r.sql, host) |
| } |
| // Upsert inserts or updates a route by host. On conflict it NEVER changes |
| @@ -1418,7 +1426,14 @@ func effectiveAccountSQL(col string) string { |
| var tenantChangedSQL = effectiveAccountSQL("routes.account") + ` != ` + effectiveAccountSQL("excluded.account") + |
| ` OR routes.app != excluded.app` |
| +// A forward row is never written here (fleet public routes spec §4.2): an |
| +// incoming row of kind forward, and a stored forward row at the host, are |
| +// both refused with ErrForwardRow and nothing is written. PutForward is the |
| +// forward row's only writer. |
| func (r *Registry) Upsert(t Route) error { |
| + if t.IsForward() { |
| + return ErrForwardRow |
| + } |
| if r.remote != nil { |
| _, err := r.remote.call(nil, remoteRequest{Method: "Upsert", TValue: t}, nil) |
| return err |
| @@ -1434,6 +1449,9 @@ func (r *Registry) Upsert(t Route) error { |
| // missing host is inserted as Upsert inserts it. Ordinary Upsert, and its |
| // re-tenancy rule, is unchanged. |
| func (r *Registry) UpsertUnlessRootfs(t Route) error { |
| + if t.IsForward() { |
| + return ErrForwardRow |
| + } |
| if r.remote != nil { |
| _, err := r.remote.call(nil, remoteRequest{Method: "UpsertUnlessRootfs", TValue: t}, nil) |
| return err |
| @@ -1490,7 +1508,12 @@ func (r *Registry) upsert(t Route, guard string) error { |
| // upsertRoute is Upsert's statement, on the database or inside a |
| // transaction. guard, when not "", is ANDed onto the conflict arm's WHERE. |
| +// The conflict arm never matches a stored forward row; a conflict it |
| +// refuses for that reason answers ErrForwardRow, any other ErrClaimOwnership. |
| func upsertRoute(db txer, t Route, guard string) error { |
| + if t.IsForward() { |
| + return ErrForwardRow |
| + } |
| res, err := db.Exec(` |
| INSERT INTO routes (`+routeCols+`) |
| VALUES (`+placeholders(routeColCount)+`) |
| @@ -1545,13 +1568,17 @@ ON CONFLICT(host) DO UPDATE SET |
| WHEN excluded.policy_expires_at = '' THEN routes.policy_expires_at ELSE excluded.policy_expires_at END, |
| ha=MAX(routes.ha, excluded.ha) |
| WHERE routes.claim_incarnation=excluded.claim_incarnation AND routes.claim_stamp=excluded.claim_stamp |
| -AND routes.claim_owner=excluded.claim_owner AND routes.claim_row_id=excluded.claim_row_id`+guard, |
| +AND routes.claim_owner=excluded.claim_owner AND routes.claim_row_id=excluded.claim_row_id |
| +AND routes.kind <> 'forward'`+guard, |
| routeArgs(normalizeRoute(t))...) |
| if err != nil { |
| return err |
| } |
| n, err := res.RowsAffected() |
| if err == nil && n != 1 { |
| + if err := forwardAt(db, t.Host); err != nil { |
| + return err |
| + } |
| return ErrClaimOwnership |
| } |
| return err |
| @@ -1619,7 +1646,7 @@ func (r *Registry) SetSeedSource(host, v string) error { |
| if r.remote != nil { |
| return errRemoteMethod |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET seed_source = ? WHERE host = ?`, v, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET seed_source = ? WHERE host = ? AND kind <> 'forward'`, v, host) |
| if err != nil { |
| return err |
| } |
| @@ -1628,7 +1655,7 @@ func (r *Registry) SetSeedSource(host, v string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -1656,7 +1683,7 @@ func (r *Registry) SetHold(host, status, op string) error { |
| if !IsHold(status) || op == "" { |
| return fmt.Errorf("registry: %q with op %q is not a hold", status, op) |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET status = ?, hold_op = ? WHERE host = ?`, status, op, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET status = ?, hold_op = ? WHERE host = ? AND kind <> 'forward'`, status, op, host) |
| if err != nil { |
| return err |
| } |
| @@ -1665,7 +1692,7 @@ func (r *Registry) SetHold(host, status, op string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -1694,7 +1721,7 @@ func (r *Registry) SetHoldIf(host, status, op, expectOp string) (bool, error) { |
| if expectOp != "" && expectOp != op { |
| return false, fmt.Errorf("registry: hold %s by %q expecting %q: another op's hold is released by that op, not taken over", host, op, expectOp) |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET status = ?, hold_op = ? WHERE host = ? AND hold_op = ?`, status, op, host, expectOp) |
| + res, err := r.sql.Exec(`UPDATE routes SET status = ?, hold_op = ? WHERE host = ? AND kind <> 'forward' AND hold_op = ?`, status, op, host, expectOp) |
| if err != nil { |
| return false, err |
| } |
| @@ -1723,7 +1750,7 @@ func (r *Registry) HandHold(host, status, toOp, fromOp string) (bool, error) { |
| if !IsHold(status) || toOp == "" || fromOp == "" || toOp == fromOp { |
| return false, fmt.Errorf("registry: hand %s from %q to %q as %q is not a hand-over between two ops' holds", host, fromOp, toOp, status) |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET status = ?, hold_op = ? WHERE host = ? AND hold_op = ?`, status, toOp, host, fromOp) |
| + res, err := r.sql.Exec(`UPDATE routes SET status = ?, hold_op = ? WHERE host = ? AND kind <> 'forward' AND hold_op = ?`, status, toOp, host, fromOp) |
| if err != nil { |
| return false, err |
| } |
| @@ -1743,7 +1770,7 @@ func (r *Registry) ReleaseHold(host, op string) (bool, error) { |
| if op == "" { |
| return false, nil |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET status = 'ready', hold_op = '' WHERE host = ? AND hold_op = ?`, host, op) |
| + res, err := r.sql.Exec(`UPDATE routes SET status = 'ready', hold_op = '' WHERE host = ? AND kind <> 'forward' AND hold_op = ?`, host, op) |
| if err != nil { |
| return false, err |
| } |
| @@ -1763,7 +1790,7 @@ func (r *Registry) DeleteIfHold(host, op string) (bool, error) { |
| if op == "" { |
| return false, nil |
| } |
| - res, err := r.sql.Exec(`DELETE FROM routes WHERE host = ? AND hold_op = ?`, host, op) |
| + res, err := r.sql.Exec(`DELETE FROM routes WHERE host = ? AND kind <> 'forward' AND hold_op = ?`, host, op) |
| if err != nil { |
| return false, err |
| } |
| @@ -1790,7 +1817,7 @@ func (r *Registry) DeleteIfHoldWithTimers(host, op string) (bool, error) { |
| return false, err |
| } |
| defer tx.Rollback() |
| - res, err := tx.Exec(`DELETE FROM routes WHERE host = ? AND hold_op = ?`, host, op) |
| + res, err := tx.Exec(`DELETE FROM routes WHERE host = ? AND kind <> 'forward' AND hold_op = ?`, host, op) |
| if err != nil { |
| return false, err |
| } |
| @@ -1837,7 +1864,7 @@ func (r *Registry) SetHoldIfSeq(host, status, op, expectOp string, pair Pair) (b |
| if expectOp != "" && expectOp != op { |
| return false, fmt.Errorf("registry: hold %s by %q expecting %q: another op's hold is released by that op, not taken over", host, op, expectOp) |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET status = ?, hold_op = ?, incarnation = ?, serving_seq = ? WHERE host = ? AND hold_op = ? AND incarnation <= ?`, |
| + res, err := r.sql.Exec(`UPDATE routes SET status = ?, hold_op = ?, incarnation = ?, serving_seq = ? WHERE host = ? AND kind <> 'forward' AND hold_op = ? AND incarnation <= ?`, |
| status, op, pair.Incarnation, pair.ServingSeq, host, expectOp, pair.Incarnation) |
| if err != nil { |
| return false, err |
| @@ -1862,7 +1889,7 @@ func (r *Registry) ReleaseHoldSeq(host, op string, pair Pair) (bool, error) { |
| if op == "" { |
| return false, nil |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET status = 'ready', hold_op = '', incarnation = ?, serving_seq = ? WHERE host = ? AND hold_op = ? AND (incarnation = ? OR incarnation = 0)`, |
| + res, err := r.sql.Exec(`UPDATE routes SET status = 'ready', hold_op = '', incarnation = ?, serving_seq = ? WHERE host = ? AND kind <> 'forward' AND hold_op = ? AND (incarnation = ? OR incarnation = 0)`, |
| pair.Incarnation, pair.ServingSeq, host, op, pair.Incarnation) |
| if err != nil { |
| return false, err |
| @@ -1883,7 +1910,7 @@ func (r *Registry) InstallLifetimeIf(host string, expect, next Pair) (bool, erro |
| return out.Changed, err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET incarnation = ?, serving_seq = ? WHERE host = ? AND incarnation = ? AND serving_seq = ? AND hold_op = ''`, |
| + res, err := r.sql.Exec(`UPDATE routes SET incarnation = ?, serving_seq = ? WHERE host = ? AND kind <> 'forward' AND incarnation = ? AND serving_seq = ? AND hold_op = ''`, |
| next.Incarnation, next.ServingSeq, host, expect.Incarnation, expect.ServingSeq) |
| if err != nil { |
| return false, err |
| @@ -1981,7 +2008,7 @@ func (r *Registry) SetAccount(host, account string) error { |
| return err |
| } |
| - _, err := r.sql.Exec(`UPDATE routes SET account = ? WHERE host = ?`, account, host) |
| + _, err := r.sql.Exec(`UPDATE routes SET account = ? WHERE host = ? AND kind <> 'forward'`, account, host) |
| return err |
| } |
| @@ -1997,7 +2024,7 @@ func (r *Registry) SetChannel(host, channel string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET channel = ? WHERE host = ?`, channel, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET channel = ? WHERE host = ? AND kind <> 'forward'`, channel, host) |
| if err != nil { |
| return err |
| } |
| @@ -2006,7 +2033,7 @@ func (r *Registry) SetChannel(host, channel string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2023,7 +2050,7 @@ func (r *Registry) SetStatus(host, status string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET status = ? WHERE host = ?`, status, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET status = ? WHERE host = ? AND kind <> 'forward'`, status, host) |
| if err != nil { |
| return err |
| } |
| @@ -2032,7 +2059,7 @@ func (r *Registry) SetStatus(host, status string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2064,7 +2091,7 @@ func (r *Registry) SetCaps(host, from, to string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET caps = ? WHERE host = ? AND caps = ?`, to, host, from) |
| + res, err := r.sql.Exec(`UPDATE routes SET caps = ? WHERE host = ? AND kind <> 'forward' AND caps = ?`, to, host, from) |
| if err != nil { |
| return err |
| } |
| @@ -2073,6 +2100,9 @@ func (r *Registry) SetCaps(host, from, to string) error { |
| return err |
| } |
| if n == 0 { |
| + if err := forwardAt(r.sql, host); err != nil { |
| + return err |
| + } |
| var cur string |
| serr := r.sql.QueryRow(`SELECT caps FROM routes WHERE host = ?`, host).Scan(&cur) |
| if serr == sql.ErrNoRows { |
| @@ -2120,7 +2150,7 @@ func (r *Registry) SetDBPath(host, from, to string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET db_path = ? WHERE host = ? AND db_path = ?`, to, host, from) |
| + res, err := r.sql.Exec(`UPDATE routes SET db_path = ? WHERE host = ? AND kind <> 'forward' AND db_path = ?`, to, host, from) |
| if err != nil { |
| return err |
| } |
| @@ -2129,6 +2159,9 @@ func (r *Registry) SetDBPath(host, from, to string) error { |
| return err |
| } |
| if n == 0 { |
| + if err := forwardAt(r.sql, host); err != nil { |
| + return err |
| + } |
| var cur string |
| serr := r.sql.QueryRow(`SELECT db_path FROM routes WHERE host = ?`, host).Scan(&cur) |
| if serr == sql.ErrNoRows { |
| @@ -2164,7 +2197,7 @@ func (r *Registry) SetInstancePaths(host, fromDB, fromSock, toDB, toSock string) |
| } |
| return r.inImmediateTx(func(tx txer) error { |
| - res, err := tx.Exec(`UPDATE routes SET db_path = ?, socket = ? WHERE host = ? AND db_path = ? AND socket = ?`, toDB, toSock, host, fromDB, fromSock) |
| + res, err := tx.Exec(`UPDATE routes SET db_path = ?, socket = ? WHERE host = ? AND kind <> 'forward' AND db_path = ? AND socket = ?`, toDB, toSock, host, fromDB, fromSock) |
| if err != nil { |
| return err |
| } |
| @@ -2173,6 +2206,9 @@ func (r *Registry) SetInstancePaths(host, fromDB, fromSock, toDB, toSock string) |
| return err |
| } |
| if n == 0 { |
| + if err := forwardAt(tx, host); err != nil { |
| + return err |
| + } |
| var curDB, curSock string |
| serr := tx.QueryRow(`SELECT db_path, socket FROM routes WHERE host = ?`, host).Scan(&curDB, &curSock) |
| if serr == sql.ErrNoRows { |
| @@ -2215,7 +2251,7 @@ func (r *Registry) SetBacking(host, backing string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET backing = ? WHERE host = ?`, backing, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET backing = ? WHERE host = ? AND kind <> 'forward'`, backing, host) |
| if err != nil { |
| return err |
| } |
| @@ -2224,7 +2260,7 @@ func (r *Registry) SetBacking(host, backing string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2263,7 +2299,7 @@ func (r *Registry) SetUnit(host, unit string) error { |
| if !ValidUnitName(unit) { |
| return fmt.Errorf("unit %q: want a systemd service unit name (e.g. console.service) or \"\" to clear", unit) |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET unit = ? WHERE host = ?`, unit, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET unit = ? WHERE host = ? AND kind <> 'forward'`, unit, host) |
| if err != nil { |
| return err |
| } |
| @@ -2272,7 +2308,7 @@ func (r *Registry) SetUnit(host, unit string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2301,7 +2337,7 @@ func (r *Registry) SetReplication(host, class string) error { |
| if !ValidReplication(class) { |
| return fmt.Errorf("replication %q: want one of %s, or \"\" for the default", class, strings.Join(ReplicationClasses(), ", ")) |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET replication = ? WHERE host = ?`, class, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET replication = ? WHERE host = ? AND kind <> 'forward'`, class, host) |
| if err != nil { |
| return err |
| } |
| @@ -2310,7 +2346,7 @@ func (r *Registry) SetReplication(host, class string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2354,7 +2390,7 @@ func (r *Registry) SetUpstreams(host, addr, addrs, health string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET addr = ?, addrs = ?, health = ? WHERE host = ?`, |
| + res, err := r.sql.Exec(`UPDATE routes SET addr = ?, addrs = ?, health = ? WHERE host = ? AND kind <> 'forward'`, |
| addr, addrs, health, host) |
| if err != nil { |
| return err |
| @@ -2364,7 +2400,7 @@ func (r *Registry) SetUpstreams(host, addr, addrs, health string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2392,7 +2428,7 @@ func (r *Registry) SetSteering(host, steering string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET steering = ? WHERE host = ?`, steering, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET steering = ? WHERE host = ? AND kind <> 'forward'`, steering, host) |
| if err != nil { |
| return err |
| } |
| @@ -2401,7 +2437,7 @@ func (r *Registry) SetSteering(host, steering string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2418,7 +2454,7 @@ func (r *Registry) SetAssets(host string, off bool, gen string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET assets_off = ?, asset_gen = ? WHERE host = ?`, b2iDB(off), gen, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET assets_off = ?, asset_gen = ? WHERE host = ? AND kind <> 'forward'`, b2iDB(off), gen, host) |
| if err != nil { |
| return err |
| } |
| @@ -2427,7 +2463,7 @@ func (r *Registry) SetAssets(host string, off bool, gen string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2442,7 +2478,7 @@ func (r *Registry) SetUpdateSettings(host, col string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET update_settings = ? WHERE host = ?`, col, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET update_settings = ? WHERE host = ? AND kind <> 'forward'`, col, host) |
| if err != nil { |
| return err |
| } |
| @@ -2451,7 +2487,7 @@ func (r *Registry) SetUpdateSettings(host, col string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2467,7 +2503,7 @@ func (r *Registry) SetPolicy(host, egressAllow, size, expiresAt string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET egress_allow = ?, size = ?, policy_expires_at = ? WHERE host = ?`, |
| + res, err := r.sql.Exec(`UPDATE routes SET egress_allow = ?, size = ?, policy_expires_at = ? WHERE host = ? AND kind <> 'forward'`, |
| egressAllow, size, expiresAt, host) |
| if err != nil { |
| return err |
| @@ -2477,7 +2513,7 @@ func (r *Registry) SetPolicy(host, egressAllow, size, expiresAt string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2491,7 +2527,7 @@ func (r *Registry) SetBuildState(host, col string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET build_state = ? WHERE host = ?`, col, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET build_state = ? WHERE host = ? AND kind <> 'forward'`, col, host) |
| if err != nil { |
| return err |
| } |
| @@ -2500,7 +2536,7 @@ func (r *Registry) SetBuildState(host, col string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2521,7 +2557,7 @@ func (r *Registry) SetReplicas(host, replicas string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET replicas = ? WHERE host = ?`, replicas, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET replicas = ? WHERE host = ? AND kind <> 'forward'`, replicas, host) |
| if err != nil { |
| return err |
| } |
| @@ -2530,7 +2566,7 @@ func (r *Registry) SetReplicas(host, replicas string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2549,7 +2585,7 @@ func (r *Registry) SetReplica(host string, replica bool) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET replica = ? WHERE host = ?`, b2iDB(replica), host) |
| + res, err := r.sql.Exec(`UPDATE routes SET replica = ? WHERE host = ? AND kind <> 'forward'`, b2iDB(replica), host) |
| if err != nil { |
| return err |
| } |
| @@ -2558,7 +2594,7 @@ func (r *Registry) SetReplica(host string, replica bool) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2571,7 +2607,7 @@ func (r *Registry) SetHA(host string) error { |
| _, err := r.remote.call(nil, remoteRequest{Method: "SetHA", Host: host}, nil) |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET ha = 1 WHERE host = ?`, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET ha = 1 WHERE host = ? AND kind <> 'forward'`, host) |
| if err != nil { |
| return err |
| } |
| @@ -2580,7 +2616,7 @@ func (r *Registry) SetHA(host string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2604,7 +2640,7 @@ func (r *Registry) SetGate(host, hash string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET gate = ? WHERE host = ?`, hash, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET gate = ? WHERE host = ? AND kind <> 'forward'`, hash, host) |
| if err != nil { |
| return err |
| } |
| @@ -2613,7 +2649,7 @@ func (r *Registry) SetGate(host, hash string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2629,7 +2665,7 @@ func (r *Registry) SetRateLimit(host, canonical string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET rate_limit = ? WHERE host = ?`, canonical, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET rate_limit = ? WHERE host = ? AND kind <> 'forward'`, canonical, host) |
| if err != nil { |
| return err |
| } |
| @@ -2638,7 +2674,7 @@ func (r *Registry) SetRateLimit(host, canonical string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2666,7 +2702,7 @@ func (r *Registry) SetChannels(hosts []string, channel string) error { |
| if err != nil { |
| return err |
| } |
| - stmt, err := tx.Prepare(`UPDATE routes SET channel = ? WHERE host = ?`) |
| + stmt, err := tx.Prepare(`UPDATE routes SET channel = ? WHERE host = ? AND kind <> 'forward'`) |
| if err != nil { |
| tx.Rollback() |
| return err |
| @@ -2687,7 +2723,7 @@ func (r *Registry) SetChannels(hosts []string, channel string) error { |
| if n == 0 { |
| stmt.Close() |
| tx.Rollback() |
| - return fmt.Errorf("no route for host %q", h) |
| + return noRoute(r.sql, h) |
| } |
| } |
| stmt.Close() |
| @@ -2707,7 +2743,7 @@ func (r *Registry) SetEnvironment(host, env string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET environment = ? WHERE host = ?`, env, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET environment = ? WHERE host = ? AND kind <> 'forward'`, env, host) |
| if err != nil { |
| return err |
| } |
| @@ -2716,7 +2752,7 @@ func (r *Registry) SetEnvironment(host, env string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2734,7 +2770,7 @@ func (r *Registry) SetTunnel(host, tunnel string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET tunnel = ? WHERE host = ?`, tunnel, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET tunnel = ? WHERE host = ? AND kind <> 'forward'`, tunnel, host) |
| if err != nil { |
| return err |
| } |
| @@ -2743,7 +2779,7 @@ func (r *Registry) SetTunnel(host, tunnel string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -2775,7 +2811,7 @@ func (r *Registry) SetPlacement(host, target string) error { |
| // A row with a runtime never moves (rootfs apps Plan 3 Task 13): the |
| // statement itself leaves it as it is unless the target is already its |
| // region, so the refusal holds whoever else writes the row meanwhile. |
| - res, err := r.sql.Exec(`UPDATE routes SET region = ? WHERE host = ? AND (runtime = '' OR region = ?)`, target, host, target) |
| + res, err := r.sql.Exec(`UPDATE routes SET region = ? WHERE host = ? AND kind <> 'forward' AND (runtime = '' OR region = ?)`, target, host, target) |
| if err != nil { |
| return err |
| } |
| @@ -2788,6 +2824,9 @@ func (r *Registry) SetPlacement(host, target string) error { |
| if err != nil { |
| return err |
| } |
| + if rt != nil && rt.IsForward() { |
| + return ErrForwardRow |
| + } |
| if rt != nil && rt.Runtime != "" { |
| return ErrRuntimePlacement |
| } |
| @@ -2815,7 +2854,7 @@ func (r *Registry) SetEnvironments(hosts []string, env string) error { |
| if err != nil { |
| return err |
| } |
| - stmt, err := tx.Prepare(`UPDATE routes SET environment = ? WHERE host = ?`) |
| + stmt, err := tx.Prepare(`UPDATE routes SET environment = ? WHERE host = ? AND kind <> 'forward'`) |
| if err != nil { |
| tx.Rollback() |
| return err |
| @@ -2836,7 +2875,7 @@ func (r *Registry) SetEnvironments(hosts []string, env string) error { |
| if n == 0 { |
| stmt.Close() |
| tx.Rollback() |
| - return fmt.Errorf("no route for host %q", h) |
| + return noRoute(r.sql, h) |
| } |
| } |
| stmt.Close() |
| @@ -2864,7 +2903,7 @@ func (r *Registry) SetChannelsAndEnvironments(hosts []string, channel, env strin |
| if err != nil { |
| return err |
| } |
| - stmt, err := tx.Prepare(`UPDATE routes SET channel = ?, environment = ? WHERE host = ?`) |
| + stmt, err := tx.Prepare(`UPDATE routes SET channel = ?, environment = ? WHERE host = ? AND kind <> 'forward'`) |
| if err != nil { |
| tx.Rollback() |
| return err |
| @@ -2885,7 +2924,7 @@ func (r *Registry) SetChannelsAndEnvironments(hosts []string, channel, env strin |
| if n == 0 { |
| stmt.Close() |
| tx.Rollback() |
| - return fmt.Errorf("no route for host %q", h) |
| + return noRoute(r.sql, h) |
| } |
| } |
| stmt.Close() |
| @@ -2925,7 +2964,7 @@ func (r *Registry) SetVersions(host, ver, prev string) error { |
| return err |
| } |
| - _, err := r.sql.Exec(`UPDATE routes SET version = ?, prev_version = ? WHERE host = ?`, ver, prev, host) |
| + _, err := r.sql.Exec(`UPDATE routes SET version = ?, prev_version = ? WHERE host = ? AND kind <> 'forward'`, ver, prev, host) |
| return err |
| } |
| @@ -2952,7 +2991,7 @@ func (r *Registry) SetGoodBuild(host string, expect, next GoodBuild) error { |
| } |
| res, err := r.sql.Exec(`UPDATE routes SET good_version = ?, good_digest = ?, good_demand = ? |
| -WHERE host = ? AND good_version = ? AND good_digest = ? AND good_demand = ?`, |
| +WHERE host = ? AND kind <> 'forward' AND good_version = ? AND good_digest = ? AND good_demand = ?`, |
| next.Version, next.Digest, next.Demand, host, expect.Version, expect.Digest, expect.Demand) |
| if err != nil { |
| return err |
| @@ -2964,6 +3003,9 @@ WHERE host = ? AND good_version = ? AND good_digest = ? AND good_demand = ?`, |
| if n == 1 { |
| return nil |
| } |
| + if err := forwardAt(r.sql, host); err != nil { |
| + return err |
| + } |
| var cur GoodBuild |
| serr := r.sql.QueryRow(`SELECT good_version, good_digest, good_demand FROM routes WHERE host = ?`, host). |
| Scan(&cur.Version, &cur.Digest, &cur.Demand) |
| @@ -2984,7 +3026,7 @@ func (r *Registry) SetServingVersion(host, ver string) error { |
| return err |
| } |
| - _, err := r.sql.Exec(`UPDATE routes SET serving_version = ? WHERE host = ?`, ver, host) |
| + _, err := r.sql.Exec(`UPDATE routes SET serving_version = ? WHERE host = ? AND kind <> 'forward'`, ver, host) |
| return err |
| } |
| @@ -3028,9 +3070,9 @@ func (r *Registry) SetHibernate(host string, on bool) error { |
| var res sql.Result |
| var err error |
| if !on { |
| - res, err = r.sql.Exec(`UPDATE routes SET hibernate = 0, replication = '' WHERE host = ? AND runtime = ''`, host) |
| + res, err = r.sql.Exec(`UPDATE routes SET hibernate = 0, replication = '' WHERE host = ? AND kind <> 'forward' AND runtime = ''`, host) |
| } else { |
| - res, err = r.sql.Exec(`UPDATE routes SET hibernate = 1 WHERE host = ? AND runtime = ''`, host) |
| + res, err = r.sql.Exec(`UPDATE routes SET hibernate = 1 WHERE host = ? AND kind <> 'forward' AND runtime = ''`, host) |
| } |
| if err != nil { |
| return err |
| @@ -3043,6 +3085,9 @@ func (r *Registry) SetHibernate(host string, on bool) error { |
| if err != nil { |
| return err |
| } |
| + if rt != nil && rt.IsForward() { |
| + return ErrForwardRow |
| + } |
| if rt != nil && rt.Runtime != "" { |
| return ErrRuntimeFixed |
| } |
| @@ -3057,7 +3102,7 @@ func (r *Registry) SetNextDue(host string, due int64) error { |
| return err |
| } |
| - _, err := r.sql.Exec(`UPDATE routes SET next_due = ? WHERE host = ?`, due, host) |
| + _, err := r.sql.Exec(`UPDATE routes SET next_due = ? WHERE host = ? AND kind <> 'forward'`, due, host) |
| return err |
| } |
| @@ -3086,7 +3131,7 @@ func (r *Registry) ClearNextDueIf(host string, due int64) error { |
| return err |
| } |
| - _, err := r.sql.Exec(`UPDATE routes SET next_due = 0 WHERE host = ? AND next_due = ?`, host, due) |
| + _, err := r.sql.Exec(`UPDATE routes SET next_due = 0 WHERE host = ? AND kind <> 'forward' AND next_due = ?`, host, due) |
| return err |
| } |
| @@ -3163,7 +3208,7 @@ func (r *Registry) SetSeed(host, seed string) error { |
| return err |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET seed = ? WHERE host = ?`, seed, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET seed = ? WHERE host = ? AND kind <> 'forward'`, seed, host) |
| if err != nil { |
| return err |
| } |
| @@ -3172,7 +3217,7 @@ func (r *Registry) SetSeed(host, seed string) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -3185,7 +3230,7 @@ func (r *Registry) SetArgs(host, args string) error { |
| return err |
| } |
| - _, err := r.sql.Exec(`UPDATE routes SET args = ? WHERE host = ?`, args, host) |
| + _, err := r.sql.Exec(`UPDATE routes SET args = ? WHERE host = ? AND kind <> 'forward'`, args, host) |
| return err |
| } |
| @@ -3200,7 +3245,7 @@ func (r *Registry) SetWorkerLimits(host string, idle, maxRun int) error { |
| } |
| _, err := r.sql.Exec( |
| - `UPDATE routes SET idle_seconds = ?, max_run_seconds = ? WHERE host = ?`, |
| + `UPDATE routes SET idle_seconds = ?, max_run_seconds = ? WHERE host = ? AND kind <> 'forward'`, |
| idle, maxRun, host) |
| return err |
| } |
| @@ -3226,7 +3271,7 @@ func (r *Registry) SetProvisioned(host string, on bool) error { |
| if on { |
| v = 1 |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET provisioned = ? WHERE host = ?`, v, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET provisioned = ? WHERE host = ? AND kind <> 'forward'`, v, host) |
| if err != nil { |
| return err |
| } |
| @@ -3235,7 +3280,7 @@ func (r *Registry) SetProvisioned(host string, on bool) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
| @@ -3256,7 +3301,7 @@ func (r *Registry) SetStatusNamed(host string, on bool) error { |
| if on { |
| v = 1 |
| } |
| - res, err := r.sql.Exec(`UPDATE routes SET status_named = ? WHERE host = ?`, v, host) |
| + res, err := r.sql.Exec(`UPDATE routes SET status_named = ? WHERE host = ? AND kind <> 'forward'`, v, host) |
| if err != nil { |
| return err |
| } |
| @@ -3265,7 +3310,7 @@ func (r *Registry) SetStatusNamed(host string, on bool) error { |
| return err |
| } |
| if n == 0 { |
| - return fmt.Errorf("no route for host %q", host) |
| + return noRoute(r.sql, host) |
| } |
| return nil |
| } |
diff --git a/internal/registry/routecas.go b/internal/registry/routecas.go| index 2ca7bf627..68a258f7c 100644 |
| --- a/internal/registry/routecas.go |
| +++ b/internal/registry/routecas.go |
| @@ -13,11 +13,18 @@ package registry |
| // A plain Delete would remove that row, and the operator grants it |
| // carries. Here the check and the delete are one statement, so a row that |
| // changed identity is never removed on the strength of the old one. |
| +// |
| +// A forward row is the forward phase's to retire (DeleteForward): a listed |
| +// forward row is refused with ErrForwardRow, and the statement never matches |
| +// one (fleet public routes spec §4.2). |
| func (r *Registry) DeleteIfUnchanged(listed Route) (bool, error) { |
| + if listed.IsForward() { |
| + return false, ErrForwardRow |
| + } |
| if r.remote != nil { |
| return false, errRemoteMethod |
| } |
| - res, err := r.sql.Exec(`DELETE FROM routes WHERE host = ? AND kind = ? AND account = ? AND app = ? |
| + res, err := r.sql.Exec(`DELETE FROM routes WHERE host = ? AND kind = ? AND kind <> 'forward' AND account = ? AND app = ? |
| AND provisioned = ? AND import_gate = ? AND seed_source = ? AND created_at = ?`, |
| listed.Host, listed.Kind, listed.Account, listed.App, b2iDB(listed.Provisioned), |
| listed.ImportGate, listed.SeedSource, listed.CreatedAt) |