@substrat-run/adapter-sqlite 0.220.0 → 0.222.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/delivery-broker.d.ts +7 -1
- package/dist/delivery-broker.d.ts.map +1 -1
- package/dist/delivery-broker.js +4 -2
- package/dist/delivery-broker.js.map +1 -1
- package/dist/dev-mail-outbox.d.ts.map +1 -1
- package/dist/dev-mail-outbox.js +4 -71
- package/dist/dev-mail-outbox.js.map +1 -1
- package/dist/index.d.ts +68 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +565 -89
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.js
CHANGED
|
@@ -2,11 +2,11 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, writeFileSync, writeSync } from 'node:fs';
|
|
3
3
|
import { dirname, join } from 'node:path';
|
|
4
4
|
import Database from 'better-sqlite3';
|
|
5
|
-
import { accessLogEntry, adminLogEntry, delegatedReadParams, operationSeriesCount, opsFailureEntry, opsFailureFingerprint, issueEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunEntry, modelUsageEntry, ATTACHMENT_ADDED, ATTACHMENT_REMOVED, createTenantInput, domainEvent, domainEventInput, exportReadInput, importBatch, pushedImport, moduleId, importCursorMove, exportsOfManifestJson, assertNoBindingShapeBreak, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, entitlementGrant, entitlementGrantInput, eventId, meterReading, platformRequestInput, platformRequestId, identityLink, identityPool, instant, isSubstratError, connection, capabilityGrant, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchRecord, peerSwitch, verticalCaller, verticalSlug as verticalSlugOf, subjectRef, requestFingerprint, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, routeTarget, ROUTE_SCOPE_HOSTNAMES_MAX, registerVerticalInput, vertical as verticalSchema, verticalChannel, verticalVersion, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, grantRefFromProof, org as orgSchema, orgMembership, principalId, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, principalBecomeCapabilityInput, principalBindLinkInput, mergeDumpPages, subjectShredReceipt, subjectAccessReceipt, SCOPE_TABLE_PAGE_DEFAULT, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, verticalServingState, verticalTraceSampling, deploymentWireAuth, callsOfManifestJson, outboundOfManifestJson, listLimitOf, pageOf, countedPageOf, SCOPE_GATE_REASONS, substratError, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsAudit, dumpObjectsOf, isRuntimeTable, replayDumpObjects, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, redrainEventsInput, REDRAIN_BATCH, errorCodeOf, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
|
|
6
|
-
import { actorOf, asPrincipal, assertAllowed, assertNoSecret, assertPermissionKey, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, redeemOrReplayUploadLink, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, becomeMintCheck, mintBecomeCapabilityAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, capabilityTokenHash, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, entityStateMigrations, assertNoCallerPurge, assertPlatformRequestRoom, isUnreachableParent, heldPurgePass, purgeDueAt, purgeDueOf, purgeHeldBy, lifecycleRefusal, scopeNotHeldRefusal, purgeOnlyKeysOf, purgeReportOf, purgeStillDue, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, runPurgePass, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, heldKeysOf, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability as exchangeCapabilitySecret, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, plausibleSessionToken, readCapabilityPage, redactSecrets, redactSecretText, moduleLog, consoleLogSink, asyncInvocationId, asyncLinePass, consoleInvocationLineSink, resolveCapabilitySession, revokeCapabilityAsPlatform, assertReadOnlyQuery, attachmentBlobKey, attachmentSha256, isSizedByteStream, knownLengthStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, guardSpine, guardSqlLimits, DO_SQL_LIMITS, tooManyResultColumns, tooManyTableColumns, parseValidationRecords, readableScopes, resolveScopeRecord, ulid, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, ATTACHMENT_BYTES_SQL, SCOPE_STORAGE_DDL, forgetScopeStorage, listScopeAttachmentStorageRows, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, 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, DIRECTORY_LAKE_DDL, ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink, listConnectLinks as listConnectLinkRows, readConnectLink, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, assertRowOffset, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, BUILD_USAGE_RETENTION_DAYS, MODEL_USAGE_RETENTION_DAYS, foldModelUsage, backoffAt, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleRowsErased, moduleErasurePlan, redactSubjectScopeText, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, JOB_RUN_PATCH_SQL, JOB_RUN_CLAIM_SQL, JOB_RUN_RENEW_SQL, JOB_RUN_BEGIN_SQL, JOB_RUN_MISS_SQL, JOB_RUN_MISS_SETTLE_SQL, admissionMissOutcome, JOB_STEP_RECORD_SQL, JOB_LEASE_EXPIRED_NOTE, assertLeaseMs, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, dumpRoleRefusal, reservedGrantRefusal, reservedRoleDefinitionRefusal, reservedRoleRefusal, reservedShapeRefusal, SCOPE_SEATED_ROLES_SQL, SEAT_HOLDING_SCOPE_STATUSES, TENANT_SEATED_ROLES_SQL, admitPeer, boundToPeerDeclarations, peerCallerAt, collectPeers, peerSeats, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, peerVerticalSpellings, samePeerVertical, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, APP_ENVIRONMENTS_DDL, defineEnvironmentIn, environmentsOf, removeEnvironmentIn, SWITCH_OWED_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, executableSqlStatements, blankSqlComments, recordWriteSuperseded, switchFencesOf, switchSupersededMessage, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, moveSwitch, reassertActionOf, reassertEntry, reassertOffRow, recordSwitchedOff, recordSwitchedOn, restoreSwitchRecord, scopesSwitchedOffFor, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, switchRecordsOf, switchedOffOf, switchesBackfillSqlOf, switchesTableExists, tenantHeldOf, tenantHoldsGrant, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, withRecorded, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, forgetVerticalScopeStores, DEPLOYMENT_WIRE_AUTH_DDL, assertWireAuthFilter, deploymentWireAuthOf, forgetVerticalWireAuth, wireAuthAccessTarget, writeDeploymentWireAuth, indexVersionScopeStores, driverDeclarationsOf, verticalScopeStoresOf, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, splitManifestMigrations, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, deriveVersionMigrationDigest, publishedMigrationDigest, migrationChangeRefusal, writeVersionMigrations, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, pruneInputOf, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, ImpersonationRefused, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, assertSessionUsable, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, impersonationStampOf, mapImpersonationRow, newImpersonationSession, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, tenantCoverage, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, noSealingKeyMessage, openSealed, sealTo, ConnectionSealingKeyUnavailableError, PermissionDenied, createAtomic, NotSearchable, NotListable, listIndexMigrations, listIndexPlans, listQuery, cursorOf, moduleMigrations, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations, isSearchIndexTable, rowCountTable, searchIndexMigrations, searchIndexPlans, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, fenceAttachmentSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, sweepOrphanAttachments, missingAttachmentStore, SETTLED_COPY_STATES, unsettledCopyRefusal, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, attachmentRecordOfRow, attachmentTextJob, enqueueAttachmentText, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, queueAttachmentTextBackfill, startAttachmentTextBackfill, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, reconcileAttachmentText, recordAttachmentText, searchAttachments, entityVersionQuery, entityVersionOf, assertIfMatch, OUTBOX_ENTITY_INDEX, SCHEDULE_STATE_DDL, SCHEDULE_STATE_REBUILD, scheduleStateHasKind, VERTICAL_EVENTS_DDL, EXPORT_HOPS_SQL, emptyImportResult, IMPORT_CURSORS_SQL, IMPORT_CURSOR_OF_SQL, OUTBOX_MARK_SQL, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, exportedSinceQuery, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, autoAdmittedProdRefusal, listedPromoteRefusal, rebindRaceRefusal, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, migratesFrom, servedFromRow, servesAsFrom, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, isPrimaryScope, PROVISIONED_VERSIONS_SQL, installsReconciledOf, strandJudgmentsOf, provisionedVersionsParams, boundShapesColumn, boundShapesOfColumn, installReconciled, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, jobRunOf, runDueJobRuns, startJobRun, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, globalFetch, fetchLikeOf, deadlineFetch, createUlid, facetEvents, readHistory, walkEventCause, walkEventEffects, assertRedrainWindow, readInvocation, readDeadLetters, readLifecycleFlow, readOperationSeries, domainEventOf, readUndrainedOutbox, undrainedEventsOf, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, unknownRoleError, callReservedStoreOperation, storesFencedRefusal, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf, } from '@substrat-run/kernel';
|
|
5
|
+
import { PRODUCTION_ENVIRONMENT, accessLogEntry, adminLogEntry, delegatedReadParams, operationSeriesCount, opsFailureEntry, opsFailureFingerprint, issueEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunEntry, modelUsageEntry, ATTACHMENT_ADDED, ATTACHMENT_REMOVED, createTenantInput, domainEvent, domainEventInput, exportReadInput, importBatch, pushedImport, moduleId, importCursorMove, exportsOfManifestJson, assertNoBindingShapeBreak, assertScopeTypesKept, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, entitlementGrant, entitlementGrantInput, eventId, meterReading, platformRequestInput, platformRequestId, identityLink, identityPool, instant, isSubstratError, connection, capabilityGrant, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchRecord, peerSwitch, verticalCaller, verticalSlug as verticalSlugOf, subjectRef, requestFingerprint, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, createOrgInput, promotionAcknowledgement, environmentServeAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, routeTarget, ROUTE_SCOPE_HOSTNAMES_MAX, registerVerticalInput, vertical as verticalSchema, verticalChannel, verticalVersion, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, grantRefFromProof, org as orgSchema, orgMembership, principalId, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, principalBecomeCapabilityInput, principalBindLinkInput, mergeDumpPages, subjectShredReceipt, subjectAccessReceipt, SCOPE_TABLE_PAGE_DEFAULT, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, verticalServingState, verticalTraceSampling, deploymentWireAuth, callsOfManifestJson, outboundOfManifestJson, listLimitOf, pageOf, countedPageOf, SCOPE_GATE_REASONS, substratError, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsAudit, dumpObjectsOf, isRuntimeTable, replayDumpObjects, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, redrainEventsInput, REDRAIN_BATCH, errorCodeOf, storeDriverDumpPageBytes, storeOperationKeyOf, } from '@substrat-run/contracts';
|
|
6
|
+
import { actorOf, asPrincipal, assertAllowed, assertNoSecret, assertPermissionKey, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, STORE_PROOF_DDL, mintStoreProof, redeemStoreProof, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, redeemOrReplayUploadLink, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, becomeMintCheck, mintBecomeCapabilityAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, capabilityTokenHash, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, entityStateMigrations, assertNoCallerPurge, assertPlatformRequestRoom, isUnreachableParent, heldPurgePass, purgeDueAt, purgeDueOf, consumeScheduleDue, dueByEventSchedulesOf, noteScheduleDue, readScheduleDue, scheduleDueAt, purgeHeldBy, lifecycleRefusal, scopeNotHeldRefusal, purgeOnlyKeysOf, purgeReportOf, purgeStillDue, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, runPurgePass, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, heldKeysOf, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability as exchangeCapabilitySecret, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, plausibleSessionToken, readCapabilityPage, redactSecrets, redactSecretText, moduleLog, consoleLogSink, asyncInvocationId, asyncLinePass, consoleInvocationLineSink, resolveCapabilitySession, revokeCapabilityAsPlatform, assertReadOnlyQuery, attachmentBlobKey, attachmentSha256, isSizedByteStream, knownLengthStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, guardSpine, guardSqlLimits, DO_SQL_LIMITS, tooManyResultColumns, tooManyTableColumns, parseValidationRecords, readableScopes, resolveScopeRecord, ulid, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, ATTACHMENT_BYTES_SQL, SCOPE_STORAGE_DDL, forgetScopeStorage, listScopeAttachmentStorageRows, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, 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, DIRECTORY_LAKE_DDL, ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink, listConnectLinks as listConnectLinkRows, readConnectLink, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, assertRowOffset, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, BUILD_USAGE_RETENTION_DAYS, MODEL_USAGE_RETENTION_DAYS, foldModelUsage, backoffAt, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleRowsErased, moduleErasurePlan, redactSubjectScopeText, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, JOB_RUN_PATCH_SQL, JOB_RUN_CLAIM_SQL, JOB_RUN_RENEW_SQL, JOB_RUN_BEGIN_SQL, JOB_RUN_MISS_SQL, JOB_RUN_MISS_SETTLE_SQL, admissionMissOutcome, JOB_STEP_RECORD_SQL, JOB_LEASE_EXPIRED_NOTE, assertLeaseMs, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, dumpRoleRefusal, reservedGrantRefusal, reservedRoleDefinitionRefusal, reservedRoleRefusal, reservedShapeRefusal, SCOPE_SEATED_ROLES_SQL, SEAT_HOLDING_SCOPE_STATUSES, TENANT_SEATED_ROLES_SQL, admitPeer, boundToPeerDeclarations, peerCallerAt, collectPeers, peerSeats, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, peerVerticalSpellings, samePeerVertical, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, APP_ENVIRONMENTS_DDL, claimEnvironmentServeIn, defineEnvironmentIn, ENVIRONMENT_SCRIPT_JOIN_SQL, environmentsOf, homeParentOf, homeScopeIn, secondHomeRefusal, releaseEnvironmentServeIn, removeEnvironmentIn, setEnvironmentServingIn, setEnvironmentEffectsIn, connectionReachIn, deliveryEnvironmentIn, environmentOfScopeIn, SWITCH_OWED_DDL, DEPENDENT_ERASURES_DDL, DEPENDENT_ERASURE_DUE_SQL, DEPENDENT_ERASURE_HOLD_SQL, DEPENDENT_ERASURE_OWE_SQL, DEPENDENT_ERASURE_SETTLE_SQL, nextDependentErasureAt, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, executableSqlStatements, blankSqlComments, recordWriteSuperseded, switchFencesOf, switchSupersededMessage, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, moveSwitch, reassertActionOf, reassertEntry, reassertOffRow, recordSwitchedOff, recordSwitchedOn, restoreSwitchRecord, scopesSwitchedOffFor, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, switchRecordsOf, switchedOffOf, switchesBackfillSqlOf, switchesTableExists, tenantHeldOf, tenantHoldsGrant, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, withRecorded, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, forgetVerticalScopeStores, DEPLOYMENT_WIRE_AUTH_DDL, assertWireAuthFilter, deploymentWireAuthOf, forgetVerticalWireAuth, wireAuthAccessTarget, writeDeploymentWireAuth, indexVersionScopeStores, driverDeclarationsOf, verticalScopeStoresOf, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, splitManifestMigrations, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, deriveVersionMigrationDigest, publishedMigrationDigest, migrationChangeRefusal, writeVersionMigrations, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, pruneInputOf, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, ImpersonationRefused, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, assertSessionUsable, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, impersonationStampOf, mapImpersonationRow, newImpersonationSession, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, tenantCoverage, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, noSealingKeyMessage, openSealed, sealTo, ConnectionSealingKeyUnavailableError, PermissionDenied, createAtomic, NotSearchable, NotListable, listIndexMigrations, listIndexPlans, listQuery, cursorOf, moduleMigrations, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations, isSearchIndexTable, rowCountTable, searchIndexMigrations, searchIndexPlans, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, fenceAttachmentSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, sweepOrphanAttachments, missingAttachmentStore, SETTLED_COPY_STATES, unsettledCopyRefusal, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, attachmentRecordOfRow, attachmentTextJob, enqueueAttachmentText, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, queueAttachmentTextBackfill, startAttachmentTextBackfill, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, reconcileAttachmentText, recordAttachmentText, searchAttachments, entityVersionQuery, entityVersionOf, assertIfMatch, OUTBOX_ENTITY_INDEX, SCHEDULE_STATE_DDL, SCHEDULE_STATE_REBUILD, scheduleStateHasKind, VERTICAL_EVENTS_DDL, EXPORT_HOPS_SQL, emptyImportResult, IMPORT_CURSORS_SQL, IMPORT_CURSOR_OF_SQL, OUTBOX_MARK_SQL, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, exportedSinceQuery, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, autoAdmittedProdRefusal, listedPromoteRefusal, rebindRaceRefusal, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, migratesFrom, servedFromRow, servesAsFrom, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, isPrimaryScope, PROVISIONED_VERSIONS_SQL, installsReconciledOf, strandJudgmentsOf, provisionedVersionsParams, boundShapesColumn, boundShapesOfColumn, installReconciled, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, jobRunOf, runDueJobRuns, startJobRun, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, globalFetch, fetchLikeOf, deadlineFetch, createUlid, facetEvents, readHistory, walkEventCause, walkEventEffects, assertRedrainWindow, readInvocation, readDeadLetters, readLifecycleFlow, readOperationSeries, domainEventOf, readUndrainedOutbox, undrainedEventsOf, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, unknownRoleError, callReservedStoreOperation, storesFencedRefusal, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, proofCheckedStoreInvoke, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf, } from '@substrat-run/kernel';
|
|
7
7
|
import { handoffOutcome, reportHandoff, traceIdOf } from '@substrat-run/kernel';
|
|
8
8
|
// #2993: the modules a scope of each declared type runs, and the type a provision fixes.
|
|
9
|
-
import { HOME_SCOPE_TYPE, operationNotInScopeType, provisionedScopeType, scopeTypePlanOf, scopeTypeRuns } from '@substrat-run/kernel';
|
|
9
|
+
import { childDoorRefusal, childScopeRefusal, directAccessRefusal, HOME_SCOPE_TYPE, operationNotInScopeType, parentlessScopeRefusal, provisionedParent, provisionedScopeType, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRoleRefusal, scopeTypeRuns, } from '@substrat-run/kernel';
|
|
10
10
|
import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
|
|
11
11
|
import { attributedView, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, shapeTopUpBatch, topUpEntityGrantShapes, settlePlatformRequestIn, } from '@substrat-run/kernel';
|
|
12
12
|
import { assertSameAttachmentGate, attachmentGateOf, decideAttachmentRemove, } from '@substrat-run/kernel';
|
|
@@ -16,12 +16,12 @@ import { advanceMarks, handoffQueries, messagesOf, senderDeliveryOf, } from '@su
|
|
|
16
16
|
import { intentStateOf, intentStateQuery, witnessesOf, witnessQueries, } from '@substrat-run/kernel';
|
|
17
17
|
import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
|
|
18
18
|
import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
|
|
19
|
-
import { breakingWithinMajorRefusal, earlierMajorsOf, releaseWithinMajorRefusal, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
|
|
19
|
+
import { breakingWithinMajorRefusal, earlierMajorReleaseTarget, earlierMajorsOf, releasedEarlierMajorJson, releaseWithinMajorRefusal, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
|
|
20
20
|
import { classify as classifyRelease } from '@substrat-run/model-view/bump';
|
|
21
21
|
import { ADMIN_LOG_INDEXES_SQL, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, readAuditedOperations, unknownOutcomeOf, } from '@substrat-run/kernel';
|
|
22
22
|
import { INERT_SCOPE_REASON, isPrimaryScopeRow, normalizeUploadMediaType } from '@substrat-run/kernel';
|
|
23
23
|
import { opsFailureReferenceWhere } from '@substrat-run/kernel';
|
|
24
|
-
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, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, scopeScriptCopyOf, } from '@substrat-run/kernel';
|
|
24
|
+
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, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, scopeScriptCopyOf, } from '@substrat-run/kernel';
|
|
25
25
|
import { GRANT_CHILDREN_INDEX_DDL, SHAPE_MARKER_INDEX_DDL, grantedEntitiesForContext } from '@substrat-run/kernel';
|
|
26
26
|
import { LEGACY_SCOPE_ROWS_BACKFILL, assertSpineTablesBuilt, capabilitiesForLoad, dumpRowsInsert, isSpineTable, loadDirectoryDump, repointScopeGrants, settleCopiedWork, emittedHere, spineColumnAdditions } from '@substrat-run/kernel';
|
|
27
27
|
import { ScopeActor } from './actor.js';
|
|
@@ -357,6 +357,9 @@ const KERNEL_DDL = `
|
|
|
357
357
|
-- #3139: download links, a short-lived URL that lets a caller with no session read ONE file as
|
|
358
358
|
-- the principal who minted it. Spine (kernel-written), shared with the DO adapter from the kernel.
|
|
359
359
|
${DOWNLOAD_LINK_DDL}
|
|
360
|
+
-- #2996 (K-64): store proofs, a short-lived, single-use proof that an operation checked the key
|
|
361
|
+
-- of one store operation. Spine (kernel-written), shared with the other adapter from the kernel.
|
|
362
|
+
${STORE_PROOF_DDL}
|
|
360
363
|
-- #1686: where a copied scope's data came from, and the event id its own events start above.
|
|
361
364
|
-- Shared with the other adapter from @substrat-run/kernel; the column comments are there.
|
|
362
365
|
${COPY_ORIGIN_DDL}
|
|
@@ -1000,12 +1003,19 @@ export class SqliteScopeHost {
|
|
|
1000
1003
|
clock;
|
|
1001
1004
|
/** #3540: whether purge schedules are due by their rows (`SqliteScopeHostOptions.purgeDue`). */
|
|
1002
1005
|
purgeDueByEvent;
|
|
1006
|
+
/**
|
|
1007
|
+
* #3540: every registered schedule declared `due: 'event'`, by operation — what `ctx.scheduleDue`
|
|
1008
|
+
* may name, and the operations whose every run clears their date in its own transaction.
|
|
1009
|
+
*/
|
|
1010
|
+
dueSchedules = new Map();
|
|
1003
1011
|
versionId;
|
|
1004
1012
|
/** K-74: the broker each scope hands off to, or null (off). */
|
|
1005
1013
|
deliveryBroker;
|
|
1006
1014
|
brokerTelemetry;
|
|
1007
1015
|
/** K-74: each scope's handoff marks, a cache of what its broker holds (`DeliveryBroker.marks`). */
|
|
1008
1016
|
handoffMarks = new Map();
|
|
1017
|
+
/** #3639: the environment each scope last handed off to, so erasure reaches that broker after the rule moved. */
|
|
1018
|
+
handoffEnvironments = new Map();
|
|
1009
1019
|
/** A5: `deliveryHandoff`, and each scope's mode with its window start (in memory, as the marks are). */
|
|
1010
1020
|
deliveryHandoff;
|
|
1011
1021
|
deliveryModes = new Map();
|
|
@@ -1605,6 +1615,8 @@ export class SqliteScopeHost {
|
|
|
1605
1615
|
${MEMBERSHIP_FENCES_DDL}
|
|
1606
1616
|
${PEER_SWITCHES_DDL}
|
|
1607
1617
|
${SWITCH_OWED_DDL}
|
|
1618
|
+
-- K-63 (#3624): erasures owed to a master's dependents, kept until each door answers.
|
|
1619
|
+
${DEPENDENT_ERASURES_DDL}
|
|
1608
1620
|
CREATE TABLE IF NOT EXISTS _substrat_admin_log (
|
|
1609
1621
|
id TEXT PRIMARY KEY,
|
|
1610
1622
|
actor TEXT NOT NULL,
|
|
@@ -2159,6 +2171,8 @@ export class SqliteScopeHost {
|
|
|
2159
2171
|
peers: manifest.peers ?? [],
|
|
2160
2172
|
purgeOnlyKeys: purgeOnlyKeysOf(manifest.schedules ?? []),
|
|
2161
2173
|
});
|
|
2174
|
+
for (const [operation, schedule] of dueByEventSchedulesOf(manifest.schedules))
|
|
2175
|
+
this.dueSchedules.set(operation, schedule);
|
|
2162
2176
|
noteReservedKeys(this.reservedKeys, manifest);
|
|
2163
2177
|
noteDeclaredKeys(this.declaredKeys, manifest);
|
|
2164
2178
|
if (erasure)
|
|
@@ -2285,10 +2299,45 @@ export class SqliteScopeHost {
|
|
|
2285
2299
|
// Idempotency is on the scope_id (§3.3: provisioning is idempotent and
|
|
2286
2300
|
// journaled — safe to re-run), so an existing scope short-circuits before the
|
|
2287
2301
|
// slug check: re-provisioning does not collide with itself.
|
|
2288
|
-
const existingRow = this.directory.prepare('SELECT scope_type FROM scopes WHERE scope_id = ?').get(input.scopeId);
|
|
2302
|
+
const existingRow = this.directory.prepare('SELECT scope_type, parent_scope_id FROM scopes WHERE scope_id = ?').get(input.scopeId);
|
|
2289
2303
|
const existing = existingRow !== undefined;
|
|
2290
2304
|
// #2993: a declared type, and the one recorded if the scope exists. Refused before anything is written.
|
|
2291
|
-
|
|
2305
|
+
// Part 4: a module-less coordinator asked for another type of a vertical's scope judges it by
|
|
2306
|
+
// the types the vertical's deployed version declares; this host's own objects still run as an
|
|
2307
|
+
// untyped host's do (`scopeTypeOf`).
|
|
2308
|
+
const plan = !this.scopeTypePlan.declared && input.scopeType !== undefined && input.scopeType !== HOME_SCOPE_TYPE && record.vertical
|
|
2309
|
+
? this.verticalScopeTypePlan(record.vertical)
|
|
2310
|
+
: this.scopeTypePlan;
|
|
2311
|
+
const scopeType = provisionedScopeType(plan, input.scopeType, existingRow?.scope_type, input.scopeId);
|
|
2312
|
+
// #2995: the parent link, fixed at the first provision. A new child is held to its parent's declared
|
|
2313
|
+
// children, tenant, app, state and depth before its row is written. No await separates the check from
|
|
2314
|
+
// the INSERT below, so no archive of the parent can land between them.
|
|
2315
|
+
const namedParent = provisionedParent(input.parentScopeId, existing ? existingRow.parent_scope_id : undefined, input.scopeId);
|
|
2316
|
+
// #3625 (K-64): a new typed scope that names no parent is a child of its app's home scope, judged below as any
|
|
2317
|
+
// named parent is. On a host that declares its own types, as the Durable Object host does: a module-less
|
|
2318
|
+
// coordinator judging by a vertical's types names a link through provision-child, which tells the vertical.
|
|
2319
|
+
const parentScopeId = existing || namedParent !== null || !this.scopeTypePlan.declared
|
|
2320
|
+
? namedParent
|
|
2321
|
+
: homeParentOf(switchSqlOf(this.directory), input.tenantId, { vertical: record.vertical, type: scopeType, forkedFrom: record.forkedFrom });
|
|
2322
|
+
// #2995 (the owner's word on #3604's fourth question): a new scope of a type other than home has a parent.
|
|
2323
|
+
const parentless = existing ? null : parentlessScopeRefusal(scopeType, parentScopeId, record.forkedFrom, input.scopeId);
|
|
2324
|
+
if (parentless)
|
|
2325
|
+
throw parentless;
|
|
2326
|
+
if (!existing && parentScopeId !== null) {
|
|
2327
|
+
const parent = this.directory
|
|
2328
|
+
.prepare('SELECT tenant_id, status, vertical, scope_type, parent_scope_id, forked_from FROM scopes WHERE scope_id = ?')
|
|
2329
|
+
.get(parentScopeId);
|
|
2330
|
+
const refusal = childScopeRefusal(plan, parentScopeId, parent && {
|
|
2331
|
+
tenantId: parent.tenant_id,
|
|
2332
|
+
status: parent.status,
|
|
2333
|
+
vertical: parent.vertical,
|
|
2334
|
+
type: parent.scope_type ?? HOME_SCOPE_TYPE,
|
|
2335
|
+
parentScopeId: parent.parent_scope_id,
|
|
2336
|
+
forkedFrom: parent.forked_from,
|
|
2337
|
+
}, { tenantId: input.tenantId, vertical: record.vertical, type: scopeType });
|
|
2338
|
+
if (refusal)
|
|
2339
|
+
throw refusal;
|
|
2340
|
+
}
|
|
2292
2341
|
if (!existing) {
|
|
2293
2342
|
// The `scopes_tenant_slug` UNIQUE index makes this fail closed either way;
|
|
2294
2343
|
// checking first is what turns a SQLITE_CONSTRAINT into a sentence naming
|
|
@@ -2303,6 +2352,19 @@ export class SqliteScopeHost {
|
|
|
2303
2352
|
throw substratError('conflict', `scope slug '${record.slug}' already taken under tenant ${input.tenantId} ` +
|
|
2304
2353
|
`by ${slugOwner.scope_id} (slugs are unique within a tenant)`);
|
|
2305
2354
|
}
|
|
2355
|
+
// #3625 (K-64): one home scope per (tenant, app, environment). A second install of the app is
|
|
2356
|
+
// refused; a sibling, a copy, a preview and a child are not installs. No await separates this
|
|
2357
|
+
// read from the INSERT below.
|
|
2358
|
+
const secondHome = secondHomeRefusal(switchSqlOf(this.directory), input.tenantId, input.scopeId, {
|
|
2359
|
+
vertical: record.vertical,
|
|
2360
|
+
type: scopeType,
|
|
2361
|
+
parentScopeId,
|
|
2362
|
+
forkedFrom: record.forkedFrom,
|
|
2363
|
+
kind: record.kind,
|
|
2364
|
+
install: input.install,
|
|
2365
|
+
});
|
|
2366
|
+
if (secondHome)
|
|
2367
|
+
throw secondHome;
|
|
2306
2368
|
this.directory
|
|
2307
2369
|
.prepare(`INSERT INTO scopes
|
|
2308
2370
|
(scope_id, tenant_id, parent_scope_id, scope_type, slug, kind, name, vertical,
|
|
@@ -2317,9 +2379,9 @@ export class SqliteScopeHost {
|
|
|
2317
2379
|
-- inheriting serving_ref would route it to the prod serving script instead
|
|
2318
2380
|
-- (COALESCE(s.serving_ref, vv.deployment_ref)). A null slug matches no row,
|
|
2319
2381
|
-- so the sub-select is NULL and routing falls through to the bound version.
|
|
2320
|
-
VALUES (?, ?,
|
|
2382
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
|
|
2321
2383
|
(SELECT serving_ref FROM verticals WHERE slug = ?), ?)`)
|
|
2322
|
-
.run(input.scopeId, input.tenantId,
|
|
2384
|
+
.run(input.scopeId, input.tenantId, parentScopeId,
|
|
2323
2385
|
// NULL for 'home', the reading every row from before scope types has, so a host that
|
|
2324
2386
|
// declares no types writes exactly the row it always did.
|
|
2325
2387
|
scopeType === HOME_SCOPE_TYPE ? null : scopeType, record.slug, record.kind, record.name, record.vertical, record.storageShape, record.jurisdiction, record.forkedFrom, record.forkedAt, record.expiresAt, record.kind === 'preview' ? null : record.vertical, new Date().toISOString());
|
|
@@ -2367,7 +2429,12 @@ export class SqliteScopeHost {
|
|
|
2367
2429
|
if (!existing) {
|
|
2368
2430
|
this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null,
|
|
2369
2431
|
// #2993: a typed scope's audit row names its type; a home scope's reads as it always did.
|
|
2370
|
-
|
|
2432
|
+
// #2995: a child's names its parent.
|
|
2433
|
+
{
|
|
2434
|
+
...record,
|
|
2435
|
+
...(scopeType === HOME_SCOPE_TYPE ? {} : { scopeType }),
|
|
2436
|
+
...(parentScopeId === null ? {} : { parentScopeId }),
|
|
2437
|
+
});
|
|
2371
2438
|
}
|
|
2372
2439
|
}
|
|
2373
2440
|
/**
|
|
@@ -3040,6 +3107,11 @@ export class SqliteScopeHost {
|
|
|
3040
3107
|
* host, made at once, so its seats are the ones that scope holds now (K-55).
|
|
3041
3108
|
*/
|
|
3042
3109
|
async importScopeFrom(actor, input, dump, judge) {
|
|
3110
|
+
// #2995: a copy carries no parent link. A link is written by provision-child alone, so a copy of a
|
|
3111
|
+
// child is a scope of its type with no parent, and nothing reaches it through the source's parent.
|
|
3112
|
+
if (input.parentScopeId !== undefined) {
|
|
3113
|
+
throw substratError('validation_failed', 'a copy carries no parent link: a child is provisioned through provision-child only');
|
|
3114
|
+
}
|
|
3043
3115
|
this.refuseUnusableScopeStores(dump.stores, input.vertical ?? null);
|
|
3044
3116
|
if (judge)
|
|
3045
3117
|
this.refuseDumpRoles(input.tenantId, dump);
|
|
@@ -3060,8 +3132,12 @@ export class SqliteScopeHost {
|
|
|
3060
3132
|
// is the dump, not whatever the local module set would have built. Provenance is
|
|
3061
3133
|
// stamped from the dump unless the caller already set it (§3: a fork always
|
|
3062
3134
|
// records where it came from).
|
|
3135
|
+
// #2993 part 3: a copy is a scope of its source's type — the type names the tables the dump
|
|
3136
|
+
// carries. The caller's type when it names one, else the source's, when this directory holds it.
|
|
3137
|
+
const copiedType = input.scopeType ?? this.recordedScopeType(dump.scopeId);
|
|
3063
3138
|
await this.provisionScope(actor, {
|
|
3064
3139
|
...input,
|
|
3140
|
+
...(copiedType === undefined ? {} : { scopeType: copiedType }),
|
|
3065
3141
|
forkedFrom: input.forkedFrom ?? dump.scopeId,
|
|
3066
3142
|
forkedAt: input.forkedAt ?? dump.capturedAt,
|
|
3067
3143
|
});
|
|
@@ -3365,11 +3441,41 @@ export class SqliteScopeHost {
|
|
|
3365
3441
|
? Object.freeze({ ...parsedDelegation, via: peerCallerAt(this.peerDeclarations(), parsedDelegation.via) })
|
|
3366
3442
|
: parsedDelegation;
|
|
3367
3443
|
const row = this.directory
|
|
3368
|
-
.prepare('SELECT tenant_id, status FROM scopes WHERE scope_id = ?')
|
|
3444
|
+
.prepare('SELECT tenant_id, status, parent_scope_id FROM scopes WHERE scope_id = ?')
|
|
3369
3445
|
.get(scopeId);
|
|
3370
3446
|
if (!row || row.tenant_id !== tenantId) {
|
|
3371
3447
|
throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
|
|
3372
3448
|
}
|
|
3449
|
+
// #2995: a child whose type accepts its parent only is not reached by a direct request.
|
|
3450
|
+
const direct = directAccessRefusal(this.scopeTypePlan, this.scopeTypeOf(scopeId), row.parent_scope_id, scopeId);
|
|
3451
|
+
if (direct)
|
|
3452
|
+
throw direct;
|
|
3453
|
+
return this.personDoor(principal, tenantId, scopeId, row.status, options, delegation);
|
|
3454
|
+
}
|
|
3455
|
+
/**
|
|
3456
|
+
* `ScopeHost.getChildScope` (#2995): the person's stub on a child, for host code of its parent. The
|
|
3457
|
+
* link, the child's type and the parent's state are checked first (`childDoorRefusal`); then the
|
|
3458
|
+
* person's door runs as `getScope` runs it, with every check in the child the person's own.
|
|
3459
|
+
*/
|
|
3460
|
+
async getChildScope(caller, tenantId, scopeId, options) {
|
|
3461
|
+
if (caller?.actor?.kind !== 'person') {
|
|
3462
|
+
throw substratError('validation_failed', 'a call into a child acts for a person: the app acting as itself is not built (#2995)');
|
|
3463
|
+
}
|
|
3464
|
+
const parsedDelegation = parseScopeDelegation(options?.delegation);
|
|
3465
|
+
const delegation = parsedDelegation?.via
|
|
3466
|
+
? Object.freeze({ ...parsedDelegation, via: peerCallerAt(this.peerDeclarations(), parsedDelegation.via) })
|
|
3467
|
+
: parsedDelegation;
|
|
3468
|
+
const read = this.directory.prepare('SELECT tenant_id, status, parent_scope_id FROM scopes WHERE scope_id = ?');
|
|
3469
|
+
const child = read.get(scopeId);
|
|
3470
|
+
const parent = read.get(caller.parentScopeId);
|
|
3471
|
+
const refusal = childDoorRefusal(this.scopeTypePlan, tenantId, caller.parentScopeId, scopeId, child && { tenantId: child.tenant_id, type: this.scopeTypeOf(scopeId), parentScopeId: child.parent_scope_id }, parent && { tenantId: parent.tenant_id, status: parent.status });
|
|
3472
|
+
if (refusal)
|
|
3473
|
+
throw refusal;
|
|
3474
|
+
return this.personDoor(caller.actor.principal, tenantId, scopeId, child.status, options, delegation);
|
|
3475
|
+
}
|
|
3476
|
+
/** The person's door past the directory pair and the reach check: lifecycle gates, migrations, the stub. */
|
|
3477
|
+
async personDoor(principal, tenantId, scopeId, status, options, delegation) {
|
|
3478
|
+
const row = { status };
|
|
3373
3479
|
// Lifecycle gates (control-plane.md §4.1/§4.2), all the K-3 fail-closed path.
|
|
3374
3480
|
// The tenant record is mandatory: every scope has a tenant with a status
|
|
3375
3481
|
// (provisioning enforces it), so a missing one is corruption, not a legacy
|
|
@@ -3419,11 +3525,18 @@ export class SqliteScopeHost {
|
|
|
3419
3525
|
throw substratError('not_found', `no scope store is bound for '${binding}'`);
|
|
3420
3526
|
}
|
|
3421
3527
|
await this.scopeStoreLifecycle.start();
|
|
3528
|
+
const rt = this.runtime(tenantId, scopeId);
|
|
3422
3529
|
return {
|
|
3423
3530
|
tenantId,
|
|
3424
3531
|
scopeId,
|
|
3425
3532
|
subjectKind: 'principal',
|
|
3426
|
-
|
|
3533
|
+
// #2996 (K-64): the proof is spent on the scope's own queue, then the runner is called.
|
|
3534
|
+
invoke: proofCheckedStoreInvoke({
|
|
3535
|
+
binding,
|
|
3536
|
+
redeem: (secret, operation) => rt.actor.enqueue(() => redeemStoreProof({ sql: spineSql(rt.db), now: this.clock() }, secret, { binding, operation, principal })),
|
|
3537
|
+
send: (request) => runner.invoke({ tenantId, vertical, scopeId, binding }, request),
|
|
3538
|
+
onStoreCall: options?.onStoreCall,
|
|
3539
|
+
}),
|
|
3427
3540
|
};
|
|
3428
3541
|
}
|
|
3429
3542
|
/** The scope's vertical when it has one. No vertical means this host has no store to touch. */
|
|
@@ -3956,6 +4069,30 @@ export class SqliteScopeHost {
|
|
|
3956
4069
|
return result;
|
|
3957
4070
|
});
|
|
3958
4071
|
}
|
|
4072
|
+
/**
|
|
4073
|
+
* #2993 part 4: a vertical's scope types, as the version a new scope of it would run declares
|
|
4074
|
+
* them: the version it serves in place, else the one its `prod` channel names. A vertical with no
|
|
4075
|
+
* such version, or one that declares no types, has the one `home` type.
|
|
4076
|
+
*/
|
|
4077
|
+
verticalScopeTypePlan(slug) {
|
|
4078
|
+
const serving = this.directory.prepare('SELECT serving_version_id FROM verticals WHERE slug = ?').get(slug);
|
|
4079
|
+
const prod = this.directory
|
|
4080
|
+
.prepare("SELECT version_id FROM vertical_channels WHERE vertical_slug = ? AND channel = 'prod'")
|
|
4081
|
+
.get(slug);
|
|
4082
|
+
const versionId = serving?.serving_version_id ?? prod?.version_id;
|
|
4083
|
+
return scopeTypePlanOfManifest(versionId ? this.manifestJsonOf(versionId, slug) : undefined);
|
|
4084
|
+
}
|
|
4085
|
+
/**
|
|
4086
|
+
* #2993 part 4: the types other than `home` the vertical's unreaped scopes hold, each once: what
|
|
4087
|
+
* a promote judges the incoming version's declared types against. K-65 (#3539): with `servingRef`,
|
|
4088
|
+
* only the scopes on that script, which is all a release into an earlier major reaches.
|
|
4089
|
+
*/
|
|
4090
|
+
scopeTypesHeldBy(vertical, servingRef) {
|
|
4091
|
+
const onScript = servingRef === undefined ? '' : ' AND serving_ref = ?';
|
|
4092
|
+
return this.directory
|
|
4093
|
+
.prepare(`SELECT DISTINCT scope_type FROM scopes WHERE vertical = ?${onScript} AND scope_type IS NOT NULL AND status <> 'reaped' ORDER BY scope_type`)
|
|
4094
|
+
.all(...(servingRef === undefined ? [vertical] : [vertical, servingRef])).map((r) => r.scope_type);
|
|
4095
|
+
}
|
|
3959
4096
|
/**
|
|
3960
4097
|
* A stored version's manifest, unaudited: the platform reading its own code metadata (#1705).
|
|
3961
4098
|
* `undefined` when the registry has no such version (under `slug`, when one is named).
|
|
@@ -4284,6 +4421,8 @@ export class SqliteScopeHost {
|
|
|
4284
4421
|
const rt = await this.openActiveScope(tenantId, scopeId);
|
|
4285
4422
|
const subject = asPrincipal(principalId.parse(principal));
|
|
4286
4423
|
return rt.actor.enqueue(() => {
|
|
4424
|
+
// #2993 part 3: a role of another scope type does not exist here.
|
|
4425
|
+
this.refuseRoleOutsideType(scopeId, roleKey);
|
|
4287
4426
|
// #2430: the answer a person's door would give — a role carrying a reserved key is refused.
|
|
4288
4427
|
this.refuseReservedRole(tenantId, roleKey, 'person');
|
|
4289
4428
|
return this.assignmentBound(subject, tenantId, scopeId, roleKey);
|
|
@@ -4294,6 +4433,7 @@ export class SqliteScopeHost {
|
|
|
4294
4433
|
const subject = asPrincipal(principalId.parse(caller));
|
|
4295
4434
|
const target = principalId.parse(assignee);
|
|
4296
4435
|
return rt.actor.turn(async () => {
|
|
4436
|
+
this.refuseRoleOutsideType(scopeId, roleKey); // #2993 part 3
|
|
4297
4437
|
// #2430: read in the same serialized task as the bound and the grant.
|
|
4298
4438
|
this.refuseReservedRole(tenantId, roleKey, 'person');
|
|
4299
4439
|
const bound = await this.assignmentBound(subject, tenantId, scopeId, roleKey);
|
|
@@ -4313,6 +4453,7 @@ export class SqliteScopeHost {
|
|
|
4313
4453
|
const answer = await rt.actor.turn(() => {
|
|
4314
4454
|
// #2430: the role moved TO is conferred by a person; the one moved from is only taken back.
|
|
4315
4455
|
// Read in the same serialized task as the bound and the write.
|
|
4456
|
+
this.refuseRoleOutsideType(scopeId, to); // #2993 part 3
|
|
4316
4457
|
this.refuseReservedRole(tenantId, to, 'person');
|
|
4317
4458
|
return changeScopeRole(switchSqlOf(rt.db), scopeId, target, from, to, this.clock(), this.roleBound(caller, tenantId, scopeId), (run) => rt.db.transaction(run)());
|
|
4318
4459
|
});
|
|
@@ -4465,6 +4606,16 @@ export class SqliteScopeHost {
|
|
|
4465
4606
|
if (refusal)
|
|
4466
4607
|
throw substratError('forbidden', refusal);
|
|
4467
4608
|
}
|
|
4609
|
+
/**
|
|
4610
|
+
* #2993 part 3: refuse seating `roleKey` at a scope whose type does not hold it
|
|
4611
|
+
* (`scopeTypeRoleRefusal`). Nothing is refused on a host with no declared types, or for a role no
|
|
4612
|
+
* type names.
|
|
4613
|
+
*/
|
|
4614
|
+
refuseRoleOutsideType(scopeId, roleKey) {
|
|
4615
|
+
const refusal = scopeTypeRoleRefusal(this.scopeTypePlan, this.scopeTypeOf(scopeId), roleKey);
|
|
4616
|
+
if (refusal)
|
|
4617
|
+
throw substratError('forbidden', refusal);
|
|
4618
|
+
}
|
|
4468
4619
|
/**
|
|
4469
4620
|
* #2447: refuse defining `role` for `tenantId` (`reservedRoleDefinitionRefusal`): against the keys
|
|
4470
4621
|
* the modules registered or listed here reserve and declare, and the tenant's other roles.
|
|
@@ -4816,7 +4967,7 @@ export class SqliteScopeHost {
|
|
|
4816
4967
|
const switched = systemScheduleState(switchSqlOf(rt.db), moduleId, nowIso);
|
|
4817
4968
|
const lastRuns = new Map();
|
|
4818
4969
|
if (switched !== 'on')
|
|
4819
|
-
return { state: switched, lastRuns, purgeDue: new Map() };
|
|
4970
|
+
return { state: switched, lastRuns, purgeDue: new Map(), eventDue: new Map() };
|
|
4820
4971
|
const read = rt.db.prepare(`SELECT last_run_at FROM _substrat_schedule_state
|
|
4821
4972
|
WHERE kind = 'schedule' AND schedule_op = ?`);
|
|
4822
4973
|
for (const schedule of mod.schedules) {
|
|
@@ -4833,7 +4984,20 @@ export class SqliteScopeHost {
|
|
|
4833
4984
|
purgeDue.set(schedule.operation, purgeDueAt(spineSql(rt.db), this.statePlans, [purgeDueScheduleOf(schedule)], Date.parse(nowIso)));
|
|
4834
4985
|
}
|
|
4835
4986
|
}
|
|
4836
|
-
|
|
4987
|
+
// #3540: under the same switch, when each `due: 'event'` schedule that has run under that form
|
|
4988
|
+
// is next due (null: nothing is). One that has not is absent, and its cadence decides.
|
|
4989
|
+
const eventDue = new Map();
|
|
4990
|
+
if (this.purgeDueByEvent) {
|
|
4991
|
+
for (const schedule of mod.schedules) {
|
|
4992
|
+
const due = this.dueSchedules.get(schedule.operation);
|
|
4993
|
+
if (!due || schedule.purge)
|
|
4994
|
+
continue;
|
|
4995
|
+
const row = readScheduleDue(spineSql(rt.db), due);
|
|
4996
|
+
if (row.established)
|
|
4997
|
+
eventDue.set(schedule.operation, row.dueAt);
|
|
4998
|
+
}
|
|
4999
|
+
}
|
|
5000
|
+
return { state: switched, lastRuns, purgeDue, eventDue };
|
|
4837
5001
|
});
|
|
4838
5002
|
const state = gate.state;
|
|
4839
5003
|
if (state === 'ungranted')
|
|
@@ -4870,14 +5034,24 @@ export class SqliteScopeHost {
|
|
|
4870
5034
|
},
|
|
4871
5035
|
};
|
|
4872
5036
|
for (const schedule of mod.schedules) {
|
|
4873
|
-
// #3540: the scope's alarm asks for its purges only (the Durable Object's `purgeAlarm`)
|
|
5037
|
+
// #3540: the scope's alarm asks for its purges only (the Durable Object's `purgeAlarm`), or for
|
|
5038
|
+
// its purges and the `due: 'event'` schedules that have run under that form (`dueAlarm`).
|
|
4874
5039
|
if (tick?.purgeAlarm && !schedule.purge)
|
|
4875
5040
|
continue;
|
|
5041
|
+
if (tick?.dueAlarm && !schedule.purge && !gate.eventDue.has(schedule.operation))
|
|
5042
|
+
continue;
|
|
4876
5043
|
const lastRunAt = gate.lastRuns.get(schedule.operation) ?? null;
|
|
4877
5044
|
const lastRun = lastRunAt ? Date.parse(lastRunAt) : null;
|
|
4878
5045
|
// #3540: a purge due by event is due when its earliest row is (null: nothing binned is ever due),
|
|
4879
|
-
// and its lateness is measured from that row's date rather than from the cadence.
|
|
4880
|
-
|
|
5046
|
+
// and its lateness is measured from that row's date rather than from the cadence. A `due: 'event'`
|
|
5047
|
+
// schedule that has run under that form is due when the date its work wrote is.
|
|
5048
|
+
const byRows = schedule.purge
|
|
5049
|
+
? this.purgeDueByEvent
|
|
5050
|
+
? (gate.purgeDue.get(schedule.operation) ?? null)
|
|
5051
|
+
: undefined
|
|
5052
|
+
: gate.eventDue.has(schedule.operation)
|
|
5053
|
+
? (gate.eventDue.get(schedule.operation) ?? null)
|
|
5054
|
+
: undefined;
|
|
4881
5055
|
const dueAt = byRows !== undefined ? (byRows ?? Infinity) : lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000;
|
|
4882
5056
|
if (now < dueAt) {
|
|
4883
5057
|
report.skipped += 1;
|
|
@@ -4985,16 +5159,32 @@ export class SqliteScopeHost {
|
|
|
4985
5159
|
* harness that wants the hosted shape sleeps until this instant and runs the pass.
|
|
4986
5160
|
*/
|
|
4987
5161
|
async purgeAlarmAt(tenantId, scopeId) {
|
|
5162
|
+
return this.alarmAt(tenantId, scopeId, false);
|
|
5163
|
+
}
|
|
5164
|
+
/**
|
|
5165
|
+
* #3540: the instant this scope's alarm would stand at for everything due by event — its purges
|
|
5166
|
+
* (`purgeAlarmAt`) and its `due: 'event'` schedules that have run under that form — or null when
|
|
5167
|
+
* nothing is, or nothing is due by event on this host (`purgeDue`). The pass runs them when due.
|
|
5168
|
+
*/
|
|
5169
|
+
async dueAlarmAt(tenantId, scopeId) {
|
|
5170
|
+
return this.alarmAt(tenantId, scopeId, true);
|
|
5171
|
+
}
|
|
5172
|
+
async alarmAt(tenantId, scopeId, withSchedules) {
|
|
4988
5173
|
if (!this.purgeDueByEvent)
|
|
4989
5174
|
return null;
|
|
4990
5175
|
if (this.scopeWorkRefusal(tenantId, scopeId))
|
|
4991
5176
|
return null;
|
|
4992
5177
|
const schedules = [...this.modules.values()].flatMap((m) => m.schedules.filter((s) => s.purge).map(purgeDueScheduleOf));
|
|
4993
|
-
|
|
5178
|
+
const due = withSchedules ? [...this.dueSchedules.values()] : [];
|
|
5179
|
+
if (schedules.length === 0 && due.length === 0)
|
|
4994
5180
|
return null;
|
|
4995
5181
|
const rt = this.runtime(tenantId, scopeId);
|
|
4996
5182
|
await this.applyPendingMigrations(rt);
|
|
4997
|
-
const at = await rt.actor.turn(() =>
|
|
5183
|
+
const at = await rt.actor.turn(() => {
|
|
5184
|
+
const purges = schedules.length > 0 ? purgeDueAt(spineSql(rt.db), this.statePlans, schedules, Date.parse(this.clock())) : null;
|
|
5185
|
+
const events = scheduleDueAt(spineSql(rt.db), due);
|
|
5186
|
+
return purges === null ? events : events === null ? purges : Math.min(purges, events);
|
|
5187
|
+
});
|
|
4998
5188
|
return at === null ? null : new Date(at).toISOString();
|
|
4999
5189
|
}
|
|
5000
5190
|
/**
|
|
@@ -5356,6 +5546,11 @@ export class SqliteScopeHost {
|
|
|
5356
5546
|
// here, before the guards and the handler — the declared key first, so a caller
|
|
5357
5547
|
// without it meets the same `forbidden` an active entity gives (`entity-trash.ts`).
|
|
5358
5548
|
await refuseTrashedTarget({ sql: spineSql(rt.db), plans: this.statePlans, check: ctx.check, now: ctx.now() }, operation, target, parsed, purging ? { gate: this.purgeGateFacts(rt, subject.id, tenantId, scopeId) } : undefined);
|
|
5549
|
+
// #3540: a run of a due-by-event schedule's operation clears its date first, in this
|
|
5550
|
+
// transaction, and the handler writes the next one for what it leaves. A throw rolls the
|
|
5551
|
+
// clearing back with the rest, so the date it was due by is still there for the next try.
|
|
5552
|
+
if (this.dueSchedules.has(operation))
|
|
5553
|
+
consumeScheduleDue(spineSql(rt.db), operation);
|
|
5359
5554
|
// Manifest guards (K-17): pre-conditions, inside the operation's own
|
|
5360
5555
|
// transaction, before the handler. A throw here blocks the operation
|
|
5361
5556
|
// and rolls back exactly like a handler throw — fail closed.
|
|
@@ -6197,13 +6392,19 @@ export class SqliteScopeHost {
|
|
|
6197
6392
|
const mode = this.deliveryModes.get(key);
|
|
6198
6393
|
if (this.deliveryHandoff === 'by-mode' && !mode)
|
|
6199
6394
|
return;
|
|
6395
|
+
// #3639 (D-83): to the broker of the scope's environment, or to none: a preview or a fork, and an
|
|
6396
|
+
// environment nobody gave connections of its own, hand off nothing, as a hosted one is told `off`.
|
|
6397
|
+
const environment = deliveryEnvironmentIn(switchSqlOf(this.directory), rt.tenantId, rt.scopeId);
|
|
6398
|
+
if (environment === null)
|
|
6399
|
+
return;
|
|
6400
|
+
this.handoffEnvironments.set(key, environment);
|
|
6200
6401
|
const options = mode
|
|
6201
6402
|
? { mode: mode.mode, ...(mode.startPending ? { start: { ...ids, after: mode.start } } : {}) }
|
|
6202
6403
|
: {};
|
|
6203
6404
|
/** #3474: the round now with the broker, so a throw reports what it tried. */
|
|
6204
6405
|
let inFlight = null;
|
|
6205
6406
|
try {
|
|
6206
|
-
const broker = this.deliveryBroker(ids);
|
|
6407
|
+
const broker = this.deliveryBroker({ ...ids, environment });
|
|
6207
6408
|
let marks = this.handoffMarks.get(key) ?? (await broker.marks(rt.tenantId, rt.scopeId));
|
|
6208
6409
|
// A backlog larger than one batch follows in the next round; bounded, so a commit never spins.
|
|
6209
6410
|
for (let round = 0; round < 20; round++) {
|
|
@@ -6225,7 +6426,7 @@ export class SqliteScopeHost {
|
|
|
6225
6426
|
delete options.start;
|
|
6226
6427
|
}
|
|
6227
6428
|
const next = advanceMarks(marks, sent, answer);
|
|
6228
|
-
this.reportHandoffRound(rt, inFlight, handoffOutcome(sent, answer));
|
|
6429
|
+
this.reportHandoffRound(rt, inFlight, handoffOutcome(sent, answer), environment);
|
|
6229
6430
|
inFlight = null;
|
|
6230
6431
|
// An answer that acknowledges nothing new: stop; the next commit or `retryHandoffs` tries again.
|
|
6231
6432
|
if (next.event === marks.event && next.intent === marks.intent)
|
|
@@ -6237,19 +6438,33 @@ export class SqliteScopeHost {
|
|
|
6237
6438
|
}
|
|
6238
6439
|
catch (err) {
|
|
6239
6440
|
if (inFlight)
|
|
6240
|
-
this.reportHandoffRound(rt, inFlight, 'failed');
|
|
6441
|
+
this.reportHandoffRound(rt, inFlight, 'failed', environment);
|
|
6241
6442
|
console.error('substrat: delivery handoff failed; the next commit retries it', err);
|
|
6242
6443
|
}
|
|
6243
6444
|
}
|
|
6445
|
+
/**
|
|
6446
|
+
* #3639: the broker a scope's messages went to: the environment the directory says the scope belongs
|
|
6447
|
+
* to (`environmentOfScopeIn`, which does not follow its effects, so it outlives a restart and an
|
|
6448
|
+
* environment taken back to none), else the one this host last handed off to, else production's (a
|
|
6449
|
+
* scope that never handed off holds nothing in any). Only with `deliveryBroker` given.
|
|
6450
|
+
*/
|
|
6451
|
+
brokerOfScope(tenantId, scopeId) {
|
|
6452
|
+
const environment = environmentOfScopeIn(switchSqlOf(this.directory), tenantId, scopeId) ??
|
|
6453
|
+
this.handoffEnvironments.get(`${tenantId}/${scopeId}`) ??
|
|
6454
|
+
PRODUCTION_ENVIRONMENT;
|
|
6455
|
+
return this.deliveryBroker({ tenantId, scopeId, environment });
|
|
6456
|
+
}
|
|
6244
6457
|
/** #3474: one point per handoff round, when `brokerTelemetry` is given. */
|
|
6245
|
-
reportHandoffRound(rt, round, outcome
|
|
6458
|
+
reportHandoffRound(rt, round, outcome,
|
|
6459
|
+
/** #3639: the environment whose broker the round went to; production's names none. */
|
|
6460
|
+
environment) {
|
|
6246
6461
|
const t = this.brokerTelemetry;
|
|
6247
6462
|
if (!t)
|
|
6248
6463
|
return;
|
|
6249
6464
|
const ids = { tenantId: rt.tenantId, scopeId: rt.scopeId };
|
|
6250
6465
|
// Telemetry never fails the handoff it follows: the harness's `appOf` may throw.
|
|
6251
6466
|
try {
|
|
6252
|
-
reportHandoff(t.sink, { ...ids, app: t.appOf(ids) }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
|
|
6467
|
+
reportHandoff(t.sink, { ...ids, app: t.appOf(ids), ...(environment === PRODUCTION_ENVIRONMENT ? {} : { environment }) }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
|
|
6253
6468
|
}
|
|
6254
6469
|
catch (err) {
|
|
6255
6470
|
console.error('substrat: delivery telemetry failed; the handoff continues', err);
|
|
@@ -7001,6 +7216,8 @@ export class SqliteScopeHost {
|
|
|
7001
7216
|
...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
|
|
7002
7217
|
archivedAt: r.archived_at ?? null,
|
|
7003
7218
|
archivedFromStatus: (r.archived_from_status ?? null),
|
|
7219
|
+
// #2993: a typed scope names its type; a home scope's record (NULL) is unchanged.
|
|
7220
|
+
...(r.scope_type ? { scopeType: r.scope_type } : {}),
|
|
7004
7221
|
createdAt: r.created_at,
|
|
7005
7222
|
});
|
|
7006
7223
|
// The directory rows `listScopes` and `listScopesReadable` map, filtered and paged alike.
|
|
@@ -7025,6 +7242,10 @@ export class SqliteScopeHost {
|
|
|
7025
7242
|
where.push('vertical = ?');
|
|
7026
7243
|
params.push(filter.vertical);
|
|
7027
7244
|
}
|
|
7245
|
+
if (filter?.parentScopeId) {
|
|
7246
|
+
where.push('parent_scope_id = ?');
|
|
7247
|
+
params.push(filter.parentScopeId);
|
|
7248
|
+
}
|
|
7028
7249
|
const tail = keysetTail(where, params, 'scope_id', filter);
|
|
7029
7250
|
const sql = 'SELECT * FROM scopes' + (where.length ? ` WHERE ${where.join(' AND ')}` : '') + tail;
|
|
7030
7251
|
return this.directory.prepare(sql).all(...params);
|
|
@@ -7061,7 +7282,7 @@ export class SqliteScopeHost {
|
|
|
7061
7282
|
// describes what the transition DID, not the state it left.
|
|
7062
7283
|
afterExtra) => {
|
|
7063
7284
|
const row = this.directory
|
|
7064
|
-
.prepare('SELECT tenant_id, status, vertical, stores_fenced_at FROM scopes WHERE scope_id = ?')
|
|
7285
|
+
.prepare('SELECT tenant_id, status, vertical, stores_fenced_at, parent_scope_id FROM scopes WHERE scope_id = ?')
|
|
7065
7286
|
.get(scopeId);
|
|
7066
7287
|
if (!row || row.tenant_id !== tenantId) {
|
|
7067
7288
|
throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
|
|
@@ -7069,6 +7290,14 @@ export class SqliteScopeHost {
|
|
|
7069
7290
|
if (to === 'active' && row.stores_fenced_at !== null) {
|
|
7070
7291
|
throw substratError('conflict', storesFencedRefusal(scopeId));
|
|
7071
7292
|
}
|
|
7293
|
+
// #2995: a child does not outlive its parent. Archiving a parent archives its children, and
|
|
7294
|
+
// none of them comes back (an unarchive, or a late activation) while the parent is archived.
|
|
7295
|
+
if (to === 'active' && row.parent_scope_id !== null) {
|
|
7296
|
+
const parent = this.directory.prepare('SELECT status FROM scopes WHERE scope_id = ?').get(row.parent_scope_id);
|
|
7297
|
+
if (!parent || parent.status === 'archived' || parent.status === 'reaped') {
|
|
7298
|
+
throw substratError('conflict', `scope ${scopeId} is a child of ${row.parent_scope_id}, which is ${parent?.status ?? 'gone'}: a child does not outlive its parent`);
|
|
7299
|
+
}
|
|
7300
|
+
}
|
|
7072
7301
|
if (!from.includes(row.status)) {
|
|
7073
7302
|
throw substratError('conflict', `illegal scope transition for ${action}: ${row.status} → ${to} ` +
|
|
7074
7303
|
`(allowed from: ${from.join('|')})`);
|
|
@@ -7109,6 +7338,57 @@ export class SqliteScopeHost {
|
|
|
7109
7338
|
this.recordAdmin(actor, action, { tenantId, scopeId, vertical: row.vertical }, { status: row.status }, { status: to, ...afterExtra });
|
|
7110
7339
|
})();
|
|
7111
7340
|
};
|
|
7341
|
+
// Reap an ARCHIVED scope's storage while keeping its directory row as a tombstone
|
|
7342
|
+
// (§4.4). Only `archived` may be reaped — an illegal source fails closed. The
|
|
7343
|
+
// STORAGE goes before the status flip (the ordering deleteSnapshot keeps): a crash
|
|
7344
|
+
// between leaves an `archived` row over an emptied file and re-running converges,
|
|
7345
|
+
// whereas flipping first would strand a live file under a `reaped` row reap never
|
|
7346
|
+
// revisits. Hostnames were released at archive and the row survives, so — unlike
|
|
7347
|
+
// deleteSnapshot — neither is touched here.
|
|
7348
|
+
const assertReapable = (tenantId, scopeId, opts) => {
|
|
7349
|
+
const rec = this.directory
|
|
7350
|
+
.prepare('SELECT tenant_id, status FROM scopes WHERE scope_id = ?')
|
|
7351
|
+
.get(scopeId);
|
|
7352
|
+
if (!rec || rec.tenant_id !== tenantId) {
|
|
7353
|
+
throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
|
|
7354
|
+
}
|
|
7355
|
+
if (rec.status !== 'archived') {
|
|
7356
|
+
throw substratError('conflict', `scope ${scopeId} is ${rec.status}, not archived — only an archived scope may be reaped`);
|
|
7357
|
+
}
|
|
7358
|
+
// A serving scope always holds ≥1 bound hostname; a truly-dead one has been
|
|
7359
|
+
// unbound. The dashboard delete path unbinds AT archive, but a bare console
|
|
7360
|
+
// `archiveScope` does not — so reap cannot ASSUME the release, it must verify it.
|
|
7361
|
+
// Refuse (fail closed) while any name still resolves here: unbinding first is a
|
|
7362
|
+
// visible, reversible step, and it is the wall that stops the irreversible wipe
|
|
7363
|
+
// from ever landing on an app that is still online (§4.4). `force` is the
|
|
7364
|
+
// deliberate-teardown bypass (tenant reap / retention sweep), where every name is
|
|
7365
|
+
// being released anyway; the interactive per-scope reap never sets it.
|
|
7366
|
+
const bound = opts?.force
|
|
7367
|
+
? undefined
|
|
7368
|
+
: this.directory
|
|
7369
|
+
.prepare('SELECT hostname FROM hostnames WHERE scope_id = ? LIMIT 1')
|
|
7370
|
+
.get(scopeId);
|
|
7371
|
+
if (bound) {
|
|
7372
|
+
throw substratError('conflict', `scope ${scopeId} still resolves hostname '${bound.hostname}' — ` +
|
|
7373
|
+
`unbind it before reaping (reap wipes storage and cannot be undone)`);
|
|
7374
|
+
}
|
|
7375
|
+
};
|
|
7376
|
+
const reapOne = async (actor, tenantId, scopeId, opts) => {
|
|
7377
|
+
assertReapable(tenantId, scopeId, opts);
|
|
7378
|
+
// The reader goes with the writer (#1624): an open handle on a removed file keeps
|
|
7379
|
+
// reading the unlinked bytes, which is the reaped data answering as if it were live.
|
|
7380
|
+
const rt = this.scopes.get(`${tenantId}/${scopeId}`);
|
|
7381
|
+
if (rt)
|
|
7382
|
+
this.closeRuntime(rt);
|
|
7383
|
+
await this.wipeScopeStores(tenantId, scopeId);
|
|
7384
|
+
rmSync(join(this.dir, `${tenantId}__${scopeId}.sqlite`), { force: true });
|
|
7385
|
+
// The recoverable copy the caller stored first (#493), named in the audit entry so
|
|
7386
|
+
// the trail answers "was there a backup" without correlating two timestamps.
|
|
7387
|
+
await transitionScope(actor, 'reapScope', tenantId, scopeId, ['archived'], 'reaped', {
|
|
7388
|
+
backupRef: opts?.backupRef ?? null,
|
|
7389
|
+
...(opts?.withParent ? { withParent: opts.withParent } : {}),
|
|
7390
|
+
});
|
|
7391
|
+
};
|
|
7112
7392
|
const writeTenantTuple = (tenantId, subject, relation, object, expiresAt) => this.directory
|
|
7113
7393
|
.prepare(`INSERT OR REPLACE INTO _substrat_tenant_tuples
|
|
7114
7394
|
(tenant_id, subject, relation, object, expires_at)
|
|
@@ -7524,6 +7804,10 @@ export class SqliteScopeHost {
|
|
|
7524
7804
|
// Before the write opens a scope's file; synchronous with a tenant node's unit, so no
|
|
7525
7805
|
// definition lands between the two.
|
|
7526
7806
|
this.refuseReservedRole(tenantId, assignment.roleKey, 'platform');
|
|
7807
|
+
// #2993 part 3: a scope-level seat in a role of another scope type is refused. A tenant-level
|
|
7808
|
+
// one names no scope, so no type: the role reaches the scopes whose type holds it.
|
|
7809
|
+
if (scopeId)
|
|
7810
|
+
this.refuseRoleOutsideType(scopeId, assignment.roleKey);
|
|
7527
7811
|
await auditedOnNode(assignment.node, () => {
|
|
7528
7812
|
if (scopeId)
|
|
7529
7813
|
writeScopeTuple(assignment.node, subject, `role:${assignment.roleKey}`, `scope:${scopeId}`);
|
|
@@ -8014,6 +8298,12 @@ export class SqliteScopeHost {
|
|
|
8014
8298
|
this.recordAccess(actor, 'peerBindings', { tenantId, scopeId: callerScopeId }, null, rows.length);
|
|
8015
8299
|
return rows.map((r) => ({ tenantId, callerScopeId, vertical: r.vertical, targetScopeId: r.target_scope_id, invalidated: r.invalidated === 1 }));
|
|
8016
8300
|
},
|
|
8301
|
+
// #3625 (K-64): the home scope of (tenant, app, environment). The rule is the kernel's (`home-scope.ts`).
|
|
8302
|
+
homeScopeOf: async (actor, tenantId, vertical, environment) => {
|
|
8303
|
+
const scopeId = homeScopeIn(switchSqlOf(this.directory), tenantId, vertical, environment);
|
|
8304
|
+
this.recordAccess(actor, 'homeScopeOf', { tenantId }, { vertical, environment: environment ?? 'prod' }, scopeId ? 1 : 0);
|
|
8305
|
+
return scopeId;
|
|
8306
|
+
},
|
|
8017
8307
|
// D-83 (#3530 step 3): an app's environments. The rule is the kernel's (`app-environments.ts`).
|
|
8018
8308
|
listEnvironments: async (actor, tenantId, vertical) => {
|
|
8019
8309
|
const rows = environmentsOf(switchSqlOf(this.directory), tenantId, vertical);
|
|
@@ -8034,6 +8324,33 @@ export class SqliteScopeHost {
|
|
|
8034
8324
|
}
|
|
8035
8325
|
return { removed: out.removed };
|
|
8036
8326
|
})(),
|
|
8327
|
+
claimEnvironmentServe: async (_actor, input, claim, leaseMs) => this.directory.transaction(() => {
|
|
8328
|
+
const now = Date.now();
|
|
8329
|
+
return claimEnvironmentServeIn(switchSqlOf(this.directory), input, claim, { now: new Date(now).toISOString(), until: new Date(now + leaseMs).toISOString() });
|
|
8330
|
+
})(),
|
|
8331
|
+
releaseEnvironmentServe: async (_actor, input, claim) => {
|
|
8332
|
+
releaseEnvironmentServeIn(switchSqlOf(this.directory), input, claim);
|
|
8333
|
+
},
|
|
8334
|
+
setEnvironmentServing: async (actor, input, next, expected, claim, acknowledge) => this.directory.transaction(() => {
|
|
8335
|
+
// #3638: judged against what this environment serves, in the write that moves it.
|
|
8336
|
+
const ack = acknowledge === undefined ? undefined : environmentServeAcknowledgement.parse(acknowledge);
|
|
8337
|
+
const out = setEnvironmentServingIn(switchSqlOf(this.directory), input, next, expected, claim, ack);
|
|
8338
|
+
if (!out.moved) {
|
|
8339
|
+
throw substratError('precondition_failed', `the environment '${input.name}' of '${input.vertical}' serves another record than the one this serve was diffed from: read it again`);
|
|
8340
|
+
}
|
|
8341
|
+
this.recordAdmin(actor, 'setEnvironmentServing', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, out.before ? { ref: out.before.ref, versionId: out.before.versionId } : null,
|
|
8342
|
+
// #3638: the acknowledgement is recorded with this environment's serve, as a promote's is with prod's.
|
|
8343
|
+
{ vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId, ...(ack ? { acknowledged: ack } : {}) });
|
|
8344
|
+
})(),
|
|
8345
|
+
// #3530 step 6: an environment given connections of its own, and the rule every connection door asks.
|
|
8346
|
+
setEnvironmentEffects: async (actor, input, effects) => this.directory.transaction(() => {
|
|
8347
|
+
const out = setEnvironmentEffectsIn(switchSqlOf(this.directory), input, effects);
|
|
8348
|
+
if (out.changed) {
|
|
8349
|
+
this.recordAdmin(actor, 'setEnvironmentEffects', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, { effects: out.before }, { vertical: input.vertical, scopeId: out.scopeId, effects });
|
|
8350
|
+
}
|
|
8351
|
+
return { changed: out.changed, before: out.before };
|
|
8352
|
+
})(),
|
|
8353
|
+
connectionReach: async (_actor, tenantId, scopeId) => connectionReachIn(switchSqlOf(this.directory), tenantId, scopeId),
|
|
8037
8354
|
setPeerBinding: async (_actor, tenantId, callerScopeId, vertical, targetScopeId) => this.directory.transaction(() => {
|
|
8038
8355
|
const caller = this.directory.prepare('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?').get(callerScopeId);
|
|
8039
8356
|
if (!caller || caller.tenant_id !== tenantId || caller.status !== 'active' || !isPrimaryScopeRow(caller)) {
|
|
@@ -8075,7 +8392,9 @@ export class SqliteScopeHost {
|
|
|
8075
8392
|
const r = this.directory
|
|
8076
8393
|
.prepare(`SELECT h.tenant_id, h.scope_id, h.vertical_slug, h.surface, h.region,
|
|
8077
8394
|
COALESCE(s.serving_ref, vv.deployment_ref) AS deployment_ref,
|
|
8078
|
-
|
|
8395
|
+
-- #3530 step 4: a scope on its environment's own script runs the version it is
|
|
8396
|
+
-- bound to, which is what that script was last served (\`ae\`, null otherwise).
|
|
8397
|
+
CASE WHEN s.serving_ref IS NOT NULL AND ae.serving_ref IS NULL
|
|
8079
8398
|
THEN json_extract(sv.manifest_json, '$.outbound')
|
|
8080
8399
|
ELSE json_extract(vv.manifest_json, '$.outbound') END AS outbound_json,
|
|
8081
8400
|
s.kind, s.forked_from,
|
|
@@ -8094,6 +8413,7 @@ export class SqliteScopeHost {
|
|
|
8094
8413
|
LEFT JOIN verticals vr ON vr.slug = s.vertical
|
|
8095
8414
|
-- K-65 (#3539 part 2): the version the scope's script runs, an earlier major's included.
|
|
8096
8415
|
LEFT JOIN vertical_versions sv ON sv.id = ${SCRIPT_SERVING_VERSION_SQL}
|
|
8416
|
+
${ENVIRONMENT_SCRIPT_JOIN_SQL}
|
|
8097
8417
|
WHERE h.hostname = ? AND h.status = 'active'
|
|
8098
8418
|
AND s.status = 'active' AND t.status = 'active'`)
|
|
8099
8419
|
.get(hostname);
|
|
@@ -8416,16 +8736,36 @@ export class SqliteScopeHost {
|
|
|
8416
8736
|
if (incoming.admission !== 'admitted') {
|
|
8417
8737
|
throw substratError('conflict', `version ${versionId} is ${incoming.admission}, not admitted — it cannot be promoted`);
|
|
8418
8738
|
}
|
|
8419
|
-
|
|
8420
|
-
|
|
8421
|
-
|
|
8739
|
+
// K-65 (#3539): a release that names an earlier major goes to that major's own script, and
|
|
8740
|
+
// every gate below is judged against the version that script runs, in place of the channel's.
|
|
8741
|
+
const target = options?.earlierMajor === undefined
|
|
8742
|
+
? null
|
|
8743
|
+
: (() => {
|
|
8744
|
+
if (channel !== 'prod')
|
|
8745
|
+
throw substratError('validation_failed', 'an earlier major is released on prod alone');
|
|
8746
|
+
const row = this.directory.prepare('SELECT earlier_majors FROM verticals WHERE slug = ?')
|
|
8747
|
+
.get(verticalSlug);
|
|
8748
|
+
return earlierMajorReleaseTarget({
|
|
8749
|
+
vertical: verticalSlug,
|
|
8750
|
+
earlierJson: row?.earlier_majors,
|
|
8751
|
+
major: options.earlierMajor,
|
|
8752
|
+
head: { version: incoming.version, deploymentRef: incoming.deploymentRef },
|
|
8753
|
+
servesMajors: options.servesMajors === true,
|
|
8754
|
+
});
|
|
8755
|
+
})();
|
|
8756
|
+
const current = target
|
|
8757
|
+
? { version_id: target.versionId }
|
|
8758
|
+
: this.directory
|
|
8759
|
+
.prepare('SELECT version_id FROM vertical_channels WHERE vertical_slug = ? AND channel = ?')
|
|
8760
|
+
.get(verticalSlug, channel);
|
|
8422
8761
|
const outgoing = current ? await readVersion(current.version_id) : undefined;
|
|
8423
8762
|
const ack = promotionAcknowledgement.parse(acknowledge ?? {});
|
|
8424
8763
|
// The owning tenant's live scopes a PRIVATE prod promote re-points — below for an embedded
|
|
8425
8764
|
// vertical, after the in-place serve for a dispatch-backed one (#321) — read before
|
|
8426
|
-
// anything moves so the #2178 gate can judge each one.
|
|
8765
|
+
// anything moves so the #2178 gate can judge each one. A release into an earlier major
|
|
8766
|
+
// re-points none: only the installs on that major's script run it.
|
|
8427
8767
|
const owning = channel === 'prod' ? readVertical(verticalSlug) : undefined;
|
|
8428
|
-
const owned = owning && owning.ownerTenant !== null && !owning.listed
|
|
8768
|
+
const owned = !target && owning && owning.ownerTenant !== null && !owning.listed
|
|
8429
8769
|
? this.directory
|
|
8430
8770
|
.prepare(`SELECT * FROM scopes
|
|
8431
8771
|
WHERE vertical = ? AND tenant_id = ? AND status = 'active' AND forked_from IS NULL AND kind != 'preview'`)
|
|
@@ -8435,7 +8775,9 @@ export class SqliteScopeHost {
|
|
|
8435
8775
|
// moves something from: the channel's version, the version served in place (a prod promote
|
|
8436
8776
|
// serves the incoming one next, and a failed serve leaves it behind the channel), and what each
|
|
8437
8777
|
// re-pointed scope RUNS (`runningVersionOf`: on the serving script, the served version).
|
|
8438
|
-
const served =
|
|
8778
|
+
const served = target
|
|
8779
|
+
? { ref: target.ref, versionId: target.versionId }
|
|
8780
|
+
: channel === 'prod' ? this.servingPointerOfVertical(verticalSlug) : null;
|
|
8439
8781
|
// And what each scope it moves last reconciled (`PROVISIONED_VERSIONS_SQL`).
|
|
8440
8782
|
this.assertNoStrandFrom([
|
|
8441
8783
|
outgoing?.id,
|
|
@@ -8455,6 +8797,10 @@ export class SqliteScopeHost {
|
|
|
8455
8797
|
: null;
|
|
8456
8798
|
if (breakingWithinMajor && owning?.listed)
|
|
8457
8799
|
throw breakingWithinMajorRefusal(breakingWithinMajor);
|
|
8800
|
+
// #2993 part 4: the incoming version declares every type the vertical's scopes hold. Ahead
|
|
8801
|
+
// of the acknowledgements, because none of them passes it.
|
|
8802
|
+
// K-65 (#3539): a release into an earlier major reaches the scopes on its script alone.
|
|
8803
|
+
assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug, target?.ref), this.manifestJsonOf(versionId, verticalSlug));
|
|
8458
8804
|
// #2333: the acknowledgements answer the review they were given against, or none at all.
|
|
8459
8805
|
const reviewed = (v) => ({
|
|
8460
8806
|
...v,
|
|
@@ -8486,6 +8832,30 @@ export class SqliteScopeHost {
|
|
|
8486
8832
|
throw substratError('precondition_failed', exportBreakRefusal(breaks));
|
|
8487
8833
|
}
|
|
8488
8834
|
}
|
|
8835
|
+
// K-65 (#3539): a release into an earlier major moves no channel. Its gates were judged against
|
|
8836
|
+
// the version that major's script runs, so its admin row, the acknowledgement's evidence, lands
|
|
8837
|
+
// only while the script still runs it, with the listing and the admission read in that unit as
|
|
8838
|
+
// a prod promote reads them. The caller then serves it on the script and records that.
|
|
8839
|
+
if (target) {
|
|
8840
|
+
const judged = this.directoryWriteAndAudit(() => {
|
|
8841
|
+
const now = this.directory.prepare('SELECT earlier_majors FROM verticals WHERE slug = ?')
|
|
8842
|
+
.get(verticalSlug);
|
|
8843
|
+
if (earlierMajorsOf(now?.earlier_majors).find((m) => m.major === target.major)?.versionId !== target.versionId)
|
|
8844
|
+
return false;
|
|
8845
|
+
const listed = readVertical(verticalSlug)?.listed;
|
|
8846
|
+
if (listed && options?.unlistedOnly)
|
|
8847
|
+
throw listedPromoteRefusal();
|
|
8848
|
+
if (listed && breakingWithinMajor)
|
|
8849
|
+
throw breakingWithinMajorRefusal(breakingWithinMajor);
|
|
8850
|
+
if (listed && target.versionId !== versionId && versionAdmission(versionId).admission_note === AUTO_ADMISSION_NOTE) {
|
|
8851
|
+
throw autoAdmittedProdRefusal(verticalSlug, versionId);
|
|
8852
|
+
}
|
|
8853
|
+
return true;
|
|
8854
|
+
}, () => this.recordAdmin(actor, 'promoteVersion', { tenantId: null, vertical: verticalSlug }, outgoing ? { versionId: outgoing.id, version: outgoing.version } : null, { channel, versionId, version: incoming.version, earlierMajor: target.major, acknowledged: ack }));
|
|
8855
|
+
if (!judged)
|
|
8856
|
+
throw promoteRaceRefusal(channel);
|
|
8857
|
+
return;
|
|
8858
|
+
}
|
|
8489
8859
|
const promotedAt = new Date().toISOString();
|
|
8490
8860
|
// #2333: a compare-and-set. Every gate above — the review binding, the digest checkpoints,
|
|
8491
8861
|
// the export breaks — was judged against `outgoing`, across awaits another promote can run
|
|
@@ -8717,7 +9087,9 @@ export class SqliteScopeHost {
|
|
|
8717
9087
|
claimExpiredScopeScriptCopies: async (_actor, input) => {
|
|
8718
9088
|
const limit = assertRowLimit('limit', input.limit);
|
|
8719
9089
|
return this.directory.transaction(() => {
|
|
8720
|
-
const due =
|
|
9090
|
+
const due = (input.tenantId !== undefined
|
|
9091
|
+
? this.directory.prepare(COPY_EXPIRED_FOR_TENANT_SQL).all(input.now, input.tenantId, limit)
|
|
9092
|
+
: this.directory.prepare(COPY_EXPIRED_SQL).all(input.now, limit));
|
|
8721
9093
|
const claimed = [];
|
|
8722
9094
|
for (const r of due) {
|
|
8723
9095
|
if (this.directory.prepare(COPY_CLAIM_SQL).run(input.owner, input.leaseUntil, r.tenant_id, r.scope_id, r.script_ref, r.move_id, input.now).changes === 0)
|
|
@@ -8730,7 +9102,7 @@ export class SqliteScopeHost {
|
|
|
8730
9102
|
},
|
|
8731
9103
|
markScopeStoresFenced: async (actor, tenantId, scopeId, opts) => {
|
|
8732
9104
|
// No await between the read and the write, so an unarchive is before or after.
|
|
8733
|
-
const scope = this.directory.prepare('SELECT status, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?')
|
|
9105
|
+
const scope = this.directory.prepare('SELECT status, archived_at, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?')
|
|
8734
9106
|
.get(tenantId, scopeId);
|
|
8735
9107
|
if (!scope)
|
|
8736
9108
|
throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
|
|
@@ -8739,8 +9111,17 @@ export class SqliteScopeHost {
|
|
|
8739
9111
|
if (scope.status !== 'archived') {
|
|
8740
9112
|
throw substratError('conflict', `scope ${scopeId} is ${scope.status}, not archived, so its stores are not fenced`);
|
|
8741
9113
|
}
|
|
8742
|
-
if (opts?.
|
|
8743
|
-
throw substratError('conflict', `
|
|
9114
|
+
if (opts?.archivedBy !== undefined && (scope.archived_at === null || scope.archived_at > opts.archivedBy)) {
|
|
9115
|
+
throw substratError('conflict', `scope ${scopeId} has not passed its archive retention`);
|
|
9116
|
+
}
|
|
9117
|
+
if (opts?.whileTenantDeleting || opts?.deletingBy !== undefined) {
|
|
9118
|
+
const tenant = readTenant(tenantId);
|
|
9119
|
+
if (tenant?.status !== 'deleting') {
|
|
9120
|
+
throw substratError('conflict', `tenant ${tenantId} is no longer deleting, so the stores of scope ${scopeId} are not fenced`);
|
|
9121
|
+
}
|
|
9122
|
+
if (opts?.deletingBy !== undefined && (tenant.deletingAt === null || tenant.deletingAt > opts.deletingBy)) {
|
|
9123
|
+
throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
|
|
9124
|
+
}
|
|
8744
9125
|
}
|
|
8745
9126
|
this.directoryWriteAndAudit(() => this.directory.prepare(`UPDATE scopes SET stores_fenced_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE tenant_id = ? AND scope_id = ?`).run(tenantId, scopeId).changes > 0, () => this.recordAdmin(actor, 'markScopeStoresFenced', { tenantId, scopeId }, { storesFencedAt: null }, { storesFenced: true }));
|
|
8746
9127
|
},
|
|
@@ -8861,6 +9242,29 @@ export class SqliteScopeHost {
|
|
|
8861
9242
|
.get(verticalSlug);
|
|
8862
9243
|
if (!r)
|
|
8863
9244
|
throw substratError('not_found', `unknown vertical '${verticalSlug}'`);
|
|
9245
|
+
// K-65 (#3539): a release served on an earlier major's own script moves that major's entry alone.
|
|
9246
|
+
if (opts?.earlierMajor !== undefined) {
|
|
9247
|
+
const major = opts.earlierMajor;
|
|
9248
|
+
if (supersede)
|
|
9249
|
+
throw substratError('validation_failed', 'a serve records a new major or a release into an earlier one, not both');
|
|
9250
|
+
const entry = earlierMajorsOf(r.earlier_majors).find((m) => m.major === major);
|
|
9251
|
+
if (!expected || !entry || entry.versionId !== expected.versionId)
|
|
9252
|
+
throw servingRaceRefusal(verticalSlug);
|
|
9253
|
+
// #2993 part 4 and #2178, as an in-place serve is judged, over the installs on that script.
|
|
9254
|
+
assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug, entry.ref), this.manifestJsonOf(parsed.versionId, verticalSlug));
|
|
9255
|
+
this.assertNoStrandFrom([entry.versionId], parsed.versionId, this.provisionedVersionsOf(verticalSlug, { ref: entry.ref, versionId: entry.versionId }, null));
|
|
9256
|
+
let was = null;
|
|
9257
|
+
this.directoryWriteAndAudit(() => {
|
|
9258
|
+
const now = this.directory.prepare('SELECT earlier_majors FROM verticals WHERE slug = ?')
|
|
9259
|
+
.get(verticalSlug);
|
|
9260
|
+
const held = earlierMajorsOf(now?.earlier_majors).find((m) => m.major === major);
|
|
9261
|
+
was = held ? { ref: held.ref, versionId: held.versionId } : null;
|
|
9262
|
+
const earlier = releasedEarlierMajorJson({ vertical: verticalSlug, earlierJson: now?.earlier_majors, major, expected, next: parsed });
|
|
9263
|
+
this.directory.prepare('UPDATE verticals SET earlier_majors = ? WHERE slug = ?').run(earlier, verticalSlug);
|
|
9264
|
+
return true;
|
|
9265
|
+
}, () => this.recordAdmin(actor, 'setVerticalServing', { tenantId: null }, was, { vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId, earlierMajor: major }));
|
|
9266
|
+
return;
|
|
9267
|
+
}
|
|
8864
9268
|
// #2577: the caller's upload diffed its DO-class migration from `expected`'s class set and tag.
|
|
8865
9269
|
if (expected !== undefined && !migratesFrom(r, expected))
|
|
8866
9270
|
throw servingRaceRefusal(verticalSlug);
|
|
@@ -8868,6 +9272,11 @@ export class SqliteScopeHost {
|
|
|
8868
9272
|
if (supersede && (!expected || expected.ref !== r.serving_ref || expected.versionId !== r.serving_version_id)) {
|
|
8869
9273
|
throw servingRaceRefusal(verticalSlug);
|
|
8870
9274
|
}
|
|
9275
|
+
// #2993 part 4: every install on the serving script runs the new version from this moment,
|
|
9276
|
+
// so it declares every type their scopes hold.
|
|
9277
|
+
if (!supersede && r.serving_version_id) {
|
|
9278
|
+
assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug), this.manifestJsonOf(parsed.versionId, verticalSlug));
|
|
9279
|
+
}
|
|
8871
9280
|
// #2178: every install on the serving script runs the new version from this moment. A new
|
|
8872
9281
|
// major's first serve moves nobody onto its script: the installs stay on the earlier one.
|
|
8873
9282
|
if (!supersede)
|
|
@@ -9068,7 +9477,7 @@ export class SqliteScopeHost {
|
|
|
9068
9477
|
// truth, so the prune keeps more, never less.
|
|
9069
9478
|
const handedOffThrough = this.deliveryBroker && (this.deliveryHandoff === 'always' || this.deliveryModes.has(`${tenantId}/${scopeId}`))
|
|
9070
9479
|
? (this.handoffMarks.get(`${tenantId}/${scopeId}`) ??
|
|
9071
|
-
(await this.
|
|
9480
|
+
(await this.brokerOfScope(tenantId, scopeId).marks(tenantId, scopeId).catch(() => ({})))).event ?? null
|
|
9072
9481
|
: undefined;
|
|
9073
9482
|
// On the scope actor, like the stamp: issued mid-invoke it would otherwise be a
|
|
9074
9483
|
// SAVEPOINT inside the invoke's transaction, and roll back with it.
|
|
@@ -9861,54 +10270,33 @@ export class SqliteScopeHost {
|
|
|
9861
10270
|
// Also from `provisioning`: a scope whose provisioning never completed (a failed
|
|
9862
10271
|
// create) must be abandonable, or its slug is stranded forever (it can't reach a
|
|
9863
10272
|
// terminal state that frees the name).
|
|
9864
|
-
|
|
10273
|
+
//
|
|
10274
|
+
// #2995: lifecycle follows the link. The scope's children are archived with it, in the same
|
|
10275
|
+
// directory transaction, each with its own audit row naming the parent; a refused parent
|
|
10276
|
+
// archives none of them. A child already archived stays as it is.
|
|
10277
|
+
this.directory.transaction(() => {
|
|
10278
|
+
for (const child of this.childScopesOf(tenantId, scopeId, ['provisioning', 'active', 'suspended'])) {
|
|
10279
|
+
transitionScope(actor, 'archiveScope', tenantId, child, ['provisioning', 'active', 'suspended'], 'archived', { withParent: scopeId });
|
|
10280
|
+
}
|
|
10281
|
+
transitionScope(actor, 'archiveScope', tenantId, scopeId, ['provisioning', 'active', 'suspended'], 'archived');
|
|
10282
|
+
})(),
|
|
9865
10283
|
unarchiveScope: async (actor, tenantId, scopeId) => transitionScope(actor, 'unarchiveScope', tenantId, scopeId, ['archived'], 'active'),
|
|
9866
10284
|
reapScope: async (actor, tenantId, scopeId, opts) => {
|
|
9867
|
-
//
|
|
9868
|
-
//
|
|
9869
|
-
//
|
|
9870
|
-
//
|
|
9871
|
-
//
|
|
9872
|
-
|
|
9873
|
-
|
|
9874
|
-
const
|
|
9875
|
-
|
|
9876
|
-
|
|
9877
|
-
|
|
9878
|
-
|
|
9879
|
-
|
|
9880
|
-
|
|
9881
|
-
|
|
9882
|
-
}
|
|
9883
|
-
// A serving scope always holds ≥1 bound hostname; a truly-dead one has been
|
|
9884
|
-
// unbound. The dashboard delete path unbinds AT archive, but a bare console
|
|
9885
|
-
// `archiveScope` does not — so reap cannot ASSUME the release, it must verify it.
|
|
9886
|
-
// Refuse (fail closed) while any name still resolves here: unbinding first is a
|
|
9887
|
-
// visible, reversible step, and it is the wall that stops the irreversible wipe
|
|
9888
|
-
// from ever landing on an app that is still online (§4.4). `force` is the
|
|
9889
|
-
// deliberate-teardown bypass (tenant reap / retention sweep), where every name is
|
|
9890
|
-
// being released anyway; the interactive per-scope reap never sets it.
|
|
9891
|
-
const bound = opts?.force
|
|
9892
|
-
? undefined
|
|
9893
|
-
: this.directory
|
|
9894
|
-
.prepare('SELECT hostname FROM hostnames WHERE scope_id = ? LIMIT 1')
|
|
9895
|
-
.get(scopeId);
|
|
9896
|
-
if (bound) {
|
|
9897
|
-
throw substratError('conflict', `scope ${scopeId} still resolves hostname '${bound.hostname}' — ` +
|
|
9898
|
-
`unbind it before reaping (reap wipes storage and cannot be undone)`);
|
|
9899
|
-
}
|
|
9900
|
-
// The reader goes with the writer (#1624): an open handle on a removed file keeps
|
|
9901
|
-
// reading the unlinked bytes, which is the reaped data answering as if it were live.
|
|
9902
|
-
const rt = this.scopes.get(`${tenantId}/${scopeId}`);
|
|
9903
|
-
if (rt)
|
|
9904
|
-
this.closeRuntime(rt);
|
|
9905
|
-
await this.wipeScopeStores(tenantId, scopeId);
|
|
9906
|
-
rmSync(join(this.dir, `${tenantId}__${scopeId}.sqlite`), { force: true });
|
|
9907
|
-
// The recoverable copy the caller stored first (#493), named in the audit entry so
|
|
9908
|
-
// the trail answers "was there a backup" without correlating two timestamps.
|
|
9909
|
-
await transitionScope(actor, 'reapScope', tenantId, scopeId, ['archived'], 'reaped', {
|
|
9910
|
-
backupRef: opts?.backupRef ?? null,
|
|
9911
|
-
});
|
|
10285
|
+
// #2995: a child does not outlive its parent, so a parent's reap reaps its children first,
|
|
10286
|
+
// each as its own reap with its own audit row. Everything that could refuse is checked over
|
|
10287
|
+
// the parent AND its children before anything is wiped: each is archived (an archive of the
|
|
10288
|
+
// parent archived them), and none still resolves a hostname. A crash part-way leaves the
|
|
10289
|
+
// parent archived over fewer children, and running the reap again finishes it.
|
|
10290
|
+
const rec = this.directory.prepare('SELECT tenant_id FROM scopes WHERE scope_id = ?').get(scopeId);
|
|
10291
|
+
const children = rec?.tenant_id === tenantId ? this.childScopesOf(tenantId, scopeId, ['provisioning', 'active', 'suspended', 'archived']) : [];
|
|
10292
|
+
for (const child of children)
|
|
10293
|
+
assertReapable(tenantId, child, opts);
|
|
10294
|
+
assertReapable(tenantId, scopeId, opts);
|
|
10295
|
+
// A child's audit row names its parent and no backup: the caller's `backupRef` is a copy of the
|
|
10296
|
+
// parent, and naming it on a child would say a copy of the child was taken.
|
|
10297
|
+
for (const child of children)
|
|
10298
|
+
await reapOne(actor, tenantId, child, { force: opts?.force, withParent: scopeId });
|
|
10299
|
+
await reapOne(actor, tenantId, scopeId, opts);
|
|
9912
10300
|
},
|
|
9913
10301
|
// -- subject erasure (#37) ----------------------------------------------
|
|
9914
10302
|
sealSubjectPayloads: async (actor, tenantId, scopeId, items) => {
|
|
@@ -9952,7 +10340,7 @@ export class SqliteScopeHost {
|
|
|
9952
10340
|
await this.applyPendingMigrations(rt);
|
|
9953
10341
|
// One read transaction on the scope actor, so the page is consistent and no invoke's open
|
|
9954
10342
|
// transaction is read half-written.
|
|
9955
|
-
const read = await rt.actor.turn(() => db.transaction(() => readSubjectPage({ sql: spineSql(db), plans: this.
|
|
10343
|
+
const read = await rt.actor.turn(() => db.transaction(() => readSubjectPage({ sql: spineSql(db), plans: this.erasurePlansOf(scopeId), subjectId, ...(page ? { page } : {}) }))());
|
|
9956
10344
|
this.recordAccess(actor, 'readSubject', { tenantId, scopeId }, { subjectId }, read.events.length + read.records.reduce((n, r) => n + r.rows.length, 0));
|
|
9957
10345
|
return read;
|
|
9958
10346
|
},
|
|
@@ -10006,11 +10394,12 @@ export class SqliteScopeHost {
|
|
|
10006
10394
|
// The module half first (#2068): the declared entities, then each hook, with the
|
|
10007
10395
|
// search indexes over them under FTS5 secure-delete. The spine half follows in the same
|
|
10008
10396
|
// transaction, so the order between them decides nothing but the reading order.
|
|
10397
|
+
// #2993 part 3: the modules this scope's type runs — another type's tables are not here.
|
|
10009
10398
|
vertical: eraseSubjectFromModules({
|
|
10010
10399
|
sql: spineSql(db),
|
|
10011
|
-
plans: this.
|
|
10012
|
-
searchPlans: this.
|
|
10013
|
-
statefulTables: statefulTablesOf(this.
|
|
10400
|
+
plans: this.erasurePlansOf(scopeId),
|
|
10401
|
+
searchPlans: this.derivedPlans(scopeId).search.values(),
|
|
10402
|
+
statefulTables: statefulTablesOf(this.derivedPlans(scopeId).state),
|
|
10014
10403
|
subjectId,
|
|
10015
10404
|
at,
|
|
10016
10405
|
migrationSqlOf: (moduleId, version) => this.modules.get(moduleId)?.migrations.find((m) => m.version === version)?.sql,
|
|
@@ -10047,7 +10436,8 @@ export class SqliteScopeHost {
|
|
|
10047
10436
|
// erasure's turn with its handoffs, so every later handoff reads the outbox redacted) and
|
|
10048
10437
|
// before the key. A broker that throws refuses the erasure here, with the key untouched.
|
|
10049
10438
|
if (this.deliveryBroker) {
|
|
10050
|
-
|
|
10439
|
+
// #3639: the broker of the scope's environment, where its handoffs went.
|
|
10440
|
+
await this.brokerOfScope(tenantId, scopeId).eraseSubject({ tenantId, scopeId, subjectId, at });
|
|
10051
10441
|
}
|
|
10052
10442
|
// Scope stores after the scope-side redaction and before the key (#2068). A store
|
|
10053
10443
|
// that errors throws here, so the key below is untouched and a retry converges.
|
|
@@ -10084,6 +10474,38 @@ export class SqliteScopeHost {
|
|
|
10084
10474
|
throw substratError('not_found', `unknown scope ${scopeId} in tenant ${tenantId}`);
|
|
10085
10475
|
return row.erasure_epoch;
|
|
10086
10476
|
},
|
|
10477
|
+
holdDependentErasures: async (_actor, tenantId, subjectId, dependents) => {
|
|
10478
|
+
const now = new Date().toISOString();
|
|
10479
|
+
this.directory.transaction(() => {
|
|
10480
|
+
for (const d of dependents)
|
|
10481
|
+
this.directory.prepare(DEPENDENT_ERASURE_HOLD_SQL).run(tenantId, subjectId, d.scopeId, d.vertical, now, now);
|
|
10482
|
+
})();
|
|
10483
|
+
},
|
|
10484
|
+
recordDependentErasures: async (actor, tenantId, subjectId, outcomes) => {
|
|
10485
|
+
if (outcomes.length === 0)
|
|
10486
|
+
return;
|
|
10487
|
+
const now = new Date().toISOString();
|
|
10488
|
+
this.directory.transaction(() => {
|
|
10489
|
+
for (const o of outcomes) {
|
|
10490
|
+
if (o.outcome === 'erased') {
|
|
10491
|
+
this.directory.prepare(DEPENDENT_ERASURE_SETTLE_SQL).run(tenantId, subjectId, o.scopeId);
|
|
10492
|
+
}
|
|
10493
|
+
else {
|
|
10494
|
+
this.directory
|
|
10495
|
+
.prepare(DEPENDENT_ERASURE_OWE_SQL)
|
|
10496
|
+
.run(tenantId, subjectId, o.scopeId, o.vertical, o.attempts, nextDependentErasureAt(now, o.attempts), o.error, now);
|
|
10497
|
+
}
|
|
10498
|
+
}
|
|
10499
|
+
this.recordAdmin(actor, 'eraseAtDependents', { tenantId }, null, { subjectId, dependents: outcomes }, now);
|
|
10500
|
+
})();
|
|
10501
|
+
},
|
|
10502
|
+
dueDependentErasures: async (actor, now, limit) => {
|
|
10503
|
+
const rows = this.directory.prepare(DEPENDENT_ERASURE_DUE_SQL).all(now, limit);
|
|
10504
|
+
this.recordAccess(actor, 'dueDependentErasures', { tenantId: null }, { now, limit }, rows.length);
|
|
10505
|
+
return rows.map((r) => ({
|
|
10506
|
+
tenantId: r.tenant_id, subjectId: r.subject_id, scopeId: r.scope_id, vertical: r.vertical, attempts: r.attempts,
|
|
10507
|
+
}));
|
|
10508
|
+
},
|
|
10087
10509
|
finalizeSubjectShred: async (actor, tenantId, scopeId, subjectId, redactions, expected, storeErasures) => {
|
|
10088
10510
|
if (redactions.length === 0)
|
|
10089
10511
|
throw substratError('conflict', 'subject erasure has no confirmed scope redaction');
|
|
@@ -10138,7 +10560,7 @@ export class SqliteScopeHost {
|
|
|
10138
10560
|
this.recordAccess(actor, 'listImpersonations', { tenantId: (filter?.tenantId ?? null) }, filter ?? null, sessions.length);
|
|
10139
10561
|
return sessions;
|
|
10140
10562
|
},
|
|
10141
|
-
reapTenant: async (actor, tenantId) => {
|
|
10563
|
+
reapTenant: async (actor, tenantId, opts) => {
|
|
10142
10564
|
// The terminal tenant reap (§4.8), the tenant analogue of reapScope. The
|
|
10143
10565
|
// caller (the reap route / grace-window sweep) has already reaped every scope's
|
|
10144
10566
|
// storage above the kernel; this clears the tenant's directory-side PII/config
|
|
@@ -10177,6 +10599,9 @@ export class SqliteScopeHost {
|
|
|
10177
10599
|
if (before.status !== 'deleting') {
|
|
10178
10600
|
throw substratError('conflict', `tenant ${tenantId} is ${before.status}, not deleting — only a deleting tenant may be reaped`);
|
|
10179
10601
|
}
|
|
10602
|
+
if (opts?.deletingBy !== undefined && (before.deletingAt === null || before.deletingAt > opts.deletingBy)) {
|
|
10603
|
+
throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
|
|
10604
|
+
}
|
|
10180
10605
|
for (const table of tables) {
|
|
10181
10606
|
this.directory.prepare(`DELETE FROM ${table} WHERE tenant_id = ?`).run(tenantId);
|
|
10182
10607
|
}
|
|
@@ -11738,6 +12163,16 @@ export class SqliteScopeHost {
|
|
|
11738
12163
|
this.ensureColumn(this.directory, 'scopes', 'stores_fenced_at', 'stores_fenced_at TEXT');
|
|
11739
12164
|
// #2993: null on every existing row, which reads as 'home', the one type a scope had before.
|
|
11740
12165
|
this.ensureColumn(this.directory, 'scopes', 'scope_type', 'scope_type TEXT');
|
|
12166
|
+
// #3530 step 4: an environment's own serving script, NULL on every row (no script of its own).
|
|
12167
|
+
// Written out, not looped over the kernel's list: lint:spine-ddl reads each call.
|
|
12168
|
+
this.ensureColumn(this.directory, 'app_environments', 'serving_ref', 'serving_ref TEXT');
|
|
12169
|
+
this.ensureColumn(this.directory, 'app_environments', 'serving_version_id', 'serving_version_id TEXT');
|
|
12170
|
+
this.ensureColumn(this.directory, 'app_environments', 'serving_do_classes', 'serving_do_classes TEXT');
|
|
12171
|
+
this.ensureColumn(this.directory, 'app_environments', 'serving_migration_tag', 'serving_migration_tag TEXT');
|
|
12172
|
+
this.ensureColumn(this.directory, 'app_environments', 'serve_claim', 'serve_claim TEXT');
|
|
12173
|
+
this.ensureColumn(this.directory, 'app_environments', 'serve_claimed_until', 'serve_claimed_until TEXT');
|
|
12174
|
+
// #3530 step 6: the environment's choice of outside effects; NULL reads as `none`.
|
|
12175
|
+
this.ensureColumn(this.directory, 'app_environments', 'effects', 'effects TEXT');
|
|
11741
12176
|
// §4.8's grace-window timestamp on tenants (mirrors scopes' archived_at).
|
|
11742
12177
|
this.ensureColumn(this.directory, 'tenants', 'deleting_at', 'deleting_at TEXT');
|
|
11743
12178
|
this.ensureColumn(this.directory, 'tenants', 'provisioned_by_tenant', 'provisioned_by_tenant TEXT REFERENCES tenants(tenant_id)');
|
|
@@ -12327,6 +12762,21 @@ export class SqliteScopeHost {
|
|
|
12327
12762
|
},
|
|
12328
12763
|
atomic: createAtomic(runSub, { passed, signals }),
|
|
12329
12764
|
noteTransition: noteTransitionInto(signals),
|
|
12765
|
+
// #3540: the schedule named is due no later than `at`, written in this operation's transaction.
|
|
12766
|
+
scheduleDue: (operation, due) => noteScheduleDue(spineSql(rt.db), this.dueSchedules, operation, due),
|
|
12767
|
+
// #2996 (K-64): the proof a store call needs, written once in the kernel. The declared key is
|
|
12768
|
+
// checked as the caller (a consumer's system actor is refused: its checks allow everything).
|
|
12769
|
+
storeProof: (binding, operation) => mintStoreProof({
|
|
12770
|
+
sql: spineSql(rt.db),
|
|
12771
|
+
subject,
|
|
12772
|
+
consumer: Boolean(overrideActor),
|
|
12773
|
+
// The mint's own instant, so the proof's minute starts when it is minted.
|
|
12774
|
+
now: this.clock(),
|
|
12775
|
+
check: runCheck,
|
|
12776
|
+
assertWrites: (verb) => assertImpersonationWrites(impersonation, verb),
|
|
12777
|
+
minted,
|
|
12778
|
+
keyOf: (b, o) => storeOperationKeyOf(this.permissions?.stores, b, o),
|
|
12779
|
+
}, binding, operation),
|
|
12330
12780
|
// #1672: mint / revoke / list, written once in the kernel. The raw spine seam (this
|
|
12331
12781
|
// is the kernel's own write to `_substrat_capabilities`), the operation's OWN check —
|
|
12332
12782
|
// the predicate `grant` shares — and `ctx.emit` for the minted/revoked events. A
|
|
@@ -12449,6 +12899,14 @@ export class SqliteScopeHost {
|
|
|
12449
12899
|
* declares no types, a row from before types, and a scope not provisioned yet (not cached, so its
|
|
12450
12900
|
* provision decides). Cached once read, since a type never changes.
|
|
12451
12901
|
*/
|
|
12902
|
+
/** #2995: the ids of `parentScopeId`'s children in `tenantId` whose status is one of `statuses`, oldest first. */
|
|
12903
|
+
childScopesOf(tenantId, parentScopeId, statuses) {
|
|
12904
|
+
const rows = this.directory
|
|
12905
|
+
.prepare(`SELECT scope_id FROM scopes WHERE tenant_id = ? AND parent_scope_id = ? AND status IN (${statuses.map(() => '?').join(', ')})
|
|
12906
|
+
ORDER BY scope_id`)
|
|
12907
|
+
.all(tenantId, parentScopeId, ...statuses);
|
|
12908
|
+
return rows.map((r) => r.scope_id);
|
|
12909
|
+
}
|
|
12452
12910
|
scopeTypeOf(scopeId) {
|
|
12453
12911
|
if (!this.scopeTypePlan.declared)
|
|
12454
12912
|
return HOME_SCOPE_TYPE;
|
|
@@ -12462,10 +12920,25 @@ export class SqliteScopeHost {
|
|
|
12462
12920
|
this.scopeTypeCache.set(scopeId, type);
|
|
12463
12921
|
return type;
|
|
12464
12922
|
}
|
|
12923
|
+
/**
|
|
12924
|
+
* #2993 part 3: the type this directory records for `scopeId`, for a copy of it to take. Undefined
|
|
12925
|
+
* on a host with no declared types (a copy provisions as it always did) and for a scope this
|
|
12926
|
+
* directory does not hold (a dump from elsewhere carries no type, so the caller names one).
|
|
12927
|
+
*/
|
|
12928
|
+
recordedScopeType(scopeId) {
|
|
12929
|
+
if (!this.scopeTypePlan.declared)
|
|
12930
|
+
return undefined;
|
|
12931
|
+
const row = this.directory.prepare('SELECT scope_type FROM scopes WHERE scope_id = ?').get(scopeId);
|
|
12932
|
+
return row ? (row.scope_type ?? HOME_SCOPE_TYPE) : undefined;
|
|
12933
|
+
}
|
|
12465
12934
|
/** #2993: whether this scope's type runs the module. Every module runs on a host with no declared types. */
|
|
12466
12935
|
runsOn(scopeId, moduleId) {
|
|
12467
12936
|
return !this.scopeTypePlan.declared || scopeTypeRuns(this.scopeTypePlan, this.scopeTypeOf(scopeId), moduleId);
|
|
12468
12937
|
}
|
|
12938
|
+
/** #2993 part 3: the erasure plans of the modules this scope's type runs, whose tables it holds. */
|
|
12939
|
+
erasurePlansOf(scopeId) {
|
|
12940
|
+
return this.scopeTypePlan.declared ? this.erasurePlans.filter((p) => this.runsOn(scopeId, p.moduleId)) : this.erasurePlans;
|
|
12941
|
+
}
|
|
12469
12942
|
/** #2993: the registered modules this scope's type runs, in registration order. */
|
|
12470
12943
|
modulesOf(scopeId) {
|
|
12471
12944
|
const all = [...this.modules.values()];
|
|
@@ -12829,6 +13302,9 @@ export class SqliteScopeHost {
|
|
|
12829
13302
|
// #2096: a purge horizon's lap in progress, on a scope DB built before the column. NULL is the
|
|
12830
13303
|
// start of a lap — the honest reading of every row already there. After the #1288 rebuild, as above.
|
|
12831
13304
|
this.ensureColumn(db, '_substrat_schedule_state', 'purge_cursor', 'purge_cursor TEXT');
|
|
13305
|
+
// #3540: a due-by-event schedule's next date, on a scope DB built before the column. NULL is "not
|
|
13306
|
+
// yet run under the form", so its cadence decides: the honest reading of every row already there.
|
|
13307
|
+
this.ensureColumn(db, '_substrat_schedule_state', 'due_at', 'due_at TEXT');
|
|
12832
13308
|
this.ensureColumn(db, '_substrat_job_runs', 'subject_id', 'subject_id TEXT');
|
|
12833
13309
|
// #2034: the lease, on a scope DB built before it. NULL = nobody holds the run.
|
|
12834
13310
|
this.ensureColumn(db, '_substrat_job_runs', 'lease_owner', 'lease_owner TEXT');
|