@tearleads/client-sdk 0.1.253 → 0.1.254
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/client/containerContents/documentDiscovery.js +0 -2
- package/client/containerContents/documentDiscovery.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +7 -10
- package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js +5 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerHydrationPersistence.js +1 -1
- package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js +11 -4
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerRemovalMetadata.js +47 -0
- package/data/persistence/container-contents/containerRemovalMetadata.js.map +1 -0
- package/data/persistence/container-contents/containerRemovalPlacements.js +22 -0
- package/data/persistence/container-contents/containerRemovalPlacements.js.map +1 -0
- package/data/persistence/container-contents/containerSyncWatermarkPersistence.d.ts +2 -1
- package/data/persistence/container-contents/containerSyncWatermarkPersistence.js +10 -2
- package/data/persistence/container-contents/containerSyncWatermarkPersistence.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryCandidate.d.ts +1 -0
- package/data/persistence/documents/documentDiscoveryCandidate.js +3 -1
- package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +16 -4
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/sqlite/migrations/localSchemaMigrations.js +11 -0
- package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
- package/data/sqlite/schema/containerSyncWatermarkSchema.js +6 -3
- package/data/sqlite/schema/containerSyncWatermarkSchema.js.map +1 -1
- package/data/sqlite/schema/index.d.ts +17 -0
- package/internal/api-client/ApiClient.d.ts +1 -0
- package/internal/api-client/client/apiClientContext.d.ts +1 -0
- package/internal/api-client/client/containerReads.d.ts +1 -0
- package/internal/api-client/requestInternals.js +14 -6
- package/internal/api-client/requestInternals.js.map +1 -1
- package/internal/validators/operation/containerReads.d.ts +29 -2
- package/internal/validators/operation/containerReads.js +2 -1
- package/internal/validators/operation/containerReads.js.map +1 -1
- package/internal/validators/request/containerDocumentLanes.d.ts +7 -0
- package/internal/validators/request/containerDocumentLanes.js +6 -0
- package/internal/validators/request/containerDocumentLanes.js.map +1 -1
- package/internal/validators/response/container.d.ts +8 -0
- package/internal/validators/response/container.js +1 -0
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/containerParentLanes.d.ts +2 -0
- package/package.json +1 -1
- package/workflows/container-contents/documentDiscovery/containerDocumentListing.js +52 -4
- package/workflows/container-contents/documentDiscovery/containerDocumentListing.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js +4 -2
- package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js +17 -12
- package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/publicationWatermark.js +15 -0
- package/workflows/container-contents/documentDiscovery/publicationWatermark.js.map +1 -0
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +4 -4
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -1
- package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js +25 -0
- package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js.map +1 -0
- package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js +107 -0
- package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js.map +1 -0
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +29 -27
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +17 -5
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/tombstoneApplication.js +67 -24
- package/workflows/container-contents/remoteHydration/tombstoneApplication.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +3 -1
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/remoteReset/remoteResetCursorScope.js +3 -3
- package/workflows/container-contents/remoteReset/remoteResetCursorScope.js.map +1 -1
- package/workflows/container-contents/syncPause/discoveryGuard.js +6 -2
- package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneGate.js +6 -3
- package/workflows/container-contents/tombstones/documentTombstoneGate.js.map +1 -1
|
@@ -27,11 +27,9 @@ function createDiscoveryLane(input) {
|
|
|
27
27
|
})
|
|
28
28
|
: Promise.resolve(),
|
|
29
29
|
containerId: request.containerId,
|
|
30
|
-
holdContainerDocumentTombstones: (tombstones) => holdRepository.holdContainerDocumentTombstones(tombstones),
|
|
31
30
|
listHeldContainerDocumentTombstones: (containerIds) => holdRepository.listRetryableHeldContainerDocumentTombstones(containerIds),
|
|
32
31
|
listKnownContainerDocumentPlacements: (placements) => holdRepository.listKnownContainerDocumentPlacements(placements),
|
|
33
32
|
onFullListing: request.onFullListing,
|
|
34
|
-
refuteContainerDocumentTombstoneHolds: (placements) => holdRepository.refuteContainerDocumentTombstoneHolds(placements),
|
|
35
33
|
verifyContainerDocumentTombstones: createContainerDocumentTombstoneVerifier(containerOrganizationId, loadHead, loadEpoch),
|
|
36
34
|
...guardDocumentDiscoveryWrites({
|
|
37
35
|
execSql,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentDiscovery.js","sourceRoot":"","sources":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esContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport { ContainerDocumentTombstoneHoldRepository } from \"../../data/persistence/documents/containerDocumentTombstoneHoldRepository\";\nimport { DocumentDiscoveryEvidenceRepository } from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../data/sync/organizationSyncPauses\";\nimport { listContainerDocumentLanesFromApi } from \"../../workflows/container-contents/documentDiscovery/containerDocumentListing\";\nimport { createDiscoveredDocumentVerifier } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryEvidence\";\nimport {\n type ContainerDocumentDiscoveryLane,\n type ContainerDocumentDiscoveryOutcome,\n type ContainerDocumentDiscoveryOutcomeHandler,\n discoverContainerDocumentLanes,\n} from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryLanes\";\nimport { ContainerDocumentListingUnavailableError } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryTypes\";\nimport { createContainerDocumentQueriesFromRuntime } from \"../../workflows/container-contents/documentQueries\";\nimport {\n type ContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntimeFromSnapshot,\n} from \"../../workflows/container-contents/runtime\";\nimport { guardDocumentDiscoveryWrites } from \"../../workflows/container-contents/syncPause/discoveryGuard\";\nimport {\n createContainerDocumentTombstoneVerifier,\n createDocumentHeadLinkSetLoader,\n} from \"../../workflows/container-contents/tombstones/documentTombstoneEvidence\";\nimport {\n createPrincipalPolicyOperation,\n type PrincipalPolicyOperation,\n} from \"../../workflows/principals/principalPolicyService\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\n\nexport type { ContainerDocumentDiscoveryOutcome } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryLanes\";\n\n/** One container to discover, with the reconciler's per-lane callbacks. */\nexport interface ContainerDocumentDiscoveryRequest {\n readonly containerId: string;\n readonly onFullListing?:\n | ((documentIds: ReadonlyArray<string>) => void)\n | undefined;\n readonly onPendingDiscovery?: ((delayMs: number) => void) | undefined;\n}\n\ntype ExecSql = ReturnType<InternalRuntime[\"workflowInput\"]>[\"infra\"][\"execSql\"];\n\nfunction createDiscoveryLane(input: {\n readonly containerOrganizationId: string | undefined;\n readonly isContainerPaused: () => boolean;\n readonly evidenceStore: DocumentDiscoveryEvidenceRepository;\n readonly execSql: ExecSql;\n readonly holdRepository: ContainerDocumentTombstoneHoldRepository;\n /** The discovery pass's token: its lanes share one directory discovery. */\n readonly policyOperation: PrincipalPolicyOperation;\n readonly queries: ReturnType<\n typeof createContainerDocumentQueriesFromRuntime\n >;\n readonly request: ContainerDocumentDiscoveryRequest;\n readonly runtime: ContainerContentsWorkflowRuntime;\n}): ContainerDocumentDiscoveryLane {\n const { containerOrganizationId, execSql, holdRepository, request, runtime } =\n input;\n const warmReferencedPrincipalPolicies =\n runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n });\n const loadHead = createDocumentHeadLinkSetLoader(\n runtime,\n undefined,\n input.policyOperation,\n );\n const loadEpoch = (documentId: string) =>\n holdRepository.loadLocalDocumentAccessEpoch(documentId);\n return {\n ...input.queries,\n cacheReferencedPrincipalPolicies: (references) =>\n containerOrganizationId\n ? warmReferencedPrincipalPolicies({\n organizationId: containerOrganizationId,\n references,\n })\n : Promise.resolve(),\n containerId: request.containerId,\n holdContainerDocumentTombstones: (tombstones) =>\n holdRepository.holdContainerDocumentTombstones(tombstones),\n listHeldContainerDocumentTombstones: (containerIds) =>\n holdRepository.listRetryableHeldContainerDocumentTombstones(containerIds),\n listKnownContainerDocumentPlacements: (placements) =>\n holdRepository.listKnownContainerDocumentPlacements(placements),\n onFullListing: request.onFullListing,\n refuteContainerDocumentTombstoneHolds: (placements) =>\n holdRepository.refuteContainerDocumentTombstoneHolds(placements),\n verifyContainerDocumentTombstones: createContainerDocumentTombstoneVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n ),\n ...guardDocumentDiscoveryWrites({\n execSql,\n isPaused: input.isContainerPaused,\n verifyDiscoveredDocuments: createDiscoveredDocumentVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n input.evidenceStore,\n request.onPendingDiscovery,\n ),\n }),\n };\n}\n\n/**\n * Internal adapter shared by explicit discovery and background reconciliation:\n * one batched listing for every requested container, then per-container\n * verification scoped to each container's durable organization.\n */\nexport async function discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n}: {\n readonly onOutcome?: ContainerDocumentDiscoveryOutcomeHandler | undefined;\n readonly requests: ReadonlyArray<ContainerDocumentDiscoveryRequest>;\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<ContainerDocumentDiscoveryOutcome>> {\n const unlisted = (\n containerId: string,\n ): ContainerDocumentDiscoveryOutcome => ({\n containerId,\n status: \"fulfilled\",\n value: null,\n });\n const input = runtimeService.workflowInput();\n if (input.infra.dbStatus !== \"ready\") {\n return requests.map(({ containerId }) => unlisted(containerId));\n }\n const runtime = createContainerContentsWorkflowRuntimeFromSnapshot({\n ...input,\n organizations: runtimeService.containerContentsOrganizations,\n });\n const execSql = input.infra.execSql;\n const evidenceStore = new DocumentDiscoveryEvidenceRepository(execSql);\n const holdRepository = new ContainerDocumentTombstoneHoldRepository(execSql);\n const queries = createContainerDocumentQueriesFromRuntime(runtime);\n // Capture the reset fence before reading any lane's scope, so a reset\n // between these reads and the listing cannot publish old-organization\n // evidence into its replacement.\n const generation = await evidenceStore.begin();\n const syncPauses = getOrCreateOrganizationSyncPauses(input.state.domainScope);\n await syncPauses.load(execSql);\n const lanes: ContainerDocumentDiscoveryLane[] = [];\n const policyOperation = createPrincipalPolicyOperation();\n for (const request of requests) {\n const stored =\n await sqlContainerContentsPersistence.loadContainerMetadataState(\n execSql,\n request.containerId,\n );\n if (!stored) continue;\n const isContainerPaused = () =>\n syncPauses.isContainerPaused(stored.container);\n // A paused organization's container lists like one that is not stored,\n // and a pause landing mid-listing stops its write.\n if (!isContainerPaused())\n lanes.push(\n createDiscoveryLane({\n containerOrganizationId: stored.container.organizationId,\n isContainerPaused,\n evidenceStore,\n execSql,\n holdRepository,\n policyOperation,\n queries,\n request,\n runtime,\n }),\n );\n }\n const outcomes = await discoverContainerDocumentLanes({\n generation,\n lanes,\n listContainerDocumentLanes: (listed) =>\n listContainerDocumentLanesFromApi(runtime.apiClient, listed),\n loadContainerDocumentWatermark: queries.loadContainerDocumentWatermark,\n onOutcome,\n });\n const outcomeByContainerId = new Map(\n outcomes.map((outcome) => [outcome.containerId, outcome]),\n );\n return requests.map(\n ({ containerId }) =>\n outcomeByContainerId.get(containerId) ?? unlisted(containerId),\n );\n}\n\n/**\n * Discovers one container; a rejected lane rethrows its failure, except an\n * unavailable listing, which this contract reports as `null`.\n */\nexport async function discoverContainerDocumentsForRuntime({\n runtimeService,\n ...request\n}: ContainerDocumentDiscoveryRequest & {\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<DocumentSummary> | null> {\n const [outcome] = await discoverContainerDocumentLanesForRuntime({\n requests: [request],\n runtimeService,\n });\n if (outcome?.status === \"rejected\") {\n if (outcome.reason instanceof ContainerDocumentListingUnavailableError) {\n return null;\n }\n throw outcome.reason;\n }\n return outcome?.value ?? null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentDiscovery.js","sourceRoot":"","sources":["documentDiscovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,+BAA+B,EAAE,MAAM,wEAAwE,CAAC;AACzH,OAAO,EAAE,wCAAwC,EAAE,MAAM,2EAA2E,CAAC;AACrI,OAAO,EAAE,mCAAmC,EAAE,MAAM,uEAAuE,CAAC;AAC5H,OAAO,EAAE,iCAAiC,EAAE,MAAM,wCAAwC,CAAC;AAC3F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+EAA+E,CAAC;AAClI,OAAO,EAAE,gCAAgC,EAAE,MAAM,gFAAgF,CAAC;AAClI,OAAO,EAIL,8BAA8B,GAC/B,MAAM,6EAA6E,CAAC;A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D,CAAC;IACF,OAAO,QAAQ,CAAC,GAAG,CACjB,CAAC,EAAE,WAAW,EAAE,EAAE,EAAE,CAClB,oBAAoB,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,QAAQ,CAAC,WAAW,CAAC,CACjE,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,EACzD,cAAc,EACd,GAAG,OAAO,EAGX;IACC,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,wCAAwC,CAAC;QAC/D,QAAQ,EAAE,CAAC,OAAO,CAAC;QACnB,cAAc;KACf,CAAC,CAAC;IACH,IAAI,OAAO,EAAE,MAAM,KAAK,UAAU,EAAE,CAAC;QACnC,IAAI,OAAO,CAAC,MAAM,YAAY,wCAAwC,EAAE,CAAC;YACvE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,OAAO,CAAC,MAAM,CAAC;IACvB,CAAC;IACD,OAAO,OAAO,EAAE,KAAK,IAAI,IAAI,CAAC;AAChC,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport { ContainerDocumentTombstoneHoldRepository } from \"../../data/persistence/documents/containerDocumentTombstoneHoldRepository\";\nimport { DocumentDiscoveryEvidenceRepository } from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../data/sync/organizationSyncPauses\";\nimport { listContainerDocumentLanesFromApi } from \"../../workflows/container-contents/documentDiscovery/containerDocumentListing\";\nimport { createDiscoveredDocumentVerifier } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryEvidence\";\nimport {\n type ContainerDocumentDiscoveryLane,\n type ContainerDocumentDiscoveryOutcome,\n type ContainerDocumentDiscoveryOutcomeHandler,\n discoverContainerDocumentLanes,\n} from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryLanes\";\nimport { ContainerDocumentListingUnavailableError } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryTypes\";\nimport { createContainerDocumentQueriesFromRuntime } from \"../../workflows/container-contents/documentQueries\";\nimport {\n type ContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntimeFromSnapshot,\n} from \"../../workflows/container-contents/runtime\";\nimport { guardDocumentDiscoveryWrites } from \"../../workflows/container-contents/syncPause/discoveryGuard\";\nimport {\n createContainerDocumentTombstoneVerifier,\n createDocumentHeadLinkSetLoader,\n} from \"../../workflows/container-contents/tombstones/documentTombstoneEvidence\";\nimport {\n createPrincipalPolicyOperation,\n type PrincipalPolicyOperation,\n} from \"../../workflows/principals/principalPolicyService\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\n\nexport type { ContainerDocumentDiscoveryOutcome } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryLanes\";\n\n/** One container to discover, with the reconciler's per-lane callbacks. */\nexport interface ContainerDocumentDiscoveryRequest {\n readonly containerId: string;\n readonly onFullListing?:\n | ((documentIds: ReadonlyArray<string>) => void)\n | undefined;\n readonly onPendingDiscovery?: ((delayMs: number) => void) | undefined;\n}\n\ntype ExecSql = ReturnType<InternalRuntime[\"workflowInput\"]>[\"infra\"][\"execSql\"];\n\nfunction createDiscoveryLane(input: {\n readonly containerOrganizationId: string | undefined;\n readonly isContainerPaused: () => boolean;\n readonly evidenceStore: DocumentDiscoveryEvidenceRepository;\n readonly execSql: ExecSql;\n readonly holdRepository: ContainerDocumentTombstoneHoldRepository;\n /** The discovery pass's token: its lanes share one directory discovery. */\n readonly policyOperation: PrincipalPolicyOperation;\n readonly queries: ReturnType<\n typeof createContainerDocumentQueriesFromRuntime\n >;\n readonly request: ContainerDocumentDiscoveryRequest;\n readonly runtime: ContainerContentsWorkflowRuntime;\n}): ContainerDocumentDiscoveryLane {\n const { containerOrganizationId, execSql, holdRepository, request, runtime } =\n input;\n const warmReferencedPrincipalPolicies =\n runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n });\n const loadHead = createDocumentHeadLinkSetLoader(\n runtime,\n undefined,\n input.policyOperation,\n );\n const loadEpoch = (documentId: string) =>\n holdRepository.loadLocalDocumentAccessEpoch(documentId);\n return {\n ...input.queries,\n cacheReferencedPrincipalPolicies: (references) =>\n containerOrganizationId\n ? warmReferencedPrincipalPolicies({\n organizationId: containerOrganizationId,\n references,\n })\n : Promise.resolve(),\n containerId: request.containerId,\n listHeldContainerDocumentTombstones: (containerIds) =>\n holdRepository.listRetryableHeldContainerDocumentTombstones(containerIds),\n listKnownContainerDocumentPlacements: (placements) =>\n holdRepository.listKnownContainerDocumentPlacements(placements),\n onFullListing: request.onFullListing,\n verifyContainerDocumentTombstones: createContainerDocumentTombstoneVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n ),\n ...guardDocumentDiscoveryWrites({\n execSql,\n isPaused: input.isContainerPaused,\n verifyDiscoveredDocuments: createDiscoveredDocumentVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n input.evidenceStore,\n request.onPendingDiscovery,\n ),\n }),\n };\n}\n\n/**\n * Internal adapter shared by explicit discovery and background reconciliation:\n * one batched listing for every requested container, then per-container\n * verification scoped to each container's durable organization.\n */\nexport async function discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n}: {\n readonly onOutcome?: ContainerDocumentDiscoveryOutcomeHandler | undefined;\n readonly requests: ReadonlyArray<ContainerDocumentDiscoveryRequest>;\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<ContainerDocumentDiscoveryOutcome>> {\n const unlisted = (\n containerId: string,\n ): ContainerDocumentDiscoveryOutcome => ({\n containerId,\n status: \"fulfilled\",\n value: null,\n });\n const input = runtimeService.workflowInput();\n if (input.infra.dbStatus !== \"ready\") {\n return requests.map(({ containerId }) => unlisted(containerId));\n }\n const runtime = createContainerContentsWorkflowRuntimeFromSnapshot({\n ...input,\n organizations: runtimeService.containerContentsOrganizations,\n });\n const execSql = input.infra.execSql;\n const evidenceStore = new DocumentDiscoveryEvidenceRepository(execSql);\n const holdRepository = new ContainerDocumentTombstoneHoldRepository(execSql);\n const queries = createContainerDocumentQueriesFromRuntime(runtime);\n // Capture the reset fence before reading any lane's scope, so a reset\n // between these reads and the listing cannot publish old-organization\n // evidence into its replacement.\n const generation = await evidenceStore.begin();\n const syncPauses = getOrCreateOrganizationSyncPauses(input.state.domainScope);\n await syncPauses.load(execSql);\n const lanes: ContainerDocumentDiscoveryLane[] = [];\n const policyOperation = createPrincipalPolicyOperation();\n for (const request of requests) {\n const stored =\n await sqlContainerContentsPersistence.loadContainerMetadataState(\n execSql,\n request.containerId,\n );\n if (!stored) continue;\n const isContainerPaused = () =>\n syncPauses.isContainerPaused(stored.container);\n // A paused organization's container lists like one that is not stored,\n // and a pause landing mid-listing stops its write.\n if (!isContainerPaused())\n lanes.push(\n createDiscoveryLane({\n containerOrganizationId: stored.container.organizationId,\n isContainerPaused,\n evidenceStore,\n execSql,\n holdRepository,\n policyOperation,\n queries,\n request,\n runtime,\n }),\n );\n }\n const outcomes = await discoverContainerDocumentLanes({\n generation,\n lanes,\n listContainerDocumentLanes: (listed) =>\n listContainerDocumentLanesFromApi(runtime.apiClient, listed),\n loadContainerDocumentWatermark: queries.loadContainerDocumentWatermark,\n onOutcome,\n });\n const outcomeByContainerId = new Map(\n outcomes.map((outcome) => [outcome.containerId, outcome]),\n );\n return requests.map(\n ({ containerId }) =>\n outcomeByContainerId.get(containerId) ?? unlisted(containerId),\n );\n}\n\n/**\n * Discovers one container; a rejected lane rethrows its failure, except an\n * unavailable listing, which this contract reports as `null`.\n */\nexport async function discoverContainerDocumentsForRuntime({\n runtimeService,\n ...request\n}: ContainerDocumentDiscoveryRequest & {\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<DocumentSummary> | null> {\n const [outcome] = await discoverContainerDocumentLanesForRuntime({\n requests: [request],\n runtimeService,\n });\n if (outcome?.status === \"rejected\") {\n if (outcome.reason instanceof ContainerDocumentListingUnavailableError) {\n return null;\n }\n throw outcome.reason;\n }\n return outcome?.value ?? null;\n}\n"]}
|
|
@@ -101,10 +101,16 @@ export interface ContainerHydrationTombstone extends ContainerRemoval {
|
|
|
101
101
|
generation: number;
|
|
102
102
|
}
|
|
103
103
|
export interface ContainerDeletionGuard {
|
|
104
|
+
/** A fresh container read denied access after the listing returned. */
|
|
105
|
+
confirmedAccessLoss?: {
|
|
106
|
+
placementHash: string | null;
|
|
107
|
+
expectedMetadata: Pick<ContainerMetadataRecord, "documentId" | "accessEpoch" | "accessStateHash" | "metadataUpdates"> | null;
|
|
108
|
+
};
|
|
104
109
|
containerId: string;
|
|
105
110
|
expectedContainer: ContainerRecord | null;
|
|
106
111
|
}
|
|
107
112
|
export interface SaveContainerOptions {
|
|
113
|
+
verifiedPlacement?: AccessManifestCheckpoint | undefined;
|
|
108
114
|
createIntent?: ContainerCreateIntentInput;
|
|
109
115
|
stillCurrent?: (() => boolean) | undefined;
|
|
110
116
|
localUpdatedAt?: string;
|
|
@@ -290,16 +296,7 @@ export interface ContainerContentsPersistence extends DormantMetadataSweepPersis
|
|
|
290
296
|
pendingUpdate?: PendingUpdateFields | undefined;
|
|
291
297
|
preserveDurableStructureWhenPending?: boolean | undefined;
|
|
292
298
|
record: ContainerMetadataRecord;
|
|
293
|
-
saveOptions?:
|
|
294
|
-
createIntent?: ContainerCreateIntentInput;
|
|
295
|
-
localUpdatedAt?: string;
|
|
296
|
-
moveIntent?: ContainerMoveIntentInput | undefined;
|
|
297
|
-
serverTimestamps?: {
|
|
298
|
-
createdAt?: string | null;
|
|
299
|
-
updatedAt?: string | null;
|
|
300
|
-
} | undefined;
|
|
301
|
-
updatedAt?: string;
|
|
302
|
-
} | undefined;
|
|
299
|
+
saveOptions?: Omit<SaveContainerOptions, "stillCurrent"> | undefined;
|
|
303
300
|
settleAcceptedPendingOnConflict: boolean;
|
|
304
301
|
stillCurrent?: (() => boolean) | undefined;
|
|
305
302
|
}) => Promise<{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerContentsPersistenceTypes.js","sourceRoot":"","sources":["containerContentsPersistenceTypes.ts"],"names":[],"mappings":"AAcA,MAAM,CAAC,MAAM,0BAA0B,GAAG,gBAAgB,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type { CONTAINER_CREATE_INTENT_TYPE } from \"../../sqlite/schema\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type {\n DocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../documents/records\";\nimport type { HeldContainerBinding } from \"./containerBinding\";\nimport type { ContainerMetadataRevalidationPersistence } from \"./containerMetadataRevalidations\";\nimport type { ContainerRecord } from \"./containerPersistence\";\nimport type { DormantMetadataSweepPersistence } from \"./dormantMetadataSweep\";\n\nexport const CONTAINER_MOVE_INTENT_TYPE = \"container.move\";\n\nexport type ContainerCreateIntentSyncStatus = \"pending\" | \"synced\";\nexport type ContainerMoveIntentSyncStatus = \"pending\" | \"blocked\";\n\nexport interface ContainerCreateIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n intentType: typeof CONTAINER_CREATE_INTENT_TYPE;\n syncStatus: ContainerCreateIntentSyncStatus;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerMoveIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n intentType: typeof CONTAINER_MOVE_INTENT_TYPE;\n syncStatus: ContainerMoveIntentSyncStatus;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerCreateIntentInput {\n id?: string;\n parentContainerId: string;\n}\n\nexport interface ContainerMoveIntentInput {\n id?: string;\n parentContainerId: string;\n previousParentContainerId?: string | null | undefined;\n}\n\nexport interface ContainerCreateIntentErrorInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport type ContainerCreateIntentErrorInputRecorder = (\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n) => Promise<void>;\n\nexport interface ContainerMoveIntentRevisionInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n stillCurrent: () => boolean;\n}\n\nexport interface ContainerCreateIntentRevisionInput\n extends ContainerMoveIntentRevisionInput {\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /** The remote parent now; a move settlement queues cites it as previous. */\n supersededMovePreviousParentId?: string | undefined;\n /**\n * The parent the create committed under. A desired parent equal to it, or\n * to the current one, owes no move: the user never moved the folder away,\n * and a later remote move by another writer stands.\n */\n createdParentContainerId?: string | undefined;\n /** The parent the settled intent wants. */\n desiredParentContainerId?: string | undefined;\n}\n\nexport interface LocalRootDescendantReparentInput {\n containerId: string;\n parentContainerId: string | null;\n updateCreateIntent?: boolean | undefined;\n}\n\n/**\n * A container's metadata document record plus its durable content: the full\n * Loro updates export of the metadata document, stored in the shared\n * history-checkpoint table under the container-metadata app kind. Metadata\n * documents are tiny registries, so the whole update log is the checkpoint.\n */\nexport interface ContainerMetadataRecord extends DocumentRecord {\n metadataUpdates: string;\n}\n\nexport interface StoredContainerState {\n container: ContainerRecord;\n record: ContainerMetadataRecord | null;\n}\n\nexport interface ContainerRemoval {\n containerId: string;\n reason: \"access_revoked\" | \"deleted\";\n updatedAt: string;\n}\n\nexport interface ContainerHydrationTombstone extends ContainerRemoval {\n generation: number;\n}\n\nexport interface ContainerDeletionGuard {\n containerId: string;\n expectedContainer: ContainerRecord | null;\n}\n\nexport interface SaveContainerOptions {\n createIntent?: ContainerCreateIntentInput;\n stillCurrent?: (() => boolean) | undefined;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n}\n\nexport interface SaveContainerWithPendingUpdateOptions\n extends SaveContainerOptions {\n pendingUpdate: PendingUpdateFields;\n}\n\nexport interface ContainerContentsPersistence\n extends DormantMetadataSweepPersistence,\n ContainerMetadataRevalidationPersistence {\n containerExists: (execSql: ExecSql, containerId: string) => Promise<boolean>;\n /**\n * Create an absent remotely hydrated container only when no newer durable\n * tombstone or concurrent container/dormant-metadata mutation won first.\n */\n commitHydratedContainer: (\n execSql: ExecSql,\n input: {\n container: ContainerRecord;\n expectedDormantRecord: ContainerMetadataRecord | null;\n /** Tombstone observed before the remote request began, or null. */\n expectedHydrationTombstone?:\n | ContainerHydrationTombstone\n | null\n | undefined;\n /** Current placement verified and pinned before recovery insertion. */\n expectedPlacementCheckpoint?: AccessManifestCheckpoint | undefined;\n record: ContainerMetadataRecord;\n remoteUpdatedAt: string;\n saveOptions: {\n localUpdatedAt?: string;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n { committed: true; container: ContainerRecord } | { committed: false }\n >;\n /** Capture anti-resurrection fences immediately before a remote fetch. */\n loadContainerHydrationTombstones: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<ContainerHydrationTombstone>>;\n deleteContainer: (\n execSql: ExecSql,\n containerId: string,\n options?: {\n reason?: ContainerRemoval[\"reason\"];\n updatedAt?: string;\n },\n ) => Promise<void>;\n deleteContainers: (\n execSql: ExecSql,\n removals: ReadonlyArray<ContainerRemoval>,\n options?: {\n /** Must run inside the deletion transaction before any row is removed. */\n beforeDeleteInTransaction?:\n | ((transactionExecSql: ExecSql) => Promise<boolean>)\n | undefined;\n /** Unsigned discovery removes listings but preserves metadata and local intent. */\n discoveryOnly?: boolean;\n /**\n * Request-time states rechecked inside the deletion transaction. An\n * absent or changed row means another pane won and aborts the cascade.\n */\n expectedContainers?: ReadonlyArray<ContainerDeletionGuard>;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ReadonlyArray<string>>;\n deletePendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n enqueuePendingUpdate: (\n execSql: ExecSql,\n input: PendingUpdateFields & { containerId: string },\n ) => Promise<string>;\n listPendingCreateIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerCreateIntentRecord[]>;\n // Every move intent that has not yet synced, regardless of syncStatus —\n // a blocked move (destination parent not synced yet) is still unsynced, and\n // synced moves are deleted (see markMoveIntentRevisionSynced), so every surviving\n // row qualifies. Blocked intents replay too: \"blocked\" names the reason the\n // last attempt could not proceed, not a terminal verdict.\n listUnsyncedMoveIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerMoveIntentRecord[]>;\n listContainerIdsWithPendingUpdates: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listContainerIdsWithPullContinuations: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listPendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n /** Revision-CAS error recorder used by asynchronous create replay. */\n recordCreateIntentRevisionError: ContainerCreateIntentErrorInputRecorder;\n recordMoveIntentError: (\n execSql: ExecSql,\n input: {\n blocked?: boolean | undefined;\n containerId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<void>;\n reassignContainerDocuments: (\n execSql: ExecSql,\n input: {\n fromContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n toContainerId: string;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalRootContainer: (\n execSql: ExecSql,\n input: {\n descendantReparents: ReadonlyArray<LocalRootDescendantReparentInput>;\n localRootContainerId: string;\n remoteOrganizationId: string;\n remoteRootContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalSystemContainer: (\n execSql: ExecSql,\n input: {\n localContainerId: string;\n remoteContainerId: string;\n remoteOrganizationId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n loadContainers: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<StoredContainerState>>;\n loadContainerMetadataState: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<StoredContainerState | null>;\n /**\n * The organization and metadata target this device holds for a container,\n * from its live row or retained dormant metadata; null when never held.\n */\n loadHeldContainerBinding: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<HeldContainerBinding | null>;\n /** Whether a held folder was re-homed away from this organization. */\n isSupersededContainerBinding: (\n execSql: ExecSql,\n input: { containerId: string; organizationId: string },\n ) => Promise<boolean>;\n /**\n * Move a held folder to the binding its own user re-created it under,\n * resetting the metadata record's remote stream; false if the held binding\n * changed since it was read.\n */\n rebindHeldContainer: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expected: HeldContainerBinding;\n next: { metadataDocumentId: string; organizationId: string };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<boolean>;\n /**\n * Load a container-metadata record by container id alone, without\n * requiring a containers row — the dormant shape row 4's access_revoked\n * branch leaves behind, re-attached on rehydration.\n */\n loadContainerMetadataRecord: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Atomically replace the exact rejected metadata pull continuation with its\n * durable recovery marker and return the authoritative current record.\n */\n invalidateMetadataPullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n containerId: string;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Conditionally commit metadata content, its outgoing row, accepted queue\n * settlement, container fields, and the canonical record in one transaction.\n */\n commitMetadataMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n clearSyncFailure?: boolean | undefined;\n container: ContainerRecord;\n expectedContainer: ContainerRecord;\n expectedRecord: ContainerMetadataRecord;\n createIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /**\n * When present, an overtaking create revision is adopted as the\n * desired local parent and converted to a move from this remotely\n * committed parent instead of rejecting the remote identity.\n */\n supersededMovePreviousParentId?: string | undefined;\n }\n | undefined;\n moveIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n }\n | undefined;\n /** Present only for an explicit local primary change; null clears it. */\n primaryDocumentId?: string | null | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n preserveDurableStructureWhenPending?: boolean | undefined;\n record: ContainerMetadataRecord;\n saveOptions?:\n | {\n createIntent?: ContainerCreateIntentInput;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n }\n | undefined;\n settleAcceptedPendingOnConflict: boolean;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n | {\n committed: true;\n container: ContainerRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | {\n committed: false;\n currentState: StoredContainerState | null;\n staleServerState?: true;\n }\n >;\n settleAcceptedMetadataPendingUpdates: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expectedRecord: ContainerMetadataRecord;\n pendingUpdateIds: readonly string[];\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<StoredContainerState | null>;\n saveContainer: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord | null,\n options?: SaveContainerOptions,\n ) => Promise<ContainerRecord>;\n /**\n * Atomically saves a container and enqueues its first metadata update.\n * Host adapters must implement the compound write in their own transaction.\n */\n saveContainerWithPendingUpdate: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n options: SaveContainerWithPendingUpdateOptions,\n ) => Promise<ContainerRecord>;\n saveContainerAndDeletePendingUpdates: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n pendingUpdateIds: readonly string[],\n ) => Promise<ContainerRecord>;\n /**\n * Revision-CAS settlement used by asynchronous create replay. Invalid\n * adapters are rejected before the remote mutation begins.\n */\n markCreateIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Explicit revision-CAS settlement. Move replay instead settles inside\n * commitMetadataMutation and requires its atomic acknowledgment.\n */\n markMoveIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Drop a move revision the server refuses for good and restore the\n * folder's previous parent in the same transaction; false if superseded.\n */\n abandonMoveIntentRevision: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput & {\n previousParentContainerId: string;\n },\n ) => Promise<boolean>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerContentsPersistenceTypes.js","sourceRoot":"","sources":["containerContentsPersistenceTypes.ts"],"names":[],"mappings":"AAcA,MAAM,CAAC,MAAM,0BAA0B,GAAG,gBAAgB,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type { CONTAINER_CREATE_INTENT_TYPE } from \"../../sqlite/schema\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type {\n DocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../documents/records\";\nimport type { HeldContainerBinding } from \"./containerBinding\";\nimport type { ContainerMetadataRevalidationPersistence } from \"./containerMetadataRevalidations\";\nimport type { ContainerRecord } from \"./containerPersistence\";\nimport type { DormantMetadataSweepPersistence } from \"./dormantMetadataSweep\";\n\nexport const CONTAINER_MOVE_INTENT_TYPE = \"container.move\";\n\nexport type ContainerCreateIntentSyncStatus = \"pending\" | \"synced\";\nexport type ContainerMoveIntentSyncStatus = \"pending\" | \"blocked\";\n\nexport interface ContainerCreateIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n intentType: typeof CONTAINER_CREATE_INTENT_TYPE;\n syncStatus: ContainerCreateIntentSyncStatus;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerMoveIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n intentType: typeof CONTAINER_MOVE_INTENT_TYPE;\n syncStatus: ContainerMoveIntentSyncStatus;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerCreateIntentInput {\n id?: string;\n parentContainerId: string;\n}\n\nexport interface ContainerMoveIntentInput {\n id?: string;\n parentContainerId: string;\n previousParentContainerId?: string | null | undefined;\n}\n\nexport interface ContainerCreateIntentErrorInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport type ContainerCreateIntentErrorInputRecorder = (\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n) => Promise<void>;\n\nexport interface ContainerMoveIntentRevisionInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n stillCurrent: () => boolean;\n}\n\nexport interface ContainerCreateIntentRevisionInput\n extends ContainerMoveIntentRevisionInput {\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /** The remote parent now; a move settlement queues cites it as previous. */\n supersededMovePreviousParentId?: string | undefined;\n /**\n * The parent the create committed under. A desired parent equal to it, or\n * to the current one, owes no move: the user never moved the folder away,\n * and a later remote move by another writer stands.\n */\n createdParentContainerId?: string | undefined;\n /** The parent the settled intent wants. */\n desiredParentContainerId?: string | undefined;\n}\n\nexport interface LocalRootDescendantReparentInput {\n containerId: string;\n parentContainerId: string | null;\n updateCreateIntent?: boolean | undefined;\n}\n\n/**\n * A container's metadata document record plus its durable content: the full\n * Loro updates export of the metadata document, stored in the shared\n * history-checkpoint table under the container-metadata app kind. Metadata\n * documents are tiny registries, so the whole update log is the checkpoint.\n */\nexport interface ContainerMetadataRecord extends DocumentRecord {\n metadataUpdates: string;\n}\n\nexport interface StoredContainerState {\n container: ContainerRecord;\n record: ContainerMetadataRecord | null;\n}\n\nexport interface ContainerRemoval {\n containerId: string;\n reason: \"access_revoked\" | \"deleted\";\n updatedAt: string;\n}\n\nexport interface ContainerHydrationTombstone extends ContainerRemoval {\n generation: number;\n}\n\nexport interface ContainerDeletionGuard {\n /** A fresh container read denied access after the listing returned. */\n confirmedAccessLoss?: {\n placementHash: string | null;\n expectedMetadata: Pick<\n ContainerMetadataRecord,\n \"documentId\" | \"accessEpoch\" | \"accessStateHash\" | \"metadataUpdates\"\n > | null;\n };\n containerId: string;\n expectedContainer: ContainerRecord | null;\n}\n\nexport interface SaveContainerOptions {\n verifiedPlacement?: AccessManifestCheckpoint | undefined;\n createIntent?: ContainerCreateIntentInput;\n stillCurrent?: (() => boolean) | undefined;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n}\n\nexport interface SaveContainerWithPendingUpdateOptions\n extends SaveContainerOptions {\n pendingUpdate: PendingUpdateFields;\n}\n\nexport interface ContainerContentsPersistence\n extends DormantMetadataSweepPersistence,\n ContainerMetadataRevalidationPersistence {\n containerExists: (execSql: ExecSql, containerId: string) => Promise<boolean>;\n /**\n * Create an absent remotely hydrated container only when no newer durable\n * tombstone or concurrent container/dormant-metadata mutation won first.\n */\n commitHydratedContainer: (\n execSql: ExecSql,\n input: {\n container: ContainerRecord;\n expectedDormantRecord: ContainerMetadataRecord | null;\n /** Tombstone observed before the remote request began, or null. */\n expectedHydrationTombstone?:\n | ContainerHydrationTombstone\n | null\n | undefined;\n /** Current placement verified and pinned before recovery insertion. */\n expectedPlacementCheckpoint?: AccessManifestCheckpoint | undefined;\n record: ContainerMetadataRecord;\n remoteUpdatedAt: string;\n saveOptions: {\n localUpdatedAt?: string;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n { committed: true; container: ContainerRecord } | { committed: false }\n >;\n /** Capture anti-resurrection fences immediately before a remote fetch. */\n loadContainerHydrationTombstones: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<ContainerHydrationTombstone>>;\n deleteContainer: (\n execSql: ExecSql,\n containerId: string,\n options?: {\n reason?: ContainerRemoval[\"reason\"];\n updatedAt?: string;\n },\n ) => Promise<void>;\n deleteContainers: (\n execSql: ExecSql,\n removals: ReadonlyArray<ContainerRemoval>,\n options?: {\n /** Must run inside the deletion transaction before any row is removed. */\n beforeDeleteInTransaction?:\n | ((transactionExecSql: ExecSql) => Promise<boolean>)\n | undefined;\n /** Unsigned discovery removes listings but preserves metadata and local intent. */\n discoveryOnly?: boolean;\n /**\n * Request-time states rechecked inside the deletion transaction. An\n * absent or changed row means another pane won and aborts the cascade.\n */\n expectedContainers?: ReadonlyArray<ContainerDeletionGuard>;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ReadonlyArray<string>>;\n deletePendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n enqueuePendingUpdate: (\n execSql: ExecSql,\n input: PendingUpdateFields & { containerId: string },\n ) => Promise<string>;\n listPendingCreateIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerCreateIntentRecord[]>;\n // Every move intent that has not yet synced, regardless of syncStatus —\n // a blocked move (destination parent not synced yet) is still unsynced, and\n // synced moves are deleted (see markMoveIntentRevisionSynced), so every surviving\n // row qualifies. Blocked intents replay too: \"blocked\" names the reason the\n // last attempt could not proceed, not a terminal verdict.\n listUnsyncedMoveIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerMoveIntentRecord[]>;\n listContainerIdsWithPendingUpdates: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listContainerIdsWithPullContinuations: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listPendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n /** Revision-CAS error recorder used by asynchronous create replay. */\n recordCreateIntentRevisionError: ContainerCreateIntentErrorInputRecorder;\n recordMoveIntentError: (\n execSql: ExecSql,\n input: {\n blocked?: boolean | undefined;\n containerId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<void>;\n reassignContainerDocuments: (\n execSql: ExecSql,\n input: {\n fromContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n toContainerId: string;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalRootContainer: (\n execSql: ExecSql,\n input: {\n descendantReparents: ReadonlyArray<LocalRootDescendantReparentInput>;\n localRootContainerId: string;\n remoteOrganizationId: string;\n remoteRootContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalSystemContainer: (\n execSql: ExecSql,\n input: {\n localContainerId: string;\n remoteContainerId: string;\n remoteOrganizationId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n loadContainers: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<StoredContainerState>>;\n loadContainerMetadataState: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<StoredContainerState | null>;\n /**\n * The organization and metadata target this device holds for a container,\n * from its live row or retained dormant metadata; null when never held.\n */\n loadHeldContainerBinding: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<HeldContainerBinding | null>;\n /** Whether a held folder was re-homed away from this organization. */\n isSupersededContainerBinding: (\n execSql: ExecSql,\n input: { containerId: string; organizationId: string },\n ) => Promise<boolean>;\n /**\n * Move a held folder to the binding its own user re-created it under,\n * resetting the metadata record's remote stream; false if the held binding\n * changed since it was read.\n */\n rebindHeldContainer: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expected: HeldContainerBinding;\n next: { metadataDocumentId: string; organizationId: string };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<boolean>;\n /**\n * Load a container-metadata record by container id alone, without\n * requiring a containers row — the dormant shape row 4's access_revoked\n * branch leaves behind, re-attached on rehydration.\n */\n loadContainerMetadataRecord: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Atomically replace the exact rejected metadata pull continuation with its\n * durable recovery marker and return the authoritative current record.\n */\n invalidateMetadataPullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n containerId: string;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Conditionally commit metadata content, its outgoing row, accepted queue\n * settlement, container fields, and the canonical record in one transaction.\n */\n commitMetadataMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n clearSyncFailure?: boolean | undefined;\n container: ContainerRecord;\n expectedContainer: ContainerRecord;\n expectedRecord: ContainerMetadataRecord;\n createIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /**\n * When present, an overtaking create revision is adopted as the\n * desired local parent and converted to a move from this remotely\n * committed parent instead of rejecting the remote identity.\n */\n supersededMovePreviousParentId?: string | undefined;\n }\n | undefined;\n moveIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n }\n | undefined;\n /** Present only for an explicit local primary change; null clears it. */\n primaryDocumentId?: string | null | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n preserveDurableStructureWhenPending?: boolean | undefined;\n record: ContainerMetadataRecord;\n saveOptions?: Omit<SaveContainerOptions, \"stillCurrent\"> | undefined;\n settleAcceptedPendingOnConflict: boolean;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n | {\n committed: true;\n container: ContainerRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | {\n committed: false;\n currentState: StoredContainerState | null;\n staleServerState?: true;\n }\n >;\n settleAcceptedMetadataPendingUpdates: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expectedRecord: ContainerMetadataRecord;\n pendingUpdateIds: readonly string[];\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<StoredContainerState | null>;\n saveContainer: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord | null,\n options?: SaveContainerOptions,\n ) => Promise<ContainerRecord>;\n /**\n * Atomically saves a container and enqueues its first metadata update.\n * Host adapters must implement the compound write in their own transaction.\n */\n saveContainerWithPendingUpdate: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n options: SaveContainerWithPendingUpdateOptions,\n ) => Promise<ContainerRecord>;\n saveContainerAndDeletePendingUpdates: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n pendingUpdateIds: readonly string[],\n ) => Promise<ContainerRecord>;\n /**\n * Revision-CAS settlement used by asynchronous create replay. Invalid\n * adapters are rejected before the remote mutation begins.\n */\n markCreateIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Explicit revision-CAS settlement. Move replay instead settles inside\n * commitMetadataMutation and requires its atomic acknowledgment.\n */\n markMoveIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Drop a move revision the server refuses for good and restore the\n * folder's previous parent in the same transaction; false if superseded.\n */\n abandonMoveIntentRevision: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput & {\n previousParentContainerId: string;\n },\n ) => Promise<boolean>;\n}\n"]}
|
|
@@ -8,6 +8,7 @@ import { ensureDocumentProjectionTables } from "../documents/records/index.js";
|
|
|
8
8
|
import { recordContainerHydrationTombstones } from "./containerHydrationPersistence.js";
|
|
9
9
|
import { deleteContainerRowsInTransaction, ensureContainerTables, } from "./containerPersistence.js";
|
|
10
10
|
import { containerRemovalBatches } from "./containerRemovalBatches.js";
|
|
11
|
+
import { confirmedRemovalMetadataMatches } from "./containerRemovalMetadata.js";
|
|
11
12
|
import { containerIdsWithRemovalWork } from "./containerRemovalWork.js";
|
|
12
13
|
import { repairDocumentsForRemovedContainersInTransaction } from "./containerStructuralRepair.js";
|
|
13
14
|
import { deleteContainerWatermarksInTransaction } from "./containerSyncWatermarkPersistence.js";
|
|
@@ -55,6 +56,8 @@ function sameGuardedContainerRow(row, guard) {
|
|
|
55
56
|
row.serverUpdatedAt === (expected.serverUpdatedAt ?? null));
|
|
56
57
|
}
|
|
57
58
|
async function canApplyContainerRemovals(input) {
|
|
59
|
+
if (!(await confirmedRemovalMetadataMatches(input.tx, input.expectedContainers ?? [])))
|
|
60
|
+
return false;
|
|
58
61
|
const currentRows = [];
|
|
59
62
|
for (const batch of containerRemovalBatches(input.removals)) {
|
|
60
63
|
currentRows.push(...(await loadGuardedContainerRows(input.tx, batch.map((removal) => removal.containerId))));
|
|
@@ -65,7 +68,8 @@ async function canApplyContainerRemovals(input) {
|
|
|
65
68
|
const currentRow = currentRowById.get(removal.containerId);
|
|
66
69
|
const guard = guardById.get(removal.containerId);
|
|
67
70
|
return ((!guard || sameGuardedContainerRow(currentRow, guard)) &&
|
|
68
|
-
(
|
|
71
|
+
(guard?.confirmedAccessLoss ||
|
|
72
|
+
currentRow?.serverUpdatedAt == null ||
|
|
69
73
|
currentRow.serverUpdatedAt <= removal.updatedAt));
|
|
70
74
|
});
|
|
71
75
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerDeletionPersistence.js","sourceRoot":"","sources":["containerDeletionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,UAAU,EACV,6BAA6B,EAC7B,sBAAsB,EACtB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EAAE,iCAAiC,EAAE,MAAM,8CAA8C,CAAC;AACjG,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAMtE,OAAO,EAAE,kCAAkC,E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C,EAAE,CAAC;oBAC5D,mBAAmB,CAAC,IAAI,CACtB,GAAG,CAAC,MAAM,2BAA2B,CACnC,EAAE,EACF,KAAK,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,WAAW,CAAC,CAC5C,CAAC,CACH,CAAC;gBACJ,CAAC;YACH,CAAC;YACD,OAAO,sBAAsB,CAAC;gBAC5B,aAAa,EAAE,OAAO,EAAE,aAAa;gBACrC,iBAAiB,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CACpD,mBAAmB,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC;oBAC/C,CAAC,CAAC,EAAE;oBACJ,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,CAC1B;gBACD,QAAQ,EAAE,cAAc;gBACxB,mBAAmB;gBACnB,EAAE;aACH,CAAC,CAAC;QACL,CAAC,CAAC;QACF,IAAI,CAAC,OAAO,EAAE,YAAY,EAAE,CAAC;YAC3B,OAAO,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;QAChE,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,MAAM,EACN,OAAO,CAAC,YAAY,EACpB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACF,OAAO,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;IAC9B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, inArray } from \"drizzle-orm\";\nimport {\n containers,\n documentPlacementIntentTables,\n inContainerIntentLanes,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { containerSyncWatermarkTables } from \"../../sqlite/schema/containerSyncWatermarkSchema\";\nimport { documentContainerProjectionTables } from \"../../sqlite/schema/documentProjectionSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { ensureDocumentProjectionTables } from \"../documents/records\";\nimport type {\n ContainerContentsPersistence,\n ContainerDeletionGuard,\n ContainerRemoval,\n} from \"./containerContentsPersistenceTypes\";\nimport { recordContainerHydrationTombstones } from \"./containerHydrationPersistence\";\nimport {\n deleteContainerRowsInTransaction,\n ensureContainerTables,\n} from \"./containerPersistence\";\nimport { containerRemovalBatches } from \"./containerRemovalBatches\";\nimport { containerIdsWithRemovalWork } from \"./containerRemovalWork\";\nimport { repairDocumentsForRemovedContainersInTransaction } from \"./containerStructuralRepair\";\nimport { deleteContainerWatermarksInTransaction } from \"./containerSyncWatermarkPersistence\";\nimport {\n refreshPlacementIntentsAfterRemoval,\n repairLinkIntentsForRemovedContainers,\n} from \"./documentLinkRemovalRepair\";\nimport {\n deleteContainerMetadataDocumentRowsInTransaction,\n retainDormantContainerMetadataInTransaction,\n} from \"./dormantContainerMetadata\";\n\ntype DeleteContainerOptions = NonNullable<\n Parameters<ContainerContentsPersistence[\"deleteContainers\"]>[2]\n>;\n\nfunction normalizeContainerRemovals(\n removals: ReadonlyArray<ContainerRemoval>,\n): ContainerRemoval[] {\n const removalByContainerId = new Map<string, ContainerRemoval>();\n for (const removal of removals) {\n const current = removalByContainerId.get(removal.containerId);\n if (\n !current ||\n (current.reason === \"access_revoked\" && removal.reason === \"deleted\") ||\n (current.reason === removal.reason &&\n current.updatedAt < removal.updatedAt)\n ) {\n removalByContainerId.set(removal.containerId, removal);\n }\n }\n return Array.from(removalByContainerId.values());\n}\n\nfunction loadGuardedContainerRows(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n) {\n return tx\n .select({\n effectiveAccessLevel: containers.effectiveAccessLevel,\n id: containers.id,\n metadataDocumentId: containers.metadataDocumentId,\n organizationId: containers.organizationId,\n parentId: containers.parentId,\n serverCreatedAt: containers.serverCreatedAt,\n serverUpdatedAt: containers.serverUpdatedAt,\n systemSlot: containers.systemSlot,\n })\n .from(containers)\n .where(inArray(containers.id, [...containerIds]));\n}\n\ntype GuardedContainerRow = Awaited<\n ReturnType<typeof loadGuardedContainerRows>\n>[number];\n\nfunction sameGuardedContainerRow(\n row: GuardedContainerRow | undefined,\n guard: ContainerDeletionGuard,\n): boolean {\n const expected = guard.expectedContainer;\n if (!row || !expected) return row === undefined && expected === null;\n return (\n row.id === expected.id &&\n row.organizationId === expected.organizationId &&\n row.parentId === expected.parentId &&\n row.metadataDocumentId === expected.metadataDocumentId &&\n row.systemSlot === (expected.systemSlot ?? null) &&\n row.effectiveAccessLevel === (expected.effectiveAccessLevel ?? \"read\") &&\n row.serverCreatedAt === (expected.serverCreatedAt ?? null) &&\n row.serverUpdatedAt === (expected.serverUpdatedAt ?? null)\n );\n}\n\nasync function canApplyContainerRemovals(input: {\n expectedContainers: DeleteContainerOptions[\"expectedContainers\"];\n removals: ReadonlyArray<ContainerRemoval>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const currentRows: GuardedContainerRow[] = [];\n for (const batch of containerRemovalBatches(input.removals)) {\n currentRows.push(\n ...(await loadGuardedContainerRows(\n input.tx,\n batch.map((removal) => removal.containerId),\n )),\n );\n }\n const currentRowById = new Map(\n currentRows.flatMap((row) => (row.id ? ([[row.id, row]] as const) : [])),\n );\n const guardById = new Map(\n input.expectedContainers?.map((guard) => [guard.containerId, guard]) ?? [],\n );\n return input.removals.every((removal) => {\n const currentRow = currentRowById.get(removal.containerId);\n const guard = guardById.get(removal.containerId);\n return (\n (!guard || sameGuardedContainerRow(currentRow, guard)) &&\n (currentRow?.serverUpdatedAt == null ||\n currentRow.serverUpdatedAt <= removal.updatedAt)\n );\n });\n}\n\nasync function retainRemovedContainerMetadata(input: {\n containerIds: ReadonlyArray<string>;\n retainedAt: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n if (input.containerIds.length === 0) return;\n const retainedContainers = await input.tx\n .select({\n containerId: containers.id,\n organizationId: containers.organizationId,\n })\n .from(containers)\n .where(inArray(containers.id, [...input.containerIds]));\n await retainDormantContainerMetadataInTransaction(\n input.tx,\n retainedContainers.flatMap((container) =>\n container.containerId\n ? [\n {\n containerId: container.containerId,\n organizationId: container.organizationId,\n retainedAt: input.retainedAt,\n },\n ]\n : [],\n ),\n );\n}\n\nasync function applyContainerRemovals(input: {\n discoveryOnly: DeleteContainerOptions[\"discoveryOnly\"];\n metadataDeleteIds: ReadonlyArray<string>;\n removals: ReadonlyArray<ContainerRemoval>;\n retainedMetadataIds: ReadonlyArray<string>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<ReadonlyArray<string>> {\n const containerIds = input.removals.map((removal) => removal.containerId);\n await recordContainerHydrationTombstones({\n removals: input.removals,\n tx: input.tx,\n });\n const retainedAt = new Date().toISOString();\n for (const batch of containerRemovalBatches(input.retainedMetadataIds)) {\n await retainRemovedContainerMetadata({\n containerIds: batch,\n retainedAt,\n tx: input.tx,\n });\n }\n // Listing clocks are untrusted; they cannot advance local projection clocks.\n const localObservedAt = new Date().toISOString();\n await repairDocumentsForRemovedContainersInTransaction({\n removals: input.discoveryOnly\n ? input.removals.map((removal) => ({\n ...removal,\n updatedAt: localObservedAt,\n }))\n : input.removals,\n tx: input.tx,\n });\n if (input.discoveryOnly) {\n await refreshPlacementIntentsAfterRemoval({ containerIds, tx: input.tx });\n } else {\n await repairLinkIntentsForRemovedContainers({ containerIds, tx: input.tx });\n for (const batch of containerRemovalBatches(containerIds)) {\n await input.tx\n .delete(localIntents)\n .where(\n and(inContainerIntentLanes(), inArray(localIntents.subjectId, batch)),\n )\n .run();\n }\n }\n for (const batch of containerRemovalBatches(containerIds)) {\n await deleteContainerRowsInTransaction(input.tx, batch);\n }\n for (const batch of containerRemovalBatches(input.metadataDeleteIds)) {\n await deleteContainerMetadataDocumentRowsInTransaction(input.tx, batch);\n }\n for (const batch of containerRemovalBatches(containerIds)) {\n await deleteContainerWatermarksInTransaction(input.tx, batch);\n }\n return containerIds;\n}\n\nexport async function deleteStoredContainers(\n execSql: Parameters<ContainerContentsPersistence[\"deleteContainers\"]>[0],\n removals: Parameters<ContainerContentsPersistence[\"deleteContainers\"]>[1],\n options?: Parameters<ContainerContentsPersistence[\"deleteContainers\"]>[2],\n): Promise<ReadonlyArray<string>> {\n const uniqueRemovals = normalizeContainerRemovals(removals);\n if (uniqueRemovals.length === 0) return [];\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentContainerProjectionTables);\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n await ensureContainerTables(lockedExecSql);\n await ensureDocumentProjectionTables(lockedExecSql);\n await ensureSqlTables(lockedExecSql, containerSyncWatermarkTables);\n const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);\n const remove = async (tx: ClientSQLiteTransactionScope) => {\n if (\n options?.beforeDeleteInTransaction &&\n !(await options.beforeDeleteInTransaction(lockedExecSql))\n )\n return [];\n if (\n !(await canApplyContainerRemovals({\n expectedContainers: options?.expectedContainers,\n removals: uniqueRemovals,\n tx,\n }))\n ) {\n return [];\n }\n const retainedMetadataIds: string[] = [];\n if (options?.discoveryOnly) {\n for (const batch of containerRemovalBatches(uniqueRemovals)) {\n retainedMetadataIds.push(\n ...(await containerIdsWithRemovalWork(\n tx,\n batch.map((removal) => removal.containerId),\n )),\n );\n }\n }\n return applyContainerRemovals({\n discoveryOnly: options?.discoveryOnly,\n metadataDeleteIds: uniqueRemovals.flatMap((removal) =>\n retainedMetadataIds.includes(removal.containerId)\n ? []\n : [removal.containerId],\n ),\n removals: uniqueRemovals,\n retainedMetadataIds,\n tx,\n });\n };\n if (!options?.stillCurrent) {\n return runtime.transaction(remove, { behavior: \"immediate\" });\n }\n const outcome = await runtime.guardedTransaction(\n remove,\n options.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.result ?? [];\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerDeletionPersistence.js","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cAAc;gBACxB,mBAAmB;gBACnB,EAAE;aACH,CAAC,CAAC;QACL,CAAC,CAAC;QACF,IAAI,CAAC,OAAO,EAAE,YAAY,EAAE,CAAC;YAC3B,OAAO,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;QAChE,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,MAAM,EACN,OAAO,CAAC,YAAY,EACpB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACF,OAAO,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;IAC9B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, inArray } from \"drizzle-orm\";\nimport {\n containers,\n documentPlacementIntentTables,\n inContainerIntentLanes,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { containerSyncWatermarkTables } from \"../../sqlite/schema/containerSyncWatermarkSchema\";\nimport { documentContainerProjectionTables } from \"../../sqlite/schema/documentProjectionSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { ensureDocumentProjectionTables } from \"../documents/records\";\nimport type {\n ContainerContentsPersistence,\n ContainerDeletionGuard,\n ContainerRemoval,\n} from \"./containerContentsPersistenceTypes\";\nimport { recordContainerHydrationTombstones } from \"./containerHydrationPersistence\";\nimport {\n deleteContainerRowsInTransaction,\n ensureContainerTables,\n} from \"./containerPersistence\";\nimport { containerRemovalBatches } from \"./containerRemovalBatches\";\nimport { confirmedRemovalMetadataMatches } from \"./containerRemovalMetadata\";\nimport { containerIdsWithRemovalWork } from \"./containerRemovalWork\";\nimport { repairDocumentsForRemovedContainersInTransaction } from \"./containerStructuralRepair\";\nimport { deleteContainerWatermarksInTransaction } from \"./containerSyncWatermarkPersistence\";\nimport {\n refreshPlacementIntentsAfterRemoval,\n repairLinkIntentsForRemovedContainers,\n} from \"./documentLinkRemovalRepair\";\nimport {\n deleteContainerMetadataDocumentRowsInTransaction,\n retainDormantContainerMetadataInTransaction,\n} from \"./dormantContainerMetadata\";\n\ntype DeleteContainerOptions = NonNullable<\n Parameters<ContainerContentsPersistence[\"deleteContainers\"]>[2]\n>;\n\nfunction normalizeContainerRemovals(\n removals: ReadonlyArray<ContainerRemoval>,\n): ContainerRemoval[] {\n const removalByContainerId = new Map<string, ContainerRemoval>();\n for (const removal of removals) {\n const current = removalByContainerId.get(removal.containerId);\n if (\n !current ||\n (current.reason === \"access_revoked\" && removal.reason === \"deleted\") ||\n (current.reason === removal.reason &&\n current.updatedAt < removal.updatedAt)\n ) {\n removalByContainerId.set(removal.containerId, removal);\n }\n }\n return Array.from(removalByContainerId.values());\n}\n\nfunction loadGuardedContainerRows(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n) {\n return tx\n .select({\n effectiveAccessLevel: containers.effectiveAccessLevel,\n id: containers.id,\n metadataDocumentId: containers.metadataDocumentId,\n organizationId: containers.organizationId,\n parentId: containers.parentId,\n serverCreatedAt: containers.serverCreatedAt,\n serverUpdatedAt: containers.serverUpdatedAt,\n systemSlot: containers.systemSlot,\n })\n .from(containers)\n .where(inArray(containers.id, [...containerIds]));\n}\n\ntype GuardedContainerRow = Awaited<\n ReturnType<typeof loadGuardedContainerRows>\n>[number];\n\nfunction sameGuardedContainerRow(\n row: GuardedContainerRow | undefined,\n guard: ContainerDeletionGuard,\n): boolean {\n const expected = guard.expectedContainer;\n if (!row || !expected) return row === undefined && expected === null;\n return (\n row.id === expected.id &&\n row.organizationId === expected.organizationId &&\n row.parentId === expected.parentId &&\n row.metadataDocumentId === expected.metadataDocumentId &&\n row.systemSlot === (expected.systemSlot ?? null) &&\n row.effectiveAccessLevel === (expected.effectiveAccessLevel ?? \"read\") &&\n row.serverCreatedAt === (expected.serverCreatedAt ?? null) &&\n row.serverUpdatedAt === (expected.serverUpdatedAt ?? null)\n );\n}\n\nasync function canApplyContainerRemovals(input: {\n expectedContainers: DeleteContainerOptions[\"expectedContainers\"];\n removals: ReadonlyArray<ContainerRemoval>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n if (\n !(await confirmedRemovalMetadataMatches(\n input.tx,\n input.expectedContainers ?? [],\n ))\n )\n return false;\n const currentRows: GuardedContainerRow[] = [];\n for (const batch of containerRemovalBatches(input.removals)) {\n currentRows.push(\n ...(await loadGuardedContainerRows(\n input.tx,\n batch.map((removal) => removal.containerId),\n )),\n );\n }\n const currentRowById = new Map(\n currentRows.flatMap((row) => (row.id ? ([[row.id, row]] as const) : [])),\n );\n const guardById = new Map(\n input.expectedContainers?.map((guard) => [guard.containerId, guard]) ?? [],\n );\n return input.removals.every((removal) => {\n const currentRow = currentRowById.get(removal.containerId);\n const guard = guardById.get(removal.containerId);\n return (\n (!guard || sameGuardedContainerRow(currentRow, guard)) &&\n (guard?.confirmedAccessLoss ||\n currentRow?.serverUpdatedAt == null ||\n currentRow.serverUpdatedAt <= removal.updatedAt)\n );\n });\n}\n\nasync function retainRemovedContainerMetadata(input: {\n containerIds: ReadonlyArray<string>;\n retainedAt: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n if (input.containerIds.length === 0) return;\n const retainedContainers = await input.tx\n .select({\n containerId: containers.id,\n organizationId: containers.organizationId,\n })\n .from(containers)\n .where(inArray(containers.id, [...input.containerIds]));\n await retainDormantContainerMetadataInTransaction(\n input.tx,\n retainedContainers.flatMap((container) =>\n container.containerId\n ? [\n {\n containerId: container.containerId,\n organizationId: container.organizationId,\n retainedAt: input.retainedAt,\n },\n ]\n : [],\n ),\n );\n}\n\nasync function applyContainerRemovals(input: {\n discoveryOnly: DeleteContainerOptions[\"discoveryOnly\"];\n metadataDeleteIds: ReadonlyArray<string>;\n removals: ReadonlyArray<ContainerRemoval>;\n retainedMetadataIds: ReadonlyArray<string>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<ReadonlyArray<string>> {\n const containerIds = input.removals.map((removal) => removal.containerId);\n await recordContainerHydrationTombstones({\n removals: input.removals,\n tx: input.tx,\n });\n const retainedAt = new Date().toISOString();\n for (const batch of containerRemovalBatches(input.retainedMetadataIds)) {\n await retainRemovedContainerMetadata({\n containerIds: batch,\n retainedAt,\n tx: input.tx,\n });\n }\n // Listing clocks are untrusted; they cannot advance local projection clocks.\n const localObservedAt = new Date().toISOString();\n await repairDocumentsForRemovedContainersInTransaction({\n removals: input.discoveryOnly\n ? input.removals.map((removal) => ({\n ...removal,\n updatedAt: localObservedAt,\n }))\n : input.removals,\n tx: input.tx,\n });\n if (input.discoveryOnly) {\n await refreshPlacementIntentsAfterRemoval({ containerIds, tx: input.tx });\n } else {\n await repairLinkIntentsForRemovedContainers({ containerIds, tx: input.tx });\n for (const batch of containerRemovalBatches(containerIds)) {\n await input.tx\n .delete(localIntents)\n .where(\n and(inContainerIntentLanes(), inArray(localIntents.subjectId, batch)),\n )\n .run();\n }\n }\n for (const batch of containerRemovalBatches(containerIds)) {\n await deleteContainerRowsInTransaction(input.tx, batch);\n }\n for (const batch of containerRemovalBatches(input.metadataDeleteIds)) {\n await deleteContainerMetadataDocumentRowsInTransaction(input.tx, batch);\n }\n for (const batch of containerRemovalBatches(containerIds)) {\n await deleteContainerWatermarksInTransaction(input.tx, batch);\n }\n return containerIds;\n}\n\nexport async function deleteStoredContainers(\n execSql: Parameters<ContainerContentsPersistence[\"deleteContainers\"]>[0],\n removals: Parameters<ContainerContentsPersistence[\"deleteContainers\"]>[1],\n options?: Parameters<ContainerContentsPersistence[\"deleteContainers\"]>[2],\n): Promise<ReadonlyArray<string>> {\n const uniqueRemovals = normalizeContainerRemovals(removals);\n if (uniqueRemovals.length === 0) return [];\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentContainerProjectionTables);\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n await ensureContainerTables(lockedExecSql);\n await ensureDocumentProjectionTables(lockedExecSql);\n await ensureSqlTables(lockedExecSql, containerSyncWatermarkTables);\n const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);\n const remove = async (tx: ClientSQLiteTransactionScope) => {\n if (\n options?.beforeDeleteInTransaction &&\n !(await options.beforeDeleteInTransaction(lockedExecSql))\n )\n return [];\n if (\n !(await canApplyContainerRemovals({\n expectedContainers: options?.expectedContainers,\n removals: uniqueRemovals,\n tx,\n }))\n ) {\n return [];\n }\n const retainedMetadataIds: string[] = [];\n if (options?.discoveryOnly) {\n for (const batch of containerRemovalBatches(uniqueRemovals)) {\n retainedMetadataIds.push(\n ...(await containerIdsWithRemovalWork(\n tx,\n batch.map((removal) => removal.containerId),\n )),\n );\n }\n }\n return applyContainerRemovals({\n discoveryOnly: options?.discoveryOnly,\n metadataDeleteIds: uniqueRemovals.flatMap((removal) =>\n retainedMetadataIds.includes(removal.containerId)\n ? []\n : [removal.containerId],\n ),\n removals: uniqueRemovals,\n retainedMetadataIds,\n tx,\n });\n };\n if (!options?.stillCurrent) {\n return runtime.transaction(remove, { behavior: \"immediate\" });\n }\n const outcome = await runtime.guardedTransaction(\n remove,\n options.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.result ?? [];\n });\n}\n"]}
|
|
@@ -65,7 +65,7 @@ export async function recordContainerHydrationTombstones(input) {
|
|
|
65
65
|
.run();
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
async function placementCheckpointMatches(tx, input) {
|
|
68
|
+
export async function placementCheckpointMatches(tx, input) {
|
|
69
69
|
const expected = input.expectedPlacementCheckpoint;
|
|
70
70
|
if (!expected)
|
|
71
71
|
return true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerHydrationPersistence.js","sourceRoot":"","sources":["containerHydrationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,O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AuB,CAC/B,iBAAiB,EACjB,oDAAoD,CACrD,CAAC;YACJ,CAAC;YACD,wEAAwE;YACxE,wEAAwE;YACxE,MAAM,qBAAqB,GAAG,MAAM,yBAAyB,CAC3D,aAAa,EACb,KAAK,CAAC,SAAS,CAAC,EAAE,CACnB,CAAC;YACF,0BAA0B,CACxB;gBACE,cAAc,EAAE,qBAAqB,IAAI,EAAE;gBAC3C,kBAAkB,EAAE,oBAAoB,EAAE,UAAU,IAAI,IAAI;aAC7D,EACD;gBACE,cAAc,EAAE,KAAK,CAAC,SAAS,CAAC,cAAc;gBAC9C,mBAAmB,EAAE;oBACnB,KAAK,CAAC,SAAS,CAAC,kBAAkB;oBAClC,KAAK,CAAC,MAAM,CAAC,UAAU;iBACxB;aACF,CACF,CAAC;YAEF,MAAM,SAAS,GAAG,MAAM,sBAAsB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;YAC1D,MAAM,2BAA2B,CAAC,EAAE,EAAE,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;YACjE,OAAO,EAAE,SAAS,EAAE,IAAa,EAAE,SAAS,EAAE,CAAC;QACjD,CAAC,CAAC;QACF,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC;YACxB,OAAO,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;QAChE,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,MAAM,EACN,KAAK,CAAC,YAAY,EAClB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACF,OAAO,OAAO,CAAC,MAAM,IAAI,EAAE,SAAS,EAAE,KAAc,EAAE,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { and, eq, inArray, sql } from \"drizzle-orm\";\nimport { documentSyncPullContinuationsEqual } from \"../../documents/shared/sync/pullContinuation\";\nimport {\n containerHydrationTombstones,\n containers,\n dormantContainerMetadata,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { loadStoredAccessManifestCheckpoint } from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n assertHeldContainerBinding,\n type HeldContainerBinding,\n heldContainerBinding,\n} from \"./containerBinding\";\nimport type {\n ContainerContentsPersistence,\n ContainerHydrationTombstone,\n ContainerMetadataRecord,\n} from \"./containerContentsPersistenceTypes\";\nimport {\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n} from \"./containerMetadataRows\";\nimport { loadContainerById } from \"./containerPersistence\";\nimport { containerRemovalBatches } from \"./containerRemovalBatches\";\nimport { isSupersededContainerBinding } from \"./supersededContainerBindings\";\n\nfunction sameNullableValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\nfunction sameMetadataRecord(\n current: ContainerMetadataRecord | null,\n expected: ContainerMetadataRecord | null,\n): boolean {\n if (!current || !expected) return current === expected;\n return (\n current.id === expected.id &&\n current.documentId === expected.documentId &&\n current.accessEpoch === expected.accessEpoch &&\n sameNullableValue(current.accessStateHash, expected.accessStateHash) &&\n sameNullableValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n sameNullableValue(current.contentKeyBundle, expected.contentKeyBundle) &&\n sameNullableValue(\n current.documentKekTargets,\n expected.documentKekTargets,\n ) &&\n sameNullableValue(\n current.documentManifestBundle,\n expected.documentManifestBundle,\n ) &&\n current.metadataUpdates === expected.metadataUpdates &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired)\n );\n}\n\nfunction sameHydrationTombstone(\n current:\n | { generation: number; reason: string; updatedAt: string }\n | undefined,\n expected: ContainerHydrationTombstone | null | undefined,\n): boolean {\n return (\n current !== undefined &&\n expected != null &&\n current.generation === expected.generation &&\n current.reason === expected.reason &&\n current.updatedAt === expected.updatedAt\n );\n}\n\n/** The fence and dormant record still match what the caller observed. */\nfunction observedRecoveryStateHeld(\n fence: Parameters<typeof sameHydrationTombstone>[0],\n currentDormantRecord: ContainerMetadataRecord | null,\n expected: {\n readonly expectedDormantRecord: ContainerMetadataRecord | null;\n readonly expectedHydrationTombstone?:\n | ContainerHydrationTombstone\n | null\n | undefined;\n },\n): boolean {\n if (\n fence &&\n !sameHydrationTombstone(fence, expected.expectedHydrationTombstone)\n ) {\n return false;\n }\n return sameMetadataRecord(\n currentDormantRecord,\n expected.expectedDormantRecord,\n );\n}\n\nexport async function recordContainerHydrationTombstones(input: {\n removals: ReadonlyArray<{\n containerId: string;\n reason: \"access_revoked\" | \"deleted\";\n updatedAt: string;\n }>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const batch of containerRemovalBatches(input.removals)) {\n await input.tx\n .insert(containerHydrationTombstones)\n .values([...batch])\n .onConflictDoUpdate({\n target: containerHydrationTombstones.containerId,\n set: {\n generation: sql`${containerHydrationTombstones.generation} + 1`,\n cleared: false,\n reason: sql`CASE\n WHEN ${containerHydrationTombstones.reason} = 'deleted' THEN 'deleted'\n ELSE excluded.reason\n END`,\n updatedAt: sql`MAX(${containerHydrationTombstones.updatedAt}, excluded.updated_at)`,\n },\n })\n .run();\n }\n}\n\nasync function placementCheckpointMatches(\n tx: ClientSQLiteTransactionScope,\n input: Parameters<ContainerContentsPersistence[\"commitHydratedContainer\"]>[1],\n): Promise<boolean> {\n const expected = input.expectedPlacementCheckpoint;\n if (!expected) return true;\n const current = await loadStoredAccessManifestCheckpoint(tx, expected);\n return (\n expected.objectKind === \"container\" &&\n expected.objectId === input.container.id &&\n expected.organizationId === input.container.organizationId &&\n current?.epoch === expected.epoch &&\n current.manifestHash === expected.manifestHash\n );\n}\n\n/** A retained local move continues to own placement after verified reattachment. */\nasync function saveRecoveredContainer(\n tx: ClientSQLiteTransactionScope,\n input: Parameters<ContainerContentsPersistence[\"commitHydratedContainer\"]>[1],\n) {\n const [move] = await tx\n .select({\n parentContainerId: localIntents.targetContainerId,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.container.id),\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n ),\n )\n .limit(1);\n return saveContainerContentsContainerRows({\n container: move\n ? { ...input.container, parentId: move.parentContainerId }\n : input.container,\n localUpdatedAt:\n move?.updatedAt ??\n input.saveOptions.localUpdatedAt ??\n input.remoteUpdatedAt,\n record: input.record,\n serverTimestamps: input.saveOptions.serverTimestamps,\n tx,\n });\n}\n\nasync function loadDormantOrganizationId(\n execSql: ExecSql,\n containerId: string,\n): Promise<string | null> {\n const [row] = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({ organizationId: dormantContainerMetadata.organizationId })\n .from(dormantContainerMetadata)\n .where(eq(dormantContainerMetadata.containerId, containerId))\n .limit(1);\n return row?.organizationId ?? null;\n}\n\n/**\n * The binding this device holds for a container id: its live row, or the\n * organization and metadata target retained after access loss. Null when the\n * device has never held the container.\n */\nexport async function loadStoredHeldContainerBinding(\n execSql: ExecSql,\n containerId: string,\n): Promise<HeldContainerBinding | null> {\n const container = await loadContainerById(execSql, containerId);\n const record = await selectContainerMetadataRecord(execSql, containerId);\n if (container) return heldContainerBinding({ container, record });\n if (!record) return null;\n // Retention records the organization with each retained record; without one\n // the retained metadata target still pins the binding.\n const dormantOrganizationId = await loadDormantOrganizationId(\n execSql,\n containerId,\n );\n return {\n organizationId: dormantOrganizationId ?? \"\",\n metadataDocumentId: record.documentId,\n };\n}\n\n/**\n * Clears the tombstone the fence read found. That read covers the container's\n * only row that is not yet cleared (one row per container), so without one\n * there is nothing to clear.\n */\nasync function clearObservedHydrationFence(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n fence: object | undefined,\n): Promise<void> {\n if (!fence) return;\n await tx\n .update(containerHydrationTombstones)\n .set({ cleared: true })\n .where(eq(containerHydrationTombstones.containerId, containerId))\n .run();\n}\n\nexport async function commitStoredHydratedContainer(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitHydratedContainer\"]\n >[0],\n input: Parameters<ContainerContentsPersistence[\"commitHydratedContainer\"]>[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);\n const commit = async (tx: ClientSQLiteTransactionScope) => {\n const existingContainers = await tx\n .select({ id: containers.id })\n .from(containers)\n .where(eq(containers.id, input.container.id))\n .limit(1);\n if (existingContainers.length > 0) return { committed: false as const };\n if (!(await placementCheckpointMatches(tx, input)))\n return { committed: false as const };\n\n const fences = await tx\n .select({\n generation: containerHydrationTombstones.generation,\n reason: containerHydrationTombstones.reason,\n updatedAt: containerHydrationTombstones.updatedAt,\n })\n .from(containerHydrationTombstones)\n .where(\n and(\n eq(containerHydrationTombstones.containerId, input.container.id),\n eq(containerHydrationTombstones.cleared, false),\n ),\n )\n .limit(1);\n const fence = fences[0];\n const currentDormantRecord = await selectContainerMetadataRecord(\n lockedExecSql,\n input.container.id,\n );\n if (!observedRecoveryStateHeld(fence, currentDormantRecord, input)) {\n return { committed: false as const };\n }\n if (\n await isSupersededContainerBinding(lockedExecSql, {\n containerId: input.container.id,\n organizationId: input.container.organizationId,\n })\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from this organization\",\n );\n }\n // Retained metadata keeps its organization and target; a relisting that\n // names others rolls back rather than replacing retained private edits.\n const dormantOrganizationId = await loadDormantOrganizationId(\n lockedExecSql,\n input.container.id,\n );\n assertHeldContainerBinding(\n {\n organizationId: dormantOrganizationId ?? \"\",\n metadataDocumentId: currentDormantRecord?.documentId ?? null,\n },\n {\n organizationId: input.container.organizationId,\n metadataDocumentIds: [\n input.container.metadataDocumentId,\n input.record.documentId,\n ],\n },\n );\n\n const container = await saveRecoveredContainer(tx, input);\n await clearObservedHydrationFence(tx, input.container.id, fence);\n return { committed: true as const, container };\n };\n if (!input.stillCurrent) {\n return runtime.transaction(commit, { behavior: \"immediate\" });\n }\n const outcome = await runtime.guardedTransaction(\n commit,\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.result ?? { committed: false as const };\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerHydrationPersistence.js","sourceRoot":"","sources":["containerHydrationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,kCAAkC,EAAE,MAAM,8CAA8C,CAAC;AAClG,OAAO,EACL,4BAA4B,EAC5B,UAAU,EACV,wBAAwB,EACxB,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,kCAAkC,EAAE,MAAM,kDAAkD,CAAC;AACtG,OAAO,EACL,0BAA0B,EAE1B,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAM5B,OAAO,EACL,kCAAkC,EAClC,6BAA6B,GAC9B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,4BAA4B,EA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AS,EAAE,IAAa,EAAE,SAAS,EAAE,CAAC;QACjD,CAAC,CAAC;QACF,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,CAAC;YACxB,OAAO,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;QAChE,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAC9C,MAAM,EACN,KAAK,CAAC,YAAY,EAClB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACF,OAAO,OAAO,CAAC,MAAM,IAAI,EAAE,SAAS,EAAE,KAAc,EAAE,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { and, eq, inArray, sql } from \"drizzle-orm\";\nimport { documentSyncPullContinuationsEqual } from \"../../documents/shared/sync/pullContinuation\";\nimport {\n containerHydrationTombstones,\n containers,\n dormantContainerMetadata,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { loadStoredAccessManifestCheckpoint } from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n assertHeldContainerBinding,\n type HeldContainerBinding,\n heldContainerBinding,\n} from \"./containerBinding\";\nimport type {\n ContainerContentsPersistence,\n ContainerHydrationTombstone,\n ContainerMetadataRecord,\n} from \"./containerContentsPersistenceTypes\";\nimport {\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n} from \"./containerMetadataRows\";\nimport { loadContainerById } from \"./containerPersistence\";\nimport { containerRemovalBatches } from \"./containerRemovalBatches\";\nimport { isSupersededContainerBinding } from \"./supersededContainerBindings\";\n\nfunction sameNullableValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\nfunction sameMetadataRecord(\n current: ContainerMetadataRecord | null,\n expected: ContainerMetadataRecord | null,\n): boolean {\n if (!current || !expected) return current === expected;\n return (\n current.id === expected.id &&\n current.documentId === expected.documentId &&\n current.accessEpoch === expected.accessEpoch &&\n sameNullableValue(current.accessStateHash, expected.accessStateHash) &&\n sameNullableValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n sameNullableValue(current.contentKeyBundle, expected.contentKeyBundle) &&\n sameNullableValue(\n current.documentKekTargets,\n expected.documentKekTargets,\n ) &&\n sameNullableValue(\n current.documentManifestBundle,\n expected.documentManifestBundle,\n ) &&\n current.metadataUpdates === expected.metadataUpdates &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired)\n );\n}\n\nfunction sameHydrationTombstone(\n current:\n | { generation: number; reason: string; updatedAt: string }\n | undefined,\n expected: ContainerHydrationTombstone | null | undefined,\n): boolean {\n return (\n current !== undefined &&\n expected != null &&\n current.generation === expected.generation &&\n current.reason === expected.reason &&\n current.updatedAt === expected.updatedAt\n );\n}\n\n/** The fence and dormant record still match what the caller observed. */\nfunction observedRecoveryStateHeld(\n fence: Parameters<typeof sameHydrationTombstone>[0],\n currentDormantRecord: ContainerMetadataRecord | null,\n expected: {\n readonly expectedDormantRecord: ContainerMetadataRecord | null;\n readonly expectedHydrationTombstone?:\n | ContainerHydrationTombstone\n | null\n | undefined;\n },\n): boolean {\n if (\n fence &&\n !sameHydrationTombstone(fence, expected.expectedHydrationTombstone)\n ) {\n return false;\n }\n return sameMetadataRecord(\n currentDormantRecord,\n expected.expectedDormantRecord,\n );\n}\n\nexport async function recordContainerHydrationTombstones(input: {\n removals: ReadonlyArray<{\n containerId: string;\n reason: \"access_revoked\" | \"deleted\";\n updatedAt: string;\n }>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n for (const batch of containerRemovalBatches(input.removals)) {\n await input.tx\n .insert(containerHydrationTombstones)\n .values([...batch])\n .onConflictDoUpdate({\n target: containerHydrationTombstones.containerId,\n set: {\n generation: sql`${containerHydrationTombstones.generation} + 1`,\n cleared: false,\n reason: sql`CASE\n WHEN ${containerHydrationTombstones.reason} = 'deleted' THEN 'deleted'\n ELSE excluded.reason\n END`,\n updatedAt: sql`MAX(${containerHydrationTombstones.updatedAt}, excluded.updated_at)`,\n },\n })\n .run();\n }\n}\n\nexport async function placementCheckpointMatches(\n tx: ClientSQLiteTransactionScope,\n input: Pick<\n Parameters<ContainerContentsPersistence[\"commitHydratedContainer\"]>[1],\n \"container\" | \"expectedPlacementCheckpoint\"\n >,\n): Promise<boolean> {\n const expected = input.expectedPlacementCheckpoint;\n if (!expected) return true;\n const current = await loadStoredAccessManifestCheckpoint(tx, expected);\n return (\n expected.objectKind === \"container\" &&\n expected.objectId === input.container.id &&\n expected.organizationId === input.container.organizationId &&\n current?.epoch === expected.epoch &&\n current.manifestHash === expected.manifestHash\n );\n}\n\n/** A retained local move continues to own placement after verified reattachment. */\nasync function saveRecoveredContainer(\n tx: ClientSQLiteTransactionScope,\n input: Parameters<ContainerContentsPersistence[\"commitHydratedContainer\"]>[1],\n) {\n const [move] = await tx\n .select({\n parentContainerId: localIntents.targetContainerId,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.container.id),\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n ),\n )\n .limit(1);\n return saveContainerContentsContainerRows({\n container: move\n ? { ...input.container, parentId: move.parentContainerId }\n : input.container,\n localUpdatedAt:\n move?.updatedAt ??\n input.saveOptions.localUpdatedAt ??\n input.remoteUpdatedAt,\n record: input.record,\n serverTimestamps: input.saveOptions.serverTimestamps,\n tx,\n });\n}\n\nasync function loadDormantOrganizationId(\n execSql: ExecSql,\n containerId: string,\n): Promise<string | null> {\n const [row] = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({ organizationId: dormantContainerMetadata.organizationId })\n .from(dormantContainerMetadata)\n .where(eq(dormantContainerMetadata.containerId, containerId))\n .limit(1);\n return row?.organizationId ?? null;\n}\n\n/**\n * The binding this device holds for a container id: its live row, or the\n * organization and metadata target retained after access loss. Null when the\n * device has never held the container.\n */\nexport async function loadStoredHeldContainerBinding(\n execSql: ExecSql,\n containerId: string,\n): Promise<HeldContainerBinding | null> {\n const container = await loadContainerById(execSql, containerId);\n const record = await selectContainerMetadataRecord(execSql, containerId);\n if (container) return heldContainerBinding({ container, record });\n if (!record) return null;\n // Retention records the organization with each retained record; without one\n // the retained metadata target still pins the binding.\n const dormantOrganizationId = await loadDormantOrganizationId(\n execSql,\n containerId,\n );\n return {\n organizationId: dormantOrganizationId ?? \"\",\n metadataDocumentId: record.documentId,\n };\n}\n\n/**\n * Clears the tombstone the fence read found. That read covers the container's\n * only row that is not yet cleared (one row per container), so without one\n * there is nothing to clear.\n */\nasync function clearObservedHydrationFence(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n fence: object | undefined,\n): Promise<void> {\n if (!fence) return;\n await tx\n .update(containerHydrationTombstones)\n .set({ cleared: true })\n .where(eq(containerHydrationTombstones.containerId, containerId))\n .run();\n}\n\nexport async function commitStoredHydratedContainer(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitHydratedContainer\"]\n >[0],\n input: Parameters<ContainerContentsPersistence[\"commitHydratedContainer\"]>[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const runtime = getClientSQLitePersistenceRuntime(lockedExecSql);\n const commit = async (tx: ClientSQLiteTransactionScope) => {\n const existingContainers = await tx\n .select({ id: containers.id })\n .from(containers)\n .where(eq(containers.id, input.container.id))\n .limit(1);\n if (existingContainers.length > 0) return { committed: false as const };\n if (!(await placementCheckpointMatches(tx, input)))\n return { committed: false as const };\n\n const fences = await tx\n .select({\n generation: containerHydrationTombstones.generation,\n reason: containerHydrationTombstones.reason,\n updatedAt: containerHydrationTombstones.updatedAt,\n })\n .from(containerHydrationTombstones)\n .where(\n and(\n eq(containerHydrationTombstones.containerId, input.container.id),\n eq(containerHydrationTombstones.cleared, false),\n ),\n )\n .limit(1);\n const fence = fences[0];\n const currentDormantRecord = await selectContainerMetadataRecord(\n lockedExecSql,\n input.container.id,\n );\n if (!observedRecoveryStateHeld(fence, currentDormantRecord, input)) {\n return { committed: false as const };\n }\n if (\n await isSupersededContainerBinding(lockedExecSql, {\n containerId: input.container.id,\n organizationId: input.container.organizationId,\n })\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from this organization\",\n );\n }\n // Retained metadata keeps its organization and target; a relisting that\n // names others rolls back rather than replacing retained private edits.\n const dormantOrganizationId = await loadDormantOrganizationId(\n lockedExecSql,\n input.container.id,\n );\n assertHeldContainerBinding(\n {\n organizationId: dormantOrganizationId ?? \"\",\n metadataDocumentId: currentDormantRecord?.documentId ?? null,\n },\n {\n organizationId: input.container.organizationId,\n metadataDocumentIds: [\n input.container.metadataDocumentId,\n input.record.documentId,\n ],\n },\n );\n\n const container = await saveRecoveredContainer(tx, input);\n await clearObservedHydrationFence(tx, input.container.id, fence);\n return { committed: true as const, container };\n };\n if (!input.stillCurrent) {\n return runtime.transaction(commit, { behavior: \"immediate\" });\n }\n const outcome = await runtime.guardedTransaction(\n commit,\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.result ?? { committed: false as const };\n });\n}\n"]}
|
|
@@ -9,6 +9,7 @@ import { clearDocumentSyncFailureInTransaction } from "../documents/records/docu
|
|
|
9
9
|
import { resetAccessDiscovery } from "./containerAccessDiscovery.js";
|
|
10
10
|
import { assertHeldContainerBinding, heldContainerBinding, } from "./containerBinding.js";
|
|
11
11
|
import { settleContainerCreateIntentRevision } from "./containerCreateIntentSettlement.js";
|
|
12
|
+
import { placementCheckpointMatches } from "./containerHydrationPersistence.js";
|
|
12
13
|
import { ContainerCreateIntentSupersededError, deleteContainerMoveIntentRevision, } from "./containerIntentPersistence.js";
|
|
13
14
|
import { getContainerMetadataScope, saveContainerContentsContainerRows, selectContainerMetadataRecord, } from "./containerMetadataRows.js";
|
|
14
15
|
import { loadContainerById, } from "./containerPersistence.js";
|
|
@@ -94,7 +95,7 @@ async function enqueuePendingUpdate(execSql, containerId, pendingUpdate) {
|
|
|
94
95
|
return;
|
|
95
96
|
await new DocumentRecordRepository(execSql).enqueueDocumentPendingUpdate(getContainerMetadataScope(containerId), pendingUpdate);
|
|
96
97
|
}
|
|
97
|
-
function staleServerMutationResult(currentState, input) {
|
|
98
|
+
async function staleServerMutationResult(tx, currentState, input) {
|
|
98
99
|
const incomingServerUpdatedAt = input.saveOptions?.serverTimestamps?.updatedAt;
|
|
99
100
|
const hasOlderContainerTimestamp = incomingServerUpdatedAt != null &&
|
|
100
101
|
currentState?.container.serverUpdatedAt != null &&
|
|
@@ -102,8 +103,14 @@ function staleServerMutationResult(currentState, input) {
|
|
|
102
103
|
const hasOlderMetadataAccessEpoch = currentState?.record != null &&
|
|
103
104
|
currentState.record.documentId === input.record.documentId &&
|
|
104
105
|
currentState.record.accessEpoch > input.record.accessEpoch;
|
|
105
|
-
|
|
106
|
-
|
|
106
|
+
const verified = input.saveOptions?.verifiedPlacement;
|
|
107
|
+
const staleClock = hasOlderContainerTimestamp &&
|
|
108
|
+
!(verified &&
|
|
109
|
+
(await placementCheckpointMatches(tx, {
|
|
110
|
+
container: input.container,
|
|
111
|
+
expectedPlacementCheckpoint: verified,
|
|
112
|
+
})));
|
|
113
|
+
return currentState?.record && (staleClock || hasOlderMetadataAccessEpoch)
|
|
107
114
|
? {
|
|
108
115
|
committed: false,
|
|
109
116
|
currentState,
|
|
@@ -192,7 +199,7 @@ export async function commitStoredMetadataMutation(execSql, input) {
|
|
|
192
199
|
return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
193
200
|
const outcome = await getClientSQLitePersistenceRuntime(lockedExecSql).guardedTransaction(async (tx) => {
|
|
194
201
|
const currentState = await loadStoredContainerState(lockedExecSql, input.container.id);
|
|
195
|
-
const staleServerResult = staleServerMutationResult(currentState, input);
|
|
202
|
+
const staleServerResult = await staleServerMutationResult(tx, currentState, input);
|
|
196
203
|
if (staleServerResult)
|
|
197
204
|
return staleServerResult;
|
|
198
205
|
if (!metadataMutationStateMatches(currentState, input)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerMetadataMutationPersistence.js","sourceRoot":"","sources":["containerMetadataMutationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kCAAkC,EAAE,MAAM,8CAA8C,CAAC;AAClG,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EACL,wBAAwB,GAEzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,wBAAwB,EACxB,wCAAwC,GACzC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,qDAAqD,CAAC;AAC5G,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAM5B,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AACxF,OAAO,EACL,oCAAoC,EACpC,iCAAiC,GAClC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,kCAAkC,EAClC,6BAA6B,GAC9B,MAAM,yBAAyB,CAAC;AACj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WAAW,EAAE,CAC1B,CAAC;QACF,IAAI,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;YACxC,OAAO,OAAO,CAAC,MAAM,CAAC;QACxB,CAAC;QACD,OAAO;YACL,SAAS,EAAE,KAAc;YACzB,YAAY,EAAE,MAAM,wBAAwB,CAC1C,aAAa,EACb,KAAK,CAAC,SAAS,CAAC,EAAE,CACnB;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAEI,EACJ,KAEI;IAEJ,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC/D,MAAM,OAAO,GAAG,MAAM,iCAAiC,CACrD,aAAa,CACd,CAAC,kBAAkB,CAClB,KAAK,EAAE,EAAE,EAAE,EAAE;YACX,MAAM,YAAY,GAAG,MAAM,wBAAwB,CACjD,aAAa,EACb,KAAK,CAAC,WAAW,CAClB,CAAC;YACF,IACE,YAAY,EAAE,MAAM;gBACpB,4BAA4B,CAC1B,YAAY,CAAC,MAAM,EACnB,KAAK,CAAC,cAAc,CACrB,EACD,CAAC;gBACD,MAAM,4BAA4B,CAChC,EAAE,EACF,KAAK,CAAC,WAAW,EACjB,KAAK,CAAC,gBAAgB,CACvB,CAAC;YACJ,CAAC;YACD,OAAO,YAAY,CAAC;QACtB,CAAC,EACD,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,EAAE,EACjD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACF,OAAO,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IACnD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, or } from \"drizzle-orm\";\nimport { documentSyncPullContinuationsEqual } from \"../../documents/shared/sync/pullContinuation\";\nimport {\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport {\n DocumentRecordRepository,\n type PendingUpdateFields,\n} from \"../documents/records\";\nimport {\n hasQueuedDocumentUpdates,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../documents/records/documentPendingUpdatePersistence\";\nimport { clearDocumentSyncFailureInTransaction } from \"../documents/records/documentSyncFailurePersistence\";\nimport { resetAccessDiscovery } from \"./containerAccessDiscovery\";\nimport {\n assertHeldContainerBinding,\n heldContainerBinding,\n} from \"./containerBinding\";\nimport type {\n ContainerContentsPersistence,\n ContainerMetadataRecord,\n StoredContainerState,\n} from \"./containerContentsPersistenceTypes\";\nimport { settleContainerCreateIntentRevision } from \"./containerCreateIntentSettlement\";\nimport {\n ContainerCreateIntentSupersededError,\n deleteContainerMoveIntentRevision,\n} from \"./containerIntentPersistence\";\nimport {\n getContainerMetadataScope,\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n} from \"./containerMetadataRows\";\nimport {\n type ContainerRecord,\n loadContainerById,\n} from \"./containerPersistence\";\nimport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\nimport { assertPrimaryDocumentSelection } from \"./linkedDocumentSummary\";\n\nfunction sameNullableValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\nfunction committedMetadataMutationResult(input: {\n container: ContainerRecord;\n createIntentSettled: boolean;\n moveIntentSettled: boolean;\n}) {\n return {\n committed: true as const,\n container: input.container,\n ...(input.createIntentSettled\n ? { createIntentSettled: true as const }\n : {}),\n ...(input.moveIntentSettled ? { moveIntentSettled: true as const } : {}),\n };\n}\n\nfunction sameMetadataSecurityIdentity(\n current: ContainerMetadataRecord,\n expected: ContainerMetadataRecord,\n): boolean {\n return (\n current.id === expected.id &&\n current.documentId === expected.documentId &&\n current.accessEpoch === expected.accessEpoch &&\n sameNullableValue(current.accessStateHash, expected.accessStateHash) &&\n sameNullableValue(current.contentKeyBundle, expected.contentKeyBundle) &&\n sameNullableValue(\n current.documentKekTargets,\n expected.documentKekTargets,\n ) &&\n sameNullableValue(\n current.documentManifestBundle,\n expected.documentManifestBundle,\n )\n );\n}\n\nfunction sameMetadataRecord(\n current: ContainerMetadataRecord,\n expected: ContainerMetadataRecord,\n): boolean {\n return (\n sameMetadataSecurityIdentity(current, expected) &&\n sameNullableValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n current.metadataUpdates === expected.metadataUpdates &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired)\n );\n}\n\nfunction sameContainerRecord(\n current: ContainerRecord,\n expected: ContainerRecord,\n): boolean {\n return (\n current.id === expected.id &&\n current.parentId === expected.parentId &&\n current.organizationId === expected.organizationId &&\n current.metadataDocumentId === expected.metadataDocumentId &&\n (current.systemSlot ?? null) === (expected.systemSlot ?? null) &&\n (current.effectiveAccessLevel ?? null) ===\n (expected.effectiveAccessLevel ?? null) &&\n (current.localUpdatedAt ?? null) === (expected.localUpdatedAt ?? null) &&\n (current.serverCreatedAt ?? null) === (expected.serverCreatedAt ?? null) &&\n (current.serverUpdatedAt ?? null) === (expected.serverUpdatedAt ?? null) &&\n current.name === expected.name &&\n (current.icon ?? null) === (expected.icon ?? null)\n );\n}\n\nasync function loadStoredContainerState(\n execSql: Parameters<\n ContainerContentsPersistence[\"loadContainerMetadataState\"]\n >[0],\n containerId: string,\n): Promise<StoredContainerState | null> {\n const container = await loadContainerById(execSql, containerId);\n if (!container) return null;\n return {\n container,\n record: await selectContainerMetadataRecord(execSql, containerId),\n };\n}\n\nasync function deleteAcceptedPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n ids: readonly string[],\n): Promise<void> {\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getContainerMetadataScope(containerId),\n ids,\n );\n}\n\nfunction clearMetadataSyncFailure(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<void> {\n return clearDocumentSyncFailureInTransaction(tx, {\n appKind: CONTAINER_METADATA_APP_KIND,\n localId: containerId,\n });\n}\n\nasync function hasPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<boolean> {\n return hasQueuedDocumentUpdates(tx, getContainerMetadataScope(containerId));\n}\n\nasync function hasPendingStructuralIntent(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<boolean> {\n // A pending create or any surviving (unsynced) move of this container.\n const structural = await tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(\n and(\n eq(localIntents.subjectId, containerId),\n or(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.syncStatus, \"pending\"),\n ),\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n ),\n ),\n )\n .limit(1);\n return structural.length > 0;\n}\n\nasync function enqueuePendingUpdate(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[0],\n containerId: string,\n pendingUpdate: PendingUpdateFields | undefined,\n): Promise<void> {\n if (!pendingUpdate) return;\n await new DocumentRecordRepository(execSql).enqueueDocumentPendingUpdate(\n getContainerMetadataScope(containerId),\n pendingUpdate,\n );\n}\n\ntype CommitMetadataMutationInput = Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n>[1];\n\nfunction staleServerMutationResult(\n currentState: StoredContainerState | null,\n input: CommitMetadataMutationInput,\n) {\n const incomingServerUpdatedAt =\n input.saveOptions?.serverTimestamps?.updatedAt;\n const hasOlderContainerTimestamp =\n incomingServerUpdatedAt != null &&\n currentState?.container.serverUpdatedAt != null &&\n currentState.container.serverUpdatedAt > incomingServerUpdatedAt;\n const hasOlderMetadataAccessEpoch =\n currentState?.record != null &&\n currentState.record.documentId === input.record.documentId &&\n currentState.record.accessEpoch > input.record.accessEpoch;\n return currentState?.record &&\n (hasOlderContainerTimestamp || hasOlderMetadataAccessEpoch)\n ? {\n committed: false as const,\n currentState,\n staleServerState: true as const,\n }\n : null;\n}\n\nfunction metadataMutationStateMatches(\n currentState: StoredContainerState | null,\n input: CommitMetadataMutationInput,\n): currentState is StoredContainerState & {\n record: ContainerMetadataRecord;\n} {\n return Boolean(\n currentState?.record &&\n sameContainerRecord(currentState.container, input.expectedContainer) &&\n sameMetadataRecord(currentState.record, input.expectedRecord),\n );\n}\n\nasync function rejectMetadataMutationConflict(input: {\n currentState: StoredContainerState | null;\n mutation: CommitMetadataMutationInput;\n tx: ClientSQLiteTransactionScope;\n}) {\n const { currentState, mutation, tx } = input;\n if (\n currentState?.record &&\n mutation.settleAcceptedPendingOnConflict &&\n sameMetadataSecurityIdentity(currentState.record, mutation.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n mutation.container.id,\n mutation.acceptedPendingUpdateIds,\n );\n }\n return { committed: false as const, currentState };\n}\n\nasync function prepareContainerMutationWrite(input: {\n currentContainer: ContainerRecord;\n mutation: CommitMetadataMutationInput;\n tx: ClientSQLiteTransactionScope;\n}): Promise<{ container: ContainerRecord; localUpdatedAt: string }> {\n const { currentContainer, mutation, tx } = input;\n const requestedLocalUpdatedAt =\n mutation.saveOptions?.localUpdatedAt ??\n mutation.saveOptions?.updatedAt ??\n new Date().toISOString();\n // Nothing below writes local intents, so one read answers both checks.\n let pendingStructuralIntent: boolean | undefined;\n const hasStructuralIntent = async () => {\n pendingStructuralIntent ??= await hasPendingStructuralIntent(\n tx,\n mutation.container.id,\n );\n return pendingStructuralIntent;\n };\n const preserveDurableStructure =\n mutation.preserveDurableStructureWhenPending === true &&\n (await hasStructuralIntent());\n // Syncing metadata is not a local edit. Preserve the durable edit clock,\n // including an edit another pane made while this request was in flight.\n const localUpdatedAt =\n preserveDurableStructure || mutation.settleAcceptedPendingOnConflict\n ? (currentContainer.localUpdatedAt ?? requestedLocalUpdatedAt)\n : requestedLocalUpdatedAt;\n const structurallyRebasedContainer = preserveDurableStructure\n ? { ...mutation.container, parentId: currentContainer.parentId }\n : mutation.container;\n const didSettleOutgoing =\n mutation.acceptedPendingUpdateIds.length > 0 &&\n !(await hasPendingUpdates(tx, mutation.container.id)) &&\n !(await hasStructuralIntent());\n // Only container responses establish the server's structural clock. A\n // metadata acknowledgement supplies no such timestamp; marking it with our\n // wall clock would make later valid listings appear stale forever.\n return {\n container: structurallyRebasedContainer,\n localUpdatedAt: didSettleOutgoing\n ? (currentContainer.serverUpdatedAt ?? localUpdatedAt)\n : localUpdatedAt,\n };\n}\n\n/** Server acknowledgements and listings cannot rebind a held folder. */\nfunction assertMutationKeepsHeldBinding(\n currentState: StoredContainerState & { record: ContainerMetadataRecord },\n input: CommitMetadataMutationInput,\n): void {\n const recordDocumentIds =\n input.record.documentId === currentState.record.documentId\n ? []\n : [input.record.documentId];\n assertHeldContainerBinding(heldContainerBinding(currentState), {\n organizationId: input.container.organizationId,\n metadataDocumentIds: [\n input.container.metadataDocumentId,\n ...recordDocumentIds,\n ],\n });\n}\n\nasync function settleMetadataStructuralIntents(\n tx: ClientSQLiteTransactionScope,\n input: CommitMetadataMutationInput,\n): Promise<void> {\n if (\n input.createIntentSettlement &&\n (await settleContainerCreateIntentRevision({\n ...input.createIntentSettlement,\n tx,\n })) === \"superseded\"\n ) {\n throw new ContainerCreateIntentSupersededError();\n }\n if (\n input.moveIntentSettlement &&\n !(await deleteContainerMoveIntentRevision({\n ...input.moveIntentSettlement,\n tx,\n }))\n ) {\n throw new Error(\n \"Container move intent was superseded before local settlement\",\n );\n }\n}\n\nexport async function commitStoredMetadataMutation(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[0],\n input: Parameters<ContainerContentsPersistence[\"commitMetadataMutation\"]>[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const outcome = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async (tx) => {\n const currentState = await loadStoredContainerState(\n lockedExecSql,\n input.container.id,\n );\n const staleServerResult = staleServerMutationResult(\n currentState,\n input,\n );\n if (staleServerResult) return staleServerResult;\n if (!metadataMutationStateMatches(currentState, input)) {\n return rejectMetadataMutationConflict({\n currentState,\n mutation: input,\n tx,\n });\n }\n assertMutationKeepsHeldBinding(currentState, input);\n await assertPrimaryDocumentSelection(\n lockedExecSql,\n currentState.container,\n input.primaryDocumentId,\n );\n\n await enqueuePendingUpdate(\n lockedExecSql,\n input.container.id,\n input.pendingUpdate,\n );\n await deleteAcceptedPendingUpdates(\n tx,\n input.container.id,\n input.acceptedPendingUpdateIds,\n );\n if (input.clearSyncFailure) {\n await clearMetadataSyncFailure(tx, input.container.id);\n }\n const { container, localUpdatedAt } =\n await prepareContainerMutationWrite({\n currentContainer: currentState.container,\n mutation: input,\n tx,\n });\n const saved = await saveContainerContentsContainerRows({\n container,\n createIntent: input.saveOptions?.createIntent,\n localUpdatedAt,\n moveIntent: input.saveOptions?.moveIntent,\n record: input.record,\n serverTimestamps: input.saveOptions?.serverTimestamps,\n tx,\n });\n await resetAccessDiscovery(tx, currentState.container, saved);\n await settleMetadataStructuralIntents(tx, input);\n return committedMetadataMutationResult({\n container: saved,\n createIntentSettled: input.createIntentSettlement !== undefined,\n moveIntentSettled: input.moveIntentSettlement !== undefined,\n });\n },\n () => !input.stillCurrent || input.stillCurrent(),\n { behavior: \"immediate\" },\n );\n if (outcome.committed && outcome.result) {\n return outcome.result;\n }\n return {\n committed: false as const,\n currentState: await loadStoredContainerState(\n lockedExecSql,\n input.container.id,\n ),\n };\n });\n}\n\nexport async function settleStoredMetadataPendingUpdates(\n execSql: Parameters<\n ContainerContentsPersistence[\"settleAcceptedMetadataPendingUpdates\"]\n >[0],\n input: Parameters<\n ContainerContentsPersistence[\"settleAcceptedMetadataPendingUpdates\"]\n >[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const outcome = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async (tx) => {\n const currentState = await loadStoredContainerState(\n lockedExecSql,\n input.containerId,\n );\n if (\n currentState?.record &&\n sameMetadataSecurityIdentity(\n currentState.record,\n input.expectedRecord,\n )\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n input.containerId,\n input.pendingUpdateIds,\n );\n }\n return currentState;\n },\n () => !input.stillCurrent || input.stillCurrent(),\n { behavior: \"immediate\" },\n );\n return outcome.committed ? outcome.result : null;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerMetadataMutationPersistence.js","sourceRoot":"","sources":["containerMetadataMutationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kCAAkC,EAAE,MAAM,8CAA8C,CAAC;AAClG,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EACL,wBAAwB,GAEzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,wBAAwB,EACxB,wCAAwC,GACzC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,qDAAqD,CAAC;AAC5G,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAM5B,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AACxF,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC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,CAAC,WAAW,EACjB,KAAK,CAAC,gBAAgB,CACvB,CAAC;YACJ,CAAC;YACD,OAAO,YAAY,CAAC;QACtB,CAAC,EACD,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,EAAE,EACjD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACF,OAAO,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IACnD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, or } from \"drizzle-orm\";\nimport { documentSyncPullContinuationsEqual } from \"../../documents/shared/sync/pullContinuation\";\nimport {\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport {\n DocumentRecordRepository,\n type PendingUpdateFields,\n} from \"../documents/records\";\nimport {\n hasQueuedDocumentUpdates,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../documents/records/documentPendingUpdatePersistence\";\nimport { clearDocumentSyncFailureInTransaction } from \"../documents/records/documentSyncFailurePersistence\";\nimport { resetAccessDiscovery } from \"./containerAccessDiscovery\";\nimport {\n assertHeldContainerBinding,\n heldContainerBinding,\n} from \"./containerBinding\";\nimport type {\n ContainerContentsPersistence,\n ContainerMetadataRecord,\n StoredContainerState,\n} from \"./containerContentsPersistenceTypes\";\nimport { settleContainerCreateIntentRevision } from \"./containerCreateIntentSettlement\";\nimport { placementCheckpointMatches } from \"./containerHydrationPersistence\";\nimport {\n ContainerCreateIntentSupersededError,\n deleteContainerMoveIntentRevision,\n} from \"./containerIntentPersistence\";\nimport {\n getContainerMetadataScope,\n saveContainerContentsContainerRows,\n selectContainerMetadataRecord,\n} from \"./containerMetadataRows\";\nimport {\n type ContainerRecord,\n loadContainerById,\n} from \"./containerPersistence\";\nimport { CONTAINER_METADATA_APP_KIND } from \"./dormantContainerMetadata\";\nimport { assertPrimaryDocumentSelection } from \"./linkedDocumentSummary\";\n\nfunction sameNullableValue(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n return (left ?? null) === (right ?? null);\n}\n\nfunction committedMetadataMutationResult(input: {\n container: ContainerRecord;\n createIntentSettled: boolean;\n moveIntentSettled: boolean;\n}) {\n return {\n committed: true as const,\n container: input.container,\n ...(input.createIntentSettled\n ? { createIntentSettled: true as const }\n : {}),\n ...(input.moveIntentSettled ? { moveIntentSettled: true as const } : {}),\n };\n}\n\nfunction sameMetadataSecurityIdentity(\n current: ContainerMetadataRecord,\n expected: ContainerMetadataRecord,\n): boolean {\n return (\n current.id === expected.id &&\n current.documentId === expected.documentId &&\n current.accessEpoch === expected.accessEpoch &&\n sameNullableValue(current.accessStateHash, expected.accessStateHash) &&\n sameNullableValue(current.contentKeyBundle, expected.contentKeyBundle) &&\n sameNullableValue(\n current.documentKekTargets,\n expected.documentKekTargets,\n ) &&\n sameNullableValue(\n current.documentManifestBundle,\n expected.documentManifestBundle,\n )\n );\n}\n\nfunction sameMetadataRecord(\n current: ContainerMetadataRecord,\n expected: ContainerMetadataRecord,\n): boolean {\n return (\n sameMetadataSecurityIdentity(current, expected) &&\n sameNullableValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n current.metadataUpdates === expected.metadataUpdates &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired)\n );\n}\n\nfunction sameContainerRecord(\n current: ContainerRecord,\n expected: ContainerRecord,\n): boolean {\n return (\n current.id === expected.id &&\n current.parentId === expected.parentId &&\n current.organizationId === expected.organizationId &&\n current.metadataDocumentId === expected.metadataDocumentId &&\n (current.systemSlot ?? null) === (expected.systemSlot ?? null) &&\n (current.effectiveAccessLevel ?? null) ===\n (expected.effectiveAccessLevel ?? null) &&\n (current.localUpdatedAt ?? null) === (expected.localUpdatedAt ?? null) &&\n (current.serverCreatedAt ?? null) === (expected.serverCreatedAt ?? null) &&\n (current.serverUpdatedAt ?? null) === (expected.serverUpdatedAt ?? null) &&\n current.name === expected.name &&\n (current.icon ?? null) === (expected.icon ?? null)\n );\n}\n\nasync function loadStoredContainerState(\n execSql: Parameters<\n ContainerContentsPersistence[\"loadContainerMetadataState\"]\n >[0],\n containerId: string,\n): Promise<StoredContainerState | null> {\n const container = await loadContainerById(execSql, containerId);\n if (!container) return null;\n return {\n container,\n record: await selectContainerMetadataRecord(execSql, containerId),\n };\n}\n\nasync function deleteAcceptedPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n ids: readonly string[],\n): Promise<void> {\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getContainerMetadataScope(containerId),\n ids,\n );\n}\n\nfunction clearMetadataSyncFailure(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<void> {\n return clearDocumentSyncFailureInTransaction(tx, {\n appKind: CONTAINER_METADATA_APP_KIND,\n localId: containerId,\n });\n}\n\nasync function hasPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<boolean> {\n return hasQueuedDocumentUpdates(tx, getContainerMetadataScope(containerId));\n}\n\nasync function hasPendingStructuralIntent(\n tx: ClientSQLiteTransactionScope,\n containerId: string,\n): Promise<boolean> {\n // A pending create or any surviving (unsynced) move of this container.\n const structural = await tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(\n and(\n eq(localIntents.subjectId, containerId),\n or(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.syncStatus, \"pending\"),\n ),\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n ),\n ),\n )\n .limit(1);\n return structural.length > 0;\n}\n\nasync function enqueuePendingUpdate(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[0],\n containerId: string,\n pendingUpdate: PendingUpdateFields | undefined,\n): Promise<void> {\n if (!pendingUpdate) return;\n await new DocumentRecordRepository(execSql).enqueueDocumentPendingUpdate(\n getContainerMetadataScope(containerId),\n pendingUpdate,\n );\n}\n\ntype CommitMetadataMutationInput = Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n>[1];\n\nasync function staleServerMutationResult(\n tx: ClientSQLiteTransactionScope,\n currentState: StoredContainerState | null,\n input: CommitMetadataMutationInput,\n) {\n const incomingServerUpdatedAt =\n input.saveOptions?.serverTimestamps?.updatedAt;\n const hasOlderContainerTimestamp =\n incomingServerUpdatedAt != null &&\n currentState?.container.serverUpdatedAt != null &&\n currentState.container.serverUpdatedAt > incomingServerUpdatedAt;\n const hasOlderMetadataAccessEpoch =\n currentState?.record != null &&\n currentState.record.documentId === input.record.documentId &&\n currentState.record.accessEpoch > input.record.accessEpoch;\n const verified = input.saveOptions?.verifiedPlacement;\n const staleClock =\n hasOlderContainerTimestamp &&\n !(\n verified &&\n (await placementCheckpointMatches(tx, {\n container: input.container,\n expectedPlacementCheckpoint: verified,\n }))\n );\n return currentState?.record && (staleClock || hasOlderMetadataAccessEpoch)\n ? {\n committed: false as const,\n currentState,\n staleServerState: true as const,\n }\n : null;\n}\n\nfunction metadataMutationStateMatches(\n currentState: StoredContainerState | null,\n input: CommitMetadataMutationInput,\n): currentState is StoredContainerState & {\n record: ContainerMetadataRecord;\n} {\n return Boolean(\n currentState?.record &&\n sameContainerRecord(currentState.container, input.expectedContainer) &&\n sameMetadataRecord(currentState.record, input.expectedRecord),\n );\n}\n\nasync function rejectMetadataMutationConflict(input: {\n currentState: StoredContainerState | null;\n mutation: CommitMetadataMutationInput;\n tx: ClientSQLiteTransactionScope;\n}) {\n const { currentState, mutation, tx } = input;\n if (\n currentState?.record &&\n mutation.settleAcceptedPendingOnConflict &&\n sameMetadataSecurityIdentity(currentState.record, mutation.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n mutation.container.id,\n mutation.acceptedPendingUpdateIds,\n );\n }\n return { committed: false as const, currentState };\n}\n\nasync function prepareContainerMutationWrite(input: {\n currentContainer: ContainerRecord;\n mutation: CommitMetadataMutationInput;\n tx: ClientSQLiteTransactionScope;\n}): Promise<{ container: ContainerRecord; localUpdatedAt: string }> {\n const { currentContainer, mutation, tx } = input;\n const requestedLocalUpdatedAt =\n mutation.saveOptions?.localUpdatedAt ??\n mutation.saveOptions?.updatedAt ??\n new Date().toISOString();\n // Nothing below writes local intents, so one read answers both checks.\n let pendingStructuralIntent: boolean | undefined;\n const hasStructuralIntent = async () => {\n pendingStructuralIntent ??= await hasPendingStructuralIntent(\n tx,\n mutation.container.id,\n );\n return pendingStructuralIntent;\n };\n const preserveDurableStructure =\n mutation.preserveDurableStructureWhenPending === true &&\n (await hasStructuralIntent());\n // Syncing metadata is not a local edit. Preserve the durable edit clock,\n // including an edit another pane made while this request was in flight.\n const localUpdatedAt =\n preserveDurableStructure || mutation.settleAcceptedPendingOnConflict\n ? (currentContainer.localUpdatedAt ?? requestedLocalUpdatedAt)\n : requestedLocalUpdatedAt;\n const structurallyRebasedContainer = preserveDurableStructure\n ? { ...mutation.container, parentId: currentContainer.parentId }\n : mutation.container;\n const didSettleOutgoing =\n mutation.acceptedPendingUpdateIds.length > 0 &&\n !(await hasPendingUpdates(tx, mutation.container.id)) &&\n !(await hasStructuralIntent());\n // Only container responses establish the server's structural clock. A\n // metadata acknowledgement supplies no such timestamp; marking it with our\n // wall clock would make later valid listings appear stale forever.\n return {\n container: structurallyRebasedContainer,\n localUpdatedAt: didSettleOutgoing\n ? (currentContainer.serverUpdatedAt ?? localUpdatedAt)\n : localUpdatedAt,\n };\n}\n\n/** Server acknowledgements and listings cannot rebind a held folder. */\nfunction assertMutationKeepsHeldBinding(\n currentState: StoredContainerState & { record: ContainerMetadataRecord },\n input: CommitMetadataMutationInput,\n): void {\n const recordDocumentIds =\n input.record.documentId === currentState.record.documentId\n ? []\n : [input.record.documentId];\n assertHeldContainerBinding(heldContainerBinding(currentState), {\n organizationId: input.container.organizationId,\n metadataDocumentIds: [\n input.container.metadataDocumentId,\n ...recordDocumentIds,\n ],\n });\n}\n\nasync function settleMetadataStructuralIntents(\n tx: ClientSQLiteTransactionScope,\n input: CommitMetadataMutationInput,\n): Promise<void> {\n if (\n input.createIntentSettlement &&\n (await settleContainerCreateIntentRevision({\n ...input.createIntentSettlement,\n tx,\n })) === \"superseded\"\n ) {\n throw new ContainerCreateIntentSupersededError();\n }\n if (\n input.moveIntentSettlement &&\n !(await deleteContainerMoveIntentRevision({\n ...input.moveIntentSettlement,\n tx,\n }))\n ) {\n throw new Error(\n \"Container move intent was superseded before local settlement\",\n );\n }\n}\n\nexport async function commitStoredMetadataMutation(\n execSql: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[0],\n input: Parameters<ContainerContentsPersistence[\"commitMetadataMutation\"]>[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const outcome = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async (tx) => {\n const currentState = await loadStoredContainerState(\n lockedExecSql,\n input.container.id,\n );\n const staleServerResult = await staleServerMutationResult(\n tx,\n currentState,\n input,\n );\n if (staleServerResult) return staleServerResult;\n if (!metadataMutationStateMatches(currentState, input)) {\n return rejectMetadataMutationConflict({\n currentState,\n mutation: input,\n tx,\n });\n }\n assertMutationKeepsHeldBinding(currentState, input);\n await assertPrimaryDocumentSelection(\n lockedExecSql,\n currentState.container,\n input.primaryDocumentId,\n );\n\n await enqueuePendingUpdate(\n lockedExecSql,\n input.container.id,\n input.pendingUpdate,\n );\n await deleteAcceptedPendingUpdates(\n tx,\n input.container.id,\n input.acceptedPendingUpdateIds,\n );\n if (input.clearSyncFailure) {\n await clearMetadataSyncFailure(tx, input.container.id);\n }\n const { container, localUpdatedAt } =\n await prepareContainerMutationWrite({\n currentContainer: currentState.container,\n mutation: input,\n tx,\n });\n const saved = await saveContainerContentsContainerRows({\n container,\n createIntent: input.saveOptions?.createIntent,\n localUpdatedAt,\n moveIntent: input.saveOptions?.moveIntent,\n record: input.record,\n serverTimestamps: input.saveOptions?.serverTimestamps,\n tx,\n });\n await resetAccessDiscovery(tx, currentState.container, saved);\n await settleMetadataStructuralIntents(tx, input);\n return committedMetadataMutationResult({\n container: saved,\n createIntentSettled: input.createIntentSettlement !== undefined,\n moveIntentSettled: input.moveIntentSettlement !== undefined,\n });\n },\n () => !input.stillCurrent || input.stillCurrent(),\n { behavior: \"immediate\" },\n );\n if (outcome.committed && outcome.result) {\n return outcome.result;\n }\n return {\n committed: false as const,\n currentState: await loadStoredContainerState(\n lockedExecSql,\n input.container.id,\n ),\n };\n });\n}\n\nexport async function settleStoredMetadataPendingUpdates(\n execSql: Parameters<\n ContainerContentsPersistence[\"settleAcceptedMetadataPendingUpdates\"]\n >[0],\n input: Parameters<\n ContainerContentsPersistence[\"settleAcceptedMetadataPendingUpdates\"]\n >[1],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const outcome = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async (tx) => {\n const currentState = await loadStoredContainerState(\n lockedExecSql,\n input.containerId,\n );\n if (\n currentState?.record &&\n sameMetadataSecurityIdentity(\n currentState.record,\n input.expectedRecord,\n )\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n input.containerId,\n input.pendingUpdateIds,\n );\n }\n return currentState;\n },\n () => !input.stillCurrent || input.stillCurrent(),\n { behavior: \"immediate\" },\n );\n return outcome.committed ? outcome.result : null;\n });\n}\n"]}
|