@substrat-run/adapter-sqlite 0.221.0 → 0.223.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/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/index.d.ts +26 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +269 -39
- 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, 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, 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, releaseEnvironmentServeIn, removeEnvironmentIn, setEnvironmentServingIn, 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, proofCheckedStoreInvoke, 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, sealingKeysForReach, 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 { childDoorRefusal, childScopeRefusal, directAccessRefusal, HOME_SCOPE_TYPE, operationNotInScopeType, provisionedParent, provisionedScopeType, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRoleRefusal, 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';
|
|
@@ -1014,6 +1014,8 @@ export class SqliteScopeHost {
|
|
|
1014
1014
|
brokerTelemetry;
|
|
1015
1015
|
/** K-74: each scope's handoff marks, a cache of what its broker holds (`DeliveryBroker.marks`). */
|
|
1016
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();
|
|
1017
1019
|
/** A5: `deliveryHandoff`, and each scope's mode with its window start (in memory, as the marks are). */
|
|
1018
1020
|
deliveryHandoff;
|
|
1019
1021
|
deliveryModes = new Map();
|
|
@@ -1613,6 +1615,8 @@ export class SqliteScopeHost {
|
|
|
1613
1615
|
${MEMBERSHIP_FENCES_DDL}
|
|
1614
1616
|
${PEER_SWITCHES_DDL}
|
|
1615
1617
|
${SWITCH_OWED_DDL}
|
|
1618
|
+
-- K-63 (#3624): erasures owed to a master's dependents, kept until each door answers.
|
|
1619
|
+
${DEPENDENT_ERASURES_DDL}
|
|
1616
1620
|
CREATE TABLE IF NOT EXISTS _substrat_admin_log (
|
|
1617
1621
|
id TEXT PRIMARY KEY,
|
|
1618
1622
|
actor TEXT NOT NULL,
|
|
@@ -1987,14 +1991,19 @@ export class SqliteScopeHost {
|
|
|
1987
1991
|
tenantId: rt.tenantId,
|
|
1988
1992
|
scopeId: rt.scopeId,
|
|
1989
1993
|
vertical: vertical ?? '',
|
|
1990
|
-
connection: async (provider) => {
|
|
1994
|
+
connection: async (provider, options) => {
|
|
1991
1995
|
if (!vertical) {
|
|
1992
1996
|
throw new Error(`scope ${rt.scopeId} is bound to no vertical, so it has no connection namespace — ` +
|
|
1993
1997
|
`provision it with a vertical before using connectors`);
|
|
1994
1998
|
}
|
|
1995
|
-
|
|
1999
|
+
// #3530 step 6: `own` opens this scope's own connection, and never the tenant's.
|
|
2000
|
+
const open = options?.own
|
|
2001
|
+
? await admin.openConnection(rt.tenantId, vertical, provider, undefined, rt.scopeId)
|
|
2002
|
+
: await admin.openConnection(rt.tenantId, vertical, provider);
|
|
1996
2003
|
if (!open) {
|
|
1997
|
-
throw new Error(
|
|
2004
|
+
throw new Error(options?.own
|
|
2005
|
+
? `scope ${rt.scopeId} owns no live '${provider}' connection, and a dispatch held to its own opens no other`
|
|
2006
|
+
: `no live '${provider}' connection for tenant ${rt.tenantId} / vertical '${vertical}'`);
|
|
1998
2007
|
}
|
|
1999
2008
|
const readSurface = () => this.buildAttachments(rt, { kind: 'connection', id: open.id }, this.attachmentStore(rt.tenantId, vertical), {
|
|
2000
2009
|
reentrant: holdsActor,
|
|
@@ -2308,7 +2317,17 @@ export class SqliteScopeHost {
|
|
|
2308
2317
|
// #2995: the parent link, fixed at the first provision. A new child is held to its parent's declared
|
|
2309
2318
|
// children, tenant, app, state and depth before its row is written. No await separates the check from
|
|
2310
2319
|
// the INSERT below, so no archive of the parent can land between them.
|
|
2311
|
-
const
|
|
2320
|
+
const namedParent = provisionedParent(input.parentScopeId, existing ? existingRow.parent_scope_id : undefined, input.scopeId);
|
|
2321
|
+
// #3625 (K-64): a new typed scope that names no parent is a child of its app's home scope, judged below as any
|
|
2322
|
+
// named parent is. On a host that declares its own types, as the Durable Object host does: a module-less
|
|
2323
|
+
// coordinator judging by a vertical's types names a link through provision-child, which tells the vertical.
|
|
2324
|
+
const parentScopeId = existing || namedParent !== null || !this.scopeTypePlan.declared
|
|
2325
|
+
? namedParent
|
|
2326
|
+
: homeParentOf(switchSqlOf(this.directory), input.tenantId, { vertical: record.vertical, type: scopeType, forkedFrom: record.forkedFrom });
|
|
2327
|
+
// #2995 (the owner's word on #3604's fourth question): a new scope of a type other than home has a parent.
|
|
2328
|
+
const parentless = existing ? null : parentlessScopeRefusal(scopeType, parentScopeId, record.forkedFrom, input.scopeId);
|
|
2329
|
+
if (parentless)
|
|
2330
|
+
throw parentless;
|
|
2312
2331
|
if (!existing && parentScopeId !== null) {
|
|
2313
2332
|
const parent = this.directory
|
|
2314
2333
|
.prepare('SELECT tenant_id, status, vertical, scope_type, parent_scope_id, forked_from FROM scopes WHERE scope_id = ?')
|
|
@@ -2338,6 +2357,25 @@ export class SqliteScopeHost {
|
|
|
2338
2357
|
throw substratError('conflict', `scope slug '${record.slug}' already taken under tenant ${input.tenantId} ` +
|
|
2339
2358
|
`by ${slugOwner.scope_id} (slugs are unique within a tenant)`);
|
|
2340
2359
|
}
|
|
2360
|
+
// #3625 (K-64): one home scope per (tenant, app, environment). A second install of the app is
|
|
2361
|
+
// refused; a copy, a preview and a child are not installs. #2993: nor is a sibling, except of an
|
|
2362
|
+
// app that declares scope types, by this host's own declaration or (a module-less coordinator)
|
|
2363
|
+
// by its deployed version's: there a sibling of type home is a second home, and a new scope is
|
|
2364
|
+
// a child instead. No await separates this read from the INSERT below.
|
|
2365
|
+
const typed = input.sibling === true && record.vertical !== null &&
|
|
2366
|
+
(plan.declared || this.verticalScopeTypePlan(record.vertical).declared);
|
|
2367
|
+
const secondHome = secondHomeRefusal(switchSqlOf(this.directory), input.tenantId, input.scopeId, {
|
|
2368
|
+
vertical: record.vertical,
|
|
2369
|
+
type: scopeType,
|
|
2370
|
+
parentScopeId,
|
|
2371
|
+
forkedFrom: record.forkedFrom,
|
|
2372
|
+
kind: record.kind,
|
|
2373
|
+
install: input.install,
|
|
2374
|
+
sibling: input.sibling,
|
|
2375
|
+
typed,
|
|
2376
|
+
});
|
|
2377
|
+
if (secondHome)
|
|
2378
|
+
throw secondHome;
|
|
2341
2379
|
this.directory
|
|
2342
2380
|
.prepare(`INSERT INTO scopes
|
|
2343
2381
|
(scope_id, tenant_id, parent_scope_id, scope_type, slug, kind, name, vertical,
|
|
@@ -4057,12 +4095,14 @@ export class SqliteScopeHost {
|
|
|
4057
4095
|
}
|
|
4058
4096
|
/**
|
|
4059
4097
|
* #2993 part 4: the types other than `home` the vertical's unreaped scopes hold, each once: what
|
|
4060
|
-
* a promote judges the incoming version's declared types against.
|
|
4098
|
+
* a promote judges the incoming version's declared types against. K-65 (#3539): with `servingRef`,
|
|
4099
|
+
* only the scopes on that script, which is all a release into an earlier major reaches.
|
|
4061
4100
|
*/
|
|
4062
|
-
scopeTypesHeldBy(vertical) {
|
|
4101
|
+
scopeTypesHeldBy(vertical, servingRef) {
|
|
4102
|
+
const onScript = servingRef === undefined ? '' : ' AND serving_ref = ?';
|
|
4063
4103
|
return this.directory
|
|
4064
|
-
.prepare(
|
|
4065
|
-
.all(vertical).map((r) => r.scope_type);
|
|
4104
|
+
.prepare(`SELECT DISTINCT scope_type FROM scopes WHERE vertical = ?${onScript} AND scope_type IS NOT NULL AND status <> 'reaped' ORDER BY scope_type`)
|
|
4105
|
+
.all(...(servingRef === undefined ? [vertical] : [vertical, servingRef])).map((r) => r.scope_type);
|
|
4066
4106
|
}
|
|
4067
4107
|
/**
|
|
4068
4108
|
* A stored version's manifest, unaudited: the platform reading its own code metadata (#1705).
|
|
@@ -6363,13 +6403,19 @@ export class SqliteScopeHost {
|
|
|
6363
6403
|
const mode = this.deliveryModes.get(key);
|
|
6364
6404
|
if (this.deliveryHandoff === 'by-mode' && !mode)
|
|
6365
6405
|
return;
|
|
6406
|
+
// #3639 (D-83): to the broker of the scope's environment, or to none: a preview or a fork, and an
|
|
6407
|
+
// environment nobody gave connections of its own, hand off nothing, as a hosted one is told `off`.
|
|
6408
|
+
const environment = deliveryEnvironmentIn(switchSqlOf(this.directory), rt.tenantId, rt.scopeId);
|
|
6409
|
+
if (environment === null)
|
|
6410
|
+
return;
|
|
6411
|
+
this.handoffEnvironments.set(key, environment);
|
|
6366
6412
|
const options = mode
|
|
6367
6413
|
? { mode: mode.mode, ...(mode.startPending ? { start: { ...ids, after: mode.start } } : {}) }
|
|
6368
6414
|
: {};
|
|
6369
6415
|
/** #3474: the round now with the broker, so a throw reports what it tried. */
|
|
6370
6416
|
let inFlight = null;
|
|
6371
6417
|
try {
|
|
6372
|
-
const broker = this.deliveryBroker(ids);
|
|
6418
|
+
const broker = this.deliveryBroker({ ...ids, environment });
|
|
6373
6419
|
let marks = this.handoffMarks.get(key) ?? (await broker.marks(rt.tenantId, rt.scopeId));
|
|
6374
6420
|
// A backlog larger than one batch follows in the next round; bounded, so a commit never spins.
|
|
6375
6421
|
for (let round = 0; round < 20; round++) {
|
|
@@ -6391,7 +6437,7 @@ export class SqliteScopeHost {
|
|
|
6391
6437
|
delete options.start;
|
|
6392
6438
|
}
|
|
6393
6439
|
const next = advanceMarks(marks, sent, answer);
|
|
6394
|
-
this.reportHandoffRound(rt, inFlight, handoffOutcome(sent, answer));
|
|
6440
|
+
this.reportHandoffRound(rt, inFlight, handoffOutcome(sent, answer), environment);
|
|
6395
6441
|
inFlight = null;
|
|
6396
6442
|
// An answer that acknowledges nothing new: stop; the next commit or `retryHandoffs` tries again.
|
|
6397
6443
|
if (next.event === marks.event && next.intent === marks.intent)
|
|
@@ -6403,19 +6449,33 @@ export class SqliteScopeHost {
|
|
|
6403
6449
|
}
|
|
6404
6450
|
catch (err) {
|
|
6405
6451
|
if (inFlight)
|
|
6406
|
-
this.reportHandoffRound(rt, inFlight, 'failed');
|
|
6452
|
+
this.reportHandoffRound(rt, inFlight, 'failed', environment);
|
|
6407
6453
|
console.error('substrat: delivery handoff failed; the next commit retries it', err);
|
|
6408
6454
|
}
|
|
6409
6455
|
}
|
|
6456
|
+
/**
|
|
6457
|
+
* #3639: the broker a scope's messages went to: the environment the directory says the scope belongs
|
|
6458
|
+
* to (`environmentOfScopeIn`, which does not follow its effects, so it outlives a restart and an
|
|
6459
|
+
* environment taken back to none), else the one this host last handed off to, else production's (a
|
|
6460
|
+
* scope that never handed off holds nothing in any). Only with `deliveryBroker` given.
|
|
6461
|
+
*/
|
|
6462
|
+
brokerOfScope(tenantId, scopeId) {
|
|
6463
|
+
const environment = environmentOfScopeIn(switchSqlOf(this.directory), tenantId, scopeId) ??
|
|
6464
|
+
this.handoffEnvironments.get(`${tenantId}/${scopeId}`) ??
|
|
6465
|
+
PRODUCTION_ENVIRONMENT;
|
|
6466
|
+
return this.deliveryBroker({ tenantId, scopeId, environment });
|
|
6467
|
+
}
|
|
6410
6468
|
/** #3474: one point per handoff round, when `brokerTelemetry` is given. */
|
|
6411
|
-
reportHandoffRound(rt, round, outcome
|
|
6469
|
+
reportHandoffRound(rt, round, outcome,
|
|
6470
|
+
/** #3639: the environment whose broker the round went to; production's names none. */
|
|
6471
|
+
environment) {
|
|
6412
6472
|
const t = this.brokerTelemetry;
|
|
6413
6473
|
if (!t)
|
|
6414
6474
|
return;
|
|
6415
6475
|
const ids = { tenantId: rt.tenantId, scopeId: rt.scopeId };
|
|
6416
6476
|
// Telemetry never fails the handoff it follows: the harness's `appOf` may throw.
|
|
6417
6477
|
try {
|
|
6418
|
-
reportHandoff(t.sink, { ...ids, app: t.appOf(ids) }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
|
|
6478
|
+
reportHandoff(t.sink, { ...ids, app: t.appOf(ids), ...(environment === PRODUCTION_ENVIRONMENT ? {} : { environment }) }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
|
|
6419
6479
|
}
|
|
6420
6480
|
catch (err) {
|
|
6421
6481
|
console.error('substrat: delivery telemetry failed; the handoff continues', err);
|
|
@@ -6795,6 +6855,26 @@ export class SqliteScopeHost {
|
|
|
6795
6855
|
* back-fill, and it is idempotent: the partial-unique index makes a race
|
|
6796
6856
|
* between two callers resolve to one current key rather than two.
|
|
6797
6857
|
*/
|
|
6858
|
+
/**
|
|
6859
|
+
* The public keys of the live connections `scopeId` owns (#3530 step 6), the oldest first, one per
|
|
6860
|
+
* provider: what an environment given connections of its own seals to in place of the tenant's.
|
|
6861
|
+
*/
|
|
6862
|
+
async ownSealingKeys(tenantId, vertical, scopeId) {
|
|
6863
|
+
const rows = this.directory
|
|
6864
|
+
.prepare(`SELECT id, provider FROM _substrat_connections
|
|
6865
|
+
WHERE tenant_id = ? AND vertical = ? AND owner_scope_id = ? AND revoked_at IS NULL
|
|
6866
|
+
ORDER BY created_at`)
|
|
6867
|
+
.all(tenantId, vertical, scopeId);
|
|
6868
|
+
const seen = new Set();
|
|
6869
|
+
const out = [];
|
|
6870
|
+
for (const r of rows) {
|
|
6871
|
+
if (seen.has(r.provider))
|
|
6872
|
+
continue;
|
|
6873
|
+
seen.add(r.provider);
|
|
6874
|
+
out.push(await this.ensureSealingKey(r.id));
|
|
6875
|
+
}
|
|
6876
|
+
return out;
|
|
6877
|
+
}
|
|
6798
6878
|
async ensureSealingKey(connectionId) {
|
|
6799
6879
|
const conn = this.connectionRow(connectionId);
|
|
6800
6880
|
const read = () => this.directory
|
|
@@ -7193,6 +7273,10 @@ export class SqliteScopeHost {
|
|
|
7193
7273
|
where.push('vertical = ?');
|
|
7194
7274
|
params.push(filter.vertical);
|
|
7195
7275
|
}
|
|
7276
|
+
if (filter?.parentScopeId) {
|
|
7277
|
+
where.push('parent_scope_id = ?');
|
|
7278
|
+
params.push(filter.parentScopeId);
|
|
7279
|
+
}
|
|
7196
7280
|
const tail = keysetTail(where, params, 'scope_id', filter);
|
|
7197
7281
|
const sql = 'SELECT * FROM scopes' + (where.length ? ` WHERE ${where.join(' AND ')}` : '') + tail;
|
|
7198
7282
|
return this.directory.prepare(sql).all(...params);
|
|
@@ -8245,6 +8329,12 @@ export class SqliteScopeHost {
|
|
|
8245
8329
|
this.recordAccess(actor, 'peerBindings', { tenantId, scopeId: callerScopeId }, null, rows.length);
|
|
8246
8330
|
return rows.map((r) => ({ tenantId, callerScopeId, vertical: r.vertical, targetScopeId: r.target_scope_id, invalidated: r.invalidated === 1 }));
|
|
8247
8331
|
},
|
|
8332
|
+
// #3625 (K-64): the home scope of (tenant, app, environment). The rule is the kernel's (`home-scope.ts`).
|
|
8333
|
+
homeScopeOf: async (actor, tenantId, vertical, environment) => {
|
|
8334
|
+
const scopeId = homeScopeIn(switchSqlOf(this.directory), tenantId, vertical, environment);
|
|
8335
|
+
this.recordAccess(actor, 'homeScopeOf', { tenantId }, { vertical, environment: environment ?? 'prod' }, scopeId ? 1 : 0);
|
|
8336
|
+
return scopeId;
|
|
8337
|
+
},
|
|
8248
8338
|
// D-83 (#3530 step 3): an app's environments. The rule is the kernel's (`app-environments.ts`).
|
|
8249
8339
|
listEnvironments: async (actor, tenantId, vertical) => {
|
|
8250
8340
|
const rows = environmentsOf(switchSqlOf(this.directory), tenantId, vertical);
|
|
@@ -8272,13 +8362,26 @@ export class SqliteScopeHost {
|
|
|
8272
8362
|
releaseEnvironmentServe: async (_actor, input, claim) => {
|
|
8273
8363
|
releaseEnvironmentServeIn(switchSqlOf(this.directory), input, claim);
|
|
8274
8364
|
},
|
|
8275
|
-
setEnvironmentServing: async (actor, input, next, expected, claim) => this.directory.transaction(() => {
|
|
8276
|
-
|
|
8365
|
+
setEnvironmentServing: async (actor, input, next, expected, claim, acknowledge) => this.directory.transaction(() => {
|
|
8366
|
+
// #3638: judged against what this environment serves, in the write that moves it.
|
|
8367
|
+
const ack = acknowledge === undefined ? undefined : environmentServeAcknowledgement.parse(acknowledge);
|
|
8368
|
+
const out = setEnvironmentServingIn(switchSqlOf(this.directory), input, next, expected, claim, ack);
|
|
8277
8369
|
if (!out.moved) {
|
|
8278
8370
|
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`);
|
|
8279
8371
|
}
|
|
8280
|
-
this.recordAdmin(actor, 'setEnvironmentServing', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, out.before ? { ref: out.before.ref, versionId: out.before.versionId } : null,
|
|
8372
|
+
this.recordAdmin(actor, 'setEnvironmentServing', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, out.before ? { ref: out.before.ref, versionId: out.before.versionId } : null,
|
|
8373
|
+
// #3638: the acknowledgement is recorded with this environment's serve, as a promote's is with prod's.
|
|
8374
|
+
{ vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId, ...(ack ? { acknowledged: ack } : {}) });
|
|
8375
|
+
})(),
|
|
8376
|
+
// #3530 step 6: an environment given connections of its own, and the rule every connection door asks.
|
|
8377
|
+
setEnvironmentEffects: async (actor, input, effects) => this.directory.transaction(() => {
|
|
8378
|
+
const out = setEnvironmentEffectsIn(switchSqlOf(this.directory), input, effects);
|
|
8379
|
+
if (out.changed) {
|
|
8380
|
+
this.recordAdmin(actor, 'setEnvironmentEffects', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, { effects: out.before }, { vertical: input.vertical, scopeId: out.scopeId, effects });
|
|
8381
|
+
}
|
|
8382
|
+
return { changed: out.changed, before: out.before };
|
|
8281
8383
|
})(),
|
|
8384
|
+
connectionReach: async (_actor, tenantId, scopeId) => connectionReachIn(switchSqlOf(this.directory), tenantId, scopeId),
|
|
8282
8385
|
setPeerBinding: async (_actor, tenantId, callerScopeId, vertical, targetScopeId) => this.directory.transaction(() => {
|
|
8283
8386
|
const caller = this.directory.prepare('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?').get(callerScopeId);
|
|
8284
8387
|
if (!caller || caller.tenant_id !== tenantId || caller.status !== 'active' || !isPrimaryScopeRow(caller)) {
|
|
@@ -8664,16 +8767,36 @@ export class SqliteScopeHost {
|
|
|
8664
8767
|
if (incoming.admission !== 'admitted') {
|
|
8665
8768
|
throw substratError('conflict', `version ${versionId} is ${incoming.admission}, not admitted — it cannot be promoted`);
|
|
8666
8769
|
}
|
|
8667
|
-
|
|
8668
|
-
|
|
8669
|
-
|
|
8770
|
+
// K-65 (#3539): a release that names an earlier major goes to that major's own script, and
|
|
8771
|
+
// every gate below is judged against the version that script runs, in place of the channel's.
|
|
8772
|
+
const target = options?.earlierMajor === undefined
|
|
8773
|
+
? null
|
|
8774
|
+
: (() => {
|
|
8775
|
+
if (channel !== 'prod')
|
|
8776
|
+
throw substratError('validation_failed', 'an earlier major is released on prod alone');
|
|
8777
|
+
const row = this.directory.prepare('SELECT earlier_majors FROM verticals WHERE slug = ?')
|
|
8778
|
+
.get(verticalSlug);
|
|
8779
|
+
return earlierMajorReleaseTarget({
|
|
8780
|
+
vertical: verticalSlug,
|
|
8781
|
+
earlierJson: row?.earlier_majors,
|
|
8782
|
+
major: options.earlierMajor,
|
|
8783
|
+
head: { version: incoming.version, deploymentRef: incoming.deploymentRef },
|
|
8784
|
+
servesMajors: options.servesMajors === true,
|
|
8785
|
+
});
|
|
8786
|
+
})();
|
|
8787
|
+
const current = target
|
|
8788
|
+
? { version_id: target.versionId }
|
|
8789
|
+
: this.directory
|
|
8790
|
+
.prepare('SELECT version_id FROM vertical_channels WHERE vertical_slug = ? AND channel = ?')
|
|
8791
|
+
.get(verticalSlug, channel);
|
|
8670
8792
|
const outgoing = current ? await readVersion(current.version_id) : undefined;
|
|
8671
8793
|
const ack = promotionAcknowledgement.parse(acknowledge ?? {});
|
|
8672
8794
|
// The owning tenant's live scopes a PRIVATE prod promote re-points — below for an embedded
|
|
8673
8795
|
// vertical, after the in-place serve for a dispatch-backed one (#321) — read before
|
|
8674
|
-
// anything moves so the #2178 gate can judge each one.
|
|
8796
|
+
// anything moves so the #2178 gate can judge each one. A release into an earlier major
|
|
8797
|
+
// re-points none: only the installs on that major's script run it.
|
|
8675
8798
|
const owning = channel === 'prod' ? readVertical(verticalSlug) : undefined;
|
|
8676
|
-
const owned = owning && owning.ownerTenant !== null && !owning.listed
|
|
8799
|
+
const owned = !target && owning && owning.ownerTenant !== null && !owning.listed
|
|
8677
8800
|
? this.directory
|
|
8678
8801
|
.prepare(`SELECT * FROM scopes
|
|
8679
8802
|
WHERE vertical = ? AND tenant_id = ? AND status = 'active' AND forked_from IS NULL AND kind != 'preview'`)
|
|
@@ -8683,7 +8806,9 @@ export class SqliteScopeHost {
|
|
|
8683
8806
|
// moves something from: the channel's version, the version served in place (a prod promote
|
|
8684
8807
|
// serves the incoming one next, and a failed serve leaves it behind the channel), and what each
|
|
8685
8808
|
// re-pointed scope RUNS (`runningVersionOf`: on the serving script, the served version).
|
|
8686
|
-
const served =
|
|
8809
|
+
const served = target
|
|
8810
|
+
? { ref: target.ref, versionId: target.versionId }
|
|
8811
|
+
: channel === 'prod' ? this.servingPointerOfVertical(verticalSlug) : null;
|
|
8687
8812
|
// And what each scope it moves last reconciled (`PROVISIONED_VERSIONS_SQL`).
|
|
8688
8813
|
this.assertNoStrandFrom([
|
|
8689
8814
|
outgoing?.id,
|
|
@@ -8705,7 +8830,8 @@ export class SqliteScopeHost {
|
|
|
8705
8830
|
throw breakingWithinMajorRefusal(breakingWithinMajor);
|
|
8706
8831
|
// #2993 part 4: the incoming version declares every type the vertical's scopes hold. Ahead
|
|
8707
8832
|
// of the acknowledgements, because none of them passes it.
|
|
8708
|
-
|
|
8833
|
+
// K-65 (#3539): a release into an earlier major reaches the scopes on its script alone.
|
|
8834
|
+
assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug, target?.ref), this.manifestJsonOf(versionId, verticalSlug));
|
|
8709
8835
|
// #2333: the acknowledgements answer the review they were given against, or none at all.
|
|
8710
8836
|
const reviewed = (v) => ({
|
|
8711
8837
|
...v,
|
|
@@ -8737,6 +8863,30 @@ export class SqliteScopeHost {
|
|
|
8737
8863
|
throw substratError('precondition_failed', exportBreakRefusal(breaks));
|
|
8738
8864
|
}
|
|
8739
8865
|
}
|
|
8866
|
+
// K-65 (#3539): a release into an earlier major moves no channel. Its gates were judged against
|
|
8867
|
+
// the version that major's script runs, so its admin row, the acknowledgement's evidence, lands
|
|
8868
|
+
// only while the script still runs it, with the listing and the admission read in that unit as
|
|
8869
|
+
// a prod promote reads them. The caller then serves it on the script and records that.
|
|
8870
|
+
if (target) {
|
|
8871
|
+
const judged = this.directoryWriteAndAudit(() => {
|
|
8872
|
+
const now = this.directory.prepare('SELECT earlier_majors FROM verticals WHERE slug = ?')
|
|
8873
|
+
.get(verticalSlug);
|
|
8874
|
+
if (earlierMajorsOf(now?.earlier_majors).find((m) => m.major === target.major)?.versionId !== target.versionId)
|
|
8875
|
+
return false;
|
|
8876
|
+
const listed = readVertical(verticalSlug)?.listed;
|
|
8877
|
+
if (listed && options?.unlistedOnly)
|
|
8878
|
+
throw listedPromoteRefusal();
|
|
8879
|
+
if (listed && breakingWithinMajor)
|
|
8880
|
+
throw breakingWithinMajorRefusal(breakingWithinMajor);
|
|
8881
|
+
if (listed && target.versionId !== versionId && versionAdmission(versionId).admission_note === AUTO_ADMISSION_NOTE) {
|
|
8882
|
+
throw autoAdmittedProdRefusal(verticalSlug, versionId);
|
|
8883
|
+
}
|
|
8884
|
+
return true;
|
|
8885
|
+
}, () => 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 }));
|
|
8886
|
+
if (!judged)
|
|
8887
|
+
throw promoteRaceRefusal(channel);
|
|
8888
|
+
return;
|
|
8889
|
+
}
|
|
8740
8890
|
const promotedAt = new Date().toISOString();
|
|
8741
8891
|
// #2333: a compare-and-set. Every gate above — the review binding, the digest checkpoints,
|
|
8742
8892
|
// the export breaks — was judged against `outgoing`, across awaits another promote can run
|
|
@@ -8968,7 +9118,9 @@ export class SqliteScopeHost {
|
|
|
8968
9118
|
claimExpiredScopeScriptCopies: async (_actor, input) => {
|
|
8969
9119
|
const limit = assertRowLimit('limit', input.limit);
|
|
8970
9120
|
return this.directory.transaction(() => {
|
|
8971
|
-
const due =
|
|
9121
|
+
const due = (input.tenantId !== undefined
|
|
9122
|
+
? this.directory.prepare(COPY_EXPIRED_FOR_TENANT_SQL).all(input.now, input.tenantId, limit)
|
|
9123
|
+
: this.directory.prepare(COPY_EXPIRED_SQL).all(input.now, limit));
|
|
8972
9124
|
const claimed = [];
|
|
8973
9125
|
for (const r of due) {
|
|
8974
9126
|
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)
|
|
@@ -8981,7 +9133,7 @@ export class SqliteScopeHost {
|
|
|
8981
9133
|
},
|
|
8982
9134
|
markScopeStoresFenced: async (actor, tenantId, scopeId, opts) => {
|
|
8983
9135
|
// No await between the read and the write, so an unarchive is before or after.
|
|
8984
|
-
const scope = this.directory.prepare('SELECT status, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?')
|
|
9136
|
+
const scope = this.directory.prepare('SELECT status, archived_at, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?')
|
|
8985
9137
|
.get(tenantId, scopeId);
|
|
8986
9138
|
if (!scope)
|
|
8987
9139
|
throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
|
|
@@ -8990,8 +9142,17 @@ export class SqliteScopeHost {
|
|
|
8990
9142
|
if (scope.status !== 'archived') {
|
|
8991
9143
|
throw substratError('conflict', `scope ${scopeId} is ${scope.status}, not archived, so its stores are not fenced`);
|
|
8992
9144
|
}
|
|
8993
|
-
if (opts?.
|
|
8994
|
-
throw substratError('conflict', `
|
|
9145
|
+
if (opts?.archivedBy !== undefined && (scope.archived_at === null || scope.archived_at > opts.archivedBy)) {
|
|
9146
|
+
throw substratError('conflict', `scope ${scopeId} has not passed its archive retention`);
|
|
9147
|
+
}
|
|
9148
|
+
if (opts?.whileTenantDeleting || opts?.deletingBy !== undefined) {
|
|
9149
|
+
const tenant = readTenant(tenantId);
|
|
9150
|
+
if (tenant?.status !== 'deleting') {
|
|
9151
|
+
throw substratError('conflict', `tenant ${tenantId} is no longer deleting, so the stores of scope ${scopeId} are not fenced`);
|
|
9152
|
+
}
|
|
9153
|
+
if (opts?.deletingBy !== undefined && (tenant.deletingAt === null || tenant.deletingAt > opts.deletingBy)) {
|
|
9154
|
+
throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
|
|
9155
|
+
}
|
|
8995
9156
|
}
|
|
8996
9157
|
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 }));
|
|
8997
9158
|
},
|
|
@@ -9112,6 +9273,29 @@ export class SqliteScopeHost {
|
|
|
9112
9273
|
.get(verticalSlug);
|
|
9113
9274
|
if (!r)
|
|
9114
9275
|
throw substratError('not_found', `unknown vertical '${verticalSlug}'`);
|
|
9276
|
+
// K-65 (#3539): a release served on an earlier major's own script moves that major's entry alone.
|
|
9277
|
+
if (opts?.earlierMajor !== undefined) {
|
|
9278
|
+
const major = opts.earlierMajor;
|
|
9279
|
+
if (supersede)
|
|
9280
|
+
throw substratError('validation_failed', 'a serve records a new major or a release into an earlier one, not both');
|
|
9281
|
+
const entry = earlierMajorsOf(r.earlier_majors).find((m) => m.major === major);
|
|
9282
|
+
if (!expected || !entry || entry.versionId !== expected.versionId)
|
|
9283
|
+
throw servingRaceRefusal(verticalSlug);
|
|
9284
|
+
// #2993 part 4 and #2178, as an in-place serve is judged, over the installs on that script.
|
|
9285
|
+
assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug, entry.ref), this.manifestJsonOf(parsed.versionId, verticalSlug));
|
|
9286
|
+
this.assertNoStrandFrom([entry.versionId], parsed.versionId, this.provisionedVersionsOf(verticalSlug, { ref: entry.ref, versionId: entry.versionId }, null));
|
|
9287
|
+
let was = null;
|
|
9288
|
+
this.directoryWriteAndAudit(() => {
|
|
9289
|
+
const now = this.directory.prepare('SELECT earlier_majors FROM verticals WHERE slug = ?')
|
|
9290
|
+
.get(verticalSlug);
|
|
9291
|
+
const held = earlierMajorsOf(now?.earlier_majors).find((m) => m.major === major);
|
|
9292
|
+
was = held ? { ref: held.ref, versionId: held.versionId } : null;
|
|
9293
|
+
const earlier = releasedEarlierMajorJson({ vertical: verticalSlug, earlierJson: now?.earlier_majors, major, expected, next: parsed });
|
|
9294
|
+
this.directory.prepare('UPDATE verticals SET earlier_majors = ? WHERE slug = ?').run(earlier, verticalSlug);
|
|
9295
|
+
return true;
|
|
9296
|
+
}, () => this.recordAdmin(actor, 'setVerticalServing', { tenantId: null }, was, { vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId, earlierMajor: major }));
|
|
9297
|
+
return;
|
|
9298
|
+
}
|
|
9115
9299
|
// #2577: the caller's upload diffed its DO-class migration from `expected`'s class set and tag.
|
|
9116
9300
|
if (expected !== undefined && !migratesFrom(r, expected))
|
|
9117
9301
|
throw servingRaceRefusal(verticalSlug);
|
|
@@ -9324,7 +9508,7 @@ export class SqliteScopeHost {
|
|
|
9324
9508
|
// truth, so the prune keeps more, never less.
|
|
9325
9509
|
const handedOffThrough = this.deliveryBroker && (this.deliveryHandoff === 'always' || this.deliveryModes.has(`${tenantId}/${scopeId}`))
|
|
9326
9510
|
? (this.handoffMarks.get(`${tenantId}/${scopeId}`) ??
|
|
9327
|
-
(await this.
|
|
9511
|
+
(await this.brokerOfScope(tenantId, scopeId).marks(tenantId, scopeId).catch(() => ({})))).event ?? null
|
|
9328
9512
|
: undefined;
|
|
9329
9513
|
// On the scope actor, like the stamp: issued mid-invoke it would otherwise be a
|
|
9330
9514
|
// SAVEPOINT inside the invoke's transaction, and roll back with it.
|
|
@@ -10283,7 +10467,8 @@ export class SqliteScopeHost {
|
|
|
10283
10467
|
// erasure's turn with its handoffs, so every later handoff reads the outbox redacted) and
|
|
10284
10468
|
// before the key. A broker that throws refuses the erasure here, with the key untouched.
|
|
10285
10469
|
if (this.deliveryBroker) {
|
|
10286
|
-
|
|
10470
|
+
// #3639: the broker of the scope's environment, where its handoffs went.
|
|
10471
|
+
await this.brokerOfScope(tenantId, scopeId).eraseSubject({ tenantId, scopeId, subjectId, at });
|
|
10287
10472
|
}
|
|
10288
10473
|
// Scope stores after the scope-side redaction and before the key (#2068). A store
|
|
10289
10474
|
// that errors throws here, so the key below is untouched and a retry converges.
|
|
@@ -10320,6 +10505,38 @@ export class SqliteScopeHost {
|
|
|
10320
10505
|
throw substratError('not_found', `unknown scope ${scopeId} in tenant ${tenantId}`);
|
|
10321
10506
|
return row.erasure_epoch;
|
|
10322
10507
|
},
|
|
10508
|
+
holdDependentErasures: async (_actor, tenantId, subjectId, dependents) => {
|
|
10509
|
+
const now = new Date().toISOString();
|
|
10510
|
+
this.directory.transaction(() => {
|
|
10511
|
+
for (const d of dependents)
|
|
10512
|
+
this.directory.prepare(DEPENDENT_ERASURE_HOLD_SQL).run(tenantId, subjectId, d.scopeId, d.vertical, now, now);
|
|
10513
|
+
})();
|
|
10514
|
+
},
|
|
10515
|
+
recordDependentErasures: async (actor, tenantId, subjectId, outcomes) => {
|
|
10516
|
+
if (outcomes.length === 0)
|
|
10517
|
+
return;
|
|
10518
|
+
const now = new Date().toISOString();
|
|
10519
|
+
this.directory.transaction(() => {
|
|
10520
|
+
for (const o of outcomes) {
|
|
10521
|
+
if (o.outcome === 'erased') {
|
|
10522
|
+
this.directory.prepare(DEPENDENT_ERASURE_SETTLE_SQL).run(tenantId, subjectId, o.scopeId);
|
|
10523
|
+
}
|
|
10524
|
+
else {
|
|
10525
|
+
this.directory
|
|
10526
|
+
.prepare(DEPENDENT_ERASURE_OWE_SQL)
|
|
10527
|
+
.run(tenantId, subjectId, o.scopeId, o.vertical, o.attempts, nextDependentErasureAt(now, o.attempts), o.error, now);
|
|
10528
|
+
}
|
|
10529
|
+
}
|
|
10530
|
+
this.recordAdmin(actor, 'eraseAtDependents', { tenantId }, null, { subjectId, dependents: outcomes }, now);
|
|
10531
|
+
})();
|
|
10532
|
+
},
|
|
10533
|
+
dueDependentErasures: async (actor, now, limit) => {
|
|
10534
|
+
const rows = this.directory.prepare(DEPENDENT_ERASURE_DUE_SQL).all(now, limit);
|
|
10535
|
+
this.recordAccess(actor, 'dueDependentErasures', { tenantId: null }, { now, limit }, rows.length);
|
|
10536
|
+
return rows.map((r) => ({
|
|
10537
|
+
tenantId: r.tenant_id, subjectId: r.subject_id, scopeId: r.scope_id, vertical: r.vertical, attempts: r.attempts,
|
|
10538
|
+
}));
|
|
10539
|
+
},
|
|
10323
10540
|
finalizeSubjectShred: async (actor, tenantId, scopeId, subjectId, redactions, expected, storeErasures) => {
|
|
10324
10541
|
if (redactions.length === 0)
|
|
10325
10542
|
throw substratError('conflict', 'subject erasure has no confirmed scope redaction');
|
|
@@ -10374,7 +10591,7 @@ export class SqliteScopeHost {
|
|
|
10374
10591
|
this.recordAccess(actor, 'listImpersonations', { tenantId: (filter?.tenantId ?? null) }, filter ?? null, sessions.length);
|
|
10375
10592
|
return sessions;
|
|
10376
10593
|
},
|
|
10377
|
-
reapTenant: async (actor, tenantId) => {
|
|
10594
|
+
reapTenant: async (actor, tenantId, opts) => {
|
|
10378
10595
|
// The terminal tenant reap (§4.8), the tenant analogue of reapScope. The
|
|
10379
10596
|
// caller (the reap route / grace-window sweep) has already reaped every scope's
|
|
10380
10597
|
// storage above the kernel; this clears the tenant's directory-side PII/config
|
|
@@ -10413,6 +10630,9 @@ export class SqliteScopeHost {
|
|
|
10413
10630
|
if (before.status !== 'deleting') {
|
|
10414
10631
|
throw substratError('conflict', `tenant ${tenantId} is ${before.status}, not deleting — only a deleting tenant may be reaped`);
|
|
10415
10632
|
}
|
|
10633
|
+
if (opts?.deletingBy !== undefined && (before.deletingAt === null || before.deletingAt > opts.deletingBy)) {
|
|
10634
|
+
throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
|
|
10635
|
+
}
|
|
10416
10636
|
for (const table of tables) {
|
|
10417
10637
|
this.directory.prepare(`DELETE FROM ${table} WHERE tenant_id = ?`).run(tenantId);
|
|
10418
10638
|
}
|
|
@@ -10680,7 +10900,7 @@ export class SqliteScopeHost {
|
|
|
10680
10900
|
});
|
|
10681
10901
|
},
|
|
10682
10902
|
connectionSealingKey: (id) => this.ensureSealingKey(id),
|
|
10683
|
-
connectionSealingKeys: async (tenantId, vertical) => {
|
|
10903
|
+
connectionSealingKeys: async (tenantId, vertical, scopeId) => {
|
|
10684
10904
|
// LIVE connections only. A revoked connection's key is kept (its pending
|
|
10685
10905
|
// ciphertext must still open) but stops being projected, so a scope can no
|
|
10686
10906
|
// longer seal to a credential that has been withdrawn. Tenant-owned only (#2732): a
|
|
@@ -10692,7 +10912,10 @@ export class SqliteScopeHost {
|
|
|
10692
10912
|
const out = [];
|
|
10693
10913
|
for (const r of rows)
|
|
10694
10914
|
out.push(await this.ensureSealingKey(r.id));
|
|
10695
|
-
|
|
10915
|
+
// #3530 step 6: the scope of an environment given connections of its own seals to its own.
|
|
10916
|
+
if (!scopeId)
|
|
10917
|
+
return out;
|
|
10918
|
+
return sealingKeysForReach(connectionReachIn(switchSqlOf(this.directory), tenantId, scopeId), out, await this.ownSealingKeys(tenantId, vertical, scopeId));
|
|
10696
10919
|
},
|
|
10697
10920
|
listConnections: async (actor, filter) => {
|
|
10698
10921
|
const f = filter ?? {};
|
|
@@ -11982,6 +12205,8 @@ export class SqliteScopeHost {
|
|
|
11982
12205
|
this.ensureColumn(this.directory, 'app_environments', 'serving_migration_tag', 'serving_migration_tag TEXT');
|
|
11983
12206
|
this.ensureColumn(this.directory, 'app_environments', 'serve_claim', 'serve_claim TEXT');
|
|
11984
12207
|
this.ensureColumn(this.directory, 'app_environments', 'serve_claimed_until', 'serve_claimed_until TEXT');
|
|
12208
|
+
// #3530 step 6: the environment's choice of outside effects; NULL reads as `none`.
|
|
12209
|
+
this.ensureColumn(this.directory, 'app_environments', 'effects', 'effects TEXT');
|
|
11985
12210
|
// §4.8's grace-window timestamp on tenants (mirrors scopes' archived_at).
|
|
11986
12211
|
this.ensureColumn(this.directory, 'tenants', 'deleting_at', 'deleting_at TEXT');
|
|
11987
12212
|
this.ensureColumn(this.directory, 'tenants', 'provisioned_by_tenant', 'provisioned_by_tenant TEXT REFERENCES tenants(tenant_id)');
|
|
@@ -12684,10 +12909,15 @@ export class SqliteScopeHost {
|
|
|
12684
12909
|
ORDER BY created_at LIMIT 1`)
|
|
12685
12910
|
.get(rt.tenantId, vertical, provider)
|
|
12686
12911
|
: undefined;
|
|
12687
|
-
|
|
12912
|
+
// #3530 step 6: the same rule the projection applies (`sealingKeysForReach`): the scope of an
|
|
12913
|
+
// environment given connections of its own seals to its own connection of the provider.
|
|
12914
|
+
const own = vertical && connectionReachIn(switchSqlOf(this.directory), rt.tenantId, rt.scopeId) === 'own'
|
|
12915
|
+
? (await this.ownSealingKeys(rt.tenantId, vertical, rt.scopeId)).find((k) => k.provider === provider)
|
|
12916
|
+
: undefined;
|
|
12917
|
+
if (!row && !own) {
|
|
12688
12918
|
throw new ConnectionSealingKeyUnavailableError(provider, noSealingKeyMessage(provider, rt.scopeId));
|
|
12689
12919
|
}
|
|
12690
|
-
const key = await this.ensureSealingKey(row.id);
|
|
12920
|
+
const key = own ?? (await this.ensureSealingKey(row.id));
|
|
12691
12921
|
return sealTo({ keyId: key.keyId, publicKey: key.publicKey }, plaintext);
|
|
12692
12922
|
},
|
|
12693
12923
|
};
|