@substrat-run/adapter-cloudflare 0.222.0 → 0.224.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 (43) hide show
  1. package/dist/client-context.d.ts +8 -1
  2. package/dist/client-context.d.ts.map +1 -1
  3. package/dist/client-context.js +13 -1
  4. package/dist/client-context.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +18 -5
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +24 -11
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +13 -5
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +2 -0
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/delivery-broker-platform.d.ts +1 -1
  14. package/dist/delivery-broker-platform.d.ts.map +1 -1
  15. package/dist/delivery-broker-platform.js +1 -1
  16. package/dist/delivery-broker-platform.js.map +1 -1
  17. package/dist/directory-placement.d.ts.map +1 -1
  18. package/dist/directory-placement.js +1 -0
  19. package/dist/directory-placement.js.map +1 -1
  20. package/dist/executor-route.d.ts +13 -0
  21. package/dist/executor-route.d.ts.map +1 -0
  22. package/dist/executor-route.js +12 -0
  23. package/dist/executor-route.js.map +1 -0
  24. package/dist/host.d.ts +73 -2
  25. package/dist/host.d.ts.map +1 -1
  26. package/dist/host.js +204 -35
  27. package/dist/host.js.map +1 -1
  28. package/dist/index.d.ts +3 -3
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +1 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/reconcile-on-wake.d.ts +6 -1
  33. package/dist/reconcile-on-wake.d.ts.map +1 -1
  34. package/dist/reconcile-on-wake.js +8 -3
  35. package/dist/reconcile-on-wake.js.map +1 -1
  36. package/dist/scope-do.d.ts.map +1 -1
  37. package/dist/scope-do.js +83 -24
  38. package/dist/scope-do.js.map +1 -1
  39. package/dist/tenant-due-work-do.d.ts +8 -3
  40. package/dist/tenant-due-work-do.d.ts.map +1 -1
  41. package/dist/tenant-due-work-do.js +1 -1
  42. package/dist/tenant-due-work-do.js.map +1 -1
  43. package/package.json +14 -10
package/dist/host.js CHANGED
@@ -2,6 +2,7 @@ import { restoreChunksOf } from './directory-restore-chunks.js';
2
2
  import { env as ambientEnv } from 'cloudflare:workers';
3
3
  import { isRewindRefusal, REWIND_REFUSED } from './rewind-refusal.js';
4
4
  import { isSystemDoorMoved, SYSTEM_DOOR_MOVED, SYSTEM_DOOR_REGATES } from './system-door.js';
5
+ import { EXECUTOR_ROUTE_NOT_DUE } from './executor-route.js';
5
6
  import { delegatedReadParams, operationSeriesCount, fromWireFailure, isSubstratError, exportReadInput, exportedBatch, importBatch, importResult, pushedImport, importState, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, exportsOfManifestJson, assertNoBindingShapeBreak, assertScopeTypesKept, importCursorMove, importCursorMoveAt, importCursorMoved, accessLogEntry, adminLogEntry, opsFailureEntry, opsFailureFingerprint, issueEntry, findingEntry, findingRuleEntry, sweepRunEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunsPayload, modelUsageEntry, createTenantInput, identityLink, identityPool, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, registerVerticalInput, vertical as verticalSchema, verticalServingState, verticalTraceSampling, deploymentWireAuth, verticalChannel, verticalVersion, connection, capabilityExchange, mintedCapability, boundedBecomeMint, boundedBindLinkMint, boundedBecomeRevoke, boundedUnbind, entityRef, becomeLinkState, principalBecomeCapabilityInput, principalBindLinkInput, capabilityGrant, principalId, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchOutcome, systemScheduleEntry, systemSwitchRecord, entitlementGrant, entitlementGrantInput, capabilityFilter, instant, meterReading, scopeStorageSample, requestDay, requestRollupDay, costDay, meterDay, meterDayTake, staleScope, staleScopeTake, verticalOwnerPeriod, subjectRef, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, org as orgSchema, orgMembership, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, subjectShredReceipt, subjectAccessReceipt, connectorDispatchKind, callsOfManifestJson, outboundOfManifestJson, SCOPE_GATE_REASONS, substratError, MODULE_OBJECTS_NOT_CARRIED, errorCodeOf, redrainEventsInput, coverage, peerCoverage, peerGrantsEntry, peerSwitch, peerSwitchOutcome, verticalCaller, verticalResolution, peerInstanceResolution, peerBinding as peerBindingSchema, appEnvironment as appEnvironmentSchema, environmentServeAcknowledgement, environmentEffects as environmentEffectsSchema, connectionReach as connectionReachSchema, verticalSlug, entityObjectRef, ATTACHMENT_BLOB_BINDING, blobStoreBindingName, lifecycleDelivery, scopeLifecycle, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
6
7
  import { normalizeHostname, toRouteTarget } from './route-resolver.js';
7
8
  import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
@@ -13,7 +14,7 @@ import { attachmentBlobKey, normalizeUploadMediaType, redeemOrReplayUploadLink,
13
14
  // #2995: the parent link a provision-child writes, and the doors it decides.
14
15
  childDoorRefusal, childScopeRefusal, claimsHome, directAccessRefusal, parentlessScopeRefusal, provisionedParent,
15
16
  // #2993 part 3: the modules (and seats) a scope of each declared type has.
16
- HOME_SCOPE_TYPE, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRuns, ulid, withheldOpsFailure, KEPT_COPY_REFUSAL, capabilityTokenHash, checkBecomeInput, assertBecomeLinkStateIds, plausibleSessionToken, foldModelUsage, backoffAt, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, openSealed, ImpersonationRefused, assertSessionUsable, impersonationRowValues, mapImpersonationRow, newImpersonationSession, jobRunOf, assertLeaseMs, runDueJobRuns, SYSTEM_DOOR_WAIT, startJobRun, attachmentTextJob, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, searchLimit, searchMatchExpression, globalFetch, fetchLikeOf, deadlineFetch, assertRedrainWindow, platformRequestOf, undrainedEventsOf, outboxSubscribersOf, pruneInputOf, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, recordedOffFromWire, peerSubjectRef, SWITCH_KINDS, reassertActionOf, reassertEntry, reassertOffRow, reassertOnRow, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, recordWriteSuperseded, switchSubjectOf, switchSupersededMessage, withRecorded, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, CrossVerticalRegistry, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, migratesFrom, servedFromRow, rebindRaceRefusal, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, strandJudgmentsOf, boundShapesOfColumn, installReconciled, collectPeers, peerCallerAt, peerSeats, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, splitManifestMigrations, publishedMigrationDigest, migrationChangeRefusal, unknownRoleError, assertRowLimit, assertRowOffset, emptyImportResult, INERT_SCOPE_REASON, lifecycleReceipt, lifecycleRefusal, scopeNotHeldRefusal, isPrimaryScope, isPrimaryScopeRow, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
17
+ HOME_SCOPE_TYPE, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRuns, ulid, withheldOpsFailure, KEPT_COPY_REFUSAL, capabilityTokenHash, checkBecomeInput, assertBecomeLinkStateIds, plausibleSessionToken, foldModelUsage, backoffAt, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, openSealed, ImpersonationRefused, assertSessionUsable, impersonationRowValues, mapImpersonationRow, newImpersonationSession, jobRunOf, assertLeaseMs, runDueJobRuns, SYSTEM_DOOR_WAIT, startJobRun, attachmentTextJob, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, searchLimit, searchMatchExpression, globalFetch, fetchLikeOf, deadlineFetch, assertRedrainWindow, platformRequestOf, undrainedEventsOf, outboxSubscribersOf, pruneInputOf, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, recordedOffFromWire, peerSubjectRef, SWITCH_KINDS, reassertActionOf, reassertEntry, reassertOffRow, reassertOnRow, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, recordWriteSuperseded, switchSubjectOf, switchSupersededMessage, withRecorded, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, CrossVerticalRegistry, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, migratesFrom, servedFromRow, rebindRaceRefusal, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, strandJudgmentsOf, boundShapesOfColumn, installReconciled, collectPeers, peerCallerAt, peerSeats, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, splitManifestMigrations, publishedMigrationDigest, migrationChangeRefusal, unknownRoleError, assertRowLimit, assertRowOffset, emptyImportResult, INERT_SCOPE_REASON, lifecycleReceipt, lifecycleRefusal, scopeNotHeldRefusal, isPrimaryScope, isPrimaryScopeRow, sealingKeysForReach, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
17
18
  import { fenceAttachmentSweep, missingAttachmentStore, sweepOrphanAttachments, unsettledCopyRefusal } from '@substrat-run/kernel';
18
19
  import { ConnectorRevokeUnsupported } from '@substrat-run/kernel';
19
20
  import { assertWireAuthFilter, wireAuthAccessTarget, COPY_RESTORE_FENCE_LAPSED, scopeScriptCopyOf } from '@substrat-run/kernel';
@@ -55,6 +56,56 @@ export const LIFECYCLE_EPOCH_SKEW_MS = 24 * 60 * 60 * 1000;
55
56
  * before the record) costs at most this many deliveries a pass and starves nothing.
56
57
  */
57
58
  export const TENANT_UNRECORDED_PER_PASS = 50;
59
+ /**
60
+ * K-69 (#3540): how soon after a failed delivery its first retry is due. The directory's own back-off
61
+ * (#3119) waits nothing after a first failure, which the sweep read as "the next pass"; an alarm
62
+ * looks again a minute on, then on the directory's back-off.
63
+ */
64
+ export const LIFECYCLE_RETRY_FIRST_LOOK_MS = 60_000;
65
+ /**
66
+ * K-69 (#3540): whether a scope is owed its first lifecycle delivery after a directory restore. The
67
+ * restore minted an epoch (`epoch > 0`), and the deployment has acknowledged nothing in it: no
68
+ * receipt, or a receipt from another history, which is what a restored dump carries. No failure
69
+ * has been counted since (a scope with one is owed a retry, and `retry_at` says so). A transition
70
+ * whose own delivery was lost within the epoch is not one: its receipt names this epoch.
71
+ */
72
+ function owedFirstDelivery(t) {
73
+ if (t.retry_at !== null || t.epoch <= 0)
74
+ return false;
75
+ if (t.delivered === null)
76
+ return true;
77
+ // `lifecycleReceipt`: `scope/tenant@epoch.scope.tenant`, or no revision at all for a lifecycle
78
+ // stored before revisions, which reads as another history.
79
+ const held = /@(\d+)\.\d+\.\d+$/.exec(t.delivered);
80
+ return held === null || Number(held[1]) !== t.epoch;
81
+ }
82
+ /** The receipt a deployment would acknowledge for this directory row (`lifecycleReceipt`). */
83
+ function targetReceipt(t) {
84
+ return lifecycleReceipt({
85
+ scope: t.scope_status,
86
+ tenant: t.tenant_status,
87
+ revision: { epoch: t.epoch, scope: t.scope_rev, tenant: t.tenant_rev },
88
+ });
89
+ }
90
+ /**
91
+ * K-69 (#3540): whether a scope is held now, as the heal's drift reads it (`lifecycleTargets`: a scope
92
+ * neither active nor archived, or a tenant not active), and its deployment acknowledged exactly the
93
+ * directory's lifecycle. The sweep delivered each of these on every pass before an owner took them.
94
+ */
95
+ function acknowledgedHold(t) {
96
+ const held = (t.scope_status !== 'active' && t.scope_status !== 'archived') || t.tenant_status !== 'active';
97
+ return held && t.delivered !== null && t.delivered === targetReceipt(t);
98
+ }
99
+ /**
100
+ * K-69 (#3540): whether an acknowledged hold is owed another delivery: the deployment that acknowledged
101
+ * it is not the one that serves the scope now (`deployment`), or the receipt is older than the
102
+ * deployment it names. A store keeps a hold through every load into it (`settleLifecycleAfterLoad`), so
103
+ * a store that never took one is the only place it can be missing, and that store serves the scope
104
+ * only after its scope or its vertical moved. A scope owed a retry is that instead.
105
+ */
106
+ function owedHoldRedelivery(t) {
107
+ return t.retry_at === null && acknowledgedHold(t) && t.receipt_deployment !== t.deployment;
108
+ }
58
109
  /**
59
110
  * K-3's refusal of a (tenant, scope) pair the host does not hold — the same answer for a scope that
60
111
  * does not exist and for one of another tenant (#1718), in one wording.
@@ -474,6 +525,7 @@ export class CloudflareScopeHost {
474
525
  systemSwitchDelegation;
475
526
  /** #1713: the lifecycle's reach into the deployment serving a scope. */
476
527
  lifecycleDelegation;
528
+ lifecycleRetryOwner;
477
529
  /** #1706: the peer kill switch's reach into the deployment serving a scope. */
478
530
  peerSwitchDelegation;
479
531
  /** #1705 PR 3: the replay lever's reach into the deployment serving a consumer scope. */
@@ -546,6 +598,7 @@ export class CloudflareScopeHost {
546
598
  this.eventDrainDelegation = options.eventDrainDelegation;
547
599
  this.systemSwitchDelegation = options.systemSwitchDelegation;
548
600
  this.lifecycleDelegation = options.lifecycleDelegation;
601
+ this.lifecycleRetryOwner = options.lifecycleRetryOwner;
549
602
  this.peerSwitchDelegation = options.peerSwitchDelegation;
550
603
  this.importCursorDelegation = options.importCursorDelegation;
551
604
  this.capabilityDelegation = options.capabilityDelegation;
@@ -592,14 +645,19 @@ export class CloudflareScopeHost {
592
645
  tenantId,
593
646
  scopeId,
594
647
  vertical: vertical ?? '',
595
- connection: async (provider) => {
648
+ connection: async (provider, options) => {
596
649
  if (!vertical) {
597
650
  throw new Error(`scope ${scopeId} is bound to no vertical, so it has no connection namespace — ` +
598
651
  `provision it with a vertical before using connectors`);
599
652
  }
600
- const open = await admin.openConnection(tenantId, vertical, provider);
653
+ // #3530 step 6: `own` opens this scope's own connection, and never the tenant's.
654
+ const open = options?.own
655
+ ? await admin.openConnection(tenantId, vertical, provider, undefined, scopeId)
656
+ : await admin.openConnection(tenantId, vertical, provider);
601
657
  if (!open) {
602
- throw new Error(`no live '${provider}' connection for tenant ${tenantId} / vertical '${vertical}'`);
658
+ throw new Error(options?.own
659
+ ? `scope ${scopeId} owns no live '${provider}' connection, and a dispatch held to its own opens no other`
660
+ : `no live '${provider}' connection for tenant ${tenantId} / vertical '${vertical}'`);
603
661
  }
604
662
  return {
605
663
  ...open,
@@ -793,6 +851,13 @@ export class CloudflareScopeHost {
793
851
  roomFull = true;
794
852
  continue drain;
795
853
  }
854
+ if (routed === EXECUTOR_ROUTE_NOT_DUE) {
855
+ // #3676: another pass acting on the same due read routed it first. The scope decided
856
+ // that in the transaction that would have written, so nothing was: not an attempt,
857
+ // and not a full room — the pass goes on to the next delivery.
858
+ report.attempted -= 1;
859
+ continue;
860
+ }
796
861
  report.routedToPlatform += 1;
797
862
  outcomeOf(event, 'routed');
798
863
  // Handed on, not run here: the platform's drain owns its attempts from now on.
@@ -1969,6 +2034,21 @@ export class CloudflareScopeHost {
1969
2034
  if (parentless)
1970
2035
  throw parentless;
1971
2036
  }
2037
+ // #2993 (K-64): a sibling of an app that declares scope types claims the home as an install does,
2038
+ // judged by the directory in its own unit. Typed by this host's own declaration, or (a module-less
2039
+ // coordinator) by the vertical's deployed version's, read only for a sibling.
2040
+ const typedSibling = input.sibling === true && record.vertical !== null &&
2041
+ (plan.declared || (await this.verticalScopeTypePlan(record.vertical)).declared);
2042
+ const homeClaim = {
2043
+ vertical: record.vertical,
2044
+ type: scopeType,
2045
+ parentScopeId,
2046
+ forkedFrom: record.forkedFrom,
2047
+ kind: record.kind,
2048
+ install: input.install,
2049
+ sibling: input.sibling,
2050
+ typed: typedSibling,
2051
+ };
1972
2052
  // Fail-closed tenant gate throws out of the awaited cp call BEFORE migrate
1973
2053
  // or audit, so a rejected provision creates nothing and writes no audit row.
1974
2054
  const created = await this.directory('provisionScope', input.tenantId, input.scopeId,
@@ -1982,16 +2062,9 @@ export class CloudflareScopeHost {
1982
2062
  ? { parentScopeId: input.parentScopeId }
1983
2063
  : recorded === undefined && parentScopeId !== null ? { parentScopeId } : {}),
1984
2064
  // #3625 (K-64): an install, which the directory refuses in its own unit while the app has a home
1985
- // scope in the tenant (`secondHomeRefusal`). Sent only when true, so a write without it is judged
1986
- // as before.
1987
- ...(claimsHome({
1988
- vertical: record.vertical,
1989
- type: scopeType,
1990
- parentScopeId,
1991
- forkedFrom: record.forkedFrom,
1992
- kind: record.kind,
1993
- install: input.install,
1994
- }) ? { claimsHome: true } : {}),
2065
+ // scope in the tenant (`secondHomeRefusal`). Sent only when it claims, so a write without it is
2066
+ // judged as before. #2993: `'sibling'` for a sibling of a typed app, refused in its own words.
2067
+ ...(claimsHome(homeClaim) ? { claimsHome: input.install === true ? true : 'sibling' } : {}),
1995
2068
  }, new Date().toISOString());
1996
2069
  // #2993 part 3: the scope's own object records its type before anything migrates it, so its
1997
2070
  // first pass lays down only its type's tables. A host with no declared types asks nothing. A
@@ -2526,7 +2599,7 @@ export class CloudflareScopeHost {
2526
2599
  const load = { sourceScopeId: dump.scopeId, exact: true };
2527
2600
  // #2555: an import lands with the directory's current permission state, as a restore does. A
2528
2601
  // snapshot is left as it was: a same-instant copy of a live scope the fan-out keeps current.
2529
- const projection = judge ? await this.loadProjectionFor(input.tenantId, input.vertical) : undefined;
2602
+ const projection = judge ? await this.loadProjectionFor(input.tenantId, input.vertical, input.scopeId) : undefined;
2530
2603
  let reprojected;
2531
2604
  if (projection === undefined)
2532
2605
  await this.scopeStub(input.scopeId).importDump(dump.tables, input.scopeId, load);
@@ -2574,7 +2647,7 @@ export class CloudflareScopeHost {
2574
2647
  // #2555: judged before the fence, so a refused restore moves nothing.
2575
2648
  await this.refuseDumpRoles(tenantId, scopeId, dump);
2576
2649
  // #2555: the directory's state the load projects, judged again in its unit against the seats it loads.
2577
- const projection = await this.loadProjectionFor(tenantId, existing.vertical);
2650
+ const projection = await this.loadProjectionFor(tenantId, existing.vertical, scopeId);
2578
2651
  // #2314: the load replaces the scope's rows, so the orphan sweep is fenced first.
2579
2652
  await this.fenceOrphanSweep(scopeId, tenantId);
2580
2653
  // #1742: a dump from before a switch was pulled brings the module's grants back live, so
@@ -7223,7 +7296,7 @@ export class CloudflareScopeHost {
7223
7296
  // here could never be removed.
7224
7297
  },
7225
7298
  connectionSealingKey: async (id) => this.ensureSealingKey(id),
7226
- connectionSealingKeys: async (tenantId, vertical) => {
7299
+ connectionSealingKeys: async (tenantId, vertical, scopeId) => {
7227
7300
  // LIVE connections only. A revoked connection's key is KEPT (its pending
7228
7301
  // ciphertext must still open) but stops being projected, so a scope can no
7229
7302
  // longer seal to a credential that has been withdrawn. Tenant-owned only (#2732): a
@@ -7232,7 +7305,23 @@ export class CloudflareScopeHost {
7232
7305
  const out = [];
7233
7306
  for (const r of rows)
7234
7307
  out.push(await this.ensureSealingKey(r.id));
7235
- return out;
7308
+ if (!scopeId)
7309
+ return out;
7310
+ // #3530 step 6: the scope of an environment given connections of its own seals to its own
7311
+ // connection of a provider in place of the tenant's (`sealingKeysForReach`), the oldest per provider.
7312
+ const reach = connectionReachSchema.parse(await this.cp.connectionReach(tenantId, scopeId));
7313
+ if (reach !== 'own')
7314
+ return out;
7315
+ const owned = (await this.cp.listConnections({ tenantId, vertical, ownerScopeId: scopeId })).sort((a, b) => String(a.created_at).localeCompare(String(b.created_at)));
7316
+ const seen = new Set();
7317
+ const own = [];
7318
+ for (const r of owned) {
7319
+ if (seen.has(r.provider))
7320
+ continue;
7321
+ seen.add(r.provider);
7322
+ own.push(await this.ensureSealingKey(r.id));
7323
+ }
7324
+ return sealingKeysForReach(reach, out, own);
7236
7325
  },
7237
7326
  listConnections: async (actor, filter) => {
7238
7327
  const f = filter ?? {};
@@ -7949,12 +8038,22 @@ export class CloudflareScopeHost {
7949
8038
  * again: on the next pass after the first failure, then backing off (#3119), so a scope that can
7950
8039
  * never be delivered to is not asked every pass for good. Only news is an ops-failure row — the
7951
8040
  * first failure against a receipt and a deployment, or another error than the last.
8041
+ *
8042
+ * K-69 (#3540): with a `lifecycleRetryOwner`, that retry is the owner's. A failed delivery is
8043
+ * handed over as it fails, and the heal sweep hands over, undelivered, the scopes it finds owed one,
8044
+ * the live scopes it finds owed their first delivery after a restore (`owedFirstDelivery`), and the
8045
+ * acknowledged holds whose deployment moved (`owedHoldRedelivery`). An acknowledged hold whose
8046
+ * deployment did not move is not delivered at all. `retry` is the owner's own run: only a scope owed
8047
+ * one of the three, delivered even when the receipt says nothing changed (a failure is owed whatever
8048
+ * the receipt), and never handed over again.
7952
8049
  */
7953
8050
  async deliverLifecycles(actor, filter) {
7954
8051
  const report = { attempted: 0, delivered: 0, failed: 0 };
7955
8052
  const delegation = this.lifecycleDelegation;
7956
8053
  if (!delegation || this.cpLess)
7957
8054
  return report;
8055
+ const owner = filter.retry ? undefined : this.lifecycleRetryOwner;
8056
+ const handOver = [];
7958
8057
  let targets;
7959
8058
  // #2016: the heal also asks the served scopes whose deployment has not answered that it holds a
7960
8059
  // record of the scope's tenant, a copy as much as a primary (no push reconciles a copy), until
@@ -7983,6 +8082,14 @@ export class CloudflareScopeHost {
7983
8082
  for (const first of targets) {
7984
8083
  const tenantId = first.tenant_id;
7985
8084
  const scopeId = first.scope_id;
8085
+ if (filter.retry && first.retry_at === null && !owedFirstDelivery(first) && !owedHoldRedelivery(first))
8086
+ continue;
8087
+ // K-69 (#3540): the sweep's check. A scope owed a retry is its owner's, at once: the directory
8088
+ // only lists one whose back-off is over, or whose receipt or deployment moved since.
8089
+ if (filter.drift && owner && first.retry_at !== null) {
8090
+ handOver.push({ tenantId, scopeId, dueAt: Date.now() });
8091
+ continue;
8092
+ }
7986
8093
  let t = first;
7987
8094
  let lifecycle = this.lifecycleOfTarget(t);
7988
8095
  if (!lifecycle) {
@@ -7991,13 +8098,28 @@ export class CloudflareScopeHost {
7991
8098
  console.error(`substrat: scope ${scopeId} has a lifecycle this code cannot read (#1713)`);
7992
8099
  continue;
7993
8100
  }
8101
+ // K-69 (#3540): a live scope's first delivery after a restore is its owner's too. A scope the
8102
+ // heal asks for its tenant record is still delivered here.
8103
+ if (filter.drift && owner && !askTenant.has(scopeId) && lifecycleRefusal(lifecycle) === null && owedFirstDelivery(t)) {
8104
+ handOver.push({ tenantId, scopeId, dueAt: Date.now() });
8105
+ continue;
8106
+ }
8107
+ // K-69 (#3540): and so is a hold the deployment acknowledged, when the deployment serving the
8108
+ // scope moved since; one acknowledged where it is still served is owed nothing. A hold not
8109
+ // acknowledged yet is delivered here, so the sweep never delays a hold that did not land.
8110
+ if (filter.drift && owner && !askTenant.has(scopeId) && acknowledgedHold(t)) {
8111
+ if (owedHoldRedelivery(t))
8112
+ handOver.push({ tenantId, scopeId, dueAt: Date.now() });
8113
+ continue;
8114
+ }
7994
8115
  // A live scope whose deployment already acknowledged exactly this has nothing to receive,
7995
8116
  // and neither does one with no receipt in a directory never restored: a deployment holding
7996
8117
  // no lifecycle runs live. That keeps an activation, and every transition before a
7997
8118
  // deployment carries the route, from posting a delivery that changes nothing. After a
7998
8119
  // restore (epoch > 0) no receipt says nothing about what the deployment holds, so it is
7999
8120
  // delivered. A HOLD is always delivered, and so is a scope the heal asks for its tenant record.
8000
- if (!askTenant.has(scopeId) &&
8121
+ if (!filter.retry &&
8122
+ !askTenant.has(scopeId) &&
8001
8123
  lifecycleRefusal(lifecycle) === null &&
8002
8124
  (t.delivered === null ? t.epoch === 0 : t.delivered === lifecycleReceipt(lifecycle))) {
8003
8125
  continue;
@@ -8056,8 +8178,9 @@ export class CloudflareScopeHost {
8056
8178
  answer = await delegation.deliver({ tenantId, scopeId, lifecycle });
8057
8179
  }
8058
8180
  }
8059
- // The receipt is what the scope HOLDS: a newer delivery it kept instead is the truth.
8060
- await this.cp.recordLifecycleReceipt(scopeId, lifecycleReceipt(answer.lifecycle), new Date().toISOString(), answer.tenantRecorded === true);
8181
+ // The receipt is what the scope HOLDS: a newer delivery it kept instead is the truth. K-69
8182
+ // (#3540): with the deployment read before the delivery, so a move during it reads as moved.
8183
+ await this.cp.recordLifecycleReceipt(scopeId, lifecycleReceipt(answer.lifecycle), new Date().toISOString(), answer.tenantRecorded === true, t.deployment);
8061
8184
  report.delivered += 1;
8062
8185
  }
8063
8186
  catch (err) {
@@ -8065,14 +8188,19 @@ export class CloudflareScopeHost {
8065
8188
  const text = err instanceof Error ? err.message : String(err);
8066
8189
  // #3119: a repeat of the last failure is counted, not filed. If the count cannot be kept,
8067
8190
  // the row is filed: a missed failure is worse than a repeated one.
8068
- const news = await this.cp
8191
+ const counted = await this.cp
8069
8192
  .recordLifecycleFailure(scopeId, lifecycleReceipt(lifecycle), t.deployment, text, new Date().toISOString())
8070
- .then((f) => f.news)
8071
8193
  .catch((e) => {
8072
8194
  console.error('substrat: could not count a lifecycle delivery failure (#3119)', e);
8073
- return true;
8195
+ return null;
8074
8196
  });
8075
- if (!news)
8197
+ // K-69 (#3540): the failure is the event that makes its retry due on the owner, a minute on
8198
+ // or at the end of the directory's back-off, whichever is later.
8199
+ if (owner) {
8200
+ const retryAt = counted ? Date.parse(counted.retryAt) : 0;
8201
+ handOver.push({ tenantId, scopeId, dueAt: Math.max(retryAt, Date.now() + LIFECYCLE_RETRY_FIRST_LOOK_MS) });
8202
+ }
8203
+ if (counted && !counted.news)
8076
8204
  continue;
8077
8205
  try {
8078
8206
  // #2554: the throw is the deployment's or its runtime's text, and the deployment serving
@@ -8086,6 +8214,16 @@ export class CloudflareScopeHost {
8086
8214
  }
8087
8215
  }
8088
8216
  }
8217
+ if (owner && handOver.length > 0) {
8218
+ try {
8219
+ await owner.handOver(handOver);
8220
+ report.handedOver = handOver.length;
8221
+ }
8222
+ catch (err) {
8223
+ // Never thrown, like a failed delivery: the failure row stays, and the next sweep hands it over again.
8224
+ console.error('substrat: could not hand lifecycle retries to their owner (#3540)', { scopes: handOver.length, err });
8225
+ }
8226
+ }
8089
8227
  return report;
8090
8228
  }
8091
8229
  /** One directory row as the lifecycle a delivery carries (#1713), or null for a status this code does not know. */
@@ -8102,11 +8240,37 @@ export class CloudflareScopeHost {
8102
8240
  * The heal sweep (#1713): deliver the lifecycle to every hosted scope whose deployment's
8103
8241
  * acknowledged state differs from the directory, and again to every scope held now — which is
8104
8242
  * what puts a hold back on a store a carry or a restore landed without it. Bounded per pass
8105
- * (`limit`), drifted scopes first. Run from the shared control plane's cron.
8243
+ * (`limit`), drifted scopes first. Run from the shared control plane's cron. With a
8244
+ * `lifecycleRetryOwner` (K-69, #3540), the retries, the first deliveries after a restore and the
8245
+ * acknowledged holds whose deployment moved are handed to it, undelivered, and an acknowledged hold
8246
+ * whose deployment did not move is delivered no more.
8106
8247
  */
8107
8248
  async healLifecycles(actor, opts) {
8108
8249
  return this.deliverLifecycles(actor, { drift: true, limit: opts?.limit ?? 200 });
8109
8250
  }
8251
+ /**
8252
+ * K-69 (#3540): one retry of a scope's failed lifecycle delivery, its first delivery after a
8253
+ * directory restore, or an acknowledged hold's delivery to the deployment that now serves it, for
8254
+ * its `lifecycleRetryOwner`. Re-reads the directory and delivers only when the scope is still owed
8255
+ * one of the three (a later transition that landed owes none), with the
8256
+ * delivery's own epoch handling and failure count; a first delivery that fails is a retry from then.
8257
+ * Answers when to look again (epoch ms), or null when nothing more is owed. Throws only when the
8258
+ * directory cannot be read, so the owner keeps the retry.
8259
+ */
8260
+ async retryLifecycle(actor, tenantId, scopeId) {
8261
+ const [owed] = await this.cp.lifecycleTargets({ tenantId, scopeId });
8262
+ if (!owed || (owed.retry_at === null && !owedFirstDelivery(owed) && !owedHoldRedelivery(owed)))
8263
+ return null;
8264
+ const report = await this.deliverLifecycles(actor, { tenantId, scopeId, retry: true });
8265
+ if (report.failed === 0)
8266
+ return null;
8267
+ // A failure the directory did not count (a foreign epoch, a status this code cannot read) is
8268
+ // not a retry: the sweep finds that scope again itself, as it did before.
8269
+ const [after] = await this.cp.lifecycleTargets({ tenantId, scopeId });
8270
+ if (!after || after.retry_at === null)
8271
+ return null;
8272
+ return Math.max(Date.parse(after.retry_at), Date.now() + LIFECYCLE_RETRY_FIRST_LOOK_MS);
8273
+ }
8110
8274
  /**
8111
8275
  * Whether a CP-less host holds this scope's work (#1713): `assertLive`'s predicate, answered
8112
8276
  * rather than thrown, for the entry points that defer instead of refusing — a sweep pass, a
@@ -8790,10 +8954,10 @@ export class CloudflareScopeHost {
8790
8954
  * this scope a write channel into a credential it may not reach. `[]` for a scope
8791
8955
  * bound to no vertical — which then seals to nothing, the fail-closed direction.
8792
8956
  */
8793
- async connectionKeyRows(tenantId, vertical) {
8957
+ async connectionKeyRows(tenantId, vertical, scopeId) {
8794
8958
  if (!vertical)
8795
8959
  return [];
8796
- const keys = await this.admin.connectionSealingKeys(tenantId, vertical);
8960
+ const keys = await this.admin.connectionSealingKeys(tenantId, vertical, scopeId);
8797
8961
  return keys.map((k) => ({
8798
8962
  connection_id: k.connectionId,
8799
8963
  provider: k.provider,
@@ -8813,7 +8977,7 @@ export class CloudflareScopeHost {
8813
8977
  if (!scope)
8814
8978
  throw unknownScopeForTenant(tenantId, scopeId);
8815
8979
  const { roles, tuples, entitlements, identities } = await this.tenantProjection(tenantId);
8816
- const connectionKeys = await this.connectionKeyRows(tenantId, scope.vertical);
8980
+ const connectionKeys = await this.connectionKeyRows(tenantId, scope.vertical, scopeId);
8817
8981
  unwrapReply(await this.scopeStub(scopeId).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, connectionKeys));
8818
8982
  }
8819
8983
  /**
@@ -8860,10 +9024,14 @@ export class CloudflareScopeHost {
8860
9024
  // revoke for the tenant's healthy ones. The failure is still loud, after the rest have landed.
8861
9025
  const settled = await Promise.allSettled(scopes.map(async (s) => {
8862
9026
  const vertical = s.vertical ?? '';
8863
- if (!keysByVertical.has(vertical)) {
8864
- keysByVertical.set(vertical, this.connectionKeyRows(tenantId, s.vertical));
9027
+ // #3530 step 6: a scope that is no install may be a named environment's, given connections of
9028
+ // its own, which seals to those: asked for itself, never shared with the vertical's installs.
9029
+ const primary = isPrimaryScopeRow(s);
9030
+ const memo = primary ? vertical : `${vertical}\u0000${s.scope_id}`;
9031
+ if (!keysByVertical.has(memo)) {
9032
+ keysByVertical.set(memo, this.connectionKeyRows(tenantId, s.vertical, primary ? undefined : s.scope_id));
8865
9033
  }
8866
- unwrapReply(await this.scopeStub(s.scope_id).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, await keysByVertical.get(vertical)));
9034
+ unwrapReply(await this.scopeStub(s.scope_id).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, await keysByVertical.get(memo)));
8867
9035
  }));
8868
9036
  const failed = settled.flatMap((r, i) => (r.status === 'rejected' ? [{ scope: scopes[i].scope_id, reason: r.reason }] : []));
8869
9037
  if (failed.length === 0)
@@ -9097,10 +9265,11 @@ export class CloudflareScopeHost {
9097
9265
  * judge its roles by. Null on a host that does not project permissions into its scopes: there the
9098
9266
  * load only keeps the destination's permission flags.
9099
9267
  */
9100
- async loadProjectionFor(tenantId, vertical) {
9268
+ async loadProjectionFor(tenantId, vertical, scopeId) {
9101
9269
  if (!this.scopeLocalPermissions)
9102
9270
  return null;
9103
- const [state, connectionKeys] = await Promise.all([this.tenantProjection(tenantId), this.connectionKeyRows(tenantId, vertical)]);
9271
+ // #3530 step 6: the keys the scope itself seals to, its own where it is an environment given its own.
9272
+ const [state, connectionKeys] = await Promise.all([this.tenantProjection(tenantId), this.connectionKeyRows(tenantId, vertical, scopeId)]);
9104
9273
  return { tenantId, ...state, connectionKeys, judge: this.roleJudge() };
9105
9274
  }
9106
9275
  /**
@@ -9168,7 +9337,7 @@ export class CloudflareScopeHost {
9168
9337
  */
9169
9338
  async convergeLoadedProjection(tenantId, scopeId, vertical, loaded, verb) {
9170
9339
  try {
9171
- const now = await this.loadProjectionFor(tenantId, vertical);
9340
+ const now = await this.loadProjectionFor(tenantId, vertical, scopeId);
9172
9341
  if (!now || projectionDigest(now) === projectionDigest(loaded))
9173
9342
  return {};
9174
9343
  unwrapReply(await this.scopeStub(scopeId).applyJudgedProjectionReply(this.roleJudge(), tenantId, now.roles, now.tuples, now.entitlements, undefined, now.identities, now.connectionKeys));