@substrat-run/adapter-cloudflare 0.221.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/broker-telemetry.d.ts +2 -5
- package/dist/broker-telemetry.d.ts.map +1 -1
- package/dist/broker-telemetry.js +2 -5
- package/dist/broker-telemetry.js.map +1 -1
- package/dist/control-plane-do.d.ts +251 -67
- package/dist/control-plane-do.d.ts.map +1 -1
- package/dist/control-plane-do.js +666 -247
- package/dist/control-plane-do.js.map +1 -1
- package/dist/delivery-broker-do.d.ts +3 -2
- package/dist/delivery-broker-do.d.ts.map +1 -1
- package/dist/delivery-broker-do.js +10 -4
- package/dist/delivery-broker-do.js.map +1 -1
- package/dist/delivery-handoff.d.ts +17 -1
- package/dist/delivery-handoff.d.ts.map +1 -1
- package/dist/delivery-handoff.js +19 -5
- package/dist/delivery-handoff.js.map +1 -1
- package/dist/directory-cutover.d.ts +243 -0
- package/dist/directory-cutover.d.ts.map +1 -0
- package/dist/directory-cutover.js +604 -0
- package/dist/directory-cutover.js.map +1 -0
- package/dist/directory-mirror-apply.d.ts +19 -1
- package/dist/directory-mirror-apply.d.ts.map +1 -1
- package/dist/directory-mirror-apply.js +19 -3
- package/dist/directory-mirror-apply.js.map +1 -1
- package/dist/directory-mirror-backfill.d.ts +2 -0
- package/dist/directory-mirror-backfill.d.ts.map +1 -1
- package/dist/directory-mirror-backfill.js +6 -4
- package/dist/directory-mirror-backfill.js.map +1 -1
- package/dist/directory-mirror.d.ts +24 -0
- package/dist/directory-mirror.d.ts.map +1 -1
- package/dist/directory-mirror.js +16 -2
- package/dist/directory-mirror.js.map +1 -1
- package/dist/directory-objects.d.ts +40 -0
- package/dist/directory-objects.d.ts.map +1 -1
- package/dist/directory-objects.js +134 -2
- package/dist/directory-objects.js.map +1 -1
- package/dist/directory-placement.d.ts.map +1 -1
- package/dist/directory-placement.js +7 -1
- package/dist/directory-placement.js.map +1 -1
- package/dist/directory-split-inventory.d.ts +5 -3
- package/dist/directory-split-inventory.d.ts.map +1 -1
- package/dist/directory-split-inventory.js +12 -6
- package/dist/directory-split-inventory.js.map +1 -1
- package/dist/directory-tenant-orgs.d.ts +19 -0
- package/dist/directory-tenant-orgs.d.ts.map +1 -0
- package/dist/directory-tenant-orgs.js +33 -0
- package/dist/directory-tenant-orgs.js.map +1 -0
- package/dist/directory-tenant-roles.d.ts +35 -0
- package/dist/directory-tenant-roles.d.ts.map +1 -0
- package/dist/directory-tenant-roles.js +78 -0
- package/dist/directory-tenant-roles.js.map +1 -0
- package/dist/directory-tenant-tuples.d.ts +165 -0
- package/dist/directory-tenant-tuples.d.ts.map +1 -0
- package/dist/directory-tenant-tuples.js +197 -0
- package/dist/directory-tenant-tuples.js.map +1 -0
- package/dist/executor-route.d.ts +13 -0
- package/dist/executor-route.d.ts.map +1 -0
- package/dist/executor-route.js +12 -0
- package/dist/executor-route.js.map +1 -0
- package/dist/host.d.ts +76 -2
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +386 -67
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/platform-sweeper-do.d.ts +1 -1
- package/dist/platform-sweeper-do.js +1 -1
- package/dist/scope-do.d.ts +11 -2
- package/dist/scope-do.d.ts.map +1 -1
- package/dist/scope-do.js +206 -58
- package/dist/scope-do.js.map +1 -1
- package/dist/scope-sweeper-do.d.ts +22 -0
- package/dist/scope-sweeper-do.d.ts.map +1 -1
- package/dist/scope-sweeper-do.js +74 -54
- package/dist/scope-sweeper-do.js.map +1 -1
- package/dist/scope-wake.d.ts +12 -1
- package/dist/scope-wake.d.ts.map +1 -1
- package/dist/scope-wake.js +14 -1
- package/dist/scope-wake.js.map +1 -1
- package/dist/tenant-due-work-do.d.ts +99 -0
- package/dist/tenant-due-work-do.d.ts.map +1 -0
- package/dist/tenant-due-work-do.js +149 -0
- package/dist/tenant-due-work-do.js.map +1 -0
- package/package.json +10 -10
package/dist/control-plane-do.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
+
import { tenantDueWorkName } from './tenant-due-work-do.js';
|
|
1
2
|
import { DurableObject } from 'cloudflare:workers';
|
|
2
|
-
import { membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, MEMBERSHIP_FENCES_TABLE, membershipFencesTableExists,
|
|
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, 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
4
|
import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, } from '@substrat-run/kernel';
|
|
4
5
|
import { replyOf } from './do-reply.js';
|
|
5
6
|
import { rowBytes, switchSqlOver } from './scope-do.js';
|
|
6
7
|
import { DIRECTORY_COPY_BY_REFERENCE, quoteIdent, referenceCompareSql, referenceExtraSql, } from './directory-copy-reference.js';
|
|
7
8
|
import { blankSqlComments, boundShapesColumn, executableSqlStatements, installsReconciledOf, PROVISIONED_VERSIONS_SQL, provisionedVersionsParams, } from '@substrat-run/kernel';
|
|
8
|
-
import { COPY_BACKFILL_SCOPE_SQL, COPY_BACKFILL_SQL, COPY_BACKFILL_SUPERSEDE_SQL, COPY_CLAIM_SQL, COPY_EXPIRED_SQL, COPY_MOVE_RENEW_SQL, copyMoveRenewParams, PENDING_COPY_KEEP_ALIVE_SQL, pendingCopyKeepAliveParams, copyBackfillParams, copyBackfillRefusal, SUBJECT_ERASURE_CLAIM_SQL, subjectErasureClaimParams, COPY_MOVE_CONFIRM_SQL, COPY_MOVE_LIVE_PREDICATE, SCOPE_COPY_LEASE_MS, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, servesAsFrom, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, } from '@substrat-run/kernel';
|
|
9
|
-
import { autoAdmittedProdRefusal, breakingWithinMajorRefusal, listedPromoteRefusal, ON_EARLIER_MAJOR_SQL, opsFailureReferenceWhere, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
|
|
10
|
-
import { canonicalInstant } from '@substrat-run/kernel';
|
|
9
|
+
import { COPY_BACKFILL_SCOPE_SQL, COPY_BACKFILL_SQL, COPY_BACKFILL_SUPERSEDE_SQL, COPY_CLAIM_SQL, COPY_EXPIRED_SQL, COPY_EXPIRED_FOR_TENANT_SQL, COPY_MOVE_RENEW_SQL, copyMoveRenewParams, PENDING_COPY_KEEP_ALIVE_SQL, pendingCopyKeepAliveParams, copyBackfillParams, copyBackfillRefusal, SUBJECT_ERASURE_CLAIM_SQL, subjectErasureClaimParams, COPY_MOVE_CONFIRM_SQL, COPY_MOVE_LIVE_PREDICATE, SCOPE_COPY_LEASE_MS, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, servesAsFrom, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, } from '@substrat-run/kernel';
|
|
10
|
+
import { autoAdmittedProdRefusal, breakingWithinMajorRefusal, earlierMajorsOf, listedPromoteRefusal, ON_EARLIER_MAJOR_SQL, opsFailureReferenceWhere, releasedEarlierMajorJson, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
|
|
11
|
+
import { canonicalInstant, provisionedParent } from '@substrat-run/kernel';
|
|
11
12
|
import { doBuiltColumnsOf, doRedactionSql } from './sql.js';
|
|
12
13
|
import { ROUTE_READ_MODEL_TABLE_GLOB, RouteReadModelPublisher, routeKvWriterOf, uninstallRouteReadModel, } from './route-read-model-publisher.js';
|
|
13
14
|
import { readPeerCallTarget } from './peer-call-target.js';
|
|
@@ -16,6 +17,14 @@ import { DIRECTORY_MIRROR_TABLE_GLOB, directoryMirrorFor, isDirectoryMirrorTable
|
|
|
16
17
|
import { durableMirrorSender } from './directory-objects.js';
|
|
17
18
|
import { directoryBackfillFor } from './directory-mirror-backfill.js';
|
|
18
19
|
import { directoryVerifyFor } from './directory-mirror-verify.js';
|
|
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';
|
|
22
|
+
// K-68 step 3e, the second family: a tenant's tuples and removal fences (directory-tenant-tuples.ts).
|
|
23
|
+
import { applyMembershipIn, assignTenantRoleIn, dumpTenantTupleRows, listMemberRows, revokeAndFenceIn, revokeTenantTupleIn, TENANT_TUPLES, tenantTupleRows, writeTenantTupleIn, } from './directory-tenant-tuples.js';
|
|
24
|
+
// K-68 step 3e, the third family: a tenant's organizations (directory-tenant-orgs.ts).
|
|
25
|
+
import { createOrgIn, listOrgRows, ORGS, readOrgRow } from './directory-tenant-orgs.js';
|
|
26
|
+
import { durableCutoverSender } from './directory-objects.js';
|
|
27
|
+
import { defineRoleRow, listRoleRows, readRole } from './directory-tenant-roles.js';
|
|
19
28
|
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';
|
|
20
29
|
/**
|
|
21
30
|
* The router's per-request directory read (`readRoute`), lifted out so its plan can be asked for
|
|
@@ -551,6 +560,8 @@ const DIRECTORY_DDL = `
|
|
|
551
560
|
${MEMBERSHIP_FENCES_DDL}
|
|
552
561
|
${PEER_SWITCHES_DDL}
|
|
553
562
|
${SWITCH_OWED_DDL}
|
|
563
|
+
-- K-63 (#3624): erasures owed to a master's dependents, kept until each door answers.
|
|
564
|
+
${DEPENDENT_ERASURES_DDL}
|
|
554
565
|
CREATE TABLE IF NOT EXISTS _substrat_admin_log (
|
|
555
566
|
id TEXT PRIMARY KEY,
|
|
556
567
|
actor TEXT NOT NULL,
|
|
@@ -922,6 +933,10 @@ export const REPLIED_METHODS = [
|
|
|
922
933
|
// #2565: refuses a listed vertical's prod with forbidden (`unlistedOnly`) or conflict (an
|
|
923
934
|
// auto-admitted version). A DO from before lists it not, so the current coordinator fails closed.
|
|
924
935
|
'promoteChannel',
|
|
936
|
+
// K-65 (#3539): a release into an earlier major, judged and then recorded, each in its unit. New
|
|
937
|
+
// names, so a DO from before refuses them rather than moving prod or the newest major's record.
|
|
938
|
+
'recordEarlierMajorPromote',
|
|
939
|
+
'setEarlierMajorServing',
|
|
925
940
|
// #2526: the role, grant and org writes at a tenant node, each with its admin row in its unit. A
|
|
926
941
|
// DO from before lists none of them, so the current coordinator fails closed against it. That is
|
|
927
942
|
// why the org write is `insertOrg` and not `createOrg` with a trailing row: an older DO lists
|
|
@@ -979,6 +994,8 @@ export const REPLIED_METHODS = [
|
|
|
979
994
|
// #3530 step 4: an environment's own serving script recorded, with its admin row.
|
|
980
995
|
'setEnvironmentServingAndAudit',
|
|
981
996
|
'claimEnvironmentServe',
|
|
997
|
+
// #3530 step 6: an environment given connections of its own, with its admin row.
|
|
998
|
+
'setEnvironmentEffectsAndAudit',
|
|
982
999
|
];
|
|
983
1000
|
/**
|
|
984
1001
|
* #1713: the directory's epoch describes THIS store's history, not its data, so it never leaves in
|
|
@@ -1071,6 +1088,39 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
1071
1088
|
kernelSql;
|
|
1072
1089
|
/** Settles once the constructor's #1764 backfill check has run (awaited by the tests). */
|
|
1073
1090
|
backfillArmed;
|
|
1091
|
+
/** The pass recovers a handoff interrupted after the directory commit. */
|
|
1092
|
+
armTenantDueWork(tenantId, items) {
|
|
1093
|
+
const env = this.env;
|
|
1094
|
+
const ns = env.TENANT_DUE_WORK;
|
|
1095
|
+
if (!ns || items.length === 0)
|
|
1096
|
+
return;
|
|
1097
|
+
if (items[0].kind === 'copies') {
|
|
1098
|
+
if (env.SCOPE_COPY_OWNER !== 'tenant' || !env.DISPATCH || !env.PLATFORM_SECRET)
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
else if (env.REAP_OWNER !== 'tenant')
|
|
1102
|
+
return;
|
|
1103
|
+
const owner = ns.get(ns.idFromName(tenantDueWorkName(tenantId)));
|
|
1104
|
+
this.ctx.waitUntil(owner.ensure(tenantId, items).catch((err) => {
|
|
1105
|
+
console.error('directory could not arm tenant due work', { tenantId, err });
|
|
1106
|
+
}));
|
|
1107
|
+
}
|
|
1108
|
+
autoReapAt(setting, at) {
|
|
1109
|
+
const raw = Reflect.get(this.env, setting);
|
|
1110
|
+
if (!raw?.trim())
|
|
1111
|
+
return undefined;
|
|
1112
|
+
const days = Number(raw);
|
|
1113
|
+
const dueAt = at + days * 86_400_000;
|
|
1114
|
+
return Number.isInteger(days) && days >= 0 && dueAt <= 8.64e15 ? dueAt : undefined;
|
|
1115
|
+
}
|
|
1116
|
+
armSnapshotReap(scopeId, expiresAt) {
|
|
1117
|
+
if (expiresAt === null || Reflect.get(this.env, 'REAP_OWNER') !== 'tenant')
|
|
1118
|
+
return;
|
|
1119
|
+
const row = this.sql.exec("SELECT tenant_id FROM scopes WHERE scope_id = ? AND (forked_from IS NOT NULL OR kind = 'preview')", scopeId).toArray()[0];
|
|
1120
|
+
const dueAt = Date.parse(expiresAt);
|
|
1121
|
+
if (row && Number.isFinite(dueAt))
|
|
1122
|
+
this.armTenantDueWork(row.tenant_id, [{ kind: 'snapshot', unit: scopeId, dueAt }]);
|
|
1123
|
+
}
|
|
1074
1124
|
constructor(ctx, env) {
|
|
1075
1125
|
super(ctx, env);
|
|
1076
1126
|
this.sql = ctx.storage.sql;
|
|
@@ -1089,10 +1139,24 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
1089
1139
|
});
|
|
1090
1140
|
this.directoryBackfill = directoryBackfillFor(env, this.directoryMirror, this.directoryBackfillLimits());
|
|
1091
1141
|
this.directoryVerify = directoryVerifyFor(env, this.directoryMirror, this.directoryVerifyLimits());
|
|
1142
|
+
this.directoryCutover = directoryCutoverFor(env, durableCutoverSender(env), {
|
|
1143
|
+
sql: this.sql,
|
|
1144
|
+
transaction: (fn) => ctx.storage.transactionSync(fn),
|
|
1145
|
+
mirror: this.directoryMirror,
|
|
1146
|
+
verify: this.directoryVerify,
|
|
1147
|
+
recordAdmin: (entry) => this.recordAdmin(entry),
|
|
1148
|
+
applyCarried: (write) => this.applyCarried(write),
|
|
1149
|
+
armRetry: async (at) => {
|
|
1150
|
+
const current = await ctx.storage.getAlarm();
|
|
1151
|
+
if (current === null || current > at)
|
|
1152
|
+
await ctx.storage.setAlarm(at);
|
|
1153
|
+
},
|
|
1154
|
+
...this.directoryCutoverOptions(),
|
|
1155
|
+
});
|
|
1092
1156
|
this.backfillArmed = ctx.blockConcurrencyWhile(async () => {
|
|
1093
1157
|
await this.armVersionMigrationsBackfill();
|
|
1094
1158
|
// K-68 step 3c: the backfill's passes ride the alarm (directory-mirror-backfill.ts).
|
|
1095
|
-
if (this.directoryMirror?.backfillWanted()) {
|
|
1159
|
+
if (this.directoryMirror?.backfillWanted() || this.directoryCutover?.wanted()) {
|
|
1096
1160
|
const current = await ctx.storage.getAlarm();
|
|
1097
1161
|
const at = Date.now() + 1_000;
|
|
1098
1162
|
if (current === null || current > at)
|
|
@@ -1148,6 +1212,43 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
1148
1212
|
return { enabled: false };
|
|
1149
1213
|
return { ...this.directoryVerify.status(), owners: this.directoryVerify.owners(query) };
|
|
1150
1214
|
}
|
|
1215
|
+
// -- K-68 step 3e: reads cut over per tenant, writes first to its object (directory-cutover.ts) --
|
|
1216
|
+
/** Set where `DIRECTORY_CUTOVER` is on, or a tenant is not off yet; null otherwise. */
|
|
1217
|
+
directoryCutover;
|
|
1218
|
+
/** The cut-over's comparison age limit: the production default, other in a test directory. */
|
|
1219
|
+
directoryCutoverOptions() {
|
|
1220
|
+
return {};
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* Flip a tenant's directory reads (and first writes) of the cut-over tables to its own object, or
|
|
1224
|
+
* back. On is gated in code (`DirectoryCutover.refusal`): the dual-write on, the tenant's last
|
|
1225
|
+
* comparison clean, nothing in flight. Off drains every write the object made first into this
|
|
1226
|
+
* directory before reads return here. Staff only (the worker's route).
|
|
1227
|
+
*/
|
|
1228
|
+
async cutOverTenantDirectory(tenantId, to, actor) {
|
|
1229
|
+
if (!this.directoryCutover)
|
|
1230
|
+
return { refused: 'the directory cut-over is off (DIRECTORY_CUTOVER), or the split’s objects are not bound' };
|
|
1231
|
+
try {
|
|
1232
|
+
return { row: await this.directoryCutover.cutOver(tenantId, to, actor) };
|
|
1233
|
+
}
|
|
1234
|
+
catch (err) {
|
|
1235
|
+
// A refusal crosses the hop as data: a throw would reach the worker without its code.
|
|
1236
|
+
if (err?.code === 'conflict')
|
|
1237
|
+
return { refused: err.message };
|
|
1238
|
+
throw err;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
/** Where each tenant's flag stands: a page after `after`, or the one `tenantId` names. */
|
|
1242
|
+
directoryCutoverStatus(query = {}) {
|
|
1243
|
+
return this.directoryCutover ? this.directoryCutover.status(query) : { enabled: false };
|
|
1244
|
+
}
|
|
1245
|
+
/** The alarm's cut-over pass, now (staff, and tests): drains, flips off it can complete, registry records. */
|
|
1246
|
+
async settleDirectoryCutover() {
|
|
1247
|
+
if (!this.directoryCutover)
|
|
1248
|
+
return { enabled: false };
|
|
1249
|
+
await this.directoryCutover.retry();
|
|
1250
|
+
return this.directoryCutover.status();
|
|
1251
|
+
}
|
|
1151
1252
|
// -- the routing read model (#3395) -------------------------------------------
|
|
1152
1253
|
/** Set where a `ROUTES` KV namespace is bound; null otherwise, and the read model is off. */
|
|
1153
1254
|
routePublisher = null;
|
|
@@ -1383,6 +1484,8 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
1383
1484
|
await this.retryRouteReadModel().catch((err) => console.error('route read model: retry failed', err));
|
|
1384
1485
|
// K-68 step 3b: the dual-write's retry after a send an object refused.
|
|
1385
1486
|
this.directoryMirror?.retry();
|
|
1487
|
+
// K-68 step 3e: fallback writes still owed, flips off waiting on them, and the registry's record.
|
|
1488
|
+
await this.directoryCutover?.retry().catch((err) => console.error('directory cutover: the alarm pass failed', err));
|
|
1386
1489
|
let more;
|
|
1387
1490
|
try {
|
|
1388
1491
|
more = this.ctx.storage.transactionSync(() => splitVersionMigrationsBatch(this.kernelSql)).more;
|
|
@@ -1765,6 +1868,8 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
1765
1868
|
this.addColumn('app_environments', 'serving_migration_tag TEXT');
|
|
1766
1869
|
this.addColumn('app_environments', 'serve_claim TEXT');
|
|
1767
1870
|
this.addColumn('app_environments', 'serve_claimed_until TEXT');
|
|
1871
|
+
// #3530 step 6: the environment's choice of outside effects (`APP_ENVIRONMENT_EFFECTS_COLUMNS`); NULL reads as `none`.
|
|
1872
|
+
this.addColumn('app_environments', 'effects TEXT');
|
|
1768
1873
|
for (const stmt of LEGACY_SCOPE_ROWS_BACKFILL)
|
|
1769
1874
|
this.sql.exec(stmt);
|
|
1770
1875
|
// #2501: an ownership period for every vertical registered before the history existed.
|
|
@@ -2082,6 +2187,10 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2082
2187
|
if (opts.requireEmpty && this.sql.exec('SELECT 1 FROM tenants LIMIT 1').toArray().length > 0) {
|
|
2083
2188
|
throw substratError('conflict', RESTORE_OVERWRITE_REFUSAL);
|
|
2084
2189
|
}
|
|
2190
|
+
// K-68 step 3e: a tenant on its own object is not in a dump's past; flip every one off first.
|
|
2191
|
+
if (cutoverLive(this.sql)) {
|
|
2192
|
+
throw substratError('conflict', 'a tenant’s directory reads are cut over to its own object (K-68 step 3e): flip every tenant off before a restore');
|
|
2193
|
+
}
|
|
2085
2194
|
// #1713: the epoch this directory was in, read before the drops take it.
|
|
2086
2195
|
const epochBefore = this.lifecycleEpoch();
|
|
2087
2196
|
this.sql.exec('PRAGMA defer_foreign_keys = ON');
|
|
@@ -2137,6 +2246,8 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2137
2246
|
// for 3c's backfill to fill again, not sent row by row.
|
|
2138
2247
|
this.directoryMirror?.install();
|
|
2139
2248
|
this.directoryMirror?.markRestored();
|
|
2249
|
+
// K-68 step 3e: the cut-over's triggers went with the cut-over tables.
|
|
2250
|
+
this.directoryCutover?.install();
|
|
2140
2251
|
});
|
|
2141
2252
|
// A restore is a new #1764 backfill episode. It replaced the data the old failure count and
|
|
2142
2253
|
// backoff were about, so neither may delay or silence it: the count is cleared and the next
|
|
@@ -2402,13 +2513,19 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2402
2513
|
// Stamp/clear deleting_at so the grace-window sweep can age tenants (§4.8):
|
|
2403
2514
|
// entering `deleting` stamps, leaving it (an un-delete) clears — the same shape
|
|
2404
2515
|
// transitionScope uses for archived_at.
|
|
2516
|
+
const now = Date.now();
|
|
2405
2517
|
this.writeAndAudit(() => {
|
|
2406
2518
|
const moved = (status === 'deleting'
|
|
2407
|
-
? this.sql.exec('UPDATE tenants SET status = ?, deleting_at = ? WHERE tenant_id = ?', status, new Date().toISOString(), tenantId)
|
|
2519
|
+
? this.sql.exec('UPDATE tenants SET status = ?, deleting_at = ? WHERE tenant_id = ?', status, new Date(now).toISOString(), tenantId)
|
|
2408
2520
|
: this.sql.exec('UPDATE tenants SET status = ?, deleting_at = NULL WHERE tenant_id = ?', status, tenantId)).rowsWritten > 0;
|
|
2409
2521
|
this.bumpLifecycleRevision(`tenant:${tenantId}`); // #1713, with the change it counts
|
|
2410
2522
|
return moved;
|
|
2411
2523
|
}, audit && { ...audit, before: { status: before.status } });
|
|
2524
|
+
if (status === 'deleting') {
|
|
2525
|
+
const dueAt = this.autoReapAt('TENANT_RETENTION_DAYS', now);
|
|
2526
|
+
if (dueAt !== undefined)
|
|
2527
|
+
this.armTenantDueWork(tenantId, [{ kind: 'tenant', unit: tenantId, dueAt }]);
|
|
2528
|
+
}
|
|
2412
2529
|
return before.status;
|
|
2413
2530
|
}
|
|
2414
2531
|
/**
|
|
@@ -2419,13 +2536,16 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2419
2536
|
* previous status (for the audit before/after). Idempotent: set-to-empty DELETEs
|
|
2420
2537
|
* plus the status flip converge on a re-run after a partial failure.
|
|
2421
2538
|
*/
|
|
2422
|
-
reapTenant(tenantId, audit) {
|
|
2539
|
+
reapTenant(tenantId, audit, deletingBy) {
|
|
2423
2540
|
const before = this.readTenant(tenantId);
|
|
2424
2541
|
if (!before)
|
|
2425
2542
|
throw substratError('not_found', `unknown tenant: ${tenantId}`);
|
|
2426
2543
|
if (before.status !== 'deleting') {
|
|
2427
2544
|
throw substratError('conflict', `tenant ${tenantId} is ${before.status}, not deleting — only a deleting tenant may be reaped`);
|
|
2428
2545
|
}
|
|
2546
|
+
if (deletingBy !== undefined && (before.deletingAt === null || before.deletingAt > deletingBy)) {
|
|
2547
|
+
throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
|
|
2548
|
+
}
|
|
2429
2549
|
// KEPT as the tombstone: the `tenants` row itself and `_substrat_admin_log` (the
|
|
2430
2550
|
// compliance witness — never swept). Scope rows were already reaped individually.
|
|
2431
2551
|
// One unit with the flip and `audit`, whose `before` is the status read here.
|
|
@@ -2714,8 +2834,10 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2714
2834
|
// Idempotency is on the scope_id (§3.3: idempotent and journaled — safe to
|
|
2715
2835
|
// re-run), so an existing scope short-circuits before the slug check:
|
|
2716
2836
|
// re-provisioning must not collide with itself.
|
|
2717
|
-
const existing = this.sql.exec('SELECT scope_type FROM scopes WHERE scope_id = ?', scopeId).toArray()[0];
|
|
2837
|
+
const existing = this.sql.exec('SELECT scope_type, parent_scope_id FROM scopes WHERE scope_id = ?', scopeId).toArray()[0];
|
|
2718
2838
|
const existed = existing !== undefined;
|
|
2839
|
+
// #2995: the link is fixed at the first provision; a re-provision restates it or names none.
|
|
2840
|
+
const parentScopeId = provisionedParent(record.parentScopeId, existing ? existing.parent_scope_id : undefined, scopeId);
|
|
2719
2841
|
// #2993: a scope's type is fixed when it is provisioned. The host judged it against the row it
|
|
2720
2842
|
// read; judged again here, in the write's own unit, so a provision racing another with a
|
|
2721
2843
|
// different type cannot both succeed. Absent: a host with no declared types, as before.
|
|
@@ -2723,6 +2845,22 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2723
2845
|
throw substratError('conflict', `scope ${scopeId} is a '${existing.scope_type ?? 'home'}' scope, and a scope's type is fixed when it is ` +
|
|
2724
2846
|
`provisioned: it cannot become '${record.scopeType ?? 'home'}'`);
|
|
2725
2847
|
}
|
|
2848
|
+
if (!existed && parentScopeId !== null) {
|
|
2849
|
+
const parent = this.sql
|
|
2850
|
+
.exec('SELECT tenant_id, status, parent_scope_id, forked_from FROM scopes WHERE scope_id = ?', parentScopeId)
|
|
2851
|
+
.toArray()[0];
|
|
2852
|
+
if (!parent || parent.tenant_id !== tenantId) {
|
|
2853
|
+
throw substratError('not_found', `unknown parent scope for tenant: (${tenantId}, ${parentScopeId})`);
|
|
2854
|
+
}
|
|
2855
|
+
if (parent.status !== 'active') {
|
|
2856
|
+
throw substratError('conflict', `scope ${parentScopeId} is ${parent.status}: a child is provisioned under an active scope only`);
|
|
2857
|
+
}
|
|
2858
|
+
if (parent.forked_from !== null)
|
|
2859
|
+
throw substratError('conflict', `scope ${parentScopeId} is a copy, and a copy holds no children`);
|
|
2860
|
+
if (parent.parent_scope_id !== null) {
|
|
2861
|
+
throw substratError('validation_failed', `scope ${parentScopeId} is a child itself, and children are one level deep`);
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2726
2864
|
if (!existed) {
|
|
2727
2865
|
// An `archived` scope (a deleted app) has released its name — and `reaped` is past
|
|
2728
2866
|
// archived, so it too has released it — both excluded so the slug can be reclaimed.
|
|
@@ -2733,6 +2871,20 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2733
2871
|
throw substratError('conflict', `scope slug '${record.slug}' already taken under tenant ${tenantId} ` +
|
|
2734
2872
|
`by ${slugOwner.scope_id} (slugs are unique within a tenant)`);
|
|
2735
2873
|
}
|
|
2874
|
+
// #3625 (K-64): one home scope per (tenant, app, environment): a second install is refused, and
|
|
2875
|
+
// (#2993) a sibling of an app that declares scope types.
|
|
2876
|
+
if (record.claimsHome) {
|
|
2877
|
+
const secondHome = secondHomeRefusal(this.kernelSql, tenantId, scopeId, {
|
|
2878
|
+
vertical: record.vertical,
|
|
2879
|
+
type: record.scopeType ?? HOME_SCOPE_TYPE,
|
|
2880
|
+
parentScopeId,
|
|
2881
|
+
forkedFrom: record.forkedFrom,
|
|
2882
|
+
kind: record.kind,
|
|
2883
|
+
...(record.claimsHome === 'sibling' ? { sibling: true, typed: true } : { install: true }),
|
|
2884
|
+
});
|
|
2885
|
+
if (secondHome)
|
|
2886
|
+
throw secondHome;
|
|
2887
|
+
}
|
|
2736
2888
|
// A scope born while its vertical serves in place (#286) is born ON the serving
|
|
2737
2889
|
// script — provisioning dispatches there — so its routing points there from row
|
|
2738
2890
|
// one. Sub-selected at insert: per-scope truth that later serves can't disturb.
|
|
@@ -2750,10 +2902,11 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2750
2902
|
(scope_id, tenant_id, parent_scope_id, scope_type, slug, kind, name, vertical,
|
|
2751
2903
|
storage_shape, jurisdiction, status, forked_from, forked_at, expires_at,
|
|
2752
2904
|
serving_ref, created_at)
|
|
2753
|
-
VALUES (?, ?,
|
|
2754
|
-
(SELECT serving_ref FROM verticals WHERE slug = ?), ?)`, scopeId, tenantId,
|
|
2905
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
|
|
2906
|
+
(SELECT serving_ref FROM verticals WHERE slug = ?), ?)`, scopeId, tenantId, parentScopeId,
|
|
2755
2907
|
// #2993: NULL for 'home', so a host with no declared types writes exactly the row it always did.
|
|
2756
2908
|
record.scopeType ?? null, record.slug, record.kind, record.name, record.vertical, record.storageShape, record.jurisdiction, record.forkedFrom, record.forkedAt, record.expiresAt, inheritServingSlug, createdAt);
|
|
2909
|
+
this.armSnapshotReap(scopeId, record.expiresAt);
|
|
2757
2910
|
}
|
|
2758
2911
|
return !existed;
|
|
2759
2912
|
}
|
|
@@ -2801,6 +2954,10 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2801
2954
|
where.push('vertical = ?');
|
|
2802
2955
|
params.push(filter.vertical);
|
|
2803
2956
|
}
|
|
2957
|
+
if (filter.parentScopeId) {
|
|
2958
|
+
where.push('parent_scope_id = ?');
|
|
2959
|
+
params.push(filter.parentScopeId);
|
|
2960
|
+
}
|
|
2804
2961
|
const tail = keysetTail(where, params, 'scope_id', filter);
|
|
2805
2962
|
const sql = 'SELECT * FROM scopes' + (where.length ? ` WHERE ${where.join(' AND ')}` : '') + tail;
|
|
2806
2963
|
return this.sql.exec(sql, ...params).toArray();
|
|
@@ -2810,9 +2967,12 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2810
2967
|
* and every status but `reaped`, each once. What a promote judges the incoming version's declared
|
|
2811
2968
|
* types against. A vertical none of whose scopes is typed answers `[]`.
|
|
2812
2969
|
*/
|
|
2813
|
-
scopeTypesHeldBy(vertical) {
|
|
2970
|
+
scopeTypesHeldBy(vertical, servingRef) {
|
|
2971
|
+
// K-65 (#3539): with `servingRef`, the scopes on that script alone: all a release into an earlier
|
|
2972
|
+
// major reaches. A DO from before ignores it and judges every scope, which only refuses more.
|
|
2973
|
+
const onScript = servingRef === undefined ? '' : ' AND serving_ref = ?';
|
|
2814
2974
|
return this.sql
|
|
2815
|
-
.exec(
|
|
2975
|
+
.exec(`SELECT DISTINCT scope_type FROM scopes WHERE vertical = ?${onScript} AND scope_type IS NOT NULL AND status <> 'reaped' ORDER BY scope_type`, ...(servingRef === undefined ? [vertical] : [vertical, servingRef]))
|
|
2816
2976
|
.toArray()
|
|
2817
2977
|
.map((r) => String(r.scope_type));
|
|
2818
2978
|
}
|
|
@@ -2928,8 +3088,59 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2928
3088
|
* for it, since the row can be deleted (`deleteScopeDirectory`) between the two.
|
|
2929
3089
|
*/
|
|
2930
3090
|
transitionScopeOrRefusal(tenantId, scopeId, from, to, action) {
|
|
3091
|
+
const judged = this.judgeTransition(tenantId, scopeId, from, to, action);
|
|
3092
|
+
if (!judged.ok)
|
|
3093
|
+
return judged;
|
|
3094
|
+
// One transaction: the status and — on a reap — the scope's switch records (#1674).
|
|
3095
|
+
// Reaped is terminal, so a cleanup that failed after the flip could never be retried.
|
|
3096
|
+
this.ctx.storage.transactionSync(() => this.applyTransition(tenantId, scopeId, judged.status, to));
|
|
3097
|
+
return judged;
|
|
3098
|
+
}
|
|
3099
|
+
/**
|
|
3100
|
+
* #2995 (K-64): archive a scope AND its children, in one unit, so a child never outlives its parent
|
|
3101
|
+
* by a crash between two writes. The parent is judged as `transitionScopeOrRefusal` judges it; each
|
|
3102
|
+
* child in `from` is archived with it, and a child already archived or reaped is left as it is. A
|
|
3103
|
+
* refused parent archives none. Answers the parent's previous state and each child's, for the
|
|
3104
|
+
* coordinator's audit rows and its lifecycle deliveries.
|
|
3105
|
+
*/
|
|
3106
|
+
archiveScopeFamilyOrRefusal(tenantId, scopeId, from, action) {
|
|
3107
|
+
const judged = this.judgeTransition(tenantId, scopeId, from, 'archived', action);
|
|
3108
|
+
if (!judged.ok)
|
|
3109
|
+
return judged;
|
|
3110
|
+
const children = this.sql
|
|
3111
|
+
.exec(`SELECT scope_id, status, vertical FROM scopes WHERE tenant_id = ? AND parent_scope_id = ? AND status IN (${from.map(() => '?').join(', ')})
|
|
3112
|
+
ORDER BY scope_id`, tenantId, scopeId, ...from)
|
|
3113
|
+
.toArray().map((c) => ({
|
|
3114
|
+
scopeId: c.scope_id,
|
|
3115
|
+
status: c.status,
|
|
3116
|
+
vertical: c.vertical,
|
|
3117
|
+
}));
|
|
3118
|
+
this.ctx.storage.transactionSync(() => {
|
|
3119
|
+
for (const child of children)
|
|
3120
|
+
this.applyTransition(tenantId, child.scopeId, child.status, 'archived');
|
|
3121
|
+
this.applyTransition(tenantId, scopeId, judged.status, 'archived');
|
|
3122
|
+
});
|
|
3123
|
+
const dueAt = this.autoReapAt('SCOPE_RETENTION_DAYS', Date.now());
|
|
3124
|
+
if (dueAt !== undefined) {
|
|
3125
|
+
this.armTenantDueWork(tenantId, [scopeId, ...children.map((child) => child.scopeId)]
|
|
3126
|
+
.map((unit) => ({ kind: 'retention', unit, dueAt })));
|
|
3127
|
+
}
|
|
3128
|
+
return { ...judged, children };
|
|
3129
|
+
}
|
|
3130
|
+
/**
|
|
3131
|
+
* #2995: the ids of `parentScopeId`'s children in `tenantId` whose status is one of `statuses`, oldest
|
|
3132
|
+
* first. What a coordinator reaps before their parent: a child does not outlive it.
|
|
3133
|
+
*/
|
|
3134
|
+
childScopeIds(tenantId, parentScopeId, statuses) {
|
|
3135
|
+
return this.sql
|
|
3136
|
+
.exec(`SELECT scope_id FROM scopes WHERE tenant_id = ? AND parent_scope_id = ? AND status IN (${statuses.map(() => '?').join(', ')})
|
|
3137
|
+
ORDER BY scope_id`, tenantId, parentScopeId, ...statuses)
|
|
3138
|
+
.toArray().map((r) => r.scope_id);
|
|
3139
|
+
}
|
|
3140
|
+
/** A transition's refusal, read in the same synchronous turn as the write that follows it. */
|
|
3141
|
+
judgeTransition(tenantId, scopeId, from, to, action) {
|
|
2931
3142
|
const row = this.sql
|
|
2932
|
-
.exec('SELECT tenant_id, status, vertical, stores_fenced_at FROM scopes WHERE scope_id = ?', scopeId)
|
|
3143
|
+
.exec('SELECT tenant_id, status, vertical, stores_fenced_at, parent_scope_id FROM scopes WHERE scope_id = ?', scopeId)
|
|
2933
3144
|
.toArray()[0];
|
|
2934
3145
|
if (!row || row.tenant_id !== tenantId) {
|
|
2935
3146
|
return { ok: false, code: 'not_found', message: `unknown scope for tenant: (${tenantId}, ${scopeId})` };
|
|
@@ -2937,6 +3148,32 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2937
3148
|
if (to === 'active' && row.stores_fenced_at !== null) {
|
|
2938
3149
|
return { ok: false, code: 'conflict', message: storesFencedRefusal(scopeId) };
|
|
2939
3150
|
}
|
|
3151
|
+
// #2995: a child does not outlive its parent. None comes back (an unarchive, an unsuspend or a late
|
|
3152
|
+
// activation) while its parent is archived or reaped.
|
|
3153
|
+
if (to === 'active' && row.parent_scope_id !== null) {
|
|
3154
|
+
const parent = this.sql.exec('SELECT status FROM scopes WHERE scope_id = ?', row.parent_scope_id).toArray()[0];
|
|
3155
|
+
if (!parent || parent.status === 'archived' || parent.status === 'reaped') {
|
|
3156
|
+
return {
|
|
3157
|
+
ok: false,
|
|
3158
|
+
code: 'conflict',
|
|
3159
|
+
message: `scope ${scopeId} is a child of ${row.parent_scope_id}, which is ${parent?.status ?? 'gone'}: a child does not outlive its parent`,
|
|
3160
|
+
};
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
// #2995: nor is a parent reaped while a child of it is not. A hosted child's bytes live in its
|
|
3164
|
+
// vertical's deployment, so the coordinator reaps each child first (`childScopeIds`); this is the fence.
|
|
3165
|
+
if (to === 'reaped') {
|
|
3166
|
+
const child = this.sql
|
|
3167
|
+
.exec("SELECT scope_id FROM scopes WHERE tenant_id = ? AND parent_scope_id = ? AND status != 'reaped' LIMIT 1", tenantId, scopeId)
|
|
3168
|
+
.toArray()[0];
|
|
3169
|
+
if (child) {
|
|
3170
|
+
return {
|
|
3171
|
+
ok: false,
|
|
3172
|
+
code: 'conflict',
|
|
3173
|
+
message: `scope ${scopeId} holds child ${child.scope_id}, which is not reaped: a child is reaped before its parent`,
|
|
3174
|
+
};
|
|
3175
|
+
}
|
|
3176
|
+
}
|
|
2940
3177
|
if (!from.includes(row.status)) {
|
|
2941
3178
|
return {
|
|
2942
3179
|
ok: false,
|
|
@@ -2945,35 +3182,34 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2945
3182
|
`(allowed from: ${from.join('|')})`,
|
|
2946
3183
|
};
|
|
2947
3184
|
}
|
|
2948
|
-
// One transaction: the status and — on a reap — the scope's switch records (#1674).
|
|
2949
|
-
// Reaped is terminal, so a cleanup that failed after the flip could never be retried.
|
|
2950
|
-
this.ctx.storage.transactionSync(() => {
|
|
2951
|
-
// Stamp/clear archived_at so the reap sweep can age scopes. Entering `archived`
|
|
2952
|
-
// records when; `unarchive` (→ active, a restore per §4.2) clears it so a later
|
|
2953
|
-
// re-archive dates from the new event. `reaped` keeps it — it is terminal history.
|
|
2954
|
-
// #1524: the status it left is recorded beside the stamp and cleared with it.
|
|
2955
|
-
if (to === 'archived') {
|
|
2956
|
-
this.sql.exec('UPDATE scopes SET status = ?, archived_at = ?, archived_from_status = ? WHERE scope_id = ?', to, new Date().toISOString(), row.status, scopeId);
|
|
2957
|
-
}
|
|
2958
|
-
else if (to === 'active') {
|
|
2959
|
-
this.sql.exec('UPDATE scopes SET status = ?, archived_at = NULL, archived_from_status = NULL WHERE scope_id = ?', to, scopeId);
|
|
2960
|
-
}
|
|
2961
|
-
else {
|
|
2962
|
-
this.sql.exec('UPDATE scopes SET status = ? WHERE scope_id = ?', to, scopeId);
|
|
2963
|
-
}
|
|
2964
|
-
if (to === 'archived' || to === 'reaped') {
|
|
2965
|
-
this.sql.exec('UPDATE peer_bindings SET invalidated = 1 WHERE tenant_id = ? AND target_scope_id = ?', tenantId, scopeId);
|
|
2966
|
-
}
|
|
2967
|
-
if (to === 'reaped') {
|
|
2968
|
-
forgetSwitchesOf(this.kernelSql, scopeId);
|
|
2969
|
-
this.forgetLifecycleDeliveries('scope_id = ?', scopeId);
|
|
2970
|
-
// #2515: its storage is gone, and its measured days are kept for the invoice (retention ends them).
|
|
2971
|
-
retireScopeStorage(doRedactionSql(this.sql), scopeId);
|
|
2972
|
-
}
|
|
2973
|
-
this.bumpLifecycleRevision(`scope:${scopeId}`); // #1713, with the status it counts
|
|
2974
|
-
});
|
|
2975
3185
|
return { ok: true, status: row.status, vertical: row.vertical };
|
|
2976
3186
|
}
|
|
3187
|
+
/** The writes of one judged transition. Called inside the caller's transaction. */
|
|
3188
|
+
applyTransition(tenantId, scopeId, previous, to) {
|
|
3189
|
+
// Stamp/clear archived_at so the reap sweep can age scopes. Entering `archived`
|
|
3190
|
+
// records when; `unarchive` (→ active, a restore per §4.2) clears it so a later
|
|
3191
|
+
// re-archive dates from the new event. `reaped` keeps it — it is terminal history.
|
|
3192
|
+
// #1524: the status it left is recorded beside the stamp and cleared with it.
|
|
3193
|
+
if (to === 'archived') {
|
|
3194
|
+
this.sql.exec('UPDATE scopes SET status = ?, archived_at = ?, archived_from_status = ? WHERE scope_id = ?', to, new Date().toISOString(), previous, scopeId);
|
|
3195
|
+
}
|
|
3196
|
+
else if (to === 'active') {
|
|
3197
|
+
this.sql.exec('UPDATE scopes SET status = ?, archived_at = NULL, archived_from_status = NULL WHERE scope_id = ?', to, scopeId);
|
|
3198
|
+
}
|
|
3199
|
+
else {
|
|
3200
|
+
this.sql.exec('UPDATE scopes SET status = ? WHERE scope_id = ?', to, scopeId);
|
|
3201
|
+
}
|
|
3202
|
+
if (to === 'archived' || to === 'reaped') {
|
|
3203
|
+
this.sql.exec('UPDATE peer_bindings SET invalidated = 1 WHERE tenant_id = ? AND target_scope_id = ?', tenantId, scopeId);
|
|
3204
|
+
}
|
|
3205
|
+
if (to === 'reaped') {
|
|
3206
|
+
forgetSwitchesOf(this.kernelSql, scopeId);
|
|
3207
|
+
this.forgetLifecycleDeliveries('scope_id = ?', scopeId);
|
|
3208
|
+
// #2515: its storage is gone, and its measured days are kept for the invoice (retention ends them).
|
|
3209
|
+
retireScopeStorage(doRedactionSql(this.sql), scopeId);
|
|
3210
|
+
}
|
|
3211
|
+
this.bumpLifecycleRevision(`scope:${scopeId}`); // #1713, with the status it counts
|
|
3212
|
+
}
|
|
2977
3213
|
// -- roles (checker rule 1) -------------------------------------------------
|
|
2978
3214
|
/**
|
|
2979
3215
|
* Kept for a coordinator from before #2447, which calls it and reads the previous role (for the
|
|
@@ -2982,10 +3218,13 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
2982
3218
|
* that never happened.
|
|
2983
3219
|
*/
|
|
2984
3220
|
defineRole(tenantId, role) {
|
|
3221
|
+
const settle = (outcome) => {
|
|
3222
|
+
if ('refused' in outcome)
|
|
3223
|
+
throw new Error(outcome.refused);
|
|
3224
|
+
return outcome.before;
|
|
3225
|
+
};
|
|
2985
3226
|
const outcome = this.defineRoleOrRefusal(tenantId, role);
|
|
2986
|
-
|
|
2987
|
-
throw new Error(outcome.refused);
|
|
2988
|
-
return outcome.before;
|
|
3227
|
+
return outcome instanceof Promise ? outcome.then(settle) : settle(outcome);
|
|
2989
3228
|
}
|
|
2990
3229
|
/**
|
|
2991
3230
|
* INSERT OR REPLACE; answer the previous role (for the audit `before`) or null. Judged first, in
|
|
@@ -3000,87 +3239,86 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3000
3239
|
* coordinator from before #2526 passes none and records its own.
|
|
3001
3240
|
*/
|
|
3002
3241
|
defineRoleOrRefusal(tenantId, role, reservation = { reserved: [], declared: [] }, seatedInScopes = false, audit) {
|
|
3242
|
+
// K-68 step 3e: a cut-over tenant's role is judged and written in its own object first, the
|
|
3243
|
+
// directory's copy and the admin row after it (`directory-cutover.ts`). Asked in the method's
|
|
3244
|
+
// first synchronous step, so the flag and the write that follows it are of the same moment.
|
|
3245
|
+
if (this.directoryCutover?.isCutOver(tenantId)) {
|
|
3246
|
+
return this.directoryCutover.defineRole(tenantId, role, reservation, seatedInScopes, audit ?? null);
|
|
3247
|
+
}
|
|
3003
3248
|
return this.ctx.storage.transactionSync(() => {
|
|
3004
|
-
const outcome = this.
|
|
3249
|
+
const outcome = defineRoleRow(this.sql, tenantId, role, reservation, seatedInScopes, new Date().toISOString());
|
|
3005
3250
|
if (audit && 'before' in outcome)
|
|
3006
3251
|
this.recordAdmin({ ...audit, before: outcome.before });
|
|
3007
3252
|
return outcome;
|
|
3008
3253
|
});
|
|
3009
3254
|
}
|
|
3010
|
-
|
|
3011
|
-
const tenantRoles = this.listRoles({ tenantId }).map((r) => ({
|
|
3012
|
-
key: r.role_key,
|
|
3013
|
-
permissions: JSON.parse(r.permissions),
|
|
3014
|
-
holder: r.holder ?? undefined,
|
|
3015
|
-
}));
|
|
3016
|
-
const stored = tenantRoles.find((r) => r.key === role.key);
|
|
3017
|
-
const seated = stored?.holder !== 'system' && role.holder === 'system' &&
|
|
3018
|
-
(seatedInScopes ||
|
|
3019
|
-
this.sql.exec(TENANT_SEATED_ROLES_SQL, tenantId, new Date().toISOString()).toArray().some((r) => r.role_key === role.key));
|
|
3020
|
-
const refused = reservedRoleDefinitionRefusal(role, { reserved: new Set(reservation.reserved), declared: new Set(reservation.declared) }, tenantRoles, seated);
|
|
3021
|
-
if (refused)
|
|
3022
|
-
return { refused };
|
|
3023
|
-
const before = this.getRole(tenantId, role.key) ?? null;
|
|
3024
|
-
this.sql.exec(`INSERT OR REPLACE INTO _substrat_roles (tenant_id, role_key, permissions, source, holder)
|
|
3025
|
-
VALUES (?, ?, ?, ?, ?)`, tenantId, role.key, JSON.stringify(role.permissions), String(role.source), role.holder ?? 'person');
|
|
3026
|
-
return { before };
|
|
3027
|
-
}
|
|
3028
|
-
/** Raw rows; the coordinator parses them through the `tenantRole` contract. */
|
|
3255
|
+
/** Raw rows; the coordinator parses them through the `tenantRole` contract. One cut-over tenant's are its object's (3e). */
|
|
3029
3256
|
listRoles(filter) {
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
where.push('tenant_id = ?');
|
|
3034
|
-
params.push(filter.tenantId);
|
|
3035
|
-
}
|
|
3036
|
-
if (filter.source) {
|
|
3037
|
-
where.push('source = ?');
|
|
3038
|
-
params.push(filter.source);
|
|
3039
|
-
}
|
|
3040
|
-
const order = (filter.order ?? 'asc') === 'desc' ? 'DESC' : 'ASC';
|
|
3041
|
-
if (filter.cursor) {
|
|
3042
|
-
// Composite sort key `${tenantId}|${roleKey}` (pagination.ts) — the
|
|
3043
|
-
// tenant id is a ULID and never contains '|', so split on the FIRST.
|
|
3044
|
-
const split = filter.cursor.indexOf('|');
|
|
3045
|
-
const afterTenant = split === -1 ? filter.cursor : filter.cursor.slice(0, split);
|
|
3046
|
-
const afterKey = split === -1 ? '' : filter.cursor.slice(split + 1);
|
|
3047
|
-
const cmp = order === 'DESC' ? '<' : '>';
|
|
3048
|
-
where.push(`(tenant_id ${cmp} ? OR (tenant_id = ? AND role_key ${cmp} ?))`);
|
|
3049
|
-
params.push(afterTenant, afterTenant, afterKey);
|
|
3050
|
-
}
|
|
3051
|
-
let sql = 'SELECT tenant_id, role_key, permissions, source, holder FROM _substrat_roles' +
|
|
3052
|
-
(where.length ? ` WHERE ${where.join(' AND ')}` : '') +
|
|
3053
|
-
` ORDER BY tenant_id ${order}, role_key ${order}`;
|
|
3054
|
-
if (filter.limit !== undefined) {
|
|
3055
|
-
sql += ' LIMIT ?';
|
|
3056
|
-
params.push(assertRowLimit('limit', filter.limit));
|
|
3057
|
-
}
|
|
3058
|
-
return this.sql.exec(sql, ...params).toArray();
|
|
3257
|
+
if (filter.tenantId && this.directoryCutover?.isCutOver(filter.tenantId))
|
|
3258
|
+
return this.directoryCutover.listRoles(filter.tenantId, filter);
|
|
3259
|
+
return listRoleRows(this.sql, filter);
|
|
3059
3260
|
}
|
|
3261
|
+
/** A role as stored; a cut-over tenant's from its object (3e). The decisions in this object read `readRole` directly. */
|
|
3060
3262
|
getRole(tenantId, key) {
|
|
3061
|
-
|
|
3062
|
-
.
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3263
|
+
if (this.directoryCutover?.isCutOver(tenantId))
|
|
3264
|
+
return this.directoryCutover.getRole(tenantId, key);
|
|
3265
|
+
return readRole(this.sql, tenantId, key);
|
|
3266
|
+
}
|
|
3267
|
+
// -- tenant-level tuples (checker rules 1, 2, 4) ----------------------------
|
|
3268
|
+
// K-68 step 3e (the second family): a tenant whose flip froze its tuples in reads them from, and
|
|
3269
|
+
// writes them first to, its own object (`directory-cutover.ts`). Every unit below runs the same code
|
|
3270
|
+
// in either store (`directory-tenant-tuples.ts`); which one is asked in the method's first
|
|
3271
|
+
// synchronous step, so the flag and the write that follows it are of the same moment.
|
|
3272
|
+
/** Whether the tenant's tuples and removal fences are read from, and first written to, its own object. */
|
|
3273
|
+
tuplesCutOver(tenantId) {
|
|
3274
|
+
return this.directoryCutover?.cutOverFor(tenantId, TENANT_TUPLES) ?? false;
|
|
3275
|
+
}
|
|
3276
|
+
/** Whether the tenant's organizations are read from, and first written to, its own object (the third family). */
|
|
3277
|
+
orgsCutOver(tenantId) {
|
|
3278
|
+
return this.directoryCutover?.cutOverFor(tenantId, ORGS) ?? false;
|
|
3279
|
+
}
|
|
3280
|
+
/** This directory as a `TupleStore`: its rows, its admin log, its orgs. */
|
|
3281
|
+
tupleStore() {
|
|
3066
3282
|
return {
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3283
|
+
sql: this.sql,
|
|
3284
|
+
now: () => new Date().toISOString(),
|
|
3285
|
+
admin: (entry) => this.recordAdmin(entry),
|
|
3286
|
+
orgKnown: (tenantId, orgId) => !!readOrgRow(this.sql, tenantId, orgId),
|
|
3071
3287
|
};
|
|
3072
3288
|
}
|
|
3073
|
-
|
|
3289
|
+
/**
|
|
3290
|
+
* Run `fn` with no other call into this object between its first step and its end. For a cut-over
|
|
3291
|
+
* tenant's unit that reads what this directory still writes (a system switch, a connection) and
|
|
3292
|
+
* writes first in the tenant's object: the read, the object's write and the fallback are then one
|
|
3293
|
+
* step for every other call here, as the synchronous unit is for a tenant not cut over. A failure
|
|
3294
|
+
* is answered after the step, never thrown inside it (a throw there resets the object).
|
|
3295
|
+
*/
|
|
3296
|
+
async exclusive(fn) {
|
|
3297
|
+
const out = await this.ctx.blockConcurrencyWhile(async () => {
|
|
3298
|
+
try {
|
|
3299
|
+
return { value: await fn() };
|
|
3300
|
+
}
|
|
3301
|
+
catch (error) {
|
|
3302
|
+
return { error };
|
|
3303
|
+
}
|
|
3304
|
+
});
|
|
3305
|
+
if ('error' in out)
|
|
3306
|
+
throw out.error;
|
|
3307
|
+
return out.value;
|
|
3308
|
+
}
|
|
3074
3309
|
/**
|
|
3075
3310
|
* A tenant tuple, upserted. With `audit` (#2526, `grant` at the tenant node, called through
|
|
3076
3311
|
* `reply`), its admin row commits in the same transaction; without, as a coordinator from before
|
|
3077
|
-
* #2526 calls it,
|
|
3312
|
+
* #2526 calls it, it is the bare write.
|
|
3078
3313
|
*/
|
|
3079
3314
|
writeTenantTuple(tenantId, subject, relation, object, expiresAt, audit) {
|
|
3315
|
+
if (this.tuplesCutOver(tenantId)) {
|
|
3316
|
+
return this.directoryCutover.tupleWrite(tenantId, {
|
|
3317
|
+
kind: 'write', subject, relation, object, expiresAt, audit: audit ?? null,
|
|
3318
|
+
}).then(() => undefined);
|
|
3319
|
+
}
|
|
3080
3320
|
const write = () => {
|
|
3081
|
-
this.
|
|
3082
|
-
(tenant_id, subject, relation, object, expires_at)
|
|
3083
|
-
VALUES (?, ?, ?, ?, ?)`, tenantId, subject, relation, object, expiresAt);
|
|
3321
|
+
writeTenantTupleIn(this.tupleStore(), tenantId, subject, relation, object, expiresAt);
|
|
3084
3322
|
return true;
|
|
3085
3323
|
};
|
|
3086
3324
|
if (audit)
|
|
@@ -3095,41 +3333,71 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3095
3333
|
* writes nothing. A role not defined here is not judged, as before.
|
|
3096
3334
|
*/
|
|
3097
3335
|
assignTenantRole(tenantId, principal, roleKey, reserved, audit) {
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
this.recordAdmin(audit);
|
|
3105
|
-
return {};
|
|
3106
|
-
});
|
|
3336
|
+
if (this.tuplesCutOver(tenantId)) {
|
|
3337
|
+
return this.directoryCutover.tupleWrite(tenantId, {
|
|
3338
|
+
kind: 'assignRole', principal, roleKey, reserved: [...reserved], audit: audit,
|
|
3339
|
+
});
|
|
3340
|
+
}
|
|
3341
|
+
return this.ctx.storage.transactionSync(() => assignTenantRoleIn(this.tupleStore(), tenantId, principal, roleKey, reserved, audit));
|
|
3107
3342
|
}
|
|
3108
3343
|
/**
|
|
3109
3344
|
* #2526: a tenant tuple that names an org — `grantToOrg` at the tenant node, and `addMember` —
|
|
3110
|
-
* with its admin row, in one unit, refused `not_found` when the org is not in the tenant.
|
|
3345
|
+
* with its admin row, in one unit, refused `not_found` when the org is not in the tenant. For a
|
|
3346
|
+
* cut-over tenant the org is asked here first: an org is never removed from a live tenant, so the
|
|
3347
|
+
* answer still holds when the object writes.
|
|
3111
3348
|
*/
|
|
3112
3349
|
writeOrgTenantTuple(tenantId, orgId, subject, relation, object, expiresAt, audit) {
|
|
3350
|
+
const unknown = () => substratError('not_found', `unknown org ${orgId} in tenant ${tenantId}`);
|
|
3351
|
+
if (this.orgsCutOver(tenantId)) {
|
|
3352
|
+
// The org and the tuple are both the object's: it judges the one and writes the other in one unit.
|
|
3353
|
+
return this.directoryCutover.tupleWrite(tenantId, {
|
|
3354
|
+
kind: 'orgTuple', orgId, subject, relation, object, expiresAt, audit: audit,
|
|
3355
|
+
}).then((r) => {
|
|
3356
|
+
if (r.unknownOrg)
|
|
3357
|
+
throw unknown();
|
|
3358
|
+
});
|
|
3359
|
+
}
|
|
3360
|
+
if (this.tuplesCutOver(tenantId)) {
|
|
3361
|
+
if (!readOrgRow(this.sql, tenantId, orgId))
|
|
3362
|
+
throw unknown();
|
|
3363
|
+
return this.directoryCutover.tupleWrite(tenantId, {
|
|
3364
|
+
kind: 'write', subject, relation, object, expiresAt, audit: audit,
|
|
3365
|
+
}).then(() => undefined);
|
|
3366
|
+
}
|
|
3113
3367
|
this.writeAndAudit(() => {
|
|
3114
|
-
if (!this.
|
|
3115
|
-
throw
|
|
3116
|
-
this.
|
|
3368
|
+
if (!readOrgRow(this.sql, tenantId, orgId))
|
|
3369
|
+
throw unknown();
|
|
3370
|
+
writeTenantTupleIn(this.tupleStore(), tenantId, subject, relation, object, expiresAt);
|
|
3117
3371
|
return true;
|
|
3118
3372
|
}, audit);
|
|
3119
3373
|
}
|
|
3120
3374
|
/**
|
|
3121
3375
|
* #1743: a tenant-level `system:<module>` grant, refused while the record holds the module
|
|
3122
3376
|
* off on any scope (`scopesSwitchedOffFor`). Synchronous, so the read and the write are one
|
|
3123
|
-
* DO unit
|
|
3124
|
-
*
|
|
3377
|
+
* DO unit; for a cut-over tenant, one exclusive step (`exclusive`), the switch read here and the
|
|
3378
|
+
* grant written first in the object. Answers the switched-off scopes; non-empty means nothing was
|
|
3379
|
+
* written. With `audit` (#2526, through `reply`), the row commits with the tuple, and a refusal
|
|
3380
|
+
* records none.
|
|
3125
3381
|
*/
|
|
3126
3382
|
writeTenantSystemGrant(tenantId, moduleId, relation, expiresAt, audit) {
|
|
3383
|
+
if (this.tuplesCutOver(tenantId)) {
|
|
3384
|
+
return this.exclusive(async () => {
|
|
3385
|
+
const off = scopesSwitchedOffFor(this.kernelSql, tenantId, moduleId);
|
|
3386
|
+
if (off.length > 0)
|
|
3387
|
+
return off;
|
|
3388
|
+
await this.directoryCutover.tupleWrite(tenantId, {
|
|
3389
|
+
kind: 'write', subject: `system:${moduleId}`, relation, object: `tenant:${tenantId}`, expiresAt,
|
|
3390
|
+
audit: audit ?? null,
|
|
3391
|
+
});
|
|
3392
|
+
return [];
|
|
3393
|
+
});
|
|
3394
|
+
}
|
|
3127
3395
|
let off = [];
|
|
3128
3396
|
this.writeAndAudit(() => {
|
|
3129
3397
|
off = scopesSwitchedOffFor(this.kernelSql, tenantId, moduleId);
|
|
3130
3398
|
if (off.length > 0)
|
|
3131
3399
|
return false;
|
|
3132
|
-
this.
|
|
3400
|
+
writeTenantTupleIn(this.tupleStore(), tenantId, `system:${moduleId}`, relation, `tenant:${tenantId}`, expiresAt);
|
|
3133
3401
|
return true;
|
|
3134
3402
|
}, audit);
|
|
3135
3403
|
return off;
|
|
@@ -3189,6 +3457,10 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3189
3457
|
peerBindings(tenantId, callerScopeId) {
|
|
3190
3458
|
return this.sql.exec('SELECT vertical, target_scope_id, invalidated FROM peer_bindings WHERE tenant_id = ? AND caller_scope_id = ? ORDER BY vertical', tenantId, callerScopeId).toArray();
|
|
3191
3459
|
}
|
|
3460
|
+
/** #3625 (K-64): the home scope of (tenant, app, environment), or null (kernel `homeScopeIn`). */
|
|
3461
|
+
homeScopeOf(tenantId, vertical, environment) {
|
|
3462
|
+
return homeScopeIn(this.kernelSql, tenantId, vertical, environment);
|
|
3463
|
+
}
|
|
3192
3464
|
/** D-83 (#3530 step 3): the app's environments in the tenant, production first (kernel `environmentsOf`). */
|
|
3193
3465
|
listEnvironments(tenantId, vertical) {
|
|
3194
3466
|
return environmentsOf(this.kernelSql, tenantId, vertical);
|
|
@@ -3220,16 +3492,18 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3220
3492
|
* record the upload diffed from (kernel `setEnvironmentServingIn`), with its admin row in the
|
|
3221
3493
|
* same transaction. False, with nothing written and no row, when the record moved since.
|
|
3222
3494
|
*/
|
|
3223
|
-
setEnvironmentServingAndAudit(input, next, expected, audit, claim
|
|
3495
|
+
setEnvironmentServingAndAudit(input, next, expected, audit, claim,
|
|
3496
|
+
/** #3638: what this serve acknowledges in this environment, judged and recorded here. */
|
|
3497
|
+
acknowledge) {
|
|
3224
3498
|
let out;
|
|
3225
3499
|
this.writeAndAudit(() => {
|
|
3226
|
-
out = setEnvironmentServingIn(this.kernelSql, input, next, expected, claim);
|
|
3500
|
+
out = setEnvironmentServingIn(this.kernelSql, input, next, expected, claim, acknowledge);
|
|
3227
3501
|
return out.moved;
|
|
3228
3502
|
}, () => ({
|
|
3229
3503
|
...audit,
|
|
3230
3504
|
scopeId: out.scopeId,
|
|
3231
3505
|
before: out.before ? { ref: out.before.ref, versionId: out.before.versionId } : null,
|
|
3232
|
-
after: { vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId },
|
|
3506
|
+
after: { vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId, ...(acknowledge ? { acknowledged: acknowledge } : {}) },
|
|
3233
3507
|
}));
|
|
3234
3508
|
return out.moved;
|
|
3235
3509
|
}
|
|
@@ -3253,6 +3527,27 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3253
3527
|
return true;
|
|
3254
3528
|
});
|
|
3255
3529
|
}
|
|
3530
|
+
/**
|
|
3531
|
+
* #3530 step 6: give a named environment connections of its own, or take that back (kernel
|
|
3532
|
+
* `setEnvironmentEffectsIn`), with its admin row in the same transaction. No row when nothing changed.
|
|
3533
|
+
*/
|
|
3534
|
+
setEnvironmentEffectsAndAudit(input, effects, audit) {
|
|
3535
|
+
let out;
|
|
3536
|
+
this.writeAndAudit(() => {
|
|
3537
|
+
out = setEnvironmentEffectsIn(this.kernelSql, input, effects);
|
|
3538
|
+
return out.changed;
|
|
3539
|
+
}, () => ({
|
|
3540
|
+
...audit,
|
|
3541
|
+
scopeId: out.scopeId,
|
|
3542
|
+
before: { effects: out.before },
|
|
3543
|
+
after: { vertical: input.vertical, scopeId: out.scopeId, effects },
|
|
3544
|
+
}));
|
|
3545
|
+
return { changed: out.changed, before: out.before };
|
|
3546
|
+
}
|
|
3547
|
+
/** #3530 step 6: which connections the scope's effects may go through (kernel `connectionReachIn`). */
|
|
3548
|
+
connectionReach(tenantId, scopeId) {
|
|
3549
|
+
return connectionReachIn(this.kernelSql, tenantId, scopeId);
|
|
3550
|
+
}
|
|
3256
3551
|
/** Directory write and endpoint checks share this DO's serialized unit. */
|
|
3257
3552
|
setPeerBinding(tenantId, callerScopeId, vertical, targetScopeId) {
|
|
3258
3553
|
const caller = this.sql.exec('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?', callerScopeId).toArray()[0];
|
|
@@ -3730,6 +4025,24 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3730
4025
|
}, audit && (() => ({ ...audit, before })));
|
|
3731
4026
|
return !raced;
|
|
3732
4027
|
}
|
|
4028
|
+
/**
|
|
4029
|
+
* K-65 (#3539): record a release into an earlier major, served on its own script: only that major's
|
|
4030
|
+
* entry of `earlier_majors` moves, compare-and-set on `expected` (`releasedEarlierMajorJson`, which
|
|
4031
|
+
* refuses `precondition_failed`), and `audit`'s `before` is the entry this unit read.
|
|
4032
|
+
*/
|
|
4033
|
+
setEarlierMajorServing(slug, major, s, expected, audit) {
|
|
4034
|
+
let before = null;
|
|
4035
|
+
return this.writeAndAudit(() => {
|
|
4036
|
+
const r = this.readVertical(slug);
|
|
4037
|
+
if (!r)
|
|
4038
|
+
throw substratError('not_found', `unknown vertical '${slug}'`);
|
|
4039
|
+
const held = earlierMajorsOf(r.earlier_majors).find((m) => m.major === major);
|
|
4040
|
+
before = held ? { ref: held.ref, versionId: held.versionId } : null;
|
|
4041
|
+
const earlier = releasedEarlierMajorJson({ vertical: slug, earlierJson: r.earlier_majors, major, expected, next: s });
|
|
4042
|
+
this.sql.exec('UPDATE verticals SET earlier_majors = ? WHERE slug = ?', earlier, slug);
|
|
4043
|
+
return true;
|
|
4044
|
+
}, () => ({ ...audit, before }));
|
|
4045
|
+
}
|
|
3733
4046
|
/** #2351: the digest of the migrations read from a version's bundle, or `undefined` for no such version. */
|
|
3734
4047
|
readMigrationsExtracted(id) {
|
|
3735
4048
|
return versionMigrationsExtractedOf(this.kernelSql, id);
|
|
@@ -3767,11 +4080,17 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3767
4080
|
/** Move a fork's GC deadline forward, or pin it (`null`) — preview-and-snapshots.md §9. False
|
|
3768
4081
|
* when a reap has claimed the row (#3314): its deadline no longer decides anything. */
|
|
3769
4082
|
setScopeExpiresAt(scopeId, expiresAt, audit) {
|
|
3770
|
-
|
|
4083
|
+
const written = this.writeAndAudit(() => this.sql.exec('UPDATE scopes SET expires_at = ? WHERE scope_id = ? AND reap_claimed_at IS NULL', expiresAt, scopeId).rowsWritten > 0, audit);
|
|
4084
|
+
if (written)
|
|
4085
|
+
this.armSnapshotReap(scopeId, expiresAt);
|
|
4086
|
+
return written;
|
|
3771
4087
|
}
|
|
3772
4088
|
/** One atomic compare-and-set across the preview row and every entry of its copy move. */
|
|
3773
4089
|
keepAlivePendingScopeCopy(tenantId, scopeId, moveId, status, expectedExpiresAt, expiresAt, audit) {
|
|
3774
|
-
|
|
4090
|
+
const written = this.writeAndAudit(() => this.sql.exec(PENDING_COPY_KEEP_ALIVE_SQL, ...pendingCopyKeepAliveParams(expiresAt, tenantId, scopeId, status, expectedExpiresAt, moveId, new Date().toISOString())).rowsWritten > 0, audit);
|
|
4091
|
+
if (written)
|
|
4092
|
+
this.armSnapshotReap(scopeId, expiresAt);
|
|
4093
|
+
return written;
|
|
3775
4094
|
}
|
|
3776
4095
|
async listVersions(verticalSlug, page) {
|
|
3777
4096
|
const where = ['vertical_slug = ?'];
|
|
@@ -3867,7 +4186,8 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3867
4186
|
*/
|
|
3868
4187
|
moveScopeRow(set, setArgs, scopeId, cond, audit) {
|
|
3869
4188
|
const now = new Date().toISOString();
|
|
3870
|
-
|
|
4189
|
+
let confirmedTenant;
|
|
4190
|
+
const written = this.writeAndAudit(() => {
|
|
3871
4191
|
const moved = this.sql.exec(`UPDATE scopes SET ${set} WHERE scope_id = ?
|
|
3872
4192
|
${cond.expectedVersionId === undefined ? '' : 'AND vertical_version_id IS ?'}
|
|
3873
4193
|
${cond.expectedErasureEpoch === undefined ? '' : 'AND COALESCE(erasure_epoch, 0) = ? AND reap_claimed_at IS NULL'}
|
|
@@ -3879,9 +4199,15 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3879
4199
|
const { tenant_id } = this.sql.exec('SELECT tenant_id FROM scopes WHERE scope_id = ?', scopeId).one();
|
|
3880
4200
|
this.sql.exec(COPY_MOVE_CONFIRM_SQL, ...copyMoveConfirmParams(cond.confirmMove, tenant_id, scopeId, now));
|
|
3881
4201
|
this.sql.exec(COPY_BACKFILL_SUPERSEDE_SQL, tenant_id, scopeId);
|
|
4202
|
+
if (cond.confirmMove.source === 'eligible')
|
|
4203
|
+
confirmedTenant = tenant_id;
|
|
3882
4204
|
}
|
|
3883
4205
|
return true;
|
|
3884
4206
|
}, audit);
|
|
4207
|
+
if (confirmedTenant !== undefined) {
|
|
4208
|
+
this.armTenantDueWork(confirmedTenant, [{ kind: 'copies', unit: confirmedTenant, dueAt: Date.parse(now) }]);
|
|
4209
|
+
}
|
|
4210
|
+
return written;
|
|
3885
4211
|
}
|
|
3886
4212
|
/**
|
|
3887
4213
|
* The directory effect and its admin row either both commit or both roll back. A thunk is
|
|
@@ -3954,6 +4280,44 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3954
4280
|
setIssueStatusAndAudit(...args) {
|
|
3955
4281
|
return this.setIssueStatus(...args);
|
|
3956
4282
|
}
|
|
4283
|
+
/**
|
|
4284
|
+
* K-63 (#3624): what an erasure did at a master's dependents. An `erased` dependent leaves the
|
|
4285
|
+
* ledger, an `outstanding` one is kept with its next try; one admin row, in the same unit.
|
|
4286
|
+
*/
|
|
4287
|
+
recordDependentErasures(tenantId, subjectId, outcomes, audit) {
|
|
4288
|
+
if (outcomes.length === 0)
|
|
4289
|
+
return;
|
|
4290
|
+
this.writeAndAudit(() => {
|
|
4291
|
+
for (const o of outcomes) {
|
|
4292
|
+
if (o.outcome === 'erased') {
|
|
4293
|
+
this.sql.exec(DEPENDENT_ERASURE_SETTLE_SQL, tenantId, subjectId, o.scopeId);
|
|
4294
|
+
}
|
|
4295
|
+
else {
|
|
4296
|
+
this.sql.exec(DEPENDENT_ERASURE_OWE_SQL, tenantId, subjectId, o.scopeId, o.vertical, o.attempts, nextDependentErasureAt(audit.at, o.attempts), o.error, audit.at);
|
|
4297
|
+
}
|
|
4298
|
+
}
|
|
4299
|
+
return true;
|
|
4300
|
+
}, audit);
|
|
4301
|
+
}
|
|
4302
|
+
/**
|
|
4303
|
+
* K-63 (#3624): hold each dependent as owed, before the master's erasure runs. The statements run
|
|
4304
|
+
* in one synchronous call, so the object commits them together. A row already owed is kept.
|
|
4305
|
+
*/
|
|
4306
|
+
holdDependentErasures(tenantId, subjectId, dependents) {
|
|
4307
|
+
const now = new Date().toISOString();
|
|
4308
|
+
for (const d of dependents)
|
|
4309
|
+
this.sql.exec(DEPENDENT_ERASURE_HOLD_SQL, tenantId, subjectId, d.scopeId, d.vertical, now, now);
|
|
4310
|
+
}
|
|
4311
|
+
/** K-63 (#3624): the owed dependent erasures due at `now`, oldest due first. */
|
|
4312
|
+
dueDependentErasures(now, limit) {
|
|
4313
|
+
return this.sql.exec(DEPENDENT_ERASURE_DUE_SQL, now, limit).toArray().map((r) => ({
|
|
4314
|
+
tenantId: r.tenant_id,
|
|
4315
|
+
subjectId: r.subject_id,
|
|
4316
|
+
scopeId: r.scope_id,
|
|
4317
|
+
vertical: r.vertical,
|
|
4318
|
+
attempts: r.attempts,
|
|
4319
|
+
}));
|
|
4320
|
+
}
|
|
3957
4321
|
scopeErasureEpoch(tenantId, scopeId) {
|
|
3958
4322
|
// NULL on every row from before the column (#1722): the same 0 every CAS compares against.
|
|
3959
4323
|
const row = this.sql.exec('SELECT COALESCE(erasure_epoch, 0) AS erasure_epoch FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
|
|
@@ -3969,12 +4333,15 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
3969
4333
|
recordScopeScriptCopy(tenantId, scopeId, scriptRef, moveId, role = null, loadStamp = null, leaseMs = SCOPE_COPY_LEASE_MS) {
|
|
3970
4334
|
if (!scriptRef || !moveId)
|
|
3971
4335
|
return 'invalid';
|
|
4336
|
+
const dueAt = Date.now() + leaseMs;
|
|
3972
4337
|
const written = this.sql.exec(`INSERT INTO scope_script_copies (tenant_id, scope_id, script_ref, move_id, state, role, load_stamp, lease_until)
|
|
3973
4338
|
SELECT tenant_id, scope_id, ?, ?, 'pending', ?, ?, ? FROM scopes
|
|
3974
4339
|
WHERE tenant_id = ? AND scope_id = ? AND reap_claimed_at IS NULL
|
|
3975
|
-
ON CONFLICT (tenant_id, scope_id, script_ref, move_id) DO NOTHING`, scriptRef, moveId, role, loadStamp, new Date(
|
|
3976
|
-
if (written.rowsWritten > 0)
|
|
4340
|
+
ON CONFLICT (tenant_id, scope_id, script_ref, move_id) DO NOTHING`, scriptRef, moveId, role, loadStamp, new Date(dueAt).toISOString(), tenantId, scopeId);
|
|
4341
|
+
if (written.rowsWritten > 0) {
|
|
4342
|
+
this.armTenantDueWork(tenantId, [{ kind: 'copies', unit: tenantId, dueAt }]);
|
|
3977
4343
|
return 'recorded';
|
|
4344
|
+
}
|
|
3978
4345
|
const scope = this.sql.exec('SELECT reap_claimed_at FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
|
|
3979
4346
|
.toArray()[0];
|
|
3980
4347
|
if (!scope)
|
|
@@ -4008,7 +4375,9 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4008
4375
|
claimExpiredScopeScriptCopies(input) {
|
|
4009
4376
|
const limit = assertRowLimit('limit', input.limit);
|
|
4010
4377
|
return this.ctx.storage.transactionSync(() => {
|
|
4011
|
-
const due =
|
|
4378
|
+
const due = (input.tenantId !== undefined
|
|
4379
|
+
? this.sql.exec(COPY_EXPIRED_FOR_TENANT_SQL, input.now, input.tenantId, limit)
|
|
4380
|
+
: this.sql.exec(COPY_EXPIRED_SQL, input.now, limit)).toArray();
|
|
4012
4381
|
const claimed = [];
|
|
4013
4382
|
for (const r of due) {
|
|
4014
4383
|
if (this.sql.exec(COPY_CLAIM_SQL, input.owner, input.leaseUntil, r.tenant_id, r.scope_id, r.script_ref, r.move_id, input.now).rowsWritten === 0)
|
|
@@ -4020,8 +4389,8 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4020
4389
|
});
|
|
4021
4390
|
}
|
|
4022
4391
|
/** `HostAdmin.markScopeStoresFenced`: read and written in one synchronous step, so an unarchive is before or after. */
|
|
4023
|
-
markScopeStoresFenced(tenantId, scopeId, whileTenantDeleting, audit) {
|
|
4024
|
-
const scope = this.sql.exec('SELECT status, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
|
|
4392
|
+
markScopeStoresFenced(tenantId, scopeId, whileTenantDeleting, audit, deadlines) {
|
|
4393
|
+
const scope = this.sql.exec('SELECT status, archived_at, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
|
|
4025
4394
|
.toArray()[0];
|
|
4026
4395
|
if (!scope)
|
|
4027
4396
|
throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
|
|
@@ -4030,8 +4399,17 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4030
4399
|
if (scope.status !== 'archived') {
|
|
4031
4400
|
throw substratError('conflict', `scope ${scopeId} is ${scope.status}, not archived, so its stores are not fenced`);
|
|
4032
4401
|
}
|
|
4033
|
-
if (
|
|
4034
|
-
throw substratError('conflict', `
|
|
4402
|
+
if (deadlines?.archivedBy !== undefined && (scope.archived_at === null || scope.archived_at > deadlines.archivedBy)) {
|
|
4403
|
+
throw substratError('conflict', `scope ${scopeId} has not passed its archive retention`);
|
|
4404
|
+
}
|
|
4405
|
+
if (whileTenantDeleting || deadlines?.deletingBy !== undefined) {
|
|
4406
|
+
const tenant = this.readTenant(tenantId);
|
|
4407
|
+
if (tenant?.status !== 'deleting') {
|
|
4408
|
+
throw substratError('conflict', `tenant ${tenantId} is no longer deleting, so the stores of scope ${scopeId} are not fenced`);
|
|
4409
|
+
}
|
|
4410
|
+
if (deadlines?.deletingBy !== undefined && (tenant.deletingAt === null || tenant.deletingAt > deadlines.deletingBy)) {
|
|
4411
|
+
throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
|
|
4412
|
+
}
|
|
4035
4413
|
}
|
|
4036
4414
|
this.writeAndAudit(() => this.sql.exec(`UPDATE scopes SET stores_fenced_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE tenant_id = ? AND scope_id = ?`, tenantId, scopeId).rowsWritten > 0, audit && { ...audit, before: { storesFencedAt: null } });
|
|
4037
4415
|
}
|
|
@@ -4061,7 +4439,7 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4061
4439
|
return 'pending';
|
|
4062
4440
|
}
|
|
4063
4441
|
settleScopeScriptCopy(tenantId, scopeId, scriptRef, moveId, state, loadStamp, revision, claimedBy) {
|
|
4064
|
-
|
|
4442
|
+
const written = this.ctx.storage.transactionSync(() => {
|
|
4065
4443
|
const settled = this.sql.exec(`UPDATE scope_script_copies SET state = ?, load_stamp = ?, revision = ?,
|
|
4066
4444
|
last_attempt_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
|
|
4067
4445
|
WHERE tenant_id = ? AND scope_id = ? AND script_ref = ? AND move_id = ?
|
|
@@ -4071,11 +4449,27 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4071
4449
|
this.sql.exec(COPY_BACKFILL_SUPERSEDE_SQL, tenantId, scopeId);
|
|
4072
4450
|
return settled;
|
|
4073
4451
|
});
|
|
4452
|
+
if (written && state === 'eligible') {
|
|
4453
|
+
this.armTenantDueWork(tenantId, [{ kind: 'copies', unit: tenantId, dueAt: Date.now() }]);
|
|
4454
|
+
}
|
|
4455
|
+
return written;
|
|
4074
4456
|
}
|
|
4075
4457
|
touchScopeScriptCopy(tenantId, scopeId, scriptRef, moveId) {
|
|
4076
4458
|
this.sql.exec(`UPDATE scope_script_copies SET last_attempt_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
|
|
4077
4459
|
WHERE tenant_id = ? AND scope_id = ? AND script_ref = ? AND move_id = ? AND state = 'eligible'`, tenantId, scopeId, scriptRef, moveId);
|
|
4078
4460
|
}
|
|
4461
|
+
nextScopeCopyDue(tenantId, now) {
|
|
4462
|
+
return this.sql.exec(`SELECT MIN(CASE WHEN state = 'eligible' THEN ? ELSE COALESCE(lease_until, ?) END) AS dueAt
|
|
4463
|
+
FROM scope_script_copies WHERE tenant_id = ? AND state IN ('eligible', 'pending')`, now, now, tenantId).one().dueAt;
|
|
4464
|
+
}
|
|
4465
|
+
listDueScopeCopyTenants(input) {
|
|
4466
|
+
return this.sql.exec(`SELECT tenant_id AS tenantId,
|
|
4467
|
+
MIN(CASE WHEN state = 'eligible' THEN ? ELSE COALESCE(lease_until, ?) END) AS dueAt
|
|
4468
|
+
FROM scope_script_copies
|
|
4469
|
+
WHERE tenant_id > ?
|
|
4470
|
+
AND (state = 'eligible' OR (state = 'pending' AND (lease_until IS NULL OR lease_until <= ?)))
|
|
4471
|
+
GROUP BY tenant_id ORDER BY tenant_id LIMIT ?`, input.now, input.now, input.after, input.by, assertRowLimit('limit', input.limit)).toArray();
|
|
4472
|
+
}
|
|
4079
4473
|
listScopeScriptCopies(filter) {
|
|
4080
4474
|
const where = [];
|
|
4081
4475
|
const args = [];
|
|
@@ -4201,6 +4595,28 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4201
4595
|
return true;
|
|
4202
4596
|
}, audit);
|
|
4203
4597
|
}
|
|
4598
|
+
/**
|
|
4599
|
+
* K-65 (#3539): the unit of a release into an earlier major, which moves no channel: its admin row
|
|
4600
|
+
* lands only while major `major`'s script still runs `from`, the version its gates were judged
|
|
4601
|
+
* against, with the listing and the admission read here as `promoteChannel` reads them for prod.
|
|
4602
|
+
* False, with nothing written, when that script moved.
|
|
4603
|
+
*/
|
|
4604
|
+
recordEarlierMajorPromote(slug, major, from, versionId, unlistedOnly, audit, breakingWithinMajor) {
|
|
4605
|
+
return this.writeAndAudit(() => {
|
|
4606
|
+
const vertical = this.readVertical(slug);
|
|
4607
|
+
if (earlierMajorsOf(vertical?.earlier_majors).find((m) => m.major === major)?.versionId !== from)
|
|
4608
|
+
return false;
|
|
4609
|
+
const listed = vertical?.listed;
|
|
4610
|
+
if (listed && unlistedOnly)
|
|
4611
|
+
throw listedPromoteRefusal();
|
|
4612
|
+
if (listed && breakingWithinMajor)
|
|
4613
|
+
throw breakingWithinMajorRefusal(breakingWithinMajor);
|
|
4614
|
+
if (listed && from !== versionId && this.versionAdmission(versionId).admission_note === AUTO_ADMISSION_NOTE) {
|
|
4615
|
+
throw autoAdmittedProdRefusal(slug, versionId);
|
|
4616
|
+
}
|
|
4617
|
+
return true;
|
|
4618
|
+
}, audit);
|
|
4619
|
+
}
|
|
4204
4620
|
listChannels(verticalSlug, page) {
|
|
4205
4621
|
const where = ['vertical_slug = ?'];
|
|
4206
4622
|
const params = [verticalSlug];
|
|
@@ -4228,23 +4644,19 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4228
4644
|
.toArray();
|
|
4229
4645
|
}
|
|
4230
4646
|
// -- organizations (K-22) ---------------------------------------------------
|
|
4647
|
+
// K-68 step 3e (the third family): a tenant whose flip froze its orgs in reads them from, and
|
|
4648
|
+
// creates them first in, its own object (`directory-tenant-orgs.ts`, the same code in either store).
|
|
4231
4649
|
readOrg(tenantId, orgId) {
|
|
4232
|
-
|
|
4233
|
-
.
|
|
4234
|
-
|
|
4650
|
+
if (this.orgsCutOver(tenantId)) {
|
|
4651
|
+
return this.directoryCutover.tupleRead(tenantId, { kind: 'org', orgId }).then((r) => r ?? undefined);
|
|
4652
|
+
}
|
|
4653
|
+
return readOrgRow(this.sql, tenantId, orgId);
|
|
4235
4654
|
}
|
|
4236
4655
|
/** Returns false when the org already exists (idempotent); throws on slug collision. */
|
|
4237
4656
|
createOrg(orgId, tenantId, slug, name, createdAt) {
|
|
4238
|
-
if (this.
|
|
4239
|
-
return
|
|
4240
|
-
|
|
4241
|
-
.exec('SELECT org_id FROM orgs WHERE tenant_id = ? AND slug = ?', tenantId, slug)
|
|
4242
|
-
.toArray()[0];
|
|
4243
|
-
if (slugOwner) {
|
|
4244
|
-
throw substratError('conflict', `org slug '${slug}' already taken by ${slugOwner.org_id} (slugs are unique per tenant)`);
|
|
4245
|
-
}
|
|
4246
|
-
this.sql.exec('INSERT INTO orgs (org_id, tenant_id, slug, name, created_at) VALUES (?, ?, ?, ?, ?)', orgId, tenantId, slug, name, createdAt);
|
|
4247
|
-
return true;
|
|
4657
|
+
if (this.orgsCutOver(tenantId))
|
|
4658
|
+
return this.createOrgFirst(orgId, tenantId, slug, name, createdAt, null);
|
|
4659
|
+
return createOrgIn({ sql: this.sql }, orgId, tenantId, slug, name, createdAt);
|
|
4248
4660
|
}
|
|
4249
4661
|
/**
|
|
4250
4662
|
* #2526: `createOrg` with its admin row, in one unit; an org that already exists writes nothing,
|
|
@@ -4253,19 +4665,24 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4253
4665
|
* org created with no row, where an unknown method fails closed.
|
|
4254
4666
|
*/
|
|
4255
4667
|
insertOrg(orgId, tenantId, slug, name, createdAt, audit) {
|
|
4256
|
-
|
|
4668
|
+
if (this.orgsCutOver(tenantId))
|
|
4669
|
+
return this.createOrgFirst(orgId, tenantId, slug, name, createdAt, audit);
|
|
4670
|
+
return this.writeAndAudit(() => createOrgIn({ sql: this.sql }, orgId, tenantId, slug, name, createdAt), audit);
|
|
4671
|
+
}
|
|
4672
|
+
/** A cut-over tenant's org, created first in its object; a slug's conflict is rethrown here with its code. */
|
|
4673
|
+
async createOrgFirst(orgId, tenantId, slug, name, createdAt, audit) {
|
|
4674
|
+
const r = await this.directoryCutover.tupleWrite(tenantId, {
|
|
4675
|
+
kind: 'createOrg', orgId, slug, name, createdAt, audit: audit,
|
|
4676
|
+
});
|
|
4677
|
+
if ('conflict' in r)
|
|
4678
|
+
throw substratError('conflict', r.conflict);
|
|
4679
|
+
return r.created;
|
|
4257
4680
|
}
|
|
4258
4681
|
listOrgs(tenantId) {
|
|
4259
|
-
|
|
4260
|
-
.
|
|
4261
|
-
|
|
4682
|
+
if (this.orgsCutOver(tenantId))
|
|
4683
|
+
return this.directoryCutover.tupleRead(tenantId, { kind: 'orgs' });
|
|
4684
|
+
return listOrgRows(this.sql, tenantId);
|
|
4262
4685
|
}
|
|
4263
|
-
/** The tenant-level reads, synchronous, for a bound asked inside one of this object's units (#1184). */
|
|
4264
|
-
directoryReader = {
|
|
4265
|
-
now: () => new Date().toISOString(),
|
|
4266
|
-
tenantTuples: (tenantId, subject, prefix) => this.tenantTuples(tenantId, subject, prefix),
|
|
4267
|
-
getRole: (tenantId, key) => this.getRole(tenantId, key),
|
|
4268
|
-
};
|
|
4269
4686
|
/**
|
|
4270
4687
|
* A membership change as ONE DO unit (#1184) — `HostAdmin.applyMembership`. Synchronous, so
|
|
4271
4688
|
* no other request into this object runs between its reads and its writes: an add's removal
|
|
@@ -4278,48 +4695,22 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4278
4695
|
* The org row's `before`/`after` are written here, since only the unit knows the expiry.
|
|
4279
4696
|
* `reserved` (#2430) is what the coordinator's modules reserve to a system principal: an add of
|
|
4280
4697
|
* a role carrying one is a person conferring it, refused in the unit (`reservedRoleRefusal`).
|
|
4698
|
+
* For a cut-over tenant (K-68 step 3e) the same unit runs in its object, whose tuples, fences and
|
|
4699
|
+
* roles are the ones written first; whether the org exists is asked here, where orgs are kept.
|
|
4281
4700
|
*/
|
|
4282
4701
|
applyMembership(change, row, orgRow, reserved = []) {
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
4291
|
-
|
|
4292
|
-
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
return { applied: false, reserved: refused };
|
|
4296
|
-
const bound = tenantCoverage(this.directoryReader, tenantId, boundedBy, role.permissions);
|
|
4297
|
-
if (!bound.covered)
|
|
4298
|
-
return { applied: false, missing: bound.missing };
|
|
4299
|
-
// #2047: the org, bounded by `boundedBy`'s own live membership of it.
|
|
4300
|
-
const org = orgId ? { orgId, row: orgRow, ...orgChangeBound(this.directoryReader, tenantId, { ...change, orgId }) } : undefined;
|
|
4301
|
-
if (org) {
|
|
4302
|
-
if (!org.row)
|
|
4303
|
-
throw new Error('applyMembership: an org change needs its audit row');
|
|
4304
|
-
if (!this.readOrg(tenantId, org.orgId))
|
|
4305
|
-
return { applied: false, unknownOrg: org.orgId };
|
|
4306
|
-
if (!org.bounded)
|
|
4307
|
-
return { applied: false, notMember: org.orgId };
|
|
4308
|
-
}
|
|
4309
|
-
if (change.op === 'remove') {
|
|
4310
|
-
const roleTaken = this.revokeAndFenceIn(tenantId, principal, `role:${roleKey}`, `tenant:${tenantId}`, row);
|
|
4311
|
-
const orgLeft = !!org && this.revokeAndFenceIn(tenantId, principal, 'member', `org:${org.orgId}`, { ...org.row, before: { principal, orgId: org.orgId } });
|
|
4312
|
-
return { applied: true, changed: roleTaken || orgLeft };
|
|
4313
|
-
}
|
|
4314
|
-
const at = new Date().toISOString();
|
|
4315
|
-
this.writeTenantTuple(tenantId, `principal:${principal}`, `role:${roleKey}`, `tenant:${tenantId}`, null);
|
|
4316
|
-
this.recordAdmin({ ...row, at });
|
|
4317
|
-
if (org?.bounded) {
|
|
4318
|
-
this.writeTenantTuple(tenantId, `principal:${principal}`, 'member', `org:${org.orgId}`, org.expiresAt);
|
|
4319
|
-
this.recordAdmin({ ...org.row, after: memberAddedAudit(principal, org.orgId, org.expiresAt), at });
|
|
4320
|
-
}
|
|
4321
|
-
return { applied: true };
|
|
4322
|
-
});
|
|
4702
|
+
if (this.tuplesCutOver(change.tenantId)) {
|
|
4703
|
+
return this.directoryCutover.tupleWrite(change.tenantId, {
|
|
4704
|
+
kind: 'membership',
|
|
4705
|
+
change,
|
|
4706
|
+
row: row,
|
|
4707
|
+
orgRow: orgRow ?? null,
|
|
4708
|
+
reserved: [...reserved],
|
|
4709
|
+
// Orgs moved with the tuples: the object reads its own. Otherwise the directory answers here.
|
|
4710
|
+
orgKnown: this.orgsCutOver(change.tenantId) ? null : !!change.orgId && !!readOrgRow(this.sql, change.tenantId, change.orgId),
|
|
4711
|
+
});
|
|
4712
|
+
}
|
|
4713
|
+
return this.ctx.storage.transactionSync(() => applyMembershipIn(this.tupleStore(), change, row, orgRow, reserved));
|
|
4323
4714
|
}
|
|
4324
4715
|
/**
|
|
4325
4716
|
* A tenant-level removal as ONE DO unit (#1184) — `unassignRole` at the tenant node, and
|
|
@@ -4327,70 +4718,51 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4327
4718
|
* K-21 writes only when something changed. The fence is raised either way: a removal of
|
|
4328
4719
|
* someone whose add is still on its way takes nothing, and must still win. One method, so
|
|
4329
4720
|
* no add can run between the revoke and the fence. Returns whether anything changed.
|
|
4330
|
-
*/
|
|
4331
|
-
revokeAndFence(tenantId, principal, relation, object, row) {
|
|
4332
|
-
return this.ctx.storage.transactionSync(() => this.revokeAndFenceIn(tenantId, principal, relation, object, row));
|
|
4333
|
-
}
|
|
4334
|
-
/**
|
|
4335
|
-
* `revokeAndFence`'s writes, for inside a transaction a caller already holds.
|
|
4336
4721
|
*
|
|
4337
|
-
* The time is minted
|
|
4338
|
-
*
|
|
4339
|
-
*
|
|
4340
|
-
*
|
|
4341
|
-
*
|
|
4342
|
-
*
|
|
4722
|
+
* The time is minted in the unit, never taken from `row.at`: the coordinator mints its row
|
|
4723
|
+
* before an awaited RPC, and a queue delay in between would age the fence by however long the
|
|
4724
|
+
* call waited, which an add's cutoff would read as a removal from before its window (Codex
|
|
4725
|
+
* round 3). The fence is compared with an add's `occurredAt`, stamped by the ScopeDO's clock.
|
|
4726
|
+
* Both are this platform's own NTP-disciplined time, sub-second apart, which is far inside
|
|
4727
|
+
* `MEMBERSHIP_REMOVAL_SKEW_MS`.
|
|
4343
4728
|
*/
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
return
|
|
4729
|
+
revokeAndFence(tenantId, principal, relation, object, row) {
|
|
4730
|
+
if (this.tuplesCutOver(tenantId)) {
|
|
4731
|
+
return this.directoryCutover.tupleWrite(tenantId, {
|
|
4732
|
+
kind: 'revokeAndFence', principal, relation, object, row: row,
|
|
4733
|
+
}).then((r) => r.changed);
|
|
4734
|
+
}
|
|
4735
|
+
return this.ctx.storage.transactionSync(() => revokeAndFenceIn(this.tupleStore(), tenantId, principal, relation, object, row));
|
|
4351
4736
|
}
|
|
4352
4737
|
/** Tombstone any tenant tuple by its exact (subject, relation, object). Returns
|
|
4353
|
-
* whether a live row changed, so a repeat revoke is a silent no-op.
|
|
4738
|
+
* whether a live row changed, so a repeat revoke is a silent no-op. A cut-over tenant's is
|
|
4739
|
+
* refused here (K-68 step 3e: its tuples are written in its object first). */
|
|
4354
4740
|
revokeTenantTuple(tenantId, subject, relation, object, at) {
|
|
4355
|
-
|
|
4356
|
-
.exec(`SELECT 1 FROM _substrat_tenant_tuples
|
|
4357
|
-
WHERE tenant_id = ? AND subject = ? AND relation = ? AND object = ?
|
|
4358
|
-
AND revoked_at IS NULL`, tenantId, subject, relation, object)
|
|
4359
|
-
.toArray();
|
|
4360
|
-
if (before.length === 0)
|
|
4361
|
-
return false;
|
|
4362
|
-
this.sql.exec(`UPDATE _substrat_tenant_tuples SET revoked_at = ?
|
|
4363
|
-
WHERE tenant_id = ? AND subject = ? AND relation = ? AND object = ?
|
|
4364
|
-
AND revoked_at IS NULL`, at, tenantId, subject, relation, object);
|
|
4365
|
-
return true;
|
|
4741
|
+
return revokeTenantTupleIn(this.tupleStore(), tenantId, subject, relation, object, at);
|
|
4366
4742
|
}
|
|
4367
4743
|
/** Members of an org. Live only unless `includeRevoked` — revoked rows are evidence. */
|
|
4368
4744
|
listMembers(tenantId, object, includeRevoked) {
|
|
4369
|
-
|
|
4370
|
-
.
|
|
4371
|
-
|
|
4372
|
-
${includeRevoked ? '' : 'AND revoked_at IS NULL'}
|
|
4373
|
-
ORDER BY subject`, tenantId, object)
|
|
4374
|
-
.toArray();
|
|
4745
|
+
if (this.tuplesCutOver(tenantId))
|
|
4746
|
+
return this.directoryCutover.tupleRead(tenantId, { kind: 'members', object, includeRevoked });
|
|
4747
|
+
return listMemberRows(this.sql, tenantId, object, includeRevoked);
|
|
4375
4748
|
}
|
|
4376
4749
|
tenantTuples(tenantId, subject, relationPrefix) {
|
|
4377
|
-
|
|
4378
|
-
.
|
|
4379
|
-
|
|
4380
|
-
.toArray();
|
|
4750
|
+
if (this.tuplesCutOver(tenantId))
|
|
4751
|
+
return this.directoryCutover.tupleRead(tenantId, { kind: 'tuples', subject, relationPrefix });
|
|
4752
|
+
return tenantTupleRows(this.sql, tenantId, subject, relationPrefix);
|
|
4381
4753
|
}
|
|
4382
4754
|
/**
|
|
4383
4755
|
* ALL of a tenant's tenant-level tuples — the read behind scope-local projection
|
|
4384
4756
|
* (docs/architecture/scope-local-permissions.md). Includes tombstoned rows so the
|
|
4385
4757
|
* projection mirrors the directory exactly and the checker's own `live()` filter
|
|
4386
4758
|
* drops them identically. Not on the request hot path — this runs on the admin
|
|
4387
|
-
* write path, projecting into a tenant's scopes.
|
|
4759
|
+
* write path, projecting into a tenant's scopes. A cut-over tenant's are its object's, so a
|
|
4760
|
+
* revocation it made first is projected even while its fallback is still owed here.
|
|
4388
4761
|
*/
|
|
4389
4762
|
dumpTenantTuples(tenantId) {
|
|
4390
|
-
|
|
4391
|
-
.
|
|
4392
|
-
|
|
4393
|
-
.toArray();
|
|
4763
|
+
if (this.tuplesCutOver(tenantId))
|
|
4764
|
+
return this.directoryCutover.tupleRead(tenantId, { kind: 'dump' });
|
|
4765
|
+
return dumpTenantTupleRows(this.sql, tenantId);
|
|
4394
4766
|
}
|
|
4395
4767
|
// -- entitlements (control-plane.md §4.3) -----------------------------------
|
|
4396
4768
|
// #33: the flag carries plan fields. The PATCH merge (omitted preserves, null
|
|
@@ -4888,6 +5260,8 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4888
5260
|
* reconcile re-seats it from when that delivery fails. Answers the connection's vertical.
|
|
4889
5261
|
*/
|
|
4890
5262
|
grantConnectionInDirectory(row, audit) {
|
|
5263
|
+
if (!row.scopeId && this.tuplesCutOver(row.tenantId))
|
|
5264
|
+
return this.grantConnectionFirst(row, audit);
|
|
4891
5265
|
return this.ctx.storage.transactionSync(() => {
|
|
4892
5266
|
const conn = this.readConnection(row.connectionId);
|
|
4893
5267
|
if (!conn)
|
|
@@ -4908,13 +5282,55 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4908
5282
|
}
|
|
4909
5283
|
this.recordConnectionGrant({ ...row, vertical: conn.vertical });
|
|
4910
5284
|
if (!row.scopeId) {
|
|
4911
|
-
this.
|
|
5285
|
+
writeTenantTupleIn(this.tupleStore(), row.tenantId, `connection:${row.connectionId}`, `granted:${row.permission}`, `tenant:${row.tenantId}`, row.expiresAt);
|
|
4912
5286
|
}
|
|
4913
5287
|
const after = (audit.after ?? {});
|
|
4914
5288
|
this.recordAdmin({ ...audit, vertical: conn.vertical, after: { ...after, provider: conn.provider } });
|
|
4915
5289
|
return { vertical: conn.vertical };
|
|
4916
5290
|
});
|
|
4917
5291
|
}
|
|
5292
|
+
/**
|
|
5293
|
+
* K-68 step 3e: a tenant-level connection grant of a cut-over tenant, as one exclusive step
|
|
5294
|
+
* (`exclusive`): the connection judged here as it stands, the tuple written first in the tenant's
|
|
5295
|
+
* object, and the record (`_substrat_connection_grants`, still this directory's) carried with it to
|
|
5296
|
+
* the fallback, which writes the record, the tuple and the admin row in one transaction. A revoke of
|
|
5297
|
+
* the connection can then land only after the grant, as it could in the synchronous unit; if the
|
|
5298
|
+
* fallback is applied later, `applyCarried` tombstones the record as that revoke's cascade would have.
|
|
5299
|
+
*/
|
|
5300
|
+
grantConnectionFirst(row, audit) {
|
|
5301
|
+
return this.exclusive(async () => {
|
|
5302
|
+
const conn = this.readConnection(row.connectionId);
|
|
5303
|
+
if (!conn)
|
|
5304
|
+
throw new Error(`connection not found: ${row.connectionId}`);
|
|
5305
|
+
if (conn.revoked_at)
|
|
5306
|
+
throw new Error(`connection ${row.connectionId} is revoked — grant nothing to it`);
|
|
5307
|
+
if (conn.tenant_id !== row.tenantId) {
|
|
5308
|
+
throw new Error(`connection ${row.connectionId} belongs to tenant ${conn.tenant_id} and cannot be granted anything in ${row.tenantId}`);
|
|
5309
|
+
}
|
|
5310
|
+
const after = (audit.after ?? {});
|
|
5311
|
+
await this.directoryCutover.tupleWrite(row.tenantId, {
|
|
5312
|
+
kind: 'write', subject: `connection:${row.connectionId}`, relation: `granted:${row.permission}`, object: `tenant:${row.tenantId}`,
|
|
5313
|
+
expiresAt: row.expiresAt,
|
|
5314
|
+
audit: { ...audit, vertical: conn.vertical, after: { ...after, provider: conn.provider } },
|
|
5315
|
+
}, [{ kind: 'connectionGrant', row: { ...row, scopeId: null, vertical: conn.vertical } }]);
|
|
5316
|
+
return { vertical: conn.vertical };
|
|
5317
|
+
});
|
|
5318
|
+
}
|
|
5319
|
+
/**
|
|
5320
|
+
* K-68 step 3e: a write the directory still owns that rode a first write (`CarriedWrite`), in the
|
|
5321
|
+
* fallback's transaction. A connection revoked since the grant was judged tombstones the record at
|
|
5322
|
+
* its revoke time (#592's cascade): the grant came first, and the revoke took it.
|
|
5323
|
+
*/
|
|
5324
|
+
applyCarried(write) {
|
|
5325
|
+
if (write.kind !== 'connectionGrant')
|
|
5326
|
+
throw new Error(`directory cutover: no carried write ${write.kind}`);
|
|
5327
|
+
this.recordConnectionGrant(write.row);
|
|
5328
|
+
const conn = this.readConnection(write.row.connectionId);
|
|
5329
|
+
if (conn?.revoked_at) {
|
|
5330
|
+
this.sql.exec(`UPDATE _substrat_connection_grants SET revoked_at = ?
|
|
5331
|
+
WHERE connection_id = ? AND permission = ? AND scope_id IS NULL AND revoked_at IS NULL`, conn.revoked_at, write.row.connectionId, write.row.permission);
|
|
5332
|
+
}
|
|
5333
|
+
}
|
|
4918
5334
|
/**
|
|
4919
5335
|
* #2732: `revokeFromConnection`'s directory half as one unit, after the scope's tuple was
|
|
4920
5336
|
* delivered gone. The scope-level record is tombstoned (K-21), so the additive reconcile never
|
|
@@ -4982,6 +5398,9 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
4982
5398
|
* there is a tenant tuple is still switchable. Read here, where the tenant tuples live.
|
|
4983
5399
|
*/
|
|
4984
5400
|
tenantHeldOf(kind, tenantId, keys, now) {
|
|
5401
|
+
// K-68 step 3e: a cut-over tenant's grants are its object's.
|
|
5402
|
+
if (this.tuplesCutOver(tenantId))
|
|
5403
|
+
return this.directoryCutover.tupleRead(tenantId, { kind: 'held', switchKind: kind, keys: [...keys], now });
|
|
4985
5404
|
return tenantHeldOf(this.kernelSql, kind, tenantId, keys, now);
|
|
4986
5405
|
}
|
|
4987
5406
|
/** The fleet read. */
|
|
@@ -5458,7 +5877,7 @@ export class ControlPlaneDO extends DurableObject {
|
|
|
5458
5877
|
return this.sql
|
|
5459
5878
|
.exec(`SELECT s.tenant_id, s.scope_id, s.status AS scope_status, t.status AS tenant_status, r.delivered,
|
|
5460
5879
|
${epoch} AS epoch, COALESCE(rs.revision, 0) AS scope_rev, COALESCE(rt.revision, 0) AS tenant_rev,
|
|
5461
|
-
${LIFECYCLE_DEPLOYMENT} AS deployment
|
|
5880
|
+
${LIFECYCLE_DEPLOYMENT} AS deployment, f.retry_at
|
|
5462
5881
|
FROM scopes s
|
|
5463
5882
|
JOIN tenants t ON t.tenant_id = s.tenant_id
|
|
5464
5883
|
LEFT JOIN verticals v ON v.slug = s.vertical
|