@substrat-run/adapter-cloudflare 0.221.0 → 0.223.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/broker-telemetry.d.ts +2 -5
  2. package/dist/broker-telemetry.d.ts.map +1 -1
  3. package/dist/broker-telemetry.js +2 -5
  4. package/dist/broker-telemetry.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +251 -67
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +666 -247
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +3 -2
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +10 -4
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/delivery-handoff.d.ts +17 -1
  14. package/dist/delivery-handoff.d.ts.map +1 -1
  15. package/dist/delivery-handoff.js +19 -5
  16. package/dist/delivery-handoff.js.map +1 -1
  17. package/dist/directory-cutover.d.ts +243 -0
  18. package/dist/directory-cutover.d.ts.map +1 -0
  19. package/dist/directory-cutover.js +604 -0
  20. package/dist/directory-cutover.js.map +1 -0
  21. package/dist/directory-mirror-apply.d.ts +19 -1
  22. package/dist/directory-mirror-apply.d.ts.map +1 -1
  23. package/dist/directory-mirror-apply.js +19 -3
  24. package/dist/directory-mirror-apply.js.map +1 -1
  25. package/dist/directory-mirror-backfill.d.ts +2 -0
  26. package/dist/directory-mirror-backfill.d.ts.map +1 -1
  27. package/dist/directory-mirror-backfill.js +6 -4
  28. package/dist/directory-mirror-backfill.js.map +1 -1
  29. package/dist/directory-mirror.d.ts +24 -0
  30. package/dist/directory-mirror.d.ts.map +1 -1
  31. package/dist/directory-mirror.js +16 -2
  32. package/dist/directory-mirror.js.map +1 -1
  33. package/dist/directory-objects.d.ts +40 -0
  34. package/dist/directory-objects.d.ts.map +1 -1
  35. package/dist/directory-objects.js +134 -2
  36. package/dist/directory-objects.js.map +1 -1
  37. package/dist/directory-placement.d.ts.map +1 -1
  38. package/dist/directory-placement.js +7 -1
  39. package/dist/directory-placement.js.map +1 -1
  40. package/dist/directory-split-inventory.d.ts +5 -3
  41. package/dist/directory-split-inventory.d.ts.map +1 -1
  42. package/dist/directory-split-inventory.js +12 -6
  43. package/dist/directory-split-inventory.js.map +1 -1
  44. package/dist/directory-tenant-orgs.d.ts +19 -0
  45. package/dist/directory-tenant-orgs.d.ts.map +1 -0
  46. package/dist/directory-tenant-orgs.js +33 -0
  47. package/dist/directory-tenant-orgs.js.map +1 -0
  48. package/dist/directory-tenant-roles.d.ts +35 -0
  49. package/dist/directory-tenant-roles.d.ts.map +1 -0
  50. package/dist/directory-tenant-roles.js +78 -0
  51. package/dist/directory-tenant-roles.js.map +1 -0
  52. package/dist/directory-tenant-tuples.d.ts +165 -0
  53. package/dist/directory-tenant-tuples.d.ts.map +1 -0
  54. package/dist/directory-tenant-tuples.js +197 -0
  55. package/dist/directory-tenant-tuples.js.map +1 -0
  56. package/dist/executor-route.d.ts +13 -0
  57. package/dist/executor-route.d.ts.map +1 -0
  58. package/dist/executor-route.js +12 -0
  59. package/dist/executor-route.js.map +1 -0
  60. package/dist/host.d.ts +76 -2
  61. package/dist/host.d.ts.map +1 -1
  62. package/dist/host.js +386 -67
  63. package/dist/host.js.map +1 -1
  64. package/dist/index.d.ts +2 -1
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +1 -0
  67. package/dist/index.js.map +1 -1
  68. package/dist/platform-sweeper-do.d.ts +1 -1
  69. package/dist/platform-sweeper-do.js +1 -1
  70. package/dist/scope-do.d.ts +11 -2
  71. package/dist/scope-do.d.ts.map +1 -1
  72. package/dist/scope-do.js +206 -58
  73. package/dist/scope-do.js.map +1 -1
  74. package/dist/scope-sweeper-do.d.ts +22 -0
  75. package/dist/scope-sweeper-do.d.ts.map +1 -1
  76. package/dist/scope-sweeper-do.js +74 -54
  77. package/dist/scope-sweeper-do.js.map +1 -1
  78. package/dist/scope-wake.d.ts +12 -1
  79. package/dist/scope-wake.d.ts.map +1 -1
  80. package/dist/scope-wake.js +14 -1
  81. package/dist/scope-wake.js.map +1 -1
  82. package/dist/tenant-due-work-do.d.ts +99 -0
  83. package/dist/tenant-due-work-do.d.ts.map +1 -0
  84. package/dist/tenant-due-work-do.js +149 -0
  85. package/dist/tenant-due-work-do.js.map +1 -0
  86. package/package.json +10 -10
@@ -0,0 +1,604 @@
1
+ /**
2
+ * Step 3e of the directory split (K-68, directory split; rfc/tenant-scale.md §12): CUT OVER, per tenant.
3
+ * A tenant whose comparison (3d) verified reads the cut-over tables from its own directory object, and
4
+ * writes them there FIRST; the one directory (`ControlPlaneDO`) is still written, after the object,
5
+ * as the fallback. A tenant whose flag is off, or that never verified, runs exactly as before.
6
+ *
7
+ * **What moves.** `CUTOVER_TABLES`, family by family:
8
+ * - role definitions (`_substrat_roles`): `defineRoleOrRefusal` (and the legacy `defineRole`) write
9
+ * them first in the object, and `listRoles` (one tenant's) and `getRole` read them there;
10
+ * - memberships and tenant-level grants (`_substrat_tenant_tuples`) with the removal fences beside them
11
+ * (`_substrat_membership_fences`): every unit that writes them (`writeTenantTuple`, `assignTenantRole`,
12
+ * `writeOrgTenantTuple`, `writeTenantSystemGrant`, `applyMembership`, `revokeAndFence`, a tenant-level
13
+ * `grantConnectionInDirectory`) runs in the object first (`directory-tenant-tuples.ts`), and every
14
+ * read of them (`tenantTuples`, `dumpTenantTuples`, `listMembers`, `tenantHeldOf`) is answered there;
15
+ * - organizations (`orgs`, `directory-tenant-orgs.ts`): `createOrg` and `insertOrg` write them first in
16
+ * the object, `readOrg` and `listOrgs` read them there, and a unit naming an org (`writeOrgTenantTuple`,
17
+ * `applyMembership`) asks the object's own rows whether it exists.
18
+ * Everything else the tenant owns is still read and decided in the directory and copied to the object
19
+ * by 3b's dual-write. A family moves by adding its tables here, its reads and writes to the object, and
20
+ * its dispatch in `ControlPlaneDO`; the triggers and the drop below then hold it without more code.
21
+ *
22
+ * **A tenant's tables are frozen at its flip on** (the flag's `tables`; none recorded reads as role
23
+ * definitions alone, a flip from before the second family). The triggers, the `first` drop and the
24
+ * drain read the tenant's own list, so a deploy that adds a family never widens a tenant already on:
25
+ * a revocation still in the dual-write's outbox for it would otherwise be dropped as `first`.
26
+ *
27
+ * **What only the directory holds** is decided there and handed to the object's unit: whether an org
28
+ * exists, for a tenant whose flip moved no orgs (orgs are never removed from a live tenant, so the
29
+ * answer cannot go stale); the system switches
30
+ * a `system:` grant is refused under, and the connection a connection grant names, are read in the same
31
+ * exclusive step (`ControlPlaneDO.exclusive`, no other call into the directory between the read, the
32
+ * object's write and its fallback). A connection grant's record, still the directory's, is carried with
33
+ * the owed write (`CarriedWrite`) and written by the fallback in the same transaction as the tuple.
34
+ *
35
+ * **Off by default.** `DIRECTORY_CUTOVER` unset (or `off`) installs nothing and no tenant can be
36
+ * flipped. `on` lets staff flip a tenant, one at a time (`cutOver`). Switching it back off flips no
37
+ * tenant at once: each one on is drained back to the directory by the alarm, as a flip off does.
38
+ *
39
+ * **The gate, in code** (`refusal`, in the same transaction as the flag's write): the switch is on;
40
+ * 3b's dual-write is on for every table a tenant object holds; 3d's comparison is on and its last
41
+ * finished comparison of this tenant verified, with nothing in flight, nothing truncated, after the
42
+ * last table was switched on and within `verifyMaxAgeMs`; 3c's backfill filled it if it ran; the
43
+ * tenant is `active`; nothing for it is queued in the dual-write's outbox or its claim work; and the
44
+ * object holds nothing parked (asked just before).
45
+ *
46
+ * **Where the flag lives.** In the directory (`directory_mirror_cutover`, which every dispatch reads
47
+ * in the call's own transaction, and which a restore keeps, like the dual-write's version) and in the
48
+ * registry (`directory_tenant_cutover`, recorded after each flip and retried by the alarm until it
49
+ * agrees). In 3e the directory dispatches, so its row is the one acted on; 3f moves the dispatch to
50
+ * the registry's.
51
+ *
52
+ * **A write, while a tenant is on.** (1) The directory takes a mirror version (`takeMirrorVersion`).
53
+ * (2) The object runs the same code the directory runs (`directory-tenant-roles.ts`) in its own
54
+ * transaction, decides, stamps each key it wrote with that version, and records the write in its
55
+ * owed ledger (`directory_mirror_owed`, numbered `seq`). (3) The directory applies every owed write
56
+ * after the `seq` it last applied, in `seq` order, in one transaction with each one's admin row (the
57
+ * fallback), and the object drops what the directory confirmed. A step-3 failure does not fail the
58
+ * write, which the object has made: the alarm drains it. A failure in (2) fails the write.
59
+ *
60
+ * **What keeps the two from crossing.** While a tenant is on:
61
+ * - a BEFORE trigger on each cut-over table refuses any directory write of that tenant's rows except
62
+ * the fallback apply (marked by `directory_mirror_cutover_applying`, inside its transaction): a path
63
+ * that would write the directory first is refused, not silently diverged;
64
+ * - every dual-write batch and 3c page read for the tenant is flagged `first`, and the object drops its
65
+ * changes to the cut-over tables: the directory's copy can lag the object by an owed write, and must
66
+ * never overwrite it;
67
+ * - a page read before the flip (unflagged) is older than the version each first write stamps, so it
68
+ * is stale for the keys the object wrote.
69
+ * 3d keeps comparing; a key the object still owes the directory is in flight there, not a difference.
70
+ *
71
+ * **Flip off** (`draining`, then `off`). Reads stay on the object and writes stay object-first while
72
+ * the directory drains every owed write; the flip completes, in one transaction, only when the object
73
+ * owes nothing and no first write is running in this directory. The directory then serves everything
74
+ * again: it was written all along, and is now complete. Batches read after it are unflagged again.
75
+ *
76
+ * **Writes in flight at a flip.** On: a directory write not yet copied to the object holds its rows in
77
+ * the outbox, so the gate refuses until the dual-write has delivered it. A directory method that read
78
+ * before the flip and writes a cut-over table after it is refused by the trigger, and its caller retries
79
+ * (into the object). Off: a first write the object made whose fallback has not landed is in the owed
80
+ * ledger; `draining` waits for it, so nothing the object accepted is lost when reads return.
81
+ */
82
+ import { REGISTRY_OWNER, tenantOwnerOf } from '@substrat-run/kernel';
83
+ import { substratError } from '@substrat-run/contracts';
84
+ import { MIRRORED_TABLES, mirrorOwnerRowsSql, quoteIdent, takeMirrorVersion } from './directory-mirror.js';
85
+ import { writeMirrorChange } from './directory-mirror-apply.js';
86
+ /**
87
+ * The tables a cut-over tenant's object writes first and serves, family by family, in the order they
88
+ * moved: role definitions (the first family), then the tenant's tuples and the removal fences beside
89
+ * them (memberships and tenant-level grants), then its organizations. A flip on freezes the list as it stands into the
90
+ * tenant's flag (`tables`), so a deploy that adds a family never widens a tenant already on: it gets
91
+ * the new family at its next flip on, after a flip off has drained it back.
92
+ */
93
+ export const CUTOVER_TABLES = ['_substrat_roles', '_substrat_tenant_tuples', '_substrat_membership_fences', 'orgs'];
94
+ export const CUTOVER_TABLE_SET = new Set(CUTOVER_TABLES);
95
+ /** The tables of a flag flipped on before the flag recorded them (step 3e's first family). */
96
+ const LEGACY_TABLES = '|_substrat_roles|';
97
+ /** `tables` as stored: `|a|b|`, so a trigger asks `instr` for one name without a pattern. */
98
+ const storedTables = (tables) => `|${tables.join('|')}|`;
99
+ const tablesOfStored = (stored) => (stored ?? LEGACY_TABLES).split('|').filter((t) => t !== '');
100
+ // ---------------------------------------------------------------------------
101
+ // The object's half: the owed ledger (TenantDirectoryDO), and the registry's record.
102
+ // ---------------------------------------------------------------------------
103
+ export const CUTOVER_OBJECT_DDL = [
104
+ `CREATE TABLE IF NOT EXISTS directory_mirror_owed (
105
+ seq INTEGER PRIMARY KEY,
106
+ changes TEXT NOT NULL,
107
+ audit TEXT,
108
+ at TEXT NOT NULL
109
+ )`,
110
+ // `seq` only grows, across drops: the directory skips anything at or below the last it applied.
111
+ `CREATE TABLE IF NOT EXISTS directory_mirror_owed_seq (id INTEGER PRIMARY KEY CHECK (id = 1), seq INTEGER NOT NULL)`,
112
+ ];
113
+ export const CUTOVER_REGISTRY_DDL = [
114
+ `CREATE TABLE IF NOT EXISTS directory_tenant_cutover (
115
+ tenant_id TEXT PRIMARY KEY,
116
+ state TEXT NOT NULL,
117
+ since_version INTEGER NOT NULL,
118
+ changed_at TEXT NOT NULL,
119
+ changed_by TEXT NOT NULL
120
+ )`,
121
+ ];
122
+ /**
123
+ * In the first write's transaction: record it owed, and answer its `seq`. The `audit` column holds
124
+ * `{ audits, carried }`; a row the first family's build wrote holds one admin row there, or null.
125
+ */
126
+ export function recordOwedIn(sql, changes, audits, nowIso, carried = []) {
127
+ sql.exec(`INSERT INTO directory_mirror_owed_seq (id, seq) VALUES (1, 1) ON CONFLICT (id) DO UPDATE SET seq = seq + 1`);
128
+ const seq = Number(sql.exec(`SELECT seq FROM directory_mirror_owed_seq WHERE id = 1`).one().seq);
129
+ sql.exec(`INSERT INTO directory_mirror_owed (seq, changes, audit, at) VALUES (?, ?, ?, ?)`, seq, JSON.stringify(changes), JSON.stringify({ audits, carried }), nowIso);
130
+ return seq;
131
+ }
132
+ function owedExtrasOf(stored) {
133
+ if (stored === null)
134
+ return { audits: [], carried: [] };
135
+ const parsed = JSON.parse(stored);
136
+ if (Array.isArray(parsed.audits))
137
+ return { audits: parsed.audits, carried: parsed.carried ?? [] };
138
+ return { audits: [parsed], carried: [] };
139
+ }
140
+ /** An owed write's admin rows, as either build of the object answers them. */
141
+ export const owedAuditsOf = (w) => w.audits ?? (w.audit ? [w.audit] : []);
142
+ /** Owed writes one answer carries at most; the directory asks again until none is left. */
143
+ export const OWED_PAGE = 50;
144
+ export function owedAfterIn(sql, appliedSeq) {
145
+ sql.exec(`DELETE FROM directory_mirror_owed WHERE seq <= ?`, appliedSeq);
146
+ return sql.exec(`SELECT seq, changes, audit FROM directory_mirror_owed ORDER BY seq LIMIT ?`, OWED_PAGE).toArray().map((r) => ({ seq: Number(r.seq), changes: JSON.parse(r.changes), ...owedExtrasOf(r.audit) }));
147
+ }
148
+ /** The keys of `table` among `keys` that the object still owes the directory (in flight for 3d). */
149
+ export function owedKeysIn(sql, table, keys) {
150
+ if (keys.length === 0)
151
+ return [];
152
+ const has = sql.exec(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'directory_mirror_owed'`).toArray().length > 0;
153
+ if (!has)
154
+ return [];
155
+ return sql
156
+ .exec(`SELECT DISTINCT json_extract(c.value, '$.key') AS k FROM directory_mirror_owed o, json_each(o.changes) c
157
+ WHERE json_extract(c.value, '$.table') = ? AND json_extract(c.value, '$.key') IN (SELECT value FROM json_each(?))`, table, JSON.stringify(keys))
158
+ .toArray().map((r) => r.k);
159
+ }
160
+ /** A cut-over table's row as it stands, as a mirror change keyed like the triggers key it. */
161
+ export function rowChangeOf(sql, table, keyColumns, keyValues) {
162
+ const where = keyColumns.map((k) => `${quoteIdent(k)} = ?`).join(' AND ');
163
+ const row = sql.exec(`SELECT * FROM ${quoteIdent(table)} WHERE ${where}`, ...keyValues).toArray()[0] ?? null;
164
+ return { table, key: JSON.stringify(keyValues), row };
165
+ }
166
+ /** The registry's half: a record replaces only an older one. */
167
+ export function recordCutoverIn(sql, row) {
168
+ sql.exec(`INSERT INTO directory_tenant_cutover (tenant_id, state, since_version, changed_at, changed_by) VALUES (?, ?, ?, ?, ?)
169
+ ON CONFLICT (tenant_id) DO UPDATE SET state = excluded.state, since_version = excluded.since_version,
170
+ changed_at = excluded.changed_at, changed_by = excluded.changed_by
171
+ WHERE excluded.since_version > directory_tenant_cutover.since_version`, row.tenantId, row.state, row.sinceVersion, row.changedAt, row.changedBy);
172
+ }
173
+ export function readCutoverIn(sql, tenantId) {
174
+ const r = sql.exec(`SELECT * FROM directory_tenant_cutover WHERE tenant_id = ?`, tenantId).toArray()[0];
175
+ return r ? { tenantId: r.tenant_id, state: r.state, sinceVersion: Number(r.since_version), changedAt: r.changed_at, changedBy: r.changed_by } : null;
176
+ }
177
+ // ---------------------------------------------------------------------------
178
+ // The directory's half.
179
+ // ---------------------------------------------------------------------------
180
+ const FLAGS = 'directory_mirror_cutover';
181
+ const APPLYING = 'directory_mirror_cutover_applying';
182
+ const DIRECTORY_DDL = [
183
+ `CREATE TABLE IF NOT EXISTS ${FLAGS} (
184
+ tenant_id TEXT PRIMARY KEY,
185
+ state TEXT NOT NULL CHECK (state IN ('on', 'draining', 'off')),
186
+ since_version INTEGER NOT NULL,
187
+ applied_seq INTEGER NOT NULL DEFAULT 0,
188
+ verified_at TEXT,
189
+ changed_at TEXT NOT NULL,
190
+ changed_by TEXT NOT NULL,
191
+ recorded_version INTEGER,
192
+ tables TEXT
193
+ )`,
194
+ // A row only inside the fallback apply's transaction: the triggers let that one writer through.
195
+ `CREATE TABLE IF NOT EXISTS ${APPLYING} (id INTEGER PRIMARY KEY CHECK (id = 1))`,
196
+ ];
197
+ const triggerName = (verb, table) => `dcutover_${verb}_${table}`;
198
+ /** The refusing triggers of one cut-over table, spelled as `sqlite_master` keeps them. */
199
+ export function cutoverTriggerSql(table) {
200
+ // Only a tenant whose flip froze this table in (`tables`; NULL is the first family alone).
201
+ const live = (ref) => `${ref}."tenant_id" IN (SELECT tenant_id FROM ${FLAGS} WHERE state <> 'off' AND instr(COALESCE(tables, '${LEGACY_TABLES}'), '|${table}|') > 0)`;
202
+ const body = `BEGIN SELECT RAISE(ABORT, 'directory cut-over (K-68 step 3e): this tenant''s ${table} is written in its own directory object first; flip it off first'); END`;
203
+ const outside = `NOT EXISTS (SELECT 1 FROM ${APPLYING})`;
204
+ const t = quoteIdent(table);
205
+ return [
206
+ { name: triggerName('i', table), sql: `CREATE TRIGGER ${triggerName('i', table)} BEFORE INSERT ON ${t} WHEN ${live('NEW')} AND ${outside} ${body}` },
207
+ { name: triggerName('u', table), sql: `CREATE TRIGGER ${triggerName('u', table)} BEFORE UPDATE ON ${t} WHEN (${live('OLD')} OR ${live('NEW')}) AND ${outside} ${body}` },
208
+ { name: triggerName('d', table), sql: `CREATE TRIGGER ${triggerName('d', table)} BEFORE DELETE ON ${t} WHEN ${live('OLD')} AND ${outside} ${body}` },
209
+ ];
210
+ }
211
+ /** Whether any tenant's flag is not off: a restore is refused, and the alarm has draining to do. */
212
+ export function cutoverLive(sql) {
213
+ const has = sql.exec(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`, FLAGS).toArray().length > 0;
214
+ return has && sql.exec(`SELECT 1 FROM ${FLAGS} WHERE state <> 'off' LIMIT 1`).toArray().length > 0;
215
+ }
216
+ function dropCutoverTriggers(sql) {
217
+ const triggers = sql.exec(`SELECT name FROM sqlite_master WHERE type = 'trigger' AND name GLOB 'dcutover_*'`).toArray();
218
+ for (const { name } of triggers)
219
+ sql.exec(`DROP TRIGGER IF EXISTS ${quoteIdent(name)}`);
220
+ }
221
+ /** The switch: unset, empty or `off` flips nothing; `on` lets staff flip a tenant. Anything else is refused. */
222
+ export function parseDirectoryCutover(value) {
223
+ const text = typeof value === 'string' ? value.trim() : '';
224
+ if (text === '' || text === 'off')
225
+ return false;
226
+ if (text === 'on')
227
+ return true;
228
+ throw new Error(`directory cutover: ${text} is not on or off`);
229
+ }
230
+ const rowOf = (r) => ({
231
+ tenantId: r.tenant_id,
232
+ state: r.state,
233
+ sinceVersion: Number(r.since_version),
234
+ appliedSeq: Number(r.applied_seq),
235
+ verifiedAt: r.verified_at,
236
+ changedAt: r.changed_at,
237
+ changedBy: r.changed_by,
238
+ recorded: r.recorded_version !== null && Number(r.recorded_version) === Number(r.since_version),
239
+ tables: tablesOfStored(r.tables),
240
+ });
241
+ /** How soon the alarm drains again after a fallback that failed, or a drain that is not done. */
242
+ export const CUTOVER_RETRY_MS = 10_000;
243
+ /** Tenants the alarm drains (and records in the registry) per pass. */
244
+ export const CUTOVER_ALARM_TENANTS = 50;
245
+ /** Owed pages one drain reads at most before leaving the rest to the alarm. */
246
+ const DRAIN_PAGES = 20;
247
+ const tenantPrefix = tenantOwnerOf('');
248
+ const conflict = (message) => substratError('conflict', message);
249
+ /** The directory's half of 3e, one per `ControlPlaneDO` instance while the switch is on or a tenant is not off. */
250
+ export class DirectoryCutover {
251
+ options;
252
+ sql;
253
+ /** First writes running in this directory, per tenant: a flip off completes only at zero. */
254
+ running = new Map();
255
+ constructor(options) {
256
+ this.options = options;
257
+ this.sql = options.sql;
258
+ }
259
+ now() {
260
+ return (this.options.now ?? Date.now)();
261
+ }
262
+ iso(ms = this.now()) {
263
+ return new Date(ms).toISOString();
264
+ }
265
+ /** Tables and triggers, in the caller's transaction; run on construction and after a restore. */
266
+ install() {
267
+ for (const stmt of DIRECTORY_DDL)
268
+ this.sql.exec(stmt);
269
+ // A flag table from the first family's build has no `tables`: its rows read as that family alone.
270
+ const columns = this.sql.exec(`SELECT name FROM pragma_table_info('${FLAGS}')`).toArray();
271
+ if (!columns.some((c) => c.name === 'tables'))
272
+ this.sql.exec(`ALTER TABLE ${FLAGS} ADD COLUMN tables TEXT`);
273
+ // A crash between the marker's insert and its delete is impossible (one transaction), but a
274
+ // restore copies nothing of it either way: the marker is never left standing.
275
+ this.sql.exec(`DELETE FROM ${APPLYING}`);
276
+ for (const table of CUTOVER_TABLES) {
277
+ for (const t of cutoverTriggerSql(table)) {
278
+ const held = this.sql.exec(`SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?`, t.name).toArray()[0];
279
+ if (held?.sql === t.sql)
280
+ continue;
281
+ this.sql.exec(`DROP TRIGGER IF EXISTS ${t.name}`);
282
+ this.sql.exec(t.sql);
283
+ }
284
+ }
285
+ }
286
+ /** The tables the tenant's last flip on froze in, whatever its state now. */
287
+ frozenTablesOf(tenantId) {
288
+ const r = this.sql.exec(`SELECT tables FROM ${FLAGS} WHERE tenant_id = ?`, tenantId).toArray()[0];
289
+ return tablesOfStored(r?.tables ?? null);
290
+ }
291
+ flag(tenantId) {
292
+ return this.sql.exec(`SELECT * FROM ${FLAGS} WHERE tenant_id = ?`, tenantId).toArray()[0] ?? null;
293
+ }
294
+ /** The tables the tenant reads and first-writes in its object (on, or draining back), or null when it is off. */
295
+ tablesOf(tenantId) {
296
+ const r = this.sql.exec(`SELECT tables FROM ${FLAGS} WHERE tenant_id = ? AND state <> 'off'`, tenantId).toArray()[0];
297
+ return r ? tablesOfStored(r.tables) : null;
298
+ }
299
+ /** The tenant reads and first-writes `table` in its object: its flip on froze `table` in, and it is not off. */
300
+ cutOverFor(tenantId, table) {
301
+ return this.tablesOf(tenantId)?.includes(table) ?? false;
302
+ }
303
+ /** The tenant reads and first-writes its role definitions in its object (the first family). */
304
+ isCutOver(tenantId) {
305
+ return this.cutOverFor(tenantId, '_substrat_roles');
306
+ }
307
+ /** For the dual-write's batches and 3c's pages: the tables an owner's batch is flagged `first` for, or null. */
308
+ firstOf(owner) {
309
+ if (owner === REGISTRY_OWNER || !owner.startsWith(tenantPrefix))
310
+ return null;
311
+ return this.tablesOf(owner.slice(tenantPrefix.length));
312
+ }
313
+ /** Why `tenantId` may not be flipped on now, or null. Synchronous: run in the flip's transaction. */
314
+ refusal(tenantId) {
315
+ const { mirror, verify } = this.options;
316
+ if (!this.options.switchedOn)
317
+ return 'DIRECTORY_CUTOVER is off';
318
+ if (!mirror)
319
+ return 'the dual-write (DIRECTORY_MIRROR) is off';
320
+ const mirrored = mirror.status().tables;
321
+ const since = new Map(mirrored.map((t) => [t.table, t.since]));
322
+ const missing = MIRRORED_TABLES.filter((t) => mirrorOwnerRowsSql(t, 't', 'tenant') !== null && !since.has(t));
323
+ if (missing.length > 0)
324
+ return `the dual-write does not copy ${missing.join(', ')}`;
325
+ if (!verify)
326
+ return 'the comparison (DIRECTORY_VERIFY) is off';
327
+ const status = this.sql.exec(`SELECT status FROM tenants WHERE tenant_id = ?`, tenantId).toArray()[0];
328
+ if (!status)
329
+ return `unknown tenant: ${tenantId}`;
330
+ if (status.status !== 'active')
331
+ return `the tenant is ${status.status}, not active`;
332
+ const owner = tenantOwnerOf(tenantId);
333
+ const [report] = verify.owners({ owner });
334
+ const result = report?.result;
335
+ if (!report || !result || report.checkedAt === null)
336
+ return 'the comparison has not finished for this tenant';
337
+ if (!result.verified)
338
+ return 'the last comparison of this tenant found differences';
339
+ if (result.inFlight > 0)
340
+ return 'the last comparison of this tenant had changes in flight; compare again';
341
+ if (result.filled === false)
342
+ return 'the backfill had not filled this tenant when it was compared';
343
+ const lastSince = [...since.values()].sort().at(-1) ?? '';
344
+ if (report.checkedAt < lastSince)
345
+ return 'the last comparison is older than a table the dual-write copies';
346
+ if (Date.parse(report.checkedAt) < this.now() - (this.options.verifyMaxAgeMs ?? 24 * 60 * 60 * 1000))
347
+ return 'the last comparison is too old; compare again';
348
+ if (this.sql.exec(`SELECT 1 FROM directory_mirror_outbox WHERE target = ? LIMIT 1`, owner).toArray().length > 0) {
349
+ return 'the dual-write has changes for this tenant not yet delivered';
350
+ }
351
+ if (this.sql.exec(`SELECT 1 FROM directory_mirror_claims_due WHERE owner = ? LIMIT 1`, owner).toArray().length > 0) {
352
+ return 'the dual-write has registry claim work for this tenant not yet done';
353
+ }
354
+ return null;
355
+ }
356
+ /**
357
+ * Flip a tenant on (gated, `refusal`) or off (draining, then off once the directory holds every
358
+ * write the object made first). Answers the tenant's row as it stands after the call.
359
+ */
360
+ async cutOver(tenantId, to, actor) {
361
+ const owner = tenantOwnerOf(tenantId);
362
+ if (to === 'on') {
363
+ const held = this.flag(tenantId);
364
+ if (held && held.state !== 'off')
365
+ return rowOf(held);
366
+ // Asked before the transaction (an RPC cannot be inside it). A change parks only from a batch,
367
+ // and a batch for this tenant holds outbox rows until it is acknowledged, which the gate refuses.
368
+ const parked = await this.options.sender.parked(owner);
369
+ if (parked > 0)
370
+ throw conflict(`directory cutover refused for ${tenantId}: its object holds ${parked} parked change(s)`);
371
+ this.options.transaction(() => {
372
+ const refused = this.refusal(tenantId);
373
+ if (refused)
374
+ throw conflict(`directory cutover refused for ${tenantId}: ${refused}`);
375
+ const version = takeMirrorVersion(this.sql);
376
+ const [report] = this.options.verify.owners({ owner });
377
+ this.sql.exec(`INSERT INTO directory_mirror_cutover (tenant_id, state, since_version, applied_seq, verified_at, changed_at, changed_by, recorded_version, tables)
378
+ VALUES (?, 'on', ?, 0, ?, ?, ?, NULL, ?)
379
+ ON CONFLICT (tenant_id) DO UPDATE SET state = 'on', since_version = excluded.since_version, verified_at = excluded.verified_at,
380
+ changed_at = excluded.changed_at, changed_by = excluded.changed_by, tables = excluded.tables`, tenantId, version, report?.checkedAt ?? null, this.iso(), actor, storedTables(CUTOVER_TABLES));
381
+ });
382
+ await this.recordInRegistry(tenantId);
383
+ return rowOf(this.flag(tenantId));
384
+ }
385
+ const held = this.flag(tenantId);
386
+ if (!held || held.state === 'off')
387
+ return held ? rowOf(held) : this.offRow(tenantId);
388
+ if (held.state === 'on') {
389
+ this.options.transaction(() => this.sql.exec(`UPDATE ${FLAGS} SET state = 'draining', changed_at = ?, changed_by = ? WHERE tenant_id = ? AND state = 'on'`, this.iso(), actor, tenantId));
390
+ }
391
+ await this.settleDraining(tenantId, actor);
392
+ return rowOf(this.flag(tenantId));
393
+ }
394
+ offRow(tenantId) {
395
+ return { tenantId, state: 'off', sinceVersion: 0, appliedSeq: 0, verifiedAt: null, changedAt: '', changedBy: '', recorded: true, tables: [] };
396
+ }
397
+ /** Drain, then complete the flip off when nothing is owed and no first write is running here. */
398
+ async settleDraining(tenantId, actor) {
399
+ let drained = false;
400
+ try {
401
+ drained = await this.drain(tenantId);
402
+ }
403
+ catch (err) {
404
+ console.error(`directory cutover: draining ${tenantId} failed; the alarm tries again`, err);
405
+ }
406
+ // No await between the drain's answer and this transaction: nothing can start a first write in between.
407
+ const done = drained && (this.running.get(tenantId) ?? 0) === 0 && this.options.transaction(() => {
408
+ const held = this.flag(tenantId);
409
+ if (!held || held.state !== 'draining')
410
+ return false;
411
+ this.sql.exec(`UPDATE ${FLAGS} SET state = 'off', since_version = ?, changed_at = ?, changed_by = ? WHERE tenant_id = ?`, takeMirrorVersion(this.sql), this.iso(), actor, tenantId);
412
+ return true;
413
+ });
414
+ if (done)
415
+ await this.recordInRegistry(tenantId);
416
+ else
417
+ await this.options.armRetry(this.now() + CUTOVER_RETRY_MS).catch(() => undefined);
418
+ return this.flag(tenantId)?.state ?? 'off';
419
+ }
420
+ /**
421
+ * Apply every write the object owes this directory, in `seq` order, each with its admin row, in one
422
+ * transaction a page. Answers whether the object owes nothing more.
423
+ */
424
+ async drain(tenantId) {
425
+ const owner = tenantOwnerOf(tenantId);
426
+ for (let page = 0; page < DRAIN_PAGES; page++) {
427
+ const applied = this.flag(tenantId)?.applied_seq ?? 0;
428
+ const owed = await this.options.sender.owedAfter(owner, Number(applied));
429
+ if (owed.length === 0)
430
+ return true;
431
+ this.options.transaction(() => {
432
+ // Re-read in the transaction: a concurrent drain may have applied some of these already.
433
+ const from = Number(this.flag(tenantId)?.applied_seq ?? 0);
434
+ const fresh = owed.filter((w) => w.seq > from).sort((a, b) => a.seq - b.seq);
435
+ if (fresh.length === 0)
436
+ return;
437
+ // The tables the tenant's flip froze in: an owed change to any other is not the object's to make.
438
+ const tables = new Set(this.frozenTablesOf(tenantId));
439
+ this.sql.exec(`INSERT OR IGNORE INTO directory_mirror_cutover_applying (id) VALUES (1)`);
440
+ try {
441
+ for (const w of fresh) {
442
+ for (const change of w.changes) {
443
+ if (!tables.has(change.table))
444
+ throw new Error(`directory cutover: ${change.table} is not a cut-over table of ${tenantId}`);
445
+ writeMirrorChange(this.sql, change);
446
+ }
447
+ for (const carried of w.carried ?? [])
448
+ this.options.applyCarried(carried);
449
+ // An admin row is written once: a replay after a lost acknowledgement finds it there.
450
+ for (const audit of owedAuditsOf(w)) {
451
+ if (this.sql.exec(`SELECT 1 FROM _substrat_admin_log WHERE id = ?`, audit.id).toArray().length === 0)
452
+ this.options.recordAdmin(audit);
453
+ }
454
+ }
455
+ this.sql.exec(`UPDATE ${FLAGS} SET applied_seq = ? WHERE tenant_id = ?`, fresh.at(-1).seq, tenantId);
456
+ }
457
+ finally {
458
+ this.sql.exec(`DELETE FROM ${APPLYING}`);
459
+ }
460
+ });
461
+ }
462
+ return false;
463
+ }
464
+ /** Run `first` as a first write of `tenantId` (counted while it runs), then drain its fallback. */
465
+ async firstWrite(tenantId, first) {
466
+ const owner = tenantOwnerOf(tenantId);
467
+ const version = this.options.transaction(() => takeMirrorVersion(this.sql));
468
+ this.running.set(tenantId, (this.running.get(tenantId) ?? 0) + 1);
469
+ try {
470
+ const out = await first(owner, version);
471
+ try {
472
+ await this.drain(tenantId);
473
+ }
474
+ catch (err) {
475
+ // The object made the write; the directory's copy follows from the alarm.
476
+ console.error(`directory cutover: the fallback write of ${tenantId} failed; the alarm applies it`, err);
477
+ await this.options.armRetry(this.now() + CUTOVER_RETRY_MS).catch(() => undefined);
478
+ }
479
+ return out;
480
+ }
481
+ finally {
482
+ const n = (this.running.get(tenantId) ?? 1) - 1;
483
+ if (n === 0)
484
+ this.running.delete(tenantId);
485
+ else
486
+ this.running.set(tenantId, n);
487
+ }
488
+ }
489
+ // -- the first family: role definitions ------------------------------------
490
+ async defineRole(tenantId, role, reservation, seatedInScopes, audit) {
491
+ return this.firstWrite(tenantId, async (owner, version) => (await this.options.sender.defineRoleFirst(owner, { version, tenantId, role, reservation, seatedInScopes, audit })).outcome);
492
+ }
493
+ listRoles(tenantId, filter) {
494
+ return this.options.sender.listRoles(tenantOwnerOf(tenantId), { ...filter, tenantId });
495
+ }
496
+ getRole(tenantId, key) {
497
+ return this.options.sender.getRole(tenantOwnerOf(tenantId), tenantId, key);
498
+ }
499
+ // -- the second family: the tenant's tuples and removal fences -----------------
500
+ /**
501
+ * One unit of the family (`runTupleOp`), run first in the tenant's object, then its fallback. The
502
+ * caller has decided whatever only the directory holds; a unit that also reads what the directory
503
+ * writes (a system switch, a connection) is run inside `ControlPlaneDO`'s exclusive step.
504
+ */
505
+ async tupleWrite(tenantId, op, carried) {
506
+ return this.firstWrite(tenantId, async (owner, version) => (await this.options.sender.tupleFirst(owner, { version, tenantId, op, ...(carried && carried.length > 0 ? { carried } : {}) })).result);
507
+ }
508
+ tupleRead(tenantId, q) {
509
+ return this.options.sender.tupleRead(tenantOwnerOf(tenantId), tenantId, q);
510
+ }
511
+ // -- the registry's record, the alarm, status --------------------------------
512
+ async recordInRegistry(tenantId) {
513
+ const held = this.flag(tenantId);
514
+ if (!held)
515
+ return true;
516
+ try {
517
+ await this.options.sender.record({
518
+ tenantId, state: held.state, sinceVersion: Number(held.since_version), changedAt: held.changed_at, changedBy: held.changed_by,
519
+ });
520
+ }
521
+ catch (err) {
522
+ console.error(`directory cutover: recording ${tenantId}'s flag in the registry failed; the alarm tries again`, err);
523
+ await this.options.armRetry(this.now() + CUTOVER_RETRY_MS).catch(() => undefined);
524
+ return false;
525
+ }
526
+ this.options.transaction(() => this.sql.exec(`UPDATE ${FLAGS} SET recorded_version = ? WHERE tenant_id = ? AND since_version = ?`, held.since_version, tenantId, held.since_version));
527
+ return true;
528
+ }
529
+ /** Work the alarm has: a tenant draining, one on with the switch off, owed writes, an unrecorded flip. */
530
+ wanted() {
531
+ return (this.sql.exec(`SELECT 1 FROM ${FLAGS} WHERE state = 'draining' OR recorded_version IS NULL OR recorded_version <> since_version ${this.options.switchedOn ? '' : `OR state = 'on'`} LIMIT 1`).toArray().length > 0);
532
+ }
533
+ /**
534
+ * The alarm's pass: drain every tenant not off (a write whose fallback failed), complete the flips
535
+ * off it can, drain back every tenant on while the switch is off, and record what the registry lacks.
536
+ */
537
+ async retry() {
538
+ const rows = this.sql.exec(`SELECT * FROM ${FLAGS} WHERE state <> 'off' OR recorded_version IS NULL OR recorded_version <> since_version ORDER BY changed_at LIMIT ?`, CUTOVER_ALARM_TENANTS).toArray();
539
+ for (const r of rows) {
540
+ try {
541
+ if (r.state === 'on' && !this.options.switchedOn) {
542
+ this.options.transaction(() => this.sql.exec(`UPDATE ${FLAGS} SET state = 'draining', changed_at = ?, changed_by = 'directory:switch-off' WHERE tenant_id = ? AND state = 'on'`, this.iso(), r.tenant_id));
543
+ }
544
+ const state = this.flag(r.tenant_id)?.state;
545
+ if (state === 'draining')
546
+ await this.settleDraining(r.tenant_id, 'directory:drain');
547
+ else if (state === 'on' && !(await this.drain(r.tenant_id)))
548
+ await this.options.armRetry(this.now() + CUTOVER_RETRY_MS);
549
+ const held = this.flag(r.tenant_id);
550
+ if (held && (held.recorded_version === null || Number(held.recorded_version) !== Number(held.since_version)))
551
+ await this.recordInRegistry(r.tenant_id);
552
+ }
553
+ catch (err) {
554
+ console.error(`directory cutover: the alarm's pass over ${r.tenant_id} failed`, err);
555
+ await this.options.armRetry(this.now() + CUTOVER_RETRY_MS).catch(() => undefined);
556
+ }
557
+ }
558
+ }
559
+ status(query = {}) {
560
+ const limit = Math.max(1, Math.min(query.limit ?? 100, 500));
561
+ const counts = this.sql.exec(`SELECT SUM(state = 'on') AS on_, SUM(state = 'draining') AS draining, SUM(state = 'off') AS off FROM ${FLAGS}`).one();
562
+ const rows = (query.tenantId
563
+ ? this.sql.exec(`SELECT * FROM ${FLAGS} WHERE tenant_id = ?`, query.tenantId)
564
+ : this.sql.exec(`SELECT * FROM ${FLAGS} WHERE tenant_id > ? ORDER BY tenant_id LIMIT ?`, query.after ?? '', limit)).toArray();
565
+ return {
566
+ enabled: this.options.switchedOn,
567
+ on: Number(counts.on_ ?? 0),
568
+ draining: Number(counts.draining ?? 0),
569
+ off: Number(counts.off ?? 0),
570
+ tenants: rows.map(rowOf),
571
+ };
572
+ }
573
+ }
574
+ /**
575
+ * The directory's cut-over as its environment sets it. Null, with its triggers dropped, when the
576
+ * switch is off and no tenant is on or draining. A tenant not off keeps it, switch or not, so the
577
+ * alarm can drain it back. Null too (its triggers kept, so a tenant on is refused directory writes
578
+ * rather than diverging) when the objects are not bound. Called once, from `ControlPlaneDO`'s constructor.
579
+ */
580
+ export function directoryCutoverFor(env, sender, options) {
581
+ let on;
582
+ try {
583
+ on = parseDirectoryCutover(Reflect.get(env, 'DIRECTORY_CUTOVER'));
584
+ }
585
+ catch (err) {
586
+ console.error('directory cutover: DIRECTORY_CUTOVER refused, no tenant may be flipped:', err.message);
587
+ on = false;
588
+ }
589
+ const live = cutoverLive(options.sql);
590
+ if (!on && !live) {
591
+ options.transaction(() => dropCutoverTriggers(options.sql));
592
+ return null;
593
+ }
594
+ if (!sender) {
595
+ console.error('directory cutover: DIRECTORY_REGISTRY / TENANT_DIRECTORY are not bound; no tenant is flipped or drained');
596
+ return null;
597
+ }
598
+ const cutover = new DirectoryCutover({ ...options, sender, switchedOn: on });
599
+ options.transaction(() => cutover.install());
600
+ if (options.mirror)
601
+ options.mirror.firstOf = (owner) => cutover.firstOf(owner);
602
+ return cutover;
603
+ }
604
+ //# sourceMappingURL=directory-cutover.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directory-cutover.js","sourceRoot":"","sources":["../src/directory-cutover.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgFG;AACH,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,aAAa,EAAuB,MAAM,yBAAyB,CAAC;AAC7E,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,UAAU,EAAE,iBAAiB,EAA2C,MAAM,uBAAuB,CAAC;AACpJ,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAKhE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,cAAc,GAAsB,CAAC,iBAAiB,EAAE,yBAAyB,EAAE,6BAA6B,EAAE,MAAM,CAAC,CAAC;AACvI,MAAM,CAAC,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CAAC,cAAc,CAAC,CAAC;AAE9E,8FAA8F;AAC9F,MAAM,aAAa,GAAG,mBAAmB,CAAC;AAC1C,6FAA6F;AAC7F,MAAM,YAAY,GAAG,CAAC,MAAyB,EAAU,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;AACpF,MAAM,cAAc,GAAG,CAAC,MAAqB,EAAY,EAAE,CAAC,CAAC,MAAM,IAAI,aAAa,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;AA8EzH,8EAA8E;AAC9E,qFAAqF;AACrF,8EAA8E;AAE9E,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC;;;;;KAKG;IACH,gGAAgG;IAChG,oHAAoH;CACrH,CAAC;AAEF,MAAM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