@substrat-run/adapter-cloudflare 0.229.0 → 0.230.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 (82) hide show
  1. package/dist/broker-lake.d.ts +26 -2
  2. package/dist/broker-lake.d.ts.map +1 -1
  3. package/dist/broker-lake.js +56 -3
  4. package/dist/broker-lake.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +41 -11
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +100 -48
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +13 -1
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +43 -3
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/directory-cutover.d.ts +93 -1
  14. package/dist/directory-cutover.d.ts.map +1 -1
  15. package/dist/directory-cutover.js +85 -2
  16. package/dist/directory-cutover.js.map +1 -1
  17. package/dist/directory-objects.d.ts +12 -0
  18. package/dist/directory-objects.d.ts.map +1 -1
  19. package/dist/directory-objects.js +8 -1
  20. package/dist/directory-objects.js.map +1 -1
  21. package/dist/directory-placement.d.ts.map +1 -1
  22. package/dist/directory-placement.js +1 -0
  23. package/dist/directory-placement.js.map +1 -1
  24. package/dist/directory-tenant-identities.d.ts +30 -0
  25. package/dist/directory-tenant-identities.d.ts.map +1 -0
  26. package/dist/directory-tenant-identities.js +64 -0
  27. package/dist/directory-tenant-identities.js.map +1 -0
  28. package/dist/directory-tenant-tuples.d.ts +30 -3
  29. package/dist/directory-tenant-tuples.d.ts.map +1 -1
  30. package/dist/directory-tenant-tuples.js +27 -0
  31. package/dist/directory-tenant-tuples.js.map +1 -1
  32. package/dist/host.d.ts +27 -1
  33. package/dist/host.d.ts.map +1 -1
  34. package/dist/host.js +81 -9
  35. package/dist/host.js.map +1 -1
  36. package/dist/index.d.ts +6 -2
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +8 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/peer-call-target.d.ts +16 -2
  41. package/dist/peer-call-target.d.ts.map +1 -1
  42. package/dist/peer-call-target.js +36 -6
  43. package/dist/peer-call-target.js.map +1 -1
  44. package/dist/route-read-model-publisher.d.ts.map +1 -1
  45. package/dist/route-read-model-publisher.js +4 -0
  46. package/dist/route-read-model-publisher.js.map +1 -1
  47. package/dist/route-resolver.d.ts +19 -2
  48. package/dist/route-resolver.d.ts.map +1 -1
  49. package/dist/route-resolver.js +25 -5
  50. package/dist/route-resolver.js.map +1 -1
  51. package/dist/scope-do.d.ts +19 -0
  52. package/dist/scope-do.d.ts.map +1 -1
  53. package/dist/scope-do.js +294 -8
  54. package/dist/scope-do.js.map +1 -1
  55. package/dist/scope-facets.d.ts +121 -0
  56. package/dist/scope-facets.d.ts.map +1 -0
  57. package/dist/scope-facets.js +98 -0
  58. package/dist/scope-facets.js.map +1 -0
  59. package/dist/scope-supervisor-do.d.ts +93 -0
  60. package/dist/scope-supervisor-do.d.ts.map +1 -0
  61. package/dist/scope-supervisor-do.js +504 -0
  62. package/dist/scope-supervisor-do.js.map +1 -0
  63. package/dist/scope-work.d.ts +1 -1
  64. package/dist/scope-work.js +1 -1
  65. package/dist/scope-work.js.map +1 -1
  66. package/dist/supplied-pass-box.d.ts +77 -0
  67. package/dist/supplied-pass-box.d.ts.map +1 -0
  68. package/dist/supplied-pass-box.js +265 -0
  69. package/dist/supplied-pass-box.js.map +1 -0
  70. package/dist/tenant-due-index-do.d.ts +76 -0
  71. package/dist/tenant-due-index-do.d.ts.map +1 -0
  72. package/dist/tenant-due-index-do.js +90 -0
  73. package/dist/tenant-due-index-do.js.map +1 -0
  74. package/dist/tenant-due-nudge.d.ts +66 -0
  75. package/dist/tenant-due-nudge.d.ts.map +1 -0
  76. package/dist/tenant-due-nudge.js +77 -0
  77. package/dist/tenant-due-nudge.js.map +1 -0
  78. package/dist/tenant-due-work-do.d.ts +26 -0
  79. package/dist/tenant-due-work-do.d.ts.map +1 -1
  80. package/dist/tenant-due-work-do.js +69 -5
  81. package/dist/tenant-due-work-do.js.map +1 -1
  82. package/package.json +12 -12
@@ -1,6 +1,6 @@
1
1
  import { tenantDueWorkName } from './tenant-due-work-do.js';
2
2
  import { DurableObject } from 'cloudflare:workers';
3
- import { membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, MEMBERSHIP_FENCES_TABLE, membershipFencesTableExists, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, SCOPE_STORAGE_DDL, forgetScopeStorage, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeAttachmentStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, DIRECTORY_LAKE_DDL, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink as insertConnectLinkRow, listConnectLinks as listConnectLinkRows, readConnectLink as readConnectLinkRow, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, APP_ENVIRONMENTS_DDL, claimEnvironmentServeIn, defineEnvironmentIn, ENVIRONMENT_SCRIPT_JOIN_SQL, environmentsOf, HOME_SCOPE_TYPE, homeScopeIn, secondHomeRefusal, releaseEnvironmentServeIn, removeEnvironmentIn, setEnvironmentServingIn, environmentBindRefusalIn, setEnvironmentEffectsIn, connectionReachIn, SWITCH_OWED_DDL, DEPENDENT_ERASURES_DDL, DEPENDENT_ERASURE_DUE_SQL, DEPENDENT_ERASURE_HOLD_SQL, DEPENDENT_ERASURE_OWE_SQL, DEPENDENT_ERASURE_SETTLE_SQL, nextDependentErasureAt, clearSwitchOwed, markSwitchOwed, scopeOwesSwitch, switchesOwedOf, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, recordSwitchedOff, recordSwitchedOn, recordWriteSuperseded, restoreSwitchRecord, scopesSwitchedOffFor, switchRecordStatesOf, switchRecordsOf, switchesBackfillSqlOf, switchesDdlOf, switchesTableExists, switchesTableOf, tenantHeldOf, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, DEPLOYMENT_WIRE_AUTH_DDL, deploymentWireAuthOf, forgetVerticalWireAuth, writeDeploymentWireAuth, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, driverDeclarationsOf, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, forgetVerticalScopeStores, indexVersionScopeStores, verticalScopeStoresOf, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, versionsAwaitSplit, versionsAwaitDigest, deriveMigrationDigestsBatch, deriveVersionMigrationDigest, writeVersionMigrations, MODEL_USAGE_RETENTION_DAYS, BUILD_USAGE_RETENTION_DAYS, DO_SQL_LIMITS, ulid, isPrimaryScopeRow, samePeerVertical, peerVerticalSpellings, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, LEGACY_SCOPE_ROWS_BACKFILL, loadDirectoryDump, storesFencedRefusal, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, unknownOutcomeOf, ADMIN_LOG_INDEX_DDL, ADMIN_LOG_INDEXES_SQL, readAuditedOperations, } from '@substrat-run/kernel';
3
+ import { membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, MEMBERSHIP_FENCES_TABLE, membershipFencesTableExists, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, SCOPE_STORAGE_DDL, forgetScopeStorage, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeAttachmentStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, DIRECTORY_LAKE_DDL, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink as insertConnectLinkRow, listConnectLinks as listConnectLinkRows, readConnectLink as readConnectLinkRow, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, APP_ENVIRONMENTS_DDL, claimEnvironmentServeIn, defineEnvironmentIn, ENVIRONMENT_SCRIPT_JOIN_SQL, environmentPeerResolutionIn, environmentsOf, HOME_SCOPE_TYPE, homeScopeIn, secondHomeRefusal, releaseEnvironmentServeIn, removeEnvironmentIn, setEnvironmentServingIn, environmentBindRefusalIn, setEnvironmentEffectsIn, connectionReachIn, SWITCH_OWED_DDL, DEPENDENT_ERASURES_DDL, DEPENDENT_ERASURE_DUE_SQL, DEPENDENT_ERASURE_HOLD_SQL, DEPENDENT_ERASURE_OWE_SQL, DEPENDENT_ERASURE_SETTLE_SQL, nextDependentErasureAt, clearSwitchOwed, markSwitchOwed, scopeOwesSwitch, switchesOwedOf, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, recordSwitchedOff, recordSwitchedOn, recordWriteSuperseded, restoreSwitchRecord, scopesSwitchedOffFor, switchRecordStatesOf, switchRecordsOf, switchesBackfillSqlOf, switchesDdlOf, switchesTableExists, switchesTableOf, tenantHeldOf, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, DEPLOYMENT_WIRE_AUTH_DDL, deploymentWireAuthOf, forgetVerticalWireAuth, writeDeploymentWireAuth, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, driverDeclarationsOf, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, forgetVerticalScopeStores, indexVersionScopeStores, verticalScopeStoresOf, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, versionsAwaitSplit, versionsAwaitDigest, deriveMigrationDigestsBatch, deriveVersionMigrationDigest, writeVersionMigrations, MODEL_USAGE_RETENTION_DAYS, BUILD_USAGE_RETENTION_DAYS, DO_SQL_LIMITS, ulid, isPrimaryScopeRow, samePeerVertical, peerVerticalSpellings, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, LEGACY_SCOPE_ROWS_BACKFILL, loadDirectoryDump, storesFencedRefusal, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, unknownOutcomeOf, ADMIN_LOG_INDEX_DDL, ADMIN_LOG_INDEXES_SQL, readAuditedOperations, } from '@substrat-run/kernel';
4
4
  import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, } from '@substrat-run/kernel';
5
5
  import { replyOf } from './do-reply.js';
6
6
  import { rowBytes, switchSqlOver } from './scope-do.js';
@@ -18,16 +18,18 @@ import { durableMirrorSender } from './directory-objects.js';
18
18
  import { directoryBackfillFor } from './directory-mirror-backfill.js';
19
19
  import { directoryVerifyFor } from './directory-mirror-verify.js';
20
20
  // K-68 step 3e: a tenant's role definitions read from, and first written to, its own object (off by default).
21
- import { cutoverLive, directoryCutoverFor } from './directory-cutover.js';
21
+ import { cutoverFlagsPage, cutoverLive, cutoverParityPage, directoryCutoverFor, PARITY_PAGE_MAX } from './directory-cutover.js';
22
22
  // K-68 step 3e, the second family: a tenant's tuples and removal fences (directory-tenant-tuples.ts).
23
23
  import { applyMembershipIn, assignTenantRoleIn, dumpTenantTupleRows, listMemberRows, revokeAndFenceIn, revokeTenantTupleIn, TENANT_TUPLES, tenantTupleRows, writeTenantTupleIn, } from './directory-tenant-tuples.js';
24
24
  // K-68 step 3e, the third family: a tenant's organizations (directory-tenant-orgs.ts).
25
25
  import { createOrgIn, listOrgRows, ORGS, readOrgRow } from './directory-tenant-orgs.js';
26
26
  // K-68 step 3e, the fourth family: a tenant's entitlements (directory-tenant-entitlements.ts).
27
27
  import { ENTITLEMENTS, entitlementAuditOf, grantEntitlementIn, holdsEntitlement, listEntitlementRows, revokeEntitlementIn, } from './directory-tenant-entitlements.js';
28
- import { durableCutoverSender } from './directory-objects.js';
28
+ // K-68 step 3e, the fifth family: a tenant's identity links (directory-tenant-identities.ts).
29
+ import { dumpIdentityRows, IDENTITIES, linkIdentityIn, resolveIdentityIn, unlinkIdentityIn } from './directory-tenant-identities.js';
30
+ import { durableCutoverSender, registryStub } from './directory-objects.js';
29
31
  import { defineRoleRow, listRoleRows, readRole } from './directory-tenant-roles.js';
30
- import { assertReplayableDump, AUTO_ADMISSION_NOTE, instant, isRuntimeTable, opsFailureFingerprint, ROUTE_SCOPE_HOSTNAMES_MAX, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_GATE_REASONS, substratError } from '@substrat-run/contracts';
32
+ import { admittedBundleAudit, assertReplayableDump, AUTO_ADMISSION_NOTE, instant, isRuntimeTable, opsFailureFingerprint, ROUTE_SCOPE_HOSTNAMES_MAX, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_GATE_REASONS, substratError } from '@substrat-run/contracts';
31
33
  /**
32
34
  * The router's per-request directory read (`readRoute`), lifted out so its plan can be asked for
33
35
  * (#2005): the scope's hostname set is a correlated subquery on the hot path every request takes,
@@ -363,6 +365,8 @@ const DIRECTORY_DDL = `
363
365
  migration_digest_derived INTEGER,
364
366
  -- #2351: the digest of the migrations read from the version's bundle. NULL = never read.
365
367
  migrations_extracted TEXT,
368
+ -- #3612: the sha256 the control plane took of the module bytes it stored. NULL = pushed before.
369
+ bundle_digest TEXT,
366
370
  created_at TEXT NOT NULL,
367
371
  UNIQUE (vertical_slug, version)
368
372
  );
@@ -1258,6 +1262,32 @@ export class ControlPlaneDO extends DurableObject {
1258
1262
  await this.directoryCutover.retry();
1259
1263
  return this.directoryCutover.status();
1260
1264
  }
1265
+ /**
1266
+ * Whether the registry's record of each tenant's flag agrees with this directory's, which is the one
1267
+ * acted on in 3e (`directory-cutover.ts`, `cutoverParityOf`): a page of tenants in id order after
1268
+ * `after`, the drift among them, and where the next page starts. Staff only, and only when asked: it
1269
+ * runs on no alarm, writes nothing on either side, and changes no dispatch, so a disagreement is
1270
+ * reported here and nowhere acted on. Works whatever `DIRECTORY_CUTOVER` says, since a flag flipped
1271
+ * off stays on record; refused only where the registry is not bound.
1272
+ */
1273
+ async directoryCutoverParity(query = {}) {
1274
+ const registry = Reflect.get(this.env, 'DIRECTORY_REGISTRY');
1275
+ if (!registry || typeof Reflect.get(registry, 'idFromName') !== 'function')
1276
+ return { enabled: false, reason: 'DIRECTORY_REGISTRY is not bound' };
1277
+ const limit = Math.max(1, Math.min(Math.trunc(query.limit ?? 100) || 100, PARITY_PAGE_MAX));
1278
+ const after = query.after ?? '';
1279
+ const flags = cutoverFlagsPage(this.sql, after, limit);
1280
+ // The same range on both sides: up to this page's last flag, or to the end when the page is the last.
1281
+ const upTo = flags.length === limit ? flags.at(-1).tenantId : null;
1282
+ const { records, truncated } = await registryStub(registry).tenantCutoversIn({ after, upTo, limit });
1283
+ if (truncated) {
1284
+ // The registry holds more in the range than one read carries: the page ends at its last record, so
1285
+ // no flag past it is judged against a record not read.
1286
+ const boundary = records.at(-1).tenantId;
1287
+ return cutoverParityPage(flags.filter((f) => f.tenantId <= boundary), records, boundary, true);
1288
+ }
1289
+ return cutoverParityPage(flags, records, upTo, false);
1290
+ }
1261
1291
  // -- the routing read model (#3395) -------------------------------------------
1262
1292
  /** Set where a `ROUTES` KV namespace is bound; null otherwise, and the read model is off. */
1263
1293
  routePublisher = null;
@@ -1863,6 +1893,8 @@ export class ControlPlaneDO extends DurableObject {
1863
1893
  this.addColumn('vertical_versions', 'migration_digest_derived INTEGER');
1864
1894
  // #2351: the digest of the migrations read from the bundle; NULL = never read.
1865
1895
  this.addColumn('vertical_versions', 'migrations_extracted TEXT');
1896
+ // #3612: the sha256 the control plane took of the module bytes; NULL = pushed before.
1897
+ this.addColumn('vertical_versions', 'bundle_digest TEXT');
1866
1898
  // #33: the SKU flag learns to express a plan. All nullable — a legacy row
1867
1899
  // reads as a perpetual boolean flag, exactly its pre-widening semantics.
1868
1900
  this.addColumn('_substrat_entitlements', 'expires_at TEXT');
@@ -3292,6 +3324,10 @@ export class ControlPlaneDO extends DurableObject {
3292
3324
  entitlementsCutOver(tenantId) {
3293
3325
  return this.directoryCutover?.cutOverFor(tenantId, ENTITLEMENTS) ?? false;
3294
3326
  }
3327
+ /** Whether the tenant's identity links are read from, and first written to, its own object (the fifth family). */
3328
+ identitiesCutOver(tenantId) {
3329
+ return this.directoryCutover?.cutOverFor(tenantId, IDENTITIES) ?? false;
3330
+ }
3295
3331
  /** This directory as a `TupleStore`: its rows, its admin log, its orgs. */
3296
3332
  tupleStore() {
3297
3333
  return {
@@ -3462,8 +3498,12 @@ export class ControlPlaneDO extends DurableObject {
3462
3498
  }
3463
3499
  /** Binding is read at call execution, so a queued invoke follows the current explicit choice. */
3464
3500
  resolvePeerInstance(tenantId, callerScopeId, vertical) {
3465
- const binding = this.peerBinding(tenantId, callerScopeId, vertical);
3466
3501
  const tenant = this.peerTenant(tenantId);
3502
+ // D-83 (#3530 step 5): a caller that is not an install is answered per environment.
3503
+ const perEnvironment = environmentPeerResolutionIn(this.kernelSql, tenant, callerScopeId, vertical);
3504
+ if (perEnvironment)
3505
+ return perEnvironment;
3506
+ const binding = this.peerBinding(tenantId, callerScopeId, vertical);
3467
3507
  return resolvePeerInstanceFrom(this.peerCandidates(tenant, vertical), tenant, vertical, binding?.target_scope_id ?? null, binding?.invalidated === 1);
3468
3508
  }
3469
3509
  peerBinding(tenantId, callerScopeId, vertical) {
@@ -3598,9 +3638,14 @@ export class ControlPlaneDO extends DurableObject {
3598
3638
  * `publish` (#3395, K-72) is the router's read-model miss: a dispatchable answer is queued for
3599
3639
  * publishing unless it is published already. A directory that predates it ignores the argument.
3600
3640
  * The answer is the same either way.
3641
+ *
3642
+ * `environments` (D-83, #3530 step 5) is a router that dispatches a named environment's pair as a
3643
+ * scope that is no install: only it is answered with the pair (`readPeerCallTarget`).
3601
3644
  */
3602
3645
  peerCallTarget(tenantId, callerScopeId, callerVertical, vertical, opts) {
3603
- const read = readPeerCallTarget(this.sql, tenantId, callerScopeId, callerVertical, vertical);
3646
+ const read = readPeerCallTarget(this.sql, tenantId, callerScopeId, callerVertical, vertical, {
3647
+ environments: opts?.environments === true,
3648
+ });
3604
3649
  if (opts?.publish === true && this.routePublisher) {
3605
3650
  // Optional, as `readRoute`'s: a fill that cannot be queued must not fail a read that succeeded.
3606
3651
  // This method's own return starts the flush (`kickRouteReadModelAfterEveryCall`).
@@ -3981,8 +4026,8 @@ export class ControlPlaneDO extends DurableObject {
3981
4026
  this.sql.exec(`INSERT INTO vertical_versions
3982
4027
  (id, vertical_slug, version, manifest_digest, permission_digest,
3983
4028
  migration_digest, deployment_ref, admission, admission_note, manifest_json,
3984
- origin_json, migration_count, migrations_split, migration_digest_derived, created_at)
3985
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, ?)`, v.id, v.verticalSlug, v.version, v.manifestDigest, v.permissionDigest, v.migrationDigest, v.deploymentRef, admission, selfAdmits ? AUTO_ADMISSION_NOTE : null, v.manifestJson, v.originJson, v.migrations?.length ?? null, v.createdAt);
4029
+ origin_json, migration_count, migrations_split, migration_digest_derived, bundle_digest, created_at)
4030
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, ?, ?)`, v.id, v.verticalSlug, v.version, v.manifestDigest, v.permissionDigest, v.migrationDigest, v.deploymentRef, admission, selfAdmits ? AUTO_ADMISSION_NOTE : null, v.manifestJson, v.originJson, v.migrations?.length ?? null, v.bundleDigest ?? null, v.createdAt);
3986
4031
  writeVersionMigrations(this.kernelSql, v.id, v.migrations);
3987
4032
  // #2286: the version's scope-store bindings, refusing one moved to another driver, in the insert's transaction.
3988
4033
  indexVersionScopeStores(this.kernelSql, v.verticalSlug, v.id, v.manifestJson);
@@ -4118,7 +4163,7 @@ export class ControlPlaneDO extends DurableObject {
4118
4163
  // failing the whole page on `->`.
4119
4164
  const read = () => this.sql
4120
4165
  .exec(`SELECT id, vertical_slug, version, manifest_digest, permission_digest, migration_digest,
4121
- migration_digest_derived, deployment_ref, admission, admission_note, origin_json, created_at,
4166
+ migration_digest_derived, deployment_ref, admission, admission_note, origin_json, bundle_digest, created_at,
4122
4167
  CASE WHEN json_valid(manifest_json) THEN manifest_json -> '$.outbound' END AS outbound_json,
4123
4168
  CASE WHEN json_valid(manifest_json) THEN manifest_json -> '$.calls' END AS calls_json
4124
4169
  FROM vertical_versions WHERE ${where.join(' AND ')}${tail}`, ...params)
@@ -4148,13 +4193,13 @@ export class ControlPlaneDO extends DurableObject {
4148
4193
  if (v.admission === 'admitted') {
4149
4194
  if (v.admission_note !== AUTO_ADMISSION_NOTE)
4150
4195
  return false;
4151
- row = { before: { admission: v.admission, note: v.admission_note }, after: { admission: 'admitted', note: null } };
4196
+ row = { before: { admission: v.admission, note: v.admission_note }, after: { admission: 'admitted', note: null, ...admittedBundleAudit(id, v.bundle_digest) } };
4152
4197
  }
4153
4198
  else if (v.admission === 'rejected') {
4154
4199
  throw substratError('conflict', `version ${id} was rejected — publish a new one`);
4155
4200
  }
4156
4201
  else {
4157
- row = { before: { admission: v.admission }, after: { admission: 'admitted' } };
4202
+ row = { before: { admission: v.admission }, after: { admission: 'admitted', ...admittedBundleAudit(id, v.bundle_digest) } };
4158
4203
  }
4159
4204
  return this.sql.exec("UPDATE vertical_versions SET admission = 'admitted', admission_note = NULL WHERE id = ?", id)
4160
4205
  .rowsWritten > 0;
@@ -4175,7 +4220,7 @@ export class ControlPlaneDO extends DurableObject {
4175
4220
  }, audit && (() => ({ ...audit, before, after: { admission: 'rejected', note } })));
4176
4221
  }
4177
4222
  versionAdmission(id) {
4178
- const v = this.sql.exec('SELECT admission, admission_note FROM vertical_versions WHERE id = ?', id)
4223
+ const v = this.sql.exec('SELECT admission, admission_note, bundle_digest FROM vertical_versions WHERE id = ?', id)
4179
4224
  .toArray()[0];
4180
4225
  if (!v)
4181
4226
  throw substratError('not_found', `unknown version ${id}`);
@@ -5518,44 +5563,51 @@ export class ControlPlaneDO extends DurableObject {
5518
5563
  .filter((r) => !prefix || r.state_key.startsWith(prefix))
5519
5564
  .map((r) => ({ key: r.state_key, value: r.value }));
5520
5565
  }
5566
+ // -- identity links (K-22/K-23) ----------------------------------------------
5567
+ // K-68 step 3e (the fifth family): a tenant whose flip froze its identity links in reads them from,
5568
+ // and links and unlinks them first in, its own object (`directory-tenant-identities.ts`, the same
5569
+ // code in either store). The cross-tenant login reads above stay here: no tenant's object holds them.
5570
+ /**
5571
+ * Bind `provider:externalId` to `principal` in the tenant. False when the same binding is already
5572
+ * held (no admin row); a conflict when another principal holds it. With `audit`, a new link commits
5573
+ * with its admin row.
5574
+ */
5521
5575
  linkIdentity(provider, externalId, principal, tenantId, scopeId, createdAt, audit) {
5522
- return this.writeAndAudit(() => {
5523
- const existing = this.sql
5524
- .exec(`SELECT principal_id FROM _substrat_identities
5525
- WHERE tenant_id = ? AND provider = ? AND external_id = ?`, tenantId, provider, externalId)
5526
- .toArray()[0];
5527
- if (existing) {
5528
- if (existing.principal_id === principal)
5529
- return false;
5530
- throw substratError('conflict', `identity ${provider}:${externalId} in tenant ${tenantId} is already bound to ${existing.principal_id}`);
5531
- }
5532
- this.sql.exec(`INSERT INTO _substrat_identities
5533
- (provider, external_id, principal_id, tenant_id, scope_id, created_at)
5534
- VALUES (?, ?, ?, ?, ?, ?)`, provider, externalId, principal, tenantId, scopeId, createdAt);
5535
- return true;
5536
- }, audit);
5576
+ if (this.identitiesCutOver(tenantId)) {
5577
+ return this.directoryCutover.tupleWrite(tenantId, {
5578
+ kind: 'linkIdentity', provider, externalId, principal, scopeId, createdAt, audit: (audit ?? null),
5579
+ }).then((r) => {
5580
+ if (r && 'conflict' in r)
5581
+ throw substratError('conflict', r.conflict);
5582
+ // An object from before this family answers nothing, having written nothing.
5583
+ if (!r || !('linked' in r))
5584
+ throw new Error(`tenant object did not link ${provider}:${externalId}: it predates the identity cut-over`);
5585
+ return r.linked;
5586
+ });
5587
+ }
5588
+ return this.writeAndAudit(() => linkIdentityIn({ sql: this.sql }, provider, externalId, principal, tenantId, scopeId, createdAt), audit);
5537
5589
  }
5538
5590
  /** Remove a principal's identity link(s) in a tenant. Returns whether a row was
5539
5591
  * deleted so a no-op stays silent (idempotent). */
5540
5592
  unlinkIdentity(tenantId, principal, audit) {
5541
- return this.writeAndAudit(() => {
5542
- const before = this.sql
5543
- .exec(`SELECT 1 FROM _substrat_identities WHERE tenant_id = ? AND principal_id = ?`, tenantId, principal)
5544
- .toArray();
5545
- if (before.length === 0)
5546
- return false;
5547
- this.sql.exec(`DELETE FROM _substrat_identities WHERE tenant_id = ? AND principal_id = ?`, tenantId, principal);
5548
- return true;
5549
- }, audit);
5593
+ if (this.identitiesCutOver(tenantId)) {
5594
+ return this.directoryCutover.tupleWrite(tenantId, {
5595
+ kind: 'unlinkIdentity', principal, audit: (audit ?? null),
5596
+ }).then((r) => {
5597
+ if (!r || !('unlinked' in r))
5598
+ throw new Error(`tenant object did not unlink ${principal}: it predates the identity cut-over`);
5599
+ return r.unlinked;
5600
+ });
5601
+ }
5602
+ return this.writeAndAudit(() => unlinkIdentityIn({ sql: this.sql }, tenantId, principal), audit);
5550
5603
  }
5551
5604
  resolveIdentity(tenantId, provider, externalId) {
5552
- const row = this.sql
5553
- .exec(`SELECT principal_id, scope_id FROM _substrat_identities
5554
- WHERE tenant_id = ? AND provider = ? AND external_id = ?`, tenantId, provider, externalId)
5555
- .toArray()[0];
5556
- if (!row)
5557
- return undefined;
5558
- return { principal: row.principal_id, scopeId: row.scope_id };
5605
+ if (this.identitiesCutOver(tenantId)) {
5606
+ return this.directoryCutover
5607
+ .tupleRead(tenantId, { kind: 'identity', provider, externalId })
5608
+ .then((r) => r ?? undefined);
5609
+ }
5610
+ return resolveIdentityIn(this.sql, tenantId, provider, externalId);
5559
5611
  }
5560
5612
  /**
5561
5613
  * ALL of a tenant's identity links — the read behind identity-link projection
@@ -5563,13 +5615,13 @@ export class ControlPlaneDO extends DurableObject {
5563
5615
  * `unlinkIdentity` hard-deletes (the admin log is the audit), so the projection
5564
5616
  * is a full replace and a removed link is simply absent from the next snapshot.
5565
5617
  * Not on the request hot path — this runs on the admin write path, projecting
5566
- * into a tenant's scopes, and at provision/reconcile gathering.
5618
+ * into a tenant's scopes, and at provision/reconcile gathering. A cut-over
5619
+ * tenant's are its object's (3e).
5567
5620
  */
5568
5621
  dumpTenantIdentities(tenantId) {
5569
- return this.sql
5570
- .exec(`SELECT provider, external_id, principal_id, scope_id FROM _substrat_identities
5571
- WHERE tenant_id = ?`, tenantId)
5572
- .toArray();
5622
+ if (this.identitiesCutOver(tenantId))
5623
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'identities' });
5624
+ return dumpIdentityRows(this.sql, tenantId);
5573
5625
  }
5574
5626
  // -- admin audit log (control-plane.md §4.4) --------------------------------
5575
5627
  /** Append one audit row. before/after are arbitrary JSON, stringified here. */