@substrat-run/adapter-cloudflare 0.215.0 → 0.216.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 (53) hide show
  1. package/dist/connection-sweep-do.d.ts +83 -0
  2. package/dist/connection-sweep-do.d.ts.map +1 -0
  3. package/dist/connection-sweep-do.js +89 -0
  4. package/dist/connection-sweep-do.js.map +1 -0
  5. package/dist/control-plane-do.d.ts +33 -42
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +91 -78
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/directory-mirror-apply.d.ts +59 -0
  10. package/dist/directory-mirror-apply.d.ts.map +1 -0
  11. package/dist/directory-mirror-apply.js +158 -0
  12. package/dist/directory-mirror-apply.js.map +1 -0
  13. package/dist/directory-mirror-claims.d.ts +77 -0
  14. package/dist/directory-mirror-claims.d.ts.map +1 -0
  15. package/dist/directory-mirror-claims.js +129 -0
  16. package/dist/directory-mirror-claims.js.map +1 -0
  17. package/dist/directory-mirror.d.ts +201 -0
  18. package/dist/directory-mirror.d.ts.map +1 -0
  19. package/dist/directory-mirror.js +557 -0
  20. package/dist/directory-mirror.js.map +1 -0
  21. package/dist/directory-objects.d.ts +24 -0
  22. package/dist/directory-objects.d.ts.map +1 -1
  23. package/dist/directory-objects.js +125 -1
  24. package/dist/directory-objects.js.map +1 -1
  25. package/dist/directory-placement.d.ts +17 -0
  26. package/dist/directory-placement.d.ts.map +1 -1
  27. package/dist/directory-placement.js +23 -2
  28. package/dist/directory-placement.js.map +1 -1
  29. package/dist/directory-split-inventory.d.ts +4 -1
  30. package/dist/directory-split-inventory.d.ts.map +1 -1
  31. package/dist/directory-split-inventory.js +7 -1
  32. package/dist/directory-split-inventory.js.map +1 -1
  33. package/dist/index.d.ts +1 -0
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +2 -0
  36. package/dist/index.js.map +1 -1
  37. package/dist/peer-call-target.d.ts +61 -0
  38. package/dist/peer-call-target.d.ts.map +1 -0
  39. package/dist/peer-call-target.js +98 -0
  40. package/dist/peer-call-target.js.map +1 -0
  41. package/dist/route-read-model-publisher.d.ts +29 -4
  42. package/dist/route-read-model-publisher.d.ts.map +1 -1
  43. package/dist/route-read-model-publisher.js +137 -3
  44. package/dist/route-read-model-publisher.js.map +1 -1
  45. package/dist/route-read-model.d.ts +75 -1
  46. package/dist/route-read-model.d.ts.map +1 -1
  47. package/dist/route-read-model.js +118 -0
  48. package/dist/route-read-model.js.map +1 -1
  49. package/dist/route-resolver.d.ts +33 -5
  50. package/dist/route-resolver.d.ts.map +1 -1
  51. package/dist/route-resolver.js +130 -70
  52. package/dist/route-resolver.js.map +1 -1
  53. package/package.json +8 -8
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The objects' half of the directory's dual-write (K-68 step 3b, `directory-mirror.ts`): apply a
3
+ * batch of changes the directory sent, each at most once and never backwards.
4
+ *
5
+ * - `directory_mirror_rows` holds, per (table, key), the version last applied and whether it was a
6
+ * delete. A change at that version or an older one is `stale` and skipped. A delete keeps its row
7
+ * as a TOMBSTONE, so an older copy of the row (a send still in flight, or 3c's backfill page read
8
+ * before the delete) cannot bring it back. Such a copy is seconds old, because every flush batch
9
+ * and backfill page takes its version when it reads, and a parked older change of the key is
10
+ * dropped when the delete applies. So a tombstone is kept `MIRROR_TOMBSTONE_MS` (a day) and then
11
+ * pruned, a bounded number per batch: without that, K-70's window prune of a log would leave a
12
+ * tombstone per pruned row, and the object would grow with tenants times time after all.
13
+ * - `directory_mirror_parked` holds a change the object's own schema refused, almost always a
14
+ * foreign key whose parent row the object does not hold yet: a write to a tenant that existed
15
+ * before the switch was turned on, whose `tenants` row only 3c's backfill brings. A parked change
16
+ * is tried again after any later batch that applied something (the parent may have arrived), and
17
+ * is dropped once a newer change of its key applies. It is never lost and never silent: 3d's
18
+ * comparison lists it, and `mirrorStatus` counts it.
19
+ *
20
+ * Each change is its own transaction, so one refused change never rolls back another, and a batch
21
+ * cut short by an eviction is resent whole and skips what it had already applied.
22
+ */
23
+ import type { MirrorApplyResult, MirrorBatch } from './directory-mirror.js';
24
+ import type { SwitchSql } from '@substrat-run/kernel';
25
+ export declare const MIRROR_TARGET_DDL: string[];
26
+ /** How long a tombstone is kept, and how many one batch prunes. */
27
+ export declare const MIRROR_TOMBSTONE_MS: number;
28
+ export declare const MIRROR_TOMBSTONE_PRUNE = 100;
29
+ /** Parked changes one batch tries again, oldest version first. */
30
+ export declare const MIRROR_PARKED_RETRY = 50;
31
+ export interface MirrorTarget {
32
+ sql: SqlStorage;
33
+ transaction: <T>(fn: () => T) => T;
34
+ /** The tables placed in this object; a change for any other is refused (parked). */
35
+ tables: ReadonlySet<string>;
36
+ now: () => number;
37
+ /** A tenant object: the registry's claims its rows make are recorded here (`directory-mirror-claims.ts`). */
38
+ claims?: {
39
+ kernelSql: SwitchSql;
40
+ owner: string;
41
+ };
42
+ }
43
+ export interface MirrorTargetStatus {
44
+ rows: number;
45
+ tombstones: number;
46
+ parked: number;
47
+ version: number | null;
48
+ /** The oldest parked changes, for 3d's report and staff. */
49
+ parkedSample: {
50
+ table: string;
51
+ key: string;
52
+ version: number;
53
+ error: string;
54
+ }[];
55
+ }
56
+ /** Apply a batch in order, then retry parked changes if anything applied. */
57
+ export declare function applyMirrorBatch(target: MirrorTarget, batch: MirrorBatch): MirrorApplyResult;
58
+ export declare function mirrorTargetStatus(sql: SqlStorage): MirrorTargetStatus;
59
+ //# sourceMappingURL=directory-mirror-apply.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directory-mirror-apply.d.ts","sourceRoot":"","sources":["../src/directory-mirror-apply.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,WAAW,EAA6B,MAAM,uBAAuB,CAAC;AAEvG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAGtD,eAAO,MAAM,iBAAiB,UAoB7B,CAAC;AAEF,mEAAmE;AACnE,eAAO,MAAM,mBAAmB,QAAsB,CAAC;AACvD,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAE1C,kEAAkE;AAClE,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAOtC,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,UAAU,CAAC;IAChB,WAAW,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;IACnC,oFAAoF;IACpF,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC5B,GAAG,EAAE,MAAM,MAAM,CAAC;IAClB,6GAA6G;IAC7G,MAAM,CAAC,EAAE;QAAE,SAAS,EAAE,SAAS,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;CAClD;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,4DAA4D;IAC5D,YAAY,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAChF;AAyFD,6EAA6E;AAC7E,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,GAAG,iBAAiB,CA+B5F;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,UAAU,GAAG,kBAAkB,CAatE"}
@@ -0,0 +1,158 @@
1
+ import { mirrorKeyColumns } from './directory-mirror.js';
2
+ import { CLAIMING_TABLES, mirrorClaimWork, recordMirrorClaims } from './directory-mirror-claims.js';
3
+ export const MIRROR_TARGET_DDL = [
4
+ `CREATE TABLE IF NOT EXISTS directory_mirror_rows (
5
+ tbl TEXT NOT NULL,
6
+ row_key TEXT NOT NULL,
7
+ version INTEGER NOT NULL,
8
+ deleted INTEGER NOT NULL,
9
+ at TEXT NOT NULL,
10
+ PRIMARY KEY (tbl, row_key)
11
+ ) WITHOUT ROWID`,
12
+ // Tombstones only, so a live row's write pays no index row; the prune reads it, never the table.
13
+ `CREATE INDEX IF NOT EXISTS directory_mirror_rows_tombstones ON directory_mirror_rows (at) WHERE deleted = 1`,
14
+ `CREATE TABLE IF NOT EXISTS directory_mirror_parked (
15
+ tbl TEXT NOT NULL,
16
+ row_key TEXT NOT NULL,
17
+ version INTEGER NOT NULL,
18
+ change TEXT NOT NULL,
19
+ error TEXT NOT NULL,
20
+ parked_at TEXT NOT NULL,
21
+ PRIMARY KEY (tbl, row_key)
22
+ ) WITHOUT ROWID`,
23
+ ];
24
+ /** How long a tombstone is kept, and how many one batch prunes. */
25
+ export const MIRROR_TOMBSTONE_MS = 24 * 60 * 60 * 1000;
26
+ export const MIRROR_TOMBSTONE_PRUNE = 100;
27
+ /** Parked changes one batch tries again, oldest version first. */
28
+ export const MIRROR_PARKED_RETRY = 50;
29
+ /** DO SQLite's bound-parameter limit per statement. */
30
+ const MAX_PARAMS = 100;
31
+ const quoteIdent = (name) => `"${name.replaceAll('"', '""')}"`;
32
+ const keyCache = new WeakMap();
33
+ function keysOf(sql, table) {
34
+ let byTable = keyCache.get(sql);
35
+ if (!byTable)
36
+ keyCache.set(sql, (byTable = new Map()));
37
+ let keys = byTable.get(table);
38
+ if (!keys)
39
+ byTable.set(table, (keys = mirrorKeyColumns(sql, table)));
40
+ return keys;
41
+ }
42
+ function keyWhere(sql, change) {
43
+ const keys = keysOf(sql, change.table);
44
+ const keyValues = JSON.parse(change.key);
45
+ if (keyValues.length !== keys.length)
46
+ throw new Error(`a key of ${keys.length} column(s) expected, got ${change.key}`);
47
+ return { keys, keyValues, where: keys.map((k) => (k === 'rowid' ? 'rowid = ?' : `${quoteIdent(k)} IS ?`)).join(' AND ') };
48
+ }
49
+ /** The object's row for a change's key, before the change. */
50
+ function readRow(sql, change) {
51
+ const { where, keyValues } = keyWhere(sql, change);
52
+ return sql.exec(`SELECT * FROM ${quoteIdent(change.table)} WHERE ${where}`, ...keyValues).toArray()[0] ?? null;
53
+ }
54
+ /** Write one change (row or delete) into its table. Throws what the schema refuses. */
55
+ function write(sql, change) {
56
+ const { where, keyValues } = keyWhere(sql, change);
57
+ const table = quoteIdent(change.table);
58
+ if (change.row === null)
59
+ return sql.exec(`DELETE FROM ${table} WHERE ${where}`, ...keyValues).rowsWritten;
60
+ const columns = Object.keys(change.row);
61
+ if (columns.length + keyValues.length > MAX_PARAMS) {
62
+ throw new Error(`${change.table} has ${columns.length} columns, over the ${MAX_PARAMS} parameters one statement may bind`);
63
+ }
64
+ const values = columns.map((c) => change.row[c]);
65
+ const exists = sql.exec(`SELECT 1 FROM ${table} WHERE ${where}`, ...keyValues).toArray().length > 0;
66
+ if (exists) {
67
+ const set = columns.filter((c) => c !== 'rowid');
68
+ if (set.length === 0)
69
+ return 0;
70
+ return sql.exec(`UPDATE ${table} SET ${set.map((c) => `${quoteIdent(c)} = ?`).join(', ')} WHERE ${where}`, ...set.map((c) => change.row[c]), ...keyValues).rowsWritten;
71
+ }
72
+ return sql.exec(`INSERT INTO ${table} (${columns.map((c) => (c === 'rowid' ? 'rowid' : quoteIdent(c))).join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`, ...values).rowsWritten;
73
+ }
74
+ function heldVersion(sql, change) {
75
+ const held = sql.exec('SELECT version FROM directory_mirror_rows WHERE tbl = ? AND row_key = ?', change.table, change.key).toArray()[0];
76
+ return held ? Number(held.version) : null;
77
+ }
78
+ /** One change, at `version`, in its own transaction; refused writes are parked in another. */
79
+ function applyOne(target, change, version) {
80
+ const { sql } = target;
81
+ try {
82
+ return target.transaction(() => {
83
+ const held = heldVersion(sql, change);
84
+ if (held !== null && held >= version) {
85
+ // A parked change a newer one has overtaken is settled too.
86
+ const dropped = sql.exec('DELETE FROM directory_mirror_parked WHERE tbl = ? AND row_key = ? AND version <= ?', change.table, change.key, held).rowsWritten;
87
+ return { kind: 'stale', rowsWritten: dropped };
88
+ }
89
+ if (!target.tables.has(change.table))
90
+ throw new Error(`${change.table} is not placed in this object`);
91
+ const claims = target.claims && CLAIMING_TABLES.has(change.table) ? target.claims : null;
92
+ const before = claims ? readRow(sql, change) : null;
93
+ let rowsWritten = write(sql, change);
94
+ // In the same transaction as the row: the crossing's intent, or the release (rfc §7.3).
95
+ if (claims)
96
+ recordMirrorClaims({ sql, kernelSql: claims.kernelSql, owner: claims.owner, nowMs: target.now() }, change, before, version);
97
+ rowsWritten += sql.exec(`INSERT INTO directory_mirror_rows (tbl, row_key, version, deleted, at) VALUES (?, ?, ?, ?, ?)
98
+ ON CONFLICT (tbl, row_key) DO UPDATE SET version = excluded.version, deleted = excluded.deleted, at = excluded.at`, change.table, change.key, version, change.row === null ? 1 : 0, new Date(target.now()).toISOString()).rowsWritten;
99
+ rowsWritten += sql.exec('DELETE FROM directory_mirror_parked WHERE tbl = ? AND row_key = ? AND version <= ?', change.table, change.key, version).rowsWritten;
100
+ return { kind: 'applied', rowsWritten };
101
+ });
102
+ }
103
+ catch (err) {
104
+ const error = String(err?.message ?? err).slice(0, 500);
105
+ const rowsWritten = target.transaction(() => sql.exec(`INSERT INTO directory_mirror_parked (tbl, row_key, version, change, error, parked_at) VALUES (?, ?, ?, ?, ?, ?)
106
+ ON CONFLICT (tbl, row_key) DO UPDATE SET version = excluded.version, change = excluded.change, error = excluded.error, parked_at = excluded.parked_at
107
+ WHERE excluded.version >= directory_mirror_parked.version`, change.table, change.key, version, JSON.stringify(change), error, new Date(target.now()).toISOString()).rowsWritten);
108
+ return { kind: 'parked', rowsWritten, error };
109
+ }
110
+ }
111
+ /** Apply a batch in order, then retry parked changes if anything applied. */
112
+ export function applyMirrorBatch(target, batch) {
113
+ if (!Number.isSafeInteger(batch.version) || batch.version < 1)
114
+ throw new Error(`directory mirror: not a version: ${batch.version}`);
115
+ const out = { applied: 0, stale: 0, parked: 0, healed: 0, rowsWritten: 0 };
116
+ const parkedNow = new Set();
117
+ for (const change of batch.changes) {
118
+ const r = applyOne(target, change, batch.version);
119
+ out.rowsWritten += r.rowsWritten;
120
+ out[r.kind] += 1;
121
+ if (r.kind === 'parked')
122
+ parkedNow.add(`${change.table}\u0000${change.key}`);
123
+ }
124
+ if (out.applied > 0) {
125
+ const before = new Date(target.now() - MIRROR_TOMBSTONE_MS).toISOString();
126
+ out.rowsWritten += target.transaction(() => target.sql.exec(`DELETE FROM directory_mirror_rows WHERE (tbl, row_key) IN (
127
+ SELECT tbl, row_key FROM directory_mirror_rows WHERE deleted = 1 AND at < ? ORDER BY at LIMIT ?)`, before, MIRROR_TOMBSTONE_PRUNE).rowsWritten);
128
+ const parked = target.sql
129
+ .exec('SELECT tbl, row_key, version, change FROM directory_mirror_parked ORDER BY version, tbl, row_key LIMIT ?', MIRROR_PARKED_RETRY)
130
+ .toArray();
131
+ for (const p of parked) {
132
+ if (parkedNow.has(`${p.tbl}\u0000${p.row_key}`))
133
+ continue;
134
+ const r = applyOne(target, JSON.parse(p.change), Number(p.version));
135
+ out.rowsWritten += r.rowsWritten;
136
+ if (r.kind === 'applied')
137
+ out.healed += 1;
138
+ }
139
+ }
140
+ if (target.claims)
141
+ out.claims = mirrorClaimWork(target.sql, target.claims.kernelSql, target.claims.owner);
142
+ return out;
143
+ }
144
+ export function mirrorTargetStatus(sql) {
145
+ const rows = sql.exec('SELECT COUNT(*) AS n, COALESCE(SUM(deleted), 0) AS d, MAX(version) AS v FROM directory_mirror_rows').one();
146
+ const parked = Number(sql.exec('SELECT COUNT(*) AS n FROM directory_mirror_parked').one().n);
147
+ const sample = sql
148
+ .exec('SELECT tbl, row_key, version, error FROM directory_mirror_parked ORDER BY version LIMIT 20')
149
+ .toArray();
150
+ return {
151
+ rows: Number(rows.n) - Number(rows.d),
152
+ tombstones: Number(rows.d),
153
+ parked,
154
+ version: rows.v === null ? null : Number(rows.v),
155
+ parkedSample: sample.map((p) => ({ table: p.tbl, key: p.row_key, version: Number(p.version), error: p.error })),
156
+ };
157
+ }
158
+ //# sourceMappingURL=directory-mirror-apply.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directory-mirror-apply.js","sourceRoot":"","sources":["../src/directory-mirror-apply.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAEpG,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B;;;;;;;mBAOiB;IACjB,iGAAiG;IACjG,6GAA6G;IAC7G;;;;;;;;mBAQiB;CAClB,CAAC;AAEF,mEAAmE;AACnE,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACvD,MAAM,CAAC,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAE1C,kEAAkE;AAClE,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAEtC,uDAAuD;AACvD,MAAM,UAAU,GAAG,GAAG,CAAC;AAEvB,MAAM,UAAU,GAAG,CAAC,IAAY,EAAU,EAAE,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC;AAuB/E,MAAM,QAAQ,GAAG,IAAI,OAAO,EAAqC,CAAC;AAClE,SAAS,MAAM,CAAC,GAAe,EAAE,KAAa;IAC5C,IAAI,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChC,IAAI,CAAC,OAAO;QAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,OAAO,GAAG,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC;IACvD,IAAI,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC9B,IAA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,CAAC"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The registry's claims, dual-written (K-68 step 3b, part 2; rfc/tenant-scale.md §7.3).
3
+ *
4
+ * The directory decides every uniqueness today (a tenant id, a slug, a hostname) and keeps deciding
5
+ * it until 3e. After the split the REGISTRY holds those keys, claimed through the intent-first
6
+ * crossing (`@substrat-run/kernel`'s `directory-crossing`). So the dual-write copies the claims too,
7
+ * through that same helper, in the order §7.3 gives: the tenant's object, which decides, records the
8
+ * crossing in the same transaction as the row that makes it; host code then claims and confirms in
9
+ * the registry, and the object settles.
10
+ *
11
+ * What makes a claim, in a TENANT object (the registry's own copy of a row makes none):
12
+ * - a `tenants` row the object did not hold: `tenant-id` and `tenant-slug` claims. A slug is never
13
+ * changed (no directory path updates it), so the slug claim's id is fixed per tenant;
14
+ * - a `tenants` row moving to `reaped` (or arriving reaped): release the slug, tombstone the id, so an
15
+ * id is never reused (§7.3);
16
+ * - a `hostnames` row the object did not hold: a `hostname` claim, its id unique per binding;
17
+ * - a `hostnames` row deleted: release that binding's claim.
18
+ *
19
+ * A release is recorded in `directory_mirror_releases` beside the row that causes it, and dropped
20
+ * only once the registry released it, or once nothing was claimed under its id (its crossing failed,
21
+ * or was settled and the claim is gone).
22
+ *
23
+ * A release of a key that must become FREE (a hostname, a slug) also settles the crossing it releases
24
+ * `failed`, in the same transaction, if that crossing is still open. Otherwise an open crossing whose
25
+ * claim reached the registry before it was marked `claimed` could be released and then run again:
26
+ * it would find no claim, claim afresh and confirm it, and the registry would hold a key for good
27
+ * that its tenant no longer has. Settled, it never claims again; a claim a crashed runner left is
28
+ * removed by the release, or, if only leased, lapses with its lease. A TOMBSTONE release (a reaped
29
+ * tenant's id) leaves its crossing open on purpose: the crossing may still make the claim the
30
+ * tombstone needs, and a claim made after the tombstone is refused by it.
31
+ *
32
+ * Because the directory already decided, a claim the registry refuses is a difference, not a
33
+ * decision: the crossing settles `failed` with the refusal, the row is applied regardless, and 3d's
34
+ * comparison reports it. The usual cause is a hostname moved between tenants whose release had not
35
+ * reached the registry yet; the flush runs every release before any claim to make that rare.
36
+ */
37
+ import { type ClaimNamespace, type SwitchSql } from '@substrat-run/kernel';
38
+ import type { MirrorChange, MirrorValue } from './directory-mirror.js';
39
+ export declare const MIRROR_CLAIMS_DDL: string[];
40
+ /** How much open claim work one apply hands back to the sender. */
41
+ export declare const MIRROR_CLAIM_WORK_MAX = 20;
42
+ export interface MirrorRelease {
43
+ namespace: ClaimNamespace;
44
+ key: string;
45
+ claimId: string;
46
+ tombstone: boolean;
47
+ }
48
+ /** An object's open claim work, handed back with every apply so a later send retries it. */
49
+ export interface MirrorClaimWork {
50
+ crossings: string[];
51
+ releases: MirrorRelease[];
52
+ }
53
+ export declare const tenantIdCrossingOf: (tenantId: string) => string;
54
+ export declare const tenantSlugCrossingOf: (tenantId: string) => string;
55
+ type Row = Record<string, MirrorValue>;
56
+ /** The tables whose rows make claims, and so need the row before the change. */
57
+ export declare const CLAIMING_TABLES: ReadonlySet<string>;
58
+ /**
59
+ * Record the claim work one applied change makes, inside the transaction that applied it. `before`
60
+ * is the object's row before the change, `change.row` after it (null for a delete).
61
+ */
62
+ export declare function recordMirrorClaims(target: {
63
+ sql: SqlStorage;
64
+ kernelSql: SwitchSql;
65
+ owner: string;
66
+ nowMs: number;
67
+ }, change: MirrorChange, before: Row | null, version: number): void;
68
+ /** The object's open claim work, bounded: crossings not yet settled, releases not yet done. */
69
+ export declare function mirrorClaimWork(sql: SqlStorage, kernelSql: SwitchSql, owner: string): MirrorClaimWork;
70
+ /**
71
+ * After the registry answered a release: drop it once it was released, or once nothing will ever be
72
+ * claimed under its id (its crossing is settled, or was never recorded). Kept while its crossing is
73
+ * open, so the claim that crossing is about to make is still released. True when it was dropped.
74
+ */
75
+ export declare function settleMirrorReleaseIn(sql: SqlStorage, kernelSql: SwitchSql, owner: string, release: MirrorRelease, released: boolean): boolean;
76
+ export {};
77
+ //# sourceMappingURL=directory-mirror-claims.d.ts.map
@@ -0,0 +1 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AC,GAAG,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,eAAe,CASrG;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAS9I"}
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The registry's claims, dual-written (K-68 step 3b, part 2; rfc/tenant-scale.md §7.3).
3
+ *
4
+ * The directory decides every uniqueness today (a tenant id, a slug, a hostname) and keeps deciding
5
+ * it until 3e. After the split the REGISTRY holds those keys, claimed through the intent-first
6
+ * crossing (`@substrat-run/kernel`'s `directory-crossing`). So the dual-write copies the claims too,
7
+ * through that same helper, in the order §7.3 gives: the tenant's object, which decides, records the
8
+ * crossing in the same transaction as the row that makes it; host code then claims and confirms in
9
+ * the registry, and the object settles.
10
+ *
11
+ * What makes a claim, in a TENANT object (the registry's own copy of a row makes none):
12
+ * - a `tenants` row the object did not hold: `tenant-id` and `tenant-slug` claims. A slug is never
13
+ * changed (no directory path updates it), so the slug claim's id is fixed per tenant;
14
+ * - a `tenants` row moving to `reaped` (or arriving reaped): release the slug, tombstone the id, so an
15
+ * id is never reused (§7.3);
16
+ * - a `hostnames` row the object did not hold: a `hostname` claim, its id unique per binding;
17
+ * - a `hostnames` row deleted: release that binding's claim.
18
+ *
19
+ * A release is recorded in `directory_mirror_releases` beside the row that causes it, and dropped
20
+ * only once the registry released it, or once nothing was claimed under its id (its crossing failed,
21
+ * or was settled and the claim is gone).
22
+ *
23
+ * A release of a key that must become FREE (a hostname, a slug) also settles the crossing it releases
24
+ * `failed`, in the same transaction, if that crossing is still open. Otherwise an open crossing whose
25
+ * claim reached the registry before it was marked `claimed` could be released and then run again:
26
+ * it would find no claim, claim afresh and confirm it, and the registry would hold a key for good
27
+ * that its tenant no longer has. Settled, it never claims again; a claim a crashed runner left is
28
+ * removed by the release, or, if only leased, lapses with its lease. A TOMBSTONE release (a reaped
29
+ * tenant's id) leaves its crossing open on purpose: the crossing may still make the claim the
30
+ * tombstone needs, and a claim made after the tombstone is refused by it.
31
+ *
32
+ * Because the directory already decided, a claim the registry refuses is a difference, not a
33
+ * decision: the crossing settles `failed` with the refusal, the row is applied regardless, and 3d's
34
+ * comparison reports it. The usual cause is a hostname moved between tenants whose release had not
35
+ * reached the registry yet; the flush runs every release before any claim to make that rare.
36
+ */
37
+ import { crossingIn, openCrossingsIn, recordCrossingIn, settleCrossingIn, } from '@substrat-run/kernel';
38
+ export const MIRROR_CLAIMS_DDL = [
39
+ `CREATE TABLE IF NOT EXISTS directory_mirror_releases (
40
+ namespace TEXT NOT NULL,
41
+ claim_key TEXT NOT NULL,
42
+ claim_id TEXT NOT NULL,
43
+ tombstone INTEGER NOT NULL,
44
+ recorded_at TEXT NOT NULL,
45
+ PRIMARY KEY (namespace, claim_key, claim_id)
46
+ ) WITHOUT ROWID`,
47
+ ];
48
+ /** How much open claim work one apply hands back to the sender. */
49
+ export const MIRROR_CLAIM_WORK_MAX = 20;
50
+ export const tenantIdCrossingOf = (tenantId) => `mirror:tenant-id:${tenantId}`;
51
+ export const tenantSlugCrossingOf = (tenantId) => `mirror:tenant-slug:${tenantId}`;
52
+ const hostnameCrossingOf = (hostname, version) => `mirror:hostname:${hostname}:${version}`;
53
+ function recordRelease(target, release, at) {
54
+ // A key that must become free: its crossing may not claim it once this release exists (header).
55
+ if (!release.tombstone) {
56
+ settleCrossingIn(target.kernelSql, target.owner, release.claimId, { state: 'failed', outcome: 'released before it settled', nowMs: target.nowMs });
57
+ }
58
+ target.sql.exec(`INSERT OR IGNORE INTO directory_mirror_releases (namespace, claim_key, claim_id, tombstone, recorded_at) VALUES (?, ?, ?, ?, ?)`, release.namespace, release.key, release.claimId, release.tombstone ? 1 : 0, at);
59
+ }
60
+ /** The tables whose rows make claims, and so need the row before the change. */
61
+ export const CLAIMING_TABLES = new Set(['tenants', 'hostnames']);
62
+ /**
63
+ * Record the claim work one applied change makes, inside the transaction that applied it. `before`
64
+ * is the object's row before the change, `change.row` after it (null for a delete).
65
+ */
66
+ export function recordMirrorClaims(target, change, before, version) {
67
+ const after = change.row;
68
+ const at = new Date(target.nowMs).toISOString();
69
+ const record = (input) => recordCrossingIn(target.kernelSql, target.owner, input);
70
+ if (change.table === 'tenants') {
71
+ const tenantId = String((after ?? before)?.['tenant_id'] ?? '');
72
+ if (!tenantId)
73
+ return;
74
+ const slug = String((after ?? before)?.['slug'] ?? '');
75
+ if (after && !before) {
76
+ record({ crossingId: tenantIdCrossingOf(tenantId), kind: 'mirror-tenant-create', namespace: 'tenant-id', key: tenantId, holder: tenantId, jurisdiction: 'global', nowMs: target.nowMs });
77
+ record({ crossingId: tenantSlugCrossingOf(tenantId), kind: 'mirror-tenant-create', namespace: 'tenant-slug', key: slug, holder: tenantId, nowMs: target.nowMs });
78
+ }
79
+ const reapedNow = after?.['status'] === 'reaped' && before?.['status'] !== 'reaped';
80
+ if (reapedNow || (!after && before)) {
81
+ recordRelease(target, { namespace: 'tenant-slug', key: slug, claimId: tenantSlugCrossingOf(tenantId), tombstone: false }, at);
82
+ recordRelease(target, { namespace: 'tenant-id', key: tenantId, claimId: tenantIdCrossingOf(tenantId), tombstone: true }, at);
83
+ }
84
+ return;
85
+ }
86
+ if (change.table === 'hostnames') {
87
+ if (after && !before) {
88
+ const hostname = String(after['hostname']);
89
+ record({
90
+ crossingId: hostnameCrossingOf(hostname, version), kind: 'mirror-hostname-bind', namespace: 'hostname', key: hostname,
91
+ holder: String(after['tenant_id']), scopeId: after['scope_id'] ?? null, nowMs: target.nowMs,
92
+ });
93
+ }
94
+ else if (!after && before) {
95
+ const hostname = String(before['hostname']);
96
+ const held = target.sql
97
+ .exec(`SELECT crossing_id FROM _substrat_directory_crossings WHERE owner = ? AND namespace = 'hostname' AND claim_key = ?
98
+ ORDER BY created_at DESC, crossing_id DESC LIMIT 1`, target.owner, hostname)
99
+ .toArray()[0];
100
+ if (held)
101
+ recordRelease(target, { namespace: 'hostname', key: hostname, claimId: held.crossing_id, tombstone: false }, at);
102
+ }
103
+ }
104
+ }
105
+ /** The object's open claim work, bounded: crossings not yet settled, releases not yet done. */
106
+ export function mirrorClaimWork(sql, kernelSql, owner) {
107
+ const crossings = openCrossingsIn(kernelSql, owner, { updatedBefore: '9999-12-31T23:59:59.999Z', limit: MIRROR_CLAIM_WORK_MAX })
108
+ .filter((c) => c.crossingId.startsWith('mirror:'))
109
+ .map((c) => c.crossingId);
110
+ const releases = sql
111
+ .exec(`SELECT namespace, claim_key, claim_id, tombstone FROM directory_mirror_releases ORDER BY recorded_at, claim_id LIMIT ?`, MIRROR_CLAIM_WORK_MAX)
112
+ .toArray()
113
+ .map((r) => ({ namespace: r.namespace, key: r.claim_key, claimId: r.claim_id, tombstone: r.tombstone === 1 }));
114
+ return { crossings, releases };
115
+ }
116
+ /**
117
+ * After the registry answered a release: drop it once it was released, or once nothing will ever be
118
+ * claimed under its id (its crossing is settled, or was never recorded). Kept while its crossing is
119
+ * open, so the claim that crossing is about to make is still released. True when it was dropped.
120
+ */
121
+ export function settleMirrorReleaseIn(sql, kernelSql, owner, release, released) {
122
+ const crossing = crossingIn(kernelSql, owner, release.claimId);
123
+ const open = crossing !== null && (crossing.state === 'intent' || crossing.state === 'claimed');
124
+ if (!released && open)
125
+ return false;
126
+ sql.exec(`DELETE FROM directory_mirror_releases WHERE namespace = ? AND claim_key = ? AND claim_id = ?`, release.namespace, release.key, release.claimId);
127
+ return true;
128
+ }
129
+ //# sourceMappingURL=directory-mirror-claims.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directory-mirror-claims.js","sourceRoot":"","sources":["../src/directory-mirror-claims.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,EACL,UAAU,EACV,eAAe,EACf,gBAAgB,EAChB,gBAAgB,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