@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
@@ -10,6 +10,10 @@ import { autoAdmittedProdRefusal, listedPromoteRefusal, opsFailureReferenceWhere
10
10
  import { canonicalInstant } from '@substrat-run/kernel';
11
11
  import { doBuiltColumnsOf, doRedactionSql } from './sql.js';
12
12
  import { ROUTE_READ_MODEL_TABLE_GLOB, RouteReadModelPublisher, routeKvWriterOf, uninstallRouteReadModel, } from './route-read-model-publisher.js';
13
+ import { readPeerCallTarget } from './peer-call-target.js';
14
+ // K-68 step 3b: the directory's dual-write to the registry and the tenant objects (off by default).
15
+ import { DIRECTORY_MIRROR_TABLE_GLOB, directoryMirrorFor, isDirectoryMirrorTable } from './directory-mirror.js';
16
+ import { durableMirrorSender } from './directory-objects.js';
13
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';
14
18
  /**
15
19
  * The router's per-request directory read (`readRoute`), lifted out so its plan can be asked for
@@ -994,8 +998,32 @@ export class ControlPlaneDO extends DurableObject {
994
998
  this.kernelSql = switchSqlOver(this.sql);
995
999
  this.applyDirectorySchema();
996
1000
  this.installRouteReadModel(routeKvWriterOf(Reflect.get(env, 'ROUTES')));
1001
+ this.directoryMirror = directoryMirrorFor(env, durableMirrorSender(env), {
1002
+ sql: this.sql,
1003
+ transaction: (fn) => ctx.storage.transactionSync(fn),
1004
+ quiet: () => this.routeCallDepth === 0,
1005
+ armRetry: async (at) => {
1006
+ const current = await ctx.storage.getAlarm();
1007
+ if (current === null || current > at)
1008
+ await ctx.storage.setAlarm(at);
1009
+ },
1010
+ });
997
1011
  this.backfillArmed = ctx.blockConcurrencyWhile(() => this.armVersionMigrationsBackfill());
998
1012
  }
1013
+ // -- K-68 step 3b: the dual-write to the split's objects (directory-mirror.ts) -----
1014
+ /** Set where `DIRECTORY_MIRROR` is on and the two object namespaces are bound; null otherwise. */
1015
+ directoryMirror;
1016
+ /** Flush what the outbox holds. Called when the outermost method returns, like the route kick. */
1017
+ kickDirectoryMirror() {
1018
+ this.directoryMirror?.kick();
1019
+ }
1020
+ /** Drain the outbox now, for a caller (and a test) that must see the copy land. */
1021
+ async settleDirectoryMirror() {
1022
+ return this.directoryMirror ? this.directoryMirror.settle() : null;
1023
+ }
1024
+ directoryMirrorStatus() {
1025
+ return this.directoryMirror ? this.directoryMirror.status() : { enabled: false };
1026
+ }
999
1027
  // -- the routing read model (#3395) -------------------------------------------
1000
1028
  /** Set where a `ROUTES` KV namespace is bound; null otherwise, and the read model is off. */
1001
1029
  routePublisher = null;
@@ -1227,6 +1255,8 @@ export class ControlPlaneDO extends DurableObject {
1227
1255
  // #3395: the routing read model's retry. It lifts the backoff (and redoes a failed namespace
1228
1256
  // check); the flush itself starts when this alarm returns, as after any directory method.
1229
1257
  await this.retryRouteReadModel().catch((err) => console.error('route read model: retry failed', err));
1258
+ // K-68 step 3b: the dual-write's retry after a send an object refused.
1259
+ this.directoryMirror?.retry();
1230
1260
  let more;
1231
1261
  try {
1232
1262
  more = this.ctx.storage.transactionSync(() => splitVersionMigrationsBatch(this.kernelSql)).more;
@@ -1646,6 +1676,10 @@ export class ControlPlaneDO extends DurableObject {
1646
1676
  */
1647
1677
  async exportDumpPage(cursor, opts = {}) {
1648
1678
  const maxBytes = opts.maxBytes ?? SCOPE_DUMP_PAGE_MAX_BYTES;
1679
+ // #3422: a copy whose pass was cut off leaves its whole snapshot here. Dropped inside the
1680
+ // snapshot's own transaction, it doubled that transaction, which then failed every retry.
1681
+ if (cursor === null)
1682
+ await this.dropLeftoverSnapshot();
1649
1683
  const taken = cursor === null ? this.snapshotDirectory(opts.byReference ?? 'off') : null;
1650
1684
  // Right after the snapshot's transaction: the storage call holds this object's input gate, so
1651
1685
  // no write lands between the copy's instant and the bookmark's.
@@ -1781,9 +1815,10 @@ export class ControlPlaneDO extends DurableObject {
1781
1815
  return this.sql.exec(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`, COPY_TABLE).toArray().length > 0;
1782
1816
  }
1783
1817
  /**
1784
- * Copy every dumped table into a fresh snapshot (#2868), replacing any a copy left unfinished,
1785
- * and return the cursor of its first page and how many tables it holds. One synchronous
1786
- * transaction, so no write lands between two tables' reads.
1818
+ * Copy every dumped table into a fresh snapshot (#2868), and return the cursor of its first page
1819
+ * and how many tables it holds. One synchronous transaction, so no write lands between two
1820
+ * tables' reads. A snapshot a copy left unfinished is dropped before it (`dropLeftoverSnapshot`,
1821
+ * #3422); the drop here only catches one a concurrent first page made in between.
1787
1822
  *
1788
1823
  * #3325: under `on`, a by-reference table is not copied; its horizon (largest rowid) and row
1789
1824
  * count are recorded instead, which costs no row written. Under `verify` it is copied as before,
@@ -1825,6 +1860,21 @@ export class ControlPlaneDO extends DurableObject {
1825
1860
  return { cursor: { copyId, ord: 0, after: 0 }, tables: defs.length };
1826
1861
  });
1827
1862
  }
1863
+ /**
1864
+ * #3422: drop the snapshot a copy left unfinished, one table per turn. Writes with no `await`
1865
+ * between them commit as one transaction, so each drop is followed by a timer, which ends the turn
1866
+ * and commits it. The snapshot's own transaction then has nothing left to drop. A failed
1867
+ * snapshot rolls back only its own writes, so the leftover stays gone.
1868
+ */
1869
+ async dropLeftoverSnapshot() {
1870
+ const tables = this.sql
1871
+ .exec(`SELECT name FROM sqlite_master WHERE type = 'table' AND name GLOB ?`, COPY_GLOB)
1872
+ .toArray();
1873
+ for (const { name } of tables) {
1874
+ this.sql.exec(`DROP TABLE IF EXISTS "${name}"`);
1875
+ await new Promise((resolve) => setTimeout(resolve, 0));
1876
+ }
1877
+ }
1828
1878
  dropDirectorySnapshot() {
1829
1879
  const tables = this.sql
1830
1880
  .exec(`SELECT name FROM sqlite_master WHERE type = 'table' AND name GLOB ?`, COPY_GLOB)
@@ -1841,10 +1891,12 @@ export class ControlPlaneDO extends DurableObject {
1841
1891
  return this.sql
1842
1892
  .exec(`SELECT name, sql FROM sqlite_master
1843
1893
  WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_cf_*'
1844
- AND name NOT GLOB ? AND name NOT GLOB ? AND sql IS NOT NULL
1894
+ AND name NOT GLOB ? AND name NOT GLOB ? AND name NOT GLOB ? AND sql IS NOT NULL
1845
1895
  ORDER BY name`, COPY_GLOB,
1846
1896
  // #3395: the read model's ledger describes KV, not the directory (route-read-model-publisher.ts).
1847
- ROUTE_READ_MODEL_TABLE_GLOB)
1897
+ ROUTE_READ_MODEL_TABLE_GLOB,
1898
+ // K-68 step 3b: the dual-write's queue and version describe the objects (directory-mirror.ts).
1899
+ DIRECTORY_MIRROR_TABLE_GLOB)
1848
1900
  .toArray();
1849
1901
  }
1850
1902
  /**
@@ -1875,7 +1927,7 @@ export class ControlPlaneDO extends DurableObject {
1875
1927
  // #3395: the routing read model's tables describe KV, survive a restore, and are never in a dump
1876
1928
  // this code exported. One a dump names (in any case: SQLite's names are) is crafted, and loading
1877
1929
  // it would make the ledger lie about what KV holds.
1878
- const routeTable = tables.find((t) => t.name.toLowerCase().startsWith('route_read_model_'));
1930
+ const routeTable = tables.find((t) => t.name.toLowerCase().startsWith('route_read_model_') || isDirectoryMirrorTable(t.name));
1879
1931
  if (routeTable) {
1880
1932
  throw substratError('validation_failed', `refusing this dump: it names ${routeTable.name}, a table no directory dump carries`);
1881
1933
  }
@@ -1888,7 +1940,9 @@ export class ControlPlaneDO extends DurableObject {
1888
1940
  // restore does not change, and the re-publish below needs it to delete what KV no longer may.
1889
1941
  const existing = this.sql
1890
1942
  .exec(`SELECT name FROM sqlite_master
1891
- WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_cf_*' AND name NOT GLOB ?`, ROUTE_READ_MODEL_TABLE_GLOB)
1943
+ 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,
1944
+ // K-68 step 3b: the dual-write's version must never go back, so its tables survive too.
1945
+ DIRECTORY_MIRROR_TABLE_GLOB)
1892
1946
  .toArray();
1893
1947
  for (const { name } of existing)
1894
1948
  this.sql.exec(`DROP TABLE IF EXISTS "${name}"`);
@@ -1924,6 +1978,11 @@ export class ControlPlaneDO extends DurableObject {
1924
1978
  // #3395: every key the restored directory routes, and every key KV was given before it —
1925
1979
  // a route the restored directory does not hold is deleted, not left serving.
1926
1980
  this.routePublisher?.markAll();
1981
+ // K-68 step 3b: the triggers went with the tables. Back AFTER the load, so the restore writes
1982
+ // what it wrote before; the objects now differ from the restored directory, which is recorded
1983
+ // for 3c's backfill to fill again, not sent row by row.
1984
+ this.directoryMirror?.install();
1985
+ this.directoryMirror?.markRestored();
1927
1986
  });
1928
1987
  // A restore is a new #1764 backfill episode. It replaced the data the old failure count and
1929
1988
  // backoff were about, so neither may delay or silence it: the count is cleared and the next
@@ -2795,78 +2854,28 @@ export class ControlPlaneDO extends DurableObject {
2795
2854
  return { ok: true, changed: true, previous };
2796
2855
  }
2797
2856
  /**
2798
- * Everything the router needs to place ONE peer call (#1706), in one round trip: the
2799
- * CALLER's own scope record, and the target instance of `vertical` in that tenant with the
2800
- * script and dispatch parameters that instance runs under.
2857
+ * Everything the router needs to place ONE peer call (#1706), in one round trip: the CALLER's
2858
+ * own scope record, and the target instance of `vertical` in that tenant with the script and
2859
+ * dispatch parameters that instance runs under (`readPeerCallTarget`, which the routing read
2860
+ * model publishes from too).
2801
2861
  *
2802
- * One directory RPC and two SQL reads, because this sits on a request path. The binding
2803
- * and the tenant's slug join the caller read, so even an unbound singleton adds no round
2804
- * trip. The caller's record is what decides whether it may call at all — live, primary, and
2805
- * the vertical it claims — and it is read HERE rather than inferred from routing, so this
2806
- * path does not inherit #1713.
2807
- * The target side applies the kernel's one rule (`resolvePeerInstanceFrom`), the same
2808
- * rule the pure host and the local broker apply.
2862
+ * `publish` (#3395, K-72) is the router's read-model miss: a dispatchable answer is queued for
2863
+ * publishing unless it is published already. A directory that predates it ignores the argument.
2864
+ * The answer is the same either way.
2809
2865
  */
2810
- peerCallTarget(tenantId, callerScopeId, callerVertical, vertical) {
2811
- const caller = this.sql
2812
- .exec(`SELECT s.tenant_id, s.vertical, s.status, s.kind, s.forked_from,
2813
- t.status AS tenant_status, pb.target_scope_id AS bound_target_scope_id,
2814
- pb.invalidated AS binding_invalidated,
2815
- (SELECT slug FROM tenants WHERE tenant_id = ?) AS peer_tenant_slug
2816
- FROM scopes s
2817
- LEFT JOIN tenants t ON t.tenant_id = s.tenant_id
2818
- LEFT JOIN peer_bindings pb ON pb.tenant_id = s.tenant_id
2819
- AND pb.caller_scope_id = s.scope_id AND pb.vertical = ?
2820
- WHERE s.scope_id = ?`, tenantId, vertical, callerScopeId)
2821
- .toArray()[0];
2822
- // No caller row is refused below ('unknown'); its candidates are then read exactly.
2823
- const tenant = { id: tenantId, slug: caller?.peer_tenant_slug ?? null };
2824
- const candidates = this.sql
2825
- .exec(`SELECT s.scope_id, s.tenant_id, s.vertical, s.status, s.kind, s.forked_from,
2826
- COALESCE(s.serving_ref, vv.deployment_ref) AS deployment_ref,
2827
- CASE WHEN s.serving_ref IS NOT NULL
2828
- THEN json_extract(sv.manifest_json, '$.outbound')
2829
- ELSE json_extract(vv.manifest_json, '$.outbound') END AS outbound_json,
2830
- CASE WHEN s.serving_ref IS NOT NULL
2831
- THEN json_extract(sv.manifest_json, '$.calls')
2832
- ELSE json_extract(vv.manifest_json, '$.calls') END AS calls_json
2833
- FROM scopes s
2834
- LEFT JOIN vertical_versions vv ON vv.id = s.vertical_version_id
2835
- LEFT JOIN verticals vr ON vr.slug = s.vertical
2836
- LEFT JOIN vertical_versions sv ON sv.id = vr.serving_version_id
2837
- WHERE s.tenant_id = ? AND s.vertical IN (SELECT value FROM json_each(?))`, tenantId, JSON.stringify(peerVerticalSpellings(vertical, tenant.slug)))
2838
- .toArray();
2839
- const resolution = resolvePeerInstanceFrom(candidates.map((r) => ({
2840
- id: r.scope_id,
2841
- tenantId: r.tenant_id,
2842
- vertical: r.vertical,
2843
- status: r.status,
2844
- kind: r.kind ?? '',
2845
- forkedFrom: r.forked_from ?? null,
2846
- })), tenant, vertical, caller?.bound_target_scope_id ?? null, caller?.binding_invalidated === 1);
2847
- const target = resolution.outcome === 'resolved'
2848
- ? (candidates.find((r) => r.scope_id === resolution.instance.scopeId) ?? null)
2849
- : null;
2850
- // The caller's own state, decided HERE — this DO already applies the kernel's one rule
2851
- // for the target, and the router must not carry a second copy of "what is primary".
2852
- const callerState = !caller || caller.tenant_id !== tenantId || !samePeerVertical(caller.vertical, callerVertical, tenant.slug)
2853
- ? 'unknown'
2854
- : !isPrimaryScopeRow(caller)
2855
- ? 'not-primary'
2856
- : caller.status !== 'active' || caller.tenant_status !== 'active'
2857
- ? 'inactive'
2858
- : 'ok';
2859
- return {
2860
- caller: {
2861
- state: callerState,
2862
- status: caller?.tenant_status !== 'active' ? `tenant ${caller?.tenant_status ?? 'unknown'}` : caller.status,
2863
- // The directory's own, for the tenant this call was authenticated in.
2864
- tenantSlug: tenant.slug,
2865
- },
2866
- outcome: resolution.outcome,
2867
- count: resolution.outcome === 'ambiguous' ? resolution.count : 0,
2868
- target,
2869
- };
2866
+ peerCallTarget(tenantId, callerScopeId, callerVertical, vertical, opts) {
2867
+ const read = readPeerCallTarget(this.sql, tenantId, callerScopeId, callerVertical, vertical);
2868
+ if (opts?.publish === true && this.routePublisher) {
2869
+ // Optional, as `readRoute`'s: a fill that cannot be queued must not fail a read that succeeded.
2870
+ // This method's own return starts the flush (`kickRouteReadModelAfterEveryCall`).
2871
+ try {
2872
+ this.routePublisher.requestPeerPublish({ tenantId, callerScopeId, callerVertical, vertical }, read);
2873
+ }
2874
+ catch (err) {
2875
+ console.error('route read model: could not queue a peer-call miss for publishing', err);
2876
+ }
2877
+ }
2878
+ return read.row;
2870
2879
  }
2871
2880
  /**
2872
2881
  * Request-path gate: only an active hostname, correctly paired active scope and active
@@ -5540,6 +5549,8 @@ const ROUTE_KICK_EXEMPT = new Set([
5540
5549
  // The retry path: its own return must not start a flush, or a failure is retried at once rather than
5541
5550
  // after `ROUTE_PUBLISH_RETRY_MS`; the alarm starts it (`retryRouteReadModel`).
5542
5551
  'armRouteReadModelRetry', 'retryRouteReadModel',
5552
+ // K-68 step 3b: the dual-write's flush is kicked by the same return, and drives itself.
5553
+ 'kickDirectoryMirror', 'settleDirectoryMirror',
5543
5554
  ]);
5544
5555
  for (const name of Object.getOwnPropertyNames(ControlPlaneDO.prototype)) {
5545
5556
  if (ROUTE_KICK_EXEMPT.has(name))
@@ -5555,8 +5566,10 @@ for (const name of Object.getOwnPropertyNames(ControlPlaneDO.prototype)) {
5555
5566
  // transaction (`bumpLifecycleRevision` within `writeAndAudit`) must not start a flush there.
5556
5567
  const leave = () => {
5557
5568
  this.routeCallDepth -= 1;
5558
- if (this.routeCallDepth === 0)
5569
+ if (this.routeCallDepth === 0) {
5559
5570
  this.kickRouteReadModel();
5571
+ this.kickDirectoryMirror();
5572
+ }
5560
5573
  };
5561
5574
  this.routeCallDepth += 1;
5562
5575
  let out;