@substrat-run/adapter-cloudflare 0.213.0 → 0.215.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 (45) hide show
  1. package/dist/control-plane-do.d.ts +89 -6
  2. package/dist/control-plane-do.d.ts.map +1 -1
  3. package/dist/control-plane-do.js +310 -12
  4. package/dist/control-plane-do.js.map +1 -1
  5. package/dist/directory-split-inventory.d.ts +2 -2
  6. package/dist/directory-split-inventory.d.ts.map +1 -1
  7. package/dist/directory-split-inventory.js +8 -2
  8. package/dist/directory-split-inventory.js.map +1 -1
  9. package/dist/host.d.ts +5 -2
  10. package/dist/host.d.ts.map +1 -1
  11. package/dist/host.js +46 -2
  12. package/dist/host.js.map +1 -1
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +3 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/kick-coalescer-do.d.ts +13 -3
  18. package/dist/kick-coalescer-do.d.ts.map +1 -1
  19. package/dist/kick-coalescer-do.js +20 -6
  20. package/dist/kick-coalescer-do.js.map +1 -1
  21. package/dist/reconcile-on-wake.d.ts +35 -0
  22. package/dist/reconcile-on-wake.d.ts.map +1 -0
  23. package/dist/reconcile-on-wake.js +75 -0
  24. package/dist/reconcile-on-wake.js.map +1 -0
  25. package/dist/route-read-model-publisher.d.ts +171 -0
  26. package/dist/route-read-model-publisher.d.ts.map +1 -0
  27. package/dist/route-read-model-publisher.js +524 -0
  28. package/dist/route-read-model-publisher.js.map +1 -0
  29. package/dist/route-read-model.d.ts +166 -0
  30. package/dist/route-read-model.d.ts.map +1 -0
  31. package/dist/route-read-model.js +195 -0
  32. package/dist/route-read-model.js.map +1 -0
  33. package/dist/route-resolver.d.ts +41 -3
  34. package/dist/route-resolver.d.ts.map +1 -1
  35. package/dist/route-resolver.js +58 -3
  36. package/dist/route-resolver.js.map +1 -1
  37. package/dist/scope-do.d.ts +8 -0
  38. package/dist/scope-do.d.ts.map +1 -1
  39. package/dist/scope-do.js +133 -6
  40. package/dist/scope-do.js.map +1 -1
  41. package/dist/scope-wake.d.ts +127 -0
  42. package/dist/scope-wake.d.ts.map +1 -0
  43. package/dist/scope-wake.js +204 -0
  44. package/dist/scope-wake.js.map +1 -0
  45. package/package.json +9 -9
@@ -9,6 +9,7 @@ import { COPY_BACKFILL_SCOPE_SQL, COPY_BACKFILL_SQL, COPY_BACKFILL_SUPERSEDE_SQL
9
9
  import { autoAdmittedProdRefusal, listedPromoteRefusal, opsFailureReferenceWhere } from '@substrat-run/kernel';
10
10
  import { canonicalInstant } from '@substrat-run/kernel';
11
11
  import { doBuiltColumnsOf, doRedactionSql } from './sql.js';
12
+ import { ROUTE_READ_MODEL_TABLE_GLOB, RouteReadModelPublisher, routeKvWriterOf, uninstallRouteReadModel, } from './route-read-model-publisher.js';
12
13
  import { assertReplayableDump, AUTO_ADMISSION_NOTE, instant, opsFailureFingerprint, ROUTE_SCOPE_HOSTNAMES_MAX, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_GATE_REASONS, substratError } from '@substrat-run/contracts';
13
14
  /**
14
15
  * The router's per-request directory read (`readRoute`), lifted out so its plan can be asked for
@@ -802,7 +803,12 @@ const SCOPE_COLUMNS_ADDED = [
802
803
  */
803
804
  export function planDirectoryDdl(ddl) {
804
805
  const all = executableSqlStatements(ddl);
805
- const afterColumns = executableSqlStatements(VERSION_MIGRATIONS_DDL);
806
+ // The sweep-runs dedupe index names `request_id` (#1232) and `kind` (#1572). On a directory whose
807
+ // `_substrat_sweep_runs` predates `request_id`, the loop meets the index before
808
+ // `ensureDirectoryColumns` adds the column: "no such column: request_id", on every construction,
809
+ // so the column is never added and the directory never starts again (the test directory, from
810
+ // 2026-09-07, #3395). Held back to run once the columns exist.
811
+ const afterColumns = [...executableSqlStatements(VERSION_MIGRATIONS_DDL), ...executableSqlStatements(SWEEP_RUNS_INTENT_INDEX)];
806
812
  const held = new Set(afterColumns);
807
813
  return {
808
814
  loop: all.filter((stmt) => !held.has(stmt)),
@@ -813,7 +819,7 @@ export function planDirectoryDdl(ddl) {
813
819
  /** Refuses a plan whose held-back statements the DDL does not carry; returns it otherwise. */
814
820
  export function assertDirectoryDdlPlan(plan) {
815
821
  if (plan.missing.length > 0) {
816
- throw new Error(`the directory DDL does not carry ${plan.missing.length} statement(s) of VERSION_MIGRATIONS_DDL — ` +
822
+ throw new Error(`the directory DDL does not carry ${plan.missing.length} statement(s) it holds back until the columns exist (VERSION_MIGRATIONS_DDL, the sweep-runs index) — ` +
817
823
  `interpolate the fragment whole: ${plan.missing[0]}`);
818
824
  }
819
825
  return plan;
@@ -823,6 +829,8 @@ export function assertDirectoryDdlPlan(plan) {
823
829
  * control-plane request goes through, so batches are spaced rather than run back to back.
824
830
  */
825
831
  const BACKFILL_PAUSE_MS = 1000;
832
+ /** #3395: how soon a routing read model publish that KV refused is tried again. */
833
+ export const ROUTE_PUBLISH_RETRY_MS = 10_000;
826
834
  /** The longest a failing #1764 backfill waits before it tries again. */
827
835
  const BACKFILL_BACKOFF_MAX_MS = 60 * 60 * 1000;
828
836
  /**
@@ -985,8 +993,209 @@ export class ControlPlaneDO extends DurableObject {
985
993
  this.sql = ctx.storage.sql;
986
994
  this.kernelSql = switchSqlOver(this.sql);
987
995
  this.applyDirectorySchema();
996
+ this.installRouteReadModel(routeKvWriterOf(Reflect.get(env, 'ROUTES')));
988
997
  this.backfillArmed = ctx.blockConcurrencyWhile(() => this.armVersionMigrationsBackfill());
989
998
  }
999
+ // -- the routing read model (#3395) -------------------------------------------
1000
+ /** Set where a `ROUTES` KV namespace is bound; null otherwise, and the read model is off. */
1001
+ routePublisher = null;
1002
+ routeFlushing = null;
1003
+ routeFlushAgain = false;
1004
+ /**
1005
+ * How many of this object's methods are running (`kickRouteReadModelAfterEveryCall`). A flush
1006
+ * computes entries synchronously from the directory, so it only starts, and only reads a group
1007
+ * of keys, while this is 0: a method still running may hold a transaction that has not committed,
1008
+ * and a snapshot read inside it could be published and then rolled back.
1009
+ */
1010
+ routeCallDepth = 0;
1011
+ /**
1012
+ * On where a KV namespace is bound, off (triggers dropped, outbox emptied) where none is. A
1013
+ * directory that had no triggers before marks every key dirty, so switching on IS the backfill;
1014
+ * `publishRouteReadModel` is the operator's handle on the same thing.
1015
+ */
1016
+ installRouteReadModel(kv) {
1017
+ if (!kv) {
1018
+ uninstallRouteReadModel(this.sql);
1019
+ return;
1020
+ }
1021
+ const publisher = new RouteReadModelPublisher(this.sql, kv);
1022
+ this.ctx.storage.transactionSync(() => {
1023
+ if (publisher.install())
1024
+ publisher.markAll();
1025
+ });
1026
+ this.routePublisher = publisher;
1027
+ // The ledger must describe THIS namespace before anything is published against it. Checked in the
1028
+ // background, so no directory call waits on a KV read; publishing waits for it instead.
1029
+ this.routeLedgerVerified = false;
1030
+ this.routeLedgerCheck = (async () => {
1031
+ try {
1032
+ await publisher.verifyNamespace();
1033
+ this.routeLedgerVerified = true;
1034
+ this.kickRouteReadModel();
1035
+ }
1036
+ catch (err) {
1037
+ console.error('route read model: the namespace check failed, retrying from the alarm', err);
1038
+ this.routeRetryAfter = Date.now() + ROUTE_PUBLISH_RETRY_MS;
1039
+ await this.armRouteReadModelRetry().catch(() => undefined);
1040
+ }
1041
+ })();
1042
+ }
1043
+ /** The ledger has been checked against the bound namespace (`verifyNamespace`). */
1044
+ routeLedgerVerified = false;
1045
+ /** That check, for a caller that must see publishing settle (`settleRouteReadModel`). */
1046
+ routeLedgerCheck = Promise.resolve();
1047
+ /** After a failed publish, nothing publishes before this time but the alarm (`ROUTE_PUBLISH_RETRY_MS`). */
1048
+ routeRetryAfter = 0;
1049
+ /** The alarm's half of the retry: check the namespace again if that failed, then publish. */
1050
+ async retryRouteReadModel() {
1051
+ const publisher = this.routePublisher;
1052
+ if (!publisher)
1053
+ return;
1054
+ this.routeRetryAfter = 0;
1055
+ if (!this.routeLedgerVerified) {
1056
+ try {
1057
+ await publisher.verifyNamespace();
1058
+ this.routeLedgerVerified = true;
1059
+ }
1060
+ catch (err) {
1061
+ console.error('route read model: the namespace check failed again', err);
1062
+ this.routeRetryAfter = Date.now() + ROUTE_PUBLISH_RETRY_MS;
1063
+ await this.armRouteReadModelRetry().catch(() => undefined);
1064
+ return;
1065
+ }
1066
+ }
1067
+ this.kickRouteReadModel();
1068
+ }
1069
+ /** The flush may read the directory: none of this object's methods is running. */
1070
+ routeQuiet = () => this.routeCallDepth === 0;
1071
+ /**
1072
+ * Publish what the outbox holds, one flush at a time: a kick that lands mid-flush runs one more
1073
+ * round after it, so a change made during a flush is never left waiting for the next one. Called
1074
+ * when the last running method of this class returns (`kickRouteReadModelAfterEveryCall`); a kick
1075
+ * while one is still running waits for that return, so a flush never reads a write whose
1076
+ * transaction has not committed. A KV failure arms the alarm.
1077
+ */
1078
+ kickRouteReadModel() {
1079
+ const publisher = this.routePublisher;
1080
+ if (!publisher || this.routeCallDepth > 0 || !this.routeLedgerVerified)
1081
+ return;
1082
+ // After a failure, only the alarm retries: a directory write meanwhile must not retry KV at once.
1083
+ if (Date.now() < this.routeRetryAfter)
1084
+ return;
1085
+ if (this.routeFlushing) {
1086
+ this.routeFlushAgain = true;
1087
+ return;
1088
+ }
1089
+ if (!publisher.pending())
1090
+ return;
1091
+ void this.ownRouteFlush(async () => {
1092
+ let result;
1093
+ do {
1094
+ this.routeFlushAgain = false;
1095
+ result = await publisher.flush(undefined, this.routeQuiet);
1096
+ // A deferred flush is restarted by the method it deferred to, when that one returns.
1097
+ } while (!result.deferred && (this.routeFlushAgain || result.remaining > 0));
1098
+ return result;
1099
+ }).catch(async (err) => {
1100
+ console.error('route read model: publish failed, retrying from the alarm', err);
1101
+ this.routeRetryAfter = Date.now() + ROUTE_PUBLISH_RETRY_MS;
1102
+ await this.armRouteReadModelRetry().catch(() => undefined);
1103
+ });
1104
+ }
1105
+ /**
1106
+ * Run `flush` as THE flush: after any running one, and with every kick meanwhile queued behind it
1107
+ * as one more round. The only way a flush starts, so two never race the same key in KV.
1108
+ */
1109
+ async ownRouteFlush(flush) {
1110
+ while (this.routeFlushing)
1111
+ await this.routeFlushing;
1112
+ let result;
1113
+ let failure;
1114
+ let failed = false;
1115
+ this.routeFlushing = (async () => {
1116
+ try {
1117
+ result = await flush();
1118
+ }
1119
+ catch (err) {
1120
+ failure = err;
1121
+ failed = true;
1122
+ }
1123
+ })();
1124
+ try {
1125
+ await this.routeFlushing;
1126
+ }
1127
+ finally {
1128
+ this.routeFlushing = null;
1129
+ }
1130
+ // A kick that arrived during this flush asked for another round.
1131
+ if (this.routeFlushAgain) {
1132
+ this.routeFlushAgain = false;
1133
+ this.kickRouteReadModel();
1134
+ }
1135
+ if (failed)
1136
+ throw failure;
1137
+ return result;
1138
+ }
1139
+ /** A retry no later than `ROUTE_PUBLISH_RETRY_MS` from now. An earlier alarm is kept. */
1140
+ async armRouteReadModelRetry() {
1141
+ const at = Date.now() + ROUTE_PUBLISH_RETRY_MS;
1142
+ const current = await this.ctx.storage.getAlarm();
1143
+ if (current === null || current > at)
1144
+ await this.ctx.storage.setAlarm(at);
1145
+ }
1146
+ /** The current flush, for a caller (and a test) that must see it land. */
1147
+ async settleRouteReadModel() {
1148
+ await this.routeLedgerCheck;
1149
+ this.kickRouteReadModel();
1150
+ while (this.routeFlushing)
1151
+ await this.routeFlushing;
1152
+ }
1153
+ /** The read model's counts, for the backfill script and staff. */
1154
+ routeReadModelStatus() {
1155
+ return this.routePublisher ? this.routePublisher.status() : { enabled: false };
1156
+ }
1157
+ /**
1158
+ * The one-off backfill (scripts/route-read-model-backfill.mjs). A dry run reports what the read
1159
+ * model holds and would hold, and writes nothing. `apply` marks every key dirty and publishes up
1160
+ * to `maxKeys` now; the rest is published by the flush rounds that follow, and the status says
1161
+ * how many are left.
1162
+ */
1163
+ async publishRouteReadModel(opts = {}) {
1164
+ const publisher = this.routePublisher;
1165
+ if (!publisher || !opts.apply)
1166
+ return { status: this.routeReadModelStatus(), flushed: null };
1167
+ this.ctx.storage.transactionSync(() => publisher.markAll());
1168
+ // As THE flush, so a kick meanwhile queues a round instead of racing it.
1169
+ let flushed;
1170
+ try {
1171
+ flushed = await this.ownRouteFlush(() => publisher.flush(opts.maxKeys ?? 2_000, this.routeQuiet));
1172
+ }
1173
+ catch (err) {
1174
+ // As the automatic path does: the alarm retries, and the caller still sees the refusal.
1175
+ this.routeRetryAfter = Date.now() + ROUTE_PUBLISH_RETRY_MS;
1176
+ await this.armRouteReadModelRetry().catch(() => undefined);
1177
+ throw err;
1178
+ }
1179
+ // What this call's bound left queued is published by the rounds that follow, not left for the
1180
+ // next directory write or the scheduled pass.
1181
+ if (flushed.remaining > 0)
1182
+ this.kickRouteReadModel();
1183
+ return { status: publisher.status(), flushed };
1184
+ }
1185
+ /**
1186
+ * The scheduled pass's drift repair: one slice of every source. What it finds is queued in the
1187
+ * outbox (durable) and a flush is started, not awaited: the pass must not wait behind a publish
1188
+ * backlog, such as a large backfill over slow KV. A flush that fails arms the alarm retry, and a
1189
+ * caller that must see the publish land calls `settleRouteReadModel`.
1190
+ */
1191
+ async reconcileRouteReadModel(opts = {}) {
1192
+ const publisher = this.routePublisher;
1193
+ if (!publisher)
1194
+ return null;
1195
+ const result = await publisher.reconcile(opts.limit);
1196
+ this.kickRouteReadModel();
1197
+ return result;
1198
+ }
990
1199
  /**
991
1200
  * Schedule the #1764 backfill when a version still carries its SQL in its manifest.
992
1201
  *
@@ -1015,6 +1224,9 @@ export class ControlPlaneDO extends DurableObject {
1015
1224
  * meanwhile, because a version the backfill has not reached reads from its manifest.
1016
1225
  */
1017
1226
  async alarm() {
1227
+ // #3395: the routing read model's retry. It lifts the backoff (and redoes a failed namespace
1228
+ // check); the flush itself starts when this alarm returns, as after any directory method.
1229
+ await this.retryRouteReadModel().catch((err) => console.error('route read model: retry failed', err));
1018
1230
  let more;
1019
1231
  try {
1020
1232
  more = this.ctx.storage.transactionSync(() => splitVersionMigrationsBatch(this.kernelSql)).more;
@@ -1259,7 +1471,12 @@ export class ControlPlaneDO extends DurableObject {
1259
1471
  const row = this.sql
1260
1472
  .exec("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?", '_substrat_sweep_runs_intent')
1261
1473
  .toArray()[0];
1262
- if (row && sweepRunsIntentHasKind(row.sql))
1474
+ // None at all (a fresh or restored directory, or one whose index never got built): the held-back
1475
+ // `DIRECTORY_DDL_PLAN.afterColumns` creates it right after this. Nothing to rebuild, and a restore's
1476
+ // async transaction could not hold the `transactionSync` a rebuild takes.
1477
+ if (!row)
1478
+ return;
1479
+ if (sweepRunsIntentHasKind(row.sql))
1263
1480
  return;
1264
1481
  this.rebuildAtomically(['DROP INDEX IF EXISTS _substrat_sweep_runs_intent', SWEEP_RUNS_INTENT_INDEX]);
1265
1482
  }
@@ -1618,14 +1835,16 @@ export class ControlPlaneDO extends DurableObject {
1618
1835
  /**
1619
1836
  * The tables a dump carries, by name. Not `_cf_*` either: workerd's own tables (the #1764
1620
1837
  * backfill's alarm creates `_cf_METADATA`), which are not the directory's and which it refuses
1621
- * to drop on restore.
1838
+ * to drop on restore. Nor the routing read model's (#3395), which record what KV holds.
1622
1839
  */
1623
1840
  dumpTableDefs() {
1624
1841
  return this.sql
1625
1842
  .exec(`SELECT name, sql FROM sqlite_master
1626
1843
  WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_cf_*'
1627
- AND name NOT GLOB ? AND sql IS NOT NULL
1628
- ORDER BY name`, COPY_GLOB)
1844
+ AND name NOT GLOB ? AND name NOT GLOB ? AND sql IS NOT NULL
1845
+ ORDER BY name`, COPY_GLOB,
1846
+ // #3395: the read model's ledger describes KV, not the directory (route-read-model-publisher.ts).
1847
+ ROUTE_READ_MODEL_TABLE_GLOB)
1629
1848
  .toArray();
1630
1849
  }
1631
1850
  /**
@@ -1653,14 +1872,23 @@ export class ControlPlaneDO extends DurableObject {
1653
1872
  // TABLE. Pure input validation, so it runs before the first DROP: a refused dump touches
1654
1873
  // nothing.
1655
1874
  assertReplayableDump(tables, { maxColumns: DO_SQL_LIMITS.columns });
1875
+ // #3395: the routing read model's tables describe KV, survive a restore, and are never in a dump
1876
+ // this code exported. One a dump names (in any case: SQLite's names are) is crafted, and loading
1877
+ // it would make the ledger lie about what KV holds.
1878
+ const routeTable = tables.find((t) => t.name.toLowerCase().startsWith('route_read_model_'));
1879
+ if (routeTable) {
1880
+ throw substratError('validation_failed', `refusing this dump: it names ${routeTable.name}, a table no directory dump carries`);
1881
+ }
1656
1882
  await this.ctx.storage.transaction(async () => {
1657
1883
  // #1713: the epoch this directory was in, read before the drops take it.
1658
1884
  const epochBefore = this.lifecycleEpoch();
1659
1885
  this.sql.exec('PRAGMA defer_foreign_keys = ON');
1660
1886
  // `_cf_*` is workerd's, and dropping it is refused (SQLITE_AUTH), as `exportDump` says.
1887
+ // The routing read model's ledger survives too (#3395): it says what KV holds, which the
1888
+ // restore does not change, and the re-publish below needs it to delete what KV no longer may.
1661
1889
  const existing = this.sql
1662
1890
  .exec(`SELECT name FROM sqlite_master
1663
- WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_cf_*'`)
1891
+ WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_cf_*' AND name NOT GLOB ?`, ROUTE_READ_MODEL_TABLE_GLOB)
1664
1892
  .toArray();
1665
1893
  for (const { name } of existing)
1666
1894
  this.sql.exec(`DROP TABLE IF EXISTS "${name}"`);
@@ -1668,6 +1896,9 @@ export class ControlPlaneDO extends DurableObject {
1668
1896
  // rebuilds fires (each would reach `transactionSync`, which this async transaction cannot
1669
1897
  // hold): every table is created on the current shape.
1670
1898
  this.buildDirectorySchema({ holdSwitchRecords: [] });
1899
+ // #3395: the dropped tables took their triggers with them. Back before the load, so the
1900
+ // rows the dump brings in are captured like any other write.
1901
+ this.routePublisher?.install();
1671
1902
  // Refuses a table this code does not build, adds unknown columns bare, loads the rows by
1672
1903
  // name, then the legacy scope and #1674 backfills, all inside this transaction.
1673
1904
  loadDirectoryDump(tables, {
@@ -1690,6 +1921,9 @@ export class ControlPlaneDO extends DurableObject {
1690
1921
  // admin table, inside this same import transaction.
1691
1922
  if (audit)
1692
1923
  this.recordAdmin(audit);
1924
+ // #3395: every key the restored directory routes, and every key KV was given before it —
1925
+ // a route the restored directory does not hold is deleted, not left serving.
1926
+ this.routePublisher?.markAll();
1693
1927
  });
1694
1928
  // A restore is a new #1764 backfill episode. It replaced the data the old failure count and
1695
1929
  // backoff were about, so neither may delay or silence it: the count is cleared and the next
@@ -2635,12 +2869,15 @@ export class ControlPlaneDO extends DurableObject {
2635
2869
  };
2636
2870
  }
2637
2871
  /**
2638
- * Uncached request-path gate: only an active hostname, correctly paired active
2639
- * scope and active owning tenant resolve (#1713). No lifecycle fields cross the
2640
- * wire: refusal is the existing unresolved route. CP-less direct/background calls
2641
- * and already-dispatched requests are outside this gate.
2872
+ * Request-path gate: only an active hostname, correctly paired active scope and active
2873
+ * owning tenant resolve (#1713). No lifecycle fields cross the wire: refusal is the existing
2874
+ * unresolved route. CP-less direct/background calls and already-dispatched requests are
2875
+ * outside this gate.
2876
+ *
2877
+ * `publish` (#3395) is the router's read-model miss: the route is queued for publishing
2878
+ * unless it is published already. The answer is the same either way.
2642
2879
  */
2643
- readRoute(hostname) {
2880
+ readRoute(hostname, opts) {
2644
2881
  // Join the scope's dispatch script, so the router resolves it in the same one
2645
2882
  // directory read (orchestration.md §5.4). A scope whose data lives in the stable
2646
2883
  // serving script (#286) routes THERE — per-scope truth, because rerouting a scope
@@ -2664,6 +2901,17 @@ export class ControlPlaneDO extends DurableObject {
2664
2901
  // #2005: the predicate runs here, once, rather than travelling as two columns for the
2665
2902
  // router to re-derive — every reader of the directory answers it the same way.
2666
2903
  const { kind, forked_from, scope_hostnames_json, ...route } = row;
2904
+ if (opts?.publish === true && this.routePublisher) {
2905
+ // Optional: a fill that cannot be queued (storage full) must not fail a read that succeeded. The
2906
+ // route stays unpublished, and the next miss asks again.
2907
+ try {
2908
+ this.routePublisher.requestPublish(hostname);
2909
+ this.kickRouteReadModel();
2910
+ }
2911
+ catch (err) {
2912
+ console.error('route read model: could not queue a miss for publishing', hostname, err);
2913
+ }
2914
+ }
2667
2915
  return {
2668
2916
  ...route,
2669
2917
  primary: isPrimaryScopeRow({ kind, forked_from }),
@@ -5276,4 +5524,54 @@ export class ControlPlaneDO extends DurableObject {
5276
5524
  inputTokens: row.input_tokens, outputTokens: row.output_tokens }));
5277
5525
  }
5278
5526
  }
5527
+ /**
5528
+ * #3395: when the last running method of the directory returns, publish what its writes queued.
5529
+ *
5530
+ * The capture is the triggers (route-read-model-publisher.ts), which miss no write path; this is
5531
+ * the matching half for the publish, so it cannot be forgotten either: a method added later is
5532
+ * covered without naming it. The check is one read of an outbox that is empty almost always. It
5533
+ * runs once the method's promise settles, so a flush never reads the writes of a transaction its
5534
+ * own call has not finished. `readRoute` is the hot path and kicks only when it queued something.
5535
+ */
5536
+ // The publishing methods drive the flush themselves, and count as no running method while they do.
5537
+ const ROUTE_KICK_EXEMPT = new Set([
5538
+ 'constructor', 'readRoute', 'kickRouteReadModel', 'settleRouteReadModel', 'publishRouteReadModel',
5539
+ 'reconcileRouteReadModel', 'routeReadModelStatus', 'ownRouteFlush', 'routeQuiet',
5540
+ // The retry path: its own return must not start a flush, or a failure is retried at once rather than
5541
+ // after `ROUTE_PUBLISH_RETRY_MS`; the alarm starts it (`retryRouteReadModel`).
5542
+ 'armRouteReadModelRetry', 'retryRouteReadModel',
5543
+ ]);
5544
+ for (const name of Object.getOwnPropertyNames(ControlPlaneDO.prototype)) {
5545
+ if (ROUTE_KICK_EXEMPT.has(name))
5546
+ continue;
5547
+ const descriptor = Object.getOwnPropertyDescriptor(ControlPlaneDO.prototype, name);
5548
+ if (!descriptor || typeof descriptor.value !== 'function')
5549
+ continue;
5550
+ const original = descriptor.value;
5551
+ Object.defineProperty(ControlPlaneDO.prototype, name, {
5552
+ ...descriptor,
5553
+ value: function (...args) {
5554
+ // Counted in and out, so only the OUTERMOST return kicks: a private helper returning inside a
5555
+ // transaction (`bumpLifecycleRevision` within `writeAndAudit`) must not start a flush there.
5556
+ const leave = () => {
5557
+ this.routeCallDepth -= 1;
5558
+ if (this.routeCallDepth === 0)
5559
+ this.kickRouteReadModel();
5560
+ };
5561
+ this.routeCallDepth += 1;
5562
+ let out;
5563
+ try {
5564
+ out = original.apply(this, args);
5565
+ }
5566
+ catch (err) {
5567
+ leave();
5568
+ throw err;
5569
+ }
5570
+ if (out instanceof Promise)
5571
+ return out.finally(leave);
5572
+ leave();
5573
+ return out;
5574
+ },
5575
+ });
5576
+ }
5279
5577
  //# sourceMappingURL=control-plane-do.js.map