@substrat-run/adapter-cloudflare 0.217.0 → 0.219.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 (59) hide show
  1. package/dist/broker-lake.d.ts +19 -0
  2. package/dist/broker-lake.d.ts.map +1 -0
  3. package/dist/broker-lake.js +20 -0
  4. package/dist/broker-lake.js.map +1 -0
  5. package/dist/control-plane-do.d.ts +82 -5
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +276 -25
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +43 -6
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +85 -9
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/delivery-broker-platform.d.ts +52 -0
  14. package/dist/delivery-broker-platform.d.ts.map +1 -0
  15. package/dist/delivery-broker-platform.js +77 -0
  16. package/dist/delivery-broker-platform.js.map +1 -0
  17. package/dist/delivery-handoff.d.ts +22 -0
  18. package/dist/delivery-handoff.d.ts.map +1 -1
  19. package/dist/delivery-handoff.js +19 -0
  20. package/dist/delivery-handoff.js.map +1 -1
  21. package/dist/directory-restore-chunks.d.ts +16 -0
  22. package/dist/directory-restore-chunks.d.ts.map +1 -0
  23. package/dist/directory-restore-chunks.js +31 -0
  24. package/dist/directory-restore-chunks.js.map +1 -0
  25. package/dist/directory-split-inventory.d.ts +2 -2
  26. package/dist/directory-split-inventory.d.ts.map +1 -1
  27. package/dist/directory-split-inventory.js +5 -4
  28. package/dist/directory-split-inventory.js.map +1 -1
  29. package/dist/host.d.ts +7 -3
  30. package/dist/host.d.ts.map +1 -1
  31. package/dist/host.js +44 -3
  32. package/dist/host.js.map +1 -1
  33. package/dist/index.d.ts +2 -1
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +3 -1
  36. package/dist/index.js.map +1 -1
  37. package/dist/kick-coalescer-do.d.ts.map +1 -1
  38. package/dist/kick-coalescer-do.js +5 -4
  39. package/dist/kick-coalescer-do.js.map +1 -1
  40. package/dist/scope-do.d.ts +8 -1
  41. package/dist/scope-do.d.ts.map +1 -1
  42. package/dist/scope-do.js +154 -32
  43. package/dist/scope-do.js.map +1 -1
  44. package/dist/scope-wake.d.ts +5 -0
  45. package/dist/scope-wake.d.ts.map +1 -1
  46. package/dist/scope-wake.js +2 -1
  47. package/dist/scope-wake.js.map +1 -1
  48. package/dist/scope-work.d.ts +1 -1
  49. package/dist/scope-work.js +1 -1
  50. package/dist/scope-work.js.map +1 -1
  51. package/dist/sql.d.ts +2 -2
  52. package/dist/sql.d.ts.map +1 -1
  53. package/dist/sql.js +11 -10
  54. package/dist/sql.js.map +1 -1
  55. package/dist/supplied-delivery-broker.d.ts +35 -0
  56. package/dist/supplied-delivery-broker.d.ts.map +1 -0
  57. package/dist/supplied-delivery-broker.js +55 -0
  58. package/dist/supplied-delivery-broker.js.map +1 -0
  59. package/package.json +9 -9
@@ -14,7 +14,7 @@ import { readPeerCallTarget } from './peer-call-target.js';
14
14
  // K-68 step 3b: the directory's dual-write to the registry and the tenant objects (off by default).
15
15
  import { DIRECTORY_MIRROR_TABLE_GLOB, directoryMirrorFor, isDirectoryMirrorTable } from './directory-mirror.js';
16
16
  import { durableMirrorSender } from './directory-objects.js';
17
- import { assertReplayableDump, AUTO_ADMISSION_NOTE, instant, opsFailureFingerprint, ROUTE_SCOPE_HOSTNAMES_MAX, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_GATE_REASONS, substratError } from '@substrat-run/contracts';
17
+ import { assertReplayableDump, AUTO_ADMISSION_NOTE, instant, isRuntimeTable, opsFailureFingerprint, ROUTE_SCOPE_HOSTNAMES_MAX, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_GATE_REASONS, substratError } from '@substrat-run/contracts';
18
18
  /**
19
19
  * The router's per-request directory read (`readRoute`), lifted out so its plan can be asked for
20
20
  * (#2005): the scope's hostname set is a correlated subquery on the hot path every request takes,
@@ -938,6 +938,10 @@ export const REPLIED_METHODS = [
938
938
  'beginStoreDriverRolloutAndAudit',
939
939
  'finishStoreDriverRolloutAndAudit',
940
940
  'importDumpAndAudit',
941
+ // #3494: the paged restore's three steps.
942
+ 'stageRestorePage',
943
+ 'commitStagedRestoreAndAudit',
944
+ 'discardStagedRestore',
941
945
  'registerIdentityPoolAndAudit',
942
946
  'insertConnectionAndAudit',
943
947
  'updateConnectionSecretAndAudit',
@@ -971,6 +975,53 @@ const COPY_GLOB = '_directory_copy*';
971
975
  const COPY_TABLE = '_directory_copy';
972
976
  const COPY_TABLES_TABLE = '_directory_copy_tables';
973
977
  const copyRowsTable = (ord) => `_directory_copy_rows_${ord}`;
978
+ /**
979
+ * A paged restore's stage (#3494): `_directory_restore` names the restore and the next page it
980
+ * takes, `_directory_restore_tables` lists the staged tables (each one's DDL, columns and row count
981
+ * as the copy's pages carried them), and `_directory_restore_rows_<ord>` holds each table's rows,
982
+ * untyped, so every cell is kept as it arrived. A copy of today's directory is far larger than one
983
+ * RPC (32 MiB) or an isolate (128 MB), so its pages are staged one call at a time and the restore
984
+ * then loads from here in one transaction. This store's own, never its data: no dump carries it,
985
+ * a dump naming it is refused, and the restore's drops leave it to the load that reads it.
986
+ */
987
+ const RESTORE_GLOB = '_directory_restore*';
988
+ const RESTORE_TABLE = '_directory_restore';
989
+ const RESTORE_TABLES_TABLE = '_directory_restore_tables';
990
+ const restoreRowsTable = (ord) => `_directory_restore_rows_${ord}`;
991
+ /**
992
+ * How long a stage holds off another restore's first page, counted from its last page. A restore
993
+ * stages its pages back to back, seconds apart, so a stage idle this long was abandoned (its caller
994
+ * cut off or gone), and the next restore may replace it: an operator retrying a restore that was
995
+ * cut off waits minutes, not hours.
996
+ */
997
+ export const RESTORE_STAGE_MAX_AGE_MS = 15 * 60_000;
998
+ /** The most staged rows a restore's load reads at a time: one batch is held, never a table. */
999
+ const RESTORE_READ_BATCH = 200;
1000
+ /** The most bytes of cells one batch of staged rows holds; a single larger row is read alone. */
1001
+ const RESTORE_READ_BATCH_BYTES = 8 * 1024 * 1024;
1002
+ /** The refusal of a restore whose stage is not (or no longer) the one this directory holds. */
1003
+ export const RESTORE_STAGE_GONE = 'this directory restore is no longer staged here: another restore replaced it, or it was discarded';
1004
+ /** The refusal of a second restore while one is being staged. */
1005
+ export const RESTORE_STAGE_IN_PROGRESS = 'another directory restore is being staged here; retry when it has finished or expired';
1006
+ /** A restore without `overwrite` meeting a directory that holds tenants: the route's own words. */
1007
+ export const RESTORE_OVERWRITE_REFUSAL = 'the directory is not empty — a restore REPLACES it, so anything created since this copy was taken would be lost; pass overwrite=true to confirm';
1008
+ /**
1009
+ * What either restore holds a dump's tables to before it touches anything (#1143, #3395, #3494):
1010
+ * names that reach SQL as identifiers and a `ddl` of one CREATE TABLE, and no table this store
1011
+ * keeps for itself. The routing read model's tables describe KV, the dual-write's describe the
1012
+ * objects, and a restore's stage is the restore's own: none is in a dump this code exported, so
1013
+ * one a dump names (in any case: SQLite's names are) is crafted. Pure validation: a refused dump
1014
+ * touches nothing.
1015
+ */
1016
+ function assertLoadableDirectoryDump(tables) {
1017
+ assertReplayableDump(tables, { maxColumns: DO_SQL_LIMITS.columns });
1018
+ const own = tables.find((t) => {
1019
+ const name = t.name.toLowerCase();
1020
+ return name.startsWith('route_read_model_') || isDirectoryMirrorTable(t.name) || name.startsWith(RESTORE_TABLE);
1021
+ });
1022
+ if (own)
1023
+ throw substratError('validation_failed', `refusing this dump: it names ${own.name}, a table no directory dump carries`);
1024
+ }
974
1025
  /**
975
1026
  * How many rows a dump page reads at a time. Small, because a batch is held whole before the byte
976
1027
  * cap is asked: `vertical_versions` keeps every pushed manifest, and a few hundred of them would
@@ -1034,6 +1085,8 @@ export class ControlPlaneDO extends DurableObject {
1034
1085
  // -- the routing read model (#3395) -------------------------------------------
1035
1086
  /** Set where a `ROUTES` KV namespace is bound; null otherwise, and the read model is off. */
1036
1087
  routePublisher = null;
1088
+ /** #3494: the restore stage's cleanup in flight, which every stage door awaits (`dropRestoreStage`). */
1089
+ restoreCleanup = Promise.resolve();
1037
1090
  routeFlushing = null;
1038
1091
  routeFlushAgain = false;
1039
1092
  /**
@@ -1898,21 +1951,24 @@ export class ControlPlaneDO extends DurableObject {
1898
1951
  this.sql.exec(`DROP TABLE IF EXISTS "${name}"`);
1899
1952
  }
1900
1953
  /**
1901
- * The tables a dump carries, by name. Not `_cf_*` either: workerd's own tables (the #1764
1954
+ * The tables a dump carries, by name. Not the runtime's own (`isRuntimeTable`; the #1764
1902
1955
  * backfill's alarm creates `_cf_METADATA`), which are not the directory's and which it refuses
1903
1956
  * to drop on restore. Nor the routing read model's (#3395), which record what KV holds.
1904
1957
  */
1905
1958
  dumpTableDefs() {
1906
1959
  return this.sql
1907
1960
  .exec(`SELECT name, sql FROM sqlite_master
1908
- WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_cf_*'
1909
- AND name NOT GLOB ? AND name NOT GLOB ? AND name NOT GLOB ? AND sql IS NOT NULL
1961
+ WHERE type = 'table' AND name NOT GLOB 'sqlite_*'
1962
+ AND name NOT GLOB ? AND name NOT GLOB ? AND name NOT GLOB ? AND name NOT GLOB ? AND sql IS NOT NULL
1910
1963
  ORDER BY name`, COPY_GLOB,
1911
1964
  // #3395: the read model's ledger describes KV, not the directory (route-read-model-publisher.ts).
1912
1965
  ROUTE_READ_MODEL_TABLE_GLOB,
1913
1966
  // K-68 step 3b: the dual-write's queue and version describe the objects (directory-mirror.ts).
1914
- DIRECTORY_MIRROR_TABLE_GLOB)
1915
- .toArray();
1967
+ DIRECTORY_MIRROR_TABLE_GLOB,
1968
+ // #3494: a restore being staged is the next directory, not this one.
1969
+ RESTORE_GLOB)
1970
+ .toArray()
1971
+ .filter(({ name }) => !isRuntimeTable(name));
1916
1972
  }
1917
1973
  /**
1918
1974
  * Replace the directory with a dump — the break-glass write half (#40).
@@ -1934,33 +1990,39 @@ export class ControlPlaneDO extends DurableObject {
1934
1990
  * directory as it was.
1935
1991
  */
1936
1992
  async importDump(tables, audit) {
1937
- // Same untrusted dump, same two holes as the scope path (#1143): names reaching SQL as
1938
- // identifiers, and a `ddl` that is never executed here but is still held to one CREATE
1939
- // TABLE. Pure input validation, so it runs before the first DROP: a refused dump touches
1940
- // nothing.
1941
- assertReplayableDump(tables, { maxColumns: DO_SQL_LIMITS.columns });
1942
- // #3395: the routing read model's tables describe KV, survive a restore, and are never in a dump
1943
- // this code exported. One a dump names (in any case: SQLite's names are) is crafted, and loading
1944
- // it would make the ledger lie about what KV holds.
1945
- const routeTable = tables.find((t) => t.name.toLowerCase().startsWith('route_read_model_') || isDirectoryMirrorTable(t.name));
1946
- if (routeTable) {
1947
- throw substratError('validation_failed', `refusing this dump: it names ${routeTable.name}, a table no directory dump carries`);
1948
- }
1993
+ assertLoadableDirectoryDump(tables);
1994
+ await this.loadDump(tables, audit);
1995
+ }
1996
+ /**
1997
+ * The load both restores run (#3494): `importDump`'s, over rows handed in whole, and
1998
+ * `commitStagedRestore`'s, over rows read from the stage a batch at a time. The tables have
1999
+ * been held to `assertLoadableDirectoryDump` before they reach it.
2000
+ */
2001
+ async loadDump(tables, audit, opts = {}) {
1949
2002
  await this.ctx.storage.transaction(async () => {
2003
+ // #3494: the paged restore's consent, judged in the unit that replaces the directory. Its pages
2004
+ // took a while to stage, and a tenant created meanwhile is not one anyone agreed to drop.
2005
+ if (opts.requireEmpty && this.sql.exec('SELECT 1 FROM tenants LIMIT 1').toArray().length > 0) {
2006
+ throw substratError('conflict', RESTORE_OVERWRITE_REFUSAL);
2007
+ }
1950
2008
  // #1713: the epoch this directory was in, read before the drops take it.
1951
2009
  const epochBefore = this.lifecycleEpoch();
1952
2010
  this.sql.exec('PRAGMA defer_foreign_keys = ON');
1953
- // `_cf_*` is workerd's, and dropping it is refused (SQLITE_AUTH), as `exportDump` says.
2011
+ // The runtime's own tables stay: dropping one is refused (SQLITE_AUTH), as `exportDump` says.
1954
2012
  // The routing read model's ledger survives too (#3395): it says what KV holds, which the
1955
2013
  // restore does not change, and the re-publish below needs it to delete what KV no longer may.
1956
2014
  const existing = this.sql
1957
2015
  .exec(`SELECT name FROM sqlite_master
1958
- WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_cf_*' AND name NOT GLOB ? AND name NOT GLOB ?`, ROUTE_READ_MODEL_TABLE_GLOB,
2016
+ WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB ? AND name NOT GLOB ?
2017
+ AND name NOT GLOB ?`, ROUTE_READ_MODEL_TABLE_GLOB,
1959
2018
  // K-68 step 3b: the dual-write's version must never go back, so its tables survive too.
1960
- DIRECTORY_MIRROR_TABLE_GLOB)
2019
+ DIRECTORY_MIRROR_TABLE_GLOB,
2020
+ // #3494: a staged restore is read by this very load, so its stage outlives the drops.
2021
+ RESTORE_GLOB)
1961
2022
  .toArray();
1962
2023
  for (const { name } of existing)
1963
- this.sql.exec(`DROP TABLE IF EXISTS "${name}"`);
2024
+ if (!isRuntimeTable(name))
2025
+ this.sql.exec(`DROP TABLE IF EXISTS "${name}"`);
1964
2026
  // Every table from this code's DDL, onto an empty directory, so none of the pass's
1965
2027
  // rebuilds fires (each would reach `transactionSync`, which this async transaction cannot
1966
2028
  // hold): every table is created on the current shape.
@@ -2015,6 +2077,192 @@ export class ControlPlaneDO extends DurableObject {
2015
2077
  console.error('substrat: the restore committed, but its version-migrations backfill was not armed', err);
2016
2078
  }
2017
2079
  }
2080
+ // -- paged restore (#3494) ----------------------------------------------------
2081
+ /**
2082
+ * Stage one page of a directory copy for `commitStagedRestoreAndAudit` (#3494). A copy of today's
2083
+ * directory is hundreds of megabytes, and one RPC carries 32 MiB, so a restore hands its pages
2084
+ * over one call at a time. The rows go into this store's own stage tables, untyped, so every cell
2085
+ * is kept as it arrived; nothing of the directory is touched until the commit.
2086
+ *
2087
+ * Pages arrive in order from 0. A page already staged answers `staged: false` and changes
2088
+ * nothing, so a retried page is harmless; one that skips ahead is refused. A table's DDL and
2089
+ * columns are held to what its first page carried, since a copy is of one instant. Page 0 of
2090
+ * another restore is refused while this stage is being written to; a stage left idle for
2091
+ * `RESTORE_STAGE_MAX_AGE_MS` was abandoned, and is dropped for the new one.
2092
+ */
2093
+ async stageRestorePage(stageId, seq, tables) {
2094
+ if (typeof stageId !== 'string' || stageId.length === 0)
2095
+ throw substratError('validation_failed', 'a restore stage needs an id');
2096
+ if (!Number.isSafeInteger(seq) || seq < 0)
2097
+ throw substratError('validation_failed', 'a restore page is numbered from 0');
2098
+ // The identifiers reach SQL below as text, so they are held to the replay rules first.
2099
+ assertLoadableDirectoryDump(tables);
2100
+ await this.restoreCleanup;
2101
+ const held = this.restoreHead();
2102
+ if (seq === 0 && held?.stageId !== stageId) {
2103
+ if (held && Date.now() - Date.parse(held.touchedAt) <= RESTORE_STAGE_MAX_AGE_MS) {
2104
+ throw substratError('conflict', RESTORE_STAGE_IN_PROGRESS);
2105
+ }
2106
+ // What an abandoned restore staged can be a whole directory: dropped a table a turn (#3422),
2107
+ // never inside the transaction that opens the new stage.
2108
+ await this.dropRestoreStage();
2109
+ this.ctx.storage.transactionSync(() => {
2110
+ this.sql.exec(`CREATE TABLE ${RESTORE_TABLE} (stage_id TEXT NOT NULL, next_seq INTEGER NOT NULL, touched_at TEXT NOT NULL)`);
2111
+ this.sql.exec(`CREATE TABLE ${RESTORE_TABLES_TABLE} (ord INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, ddl TEXT NOT NULL,
2112
+ columns TEXT NOT NULL, row_count INTEGER NOT NULL)`);
2113
+ this.sql.exec(`INSERT INTO ${RESTORE_TABLE} (stage_id, next_seq, touched_at) VALUES (?, 0, ?)`, stageId, new Date().toISOString());
2114
+ });
2115
+ }
2116
+ return this.ctx.storage.transactionSync(() => {
2117
+ const head = this.restoreHead();
2118
+ if (head?.stageId !== stageId)
2119
+ throw substratError('precondition_failed', RESTORE_STAGE_GONE);
2120
+ if (seq < head.nextSeq)
2121
+ return { staged: false };
2122
+ if (seq > head.nextSeq)
2123
+ throw substratError('precondition_failed', `restore page ${seq} arrived before page ${head.nextSeq}`);
2124
+ for (const t of tables) {
2125
+ const columns = JSON.stringify(t.columns);
2126
+ const found = this.sql
2127
+ .exec(`SELECT ord, ddl, columns FROM ${RESTORE_TABLES_TABLE} WHERE name = ?`, t.name)
2128
+ .toArray()[0];
2129
+ let ord;
2130
+ if (!found) {
2131
+ ord = Number(this.sql.exec(`SELECT COUNT(*) AS n FROM ${RESTORE_TABLES_TABLE}`).one().n);
2132
+ this.sql.exec(`INSERT INTO ${RESTORE_TABLES_TABLE} (ord, name, ddl, columns, row_count) VALUES (?, ?, ?, ?, 0)`, ord, t.name, t.ddl, columns);
2133
+ // Untyped columns: no affinity, so a cell is stored exactly as it came.
2134
+ this.sql.exec(`CREATE TABLE "${restoreRowsTable(ord)}" (${t.columns.map((_, i) => `c${i}`).join(', ')})`);
2135
+ }
2136
+ else if (found.ddl !== t.ddl || found.columns !== columns) {
2137
+ throw substratError('precondition_failed', `table ${t.name} changed between the copy's pages; nothing more was staged`);
2138
+ }
2139
+ else {
2140
+ ord = Number(found.ord);
2141
+ }
2142
+ const insert = `INSERT INTO "${restoreRowsTable(ord)}" VALUES (${t.columns.map(() => '?').join(', ')})`;
2143
+ for (const row of t.rows) {
2144
+ if (row.length !== t.columns.length) {
2145
+ throw substratError('validation_failed', `a row of ${t.name} holds ${row.length} cells for ${t.columns.length} columns`);
2146
+ }
2147
+ this.sql.exec(insert, ...row);
2148
+ }
2149
+ this.sql.exec(`UPDATE ${RESTORE_TABLES_TABLE} SET row_count = row_count + ? WHERE ord = ?`, t.rows.length, ord);
2150
+ }
2151
+ this.sql.exec(`UPDATE ${RESTORE_TABLE} SET next_seq = ?, touched_at = ?`, seq + 1, new Date().toISOString());
2152
+ return { staged: true };
2153
+ });
2154
+ }
2155
+ /**
2156
+ * Replace the directory with the copy staged under `stageId` (#3494): `importDump`'s load, its
2157
+ * rows read from the stage a batch at a time rather than handed over whole, in the same one
2158
+ * transaction with the same refusals, epoch and audit row. `overwrite` is the caller's consent to
2159
+ * replace a directory holding tenants; without it one that holds any is refused (`conflict`)
2160
+ * inside that transaction, before the first drop. A refused or failed load leaves the
2161
+ * directory as it was, and keeps the stage. The stage is dropped after the load commits, a table
2162
+ * a turn: dropped inside it, it would be a second directory's worth of work in the one unit.
2163
+ */
2164
+ async commitStagedRestore(stageId, audit, opts = {}) {
2165
+ await this.restoreCleanup;
2166
+ if (this.restoreHead()?.stageId !== stageId)
2167
+ throw substratError('precondition_failed', RESTORE_STAGE_GONE);
2168
+ const staged = this.sql
2169
+ .exec(`SELECT ord, name, ddl, columns, row_count FROM ${RESTORE_TABLES_TABLE} ORDER BY ord`)
2170
+ .toArray();
2171
+ const tables = staged.map((t) => ({
2172
+ name: t.name,
2173
+ ddl: t.ddl,
2174
+ columns: JSON.parse(t.columns),
2175
+ rows: this.stagedRestoreRows(Number(t.ord), Number(t.row_count), JSON.parse(t.columns).length),
2176
+ }));
2177
+ assertLoadableDirectoryDump(tables);
2178
+ // Without `overwrite`, a directory that holds a tenant now is refused, and the stage kept.
2179
+ await this.loadDump(tables, audit, { requireEmpty: opts.overwrite !== true });
2180
+ try {
2181
+ await this.dropRestoreStage();
2182
+ }
2183
+ catch (err) {
2184
+ // The restore has committed; a stage left behind is dropped by the next restore's first page.
2185
+ console.error('substrat: the directory restore committed, but its stage was not dropped', err);
2186
+ }
2187
+ return { tables: tables.length, rows: tables.reduce((n, t) => n + t.rows.length, 0) };
2188
+ }
2189
+ /** Drop the stage of a restore that gave up (#3494), if it is still `stageId`'s. */
2190
+ async discardStagedRestore(stageId) {
2191
+ await this.restoreCleanup;
2192
+ if (this.restoreHead()?.stageId !== stageId)
2193
+ return { discarded: false };
2194
+ await this.dropRestoreStage();
2195
+ return { discarded: true };
2196
+ }
2197
+ /** The restore this directory has staged (#3494), or null. */
2198
+ restoreHead() {
2199
+ const present = this.sql.exec(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`, RESTORE_TABLE).toArray();
2200
+ if (present.length === 0)
2201
+ return null;
2202
+ const row = this.sql.exec(`SELECT stage_id, next_seq, touched_at FROM ${RESTORE_TABLE}`).toArray()[0];
2203
+ return row ? { stageId: row.stage_id, nextSeq: Number(row.next_seq), touchedAt: row.touched_at } : null;
2204
+ }
2205
+ /**
2206
+ * Drop a restore's stage, one table per turn (#3422's reason: a stage can hold a whole directory).
2207
+ * The head first, so a drop cut off part-way leaves no stage that refuses the next restore, only
2208
+ * rows tables its first page drops.
2209
+ *
2210
+ * Each drop yields a turn, and another call can run in it, so drops are chained on
2211
+ * `restoreCleanup` and every stage door awaits that before it reads the head: a new stage is never
2212
+ * opened while an earlier cleanup still holds a list of tables to drop.
2213
+ */
2214
+ dropRestoreStage() {
2215
+ const run = this.restoreCleanup.then(() => this.dropRestoreStageTables());
2216
+ this.restoreCleanup = run.catch(() => undefined);
2217
+ return run;
2218
+ }
2219
+ async dropRestoreStageTables() {
2220
+ const tables = this.sql
2221
+ .exec(`SELECT name FROM sqlite_master WHERE type = 'table' AND name GLOB ? ORDER BY name = ? DESC, name`, RESTORE_GLOB, RESTORE_TABLE)
2222
+ .toArray();
2223
+ for (const { name } of tables) {
2224
+ this.sql.exec(`DROP TABLE IF EXISTS "${name}"`);
2225
+ await new Promise((resolve) => setTimeout(resolve, 0));
2226
+ }
2227
+ }
2228
+ /**
2229
+ * One staged table's rows, in the order they were staged, a batch at a time (#3494). A batch is
2230
+ * bounded by bytes as well as rows: a staged `vertical_versions` row is a whole pushed manifest,
2231
+ * so 200 of them could be more than the isolate. Each batch's rows are sized in SQLite first
2232
+ * (rowids and lengths only), then read up to `RESTORE_READ_BATCH_BYTES`; a single larger row is
2233
+ * read alone. Each iteration reads from the start, so the rows can be walked more than once.
2234
+ */
2235
+ stagedRestoreRows(ord, count, columns) {
2236
+ const sql = this.sql;
2237
+ const table = `"${restoreRowsTable(ord)}"`;
2238
+ const size = Array.from({ length: columns }, (_, i) => `COALESCE(LENGTH(CAST(c${i} AS BLOB)), 0)`).join(' + ') || '0';
2239
+ return {
2240
+ length: count,
2241
+ *[Symbol.iterator]() {
2242
+ let after = 0;
2243
+ for (;;) {
2244
+ const sized = sql
2245
+ .exec(`SELECT rowid AS r, ${size} AS b FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT ?`, after, RESTORE_READ_BATCH)
2246
+ .toArray();
2247
+ if (sized.length === 0)
2248
+ return;
2249
+ let upTo = Number(sized[0].r);
2250
+ let bytes = Number(sized[0].b);
2251
+ for (const { r, b } of sized.slice(1)) {
2252
+ if (bytes + Number(b) > RESTORE_READ_BATCH_BYTES)
2253
+ break;
2254
+ bytes += Number(b);
2255
+ upTo = Number(r);
2256
+ }
2257
+ // Read whole before yielding: the load writes between yields, and no cursor is held open across them.
2258
+ const batch = Array.from(sql.exec(`SELECT * FROM ${table} WHERE rowid > ? AND rowid <= ? ORDER BY rowid`, after, upTo).raw(), (row) => row);
2259
+ for (const row of batch)
2260
+ yield row;
2261
+ after = upTo;
2262
+ }
2263
+ },
2264
+ };
2265
+ }
2018
2266
  // -- tenant registry (control-plane.md §4.1) --------------------------------
2019
2267
  mapTenant(r) {
2020
2268
  return {
@@ -2164,12 +2412,12 @@ export class ControlPlaneDO extends DurableObject {
2164
2412
  * Every table the schema holds is counted, read off `sqlite_master` rather than a list
2165
2413
  * here, so a table nobody remembered writing is counted too. That is the point: before a
2166
2414
  * directory is retired, a table with rows and no owner is the thing to find. The
2167
- * platform's own `_cf_*` tables and SQLite's are not the directory's and are skipped.
2415
+ * runtime's own tables and SQLite's are not the directory's and are skipped.
2168
2416
  */
2169
2417
  directoryInventory() {
2170
2418
  const names = this.sql
2171
- .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\' ORDER BY name")
2172
- .toArray().map((r) => r.name);
2419
+ .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name")
2420
+ .toArray().map((r) => r.name).filter((name) => !isRuntimeTable(name));
2173
2421
  const tables = names.map((table) => ({
2174
2422
  table,
2175
2423
  // The name is the schema's own, never input; quoted as an identifier all the same.
@@ -3491,6 +3739,9 @@ export class ControlPlaneDO extends DurableObject {
3491
3739
  importDumpAndAudit(...args) {
3492
3740
  return this.importDump(...args);
3493
3741
  }
3742
+ commitStagedRestoreAndAudit(...args) {
3743
+ return this.commitStagedRestore(...args);
3744
+ }
3494
3745
  registerIdentityPoolAndAudit(...args) {
3495
3746
  return this.registerIdentityPool(...args);
3496
3747
  }