@substrat-run/adapter-cloudflare 0.222.0 → 0.223.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.
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,12 @@ 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;
58
65
  /**
59
66
  * K-3's refusal of a (tenant, scope) pair the host does not hold — the same answer for a scope that
60
67
  * does not exist and for one of another tenant (#1718), in one wording.
@@ -474,6 +481,7 @@ export class CloudflareScopeHost {
474
481
  systemSwitchDelegation;
475
482
  /** #1713: the lifecycle's reach into the deployment serving a scope. */
476
483
  lifecycleDelegation;
484
+ lifecycleRetryOwner;
477
485
  /** #1706: the peer kill switch's reach into the deployment serving a scope. */
478
486
  peerSwitchDelegation;
479
487
  /** #1705 PR 3: the replay lever's reach into the deployment serving a consumer scope. */
@@ -546,6 +554,7 @@ export class CloudflareScopeHost {
546
554
  this.eventDrainDelegation = options.eventDrainDelegation;
547
555
  this.systemSwitchDelegation = options.systemSwitchDelegation;
548
556
  this.lifecycleDelegation = options.lifecycleDelegation;
557
+ this.lifecycleRetryOwner = options.lifecycleRetryOwner;
549
558
  this.peerSwitchDelegation = options.peerSwitchDelegation;
550
559
  this.importCursorDelegation = options.importCursorDelegation;
551
560
  this.capabilityDelegation = options.capabilityDelegation;
@@ -592,14 +601,19 @@ export class CloudflareScopeHost {
592
601
  tenantId,
593
602
  scopeId,
594
603
  vertical: vertical ?? '',
595
- connection: async (provider) => {
604
+ connection: async (provider, options) => {
596
605
  if (!vertical) {
597
606
  throw new Error(`scope ${scopeId} is bound to no vertical, so it has no connection namespace — ` +
598
607
  `provision it with a vertical before using connectors`);
599
608
  }
600
- const open = await admin.openConnection(tenantId, vertical, provider);
609
+ // #3530 step 6: `own` opens this scope's own connection, and never the tenant's.
610
+ const open = options?.own
611
+ ? await admin.openConnection(tenantId, vertical, provider, undefined, scopeId)
612
+ : await admin.openConnection(tenantId, vertical, provider);
601
613
  if (!open) {
602
- throw new Error(`no live '${provider}' connection for tenant ${tenantId} / vertical '${vertical}'`);
614
+ throw new Error(options?.own
615
+ ? `scope ${scopeId} owns no live '${provider}' connection, and a dispatch held to its own opens no other`
616
+ : `no live '${provider}' connection for tenant ${tenantId} / vertical '${vertical}'`);
603
617
  }
604
618
  return {
605
619
  ...open,
@@ -793,6 +807,13 @@ export class CloudflareScopeHost {
793
807
  roomFull = true;
794
808
  continue drain;
795
809
  }
810
+ if (routed === EXECUTOR_ROUTE_NOT_DUE) {
811
+ // #3676: another pass acting on the same due read routed it first. The scope decided
812
+ // that in the transaction that would have written, so nothing was: not an attempt,
813
+ // and not a full room — the pass goes on to the next delivery.
814
+ report.attempted -= 1;
815
+ continue;
816
+ }
796
817
  report.routedToPlatform += 1;
797
818
  outcomeOf(event, 'routed');
798
819
  // Handed on, not run here: the platform's drain owns its attempts from now on.
@@ -1969,6 +1990,21 @@ export class CloudflareScopeHost {
1969
1990
  if (parentless)
1970
1991
  throw parentless;
1971
1992
  }
1993
+ // #2993 (K-64): a sibling of an app that declares scope types claims the home as an install does,
1994
+ // judged by the directory in its own unit. Typed by this host's own declaration, or (a module-less
1995
+ // coordinator) by the vertical's deployed version's, read only for a sibling.
1996
+ const typedSibling = input.sibling === true && record.vertical !== null &&
1997
+ (plan.declared || (await this.verticalScopeTypePlan(record.vertical)).declared);
1998
+ const homeClaim = {
1999
+ vertical: record.vertical,
2000
+ type: scopeType,
2001
+ parentScopeId,
2002
+ forkedFrom: record.forkedFrom,
2003
+ kind: record.kind,
2004
+ install: input.install,
2005
+ sibling: input.sibling,
2006
+ typed: typedSibling,
2007
+ };
1972
2008
  // Fail-closed tenant gate throws out of the awaited cp call BEFORE migrate
1973
2009
  // or audit, so a rejected provision creates nothing and writes no audit row.
1974
2010
  const created = await this.directory('provisionScope', input.tenantId, input.scopeId,
@@ -1982,16 +2018,9 @@ export class CloudflareScopeHost {
1982
2018
  ? { parentScopeId: input.parentScopeId }
1983
2019
  : recorded === undefined && parentScopeId !== null ? { parentScopeId } : {}),
1984
2020
  // #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 } : {}),
2021
+ // scope in the tenant (`secondHomeRefusal`). Sent only when it claims, so a write without it is
2022
+ // judged as before. #2993: `'sibling'` for a sibling of a typed app, refused in its own words.
2023
+ ...(claimsHome(homeClaim) ? { claimsHome: input.install === true ? true : 'sibling' } : {}),
1995
2024
  }, new Date().toISOString());
1996
2025
  // #2993 part 3: the scope's own object records its type before anything migrates it, so its
1997
2026
  // first pass lays down only its type's tables. A host with no declared types asks nothing. A
@@ -2526,7 +2555,7 @@ export class CloudflareScopeHost {
2526
2555
  const load = { sourceScopeId: dump.scopeId, exact: true };
2527
2556
  // #2555: an import lands with the directory's current permission state, as a restore does. A
2528
2557
  // 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;
2558
+ const projection = judge ? await this.loadProjectionFor(input.tenantId, input.vertical, input.scopeId) : undefined;
2530
2559
  let reprojected;
2531
2560
  if (projection === undefined)
2532
2561
  await this.scopeStub(input.scopeId).importDump(dump.tables, input.scopeId, load);
@@ -2574,7 +2603,7 @@ export class CloudflareScopeHost {
2574
2603
  // #2555: judged before the fence, so a refused restore moves nothing.
2575
2604
  await this.refuseDumpRoles(tenantId, scopeId, dump);
2576
2605
  // #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);
2606
+ const projection = await this.loadProjectionFor(tenantId, existing.vertical, scopeId);
2578
2607
  // #2314: the load replaces the scope's rows, so the orphan sweep is fenced first.
2579
2608
  await this.fenceOrphanSweep(scopeId, tenantId);
2580
2609
  // #1742: a dump from before a switch was pulled brings the module's grants back live, so
@@ -7223,7 +7252,7 @@ export class CloudflareScopeHost {
7223
7252
  // here could never be removed.
7224
7253
  },
7225
7254
  connectionSealingKey: async (id) => this.ensureSealingKey(id),
7226
- connectionSealingKeys: async (tenantId, vertical) => {
7255
+ connectionSealingKeys: async (tenantId, vertical, scopeId) => {
7227
7256
  // LIVE connections only. A revoked connection's key is KEPT (its pending
7228
7257
  // ciphertext must still open) but stops being projected, so a scope can no
7229
7258
  // longer seal to a credential that has been withdrawn. Tenant-owned only (#2732): a
@@ -7232,7 +7261,23 @@ export class CloudflareScopeHost {
7232
7261
  const out = [];
7233
7262
  for (const r of rows)
7234
7263
  out.push(await this.ensureSealingKey(r.id));
7235
- return out;
7264
+ if (!scopeId)
7265
+ return out;
7266
+ // #3530 step 6: the scope of an environment given connections of its own seals to its own
7267
+ // connection of a provider in place of the tenant's (`sealingKeysForReach`), the oldest per provider.
7268
+ const reach = connectionReachSchema.parse(await this.cp.connectionReach(tenantId, scopeId));
7269
+ if (reach !== 'own')
7270
+ return out;
7271
+ const owned = (await this.cp.listConnections({ tenantId, vertical, ownerScopeId: scopeId })).sort((a, b) => String(a.created_at).localeCompare(String(b.created_at)));
7272
+ const seen = new Set();
7273
+ const own = [];
7274
+ for (const r of owned) {
7275
+ if (seen.has(r.provider))
7276
+ continue;
7277
+ seen.add(r.provider);
7278
+ own.push(await this.ensureSealingKey(r.id));
7279
+ }
7280
+ return sealingKeysForReach(reach, out, own);
7236
7281
  },
7237
7282
  listConnections: async (actor, filter) => {
7238
7283
  const f = filter ?? {};
@@ -7949,12 +7994,19 @@ export class CloudflareScopeHost {
7949
7994
  * again: on the next pass after the first failure, then backing off (#3119), so a scope that can
7950
7995
  * never be delivered to is not asked every pass for good. Only news is an ops-failure row — the
7951
7996
  * first failure against a receipt and a deployment, or another error than the last.
7997
+ *
7998
+ * K-69 (#3540): with a `lifecycleRetryOwner`, that retry is the owner's. A failed delivery is
7999
+ * handed over as it fails, and the heal sweep hands over, undelivered, the scopes it finds owed one.
8000
+ * `retry` is the owner's own run: only a scope owed a retry, delivered even when the receipt says
8001
+ * nothing changed (a failure is owed whatever the receipt), and never handed over again.
7952
8002
  */
7953
8003
  async deliverLifecycles(actor, filter) {
7954
8004
  const report = { attempted: 0, delivered: 0, failed: 0 };
7955
8005
  const delegation = this.lifecycleDelegation;
7956
8006
  if (!delegation || this.cpLess)
7957
8007
  return report;
8008
+ const owner = filter.retry ? undefined : this.lifecycleRetryOwner;
8009
+ const handOver = [];
7958
8010
  let targets;
7959
8011
  // #2016: the heal also asks the served scopes whose deployment has not answered that it holds a
7960
8012
  // record of the scope's tenant, a copy as much as a primary (no push reconciles a copy), until
@@ -7983,6 +8035,14 @@ export class CloudflareScopeHost {
7983
8035
  for (const first of targets) {
7984
8036
  const tenantId = first.tenant_id;
7985
8037
  const scopeId = first.scope_id;
8038
+ if (filter.retry && first.retry_at === null)
8039
+ continue;
8040
+ // K-69 (#3540): the sweep's check. A scope owed a retry is its owner's, at once: the directory
8041
+ // only lists one whose back-off is over, or whose receipt or deployment moved since.
8042
+ if (filter.drift && owner && first.retry_at !== null) {
8043
+ handOver.push({ tenantId, scopeId, dueAt: Date.now() });
8044
+ continue;
8045
+ }
7986
8046
  let t = first;
7987
8047
  let lifecycle = this.lifecycleOfTarget(t);
7988
8048
  if (!lifecycle) {
@@ -7997,7 +8057,8 @@ export class CloudflareScopeHost {
7997
8057
  // deployment carries the route, from posting a delivery that changes nothing. After a
7998
8058
  // restore (epoch > 0) no receipt says nothing about what the deployment holds, so it is
7999
8059
  // delivered. A HOLD is always delivered, and so is a scope the heal asks for its tenant record.
8000
- if (!askTenant.has(scopeId) &&
8060
+ if (!filter.retry &&
8061
+ !askTenant.has(scopeId) &&
8001
8062
  lifecycleRefusal(lifecycle) === null &&
8002
8063
  (t.delivered === null ? t.epoch === 0 : t.delivered === lifecycleReceipt(lifecycle))) {
8003
8064
  continue;
@@ -8065,14 +8126,19 @@ export class CloudflareScopeHost {
8065
8126
  const text = err instanceof Error ? err.message : String(err);
8066
8127
  // #3119: a repeat of the last failure is counted, not filed. If the count cannot be kept,
8067
8128
  // the row is filed: a missed failure is worse than a repeated one.
8068
- const news = await this.cp
8129
+ const counted = await this.cp
8069
8130
  .recordLifecycleFailure(scopeId, lifecycleReceipt(lifecycle), t.deployment, text, new Date().toISOString())
8070
- .then((f) => f.news)
8071
8131
  .catch((e) => {
8072
8132
  console.error('substrat: could not count a lifecycle delivery failure (#3119)', e);
8073
- return true;
8133
+ return null;
8074
8134
  });
8075
- if (!news)
8135
+ // K-69 (#3540): the failure is the event that makes its retry due on the owner, a minute on
8136
+ // or at the end of the directory's back-off, whichever is later.
8137
+ if (owner) {
8138
+ const retryAt = counted ? Date.parse(counted.retryAt) : 0;
8139
+ handOver.push({ tenantId, scopeId, dueAt: Math.max(retryAt, Date.now() + LIFECYCLE_RETRY_FIRST_LOOK_MS) });
8140
+ }
8141
+ if (counted && !counted.news)
8076
8142
  continue;
8077
8143
  try {
8078
8144
  // #2554: the throw is the deployment's or its runtime's text, and the deployment serving
@@ -8086,6 +8152,16 @@ export class CloudflareScopeHost {
8086
8152
  }
8087
8153
  }
8088
8154
  }
8155
+ if (owner && handOver.length > 0) {
8156
+ try {
8157
+ await owner.handOver(handOver);
8158
+ report.handedOver = handOver.length;
8159
+ }
8160
+ catch (err) {
8161
+ // Never thrown, like a failed delivery: the failure row stays, and the next sweep hands it over again.
8162
+ console.error('substrat: could not hand lifecycle retries to their owner (#3540)', { scopes: handOver.length, err });
8163
+ }
8164
+ }
8089
8165
  return report;
8090
8166
  }
8091
8167
  /** One directory row as the lifecycle a delivery carries (#1713), or null for a status this code does not know. */
@@ -8107,6 +8183,27 @@ export class CloudflareScopeHost {
8107
8183
  async healLifecycles(actor, opts) {
8108
8184
  return this.deliverLifecycles(actor, { drift: true, limit: opts?.limit ?? 200 });
8109
8185
  }
8186
+ /**
8187
+ * K-69 (#3540): one retry of a scope's failed lifecycle delivery, for its `lifecycleRetryOwner`.
8188
+ * Re-reads the directory and delivers only when the scope is still owed a retry (a later
8189
+ * transition that landed owes none), with the delivery's own epoch handling and failure count.
8190
+ * Answers when to look again (epoch ms), or null when nothing more is owed. Throws only when the
8191
+ * directory cannot be read, so the owner keeps the retry.
8192
+ */
8193
+ async retryLifecycle(actor, tenantId, scopeId) {
8194
+ const [owed] = await this.cp.lifecycleTargets({ tenantId, scopeId });
8195
+ if (!owed || owed.retry_at === null)
8196
+ return null;
8197
+ const report = await this.deliverLifecycles(actor, { tenantId, scopeId, retry: true });
8198
+ if (report.failed === 0)
8199
+ return null;
8200
+ // A failure the directory did not count (a foreign epoch, a status this code cannot read) is
8201
+ // not a retry: the sweep delivers that scope itself, as it did before.
8202
+ const [after] = await this.cp.lifecycleTargets({ tenantId, scopeId });
8203
+ if (!after || after.retry_at === null)
8204
+ return null;
8205
+ return Math.max(Date.parse(after.retry_at), Date.now() + LIFECYCLE_RETRY_FIRST_LOOK_MS);
8206
+ }
8110
8207
  /**
8111
8208
  * Whether a CP-less host holds this scope's work (#1713): `assertLive`'s predicate, answered
8112
8209
  * rather than thrown, for the entry points that defer instead of refusing — a sweep pass, a
@@ -8790,10 +8887,10 @@ export class CloudflareScopeHost {
8790
8887
  * this scope a write channel into a credential it may not reach. `[]` for a scope
8791
8888
  * bound to no vertical — which then seals to nothing, the fail-closed direction.
8792
8889
  */
8793
- async connectionKeyRows(tenantId, vertical) {
8890
+ async connectionKeyRows(tenantId, vertical, scopeId) {
8794
8891
  if (!vertical)
8795
8892
  return [];
8796
- const keys = await this.admin.connectionSealingKeys(tenantId, vertical);
8893
+ const keys = await this.admin.connectionSealingKeys(tenantId, vertical, scopeId);
8797
8894
  return keys.map((k) => ({
8798
8895
  connection_id: k.connectionId,
8799
8896
  provider: k.provider,
@@ -8813,7 +8910,7 @@ export class CloudflareScopeHost {
8813
8910
  if (!scope)
8814
8911
  throw unknownScopeForTenant(tenantId, scopeId);
8815
8912
  const { roles, tuples, entitlements, identities } = await this.tenantProjection(tenantId);
8816
- const connectionKeys = await this.connectionKeyRows(tenantId, scope.vertical);
8913
+ const connectionKeys = await this.connectionKeyRows(tenantId, scope.vertical, scopeId);
8817
8914
  unwrapReply(await this.scopeStub(scopeId).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, connectionKeys));
8818
8915
  }
8819
8916
  /**
@@ -8860,10 +8957,14 @@ export class CloudflareScopeHost {
8860
8957
  // revoke for the tenant's healthy ones. The failure is still loud, after the rest have landed.
8861
8958
  const settled = await Promise.allSettled(scopes.map(async (s) => {
8862
8959
  const vertical = s.vertical ?? '';
8863
- if (!keysByVertical.has(vertical)) {
8864
- keysByVertical.set(vertical, this.connectionKeyRows(tenantId, s.vertical));
8960
+ // #3530 step 6: a scope that is no install may be a named environment's, given connections of
8961
+ // its own, which seals to those: asked for itself, never shared with the vertical's installs.
8962
+ const primary = isPrimaryScopeRow(s);
8963
+ const memo = primary ? vertical : `${vertical}\u0000${s.scope_id}`;
8964
+ if (!keysByVertical.has(memo)) {
8965
+ keysByVertical.set(memo, this.connectionKeyRows(tenantId, s.vertical, primary ? undefined : s.scope_id));
8865
8966
  }
8866
- unwrapReply(await this.scopeStub(s.scope_id).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, await keysByVertical.get(vertical)));
8967
+ unwrapReply(await this.scopeStub(s.scope_id).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, await keysByVertical.get(memo)));
8867
8968
  }));
8868
8969
  const failed = settled.flatMap((r, i) => (r.status === 'rejected' ? [{ scope: scopes[i].scope_id, reason: r.reason }] : []));
8869
8970
  if (failed.length === 0)
@@ -9097,10 +9198,11 @@ export class CloudflareScopeHost {
9097
9198
  * judge its roles by. Null on a host that does not project permissions into its scopes: there the
9098
9199
  * load only keeps the destination's permission flags.
9099
9200
  */
9100
- async loadProjectionFor(tenantId, vertical) {
9201
+ async loadProjectionFor(tenantId, vertical, scopeId) {
9101
9202
  if (!this.scopeLocalPermissions)
9102
9203
  return null;
9103
- const [state, connectionKeys] = await Promise.all([this.tenantProjection(tenantId), this.connectionKeyRows(tenantId, vertical)]);
9204
+ // #3530 step 6: the keys the scope itself seals to, its own where it is an environment given its own.
9205
+ const [state, connectionKeys] = await Promise.all([this.tenantProjection(tenantId), this.connectionKeyRows(tenantId, vertical, scopeId)]);
9104
9206
  return { tenantId, ...state, connectionKeys, judge: this.roleJudge() };
9105
9207
  }
9106
9208
  /**
@@ -9168,7 +9270,7 @@ export class CloudflareScopeHost {
9168
9270
  */
9169
9271
  async convergeLoadedProjection(tenantId, scopeId, vertical, loaded, verb) {
9170
9272
  try {
9171
- const now = await this.loadProjectionFor(tenantId, vertical);
9273
+ const now = await this.loadProjectionFor(tenantId, vertical, scopeId);
9172
9274
  if (!now || projectionDigest(now) === projectionDigest(loaded))
9173
9275
  return {};
9174
9276
  unwrapReply(await this.scopeStub(scopeId).applyJudgedProjectionReply(this.roleJudge(), tenantId, now.roles, now.tuples, now.entitlements, undefined, now.identities, now.connectionKeys));