@tearleads/client-sdk 0.1.226 → 0.1.230
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/Tearleads.js +1 -1
- package/Tearleads.js.map +1 -1
- package/client/containerContents/documentDiscovery.js +4 -1
- package/client/containerContents/documentDiscovery.js.map +1 -1
- package/client/containerContents/index.d.ts +1 -1
- package/client/containerContents/index.js +4 -2
- package/client/containerContents/index.js.map +1 -1
- package/client/deviceFirst/index.js +1 -1
- package/client/deviceFirst/index.js.map +1 -1
- package/client/documents/index.js +6 -2
- package/client/documents/index.js.map +1 -1
- package/client/identity/index.js +1 -1
- package/client/identity/index.js.map +1 -1
- package/client/identity/userIdentities.d.ts +1 -1
- package/client/identity/userIdentities.js +1 -1
- package/client/identity/userIdentities.js.map +1 -1
- package/client/index.d.ts +2 -0
- package/client/index.js +2 -0
- package/client/index.js.map +1 -1
- package/client/organizations/index.js +1 -1
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationMemberships.d.ts +1 -1
- package/client/organizations/organizationMemberships.js +1 -1
- package/client/organizations/organizationMemberships.js.map +1 -1
- package/client/organizations/principalMutations.js +1 -1
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/organizations/recipientAdmission.d.ts +1 -1
- package/client/organizations/recipientAdmission.js +1 -1
- package/client/organizations/recipientAdmission.js.map +1 -1
- package/client/runtime/apiVersion.js +1 -1
- package/client/runtime/apiVersion.js.map +1 -1
- package/client/runtime/containerContentsRuntime.d.ts +8 -0
- package/client/runtime/containerContentsRuntime.js +14 -0
- package/client/runtime/containerContentsRuntime.js.map +1 -0
- package/client/runtime/database.js +1 -1
- package/client/runtime/database.js.map +1 -1
- package/client/runtime/documentsRuntime.d.ts +5 -0
- package/client/runtime/documentsRuntime.js +10 -0
- package/client/runtime/documentsRuntime.js.map +1 -0
- package/client/runtime/events.js +1 -1
- package/client/runtime/events.js.map +1 -1
- package/client/runtime/network.js +1 -1
- package/client/runtime/network.js.map +1 -1
- package/client/runtime/runtimeIdentityResolution.js +1 -1
- package/client/runtime/runtimeIdentityResolution.js.map +1 -1
- package/client/runtime/syncBillingGate.js +1 -1
- package/client/runtime/syncBillingGate.js.map +1 -1
- package/client/runtime/workflowRuntime.d.ts +5 -2
- package/client/runtime/workflowRuntime.js +6 -2
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/client/securityIncidents/index.d.ts +1 -1
- package/client/securityIncidents/index.js +2 -2
- package/client/securityIncidents/index.js.map +1 -1
- package/client/session/index.js +1 -1
- package/client/session/index.js.map +1 -1
- package/client/session/sessionLoginRefusal.js +1 -1
- package/client/session/sessionLoginRefusal.js.map +1 -1
- package/client/session/sessionRootAuthority.js +1 -1
- package/client/session/sessionRootAuthority.js.map +1 -1
- package/data/documents/shared/projection/freshProjectionRetry.js +1 -1
- package/data/documents/shared/projection/freshProjectionRetry.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/heldContainerHeads.js.map +1 -0
- package/data/keyingProjectionVerification/error.js +1 -57
- package/data/keyingProjectionVerification/error.js.map +1 -1
- package/data/persistence/container-contents/documentContainerProjectionPersistence.d.ts +6 -2
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js +10 -1
- package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
- package/data/persistence/documents/documentDeletionPort.d.ts +28 -0
- package/data/persistence/documents/documentDeletionPort.js +2 -0
- package/data/persistence/documents/documentDeletionPort.js.map +1 -0
- package/data/persistence/documents/documentsPersistence.d.ts +1 -0
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentDeletionPersistence.js +7 -7
- package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
- package/data/persistence/documents/types.d.ts +2 -15
- package/data/persistence/documents/types.js.map +1 -1
- package/data/shared/securityIncidents.d.ts +18 -1
- package/data/shared/securityIncidents.js +58 -1
- package/data/shared/securityIncidents.js.map +1 -1
- package/index.d.ts +5 -5
- package/index.js +3 -3
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/hydration/backgroundHydration.js +1 -1
- package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
- package/stores/container-contents/operations/reportShareFailure.js +1 -1
- package/stores/container-contents/operations/reportShareFailure.js.map +1 -1
- package/stores/container-contents/operations/shareOperations.js +1 -1
- package/stores/container-contents/operations/shareOperations.js.map +1 -1
- package/stores/container-contents/systemContainers/systemContainerHydration.js +1 -1
- package/stores/container-contents/systemContainers/systemContainerHydration.js.map +1 -1
- package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js +1 -1
- package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js.map +1 -1
- package/stores/documents/documentStore/persistence.js +1 -0
- package/stores/documents/documentStore/persistence.js.map +1 -1
- package/stores/documents/documentStore/sync/index.js +1 -1
- package/stores/documents/documentStore/sync/index.js.map +1 -1
- package/stores/documents/documentStore/sync/syncRequest.js +1 -0
- package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
- package/workflows/blobs/hydration/hydrationResults.js +2 -1
- package/workflows/blobs/hydration/hydrationResults.js.map +1 -1
- package/workflows/blobs/verification/attachmentDecryptor.js +1 -1
- package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -1
- package/workflows/container-contents/container-state/create/createAdoption.js +1 -1
- package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
- package/workflows/container-contents/container-state/create/createIntentSync.js +1 -1
- package/workflows/container-contents/container-state/create/createIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -1
- package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/organizationHost.d.ts +54 -0
- package/workflows/container-contents/container-state/organizationHost.js +2 -0
- package/workflows/container-contents/container-state/organizationHost.js.map +1 -0
- package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -1
- package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +2 -4
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
- package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
- package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -2
- package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/documentLinks/index.js +1 -1
- package/workflows/container-contents/documentLinks/index.js.map +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntentSync.js +1 -1
- package/workflows/container-contents/documentMove/documentMoveIntentSync.js.map +1 -1
- package/workflows/container-contents/index.d.ts +1 -0
- package/workflows/container-contents/index.js.map +1 -1
- package/workflows/container-contents/info/documentInfo.d.ts +1 -1
- package/workflows/container-contents/info/documentInfo.js +1 -1
- package/workflows/container-contents/info/documentInfo.js.map +1 -1
- package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
- package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
- package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js +1 -2
- package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js.map +1 -1
- package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +3 -4
- package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/runtime.d.ts +5 -0
- package/workflows/container-contents/runtime.js +3 -0
- package/workflows/container-contents/runtime.js.map +1 -1
- package/workflows/container-contents/syncPause/documentRemoval.js +2 -0
- package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
- package/workflows/container-contents/tombstones/documentPurge.js +5 -2
- package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
- package/workflows/containers/child/mutationSubmit.js +1 -1
- package/workflows/containers/child/mutationSubmit.js.map +1 -1
- package/workflows/containers/child/recite.js +1 -1
- package/workflows/containers/child/recite.js.map +1 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js +1 -1
- package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js.map +1 -1
- package/workflows/documents/documentMutationCommit.d.ts +2 -1
- package/workflows/documents/documentMutationCommit.js +1 -0
- package/workflows/documents/documentMutationCommit.js.map +1 -1
- package/workflows/documents/documentPersistGuards.js +2 -1
- package/workflows/documents/documentPersistGuards.js.map +1 -1
- package/workflows/documents/purge/persistedDocumentRemoval.d.ts +2 -1
- package/workflows/documents/purge/persistedDocumentRemoval.js +2 -2
- package/workflows/documents/purge/persistedDocumentRemoval.js.map +1 -1
- package/workflows/documents/runtime.d.ts +5 -0
- package/workflows/documents/runtime.js +1 -0
- package/workflows/documents/runtime.js.map +1 -1
- package/workflows/documents/sync/syncSubmittedResult.js +1 -1
- package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
- package/workflows/documents/syncPlan/syncContentKeys.js +1 -1
- package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
- package/workflows/organizations/containerContentsHost.js +14 -0
- package/workflows/organizations/containerContentsHost.js.map +1 -0
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js +1 -1
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -1
- package/workflows/principals/policyCache/index.d.ts +1 -1
- package/workflows/principals/policyCache/index.js +2 -1
- package/workflows/principals/policyCache/index.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.d.ts +1 -1
- package/workflows/principals/runtimePolicyRecovery.js +1 -1
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
- package/workflows/principals/runtimeProjectionPolicyRecovery.js +1 -1
- package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
- package/workflows/registration/persistRegistrationBootstrap.js +2 -0
- package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
- package/data/containers/shared/heldContainerHeads.js.map +0 -1
- /package/data/{containers/shared → keyingProjectionVerification/checkpoints}/heldContainerHeads.js +0 -0
- /package/{client/runtime → data/shared}/listenerSet.js +0 -0
- /package/{client/runtime → data/shared}/listenerSet.js.map +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentPurge.js","sourceRoot":"","sources":["documentPurge.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,sCAAsC,EAAE,MAAM,kDAAkD,CAAC;AAC1G,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAEL,2BAA2B,EAC3B,uBAAuB,EACvB,qBAAqB,EAErB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,oCAAoC,EAAE,MAAM,6BAA6B,CAAC;AAwCnF,KAAK,UAAU,yBAAyB,CAAC,KASxC;IACC,OAAO,KAAK,CAAC,WAAW,CAAC,8BAA8B,CACrD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAC3B,KAAK,CAAC,MAAM,EACZ,KAAK,CAAC,UAAU,EAChB,KAAK,EAAE,kBAAkB,EAAE,EAAE;QAC3B,MAAM,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CAAC,oCAAoC,CAC/E;YACE,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,OAAO,EAAE,kBAAkB;YAC3B,OAAO,EAAE,KAAK,CAA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AC,mBAAmB,KAAK,SAAS;gBACtC,cAAc,CAAC,WAAW,KAAK,KAAK,CAAC,mBAAmB,CAAC,EAC3D,CAAC;YACD,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,yDAAyD,MAAM,wCAAwC,CACxG,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,uBAAuB,CAAC;YAC5C,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;YAC1D,kBAAkB,EAAE,OAAO,CAAC,KAAK,CAAC,kBAAkB;YACpD,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;YAC9B,cAAc;YACd,OAAO,EAAE,MAAM;YACf,WAAW;SACZ,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,yDAAyD,MAAM,+BAA+B,CAC/F,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QACD,IAAI,OAAO,EAAE,CAAC;YACZ,KAAK,0BAA0B,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QACxD,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,8CAA8C,MAAM,EAAE,CAAC,CAAC;QACzE,OAAO;YACL,UAAU,EAAE,MAAM;YAClB,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YAClC,wBAAwB,EAAE,EAAE;SAC7B,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,uDAAuD,MAAM,KAAK,YAAY,CAAC,KAAK,CAAC,EAAE,CACxF,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { DocumentPurgeResponse } from \"@tearleads/validators/response\";\nimport type { StoredDocumentKind } from \"../../../data/documents/documentKinds\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { rethrowProjectionVerificationCancelled } from \"../../../data/keyingProjectionVerification/types\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n RemoteDocumentService,\n type RemoteDocumentServiceApi,\n reclaimDocumentOrphanBlobs,\n resolveDocumentCreateAuthor,\n} from \"../../documents\";\nimport { ensureDocumentClientProjectionTables } from \"../../documents/persistence\";\nimport type { SubtreePurgeRoot } from \"../../documents/purge/subtreePurgeScope\";\n\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\ntype DocumentPurgeResult =\n | DocumentPurgeResponse\n | {\n readonly documentId: string;\n readonly purgedAt: string;\n readonly reclaimedBlobStorageKeys: readonly string[];\n }\n | null;\n\ninterface ContainerDocumentPurgeRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteDocumentServiceApi;\n}\n\ninterface PurgeRemoteContainerDocumentInput {\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n stillCurrent?: (() => boolean) | undefined;\n documentKind: StoredDocumentKind;\n noteId: string;\n persistence?: DocumentsPersistence | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentPurgeRuntime;\n}\n\nasync function deleteAbsentDocumentState(input: {\n readonly commitPurgeProof: (\n transactionExecSql: ContainerDocumentPurgeRuntime[\"infra\"][\"execSql\"],\n ) => Promise<void>;\n readonly documentId: string;\n readonly documentKind: StoredDocumentKind;\n readonly noteId: string;\n readonly persistence: DocumentsPersistence;\n readonly runtime: ContainerDocumentPurgeRuntime;\n}): Promise<boolean> {\n return input.persistence.deleteDocumentSideRowsIfAbsent(\n input.runtime.infra.execSql,\n input.noteId,\n input.documentId,\n async (transactionExecSql) => {\n await input.runtime.infra.documentProjectors.deleteStoredDocumentClientProjection(\n {\n documentKind: input.documentKind,\n execSql: transactionExecSql,\n localId: input.noteId,\n },\n );\n await input.commitPurgeProof(transactionExecSql);\n },\n );\n}\n\nasync function commitVerifiedDocumentPurge(input: {\n readonly commitPurgeProof: (\n transactionExecSql: ContainerDocumentPurgeRuntime[\"infra\"][\"execSql\"],\n ) => Promise<void>;\n readonly documentId: string;\n readonly documentKind: StoredDocumentKind;\n readonly noteId: string;\n readonly persistence: DocumentsPersistence;\n readonly runtime: ContainerDocumentPurgeRuntime;\n}): Promise<boolean> {\n await input.persistence.ensureSchema(input.runtime.infra.execSql);\n await ensureDocumentClientProjectionTables({\n documentProjectors: input.runtime.infra.documentProjectors,\n execSql: input.runtime.infra.execSql,\n });\n const expectedRecord = await input.persistence.loadDocument(\n input.runtime.infra.execSql,\n input.noteId,\n );\n if (expectedRecord && expectedRecord.documentId !== input.documentId) {\n throw new Error(\n \"Local document identity changed while its remote purge was committing\",\n );\n }\n const deleted = expectedRecord\n ? await deletePersistedDocument({\n beforeDeleteInTransaction: input.commitPurgeProof,\n documentProjectors: input.runtime.infra.documentProjectors,\n execSql: input.runtime.infra.execSql,\n expectedRecord,\n localId: input.noteId,\n persistence: input.persistence,\n })\n : await deleteAbsentDocumentState(input);\n if (!deleted) {\n throw new Error(\n \"Local document state changed while its remote purge was committing\",\n );\n }\n return true;\n}\n\nexport async function purgeRemoteContainerDocument(\n input: PurgeRemoteContainerDocumentInput,\n): Promise<DocumentPurgeResult> {\n const { documentId, noteId, runtime } = input;\n const persistence = input.persistence ?? defaultDocumentsPersistence;\n try {\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n `Container contents: failed to purge note ${noteId} because the local signing context is unavailable`,\n );\n return null;\n }\n let deleted = false;\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey:\n runtime.crypto.encapsulationKeyPair?.secretKey ?? null,\n execSql: runtime.infra.execSql,\n });\n const response = await remoteDocuments.purgeRemoteDocument({\n beforeSubmit: input.beforeSubmit,\n author,\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n stillCurrent: input.stillCurrent,\n onVerifiedPurge: async ({ commitPurgeProof }) => {\n deleted = await commitVerifiedDocumentPurge({\n commitPurgeProof,\n documentId,\n documentKind: input.documentKind,\n noteId,\n persistence,\n runtime,\n });\n },\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer(),\n });\n if (!response) {\n runtime.util.log(\n `Container contents: failed to purge note ${noteId} (document ${documentId})`,\n );\n return null;\n }\n if (deleted) {\n void reclaimDocumentOrphanBlobs(runtime, persistence);\n }\n runtime.util.log(\n `Container contents: purged note ${noteId} (document ${documentId})`,\n );\n return response;\n } catch (error) {\n // A cancelled verification is neither a failure nor a completed purge; the\n // caller that owns the generation decides what to do with it.\n rethrowProjectionVerificationCancelled(error);\n await reportAndRethrowKeyingVerificationError(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.purge\",\n },\n );\n runtime.util.log(\n `Container contents: failed to purge note ${noteId} (document ${documentId}): ${errorMessage(error)}`,\n );\n return null;\n }\n}\n\ninterface ContainerDocumentLocalPurgeRuntime\n extends Pick<ContainerContentsWorkflowRuntime, \"infra\" | \"util\"> {}\n\nexport async function purgeLocalContainerDocument(input: {\n beforeDeleteInTransaction?: Parameters<\n typeof deletePersistedDocument\n >[0][\"beforeDeleteInTransaction\"];\n noteId: string;\n expectedContainerId?: string | null | undefined;\n persistence?: DocumentsPersistence | undefined;\n runtime: ContainerDocumentLocalPurgeRuntime;\n}): Promise<DocumentPurgeResult> {\n const { noteId, runtime } = input;\n const persistence = input.persistence ?? defaultDocumentsPersistence;\n try {\n await persistence.ensureSchema(runtime.infra.execSql);\n const expectedRecord = await persistence.loadDocument(\n runtime.infra.execSql,\n noteId,\n );\n if (\n !expectedRecord ||\n expectedRecord.documentId !== null ||\n (input.expectedContainerId !== undefined &&\n expectedRecord.containerId !== input.expectedContainerId)\n ) {\n runtime.util.log(\n `Container contents: local-only purge refused for note ${noteId} because it is absent or remote-backed`,\n );\n return null;\n }\n const deleted = await deletePersistedDocument({\n beforeDeleteInTransaction: input.beforeDeleteInTransaction,\n documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n expectedRecord,\n localId: noteId,\n persistence,\n });\n if (!deleted) {\n runtime.util.log(\n `Container contents: local-only purge refused for note ${noteId} because its identity changed`,\n );\n return null;\n }\n if (deleted) {\n void reclaimDocumentOrphanBlobs(runtime, persistence);\n }\n runtime.util.log(`Container contents: purged local-only note ${noteId}`);\n return {\n documentId: noteId,\n purgedAt: new Date().toISOString(),\n reclaimedBlobStorageKeys: [],\n };\n } catch (error) {\n runtime.util.log(\n `Container contents: failed to purge local-only note ${noteId}: ${errorMessage(error)}`,\n );\n return null;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentPurge.js","sourceRoot":"","sources":["documentPurge.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,sCAAsC,EAAE,MAAM,kDAAkD,CAAC;AAC1G,OAAO,EAAE,wBAAwB,EAAE,MAAM,qFAAqF,CAAC;AAC/H,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAAE,uCAAuC,EAAE,MAAM,wCAAwC,CAAC;AACjG,OAAO,EAEL,2BAA2B,EAC3B,uBAAuB,EACvB,qBAAqB,EAErB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,oCAAoC,EAAE,MAAM,6BAA6B,CAAC;AAwCnF,KAAK,UAAU,yBAAyB,CAAC,KASxC;IACC,OAAO,KAAK,CAAC,WAAW,CAAC,8BAA8B,CACrD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC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,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,uDAAuD,MAAM,KAAK,YAAY,CAAC,KAAK,CAAC,EAAE,CACxF,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { DocumentPurgeResponse } from \"@tearleads/validators/response\";\nimport type { StoredDocumentKind } from \"../../../data/documents/documentKinds\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { rethrowProjectionVerificationCancelled } from \"../../../data/keyingProjectionVerification/types\";\nimport { deleteDocumentPlacements } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../data/shared/securityIncidents\";\nimport {\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n RemoteDocumentService,\n type RemoteDocumentServiceApi,\n reclaimDocumentOrphanBlobs,\n resolveDocumentCreateAuthor,\n} from \"../../documents\";\nimport { ensureDocumentClientProjectionTables } from \"../../documents/persistence\";\nimport type { SubtreePurgeRoot } from \"../../documents/purge/subtreePurgeScope\";\n\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\ntype DocumentPurgeResult =\n | DocumentPurgeResponse\n | {\n readonly documentId: string;\n readonly purgedAt: string;\n readonly reclaimedBlobStorageKeys: readonly string[];\n }\n | null;\n\ninterface ContainerDocumentPurgeRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteDocumentServiceApi;\n}\n\ninterface PurgeRemoteContainerDocumentInput {\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n stillCurrent?: (() => boolean) | undefined;\n documentKind: StoredDocumentKind;\n noteId: string;\n persistence?: DocumentsPersistence | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentPurgeRuntime;\n}\n\nasync function deleteAbsentDocumentState(input: {\n readonly commitPurgeProof: (\n transactionExecSql: ContainerDocumentPurgeRuntime[\"infra\"][\"execSql\"],\n ) => Promise<void>;\n readonly documentId: string;\n readonly documentKind: StoredDocumentKind;\n readonly noteId: string;\n readonly persistence: DocumentsPersistence;\n readonly runtime: ContainerDocumentPurgeRuntime;\n}): Promise<boolean> {\n return input.persistence.deleteDocumentSideRowsIfAbsent(\n input.runtime.infra.execSql,\n input.noteId,\n input.documentId,\n async (transactionExecSql) => {\n await input.runtime.infra.documentProjectors.deleteStoredDocumentClientProjection(\n {\n documentKind: input.documentKind,\n execSql: transactionExecSql,\n localId: input.noteId,\n },\n );\n await input.commitPurgeProof(transactionExecSql);\n },\n deleteDocumentPlacements,\n );\n}\n\nasync function commitVerifiedDocumentPurge(input: {\n readonly commitPurgeProof: (\n transactionExecSql: ContainerDocumentPurgeRuntime[\"infra\"][\"execSql\"],\n ) => Promise<void>;\n readonly documentId: string;\n readonly documentKind: StoredDocumentKind;\n readonly noteId: string;\n readonly persistence: DocumentsPersistence;\n readonly runtime: ContainerDocumentPurgeRuntime;\n}): Promise<boolean> {\n await input.persistence.ensureSchema(input.runtime.infra.execSql);\n await ensureDocumentClientProjectionTables({\n documentProjectors: input.runtime.infra.documentProjectors,\n execSql: input.runtime.infra.execSql,\n });\n const expectedRecord = await input.persistence.loadDocument(\n input.runtime.infra.execSql,\n input.noteId,\n );\n if (expectedRecord && expectedRecord.documentId !== input.documentId) {\n throw new Error(\n \"Local document identity changed while its remote purge was committing\",\n );\n }\n const deleted = expectedRecord\n ? await deletePersistedDocument({\n beforeDeleteInTransaction: input.commitPurgeProof,\n deleteDocumentPlacements,\n documentProjectors: input.runtime.infra.documentProjectors,\n execSql: input.runtime.infra.execSql,\n expectedRecord,\n localId: input.noteId,\n persistence: input.persistence,\n })\n : await deleteAbsentDocumentState(input);\n if (!deleted) {\n throw new Error(\n \"Local document state changed while its remote purge was committing\",\n );\n }\n return true;\n}\n\nexport async function purgeRemoteContainerDocument(\n input: PurgeRemoteContainerDocumentInput,\n): Promise<DocumentPurgeResult> {\n const { documentId, noteId, runtime } = input;\n const persistence = input.persistence ?? defaultDocumentsPersistence;\n try {\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n `Container contents: failed to purge note ${noteId} because the local signing context is unavailable`,\n );\n return null;\n }\n let deleted = false;\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey:\n runtime.crypto.encapsulationKeyPair?.secretKey ?? null,\n execSql: runtime.infra.execSql,\n });\n const response = await remoteDocuments.purgeRemoteDocument({\n beforeSubmit: input.beforeSubmit,\n author,\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n stillCurrent: input.stillCurrent,\n onVerifiedPurge: async ({ commitPurgeProof }) => {\n deleted = await commitVerifiedDocumentPurge({\n commitPurgeProof,\n documentId,\n documentKind: input.documentKind,\n noteId,\n persistence,\n runtime,\n });\n },\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer(),\n });\n if (!response) {\n runtime.util.log(\n `Container contents: failed to purge note ${noteId} (document ${documentId})`,\n );\n return null;\n }\n if (deleted) {\n void reclaimDocumentOrphanBlobs(runtime, persistence);\n }\n runtime.util.log(\n `Container contents: purged note ${noteId} (document ${documentId})`,\n );\n return response;\n } catch (error) {\n // A cancelled verification is neither a failure nor a completed purge; the\n // caller that owns the generation decides what to do with it.\n rethrowProjectionVerificationCancelled(error);\n await reportAndRethrowKeyingVerificationError(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.purge\",\n },\n );\n runtime.util.log(\n `Container contents: failed to purge note ${noteId} (document ${documentId}): ${errorMessage(error)}`,\n );\n return null;\n }\n}\n\ninterface ContainerDocumentLocalPurgeRuntime\n extends Pick<ContainerContentsWorkflowRuntime, \"infra\" | \"util\"> {}\n\nexport async function purgeLocalContainerDocument(input: {\n beforeDeleteInTransaction?: Parameters<\n typeof deletePersistedDocument\n >[0][\"beforeDeleteInTransaction\"];\n noteId: string;\n expectedContainerId?: string | null | undefined;\n persistence?: DocumentsPersistence | undefined;\n runtime: ContainerDocumentLocalPurgeRuntime;\n}): Promise<DocumentPurgeResult> {\n const { noteId, runtime } = input;\n const persistence = input.persistence ?? defaultDocumentsPersistence;\n try {\n await persistence.ensureSchema(runtime.infra.execSql);\n const expectedRecord = await persistence.loadDocument(\n runtime.infra.execSql,\n noteId,\n );\n if (\n !expectedRecord ||\n expectedRecord.documentId !== null ||\n (input.expectedContainerId !== undefined &&\n expectedRecord.containerId !== input.expectedContainerId)\n ) {\n runtime.util.log(\n `Container contents: local-only purge refused for note ${noteId} because it is absent or remote-backed`,\n );\n return null;\n }\n const deleted = await deletePersistedDocument({\n beforeDeleteInTransaction: input.beforeDeleteInTransaction,\n deleteDocumentPlacements,\n documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n expectedRecord,\n localId: noteId,\n persistence,\n });\n if (!deleted) {\n runtime.util.log(\n `Container contents: local-only purge refused for note ${noteId} because its identity changed`,\n );\n return null;\n }\n if (deleted) {\n void reclaimDocumentOrphanBlobs(runtime, persistence);\n }\n runtime.util.log(`Container contents: purged local-only note ${noteId}`);\n return {\n documentId: noteId,\n purgedAt: new Date().toISOString(),\n reclaimedBlobStorageKeys: [],\n };\n } catch (error) {\n runtime.util.log(\n `Container contents: failed to purge local-only note ${noteId}: ${errorMessage(error)}`,\n );\n return null;\n }\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { DOCUMENT_NOT_FOUND_ERROR_CODE, } from "../../../internal/validators/response/index.js";
|
|
2
2
|
import { assertDocumentWriterProjectionConsistent } from "../../../data/documents/shared/projection/index.js";
|
|
3
3
|
import { uniqueSortedStrings } from "../../../data/documents/shared/readers.js";
|
|
4
|
-
import { reportKeyingVerificationErrorInCauseChain } from "../../../data/keyingProjectionVerification/error.js";
|
|
5
4
|
import { createProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/userKeyResolver.js";
|
|
6
5
|
import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
7
6
|
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
7
|
+
import { reportKeyingVerificationErrorInCauseChain } from "../../../data/shared/securityIncidents.js";
|
|
8
8
|
import { documentHeadMatchesOrganization } from "../documentDiscovery/documentHeadScope.js";
|
|
9
9
|
export const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;
|
|
10
10
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentTombstoneEvidence.js","sourceRoot":"","sources":["documentTombstoneEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EAAE,yCAAyC,EAAE,MAAM,kDAAkD,CAAC;AAC7G,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAE7G,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAQlG,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC;AAkCzF,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,CAAC;AAChD;;;;GAIG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAE9C,KAAK,UAAU,mBAAmB,CAChC,OAAyC,EACzC,IAAmC,EACnC,UAAkB,EAClB,UAA4C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ACH,CAAC,CAAC;QACF,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,IAAI,CACR,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EACnE,MAAM,CACP,CACF,CAAC;QACF,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/keyingProjectionVerification/error\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { DocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport type {\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n ContainerDocumentTombstoneVerifier,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"../documentDiscovery/documentHeadScope\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport interface VerifiedDocumentHeadLinkSet {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n /** Present for a signed head; a terminal purge has no live access state. */\n readonly accessStateHash?: string;\n readonly linkedContainerIds: ReadonlyArray<string>;\n}\n\n/**\n * The document's verified head link set, or `null` when no verified head is\n * available: the projection could not be fetched (the requester may no\n * longer read the document, or it was purged) or failed verification.\n */\nexport type DocumentHeadLinkSetLoader = (\n documentId: string,\n expectedManifestHash?: string,\n) => Promise<VerifiedDocumentHeadLinkSet | \"not-found\" | null>;\n\n/** The highest access epoch local state records for the document. */\nexport type LocalDocumentAccessEpochLoader = (\n documentId: string,\n) => Promise<number>;\n\nexport interface DocumentHeadLinkSetLoaderDeps {\n readonly assertDocumentWriterProjectionConsistent: typeof assertDocumentWriterProjectionConsistent;\n readonly loadDocumentPurgeCheckpoint: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<DocumentPurgeCheckpoint | null>;\n}\n\nexport const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;\n/**\n * Head loads per settle. Tombstones beyond it stay unverified and are held\n * for a later, backed-off retry, so a bulk move out of a folder does not cost\n * every device an unbounded burst of fetches before the watermark advances.\n */\nexport const HEAD_LINK_SET_LOADS_PER_RUN = 32;\n\nasync function verifiedHeadLinkSet(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps,\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n policyOperation: PrincipalPolicyOperation | undefined,\n): Promise<VerifiedDocumentHeadLinkSet> {\n const verified: { value?: VerifiedDocumentHeadLinkSet } = {};\n await deps.assertDocumentWriterProjectionConsistent(projection, {\n // Only the link set is read; a bundle wrapped to superseded KEK targets\n // still carries the signed head.\n allowStaleContentKeyBundle: true,\n execSql: runtime.infra.execSql,\n onVerifiedAuthorization: (authorization) => {\n const head = authorization.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (head && head.state.documentId === documentId) {\n verified.value = {\n organizationId: head.state.organizationId,\n accessEpoch: head.state.epoch,\n accessStateHash: head.manifestHash,\n linkedContainerIds: uniqueSortedStrings(\n head.state.linkedContainerIds,\n ),\n };\n }\n },\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!verified.value) {\n throw new Error(\"Tombstone evidence lacks a verified document head\");\n }\n return verified.value;\n}\n\nasync function reportUnavailableHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n error: unknown,\n): Promise<void> {\n const integrityFailure = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.tombstone-evidence\",\n },\n );\n try {\n if (\n !integrityFailure &&\n error instanceof ProjectionDependencyUnavailableError\n ) {\n // A policy can advance without changing this document's hash. Drop its\n // cached evidence so the held head can recover on the next run.\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is awaiting current policy history`,\n );\n return;\n }\n runtime.util.logError?.(\n \"Container contents: tombstone evidence is unavailable\",\n error,\n );\n } catch {\n // A host logger that throws must not fail the discovery pass.\n }\n}\n\n/** Only a typed 404 proves absence; any other failure leaves the head unavailable. */\nfunction failedHeadVerdict(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n failure: {\n readonly code?: string | undefined;\n readonly status?: number | null | undefined;\n },\n): \"not-found\" | null {\n if (failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE)\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${failure.status ?? \"offline\"})`,\n );\n return null;\n}\n\n/** `policyOperation` lets one discovery pass share a directory discovery. */\nexport function createDocumentHeadLinkSetLoader(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps = {\n assertDocumentWriterProjectionConsistent,\n loadDocumentPurgeCheckpoint: (execSql, documentId) =>\n new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(\n documentId,\n ),\n },\n policyOperation?: PrincipalPolicyOperation,\n): DocumentHeadLinkSetLoader {\n return async (documentId, expectedManifestHash) => {\n try {\n // A verified purge proof is terminal signed evidence that the document\n // links nothing any more.\n if (\n await deps.loadDocumentPurgeCheckpoint(\n runtime.infra.execSql,\n documentId,\n )\n ) {\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n }\n // Tombstones require a fresh head. Listings can reuse a matching cached\n // projection, whose signature and local checkpoint are still verified.\n if (!expectedManifestHash)\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n let result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n if (\n expectedManifestHash &&\n result.ok &&\n result.data.documentManifest.manifestHash !== expectedManifestHash\n ) {\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n }\n if (!result.ok) return failedHeadVerdict(runtime, documentId, result);\n return await verifiedHeadLinkSet(\n runtime,\n deps,\n documentId,\n result.data,\n policyOperation,\n );\n } catch (error) {\n // Any failure leaves the tombstone unverified (held and retried); a\n // thrown error here must not fail the whole discovery pass.\n await reportUnavailableHead(runtime, documentId, error);\n return null;\n }\n };\n}\n\nfunction judgeTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n head: VerifiedDocumentHeadLinkSet | null,\n): ContainerDocumentTombstoneVerdict[] {\n return tombstones.map((tombstone): ContainerDocumentTombstoneVerdict => {\n if (head === null) {\n return { kind: \"unverified\", tombstone };\n }\n if (head.linkedContainerIds.includes(tombstone.containerId)) {\n return {\n kind: \"refuted\",\n linkedContainerIds: head.linkedContainerIds,\n tombstone,\n };\n }\n return {\n kind: \"verified\",\n tombstone: {\n ...tombstone,\n accessEpoch: head.accessEpoch,\n linkedContainerIds: head.linkedContainerIds,\n },\n };\n });\n}\n\n/**\n * Judge listing tombstones against each document's verified head link set,\n * fetched once per document with bounded concurrency and a per-run cap. A\n * head whose epoch is below local document state is no evidence: it may be a\n * lagging replica or a replay, and applying it could delete rows a newer\n * listing or settled move wrote.\n */\nexport function createContainerDocumentTombstoneVerifier(\n organizationId: string | undefined,\n loadDocumentHeadLinkSet: DocumentHeadLinkSetLoader,\n loadLocalDocumentAccessEpoch: LocalDocumentAccessEpochLoader,\n): ContainerDocumentTombstoneVerifier {\n return async (tombstones) => {\n const byDocumentId = new Map<string, ContainerDocumentTombstone[]>();\n for (const tombstone of tombstones) {\n const group = byDocumentId.get(tombstone.documentId) ?? [];\n group.push(tombstone);\n byDocumentId.set(tombstone.documentId, group);\n }\n const groups = [...byDocumentId.entries()];\n const verdicts: ContainerDocumentTombstoneVerdict[][] = groups.map(\n ([, group], index): ContainerDocumentTombstoneVerdict[] =>\n index < HEAD_LINK_SET_LOADS_PER_RUN\n ? judgeTombstones(group, null)\n : group.map((tombstone) => ({ kind: \"deferred\", tombstone })),\n );\n // A missing, foreign, or older-than-local head is no evidence.\n const evidentialHead = async (documentId: string) => {\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") return null;\n if (!documentHeadMatchesOrganization(head, organizationId)) return null;\n // A local-state read that fails is treated like an unavailable head:\n // the tombstones stay held rather than failing the discovery pass.\n const localEpoch = await loadLocalDocumentAccessEpoch(documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n return head.accessEpoch < localEpoch ? null : head;\n };\n let next = 0;\n const worker = async () => {\n while (next < Math.min(groups.length, HEAD_LINK_SET_LOADS_PER_RUN)) {\n const index = next++;\n const entry = groups[index];\n if (!entry) break;\n const [documentId, group] = entry;\n const head = await evidentialHead(documentId);\n if (head !== null) verdicts[index] = judgeTombstones(group, head);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, groups.length) },\n worker,\n ),\n );\n return verdicts.flat();\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentTombstoneEvidence.js","sourceRoot":"","sources":["documentTombstoneEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wCAAwC,EAAE,MAAM,2C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AC;QACb,MAAM,MAAM,GAAG,KAAK,IAAI,EAAE;YACxB,OAAO,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,EAAE,CAAC;gBACnE,MAAM,KAAK,GAAG,IAAI,EAAE,CAAC;gBACrB,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;gBAC5B,IAAI,CAAC,KAAK;oBAAE,MAAM;gBAClB,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,KAAK,CAAC;gBAClC,MAAM,IAAI,GAAG,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC;gBAC9C,IAAI,IAAI,KAAK,IAAI;oBAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACpE,CAAC;QACH,CAAC,CAAC;QACF,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,IAAI,CACR,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EACnE,MAAM,CACP,CACF,CAAC;QACF,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { DocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport type {\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n ContainerDocumentTombstoneVerifier,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"../documentDiscovery/documentHeadScope\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport interface VerifiedDocumentHeadLinkSet {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n /** Present for a signed head; a terminal purge has no live access state. */\n readonly accessStateHash?: string;\n readonly linkedContainerIds: ReadonlyArray<string>;\n}\n\n/**\n * The document's verified head link set, or `null` when no verified head is\n * available: the projection could not be fetched (the requester may no\n * longer read the document, or it was purged) or failed verification.\n */\nexport type DocumentHeadLinkSetLoader = (\n documentId: string,\n expectedManifestHash?: string,\n) => Promise<VerifiedDocumentHeadLinkSet | \"not-found\" | null>;\n\n/** The highest access epoch local state records for the document. */\nexport type LocalDocumentAccessEpochLoader = (\n documentId: string,\n) => Promise<number>;\n\nexport interface DocumentHeadLinkSetLoaderDeps {\n readonly assertDocumentWriterProjectionConsistent: typeof assertDocumentWriterProjectionConsistent;\n readonly loadDocumentPurgeCheckpoint: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<DocumentPurgeCheckpoint | null>;\n}\n\nexport const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;\n/**\n * Head loads per settle. Tombstones beyond it stay unverified and are held\n * for a later, backed-off retry, so a bulk move out of a folder does not cost\n * every device an unbounded burst of fetches before the watermark advances.\n */\nexport const HEAD_LINK_SET_LOADS_PER_RUN = 32;\n\nasync function verifiedHeadLinkSet(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps,\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n policyOperation: PrincipalPolicyOperation | undefined,\n): Promise<VerifiedDocumentHeadLinkSet> {\n const verified: { value?: VerifiedDocumentHeadLinkSet } = {};\n await deps.assertDocumentWriterProjectionConsistent(projection, {\n // Only the link set is read; a bundle wrapped to superseded KEK targets\n // still carries the signed head.\n allowStaleContentKeyBundle: true,\n execSql: runtime.infra.execSql,\n onVerifiedAuthorization: (authorization) => {\n const head = authorization.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (head && head.state.documentId === documentId) {\n verified.value = {\n organizationId: head.state.organizationId,\n accessEpoch: head.state.epoch,\n accessStateHash: head.manifestHash,\n linkedContainerIds: uniqueSortedStrings(\n head.state.linkedContainerIds,\n ),\n };\n }\n },\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!verified.value) {\n throw new Error(\"Tombstone evidence lacks a verified document head\");\n }\n return verified.value;\n}\n\nasync function reportUnavailableHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n error: unknown,\n): Promise<void> {\n const integrityFailure = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.tombstone-evidence\",\n },\n );\n try {\n if (\n !integrityFailure &&\n error instanceof ProjectionDependencyUnavailableError\n ) {\n // A policy can advance without changing this document's hash. Drop its\n // cached evidence so the held head can recover on the next run.\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is awaiting current policy history`,\n );\n return;\n }\n runtime.util.logError?.(\n \"Container contents: tombstone evidence is unavailable\",\n error,\n );\n } catch {\n // A host logger that throws must not fail the discovery pass.\n }\n}\n\n/** Only a typed 404 proves absence; any other failure leaves the head unavailable. */\nfunction failedHeadVerdict(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n failure: {\n readonly code?: string | undefined;\n readonly status?: number | null | undefined;\n },\n): \"not-found\" | null {\n if (failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE)\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${failure.status ?? \"offline\"})`,\n );\n return null;\n}\n\n/** `policyOperation` lets one discovery pass share a directory discovery. */\nexport function createDocumentHeadLinkSetLoader(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps = {\n assertDocumentWriterProjectionConsistent,\n loadDocumentPurgeCheckpoint: (execSql, documentId) =>\n new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(\n documentId,\n ),\n },\n policyOperation?: PrincipalPolicyOperation,\n): DocumentHeadLinkSetLoader {\n return async (documentId, expectedManifestHash) => {\n try {\n // A verified purge proof is terminal signed evidence that the document\n // links nothing any more.\n if (\n await deps.loadDocumentPurgeCheckpoint(\n runtime.infra.execSql,\n documentId,\n )\n ) {\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n }\n // Tombstones require a fresh head. Listings can reuse a matching cached\n // projection, whose signature and local checkpoint are still verified.\n if (!expectedManifestHash)\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n let result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n if (\n expectedManifestHash &&\n result.ok &&\n result.data.documentManifest.manifestHash !== expectedManifestHash\n ) {\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n }\n if (!result.ok) return failedHeadVerdict(runtime, documentId, result);\n return await verifiedHeadLinkSet(\n runtime,\n deps,\n documentId,\n result.data,\n policyOperation,\n );\n } catch (error) {\n // Any failure leaves the tombstone unverified (held and retried); a\n // thrown error here must not fail the whole discovery pass.\n await reportUnavailableHead(runtime, documentId, error);\n return null;\n }\n };\n}\n\nfunction judgeTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n head: VerifiedDocumentHeadLinkSet | null,\n): ContainerDocumentTombstoneVerdict[] {\n return tombstones.map((tombstone): ContainerDocumentTombstoneVerdict => {\n if (head === null) {\n return { kind: \"unverified\", tombstone };\n }\n if (head.linkedContainerIds.includes(tombstone.containerId)) {\n return {\n kind: \"refuted\",\n linkedContainerIds: head.linkedContainerIds,\n tombstone,\n };\n }\n return {\n kind: \"verified\",\n tombstone: {\n ...tombstone,\n accessEpoch: head.accessEpoch,\n linkedContainerIds: head.linkedContainerIds,\n },\n };\n });\n}\n\n/**\n * Judge listing tombstones against each document's verified head link set,\n * fetched once per document with bounded concurrency and a per-run cap. A\n * head whose epoch is below local document state is no evidence: it may be a\n * lagging replica or a replay, and applying it could delete rows a newer\n * listing or settled move wrote.\n */\nexport function createContainerDocumentTombstoneVerifier(\n organizationId: string | undefined,\n loadDocumentHeadLinkSet: DocumentHeadLinkSetLoader,\n loadLocalDocumentAccessEpoch: LocalDocumentAccessEpochLoader,\n): ContainerDocumentTombstoneVerifier {\n return async (tombstones) => {\n const byDocumentId = new Map<string, ContainerDocumentTombstone[]>();\n for (const tombstone of tombstones) {\n const group = byDocumentId.get(tombstone.documentId) ?? [];\n group.push(tombstone);\n byDocumentId.set(tombstone.documentId, group);\n }\n const groups = [...byDocumentId.entries()];\n const verdicts: ContainerDocumentTombstoneVerdict[][] = groups.map(\n ([, group], index): ContainerDocumentTombstoneVerdict[] =>\n index < HEAD_LINK_SET_LOADS_PER_RUN\n ? judgeTombstones(group, null)\n : group.map((tombstone) => ({ kind: \"deferred\", tombstone })),\n );\n // A missing, foreign, or older-than-local head is no evidence.\n const evidentialHead = async (documentId: string) => {\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") return null;\n if (!documentHeadMatchesOrganization(head, organizationId)) return null;\n // A local-state read that fails is treated like an unavailable head:\n // the tombstones stay held rather than failing the discovery pass.\n const localEpoch = await loadLocalDocumentAccessEpoch(documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n return head.accessEpoch < localEpoch ? null : head;\n };\n let next = 0;\n const worker = async () => {\n while (next < Math.min(groups.length, HEAD_LINK_SET_LOADS_PER_RUN)) {\n const index = next++;\n const entry = groups[index];\n if (!entry) break;\n const [documentId, group] = entry;\n const head = await evidentialHead(documentId);\n if (head !== null) verdicts[index] = judgeTombstones(group, head);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, groups.length) },\n worker,\n ),\n );\n return verdicts.flat();\n };\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { CONTAINER_MUTATION_ERROR_CODES, } from "../../../internal/validators/response/index.js";
|
|
2
2
|
import { ContainerPathTooDeepError } from "../../../data/containers/shared/containerPathLimits.js";
|
|
3
|
-
import { rememberVerifiedContainerHeads } from "../../../data/containers/shared/heldContainerHeads.js";
|
|
4
3
|
import { acknowledgeContainerMutation, acknowledgeContainerMutationBatch, } from "../../../data/containers/shared/mutationAcknowledgement.js";
|
|
5
4
|
import { isContainerPathTooDeepFailure } from "../../../data/containers/shared/mutationFailures.js";
|
|
5
|
+
import { rememberVerifiedContainerHeads } from "../../../data/keyingProjectionVerification/checkpoints/heldContainerHeads.js";
|
|
6
6
|
import { scheduleHeldDescendantRecitations } from "./recite.js";
|
|
7
7
|
import { planCarriedDescendantRekeys, } from "./rekey/carriedDescendantRekeys.js";
|
|
8
8
|
/** A mutation with no status-bearing variant: a share mints nothing to carry. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutationSubmit.js","sourceRoot":"","sources":["mutationSubmit.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,GAE/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,yBAAyB,EAAE,MAAM,qDAAqD,CAAC;AAChG,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,4BAA4B,EAC5B,iCAAiC,GAClC,M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,CAAC,sBAAsB,IAAI,KAAK,CAAC,YAAY;SACjE,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;IAC7E,CAAC;IACD,OAAO;QACL,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,QAAQ;KACT,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerMutationRequest } from \"@tearleads/validators/request\";\nimport {\n CONTAINER_MUTATION_ERROR_CODES,\n type ContainerRotationResponse,\n} from \"@tearleads/validators/response\";\nimport { ContainerPathTooDeepError } from \"../../../data/containers/shared/containerPathLimits\";\nimport { rememberVerifiedContainerHeads } from \"../../../data/containers/shared/heldContainerHeads\";\nimport {\n acknowledgeContainerMutation,\n acknowledgeContainerMutationBatch,\n} from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport { isContainerPathTooDeepFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport type { ContainerReciteApi } from \"../../../data/containers/shared/reciteApi\";\nimport type {\n ContainerMutationAuthor,\n ContainerRotationResult,\n MaterializedContainerRekeyPlan,\n} from \"../../../data/containers/shared/types\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../../data/principalContracts/principalPolicyEvidence\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { scheduleHeldDescendantRecitations } from \"./recite\";\nimport {\n type CarriedRekeyPlanningInput,\n planCarriedDescendantRekeys,\n type SpeculativePath,\n} from \"./rekey/carriedDescendantRekeys\";\n\n/**\n * Supplied by mutations that mint a new key epoch (rekey, revoke, move). The\n * server refuses one that would strand a level above a directly granted\n * container, and names the descendant rekeys it must carry instead (#2340).\n */\nexport interface CarriedRekeys {\n readonly planning: CarriedRekeyPlanningInput;\n /** The rotated container's own path once the rotation is accepted. */\n readonly rotated: () => Promise<SpeculativePath>;\n}\n\n/** A mutation with no status-bearing variant: a share mints nothing to carry. */\nexport async function submitPlainContainerMutation(\n plain: () => Promise<ContainerRotationResponse | null>,\n): Promise<ContainerRotationResult> {\n const data = await plain();\n return data ? { data, ok: true } : { ok: false, status: null };\n}\n\n/**\n * Adapt a rotation endpoint pair to one status-bearing call. An adapter with\n * only the plain method still rotates; it just cannot learn what to carry, so a\n * rotation that needs descendants fails as any other refusal does.\n */\nexport async function submitContainerRotation(input: {\n plain: () => Promise<ContainerRotationResponse | null>;\n result: (() => Promise<ContainerRotationResult>) | undefined;\n}): Promise<ContainerRotationResult> {\n return input.result\n ? input.result()\n : submitPlainContainerMutation(input.plain);\n}\n\n/**\n * Submit a rotation; if the server refuses it for stranding a level above a\n * directly granted container, sign the descendant rekeys it names and resubmit\n * once with them carried. The refused attempt rolled back whole, so the signed\n * rotation still extends the current head and only the descendants need\n * signing. A second refusal means the tree moved underneath, and the caller's\n * own retry starts from a fresh projection.\n */\nexport async function submitRotationCarryingDescendants(input: {\n carriedRekeys?: CarriedRekeys | undefined;\n stillCurrent?: (() => boolean) | undefined;\n submit: (\n carried: readonly ContainerMutationRequest[],\n ) => Promise<ContainerRotationResult>;\n}): Promise<{\n carriedPlans: MaterializedContainerRekeyPlan[];\n result: ContainerRotationResult;\n}> {\n const result = await input.submit([]);\n if (\n result.ok ||\n result.code !== CONTAINER_MUTATION_ERROR_CODES.descendantRekeysRequired ||\n !result.requiredContainerIds?.length ||\n !input.carriedRekeys\n ) {\n return { carriedPlans: [], result: reportTerminalRefusal(result) };\n }\n // Answerable, so not an error: callers submit with `reportErrors: false` and\n // only the refusal that ends the attempt is surfaced.\n const carriedPlans = await planCarriedDescendantRekeys({\n ...input.carriedRekeys.planning,\n requiredContainerIds: result.requiredContainerIds,\n rotated: [await input.carriedRekeys.rotated()],\n });\n // Superseded mid-flight: hand back the refusal unreported, since the caller\n // discards it and the generation that owned this attempt is gone.\n if (input.stillCurrent?.() === false) return { carriedPlans: [], result };\n return {\n carriedPlans,\n result: reportTerminalRefusal(\n await input.submit(carriedPlans.map(({ plan }) => plan.request)),\n ),\n };\n}\n\nfunction reportTerminalRefusal(\n result: ContainerRotationResult,\n): ContainerRotationResult {\n if (!result.ok) result.report?.();\n return result;\n}\n\n/**\n * Submit and acknowledge remote share/rekey/revoke/move plans before scheduling\n * opportunistic descendant re-citations. Create separately handles its lost\n * response conflict; group share caches the rotated policy after this tail.\n */\nexport async function submitAcknowledgedContainerMutation<\n TPlan extends Parameters<typeof acknowledgeContainerMutation>[0][\"plan\"],\n>(input: {\n apiClient: ContainerReciteApi;\n author: ContainerMutationAuthor;\n /** Present exactly when the plan minted a new key epoch. */\n carriedRekeys?: CarriedRekeys | undefined;\n containerKey: Uint8Array;\n execSql: ExecSql;\n plan: TPlan;\n recitationPolicies: readonly PrincipalPolicyCheckpointEvidence[];\n /**\n * Called once the server has accepted the mutation, before this device\n * acknowledges it, so a caller can tell an accepted mutation it failed to\n * settle from one that never committed.\n */\n onAccepted?: (() => void) | undefined;\n /** Session lifetime for best-effort work after durable acknowledgement. */\n recitationStillCurrent?: (() => boolean) | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n stillCurrent?: (() => boolean) | undefined;\n submit: (\n carried: readonly ContainerMutationRequest[],\n ) => Promise<ContainerRotationResult>;\n}): Promise<{\n containerKey: Uint8Array;\n plan: TPlan;\n response: ContainerRotationResponse;\n} | null> {\n if (input.stillCurrent?.() === false) return null;\n const submitted = await submitRotationCarryingDescendants(input);\n if (!submitted.result.ok) {\n // Final, unlike the other refusals: a queued move must not retry it.\n if (isContainerPathTooDeepFailure(submitted.result))\n throw new ContainerPathTooDeepError();\n return null;\n }\n input.onAccepted?.();\n const { carriedPlans } = submitted;\n const response = submitted.result.data;\n\n const acknowledged =\n carriedPlans.length === 0\n ? await acknowledgeContainerMutation({\n execSql: input.execSql,\n plan: input.plan,\n response,\n stillCurrent: input.stillCurrent,\n })\n : // The rotation and what it carried committed together, so their pins\n // advance together: a missing acknowledgement refuses the whole batch.\n await acknowledgeContainerMutationBatch({\n execSql: input.execSql,\n plans: [input.plan, ...carriedPlans.map(({ plan }) => plan)],\n responses: [response, ...(response.containerRekeys ?? [])],\n stillCurrent: input.stillCurrent,\n });\n if (!acknowledged || input.stillCurrent?.() === false) return null;\n\n try {\n rememberVerifiedContainerHeads({\n execSql: input.execSql,\n organizationId: input.author.organizationId,\n heads: [],\n policies: input.recitationPolicies,\n });\n scheduleHeldDescendantRecitations({\n apiClient: input.apiClient,\n author: input.author,\n execSql: input.execSql,\n // `plans` are the containers whose descendants get re-cited; they are\n // never re-cited themselves. A carried rekey already cites the current\n // path, so listing it here spares its recitation budget.\n plans: [input.plan, ...carriedPlans.map(({ plan }) => plan)],\n reportSecurityIncident: input.reportSecurityIncident,\n stillCurrent: input.recitationStillCurrent ?? input.stillCurrent,\n });\n } catch {\n // Optional cache population cannot change an acknowledged mutation result.\n }\n return {\n containerKey: input.containerKey,\n plan: input.plan,\n response,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mutationSubmit.js","sourceRoot":"","sources":["mutationSubmit.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,GAE/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,yBAAyB,EAAE,MAAM,qDAAqD,CAAC;AAChG,OAAO,EACL,4BAA4B,EAC5B,iCAAiC,GAClC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AAOjG,OAAO,EAAE,8BAA8B,EAAE,MAAM,2EAA2E,CAAC;AAI3H,OAAO,EAAE,iCAAiC,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,EAEL,2BAA2B,GAE5B,MAAM,iCAAiC,CAAC;AAazC,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,KAAsD;IAEtD,MAAM,IAAI,GAAG,MAAM,KAAK,EAAE,CAAC;IAC3B,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,CA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AE,CAAC,IAAI,CAAC,CAAC;gBAC5D,SAAS,EAAE,CAAC,QAAQ,EAAE,GAAG,CAAC,QAAQ,CAAC,eAAe,IAAI,EAAE,CAAC,CAAC;gBAC1D,YAAY,EAAE,KAAK,CAAC,YAAY;aACjC,CAAC,CAAC;IACT,IAAI,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAEnE,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;YAC3C,KAAK,EAAE,EAAE;YACT,QAAQ,EAAE,KAAK,CAAC,kBAAkB;SACnC,CAAC,CAAC;QACH,iCAAiC,CAAC;YAChC,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,sEAAsE;YACtE,uEAAuE;YACvE,yDAAyD;YACzD,KAAK,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;YAC5D,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,YAAY,EAAE,KAAK,CAAC,sBAAsB,IAAI,KAAK,CAAC,YAAY;SACjE,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;IAC7E,CAAC;IACD,OAAO;QACL,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,QAAQ;KACT,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerMutationRequest } from \"@tearleads/validators/request\";\nimport {\n CONTAINER_MUTATION_ERROR_CODES,\n type ContainerRotationResponse,\n} from \"@tearleads/validators/response\";\nimport { ContainerPathTooDeepError } from \"../../../data/containers/shared/containerPathLimits\";\nimport {\n acknowledgeContainerMutation,\n acknowledgeContainerMutationBatch,\n} from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport { isContainerPathTooDeepFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport type { ContainerReciteApi } from \"../../../data/containers/shared/reciteApi\";\nimport type {\n ContainerMutationAuthor,\n ContainerRotationResult,\n MaterializedContainerRekeyPlan,\n} from \"../../../data/containers/shared/types\";\nimport { rememberVerifiedContainerHeads } from \"../../../data/keyingProjectionVerification/checkpoints/heldContainerHeads\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../../data/principalContracts/principalPolicyEvidence\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { scheduleHeldDescendantRecitations } from \"./recite\";\nimport {\n type CarriedRekeyPlanningInput,\n planCarriedDescendantRekeys,\n type SpeculativePath,\n} from \"./rekey/carriedDescendantRekeys\";\n\n/**\n * Supplied by mutations that mint a new key epoch (rekey, revoke, move). The\n * server refuses one that would strand a level above a directly granted\n * container, and names the descendant rekeys it must carry instead (#2340).\n */\nexport interface CarriedRekeys {\n readonly planning: CarriedRekeyPlanningInput;\n /** The rotated container's own path once the rotation is accepted. */\n readonly rotated: () => Promise<SpeculativePath>;\n}\n\n/** A mutation with no status-bearing variant: a share mints nothing to carry. */\nexport async function submitPlainContainerMutation(\n plain: () => Promise<ContainerRotationResponse | null>,\n): Promise<ContainerRotationResult> {\n const data = await plain();\n return data ? { data, ok: true } : { ok: false, status: null };\n}\n\n/**\n * Adapt a rotation endpoint pair to one status-bearing call. An adapter with\n * only the plain method still rotates; it just cannot learn what to carry, so a\n * rotation that needs descendants fails as any other refusal does.\n */\nexport async function submitContainerRotation(input: {\n plain: () => Promise<ContainerRotationResponse | null>;\n result: (() => Promise<ContainerRotationResult>) | undefined;\n}): Promise<ContainerRotationResult> {\n return input.result\n ? input.result()\n : submitPlainContainerMutation(input.plain);\n}\n\n/**\n * Submit a rotation; if the server refuses it for stranding a level above a\n * directly granted container, sign the descendant rekeys it names and resubmit\n * once with them carried. The refused attempt rolled back whole, so the signed\n * rotation still extends the current head and only the descendants need\n * signing. A second refusal means the tree moved underneath, and the caller's\n * own retry starts from a fresh projection.\n */\nexport async function submitRotationCarryingDescendants(input: {\n carriedRekeys?: CarriedRekeys | undefined;\n stillCurrent?: (() => boolean) | undefined;\n submit: (\n carried: readonly ContainerMutationRequest[],\n ) => Promise<ContainerRotationResult>;\n}): Promise<{\n carriedPlans: MaterializedContainerRekeyPlan[];\n result: ContainerRotationResult;\n}> {\n const result = await input.submit([]);\n if (\n result.ok ||\n result.code !== CONTAINER_MUTATION_ERROR_CODES.descendantRekeysRequired ||\n !result.requiredContainerIds?.length ||\n !input.carriedRekeys\n ) {\n return { carriedPlans: [], result: reportTerminalRefusal(result) };\n }\n // Answerable, so not an error: callers submit with `reportErrors: false` and\n // only the refusal that ends the attempt is surfaced.\n const carriedPlans = await planCarriedDescendantRekeys({\n ...input.carriedRekeys.planning,\n requiredContainerIds: result.requiredContainerIds,\n rotated: [await input.carriedRekeys.rotated()],\n });\n // Superseded mid-flight: hand back the refusal unreported, since the caller\n // discards it and the generation that owned this attempt is gone.\n if (input.stillCurrent?.() === false) return { carriedPlans: [], result };\n return {\n carriedPlans,\n result: reportTerminalRefusal(\n await input.submit(carriedPlans.map(({ plan }) => plan.request)),\n ),\n };\n}\n\nfunction reportTerminalRefusal(\n result: ContainerRotationResult,\n): ContainerRotationResult {\n if (!result.ok) result.report?.();\n return result;\n}\n\n/**\n * Submit and acknowledge remote share/rekey/revoke/move plans before scheduling\n * opportunistic descendant re-citations. Create separately handles its lost\n * response conflict; group share caches the rotated policy after this tail.\n */\nexport async function submitAcknowledgedContainerMutation<\n TPlan extends Parameters<typeof acknowledgeContainerMutation>[0][\"plan\"],\n>(input: {\n apiClient: ContainerReciteApi;\n author: ContainerMutationAuthor;\n /** Present exactly when the plan minted a new key epoch. */\n carriedRekeys?: CarriedRekeys | undefined;\n containerKey: Uint8Array;\n execSql: ExecSql;\n plan: TPlan;\n recitationPolicies: readonly PrincipalPolicyCheckpointEvidence[];\n /**\n * Called once the server has accepted the mutation, before this device\n * acknowledges it, so a caller can tell an accepted mutation it failed to\n * settle from one that never committed.\n */\n onAccepted?: (() => void) | undefined;\n /** Session lifetime for best-effort work after durable acknowledgement. */\n recitationStillCurrent?: (() => boolean) | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n stillCurrent?: (() => boolean) | undefined;\n submit: (\n carried: readonly ContainerMutationRequest[],\n ) => Promise<ContainerRotationResult>;\n}): Promise<{\n containerKey: Uint8Array;\n plan: TPlan;\n response: ContainerRotationResponse;\n} | null> {\n if (input.stillCurrent?.() === false) return null;\n const submitted = await submitRotationCarryingDescendants(input);\n if (!submitted.result.ok) {\n // Final, unlike the other refusals: a queued move must not retry it.\n if (isContainerPathTooDeepFailure(submitted.result))\n throw new ContainerPathTooDeepError();\n return null;\n }\n input.onAccepted?.();\n const { carriedPlans } = submitted;\n const response = submitted.result.data;\n\n const acknowledged =\n carriedPlans.length === 0\n ? await acknowledgeContainerMutation({\n execSql: input.execSql,\n plan: input.plan,\n response,\n stillCurrent: input.stillCurrent,\n })\n : // The rotation and what it carried committed together, so their pins\n // advance together: a missing acknowledgement refuses the whole batch.\n await acknowledgeContainerMutationBatch({\n execSql: input.execSql,\n plans: [input.plan, ...carriedPlans.map(({ plan }) => plan)],\n responses: [response, ...(response.containerRekeys ?? [])],\n stillCurrent: input.stillCurrent,\n });\n if (!acknowledged || input.stillCurrent?.() === false) return null;\n\n try {\n rememberVerifiedContainerHeads({\n execSql: input.execSql,\n organizationId: input.author.organizationId,\n heads: [],\n policies: input.recitationPolicies,\n });\n scheduleHeldDescendantRecitations({\n apiClient: input.apiClient,\n author: input.author,\n execSql: input.execSql,\n // `plans` are the containers whose descendants get re-cited; they are\n // never re-cited themselves. A carried rekey already cites the current\n // path, so listing it here spares its recitation budget.\n plans: [input.plan, ...carriedPlans.map(({ plan }) => plan)],\n reportSecurityIncident: input.reportSecurityIncident,\n stillCurrent: input.recitationStillCurrent ?? input.stillCurrent,\n });\n } catch {\n // Optional cache population cannot change an acknowledged mutation result.\n }\n return {\n containerKey: input.containerKey,\n plan: input.plan,\n response,\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { heldContainerPath, heldContainerSnapshot, rememberAcknowledgedContainerHead, } from "../../../data/
|
|
2
|
+
import { heldContainerPath, heldContainerSnapshot, rememberAcknowledgedContainerHead, } from "../../../data/keyingProjectionVerification/checkpoints/heldContainerHeads.js";
|
|
3
3
|
import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
4
4
|
import { locallyAuthoredAccessManifestHead } from "../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js";
|
|
5
5
|
import { resolveCanonicalExecSql, } from "../../../data/sqlite/sqlSchema.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recite.js","sourceRoot":"","sources":["recite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAEL,iBAAiB,EACjB,qBAAqB,EACrB,iCAAiC,GAClC,MAAM,oDAAoD,CAAC;AAI5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,iCAAiC,EAAE,MAAM,sFAAsF,CAAC;AAEzI,OAAO,EAEL,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,oCAAoC,EACpC,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,cAAc,CAAC;AAEtB,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAW9B,KAAK,UAAU,Y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ACvB,KAAK,OAAO,CAAC,OAAO,EAAE;SACnB,IAAI,CAAC,GAAG,EAAE,CACT,qBAAqB,CAAC;QACpB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,sEAAsE;QACtE,iEAAiE;QACjE,OAAO,EAAE,SAAS;QAClB,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;QACpD,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,WAAW,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC;KACzD,CAAC,CACH;SACA,KAAK,CAAC,GAAG,EAAE;QACV,wEAAwE;IAC1E,CAAC,CAAC;SACD,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n type HeldContainerHead,\n heldContainerPath,\n heldContainerSnapshot,\n rememberAcknowledgedContainerHead,\n} from \"../../../data/containers/shared/heldContainerHeads\";\nimport type { AuthoredContainerMutationHead } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport type { ContainerReciteApi } from \"../../../data/containers/shared/reciteApi\";\nimport type { ContainerMutationAuthor } from \"../../../data/containers/shared/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { locallyAuthoredAccessManifestHead } from \"../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport {\n type ExecSql,\n resolveCanonicalExecSql,\n} from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertContainerReciteAcknowledgement,\n buildContainerRecitePlan,\n referencedRecitationPolicies,\n} from \"./recitePlan\";\n\nconst MAX_RECITES_PER_PASS = 8;\nconst RECITE_SPACING_MS = 250;\n\ninterface ReciteHeldDescendantsInput {\n readonly apiClient: ContainerReciteApi;\n readonly author: ContainerMutationAuthor;\n readonly ancestorIds: readonly string[];\n readonly execSql: ExecSql;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nasync function pathIsPinned(\n execSql: ExecSql,\n path: readonly HeldContainerHead[],\n): Promise<boolean> {\n for (const head of path) {\n const checkpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadAccessManifestCheckpoint(\n \"container\",\n head.state.organizationId,\n head.state.containerId,\n );\n if (checkpoint?.manifestHash !== head.bundle.manifestHash) return false;\n }\n return true;\n}\n\nasync function recitePinnedPath(\n input: ReciteHeldDescendantsInput,\n path: readonly HeldContainerHead[],\n policies: ReturnType<typeof heldContainerSnapshot>[\"policies\"],\n): Promise<HeldContainerHead | null> {\n const usedPolicies = referencedRecitationPolicies(path, policies);\n if (!(await policiesArePinned(input.execSql, usedPolicies))) return null;\n const plan = await buildContainerRecitePlan({\n author: input.author,\n path,\n policies: usedPolicies,\n });\n if (!(await policiesArePinned(input.execSql, usedPolicies))) return null;\n if (!(await pathIsPinned(input.execSql, path))) return null;\n if (input.stillCurrent?.() === false) return null;\n const id = plan.state.containerId;\n const response = await input.apiClient.reciteContainer(id, plan.request, {\n reportErrors: false,\n });\n if (!response || input.stillCurrent?.() === false) return null;\n try {\n assertContainerReciteAcknowledgement(plan, response);\n } catch (error) {\n const failure =\n error instanceof KeyingVerificationError\n ? error\n : new KeyingVerificationError(\n \"invalid_shape\",\n \"Malformed re-citation acknowledgement\",\n );\n await input.reportSecurityIncident(failure, {\n operation: \"container.recite.acknowledge\",\n objectKind: \"container\",\n objectId: id,\n organizationId: input.author.organizationId,\n evidenceHashes: { plannedManifestHash: plan.manifestHash },\n });\n return null;\n }\n let acknowledged: boolean;\n try {\n acknowledged = await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [locallyAuthoredAccessManifestHead(plan)],\n expectedAccessManifestCheckpoints: path.map((head) => ({\n objectKind: \"container\",\n objectId: head.state.containerId,\n organizationId: head.state.organizationId,\n epoch: head.state.epoch,\n manifestHash: head.bundle.manifestHash,\n })),\n expectedPrincipalPolicyCheckpoints: usedPolicies.map(\n (policy) => policy.checkpoint,\n ),\n stillCurrent: input.stillCurrent,\n });\n } catch (error) {\n if (!(error instanceof KeyingVerificationError)) throw error;\n // Another local operation can advance the durable pin while the request\n // is in flight. Refuse the write, but do not label that local race as a\n // contradictory server response: the exact signed acknowledgement above\n // already passed. Normal projection verification reconciles newer heads.\n return null;\n }\n if (!acknowledged || input.stillCurrent?.() === false) return null;\n return rememberAcknowledgedContainerHead(input.execSql, plan);\n}\n\nasync function policiesArePinned(\n execSql: ExecSql,\n policies: ReturnType<typeof referencedRecitationPolicies>,\n): Promise<boolean> {\n for (const policy of policies) {\n const checkpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(policy.principalType, policy.principalId);\n if (\n checkpoint?.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n )\n return false;\n }\n return true;\n}\n\nasync function waitForPinnedPath(\n input: ReciteHeldDescendantsInput,\n path: readonly HeldContainerHead[],\n attempts: number,\n): Promise<boolean> {\n if (!(await pathIsPinned(input.execSql, path))) return false;\n if (attempts > 0) {\n await new Promise((resolve) => setTimeout(resolve, RECITE_SPACING_MS));\n if (!(await pathIsPinned(input.execSql, path))) return false;\n }\n return input.stillCurrent?.() !== false;\n}\n\n/**\n * Best effort only: never fetches a subtree or policy, never retries conflicts,\n * and never turns an unavailable/missing descendant into an ancestor refusal.\n * The API checks admin authority and exact current paths again at commit time.\n */\nexport async function reciteHeldDescendants(\n input: ReciteHeldDescendantsInput,\n): Promise<void> {\n const snapshot = heldContainerSnapshot(\n input.execSql,\n input.author.organizationId,\n );\n const ancestors = new Set(input.ancestorIds);\n const candidates = [...snapshot.heads.keys()]\n .map((id) => ({ id, path: heldContainerPath(snapshot.heads, id) }))\n .filter(\n ({ id, path }) =>\n !ancestors.has(id) &&\n path?.some((head) => ancestors.has(head.state.containerId)),\n )\n .sort((a, b) => (a.path?.length ?? 0) - (b.path?.length ?? 0));\n let attempts = 0;\n for (const { id } of candidates) {\n if (attempts >= MAX_RECITES_PER_PASS) return;\n if (input.stillCurrent?.() === false) return;\n try {\n const path = heldContainerPath(snapshot.heads, id);\n if (!path) continue;\n // Every held head must still equal its durable pin. A failed projection,\n // concurrent mutation, or verify-without-persist result cannot become an\n // implicit checkpoint advance through this opportunistic path.\n if (!(await waitForPinnedPath(input, path, attempts))) continue;\n attempts += 1;\n const updated = await recitePinnedPath(input, path, snapshot.policies);\n if (updated) snapshot.heads.set(id, updated);\n } catch {\n // A later reconciliation can observe any committed response we lost.\n // Do not retry here or change the result of the acknowledged ancestor.\n }\n }\n}\n\nconst running = new WeakSet<ExecSql>();\n\n/** Called only after exact acknowledgement of the original mutation. */\nexport function scheduleHeldDescendantRecitations(\n input: Omit<ReciteHeldDescendantsInput, \"ancestorIds\"> & {\n readonly plans: readonly AuthoredContainerMutationHead[];\n },\n): void {\n if (input.stillCurrent?.() === false) return;\n try {\n for (const plan of input.plans) {\n rememberAcknowledgedContainerHead(input.execSql, plan);\n }\n } catch {\n return;\n }\n const canonical = resolveCanonicalExecSql(input.execSql);\n if (running.has(canonical)) return;\n running.add(canonical);\n void Promise.resolve()\n .then(() =>\n reciteHeldDescendants({\n apiClient: input.apiClient,\n author: input.author,\n // Background work outlives the caller's lock scope. Use the canonical\n // executor so its checkpoint write acquires a new mutation lock.\n execSql: canonical,\n reportSecurityIncident: input.reportSecurityIncident,\n stillCurrent: input.stillCurrent,\n ancestorIds: input.plans.map((plan) => plan.containerId),\n }),\n )\n .catch(() => {\n // Failure is deliberately independent of the user's completed mutation.\n })\n .finally(() => running.delete(canonical));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recite.js","sourceRoot":"","sources":["recite.ts"],"names":[],"mappings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AM,UAAU,iCAAiC,CAC/C,KAEC;IAED,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO;IAC7C,IAAI,CAAC;QACH,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YAC/B,iCAAiC,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,OAAO;IACT,CAAC;IACD,MAAM,SAAS,GAAG,uBAAuB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACzD,IAAI,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;QAAE,OAAO;IACnC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACvB,KAAK,OAAO,CAAC,OAAO,EAAE;SACnB,IAAI,CAAC,GAAG,EAAE,CACT,qBAAqB,CAAC;QACpB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,sEAAsE;QACtE,iEAAiE;QACjE,OAAO,EAAE,SAAS;QAClB,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;QACpD,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,WAAW,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC;KACzD,CAAC,CACH;SACA,KAAK,CAAC,GAAG,EAAE;QACV,wEAAwE;IAC1E,CAAC,CAAC;SACD,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { AuthoredContainerMutationHead } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport type { ContainerReciteApi } from \"../../../data/containers/shared/reciteApi\";\nimport type { ContainerMutationAuthor } from \"../../../data/containers/shared/types\";\nimport {\n type HeldContainerHead,\n heldContainerPath,\n heldContainerSnapshot,\n rememberAcknowledgedContainerHead,\n} from \"../../../data/keyingProjectionVerification/checkpoints/heldContainerHeads\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { locallyAuthoredAccessManifestHead } from \"../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport {\n type ExecSql,\n resolveCanonicalExecSql,\n} from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertContainerReciteAcknowledgement,\n buildContainerRecitePlan,\n referencedRecitationPolicies,\n} from \"./recitePlan\";\n\nconst MAX_RECITES_PER_PASS = 8;\nconst RECITE_SPACING_MS = 250;\n\ninterface ReciteHeldDescendantsInput {\n readonly apiClient: ContainerReciteApi;\n readonly author: ContainerMutationAuthor;\n readonly ancestorIds: readonly string[];\n readonly execSql: ExecSql;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nasync function pathIsPinned(\n execSql: ExecSql,\n path: readonly HeldContainerHead[],\n): Promise<boolean> {\n for (const head of path) {\n const checkpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadAccessManifestCheckpoint(\n \"container\",\n head.state.organizationId,\n head.state.containerId,\n );\n if (checkpoint?.manifestHash !== head.bundle.manifestHash) return false;\n }\n return true;\n}\n\nasync function recitePinnedPath(\n input: ReciteHeldDescendantsInput,\n path: readonly HeldContainerHead[],\n policies: ReturnType<typeof heldContainerSnapshot>[\"policies\"],\n): Promise<HeldContainerHead | null> {\n const usedPolicies = referencedRecitationPolicies(path, policies);\n if (!(await policiesArePinned(input.execSql, usedPolicies))) return null;\n const plan = await buildContainerRecitePlan({\n author: input.author,\n path,\n policies: usedPolicies,\n });\n if (!(await policiesArePinned(input.execSql, usedPolicies))) return null;\n if (!(await pathIsPinned(input.execSql, path))) return null;\n if (input.stillCurrent?.() === false) return null;\n const id = plan.state.containerId;\n const response = await input.apiClient.reciteContainer(id, plan.request, {\n reportErrors: false,\n });\n if (!response || input.stillCurrent?.() === false) return null;\n try {\n assertContainerReciteAcknowledgement(plan, response);\n } catch (error) {\n const failure =\n error instanceof KeyingVerificationError\n ? error\n : new KeyingVerificationError(\n \"invalid_shape\",\n \"Malformed re-citation acknowledgement\",\n );\n await input.reportSecurityIncident(failure, {\n operation: \"container.recite.acknowledge\",\n objectKind: \"container\",\n objectId: id,\n organizationId: input.author.organizationId,\n evidenceHashes: { plannedManifestHash: plan.manifestHash },\n });\n return null;\n }\n let acknowledged: boolean;\n try {\n acknowledged = await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [locallyAuthoredAccessManifestHead(plan)],\n expectedAccessManifestCheckpoints: path.map((head) => ({\n objectKind: \"container\",\n objectId: head.state.containerId,\n organizationId: head.state.organizationId,\n epoch: head.state.epoch,\n manifestHash: head.bundle.manifestHash,\n })),\n expectedPrincipalPolicyCheckpoints: usedPolicies.map(\n (policy) => policy.checkpoint,\n ),\n stillCurrent: input.stillCurrent,\n });\n } catch (error) {\n if (!(error instanceof KeyingVerificationError)) throw error;\n // Another local operation can advance the durable pin while the request\n // is in flight. Refuse the write, but do not label that local race as a\n // contradictory server response: the exact signed acknowledgement above\n // already passed. Normal projection verification reconciles newer heads.\n return null;\n }\n if (!acknowledged || input.stillCurrent?.() === false) return null;\n return rememberAcknowledgedContainerHead(input.execSql, plan);\n}\n\nasync function policiesArePinned(\n execSql: ExecSql,\n policies: ReturnType<typeof referencedRecitationPolicies>,\n): Promise<boolean> {\n for (const policy of policies) {\n const checkpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(policy.principalType, policy.principalId);\n if (\n checkpoint?.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n )\n return false;\n }\n return true;\n}\n\nasync function waitForPinnedPath(\n input: ReciteHeldDescendantsInput,\n path: readonly HeldContainerHead[],\n attempts: number,\n): Promise<boolean> {\n if (!(await pathIsPinned(input.execSql, path))) return false;\n if (attempts > 0) {\n await new Promise((resolve) => setTimeout(resolve, RECITE_SPACING_MS));\n if (!(await pathIsPinned(input.execSql, path))) return false;\n }\n return input.stillCurrent?.() !== false;\n}\n\n/**\n * Best effort only: never fetches a subtree or policy, never retries conflicts,\n * and never turns an unavailable/missing descendant into an ancestor refusal.\n * The API checks admin authority and exact current paths again at commit time.\n */\nexport async function reciteHeldDescendants(\n input: ReciteHeldDescendantsInput,\n): Promise<void> {\n const snapshot = heldContainerSnapshot(\n input.execSql,\n input.author.organizationId,\n );\n const ancestors = new Set(input.ancestorIds);\n const candidates = [...snapshot.heads.keys()]\n .map((id) => ({ id, path: heldContainerPath(snapshot.heads, id) }))\n .filter(\n ({ id, path }) =>\n !ancestors.has(id) &&\n path?.some((head) => ancestors.has(head.state.containerId)),\n )\n .sort((a, b) => (a.path?.length ?? 0) - (b.path?.length ?? 0));\n let attempts = 0;\n for (const { id } of candidates) {\n if (attempts >= MAX_RECITES_PER_PASS) return;\n if (input.stillCurrent?.() === false) return;\n try {\n const path = heldContainerPath(snapshot.heads, id);\n if (!path) continue;\n // Every held head must still equal its durable pin. A failed projection,\n // concurrent mutation, or verify-without-persist result cannot become an\n // implicit checkpoint advance through this opportunistic path.\n if (!(await waitForPinnedPath(input, path, attempts))) continue;\n attempts += 1;\n const updated = await recitePinnedPath(input, path, snapshot.policies);\n if (updated) snapshot.heads.set(id, updated);\n } catch {\n // A later reconciliation can observe any committed response we lost.\n // Do not retry here or change the result of the acknowledged ancestor.\n }\n }\n}\n\nconst running = new WeakSet<ExecSql>();\n\n/** Called only after exact acknowledgement of the original mutation. */\nexport function scheduleHeldDescendantRecitations(\n input: Omit<ReciteHeldDescendantsInput, \"ancestorIds\"> & {\n readonly plans: readonly AuthoredContainerMutationHead[];\n },\n): void {\n if (input.stillCurrent?.() === false) return;\n try {\n for (const plan of input.plans) {\n rememberAcknowledgedContainerHead(input.execSql, plan);\n }\n } catch {\n return;\n }\n const canonical = resolveCanonicalExecSql(input.execSql);\n if (running.has(canonical)) return;\n running.add(canonical);\n void Promise.resolve()\n .then(() =>\n reciteHeldDescendants({\n apiClient: input.apiClient,\n author: input.author,\n // Background work outlives the caller's lock scope. Use the canonical\n // executor so its checkpoint write acquires a new mutation lock.\n execSql: canonical,\n reportSecurityIncident: input.reportSecurityIncident,\n stillCurrent: input.stillCurrent,\n ancestorIds: input.plans.map((plan) => plan.containerId),\n }),\n )\n .catch(() => {\n // Failure is deliberately independent of the user's completed mutation.\n })\n .finally(() => running.delete(canonical));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recitePlan.js","sourceRoot":"","sources":["recitePlan.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,6BAA6B,EAC7B,uBAAuB,EACvB,8BAA8B,EAC9B,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;
|
|
1
|
+
{"version":3,"file":"recitePlan.js","sourceRoot":"","sources":["recitePlan.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,6BAA6B,EAC7B,uBAAuB,EACvB,8BAA8B,EAC9B,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EAAE,kBAAkB,EAAE,MAAM,mDAAmD,CAAC;AACvF,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAElF,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAIzE,MAAM,UAAU,4BAA4B,CAC1C,IAAkC,EAClC,QAAsD;IAEtD,MAAM,aAAa,GAAG,IAAI,GAAG,CAC3B,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,E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IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACjD,oBAAoB,CAAC,IAAI,CAAC,MAAM,CAAC,CAClC;QACD,mBAAmB,EAAE,4BAA4B,CAC/C,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,QAAQ,CACf,CAAC,GAAG,CAAC,kBAAkB,CAAC;KAC1B,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AAC5E,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,IAA0D,EAC1D,QAAiC;IAEjC,wEAAwE;IACxE,4EAA4E;IAC5E,IACE,QAAQ,CAAC,WAAW,KAAK,IAAI,CAAC,KAAK,CAAC,WAAW;QAC/C,QAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,KAAK,CAAC,cAAc;QACrD,QAAQ,CAAC,QAAQ,KAAK,IAAI,CAAC,KAAK,CAAC,iBAAiB;QAClD,CAAC,QAAQ,CAAC,UAAU,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,UAAU;QACvD,QAAQ,CAAC,YAAY,CAAC,KAAK,KAAK,IAAI,CAAC,KAAK,CAAC,KAAK;QAChD,QAAQ,CAAC,YAAY,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY;QACxD,QAAQ,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS;QAErC,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;AACN,CAAC","sourcesContent":["import {\n computeAccessManifestHash,\n deriveContainerAccessManifest,\n KeyingVerificationError,\n MAX_CONTAINER_RECITATION_EPOCH,\n resolveContainerStatePathUserAccessLevel,\n} from \"@tearleads/crypto\";\nimport type { ContainerReciteRequest } from \"@tearleads/validators/request\";\nimport type { ContainerReciteResponse } from \"@tearleads/validators/response\";\nimport { signContainerMutationEvent } from \"../../../data/containers/shared/events\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport { containerManifestRef } from \"../../../data/containers/shared/projection\";\nimport type { ContainerMutationAuthor } from \"../../../data/containers/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type { HeldContainerHead } from \"../../../data/keyingProjectionVerification/checkpoints/heldContainerHeads\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../../data/principalContracts/principalPolicyEvidence\";\n\nexport function referencedRecitationPolicies(\n path: readonly HeldContainerHead[],\n policies: readonly PrincipalPolicyCheckpointEvidence[],\n): readonly PrincipalPolicyCheckpointEvidence[] {\n const referencedIds = new Set(\n path.flatMap((head) =>\n head.state.referencedPrincipalHeads.map(\n (ref) => `${ref.principalType}:${ref.principalId}`,\n ),\n ),\n );\n return policies.filter((policy) =>\n referencedIds.has(`${policy.principalType}:${policy.principalId}`),\n );\n}\n\nexport async function buildContainerRecitePlan(input: {\n readonly author: ContainerMutationAuthor;\n readonly path: readonly HeldContainerHead[];\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n}) {\n const previous = input.path.at(-1);\n if (!previous) throw new Error(\"Recitation requires a held container path\");\n if (previous.state.epoch >= MAX_CONTAINER_RECITATION_EPOCH) {\n throw new Error(\"Container re-citation history budget is exhausted\");\n }\n if (\n input.path.some(\n (head) => head.state.organizationId !== input.author.organizationId,\n )\n ) {\n throw new Error(\"Recitation cannot cross organizations\");\n }\n if (\n resolveContainerStatePathUserAccessLevel({\n states: input.path.map((head) => head.state),\n principalPolicies: input.policies,\n userId: input.author.signerUserId,\n }) !== \"admin\"\n ) {\n throw new KeyingVerificationError(\n \"unauthorized\",\n \"Container re-citation signer lacks admin access on the held path\",\n );\n }\n const body = {\n eventType: \"container.recite\" as const,\n containerKeyEpochId: previous.state.containerKeyEpochId,\n containerKeyPublicKey: previous.state.containerKeyPublicKey,\n };\n const { event, eventHash } = await signContainerMutationEvent({\n author: input.author,\n body,\n containerId: previous.state.containerId,\n dependencyManifestHashes: input.path.map(\n (head) => head.bundle.manifestHash,\n ),\n eventId: crypto.randomUUID(),\n previousManifestHash: previous.bundle.manifestHash,\n signedAt: new Date().toISOString(),\n });\n const state = {\n ...previous.state,\n epoch: previous.state.epoch + 1,\n eventHash,\n previousManifestHash: previous.bundle.manifestHash,\n };\n const manifest = await deriveContainerAccessManifest(state);\n const manifestHash = await computeAccessManifestHash(manifest);\n const request: ContainerReciteRequest = {\n body,\n event: readCanonicalRecord(event, \"Recitation event\"),\n manifest: readCanonicalRecord(manifest, \"Recitation manifest\"),\n expectedManifestHash: manifestHash,\n previousManifestRef: containerManifestRef(previous.bundle),\n previousContainerPathRefs: input.path.map((head) =>\n containerManifestRef(head.bundle),\n ),\n principalPolicyRefs: referencedRecitationPolicies(\n input.path,\n input.policies,\n ).map(principalPolicyRef),\n };\n return { body, event, eventHash, manifest, manifestHash, state, request };\n}\n\nexport function assertContainerReciteAcknowledgement(\n plan: Awaited<ReturnType<typeof buildContainerRecitePlan>>,\n response: ContainerReciteResponse,\n): void {\n // The manifest hash commits to the signed event, the derived state, and\n // the cited principal heads, so equal hashes acknowledge exactly this plan.\n if (\n response.containerId !== plan.state.containerId ||\n response.organizationId !== plan.state.organizationId ||\n response.parentId !== plan.state.parentContainerId ||\n (response.systemSlot ?? null) !== plan.state.systemSlot ||\n response.manifestHead.epoch !== plan.state.epoch ||\n response.manifestHead.manifestHash !== plan.manifestHash ||\n response.eventHash !== plan.eventHash\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container recitation response does not match the signed plan\",\n );\n}\n"]}
|
package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { rememberVerifiedContainerHeads } from "../../../data/containers/shared/heldContainerHeads.js";
|
|
2
1
|
import { acknowledgeContainerMutationBatch } from "../../../data/containers/shared/mutationAcknowledgement.js";
|
|
2
|
+
import { rememberVerifiedContainerHeads } from "../../../data/keyingProjectionVerification/checkpoints/heldContainerHeads.js";
|
|
3
3
|
import { scheduleHeldDescendantRecitations } from "../child/recite.js";
|
|
4
4
|
export async function acknowledgePrincipalContainerRematerialization(input, entries, responses, stillCurrent) {
|
|
5
5
|
const isCurrent = () => input.stillCurrent?.() !== false && stillCurrent?.() !== false;
|
package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"acknowledgePrincipalContainerRematerialization.js","sourceRoot":"","sources":["acknowledgePrincipalContainerRematerialization.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"acknowledgePrincipalContainerRematerialization.js","sourceRoot":"","sources":["acknowledgePrincipalContainerRematerialization.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iCAAiC,EAAE,MAAM,yDAAyD,CAAC;AAC5G,OAAO,EAAE,8BAA8B,EAAE,MAAM,2EAA2E,CAAC;AAC3H,OAAO,EAAE,iCAAiC,EAAE,MAAM,iBAAiB,CAAC;AAIpE,MAAM,CAAC,KAAK,UAAU,8CAA8C,CAClE,KAA+C,EAC/C,OAA4C,EAC5C,SAA+C,EAC/C,YAA0C;IAE1C,MAAM,SAAS,GAAG,GAAG,EAAE,CACrB,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,IAAI,YAAY,EAAE,EAAE,KAAK,KAAK,CAAC;IACjE,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,MAAM,YAAY,GAAG,MAAM,iCAAiC,CAAC;QAC3D,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,KAAK,EAAE,KAAK;QACZ,SAAS;QACT,YAAY,EAAE,SAAS;KACxB,CAAC,CAAC;IACH,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,EAAE;QAAE,OAAO;IAC1C,MAAM,mBAAmB,GAAG,IAAI,GAAG,EAGhC,CAAC;IACJ,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC;QACjD,MAAM,KAAK,GAAG,mBAAmB,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;QAC5D,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjB,mBAAmB,CAAC,GAAG,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC;IACD,KAAK,MAAM,CAAC,cAAc,EAAE,iBAAiB,CAAC,IAAI,mBAAmB,EAAE,CAAC;QACtE,IAAI,CAAC;YACH,8BAA8B,CAAC;gBAC7B,cAAc;gBACd,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,KAAK,EAAE,EAAE;gBACT,QAAQ,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC;aAC7B,CAAC,CAAC;QACL,CAAC;QAAC,MAAM,CAAC;YACP,oEAAoE;YACpE,SAAS;QACX,CAAC;QACD,iCAAiC,CAAC;YAChC,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,MAAM,EAAE,EAAE,GAAG,KAAK,CAAC,MAAM,EAAE,cAAc,EAAE;YAC3C,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,KAAK,EAAE,iBAAiB;YACxB,YAAY,EAAE,KAAK,CAAC,sBAAsB,IAAI,SAAS;YACvD,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;SACrD,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import type { ContainerMutationResponse } from \"@tearleads/validators/response\";\nimport type { AuthoredContainerMutationHead } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport { acknowledgeContainerMutationBatch } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport { rememberVerifiedContainerHeads } from \"../../../data/keyingProjectionVerification/checkpoints/heldContainerHeads\";\nimport { scheduleHeldDescendantRecitations } from \"../child/recite\";\nimport type { PrincipalContainerRematerializationInput } from \"./principalContainerRematerializationPlanning\";\nimport type { PlannedRematerialization } from \"./principalContainerRematerializationTargets\";\n\nexport async function acknowledgePrincipalContainerRematerialization(\n input: PrincipalContainerRematerializationInput,\n entries: readonly PlannedRematerialization[],\n responses: readonly ContainerMutationResponse[],\n stillCurrent?: (() => boolean) | undefined,\n): Promise<void> {\n const isCurrent = () =>\n input.stillCurrent?.() !== false && stillCurrent?.() !== false;\n const heads = entries.map((entry) => entry.planned.plan);\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.execSql,\n plans: heads,\n responses,\n stillCurrent: isCurrent,\n });\n if (!acknowledged || !isCurrent()) return;\n const plansByOrganization = new Map<\n string,\n AuthoredContainerMutationHead[]\n >();\n for (const head of heads) {\n const organizationId = head.state.organizationId;\n const group = plansByOrganization.get(organizationId) ?? [];\n group.push(head);\n plansByOrganization.set(organizationId, group);\n }\n for (const [organizationId, organizationPlans] of plansByOrganization) {\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql,\n heads: [],\n policies: [input.nextPolicy],\n });\n } catch {\n // Cache failure must not invalidate the durably acknowledged batch.\n continue;\n }\n scheduleHeldDescendantRecitations({\n apiClient: input.apiClient,\n author: { ...input.author, organizationId },\n execSql: input.execSql,\n plans: organizationPlans,\n stillCurrent: input.recitationStillCurrent ?? isCurrent,\n reportSecurityIncident: input.reportSecurityIncident,\n });\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DocumentProjectorRegistry, type DocumentProjectorRegistryInput } from "../../data/documents/documentKinds.js";
|
|
2
|
-
import type { DocumentsPersistence, StoredDocumentRecord } from "../../data/persistence/documents/documentsPersistence.js";
|
|
2
|
+
import type { DocumentPlacementCleanup, DocumentsPersistence, StoredDocumentRecord } from "../../data/persistence/documents/documentsPersistence.js";
|
|
3
3
|
import type { PendingUpdateFields } from "../../data/persistence/documents/records/index.js";
|
|
4
4
|
import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
|
|
5
5
|
import { type PrepareDocumentMutationInput } from "./documentMutationPreparation.js";
|
|
@@ -19,6 +19,7 @@ export interface PersistDocumentStateInput extends PrepareDocumentMutationInput
|
|
|
19
19
|
clearSyncFailure?: boolean | undefined;
|
|
20
20
|
commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>;
|
|
21
21
|
containerId?: string | null | undefined;
|
|
22
|
+
deleteDocumentPlacements: DocumentPlacementCleanup;
|
|
22
23
|
documentProjectors: DocumentProjectorRegistryInput;
|
|
23
24
|
execSql: ExecSql;
|
|
24
25
|
patch?: Partial<StoredDocumentRecord> | undefined;
|
|
@@ -268,6 +268,7 @@ export async function commitPreparedDocumentState(input) {
|
|
|
268
268
|
const acceptedPendingUpdateIds = persistInput.acceptedPendingUpdateIds ?? [];
|
|
269
269
|
for (let attempt = 0; attempt < MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS; attempt += 1) {
|
|
270
270
|
const mutation = await prepareDocumentMutationUnlessDeleted({
|
|
271
|
+
deleteDocumentPlacements: persistInput.deleteDocumentPlacements,
|
|
271
272
|
documentProjectors: input.documentProjectors,
|
|
272
273
|
guard: attempt === 0,
|
|
273
274
|
lockedExecSql,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentMutationCommit.js","sourceRoot":"","sources":["documentMutationCommit.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAGL,uBAAuB,GACxB,MAAM,oCAAoC,CAAC;AAO5C,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EACL,kCAAkC,GAGnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,oCAAoC,EAAE,MAAM,yBAAyB,CAAC;AAU/E,MAAM,qCAAqC,GAAG,CAAC,CAA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D,MAAM,MAAM,GAAG,MAAM,iCAAiC,CAAC;YACrD,wBAAwB;YACxB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,aAAa;YACb,QAAQ;YACR,YAAY;SACb,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,OAAO;YAAE,OAAO,MAAM,CAAC;IACxC,CAAC;IACD,MAAM,IAAI,KAAK,CACb,0CAA0C,qCAAqC,uBAAuB,CACvG,CAAC;AACJ,CAAC","sourcesContent":["import { type encodeVersionVector, getTextValue } from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../data/documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n readStoredDocumentState,\n} from \"../../data/documents/documentKinds\";\nimport type {\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PendingUpdateFields } from \"../../data/persistence/documents/records\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { createInitialDocumentRows } from \"./create/documentCreationPersistence\";\nimport {\n documentSyncSecurityContextMatches,\n type PrepareDocumentMutationInput,\n type prepareDocumentMutation,\n} from \"./documentMutationPreparation\";\nimport { prepareDocumentMutationUnlessDeleted } from \"./documentPersistGuards\";\n\ntype DocumentContentState = Parameters<typeof encodeVersionVector>[0];\ntype NullableDocumentRuntimeField =\n | \"accessStateHash\"\n | \"lastCommitLsn\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\";\n\nconst MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS = 8;\n\nexport interface PersistedDocumentState {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: StoredDocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\n\nexport interface PersistDocumentStateInput\n extends PrepareDocumentMutationInput {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?:\n | Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"attachmentRemoval\"]\n | undefined;\n attachmentStaging?:\n | Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"attachmentStaging\"]\n | undefined;\n canStartDurableMutation?: (() => boolean) | undefined;\n clearSyncFailure?: boolean | undefined;\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>;\n containerId?: string | null | undefined;\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n patch?: Partial<StoredDocumentRecord> | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n}\n\nasync function loadSupersededPersistedDocumentState(input: {\n creationSuperseded: boolean;\n execSql: ExecSql;\n localId: string;\n persistence: DocumentsPersistence;\n record: StoredDocumentRecord;\n syncIdentitySuperseded: boolean;\n}): Promise<PersistedDocumentState | null> {\n const { document, historyRestoreState } =\n await input.persistence.loadDocumentWithHistoryRestoreState(\n input.execSql,\n input.localId,\n );\n if (!document) return null;\n const syncIdentitySuperseded =\n input.syncIdentitySuperseded ||\n !documentSyncSecurityContextMatches(document, input.record);\n return {\n ...(input.creationSuperseded ? { creationSuperseded: true as const } : {}),\n historyRestoreState,\n pullContinuationSuperseded: true,\n record: document,\n ...(syncIdentitySuperseded\n ? { syncIdentitySuperseded: true as const }\n : {}),\n };\n}\n\nfunction resolveNullableDocumentRuntimeField(\n patch: Partial<StoredDocumentRecord>,\n key: NullableDocumentRuntimeField,\n currentValue: string | null | undefined,\n resetWhenUnpatched = false,\n): string | null {\n if (Object.hasOwn(patch, key)) return patch[key] ?? null;\n return resetWhenUnpatched ? null : (currentValue ?? null);\n}\n\nfunction resolveStoredDocumentContainerId(input: {\n containerId?: string | null | undefined;\n currentRecord: StoredDocumentRecord | null;\n patch: Partial<StoredDocumentRecord>;\n}): string | null {\n if (Object.hasOwn(input.patch, \"containerId\")) {\n return input.patch.containerId ?? null;\n }\n return input.currentRecord?.containerId ?? input.containerId ?? null;\n}\n\nfunction resolveStoredDocumentPullState(input: {\n currentRecord: StoredDocumentRecord | null;\n patch: Partial<StoredDocumentRecord>;\n securityContextChanged: boolean;\n}): Pick<\n StoredDocumentRecord,\n \"pullContinuation\" | \"pullContinuationRecoveryRequired\"\n> {\n if (Object.hasOwn(input.patch, \"pullContinuation\")) {\n return { pullContinuation: input.patch.pullContinuation ?? null };\n }\n if (input.securityContextChanged) return { pullContinuation: null };\n if (input.currentRecord?.pullContinuationRecoveryRequired) {\n return { pullContinuationRecoveryRequired: true };\n }\n return { pullContinuation: input.currentRecord?.pullContinuation ?? null };\n}\n\nfunction buildStoredDocumentRecord(input: {\n containerId?: string | null | undefined;\n currentDoc: DocumentContentState;\n currentRecord: StoredDocumentRecord | null;\n documentProjectors: DocumentProjectorRegistry;\n localId: string;\n patch: Partial<StoredDocumentRecord>;\n}) {\n const { currentDoc, currentRecord, documentProjectors, localId, patch } =\n input;\n const currentDocumentId = currentRecord?.documentId ?? null;\n const nextDocumentId = patch.documentId ?? currentDocumentId;\n const documentIdChanged = nextDocumentId !== currentDocumentId;\n const currentAccessEpoch =\n currentRecord?.accessEpoch ?? DEFAULT_DOCUMENT_ACCESS_EPOCH;\n const nextAccessEpoch = patch.accessEpoch ?? currentAccessEpoch;\n const securityContextChanged =\n documentIdChanged || nextAccessEpoch !== currentAccessEpoch;\n const documentState = readStoredDocumentState(currentDoc, documentProjectors);\n const record: StoredDocumentRecord = {\n id: currentRecord?.id ?? localId,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolveNullableDocumentRuntimeField(\n patch,\n \"accessStateHash\",\n currentRecord?.accessStateHash,\n securityContextChanged,\n ),\n containerId: resolveStoredDocumentContainerId({\n containerId: input.containerId,\n currentRecord,\n patch,\n }),\n contentKeyBundle: resolveNullableDocumentRuntimeField(\n patch,\n \"contentKeyBundle\",\n currentRecord?.contentKeyBundle,\n securityContextChanged,\n ),\n documentId: nextDocumentId,\n effectiveAccessLevel:\n patch.effectiveAccessLevel ?? currentRecord?.effectiveAccessLevel ?? null,\n documentKekTargets: resolveNullableDocumentRuntimeField(\n patch,\n \"documentKekTargets\",\n currentRecord?.documentKekTargets,\n securityContextChanged,\n ),\n documentKind: patch.documentKind ?? documentState.documentKind,\n documentManifestBundle: resolveNullableDocumentRuntimeField(\n patch,\n \"documentManifestBundle\",\n currentRecord?.documentManifestBundle,\n securityContextChanged,\n ),\n lastCommitLsn: resolveNullableDocumentRuntimeField(\n patch,\n \"lastCommitLsn\",\n currentRecord?.lastCommitLsn,\n documentIdChanged,\n ),\n snapshotEndVersion:\n patch.snapshotEndVersion ?? currentRecord?.snapshotEndVersion ?? \"\",\n pendingBaseVersion:\n patch.pendingBaseVersion !== undefined\n ? patch.pendingBaseVersion\n : (currentRecord?.pendingBaseVersion ?? null),\n recoveryGeneration:\n patch.recoveryGeneration ?? currentRecord?.recoveryGeneration ?? 0,\n ...resolveStoredDocumentPullState({\n currentRecord,\n patch,\n securityContextChanged,\n }),\n text: patch.text ?? getTextValue(currentDoc),\n title: patch.title ?? documentState.title,\n };\n return { documentState, record };\n}\n\nasync function saveDocumentClientProjection(input: {\n currentRecord: StoredDocumentRecord | null;\n documentProjectors: DocumentProjectorRegistry;\n documentState: ReturnType<typeof readStoredDocumentState>;\n execSql: ExecSql;\n localId: string;\n record: StoredDocumentRecord;\n updatedAt: string;\n}): Promise<void> {\n const previousKind =\n input.currentRecord?.documentKind ?? DEFAULT_DOCUMENT_KIND;\n const nextKind = input.record.documentKind ?? DEFAULT_DOCUMENT_KIND;\n if (previousKind !== nextKind) {\n await input.documentProjectors.deleteStoredDocumentClientProjection({\n documentKind: previousKind,\n execSql: input.execSql,\n localId: input.localId,\n });\n }\n await input.documentProjectors.saveStoredDocumentClientProjection({\n containerId: input.record.containerId,\n documentId: input.record.documentId,\n documentKind: nextKind,\n execSql: input.execSql,\n localId: input.record.id,\n structuredFields: input.documentState.structuredFields,\n text: input.record.text,\n title: input.record.title ?? input.documentState.title,\n updatedAt: input.updatedAt,\n });\n}\n\nasync function settleSupersededDocumentMutation(input: {\n acceptedPendingUpdateIds: readonly string[];\n lockedExecSql: ExecSql;\n mutation: Awaited<ReturnType<typeof prepareDocumentMutation>>;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null> {\n const { mutation, persistInput } = input;\n if (!mutation.mutationCurrentRecord) return null;\n const authoritativeRecord = persistInput.expectedSyncState\n ? await persistInput.persistence.settleAcceptedPendingUpdates(\n input.lockedExecSql,\n {\n expectedRecord: persistInput.expectedSyncState.record,\n pendingUpdateIds: input.acceptedPendingUpdateIds,\n },\n )\n : mutation.mutationCurrentRecord;\n if (!authoritativeRecord) return null;\n return loadSupersededPersistedDocumentState({\n creationSuperseded: mutation.creationSuperseded,\n execSql: input.lockedExecSql,\n localId: persistInput.localId,\n persistence: persistInput.persistence,\n record: authoritativeRecord,\n syncIdentitySuperseded: !mutation.securityContextMatches,\n });\n}\n\nasync function loadConcurrentCreationWinner(input: {\n execSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState> {\n const winningRecord = await input.persistInput.persistence.loadDocument(\n input.execSql,\n input.persistInput.localId,\n );\n if (!winningRecord) {\n throw new Error(\"Concurrent document creation lost without a winner\");\n }\n const winner = await loadSupersededPersistedDocumentState({\n creationSuperseded: true,\n execSql: input.execSql,\n localId: input.persistInput.localId,\n persistence: input.persistInput.persistence,\n record: winningRecord,\n syncIdentitySuperseded: true,\n });\n if (!winner) {\n throw new Error(\"Concurrent document creation winner disappeared\");\n }\n return winner;\n}\n\nasync function resolveInitialDocumentCreation(input: {\n execSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n record: StoredDocumentRecord;\n savedAt: Awaited<\n ReturnType<DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]>\n >;\n}): Promise<PersistedDocumentState | null> {\n if (typeof input.savedAt === \"string\") {\n return { record: input.record, updatedAt: input.savedAt };\n }\n // A discovered alias is not a concurrent local winner. Leave its backing\n // store untouched and refuse until a caller can establish verified identity.\n if (input.savedAt?.status === \"remote-alias\") return null;\n if (\n input.persistInput.canStartDurableMutation &&\n !input.persistInput.canStartDurableMutation()\n ) {\n return null;\n }\n return loadConcurrentCreationWinner({\n execSql: input.execSql,\n persistInput: input.persistInput,\n });\n}\n\nasync function resolveDocumentMutationCommit(input: {\n committed: Awaited<\n ReturnType<DocumentsPersistence[\"commitDocumentMutation\"]>\n >;\n lockedExecSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n record: StoredDocumentRecord;\n}): Promise<PersistedDocumentState | null | \"retry\"> {\n const { committed, persistInput, record } = input;\n if (\n persistInput.canStartDurableMutation &&\n !persistInput.canStartDurableMutation()\n ) {\n return null;\n }\n if (committed.committed) return { record, updatedAt: committed.updatedAt };\n if (!committed.currentRecord) return null;\n if (persistInput.expectedSyncState === undefined) return \"retry\";\n return loadSupersededPersistedDocumentState({\n creationSuperseded: false,\n execSql: input.lockedExecSql,\n localId: persistInput.localId,\n persistence: persistInput.persistence,\n record: committed.currentRecord,\n syncIdentitySuperseded: !documentSyncSecurityContextMatches(\n committed.currentRecord,\n persistInput.expectedSyncState.record,\n ),\n });\n}\n\nasync function commitOnePreparedDocumentMutation(input: {\n acceptedPendingUpdateIds: readonly string[];\n documentProjectors: DocumentProjectorRegistry;\n lockedExecSql: ExecSql;\n mutation: Exclude<\n Awaited<ReturnType<typeof prepareDocumentMutation>>,\n { pullContinuationSuperseded: true }\n >;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null | \"retry\"> {\n const { mutation, persistInput } = input;\n const { documentState, record } = buildStoredDocumentRecord({\n containerId: persistInput.containerId,\n currentDoc: persistInput.currentDoc,\n currentRecord: mutation.mutationCurrentRecord,\n documentProjectors: input.documentProjectors,\n localId: persistInput.localId,\n patch: mutation.resolvedPatch,\n });\n if (!mutation.mutationCurrentRecord) {\n const savedAt = await createInitialDocumentRows({\n currentDoc: persistInput.currentDoc,\n execSql: input.lockedExecSql,\n pendingUpdate: persistInput.pendingUpdate,\n persistence: persistInput.persistence,\n record,\n stillCurrent: persistInput.canStartDurableMutation,\n saveClientProjection: (transactionExecSql, updatedAt) =>\n saveDocumentClientProjection({\n currentRecord: null,\n documentProjectors: input.documentProjectors,\n documentState,\n execSql: transactionExecSql,\n localId: persistInput.localId,\n record,\n updatedAt,\n }),\n });\n return resolveInitialDocumentCreation({\n execSql: input.lockedExecSql,\n persistInput,\n record,\n savedAt,\n });\n }\n\n const committed = await persistInput.persistence.commitDocumentMutation(\n input.lockedExecSql,\n {\n acceptedPendingUpdateIds: input.acceptedPendingUpdateIds,\n clearSyncFailure: persistInput.clearSyncFailure,\n ...(persistInput.attachmentRemoval\n ? { attachmentRemoval: persistInput.attachmentRemoval }\n : {}),\n ...(persistInput.attachmentStaging\n ? { attachmentStaging: persistInput.attachmentStaging }\n : {}),\n document: record,\n expectedRecord: mutation.mutationCurrentRecord,\n ...(persistInput.historyCheckpoint\n ? { historyCheckpoint: persistInput.historyCheckpoint }\n : {}),\n ...(persistInput.historyUpdateOrigin\n ? { historyUpdateOrigin: persistInput.historyUpdateOrigin }\n : {}),\n ...(persistInput.historyUpdates\n ? { historyUpdates: persistInput.historyUpdates }\n : {}),\n ...(persistInput.pendingUpdate\n ? { pendingUpdate: persistInput.pendingUpdate }\n : {}),\n settleAcceptedPendingOnConflict:\n persistInput.expectedSyncState !== undefined,\n ...(persistInput.canStartDurableMutation\n ? { stillCurrent: persistInput.canStartDurableMutation }\n : {}),\n },\n async (transactionExecSql, updatedAt) => {\n await saveDocumentClientProjection({\n currentRecord: mutation.mutationCurrentRecord,\n documentProjectors: input.documentProjectors,\n documentState,\n execSql: transactionExecSql,\n localId: persistInput.localId,\n record,\n updatedAt,\n });\n await persistInput.commitSideEffect?.(transactionExecSql);\n },\n );\n return resolveDocumentMutationCommit({\n committed,\n lockedExecSql: input.lockedExecSql,\n persistInput,\n record,\n });\n}\n\nexport async function commitPreparedDocumentState(input: {\n documentProjectors: DocumentProjectorRegistry;\n lockedExecSql: ExecSql;\n patch: Partial<StoredDocumentRecord>;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null> {\n const { lockedExecSql, persistInput } = input;\n const acceptedPendingUpdateIds = persistInput.acceptedPendingUpdateIds ?? [];\n for (\n let attempt = 0;\n attempt < MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS;\n attempt += 1\n ) {\n const mutation = await prepareDocumentMutationUnlessDeleted({\n documentProjectors: input.documentProjectors,\n guard: attempt === 0,\n lockedExecSql,\n patch: input.patch,\n persistInput,\n });\n if (!mutation) return null;\n if (mutation.pullContinuationSuperseded) {\n return settleSupersededDocumentMutation({\n acceptedPendingUpdateIds,\n lockedExecSql,\n mutation,\n persistInput,\n });\n }\n const result = await commitOnePreparedDocumentMutation({\n acceptedPendingUpdateIds,\n documentProjectors: input.documentProjectors,\n lockedExecSql,\n mutation,\n persistInput,\n });\n if (result !== \"retry\") return result;\n }\n throw new Error(\n `Document mutation commit gave up after ${MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS} concurrent conflicts`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentMutationCommit.js","sourceRoot":"","sources":["documentMutationCommit.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAGL,uBAAuB,GACxB,MAAM,oCAAoC,CAAC;AAQ5C,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EACL,kCAAkC,GAGnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,oCAAoC,EAAE,MAAM,yBAAyB,CAAC;AAU/E,MAAM,qCAAqC,GAAG,CAAC,CAAC;AAqChD,KAAK,UAAU,oCAAoC,CAAC,KAOn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ACD,MAAM,MAAM,GAAG,MAAM,iCAAiC,CAAC;YACrD,wBAAwB;YACxB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,aAAa;YACb,QAAQ;YACR,YAAY;SACb,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,OAAO;YAAE,OAAO,MAAM,CAAC;IACxC,CAAC;IACD,MAAM,IAAI,KAAK,CACb,0CAA0C,qCAAqC,uBAAuB,CACvG,CAAC;AACJ,CAAC","sourcesContent":["import { type encodeVersionVector, getTextValue } from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../data/documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n readStoredDocumentState,\n} from \"../../data/documents/documentKinds\";\nimport type {\n DocumentPlacementCleanup,\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PendingUpdateFields } from \"../../data/persistence/documents/records\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { createInitialDocumentRows } from \"./create/documentCreationPersistence\";\nimport {\n documentSyncSecurityContextMatches,\n type PrepareDocumentMutationInput,\n type prepareDocumentMutation,\n} from \"./documentMutationPreparation\";\nimport { prepareDocumentMutationUnlessDeleted } from \"./documentPersistGuards\";\n\ntype DocumentContentState = Parameters<typeof encodeVersionVector>[0];\ntype NullableDocumentRuntimeField =\n | \"accessStateHash\"\n | \"lastCommitLsn\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\";\n\nconst MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS = 8;\n\nexport interface PersistedDocumentState {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: StoredDocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\n\nexport interface PersistDocumentStateInput\n extends PrepareDocumentMutationInput {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?:\n | Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"attachmentRemoval\"]\n | undefined;\n attachmentStaging?:\n | Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"attachmentStaging\"]\n | undefined;\n canStartDurableMutation?: (() => boolean) | undefined;\n clearSyncFailure?: boolean | undefined;\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>;\n containerId?: string | null | undefined;\n deleteDocumentPlacements: DocumentPlacementCleanup;\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n patch?: Partial<StoredDocumentRecord> | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n}\n\nasync function loadSupersededPersistedDocumentState(input: {\n creationSuperseded: boolean;\n execSql: ExecSql;\n localId: string;\n persistence: DocumentsPersistence;\n record: StoredDocumentRecord;\n syncIdentitySuperseded: boolean;\n}): Promise<PersistedDocumentState | null> {\n const { document, historyRestoreState } =\n await input.persistence.loadDocumentWithHistoryRestoreState(\n input.execSql,\n input.localId,\n );\n if (!document) return null;\n const syncIdentitySuperseded =\n input.syncIdentitySuperseded ||\n !documentSyncSecurityContextMatches(document, input.record);\n return {\n ...(input.creationSuperseded ? { creationSuperseded: true as const } : {}),\n historyRestoreState,\n pullContinuationSuperseded: true,\n record: document,\n ...(syncIdentitySuperseded\n ? { syncIdentitySuperseded: true as const }\n : {}),\n };\n}\n\nfunction resolveNullableDocumentRuntimeField(\n patch: Partial<StoredDocumentRecord>,\n key: NullableDocumentRuntimeField,\n currentValue: string | null | undefined,\n resetWhenUnpatched = false,\n): string | null {\n if (Object.hasOwn(patch, key)) return patch[key] ?? null;\n return resetWhenUnpatched ? null : (currentValue ?? null);\n}\n\nfunction resolveStoredDocumentContainerId(input: {\n containerId?: string | null | undefined;\n currentRecord: StoredDocumentRecord | null;\n patch: Partial<StoredDocumentRecord>;\n}): string | null {\n if (Object.hasOwn(input.patch, \"containerId\")) {\n return input.patch.containerId ?? null;\n }\n return input.currentRecord?.containerId ?? input.containerId ?? null;\n}\n\nfunction resolveStoredDocumentPullState(input: {\n currentRecord: StoredDocumentRecord | null;\n patch: Partial<StoredDocumentRecord>;\n securityContextChanged: boolean;\n}): Pick<\n StoredDocumentRecord,\n \"pullContinuation\" | \"pullContinuationRecoveryRequired\"\n> {\n if (Object.hasOwn(input.patch, \"pullContinuation\")) {\n return { pullContinuation: input.patch.pullContinuation ?? null };\n }\n if (input.securityContextChanged) return { pullContinuation: null };\n if (input.currentRecord?.pullContinuationRecoveryRequired) {\n return { pullContinuationRecoveryRequired: true };\n }\n return { pullContinuation: input.currentRecord?.pullContinuation ?? null };\n}\n\nfunction buildStoredDocumentRecord(input: {\n containerId?: string | null | undefined;\n currentDoc: DocumentContentState;\n currentRecord: StoredDocumentRecord | null;\n documentProjectors: DocumentProjectorRegistry;\n localId: string;\n patch: Partial<StoredDocumentRecord>;\n}) {\n const { currentDoc, currentRecord, documentProjectors, localId, patch } =\n input;\n const currentDocumentId = currentRecord?.documentId ?? null;\n const nextDocumentId = patch.documentId ?? currentDocumentId;\n const documentIdChanged = nextDocumentId !== currentDocumentId;\n const currentAccessEpoch =\n currentRecord?.accessEpoch ?? DEFAULT_DOCUMENT_ACCESS_EPOCH;\n const nextAccessEpoch = patch.accessEpoch ?? currentAccessEpoch;\n const securityContextChanged =\n documentIdChanged || nextAccessEpoch !== currentAccessEpoch;\n const documentState = readStoredDocumentState(currentDoc, documentProjectors);\n const record: StoredDocumentRecord = {\n id: currentRecord?.id ?? localId,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolveNullableDocumentRuntimeField(\n patch,\n \"accessStateHash\",\n currentRecord?.accessStateHash,\n securityContextChanged,\n ),\n containerId: resolveStoredDocumentContainerId({\n containerId: input.containerId,\n currentRecord,\n patch,\n }),\n contentKeyBundle: resolveNullableDocumentRuntimeField(\n patch,\n \"contentKeyBundle\",\n currentRecord?.contentKeyBundle,\n securityContextChanged,\n ),\n documentId: nextDocumentId,\n effectiveAccessLevel:\n patch.effectiveAccessLevel ?? currentRecord?.effectiveAccessLevel ?? null,\n documentKekTargets: resolveNullableDocumentRuntimeField(\n patch,\n \"documentKekTargets\",\n currentRecord?.documentKekTargets,\n securityContextChanged,\n ),\n documentKind: patch.documentKind ?? documentState.documentKind,\n documentManifestBundle: resolveNullableDocumentRuntimeField(\n patch,\n \"documentManifestBundle\",\n currentRecord?.documentManifestBundle,\n securityContextChanged,\n ),\n lastCommitLsn: resolveNullableDocumentRuntimeField(\n patch,\n \"lastCommitLsn\",\n currentRecord?.lastCommitLsn,\n documentIdChanged,\n ),\n snapshotEndVersion:\n patch.snapshotEndVersion ?? currentRecord?.snapshotEndVersion ?? \"\",\n pendingBaseVersion:\n patch.pendingBaseVersion !== undefined\n ? patch.pendingBaseVersion\n : (currentRecord?.pendingBaseVersion ?? null),\n recoveryGeneration:\n patch.recoveryGeneration ?? currentRecord?.recoveryGeneration ?? 0,\n ...resolveStoredDocumentPullState({\n currentRecord,\n patch,\n securityContextChanged,\n }),\n text: patch.text ?? getTextValue(currentDoc),\n title: patch.title ?? documentState.title,\n };\n return { documentState, record };\n}\n\nasync function saveDocumentClientProjection(input: {\n currentRecord: StoredDocumentRecord | null;\n documentProjectors: DocumentProjectorRegistry;\n documentState: ReturnType<typeof readStoredDocumentState>;\n execSql: ExecSql;\n localId: string;\n record: StoredDocumentRecord;\n updatedAt: string;\n}): Promise<void> {\n const previousKind =\n input.currentRecord?.documentKind ?? DEFAULT_DOCUMENT_KIND;\n const nextKind = input.record.documentKind ?? DEFAULT_DOCUMENT_KIND;\n if (previousKind !== nextKind) {\n await input.documentProjectors.deleteStoredDocumentClientProjection({\n documentKind: previousKind,\n execSql: input.execSql,\n localId: input.localId,\n });\n }\n await input.documentProjectors.saveStoredDocumentClientProjection({\n containerId: input.record.containerId,\n documentId: input.record.documentId,\n documentKind: nextKind,\n execSql: input.execSql,\n localId: input.record.id,\n structuredFields: input.documentState.structuredFields,\n text: input.record.text,\n title: input.record.title ?? input.documentState.title,\n updatedAt: input.updatedAt,\n });\n}\n\nasync function settleSupersededDocumentMutation(input: {\n acceptedPendingUpdateIds: readonly string[];\n lockedExecSql: ExecSql;\n mutation: Awaited<ReturnType<typeof prepareDocumentMutation>>;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null> {\n const { mutation, persistInput } = input;\n if (!mutation.mutationCurrentRecord) return null;\n const authoritativeRecord = persistInput.expectedSyncState\n ? await persistInput.persistence.settleAcceptedPendingUpdates(\n input.lockedExecSql,\n {\n expectedRecord: persistInput.expectedSyncState.record,\n pendingUpdateIds: input.acceptedPendingUpdateIds,\n },\n )\n : mutation.mutationCurrentRecord;\n if (!authoritativeRecord) return null;\n return loadSupersededPersistedDocumentState({\n creationSuperseded: mutation.creationSuperseded,\n execSql: input.lockedExecSql,\n localId: persistInput.localId,\n persistence: persistInput.persistence,\n record: authoritativeRecord,\n syncIdentitySuperseded: !mutation.securityContextMatches,\n });\n}\n\nasync function loadConcurrentCreationWinner(input: {\n execSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState> {\n const winningRecord = await input.persistInput.persistence.loadDocument(\n input.execSql,\n input.persistInput.localId,\n );\n if (!winningRecord) {\n throw new Error(\"Concurrent document creation lost without a winner\");\n }\n const winner = await loadSupersededPersistedDocumentState({\n creationSuperseded: true,\n execSql: input.execSql,\n localId: input.persistInput.localId,\n persistence: input.persistInput.persistence,\n record: winningRecord,\n syncIdentitySuperseded: true,\n });\n if (!winner) {\n throw new Error(\"Concurrent document creation winner disappeared\");\n }\n return winner;\n}\n\nasync function resolveInitialDocumentCreation(input: {\n execSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n record: StoredDocumentRecord;\n savedAt: Awaited<\n ReturnType<DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]>\n >;\n}): Promise<PersistedDocumentState | null> {\n if (typeof input.savedAt === \"string\") {\n return { record: input.record, updatedAt: input.savedAt };\n }\n // A discovered alias is not a concurrent local winner. Leave its backing\n // store untouched and refuse until a caller can establish verified identity.\n if (input.savedAt?.status === \"remote-alias\") return null;\n if (\n input.persistInput.canStartDurableMutation &&\n !input.persistInput.canStartDurableMutation()\n ) {\n return null;\n }\n return loadConcurrentCreationWinner({\n execSql: input.execSql,\n persistInput: input.persistInput,\n });\n}\n\nasync function resolveDocumentMutationCommit(input: {\n committed: Awaited<\n ReturnType<DocumentsPersistence[\"commitDocumentMutation\"]>\n >;\n lockedExecSql: ExecSql;\n persistInput: PersistDocumentStateInput;\n record: StoredDocumentRecord;\n}): Promise<PersistedDocumentState | null | \"retry\"> {\n const { committed, persistInput, record } = input;\n if (\n persistInput.canStartDurableMutation &&\n !persistInput.canStartDurableMutation()\n ) {\n return null;\n }\n if (committed.committed) return { record, updatedAt: committed.updatedAt };\n if (!committed.currentRecord) return null;\n if (persistInput.expectedSyncState === undefined) return \"retry\";\n return loadSupersededPersistedDocumentState({\n creationSuperseded: false,\n execSql: input.lockedExecSql,\n localId: persistInput.localId,\n persistence: persistInput.persistence,\n record: committed.currentRecord,\n syncIdentitySuperseded: !documentSyncSecurityContextMatches(\n committed.currentRecord,\n persistInput.expectedSyncState.record,\n ),\n });\n}\n\nasync function commitOnePreparedDocumentMutation(input: {\n acceptedPendingUpdateIds: readonly string[];\n documentProjectors: DocumentProjectorRegistry;\n lockedExecSql: ExecSql;\n mutation: Exclude<\n Awaited<ReturnType<typeof prepareDocumentMutation>>,\n { pullContinuationSuperseded: true }\n >;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null | \"retry\"> {\n const { mutation, persistInput } = input;\n const { documentState, record } = buildStoredDocumentRecord({\n containerId: persistInput.containerId,\n currentDoc: persistInput.currentDoc,\n currentRecord: mutation.mutationCurrentRecord,\n documentProjectors: input.documentProjectors,\n localId: persistInput.localId,\n patch: mutation.resolvedPatch,\n });\n if (!mutation.mutationCurrentRecord) {\n const savedAt = await createInitialDocumentRows({\n currentDoc: persistInput.currentDoc,\n execSql: input.lockedExecSql,\n pendingUpdate: persistInput.pendingUpdate,\n persistence: persistInput.persistence,\n record,\n stillCurrent: persistInput.canStartDurableMutation,\n saveClientProjection: (transactionExecSql, updatedAt) =>\n saveDocumentClientProjection({\n currentRecord: null,\n documentProjectors: input.documentProjectors,\n documentState,\n execSql: transactionExecSql,\n localId: persistInput.localId,\n record,\n updatedAt,\n }),\n });\n return resolveInitialDocumentCreation({\n execSql: input.lockedExecSql,\n persistInput,\n record,\n savedAt,\n });\n }\n\n const committed = await persistInput.persistence.commitDocumentMutation(\n input.lockedExecSql,\n {\n acceptedPendingUpdateIds: input.acceptedPendingUpdateIds,\n clearSyncFailure: persistInput.clearSyncFailure,\n ...(persistInput.attachmentRemoval\n ? { attachmentRemoval: persistInput.attachmentRemoval }\n : {}),\n ...(persistInput.attachmentStaging\n ? { attachmentStaging: persistInput.attachmentStaging }\n : {}),\n document: record,\n expectedRecord: mutation.mutationCurrentRecord,\n ...(persistInput.historyCheckpoint\n ? { historyCheckpoint: persistInput.historyCheckpoint }\n : {}),\n ...(persistInput.historyUpdateOrigin\n ? { historyUpdateOrigin: persistInput.historyUpdateOrigin }\n : {}),\n ...(persistInput.historyUpdates\n ? { historyUpdates: persistInput.historyUpdates }\n : {}),\n ...(persistInput.pendingUpdate\n ? { pendingUpdate: persistInput.pendingUpdate }\n : {}),\n settleAcceptedPendingOnConflict:\n persistInput.expectedSyncState !== undefined,\n ...(persistInput.canStartDurableMutation\n ? { stillCurrent: persistInput.canStartDurableMutation }\n : {}),\n },\n async (transactionExecSql, updatedAt) => {\n await saveDocumentClientProjection({\n currentRecord: mutation.mutationCurrentRecord,\n documentProjectors: input.documentProjectors,\n documentState,\n execSql: transactionExecSql,\n localId: persistInput.localId,\n record,\n updatedAt,\n });\n await persistInput.commitSideEffect?.(transactionExecSql);\n },\n );\n return resolveDocumentMutationCommit({\n committed,\n lockedExecSql: input.lockedExecSql,\n persistInput,\n record,\n });\n}\n\nexport async function commitPreparedDocumentState(input: {\n documentProjectors: DocumentProjectorRegistry;\n lockedExecSql: ExecSql;\n patch: Partial<StoredDocumentRecord>;\n persistInput: PersistDocumentStateInput;\n}): Promise<PersistedDocumentState | null> {\n const { lockedExecSql, persistInput } = input;\n const acceptedPendingUpdateIds = persistInput.acceptedPendingUpdateIds ?? [];\n for (\n let attempt = 0;\n attempt < MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS;\n attempt += 1\n ) {\n const mutation = await prepareDocumentMutationUnlessDeleted({\n deleteDocumentPlacements: persistInput.deleteDocumentPlacements,\n documentProjectors: input.documentProjectors,\n guard: attempt === 0,\n lockedExecSql,\n patch: input.patch,\n persistInput,\n });\n if (!mutation) return null;\n if (mutation.pullContinuationSuperseded) {\n return settleSupersededDocumentMutation({\n acceptedPendingUpdateIds,\n lockedExecSql,\n mutation,\n persistInput,\n });\n }\n const result = await commitOnePreparedDocumentMutation({\n acceptedPendingUpdateIds,\n documentProjectors: input.documentProjectors,\n lockedExecSql,\n mutation,\n persistInput,\n });\n if (result !== \"retry\") return result;\n }\n throw new Error(\n `Document mutation commit gave up after ${MAX_DOCUMENT_MUTATION_COMMIT_ATTEMPTS} concurrent conflicts`,\n );\n}\n"]}
|
|
@@ -11,7 +11,7 @@ export async function refuseDeletedDocumentPersist(input) {
|
|
|
11
11
|
execSql: transactionExecSql,
|
|
12
12
|
localId: input.localId,
|
|
13
13
|
});
|
|
14
|
-
});
|
|
14
|
+
}, input.deleteDocumentPlacements);
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
17
|
* The preparation read doubles as the first look for a deleted row: only when
|
|
@@ -29,6 +29,7 @@ export async function prepareDocumentMutationUnlessDeleted(input) {
|
|
|
29
29
|
return mutation;
|
|
30
30
|
const refused = await refuseDeletedDocumentPersist({
|
|
31
31
|
currentRecord: persistInput.currentRecord,
|
|
32
|
+
deleteDocumentPlacements: input.deleteDocumentPlacements,
|
|
32
33
|
documentProjectors: input.documentProjectors,
|
|
33
34
|
execSql: lockedExecSql,
|
|
34
35
|
localId: persistInput.localId,
|