@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
package/dist/scope-do.js CHANGED
@@ -6,6 +6,7 @@ import { ulid, DO_SQL_LIMITS, unknownRoleError, createUlid, assertAllowed, Conne
6
6
  import { isUpgradeRequest, readSubscription, LIVE_DECIDE_ATTEMPTS, LIVE_FANOUT_LIMIT, LIVE_PRINCIPAL_HEADER, LIVE_SCOPE_HEADER, LIVE_SUBSCRIBE_PATH, LIVE_TENANT_HEADER, LIVE_WITHIN_HEADER, LIVE_EXPIRES_HEADER, LIVE_CLOSE, LIVE_SOCKETS_PER_PRINCIPAL, decodeLiveWithin, liveInstant, liveRefusal, liveRefusalStatus, } from './live-reads.js';
7
7
  import { replyOf } from './do-reply.js';
8
8
  import { OperationQueue } from './serialization.js';
9
+ import { reconcileOnWake } from './reconcile-on-wake.js';
9
10
  import { meterScopeWorkEntries, ScopeWorkMeter } from './scope-work.js';
10
11
  import { assertNoWorkerdStorage, doScopedSql, doBuiltColumnsOf, doRedactionSql, doSpineSql } from './sql.js';
11
12
  import { actorOf, admitPeer, boundToPeerDeclarations, collectPeers, switchPeer, peerSubjectRef, subjectGrantState, assertNoSecret, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, splitSqlStatements, executableSqlStatements, blankSqlComments, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, becomeMintCheck, mintBecomeCapabilityAsPrincipal, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, assertNoCallerPurge, isUnreachableParent, PURGE_BATCH, heldPurgePass, lifecycleRefusal, purgeHeldBy, assertPlatformRequestRoom, CONNECTOR_DISPATCH_REQUESTED_BY, MAX_PENDING_CONNECTOR_DISPATCHES, purgeDueOf, purgeOnlyKeysOf, runPurgePass, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, redactSecrets, redactSecretText, moduleLog, asyncInvocationId, asyncLinePass, resolveCapabilitySession, revokeCapabilityAsPlatform, readCapabilityPage, domainEventOf, facetEvents, readDeadLetters, readLifecycleFlow, readOperationSeries, readHistory, readInvocation, readUndrainedOutbox, walkEventCause, walkEventEffects, } from '@substrat-run/kernel';
@@ -13,6 +14,7 @@ import { COPY_RESTORE_FENCE_LAPSED, copyRestoreFenceLapsed, orphanSweepVersionRe
13
14
  import { createDoTupleChecker, createLocalControlPlaneReader, scopeTupleReader } from './checker.js';
14
15
  import { settlePlatformRequestIn } from '@substrat-run/kernel';
15
16
  import { loadDropsRowsOf, SCOPE_COPY_LEASE_MS, ulidTime } from '@substrat-run/kernel';
17
+ import { SCOPE_WAKE_KEY, keepRegisteredMeanwhile, kickControlPlane, runWake, wakeAfterCommit, wakeDueAt } from './scope-wake.js';
16
18
  import { CARRIED_AWAY_KEY, COPY_MARK_CLEARED_KEY, KEPT_COPY_REFUSAL, KEPT_DIVERGENT_KEY, LOAD_STAMP_KEY, STORE_LOCAL_META_KEYS, WRITE_REVISION_KEY, carriedAwayDump, isCopyMarkInsert, isWriteStatement, assertSpineTablesBuilt, clearCopyMarker, dumpRowsInsert, isSpineTable, markCopyOrigin, repointScopeGrants, settleCopiedWork, emittedHere, IS_COPY_SQL, CLEAN_ROOM_COPY_SQL, isCopyLoad, isLifecycleWrite, readLifecycle, settleLifecycleAfterLoad, writeLifecycle, spineColumnAdditions } from '@substrat-run/kernel';
17
19
  import { GRANT_CHILDREN_INDEX_DDL, SHAPE_MARKER_INDEX_DDL, grantedEntitiesForContext } from '@substrat-run/kernel';
18
20
  /** A scope's migration journal: `module@version` → the SQL digest it recorded (#2066). */
@@ -1058,6 +1060,8 @@ options = {}) {
1058
1060
  lastFailure = null;
1059
1061
  /** Passes of `applyPendingMigrations` that had work to do — see `migrationAttemptsOnInstance`. */
1060
1062
  migrationRuns = 0;
1063
+ /** K-69: this instance's wake wrote a `provision-reconcile` intent no invoke has reported yet. */
1064
+ reconcileAskUnsignalled = false;
1061
1065
  /**
1062
1066
  * TEST-ONLY (#1860): no production code reads this. An exact `'ping'` is answered
1063
1067
  * by `setWebSocketAutoResponse` without reaching `webSocketMessage` at all, and
@@ -2748,7 +2752,8 @@ options = {}) {
2748
2752
  const exported = exportMark !== null && !replayed ? this.exportedSince(exportTypes, exportMark) : 0;
2749
2753
  return {
2750
2754
  result,
2751
- platformRequests: signals.platformRequests,
2755
+ // K-69: plus the intent this instance's wake wrote, once, so the router kicks its drain.
2756
+ platformRequests: signals.platformRequests + this.takeReconcileAsk(),
2752
2757
  // #1705 PR 2: the coordinator fires `onExportedEvents` from this. Omitted at 0, so
2753
2758
  // the envelope of a deployment that exports nothing is byte-for-byte what it was.
2754
2759
  ...(exported > 0 ? { exported } : {}),
@@ -2958,14 +2963,97 @@ options = {}) {
2958
2963
  }
2959
2964
  if (earliest === undefined)
2960
2965
  return;
2961
- const at = Date.parse(earliest);
2966
+ await this.armAlarmBy(Date.parse(earliest));
2967
+ }
2968
+ /** The one alarm, moved only earlier: every user of it arms through here (#938, K-69). */
2969
+ async armAlarmBy(at) {
2962
2970
  const current = await this.ctx.storage.getAlarm();
2963
2971
  if (current === null || current > at)
2964
2972
  await this.ctx.storage.setAlarm(at);
2965
2973
  }
2966
- /** The live reaper's alarm (#938): close what has expired, then arm for what is next. */
2974
+ /**
2975
+ * The scope's alarm, shared by its two users: the live reaper (#938) closes what has expired, and
2976
+ * the scope's wake (K-69, `scope-wake.ts`) asks for the drains its pending work is waiting on.
2977
+ * Each re-arms for what it has next, earliest wins.
2978
+ */
2967
2979
  async alarm() {
2968
2980
  await this.armLiveExpiry();
2981
+ await this.runScopeWake();
2982
+ }
2983
+ /** K-69: a scope with the control plane's origin and secret asks for its own drains. */
2984
+ wakeTransport() {
2985
+ const url = this.env.CONTROL_PLANE_URL;
2986
+ const secret = this.env.PLATFORM_SECRET;
2987
+ return url && secret ? { controlPlaneUrl: url, secret } : null;
2988
+ }
2989
+ /**
2990
+ * K-69: what a commit left for the platform, read by index (`CommitWork`): the newest intent by
2991
+ * primary key, and whether an emitted event waits unshipped, by `_substrat_outbox_drained`.
2992
+ */
2993
+ commitWork() {
2994
+ const newest = this.sql
2995
+ .exec('SELECT id FROM _substrat_platform_requests ORDER BY id DESC LIMIT 1')
2996
+ .toArray()[0];
2997
+ const undrained = this.sql
2998
+ .exec(`SELECT 1 AS one FROM _substrat_outbox WHERE drained_at IS NULL AND ${emittedHere()} LIMIT 1`)
2999
+ .toArray();
3000
+ return { newestIntent: newest?.id ?? null, undrainedEvents: undrained.length > 0 };
3001
+ }
3002
+ /** K-69: at the alarm, also whether any intent is still pending — the drain's own listing scans the same rows. */
3003
+ wakeWork() {
3004
+ const pending = this.sql
3005
+ .exec(`SELECT 1 AS one FROM _substrat_platform_requests WHERE status = 'pending' LIMIT 1`)
3006
+ .toArray();
3007
+ return { ...this.commitWork(), pendingIntents: pending.length > 0 };
3008
+ }
3009
+ /**
3010
+ * K-69: after a commit, arm the scope's wake for the work it left. Never fails the commit it
3011
+ * follows: a wake not armed costs latency, and the pass (or its check) is the backstop.
3012
+ */
3013
+ async noteScopeWake(tenantId, scopeId) {
3014
+ if (!this.wakeTransport())
3015
+ return;
3016
+ try {
3017
+ const prior = (await this.ctx.storage.get(SCOPE_WAKE_KEY)) ?? null;
3018
+ const next = wakeAfterCommit(prior, { tenantId, scopeId }, this.commitWork(), Date.now());
3019
+ if (!next)
3020
+ return;
3021
+ await this.ctx.storage.put(SCOPE_WAKE_KEY, next);
3022
+ const at = wakeDueAt(next);
3023
+ if (at !== null)
3024
+ await this.armAlarmBy(at);
3025
+ }
3026
+ catch (err) {
3027
+ console.error('substrat: scope wake not armed after commit; the pass is the backstop', err);
3028
+ }
3029
+ }
3030
+ /** K-69: the wake's half of the alarm. Never throws: a thrown alarm is retried by the runtime. */
3031
+ async runScopeWake() {
3032
+ const transport = this.wakeTransport();
3033
+ try {
3034
+ const state = (await this.ctx.storage.get(SCOPE_WAKE_KEY)) ?? null;
3035
+ if (!state)
3036
+ return;
3037
+ if (!transport) {
3038
+ // The binding went away (a re-upload without it): nothing can be asked, so nothing is kept.
3039
+ await this.ctx.storage.delete(SCOPE_WAKE_KEY);
3040
+ return;
3041
+ }
3042
+ const ran = await runWake(state, Date.now(), () => this.wakeWork(), (body) => kickControlPlane(transport, body));
3043
+ // The object took other calls while the kick was out: keep what a commit stored meanwhile.
3044
+ const next = keepRegisteredMeanwhile(state, ran, (await this.ctx.storage.get(SCOPE_WAKE_KEY)) ?? null);
3045
+ if (!next) {
3046
+ await this.ctx.storage.delete(SCOPE_WAKE_KEY);
3047
+ return;
3048
+ }
3049
+ await this.ctx.storage.put(SCOPE_WAKE_KEY, next);
3050
+ const at = wakeDueAt(next);
3051
+ if (at !== null)
3052
+ await this.armAlarmBy(at);
3053
+ }
3054
+ catch (err) {
3055
+ console.error('substrat: scope wake failed; the pass is the backstop', err);
3056
+ }
2969
3057
  }
2970
3058
  /** The context a live subscriber's checks run in: its own principal, under `live.subscribe`. */
2971
3059
  liveContext(subscriber) {
@@ -3081,6 +3169,8 @@ options = {}) {
3081
3169
  */
3082
3170
  invocationId) {
3083
3171
  await this.dispatch(tenantId, scopeId, invocationId);
3172
+ // K-69: after the consumers, whose own emits and intents count too.
3173
+ await this.noteScopeWake(tenantId, scopeId);
3084
3174
  if (liveSince === null)
3085
3175
  return;
3086
3176
  try {
@@ -5082,14 +5172,46 @@ options = {}) {
5082
5172
  // -- migrations (port of applyPendingMigrations) --------------------------
5083
5173
  ensureMigrations() {
5084
5174
  if (!this.migrationPromise) {
5175
+ // K-69: read before the pass, so a scope with nothing applied yet reads as a provision.
5176
+ const upgrade = this.applied.size > 0;
5085
5177
  // #3316: counted as the migration it is, not as whichever entry woke it — the first
5086
5178
  // operation after a promote runs the whole pass.
5087
- this.migrationPromise = this.scopeWork
5179
+ const pass = this.scopeWork
5088
5180
  ? this.scopeWork.apart('migration-pass', 'migration', () => this.applyPendingMigrations())
5089
5181
  : this.applyPendingMigrations();
5182
+ // K-69: only after the pass SUCCEEDED — a scope failing closed asks for nothing, and the
5183
+ // rejection passes through untouched.
5184
+ this.migrationPromise = pass.then((applied) => {
5185
+ this.askReconcileOnWake(upgrade);
5186
+ return applied;
5187
+ });
5090
5188
  }
5091
5189
  return this.migrationPromise;
5092
5190
  }
5191
+ /**
5192
+ * K-69 (rfc/tenant-scale.md §7.5): the first wake on a version this scope has not asked about
5193
+ * writes one `provision-reconcile` intent (`reconcileOnWake`). Never throws: a scope that cannot
5194
+ * ask is still reached by the batched pass, and failing the request over it protects nothing.
5195
+ */
5196
+ askReconcileOnWake(upgrade) {
5197
+ try {
5198
+ const asked = reconcileOnWake(this.sql, this.env.SUBSTRAT_VERSION_ID, upgrade, new Date().toISOString());
5199
+ if (asked === 'requested')
5200
+ this.reconcileAskUnsignalled = true;
5201
+ }
5202
+ catch (err) {
5203
+ console.warn('reconcile-on-wake: could not ask; the batched pass is the backstop', {
5204
+ error: err instanceof Error ? err.message : String(err),
5205
+ });
5206
+ }
5207
+ }
5208
+ /** K-69: 1 once, on the first committed invoke after the wake asked, so its response flags a drain. */
5209
+ takeReconcileAsk() {
5210
+ if (!this.reconcileAskUnsignalled)
5211
+ return 0;
5212
+ this.reconcileAskUnsignalled = false;
5213
+ return 1;
5214
+ }
5093
5215
  /** Every registered module's derivation plans — what `repairDerivedObjects` and its checks read. */
5094
5216
  derivedPlans() {
5095
5217
  return { state: this.statePlans, lists: this.listPlans, search: this.searchPlans };
@@ -5535,7 +5657,7 @@ options = {}) {
5535
5657
  * `invocationId` is LAST, and defaulted, for the RPC-skew reason `recordExecutorAttempt`
5536
5658
  * states at length.
5537
5659
  */
5538
- routeExecutorEventToPlatform(eventId, deliveryId, kind, payload, requestedBy,
5660
+ async routeExecutorEventToPlatform(eventId, deliveryId, kind, payload, requestedBy,
5539
5661
  /**
5540
5662
  * #1525: the call this routing ran in, or null. On the hosted path this is the
5541
5663
  * dominant executor journal — every vertical is CP-less, so a connector delivery
@@ -5553,12 +5675,17 @@ options = {}) {
5553
5675
  // caused an outbound effect. Read here rather than passed over the RPC: the DO
5554
5676
  // owns the outbox, so a coordinator cannot claim a stamp or drop one.
5555
5677
  const source = this.sql
5556
- .exec('SELECT impersonation FROM _substrat_outbox WHERE id = ?', eventId)
5678
+ .exec('SELECT impersonation, tenant_id, scope_id FROM _substrat_outbox WHERE id = ?', eventId)
5557
5679
  .toArray()[0];
5558
5680
  this.sql.exec(`INSERT INTO _substrat_platform_requests
5559
5681
  (id, kind, payload, requested_by, impersonation, status, attempts, requested_at)
5560
5682
  VALUES (?, ?, ?, ?, ?, 'pending', 0, ?)`, id, kind, payload, requestedBy, source?.impersonation ?? null, instant.parse(new Date().toISOString()));
5561
5683
  this.recordExecutorAttempt(eventId, deliveryId, null, null, invocationId);
5684
+ // K-69: this intent is enqueued by the coordinator after the commit's own wake was armed, so
5685
+ // it arms one too, under the ids its source event carries. Both writes above are made before
5686
+ // this await, as one unit.
5687
+ if (source)
5688
+ await this.noteScopeWake(tenantIdOf.parse(source.tenant_id), scopeIdOf.parse(source.scope_id));
5562
5689
  return id;
5563
5690
  }
5564
5691
  /** #3365: the routed connector deliveries this scope holds pending — their own room. */