@tearleads/client-sdk 0.1.225 → 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/principalContainerMutations.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 +2 -2
- package/client/organizations/recipientAdmission.js.map +1 -1
- package/client/organizations/rosterAdmissionEvidence.js +1 -1
- package/client/organizations/rosterAdmissionEvidence.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/containers/shared/authorAccess.d.ts +1 -1
- package/data/containers/shared/authorAccess.js.map +1 -1
- package/data/containers/shared/principalPolicies.js.map +1 -1
- package/data/containers/shared/types.d.ts +1 -1
- package/data/containers/shared/types.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/accessManifestCheckpointEnforcement.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +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/container/containerProjectionVerification.d.ts +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js +1 -1
- package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/error.js +1 -57
- package/data/keyingProjectionVerification/error.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +1 -1
- package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js +2 -2
- package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.d.ts +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/types.d.ts +1 -1
- package/data/keyingProjectionVerification/types.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/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +1 -1
- package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +1 -1
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
- package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js +1 -1
- package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -1
- package/data/persistence/organizationFounderPersistence.js +1 -1
- package/data/persistence/organizationFounderPersistence.js.map +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/heldPrincipalState.js +1 -1
- package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
- package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +1 -1
- package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
- package/data/principals/organizationGroupRoles.js +1 -1
- package/data/principals/organizationGroupRoles.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/create/index.js.map +1 -1
- package/workflows/containers/child/move/moveRequest.js.map +1 -1
- package/workflows/containers/child/move/moveWraps.js.map +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/mutationSubmit.d.ts +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/child/rekey/carriedDescendantRekeys.d.ts +1 -1
- package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
- package/workflows/containers/child/rekey/index.d.ts +1 -1
- package/workflows/containers/child/rekey/index.js.map +1 -1
- package/workflows/containers/child/revoke.d.ts +1 -1
- package/workflows/containers/child/revoke.js.map +1 -1
- package/workflows/containers/child/rotation/replacementPrincipalPolicyReferences.js.map +1 -1
- package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
- package/workflows/containers/child/rotation/rotationWraps.js.map +1 -1
- package/workflows/containers/child/share/sharePlanCore.d.ts +1 -1
- package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
- package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js +1 -1
- package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js.map +1 -1
- package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js +1 -1
- package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js.map +1 -1
- package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
- package/workflows/containers/rematerialization/principalContainerRematerializationTargets.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/linkSet/linkSetAuthority.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/currentOrganizationAuthority.d.ts +1 -1
- package/workflows/organizations/currentOrganizationAuthority.js +1 -1
- package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js +1 -1
- package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataBinding.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js +2 -2
- package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js.map +1 -1
- package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
- package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
- package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
- package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
- package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +1 -1
- package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js +1 -1
- package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -1
- package/workflows/organizations/policyHistory/organizationPolicyHistoryDetails.js.map +1 -1
- package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js +1 -1
- package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -1
- package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js +1 -1
- package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js.map +1 -1
- package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js +1 -1
- package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js.map +1 -1
- package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js +1 -1
- package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
- package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +1 -1
- package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyRecipients.js +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyRecipients.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyRequest.js +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +2 -2
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
- package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +1 -1
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
- package/workflows/principals/externalAdminPolicy.d.ts +1 -1
- package/workflows/principals/externalAdminPolicy.js +2 -2
- package/workflows/principals/externalAdminPolicy.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +1 -1
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js +1 -1
- package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/policyCache/index.d.ts +1 -1
- package/workflows/principals/policyCache/index.js +3 -2
- package/workflows/principals/policyCache/index.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
- package/workflows/principals/policyVerification.js +1 -1
- package/workflows/principals/policyVerification.js.map +1 -1
- package/workflows/principals/principalPolicyService.js +1 -1
- package/workflows/principals/principalPolicyService.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
- package/workflows/principals/publicHistory/publicProjectionDirectory.js +1 -1
- package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -1
- package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
- package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
- package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js +1 -1
- package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js.map +1 -1
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -2
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.d.ts +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryMemo.js +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryMemo.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/organizationProvisioning.js +2 -2
- package/workflows/registration/organizationProvisioning.js.map +1 -1
- package/workflows/registration/persistRegistrationBootstrap.js +2 -0
- package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
- package/workflows/registration/provisionedPrincipalHistory.js +1 -1
- package/workflows/registration/provisionedPrincipalHistory.js.map +1 -1
- package/workflows/registration/registrationAccessHeadPersistence.js +1 -1
- package/workflows/registration/registrationAccessHeadPersistence.js.map +1 -1
- package/data/containers/shared/heldContainerHeads.js.map +0 -1
- /package/data/{containers/shared → keyingProjectionVerification/checkpoints}/heldContainerHeads.js +0 -0
- /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js +0 -0
- /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js.map +0 -0
- /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.d.ts +0 -0
- /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js +0 -0
- /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js.map +0 -0
- /package/data/{principals → principalContracts}/principalIdentityCommitments.js +0 -0
- /package/data/{principals → principalContracts}/principalIdentityCommitments.js.map +0 -0
- /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js +0 -0
- /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js.map +0 -0
- /package/data/{principals → principalContracts}/principalPolicyEvidence.d.ts +0 -0
- /package/data/{principals → principalContracts}/principalPolicyEvidence.js +0 -0
- /package/data/{principals → principalContracts}/principalPolicyEvidence.js.map +0 -0
- /package/data/{principals → principalContracts}/principalPolicyStates.js +0 -0
- /package/data/{principals → principalContracts}/principalPolicyStates.js.map +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":"index.js","sourceRoot":"","sources":["index.ts"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AC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC5D,CAAC;QACD,GAAG,EAAE,CAAC,eAAe,EAAE,EAAE;YACvB,MAAM,kBAAkB,GAAG,qBAAqB,EAAE,CAAC;YACnD,IAAI,CAAC,kBAAkB;gBAAE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,UAAU,GAAG,2BAA2B,CAAC,KAAK,CAAC,CAAC;YACtD,IAAI,UAAU,EAAE,CAAC;gBACf,qEAAqE;gBACrE,uEAAuE;gBACvE,KAAK,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE;oBACxB,IACE,wCAAwC,CAAC,KAAK,EAAE,kBAAkB,CAAC,EACnE,CAAC;wBACD,wBAAwB,CAAC,KAAK,CAAC,CAAC;oBAClC,CAAC;gBACH,CAAC,CAAC,CAAC;gBACH,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;YAC3B,CAAC;YACD,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,CACvC,wCAAwC,CAAC,KAAK,EAAE,kBAAkB,CAAC;gBACjE,CAAC,CAAC,oBAAoB,CAAC,KAAK,EAAE,kBAAkB,EAAE,eAAe,CAAC;gBAClE,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,CACtB,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { reportAndRethrowKeyingVerificationError } from \"../../../../data/keyingProjectionVerification/error\";\nimport {\n type DocumentRecord,\n type DocumentSyncLane,\n isDatabaseUnavailableError,\n type PendingUpdateRecord,\n registerDocumentSyncLane,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport {\n onDocumentStoreRetired,\n requestDocumentStoreSync,\n} from \"../../registry\";\nimport { awaitInitializationForSync } from \"../initialization\";\nimport { listPendingUpdates } from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type DocumentSyncAttempt,\n type EncapsulationKeyPair,\n setDocumentSyncing,\n} from \"../state\";\nimport { logRevalidationUnavailable as logUnavailable } from \"./remoteRevalidationTelemetry\";\nimport {\n getActiveDocumentRemoteWork,\n runDocumentRemoteWork,\n} from \"./remoteWork\";\nimport {\n cleanupPreRegisteredUpdateIdsOnFailure,\n discardPreRegisteredUpdateIds,\n preRegisterMaterializedDocumentSyncUpdateIds,\n} from \"./syncAcceptedUpdateIds\";\nimport { syncPendingAttachments } from \"./syncAttachments\";\nimport { syncDetachedAttachmentBindings } from \"./syncDetachedAttachments\";\nimport { finalizeDocumentSync } from \"./syncFinalize\";\nimport {\n captureDocumentStoreAttachmentSyncGeneration,\n captureDocumentStoreRemoteSyncGeneration,\n captureDocumentStoreSyncGeneration,\n type DocumentStoreSyncGeneration,\n type DocumentStoreSyncLaneGeneration,\n invalidateDocumentStoreSyncLane,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreSyncGenerationCurrent,\n isDocumentStoreSyncLaneGenerationCurrent,\n} from \"./syncGeneration\";\nimport { prepareDocumentOutgoingCoverage } from \"./syncOutgoingCoverage\";\nimport { mergeQueuedDocumentUpdates } from \"./syncQueueMerge\";\nimport { requestRemoteDocumentSync } from \"./syncRequest\";\nimport { revalidateRemoteDocumentBeforeAttachments } from \"./syncRevalidation\";\nimport {\n ensureSeededRemoteDocument,\n remoteCreateGate,\n} from \"./syncSeededCreate\";\nimport { shouldSkipCleanScheduledDocumentSync } from \"./syncShared\";\n\nfunction canRunScheduledSync(state: DocumentStoreState): boolean {\n return (\n // A deferred birth waits for its attach to carry it (see\n // deferredInitialUpdate.ts); a pass now would ship it on its own.\n state.deferInitialUpdate !== true &&\n state.doc !== null &&\n state.snapshot.ready &&\n state.runtime.state.online &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.crypto.encapsulationKeyPair !== null &&\n resolveDocumentCreateAuthor(state.runtime) !== null\n );\n}\n\nasync function requestOutgoingDocumentBatch(input: {\n readonly currentDoc: DocumentState;\n readonly encapsulationKeyPair: EncapsulationKeyPair;\n readonly generation: DocumentStoreSyncGeneration;\n readonly pendingUpdates: PendingUpdateRecord[];\n readonly policyOperation: PrincipalPolicyOperation;\n readonly record: DocumentRecord;\n readonly state: DocumentStoreState;\n}): Promise<{\n sentUpdateIds: string[];\n syncAttempt: DocumentSyncAttempt | null;\n}> {\n const { planningUpdates, queuedUpdateCount } = prepareDocumentStoreSyncQueue(\n input.pendingUpdates,\n );\n const sentUpdateIds: string[] = [];\n const syncAttempt = await cleanupPreRegisteredUpdateIdsOnFailure(\n input.state,\n sentUpdateIds,\n () =>\n requestRemoteDocumentSync({\n currentDoc: input.currentDoc,\n currentRecord: input.record,\n encapsulationKeyPair: input.encapsulationKeyPair,\n generation: input.generation,\n onOutgoingUpdatesMaterialized: (updateIds) =>\n preRegisterMaterializedDocumentSyncUpdateIds(\n input.state,\n sentUpdateIds,\n updateIds,\n ),\n pendingUpdates: planningUpdates,\n policyOperation: input.policyOperation,\n queuedUpdateCount,\n state: input.state,\n unavailableWriterLogMessage:\n \"Documents: skipped sync because the writer context is unavailable.\",\n }),\n );\n return { sentUpdateIds, syncAttempt };\n}\n\n/**\n * Keep the full durable queue visible to stale-heal/checkpoint classification.\n * The workflow planner owns the final count and byte bounds, and the exact\n * materialized batch is pre-registered immediately before each submit.\n */\nexport function prepareDocumentStoreSyncQueue(\n pendingUpdates: PendingUpdateRecord[],\n): {\n planningUpdates: PendingUpdateRecord[];\n queuedUpdateCount: number;\n} {\n return {\n planningUpdates: pendingUpdates,\n queuedUpdateCount: pendingUpdates.length,\n };\n}\n\nexport function canSyncDetachedAttachmentBindings(\n record: DocumentRecord,\n pendingUpdateCount: number,\n): boolean {\n return (\n pendingUpdateCount === 0 &&\n (record.pullContinuation ?? null) === null &&\n !record.pullContinuationRecoveryRequired\n );\n}\n\n/** Another pass picks up whatever this stale one could not finish. */\nfunction requestSyncAgain(\n state: DocumentStoreState,\n fallback: DocumentRecord,\n): DocumentRecord {\n requestDocumentStoreSync(state);\n return state.record ?? fallback;\n}\n\nasync function syncDocumentState(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<DocumentRecord> {\n // Snapshot the remote-update signal sequence before any await. The GET below\n // fetches server state as of its own snapshot; any remote event delivered\n // after this point describes an update that may not be in that response, so\n // finalizeDocumentSync must not clear the signal if this sequence has moved.\n const consumedRemoteUpdateSignalSeq = state.remoteUpdateSignalSeq;\n const wasRemoteProbe = state.remoteUpdatePending;\n let pendingUpdates: PendingUpdateRecord[] = await listPendingUpdates(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation))\n return requestSyncAgain(state, nextRecord);\n if (pendingUpdates.length === 0 && isDocumentStoreRemoteSyncBlocked(state)) {\n return nextRecord;\n }\n // Create the remote document even when nothing is queued to send: a note\n // created and never edited enqueues no updates, but its local row is still a\n // pending create the write queue reports — it must flush, not sit. Defer\n // while the container itself still awaits its remote create — with OR\n // without queued edits, since the create cannot succeed before its parent\n // exists and attempting it just records a spurious failure. The structural\n // lane primes this store again as soon as the container create lands.\n const createGate = await remoteCreateGate(state, nextRecord, generation);\n if (createGate === \"stale\") return requestSyncAgain(state, nextRecord);\n if (createGate === \"defer\") return nextRecord;\n const created = await ensureSeededRemoteDocument({\n consumedRemoteUpdateSignalSeq,\n currentDoc,\n encapsulationKeyPair,\n generation,\n nextRecord,\n pendingUpdates,\n policyOperation,\n state,\n });\n let nextRemoteRecord = created.record;\n pendingUpdates = created.pendingUpdates;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation))\n return requestSyncAgain(state, nextRecord);\n if (!nextRemoteRecord?.documentId) return nextRecord;\n\n const preparedCoverage = await prepareDocumentOutgoingCoverage({\n currentDoc,\n generation,\n pendingUpdates,\n state,\n });\n if (!preparedCoverage) return requestSyncAgain(state, nextRemoteRecord);\n nextRemoteRecord = preparedCoverage.record;\n pendingUpdates = await mergeQueuedDocumentUpdates({\n currentDoc,\n generation,\n pendingUpdates: preparedCoverage.pendingUpdates,\n state,\n });\n\n if (\n shouldSkipCleanScheduledDocumentSync({\n currentRecord: nextRemoteRecord,\n pendingUpdates,\n state,\n })\n ) {\n return nextRemoteRecord;\n }\n\n // Pre-register the IDs we are about to send so the author's OWN\n // `document_update_created` echo (fanned back over realtime) is classified as\n // self-authored and never re-arms a redundant sync. Registering BEFORE the\n // network await closes the race where the echo lands before\n // finalizeDocumentSync records the accepted IDs — the gap that turned every\n // fast keystroke into an extra self-triggered sync.\n const { sentUpdateIds, syncAttempt } = await requestOutgoingDocumentBatch({\n currentDoc,\n encapsulationKeyPair,\n generation,\n pendingUpdates,\n policyOperation,\n record: nextRemoteRecord,\n state,\n });\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return state.record ?? nextRemoteRecord;\n }\n if (!syncAttempt) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n logUnavailable(state, wasRemoteProbe);\n return nextRemoteRecord;\n }\n\n return cleanupPreRegisteredUpdateIdsOnFailure(state, sentUpdateIds, () =>\n finalizeDocumentSync(\n state,\n currentDoc,\n nextRemoteRecord,\n syncAttempt,\n consumedRemoteUpdateSignalSeq,\n generation,\n sentUpdateIds,\n wasRemoteProbe,\n ),\n );\n}\n\nasync function runDocumentSyncPass(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n policyOperation: PrincipalPolicyOperation,\n) {\n const currentDoc = state.doc;\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n let nextRecord = state.record;\n\n if (!currentDoc || !nextRecord || !encapsulationKeyPair) {\n return;\n }\n\n const generation = captureDocumentStoreRemoteSyncGeneration(\n state,\n currentDoc,\n syncLaneGeneration,\n );\n const attachmentGeneration = captureDocumentStoreAttachmentSyncGeneration(\n state,\n currentDoc,\n syncLaneGeneration,\n );\n if (!generation || !attachmentGeneration) {\n requestDocumentStoreSync(state);\n return;\n }\n\n const revalidation = await revalidateRemoteDocumentBeforeAttachments(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n policyOperation,\n );\n nextRecord = revalidation.nextRecord;\n if (!revalidation.canSyncAttachments) {\n return;\n }\n\n const attachmentResult = await syncPendingAttachments(\n state,\n nextRecord,\n encapsulationKeyPair,\n attachmentGeneration,\n policyOperation,\n );\n nextRecord = attachmentResult.nextRecord;\n if (state.pendingAttachments.length > 0) {\n return;\n }\n // A settled bind and the content update carrying its digest are two server\n // writes. Push the content in this same pass rather than re-arming a later\n // one, so a device lost between them is the only remaining window: peers\n // otherwise see the old digest against the new binding.\n\n nextRecord = await syncDocumentState(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n policyOperation,\n );\n\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return;\n }\n\n if (!state.doc || !state.record) return;\n\n const pendingUpdates = await listPendingUpdates(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return;\n }\n if (!canSyncDetachedAttachmentBindings(nextRecord, pendingUpdates.length)) {\n return;\n }\n\n await syncDetachedAttachmentBindings(\n state,\n nextRecord,\n generation,\n policyOperation,\n );\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nasync function runScheduledSyncIteration(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n policyOperation: PrincipalPolicyOperation,\n) {\n if (!(await awaitInitializationForSync(state))) {\n return false;\n }\n if (!isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)) {\n return true;\n }\n\n if (!canRunScheduledSync(state)) {\n return true;\n }\n\n try {\n await runDocumentSyncPass(state, syncLaneGeneration, policyOperation);\n return true;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: state.record?.documentId ?? state.localId,\n objectKind: \"document\",\n operation: \"document.sync\",\n },\n );\n\n throw error;\n }\n}\n\nasync function runScheduledSyncLoop(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n policyOperation: PrincipalPolicyOperation,\n) {\n const syncingGeneration = captureDocumentStoreSyncGeneration(\n state,\n state.doc,\n );\n setDocumentSyncing(state, true);\n\n try {\n await runScheduledSyncIteration(state, syncLaneGeneration, policyOperation);\n } finally {\n if (\n syncingGeneration &&\n isDocumentStoreSyncGenerationCurrent(state, syncingGeneration) &&\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ) {\n setDocumentSyncing(state, false);\n }\n }\n}\n\nexport function registerDocumentStoreSyncLane(\n state: DocumentStoreState,\n getSyncLaneGeneration: () => DocumentStoreSyncLaneGeneration | null,\n): DocumentSyncLane {\n // Retiring the store (its document removed under it) ends this lane's\n // current and in-flight work; a replacement store registers its own.\n onDocumentStoreRetired(state.runtime.state.domainScope, state.localId, () =>\n invalidateDocumentStoreSyncLane(state),\n );\n return registerDocumentSyncLane({\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n priority: () =>\n state.remoteUpdatePending || state.record?.snapshotEndVersion === \"\"\n ? -1\n : 0,\n logError: (message, error) => {\n // Read the runtime lazily: a store's runtime is replaced in place, and a\n // reference captured here would report into a torn-down host.\n const { log, logError } = state.runtime.util;\n // Return the host's result: both callbacks are declared `=> void` but may\n // be async, and the lane reporter only catches a rejection it is handed.\n return logError ? logError(message, error) : log(message);\n },\n run: (policyOperation) => {\n const syncLaneGeneration = getSyncLaneGeneration();\n if (!syncLaneGeneration) return Promise.resolve();\n const activeWork = getActiveDocumentRemoteWork(state);\n if (activeWork) {\n // Re-arm on settlement, not immediately: immediate re-requests would\n // spin this lane and starve other work while the HTTP request is held.\n void activeWork.then(() => {\n if (\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ) {\n requestDocumentStoreSync(state);\n }\n });\n return Promise.resolve();\n }\n return runDocumentRemoteWork(state, () =>\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ? runScheduledSyncLoop(state, syncLaneGeneration, policyOperation)\n : Promise.resolve(),\n );\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uCAAuC,EAAE,MAAM,2CAA2C,CAAC;AACpG,OAAO,EAGL,0BAA0B,EAE1B,wBAAwB,EACxB,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EACL,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAKL,kBAAkB,GACnB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,0BAA0B,IAAI,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,sCAAsC,EACtC,6BAA6B,EAC7B,4CAA4C,GAC7C,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,8BAA8B,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EACL,4CAA4C,EAC5C,wCAAwC,EACxC,kCAAkC,EAGlC,+BAA+B,EAC/B,gCAAgC,EAChC,oCAAoC,EACpC,wCAAwC,GACzC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,+BAA+B,EAAE,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CAAC,CAAC,CAAC;QACP,QAAQ,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE;YAC3B,yEAAyE;YACzE,8DAA8D;YAC9D,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;YAC7C,0EAA0E;YAC1E,yEAAyE;YACzE,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC5D,CAAC;QACD,GAAG,EAAE,CAAC,eAAe,EAAE,EAAE;YACvB,MAAM,kBAAkB,GAAG,qBAAqB,EAAE,CAAC;YACnD,IAAI,CAAC,kBAAkB;gBAAE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,UAAU,GAAG,2BAA2B,CAAC,KAAK,CAAC,CAAC;YACtD,IAAI,UAAU,EAAE,CAAC;gBACf,qEAAqE;gBACrE,uEAAuE;gBACvE,KAAK,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE;oBACxB,IACE,wCAAwC,CAAC,KAAK,EAAE,kBAAkB,CAAC,EACnE,CAAC;wBACD,wBAAwB,CAAC,KAAK,CAAC,CAAC;oBAClC,CAAC;gBACH,CAAC,CAAC,CAAC;gBACH,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;YAC3B,CAAC;YACD,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,CACvC,wCAAwC,CAAC,KAAK,EAAE,kBAAkB,CAAC;gBACjE,CAAC,CAAC,oBAAoB,CAAC,KAAK,EAAE,kBAAkB,EAAE,eAAe,CAAC;gBAClE,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,CACtB,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { reportAndRethrowKeyingVerificationError } from \"../../../../data/shared/securityIncidents\";\nimport {\n type DocumentRecord,\n type DocumentSyncLane,\n isDatabaseUnavailableError,\n type PendingUpdateRecord,\n registerDocumentSyncLane,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport {\n onDocumentStoreRetired,\n requestDocumentStoreSync,\n} from \"../../registry\";\nimport { awaitInitializationForSync } from \"../initialization\";\nimport { listPendingUpdates } from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type DocumentSyncAttempt,\n type EncapsulationKeyPair,\n setDocumentSyncing,\n} from \"../state\";\nimport { logRevalidationUnavailable as logUnavailable } from \"./remoteRevalidationTelemetry\";\nimport {\n getActiveDocumentRemoteWork,\n runDocumentRemoteWork,\n} from \"./remoteWork\";\nimport {\n cleanupPreRegisteredUpdateIdsOnFailure,\n discardPreRegisteredUpdateIds,\n preRegisterMaterializedDocumentSyncUpdateIds,\n} from \"./syncAcceptedUpdateIds\";\nimport { syncPendingAttachments } from \"./syncAttachments\";\nimport { syncDetachedAttachmentBindings } from \"./syncDetachedAttachments\";\nimport { finalizeDocumentSync } from \"./syncFinalize\";\nimport {\n captureDocumentStoreAttachmentSyncGeneration,\n captureDocumentStoreRemoteSyncGeneration,\n captureDocumentStoreSyncGeneration,\n type DocumentStoreSyncGeneration,\n type DocumentStoreSyncLaneGeneration,\n invalidateDocumentStoreSyncLane,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreSyncGenerationCurrent,\n isDocumentStoreSyncLaneGenerationCurrent,\n} from \"./syncGeneration\";\nimport { prepareDocumentOutgoingCoverage } from \"./syncOutgoingCoverage\";\nimport { mergeQueuedDocumentUpdates } from \"./syncQueueMerge\";\nimport { requestRemoteDocumentSync } from \"./syncRequest\";\nimport { revalidateRemoteDocumentBeforeAttachments } from \"./syncRevalidation\";\nimport {\n ensureSeededRemoteDocument,\n remoteCreateGate,\n} from \"./syncSeededCreate\";\nimport { shouldSkipCleanScheduledDocumentSync } from \"./syncShared\";\n\nfunction canRunScheduledSync(state: DocumentStoreState): boolean {\n return (\n // A deferred birth waits for its attach to carry it (see\n // deferredInitialUpdate.ts); a pass now would ship it on its own.\n state.deferInitialUpdate !== true &&\n state.doc !== null &&\n state.snapshot.ready &&\n state.runtime.state.online &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.crypto.encapsulationKeyPair !== null &&\n resolveDocumentCreateAuthor(state.runtime) !== null\n );\n}\n\nasync function requestOutgoingDocumentBatch(input: {\n readonly currentDoc: DocumentState;\n readonly encapsulationKeyPair: EncapsulationKeyPair;\n readonly generation: DocumentStoreSyncGeneration;\n readonly pendingUpdates: PendingUpdateRecord[];\n readonly policyOperation: PrincipalPolicyOperation;\n readonly record: DocumentRecord;\n readonly state: DocumentStoreState;\n}): Promise<{\n sentUpdateIds: string[];\n syncAttempt: DocumentSyncAttempt | null;\n}> {\n const { planningUpdates, queuedUpdateCount } = prepareDocumentStoreSyncQueue(\n input.pendingUpdates,\n );\n const sentUpdateIds: string[] = [];\n const syncAttempt = await cleanupPreRegisteredUpdateIdsOnFailure(\n input.state,\n sentUpdateIds,\n () =>\n requestRemoteDocumentSync({\n currentDoc: input.currentDoc,\n currentRecord: input.record,\n encapsulationKeyPair: input.encapsulationKeyPair,\n generation: input.generation,\n onOutgoingUpdatesMaterialized: (updateIds) =>\n preRegisterMaterializedDocumentSyncUpdateIds(\n input.state,\n sentUpdateIds,\n updateIds,\n ),\n pendingUpdates: planningUpdates,\n policyOperation: input.policyOperation,\n queuedUpdateCount,\n state: input.state,\n unavailableWriterLogMessage:\n \"Documents: skipped sync because the writer context is unavailable.\",\n }),\n );\n return { sentUpdateIds, syncAttempt };\n}\n\n/**\n * Keep the full durable queue visible to stale-heal/checkpoint classification.\n * The workflow planner owns the final count and byte bounds, and the exact\n * materialized batch is pre-registered immediately before each submit.\n */\nexport function prepareDocumentStoreSyncQueue(\n pendingUpdates: PendingUpdateRecord[],\n): {\n planningUpdates: PendingUpdateRecord[];\n queuedUpdateCount: number;\n} {\n return {\n planningUpdates: pendingUpdates,\n queuedUpdateCount: pendingUpdates.length,\n };\n}\n\nexport function canSyncDetachedAttachmentBindings(\n record: DocumentRecord,\n pendingUpdateCount: number,\n): boolean {\n return (\n pendingUpdateCount === 0 &&\n (record.pullContinuation ?? null) === null &&\n !record.pullContinuationRecoveryRequired\n );\n}\n\n/** Another pass picks up whatever this stale one could not finish. */\nfunction requestSyncAgain(\n state: DocumentStoreState,\n fallback: DocumentRecord,\n): DocumentRecord {\n requestDocumentStoreSync(state);\n return state.record ?? fallback;\n}\n\nasync function syncDocumentState(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<DocumentRecord> {\n // Snapshot the remote-update signal sequence before any await. The GET below\n // fetches server state as of its own snapshot; any remote event delivered\n // after this point describes an update that may not be in that response, so\n // finalizeDocumentSync must not clear the signal if this sequence has moved.\n const consumedRemoteUpdateSignalSeq = state.remoteUpdateSignalSeq;\n const wasRemoteProbe = state.remoteUpdatePending;\n let pendingUpdates: PendingUpdateRecord[] = await listPendingUpdates(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation))\n return requestSyncAgain(state, nextRecord);\n if (pendingUpdates.length === 0 && isDocumentStoreRemoteSyncBlocked(state)) {\n return nextRecord;\n }\n // Create the remote document even when nothing is queued to send: a note\n // created and never edited enqueues no updates, but its local row is still a\n // pending create the write queue reports — it must flush, not sit. Defer\n // while the container itself still awaits its remote create — with OR\n // without queued edits, since the create cannot succeed before its parent\n // exists and attempting it just records a spurious failure. The structural\n // lane primes this store again as soon as the container create lands.\n const createGate = await remoteCreateGate(state, nextRecord, generation);\n if (createGate === \"stale\") return requestSyncAgain(state, nextRecord);\n if (createGate === \"defer\") return nextRecord;\n const created = await ensureSeededRemoteDocument({\n consumedRemoteUpdateSignalSeq,\n currentDoc,\n encapsulationKeyPair,\n generation,\n nextRecord,\n pendingUpdates,\n policyOperation,\n state,\n });\n let nextRemoteRecord = created.record;\n pendingUpdates = created.pendingUpdates;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation))\n return requestSyncAgain(state, nextRecord);\n if (!nextRemoteRecord?.documentId) return nextRecord;\n\n const preparedCoverage = await prepareDocumentOutgoingCoverage({\n currentDoc,\n generation,\n pendingUpdates,\n state,\n });\n if (!preparedCoverage) return requestSyncAgain(state, nextRemoteRecord);\n nextRemoteRecord = preparedCoverage.record;\n pendingUpdates = await mergeQueuedDocumentUpdates({\n currentDoc,\n generation,\n pendingUpdates: preparedCoverage.pendingUpdates,\n state,\n });\n\n if (\n shouldSkipCleanScheduledDocumentSync({\n currentRecord: nextRemoteRecord,\n pendingUpdates,\n state,\n })\n ) {\n return nextRemoteRecord;\n }\n\n // Pre-register the IDs we are about to send so the author's OWN\n // `document_update_created` echo (fanned back over realtime) is classified as\n // self-authored and never re-arms a redundant sync. Registering BEFORE the\n // network await closes the race where the echo lands before\n // finalizeDocumentSync records the accepted IDs — the gap that turned every\n // fast keystroke into an extra self-triggered sync.\n const { sentUpdateIds, syncAttempt } = await requestOutgoingDocumentBatch({\n currentDoc,\n encapsulationKeyPair,\n generation,\n pendingUpdates,\n policyOperation,\n record: nextRemoteRecord,\n state,\n });\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return state.record ?? nextRemoteRecord;\n }\n if (!syncAttempt) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n logUnavailable(state, wasRemoteProbe);\n return nextRemoteRecord;\n }\n\n return cleanupPreRegisteredUpdateIdsOnFailure(state, sentUpdateIds, () =>\n finalizeDocumentSync(\n state,\n currentDoc,\n nextRemoteRecord,\n syncAttempt,\n consumedRemoteUpdateSignalSeq,\n generation,\n sentUpdateIds,\n wasRemoteProbe,\n ),\n );\n}\n\nasync function runDocumentSyncPass(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n policyOperation: PrincipalPolicyOperation,\n) {\n const currentDoc = state.doc;\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n let nextRecord = state.record;\n\n if (!currentDoc || !nextRecord || !encapsulationKeyPair) {\n return;\n }\n\n const generation = captureDocumentStoreRemoteSyncGeneration(\n state,\n currentDoc,\n syncLaneGeneration,\n );\n const attachmentGeneration = captureDocumentStoreAttachmentSyncGeneration(\n state,\n currentDoc,\n syncLaneGeneration,\n );\n if (!generation || !attachmentGeneration) {\n requestDocumentStoreSync(state);\n return;\n }\n\n const revalidation = await revalidateRemoteDocumentBeforeAttachments(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n policyOperation,\n );\n nextRecord = revalidation.nextRecord;\n if (!revalidation.canSyncAttachments) {\n return;\n }\n\n const attachmentResult = await syncPendingAttachments(\n state,\n nextRecord,\n encapsulationKeyPair,\n attachmentGeneration,\n policyOperation,\n );\n nextRecord = attachmentResult.nextRecord;\n if (state.pendingAttachments.length > 0) {\n return;\n }\n // A settled bind and the content update carrying its digest are two server\n // writes. Push the content in this same pass rather than re-arming a later\n // one, so a device lost between them is the only remaining window: peers\n // otherwise see the old digest against the new binding.\n\n nextRecord = await syncDocumentState(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n policyOperation,\n );\n\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return;\n }\n\n if (!state.doc || !state.record) return;\n\n const pendingUpdates = await listPendingUpdates(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return;\n }\n if (!canSyncDetachedAttachmentBindings(nextRecord, pendingUpdates.length)) {\n return;\n }\n\n await syncDetachedAttachmentBindings(\n state,\n nextRecord,\n generation,\n policyOperation,\n );\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nasync function runScheduledSyncIteration(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n policyOperation: PrincipalPolicyOperation,\n) {\n if (!(await awaitInitializationForSync(state))) {\n return false;\n }\n if (!isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)) {\n return true;\n }\n\n if (!canRunScheduledSync(state)) {\n return true;\n }\n\n try {\n await runDocumentSyncPass(state, syncLaneGeneration, policyOperation);\n return true;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: state.record?.documentId ?? state.localId,\n objectKind: \"document\",\n operation: \"document.sync\",\n },\n );\n\n throw error;\n }\n}\n\nasync function runScheduledSyncLoop(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n policyOperation: PrincipalPolicyOperation,\n) {\n const syncingGeneration = captureDocumentStoreSyncGeneration(\n state,\n state.doc,\n );\n setDocumentSyncing(state, true);\n\n try {\n await runScheduledSyncIteration(state, syncLaneGeneration, policyOperation);\n } finally {\n if (\n syncingGeneration &&\n isDocumentStoreSyncGenerationCurrent(state, syncingGeneration) &&\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ) {\n setDocumentSyncing(state, false);\n }\n }\n}\n\nexport function registerDocumentStoreSyncLane(\n state: DocumentStoreState,\n getSyncLaneGeneration: () => DocumentStoreSyncLaneGeneration | null,\n): DocumentSyncLane {\n // Retiring the store (its document removed under it) ends this lane's\n // current and in-flight work; a replacement store registers its own.\n onDocumentStoreRetired(state.runtime.state.domainScope, state.localId, () =>\n invalidateDocumentStoreSyncLane(state),\n );\n return registerDocumentSyncLane({\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n priority: () =>\n state.remoteUpdatePending || state.record?.snapshotEndVersion === \"\"\n ? -1\n : 0,\n logError: (message, error) => {\n // Read the runtime lazily: a store's runtime is replaced in place, and a\n // reference captured here would report into a torn-down host.\n const { log, logError } = state.runtime.util;\n // Return the host's result: both callbacks are declared `=> void` but may\n // be async, and the lane reporter only catches a rejection it is handed.\n return logError ? logError(message, error) : log(message);\n },\n run: (policyOperation) => {\n const syncLaneGeneration = getSyncLaneGeneration();\n if (!syncLaneGeneration) return Promise.resolve();\n const activeWork = getActiveDocumentRemoteWork(state);\n if (activeWork) {\n // Re-arm on settlement, not immediately: immediate re-requests would\n // spin this lane and starve other work while the HTTP request is held.\n void activeWork.then(() => {\n if (\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ) {\n requestDocumentStoreSync(state);\n }\n });\n return Promise.resolve();\n }\n return runDocumentRemoteWork(state, () =>\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ? runScheduledSyncLoop(state, syncLaneGeneration, policyOperation)\n : Promise.resolve(),\n );\n },\n });\n}\n"]}
|
|
@@ -28,6 +28,7 @@ export async function deleteUpstreamDeletedDocument(state, generation, requestRe
|
|
|
28
28
|
const deletionStarted = await deletePersistedDocument({
|
|
29
29
|
beforeDeleteInTransaction: commitPurgeProof,
|
|
30
30
|
canStartDurableMutation: canDeleteCapturedDocument,
|
|
31
|
+
deleteDocumentPlacements: state.runtime.deleteDocumentPlacements,
|
|
31
32
|
documentProjectors: state.runtime.infra.documentProjectors,
|
|
32
33
|
execSql: generation.execSql,
|
|
33
34
|
expectedRecord: requestRecord,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncRequest.js","sourceRoot":"","sources":["syncRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,qCAAqC,EAErC,uBAAuB,EAGvB,qBAAqB,EACrB,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,qBAAq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,2BAA2B,GAC5B,GAAG,KAAK,CAAC;IACV,IAAI,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1E,sEAAsE;IACtE,wDAAwD;IACxD,MAAM,0BAA0B,GAAG,KAAK,CAAC,0BAA0B,CAAC;IAEpE,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC9B,IAAI,CAAC,aAAa,CAAC,UAAU;QAAE,OAAO,IAAI,CAAC;IAE3C,MAAM,yBAAyB,GAAG,KAAK,CAAC,gBAAgB,CAAC;IAEzD,MAAM,MAAM,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;IACpD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,qBAAqB,CACxC,KAAK,EACL,MAAM,EACN,aAAa,CAAC,UAAU,EACxB,yBAAyB,CAC1B,CAAC;IACF,IAAI,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1E,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAEzB,MAAM,mBAAmB,GAAG,KAAK,CAAC,iBAAiB,IAAI,cAAc,CAAC,MAAM,CAAC;IAC7E,OAAO,yBAAyB,CAAC;QAC/B,aAAa;QACb,mBAAmB;QACnB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,yBAAyB;QACzB,MAAM;QACN,0BAA0B;KAC3B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport {\n createDocumentWriterPublicKeyResolver,\n type DocumentRecord,\n deletePersistedDocument,\n type ExecSql,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n validateDocumentSyncUpdateImports,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { parkForAncestorRepair } from \"../ancestorRepairPark\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type DocumentSyncAttempt,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { invalidateDocumentStorePullContinuation } from \"./pullContinuationInvalidation\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport {\n documentIncomingUpdateIsolationFailureHandler,\n documentRevalidationFailureHandler,\n documentTerminalSubmitFailureHandler,\n} from \"./syncShared\";\nimport { documentSyncContextMatches } from \"./syncUpdateImport\";\n\n/**\n * Destroying queued local edits here is settled policy, not an oversight\n * (docs/sync-edge-cases.md row 1): deletion is a privacy operation, so an\n * authoritative remote delete removes the document and its unsynced edits\n * everywhere with no preservation copy. Quarantine/export were rejected —\n * they retain or re-upload content the user deliberately destroyed.\n */\nexport async function deleteUpstreamDeletedDocument(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n requestRecord: DocumentRecord,\n remoteDocumentId: string,\n commitPurgeProof?: (transactionExecSql: ExecSql) => Promise<void>,\n) {\n await chainIdentityWrite(state, async () => {\n if (\n !isDocumentStoreSyncGenerationCurrent(state, generation) ||\n !documentSyncContextMatches(state.record, requestRecord, remoteDocumentId)\n ) {\n return;\n }\n\n const canDeleteCapturedDocument = () =>\n isDocumentStoreSyncGenerationCurrent(state, generation) &&\n documentSyncContextMatches(state.record, requestRecord, remoteDocumentId);\n let removedInMutation = false;\n const deletionStarted = await deletePersistedDocument({\n beforeDeleteInTransaction: commitPurgeProof,\n canStartDurableMutation: canDeleteCapturedDocument,\n documentProjectors: state.runtime.infra.documentProjectors,\n execSql: generation.execSql,\n expectedRecord: requestRecord,\n localId: requestRecord.id,\n // Invalidate the store generation INSIDE the deletion mutation: a\n // terminal failure handler queued behind it then observes the stale\n // generation and cannot resurrect a failure row the deletes removed.\n onDeletedInMutation: () => {\n if (canDeleteCapturedDocument()) {\n markDocumentStoreRemoved(state);\n removedInMutation = true;\n }\n },\n persistence: state.persistence,\n });\n if (!deletionStarted || !removedInMutation) {\n return;\n }\n void runDocumentOrphanMaintenance(state);\n state.runtime.util.log(\n `Documents: removed local document ${state.localId} after remote deletion.`,\n );\n });\n}\n\nfunction createDocumentSyncAttempt(input: {\n currentRecord: DocumentRecord;\n outgoingUpdateCount: number;\n policyOperation: PrincipalPolicyOperation;\n requestedPullContinuation: DocumentStoreState[\"pullContinuation\"];\n synced: DocumentSyncAttempt[\"synced\"];\n writerProjectionGeneration: number;\n}): DocumentSyncAttempt {\n return {\n consumedPullContinuation:\n input.synced.plan.request.pullCursor === undefined\n ? null\n : input.requestedPullContinuation,\n outgoingUpdateCount: input.outgoingUpdateCount,\n policyOperation: input.policyOperation,\n requestRecord: input.currentRecord,\n synced: input.synced,\n writerProjectionGeneration: input.writerProjectionGeneration,\n };\n}\n\ninterface RequestRemoteDocumentSyncInput {\n allowRecoveryBaseline?: boolean | undefined;\n currentDoc: DocumentState;\n currentRecord: DocumentRecord;\n encapsulationKeyPair: EncapsulationKeyPair;\n generation: DocumentStoreSyncGeneration;\n onOutgoingUpdatesMaterialized?:\n | ((updateIds: readonly string[]) => void)\n | undefined;\n pendingUpdates: PendingUpdateRecord[];\n /** The pass or workflow operation the sync's policy reads belong to. */\n policyOperation: PrincipalPolicyOperation;\n queuedUpdateCount?: number | undefined;\n state: DocumentStoreState;\n unavailableWriterLogMessage: string;\n}\n\nfunction runRemoteDocumentSync(\n input: RequestRemoteDocumentSyncInput,\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>,\n documentId: string,\n requestedPullContinuation: DocumentStoreState[\"pullContinuation\"],\n) {\n const { currentDoc, currentRecord, generation, pendingUpdates, state } =\n input;\n const runtime = state.runtime;\n const writerProjectionGenerationAtStart = state.writerProjectionGeneration;\n state.awaitingAncestorRepair = false;\n // The generation's API client and executor with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: input.encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n return remoteDocuments.syncRemoteDocument({\n author,\n // Heal a stale content-key bundle from this full-history snapshot. Rotation\n // settlement disables this: it may submit only the ordinary local stream.\n ...(input.allowRecoveryBaseline === false\n ? {}\n : {\n buildRotationSnapshot: async () =>\n exportFullHistorySnapshot(currentDoc),\n }),\n documentId,\n localVersionVector: encodeVersionVector(currentDoc),\n minLsn: currentRecord.lastCommitLsn ?? undefined,\n onRemoteDocumentDeleted: ({ commitPurgeProof, documentId }) =>\n deleteUpstreamDeletedDocument(\n state,\n generation,\n currentRecord,\n documentId,\n commitPurgeProof,\n ),\n onSyncAbandoned: (reason) => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return;\n const hintLandedMidPass = parkForAncestorRepair(\n state,\n reason,\n writerProjectionGenerationAtStart,\n );\n if (hintLandedMidPass) requestDocumentStoreSync(state);\n },\n onSyncTrace: (line) => runtime.util.log(`Documents: ${line}`),\n onReadOnlyProjectionFailure: documentRevalidationFailureHandler(\n state,\n generation,\n ),\n onIncomingUpdateIsolationFailure:\n documentIncomingUpdateIsolationFailureHandler(state, generation),\n onOutgoingUpdatesMaterialized: input.onOutgoingUpdatesMaterialized,\n onPullContinuationInvalidated: (continuation) =>\n invalidateDocumentStorePullContinuation({\n continuation,\n currentRecord,\n generation,\n state,\n }),\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n pendingUpdates,\n persistedState: currentRecord,\n pullContinuation: requestedPullContinuation ?? undefined,\n rekeyPendingUpdate: state.persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Documents\",\n runtime,\n writerKeyLabel: \"writer key\",\n }),\n stillCurrent: () => isDocumentStoreSyncGenerationCurrent(state, generation),\n validateIncomingUpdates: (result) =>\n validateDocumentSyncUpdateImports({\n currentDocument: currentDoc,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n }),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n }),\n writerProjection:\n state.writerProjection?.documentId === currentRecord.documentId\n ? state.writerProjection\n : undefined,\n });\n}\n\nexport async function requestRemoteDocumentSync(\n input: RequestRemoteDocumentSyncInput,\n): Promise<DocumentSyncAttempt | null> {\n const {\n currentRecord,\n generation,\n pendingUpdates,\n state,\n unavailableWriterLogMessage,\n } = input;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n // Captured before the network round trip: a hint that lands meanwhile\n // must keep the response's projection out of the cache.\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n const runtime = state.runtime;\n if (!currentRecord.documentId) return null;\n\n const requestedPullContinuation = state.pullContinuation;\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(unavailableWriterLogMessage);\n return null;\n }\n\n const synced = await runRemoteDocumentSync(\n input,\n author,\n currentRecord.documentId,\n requestedPullContinuation,\n );\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n if (!synced) return null;\n\n const outgoingUpdateCount = input.queuedUpdateCount ?? pendingUpdates.length;\n return createDocumentSyncAttempt({\n currentRecord,\n outgoingUpdateCount,\n policyOperation: input.policyOperation,\n requestedPullContinuation,\n synced,\n writerProjectionGeneration,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncRequest.js","sourceRoot":"","sources":["syncRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;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;QACN,0BAA0B;KAC3B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport {\n createDocumentWriterPublicKeyResolver,\n type DocumentRecord,\n deletePersistedDocument,\n type ExecSql,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n validateDocumentSyncUpdateImports,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { parkForAncestorRepair } from \"../ancestorRepairPark\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type DocumentSyncAttempt,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { invalidateDocumentStorePullContinuation } from \"./pullContinuationInvalidation\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport {\n documentIncomingUpdateIsolationFailureHandler,\n documentRevalidationFailureHandler,\n documentTerminalSubmitFailureHandler,\n} from \"./syncShared\";\nimport { documentSyncContextMatches } from \"./syncUpdateImport\";\n\n/**\n * Destroying queued local edits here is settled policy, not an oversight\n * (docs/sync-edge-cases.md row 1): deletion is a privacy operation, so an\n * authoritative remote delete removes the document and its unsynced edits\n * everywhere with no preservation copy. Quarantine/export were rejected —\n * they retain or re-upload content the user deliberately destroyed.\n */\nexport async function deleteUpstreamDeletedDocument(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n requestRecord: DocumentRecord,\n remoteDocumentId: string,\n commitPurgeProof?: (transactionExecSql: ExecSql) => Promise<void>,\n) {\n await chainIdentityWrite(state, async () => {\n if (\n !isDocumentStoreSyncGenerationCurrent(state, generation) ||\n !documentSyncContextMatches(state.record, requestRecord, remoteDocumentId)\n ) {\n return;\n }\n\n const canDeleteCapturedDocument = () =>\n isDocumentStoreSyncGenerationCurrent(state, generation) &&\n documentSyncContextMatches(state.record, requestRecord, remoteDocumentId);\n let removedInMutation = false;\n const deletionStarted = await deletePersistedDocument({\n beforeDeleteInTransaction: commitPurgeProof,\n canStartDurableMutation: canDeleteCapturedDocument,\n deleteDocumentPlacements: state.runtime.deleteDocumentPlacements,\n documentProjectors: state.runtime.infra.documentProjectors,\n execSql: generation.execSql,\n expectedRecord: requestRecord,\n localId: requestRecord.id,\n // Invalidate the store generation INSIDE the deletion mutation: a\n // terminal failure handler queued behind it then observes the stale\n // generation and cannot resurrect a failure row the deletes removed.\n onDeletedInMutation: () => {\n if (canDeleteCapturedDocument()) {\n markDocumentStoreRemoved(state);\n removedInMutation = true;\n }\n },\n persistence: state.persistence,\n });\n if (!deletionStarted || !removedInMutation) {\n return;\n }\n void runDocumentOrphanMaintenance(state);\n state.runtime.util.log(\n `Documents: removed local document ${state.localId} after remote deletion.`,\n );\n });\n}\n\nfunction createDocumentSyncAttempt(input: {\n currentRecord: DocumentRecord;\n outgoingUpdateCount: number;\n policyOperation: PrincipalPolicyOperation;\n requestedPullContinuation: DocumentStoreState[\"pullContinuation\"];\n synced: DocumentSyncAttempt[\"synced\"];\n writerProjectionGeneration: number;\n}): DocumentSyncAttempt {\n return {\n consumedPullContinuation:\n input.synced.plan.request.pullCursor === undefined\n ? null\n : input.requestedPullContinuation,\n outgoingUpdateCount: input.outgoingUpdateCount,\n policyOperation: input.policyOperation,\n requestRecord: input.currentRecord,\n synced: input.synced,\n writerProjectionGeneration: input.writerProjectionGeneration,\n };\n}\n\ninterface RequestRemoteDocumentSyncInput {\n allowRecoveryBaseline?: boolean | undefined;\n currentDoc: DocumentState;\n currentRecord: DocumentRecord;\n encapsulationKeyPair: EncapsulationKeyPair;\n generation: DocumentStoreSyncGeneration;\n onOutgoingUpdatesMaterialized?:\n | ((updateIds: readonly string[]) => void)\n | undefined;\n pendingUpdates: PendingUpdateRecord[];\n /** The pass or workflow operation the sync's policy reads belong to. */\n policyOperation: PrincipalPolicyOperation;\n queuedUpdateCount?: number | undefined;\n state: DocumentStoreState;\n unavailableWriterLogMessage: string;\n}\n\nfunction runRemoteDocumentSync(\n input: RequestRemoteDocumentSyncInput,\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>,\n documentId: string,\n requestedPullContinuation: DocumentStoreState[\"pullContinuation\"],\n) {\n const { currentDoc, currentRecord, generation, pendingUpdates, state } =\n input;\n const runtime = state.runtime;\n const writerProjectionGenerationAtStart = state.writerProjectionGeneration;\n state.awaitingAncestorRepair = false;\n // The generation's API client and executor with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: input.encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n return remoteDocuments.syncRemoteDocument({\n author,\n // Heal a stale content-key bundle from this full-history snapshot. Rotation\n // settlement disables this: it may submit only the ordinary local stream.\n ...(input.allowRecoveryBaseline === false\n ? {}\n : {\n buildRotationSnapshot: async () =>\n exportFullHistorySnapshot(currentDoc),\n }),\n documentId,\n localVersionVector: encodeVersionVector(currentDoc),\n minLsn: currentRecord.lastCommitLsn ?? undefined,\n onRemoteDocumentDeleted: ({ commitPurgeProof, documentId }) =>\n deleteUpstreamDeletedDocument(\n state,\n generation,\n currentRecord,\n documentId,\n commitPurgeProof,\n ),\n onSyncAbandoned: (reason) => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return;\n const hintLandedMidPass = parkForAncestorRepair(\n state,\n reason,\n writerProjectionGenerationAtStart,\n );\n if (hintLandedMidPass) requestDocumentStoreSync(state);\n },\n onSyncTrace: (line) => runtime.util.log(`Documents: ${line}`),\n onReadOnlyProjectionFailure: documentRevalidationFailureHandler(\n state,\n generation,\n ),\n onIncomingUpdateIsolationFailure:\n documentIncomingUpdateIsolationFailureHandler(state, generation),\n onOutgoingUpdatesMaterialized: input.onOutgoingUpdatesMaterialized,\n onPullContinuationInvalidated: (continuation) =>\n invalidateDocumentStorePullContinuation({\n continuation,\n currentRecord,\n generation,\n state,\n }),\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n pendingUpdates,\n persistedState: currentRecord,\n pullContinuation: requestedPullContinuation ?? undefined,\n rekeyPendingUpdate: state.persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Documents\",\n runtime,\n writerKeyLabel: \"writer key\",\n }),\n stillCurrent: () => isDocumentStoreSyncGenerationCurrent(state, generation),\n validateIncomingUpdates: (result) =>\n validateDocumentSyncUpdateImports({\n currentDocument: currentDoc,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n }),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n }),\n writerProjection:\n state.writerProjection?.documentId === currentRecord.documentId\n ? state.writerProjection\n : undefined,\n });\n}\n\nexport async function requestRemoteDocumentSync(\n input: RequestRemoteDocumentSyncInput,\n): Promise<DocumentSyncAttempt | null> {\n const {\n currentRecord,\n generation,\n pendingUpdates,\n state,\n unavailableWriterLogMessage,\n } = input;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n // Captured before the network round trip: a hint that lands meanwhile\n // must keep the response's projection out of the cache.\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n const runtime = state.runtime;\n if (!currentRecord.documentId) return null;\n\n const requestedPullContinuation = state.pullContinuation;\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(unavailableWriterLogMessage);\n return null;\n }\n\n const synced = await runRemoteDocumentSync(\n input,\n author,\n currentRecord.documentId,\n requestedPullContinuation,\n );\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n if (!synced) return null;\n\n const outgoingUpdateCount = input.queuedUpdateCount ?? pendingUpdates.length;\n return createDocumentSyncAttempt({\n currentRecord,\n outgoingUpdateCount,\n policyOperation: input.policyOperation,\n requestedPullContinuation,\n synced,\n writerProjectionGeneration,\n });\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { rethrowDatabaseUnavailableError } from "../../../data/keyingProjectionVerification/error.js";
|
|
2
2
|
import { rethrowProjectionVerificationCancelled } from "../../../data/keyingProjectionVerification/types.js";
|
|
3
|
+
import { reportKeyingVerificationErrorInCauseChain, } from "../../../data/shared/securityIncidents.js";
|
|
3
4
|
/** One unavailable or invalid attachment does not suppress independent successes. */
|
|
4
5
|
export async function collectHydrationResults(input) {
|
|
5
6
|
const outcomes = await Promise.allSettled(input.tasks.map((task) => task.run()));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydrationResults.js","sourceRoot":"","sources":["hydrationResults.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"hydrationResults.js","sourceRoot":"","sources":["hydrationResults.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,kDAAkD,CAAC;AACnG,OAAO,EAAE,sCAAsC,EAAE,MAAM,kDAAkD,CAAC;AAC1G,OAAO,EACL,yCAAyC,GAE1C,MAAM,wCAAwC,CAAC;AAEhD,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAI,KAIhD;IACC,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,UAAU,CACvC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CACtC,CAAC;IACF,MAAM,MAAM,GAAQ,EAAE,CAAC;IACvB,KAAK,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;QAClD,IAAI,OAAO,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;YACnC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC3B,SAAS;QACX,CAAC;QACD,+BAA+B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAChD,sCAAsC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACvD,MAAM,yCAAyC,CAC7C,OAAO,CAAC,MAAM,EACd,KAAK,CAAC,sBAAsB,EAC5B;YACE,SAAS,EAAE,oBAAoB;YAC/B,UAAU,EAAE,MAAM;YAClB,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,IAAI,IAAI;SAC7C,CACF,CAAC;QACF,KAAK,CAAC,GAAG,EAAE,CAAC,2DAA2D,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { rethrowDatabaseUnavailableError } from \"../../../data/keyingProjectionVerification/error\";\nimport { rethrowProjectionVerificationCancelled } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n reportKeyingVerificationErrorInCauseChain,\n type SecurityIncidentReporter,\n} from \"../../../data/shared/securityIncidents\";\n\n/** One unavailable or invalid attachment does not suppress independent successes. */\nexport async function collectHydrationResults<T>(input: {\n tasks: readonly { blobId: string; run: () => Promise<T> }[];\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n log?: ((message: string) => void) | undefined;\n}): Promise<T[]> {\n const outcomes = await Promise.allSettled(\n input.tasks.map((task) => task.run()),\n );\n const values: T[] = [];\n for (const [index, outcome] of outcomes.entries()) {\n if (outcome.status === \"fulfilled\") {\n values.push(outcome.value);\n continue;\n }\n rethrowDatabaseUnavailableError(outcome.reason);\n rethrowProjectionVerificationCancelled(outcome.reason);\n await reportKeyingVerificationErrorInCauseChain(\n outcome.reason,\n input.reportSecurityIncident,\n {\n operation: \"hydrate_attachment\",\n objectKind: \"blob\",\n objectId: input.tasks[index]?.blobId ?? null,\n },\n );\n input.log?.(\"Documents: an attachment is unavailable during hydration.\");\n }\n return values;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { isKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
|
|
2
1
|
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
2
|
+
import { isKeyingVerificationError } from "../../../data/shared/securityIncidents.js";
|
|
3
3
|
import { decryptDocumentAttachmentBlob } from "../hydration/decrypt.js";
|
|
4
4
|
/**
|
|
5
5
|
* Proof material the cached projection lacks, such as a wrap-cited container
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentDecryptor.js","sourceRoot":"","sources":["attachmentDecryptor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"attachmentDecryptor.js","sourceRoot":"","sources":["attachmentDecryptor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACnF,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AASrE;;;GAGG;AACH,SAAS,4BAA4B,CAAC,KAAc;IAClD,OAAO,CACL,KAAK,YAAY,oCAAoC;QACrD,CAAC,yBAAyB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC,CAC1E,CAAC;AACJ,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,2BAA2B,CAIzC,SAAkC,EAClC,UAAkB,EAClB,IAAuC;IAEvC,IAAI,SAAuE,CAAC;IAC5E,MAAM,OAAO,GAAG,GAAG,EAAE;QACnB,SAAS,KAAK,CAAC,KAAK,IAAI,EAAE;YACxB,SAAS,CAAC,6BAA6B,EAAE,CAAC,UAAU,CAAC,CAAC;YACtD,OAAO,SAAS,CAAC,2BAA2B,CAAC,UAAU,CAAC,CAAC;QAC3D,CAAC,CAAC,EAAE,CAAC;QACL,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;IACF,OAAO,KAAK,EAAE,KAAY,EAAE,EAAE;QAC5B,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC;QAC3B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,4BAA4B,CAAC,KAAK,CAAC;gBAAE,MAAM,KAAK,CAAC;YACtD,MAAM,gBAAgB,GAAG,MAAM,OAAO,EAAE,CAAC;YACzC,IAAI,CAAC,gBAAgB;gBAAE,MAAM,KAAK,CAAC;YACnC,yEAAyE;YACzE,wEAAwE;YACxE,OAAO,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,gBAAgB,EAAE,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,SAAkC,EAClC,UAAkB;IAElB,OAAO,2BAA2B,CAChC,SAAS,EACT,UAAU,EACV,6BAA6B,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { isKeyingVerificationError } from \"../../../data/shared/securityIncidents\";\nimport { decryptDocumentAttachmentBlob } from \"../hydration/decrypt\";\n\ninterface AttachmentProjectionApi {\n evictDocumentWriterProjection?(documentId: string): void;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n}\n\n/**\n * Proof material the cached projection lacks, such as a wrap-cited container\n * manifest that a fresher projection serves. Not integrity evidence.\n */\nfunction isRefreshableProofDependency(error: unknown): boolean {\n return (\n error instanceof ProjectionDependencyUnavailableError ||\n (isKeyingVerificationError(error) && error.code === \"missing_dependency\")\n );\n}\n\n/** One fresh proof fetch shared by a hydration or key-rewrap run. */\nexport function createAttachmentProofReader<\n Input extends { writerProjection: DocumentWriterProjectionResponse },\n Result,\n>(\n apiClient: AttachmentProjectionApi,\n documentId: string,\n read: (input: Input) => Promise<Result>,\n) {\n let refreshed: Promise<DocumentWriterProjectionResponse | null> | undefined;\n const refresh = () => {\n refreshed ??= (async () => {\n apiClient.evictDocumentWriterProjection?.(documentId);\n return apiClient.getDocumentWriterProjection(documentId);\n })();\n return refreshed;\n };\n return async (input: Input) => {\n try {\n return await read(input);\n } catch (error) {\n if (!isRefreshableProofDependency(error)) throw error;\n const writerProjection = await refresh();\n if (!writerProjection) throw error;\n // Retry the same binding and ciphertext with fully verified fresh proof.\n // A second missing dependency escapes; it cannot trigger another fetch.\n return read({ ...input, writerProjection });\n }\n };\n}\n\nexport function createAttachmentDecryptor(\n apiClient: AttachmentProjectionApi,\n documentId: string,\n) {\n return createAttachmentProofReader(\n apiClient,\n documentId,\n decryptDocumentAttachmentBlob,\n );\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../../internal/crypto/index.js";
|
|
2
2
|
import { verifiedContainerCreateManifest, verifyContainerDestinationProjection, } from "../../../../data/keyingProjectionVerification/index.js";
|
|
3
|
-
import { isKeyingVerificationError, reportKeyingVerificationErrorInCauseChain, } from "../../../../data/keyingProjectionVerification/error.js";
|
|
4
3
|
import { openPrincipalPolicyBundleReader } from "../../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
|
|
5
4
|
import { errorMessage } from "../../../../data/shared/errorMessage.js";
|
|
5
|
+
import { isKeyingVerificationError, reportKeyingVerificationErrorInCauseChain, } from "../../../../data/shared/securityIncidents.js";
|
|
6
6
|
import { settleContainerCreateIntent } from "./createIntentSettlement.js";
|
|
7
7
|
const LABEL = "Container create conflict";
|
|
8
8
|
/** The recorded error that parks an intent whose listed create is foreign. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GACxB,MAAM,mBAAmB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M,CAAC,iBAAiB,EAAE,CAAC;QAC3D,SAAS,CAAC,2BAA2B,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n} from \"../../../../data/keyingProjectionVerification/error\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\n\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type {\n AdoptedContainerPlacement,\n ContainerCreateIntentSyncInput,\n ContainerCreateIntentSyncState,\n} from \"../types\";\nimport { settleContainerCreateIntent } from \"./createIntentSettlement\";\n\nconst LABEL = \"Container create conflict\";\n\n/** The recorded error that parks an intent whose listed create is foreign. */\nexport const CONTAINER_CREATE_ADOPTION_REFUSED =\n \"Container create adoption was refused\";\n\n/**\n * The listed create's signed identity is not this device's pending create: its\n * signed create names another signer, another organization, or a root. An honest server never lists that under the\n * id this device minted, and no later read can change those signed facts, so\n * the intent parks instead of re-verifying.\n */\nclass ForeignContainerCreateError extends KeyingVerificationError {}\n\nfunction foreignCreate(\n code: KeyingVerificationCode,\n message: string,\n): ForeignContainerCreateError {\n return new ForeignContainerCreateError(code, `${LABEL} ${message}`);\n}\n\nasync function verifyAdoptableProjection(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly projection: ContainerWriterProjectionResponse;\n readonly sessionUserId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { projection } = input;\n if (\n projection.containerId !== input.containerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n // The envelope is unsigned: a corrupt read is retried, not parked.\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection has the wrong identity`,\n );\n }\n const { path, verifiedByHash } = await verifyContainerDestinationProjection({\n execSql: input.state.runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n projection,\n resolveUserKey: input.state.resolveProjectionUserKey,\n warmReferencedPrincipalPolicies:\n input.state.runtime.principalPolicies.createWarmer(),\n });\n const head = path.at(-1);\n // One read naming another container says nothing signed about this id.\n if (!head || head.state.containerId !== input.containerId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection names another container`,\n );\n }\n const create = verifiedContainerCreateManifest({\n head,\n label: LABEL,\n verifiedByHash,\n });\n if (create.event.event.signerUserId !== input.sessionUserId) {\n throw foreignCreate(\"signer_mismatch\", \"was signed by another user\");\n }\n if (create.state.organizationId !== input.expectedOrganizationId) {\n throw foreignCreate(\"object_mismatch\", \"belongs to another organization\");\n }\n const createdParentId = create.state.parentContainerId;\n const currentParentId = head.state.parentContainerId;\n if (createdParentId === null || currentParentId === null) {\n throw foreignCreate(\"object_mismatch\", \"is an organization root\");\n }\n return { createdParentId, currentParentId };\n}\n\n/**\n * A pending create whose container the listing already carries is adopted\n * only when the container's signed epoch-1 `container.create` is this user's,\n * in the intended organization (#2365 finding 26). Listing metadata is\n * unsigned: a create by another writer that collides on the pending id, or one\n * a dishonest server invents, must not become this device's container.\n * Documents apply the same rule (`workflows/documents/createAdoption.ts`).\n *\n * Returns where the create committed and where the verified head sits now.\n * The user may have moved the pending container since, which rewrites its\n * intent's parent; that is a move still owed, not a mismatch.\n */\nasync function assertContainerCreateAdoptable(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { runtime } = input.state;\n const sessionUserId = runtime.auth.userId;\n // Without a session user there is no signer to compare: not tampering.\n if (!sessionUserId) {\n throw new Error(`${LABEL} needs a signed-in session user`);\n }\n const projection = await runtime.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!projection) {\n throw new Error(`${LABEL} is unavailable to verify`);\n }\n try {\n return await verifyAdoptableProjection({\n ...input,\n projection,\n sessionUserId,\n });\n } catch (error) {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error)) {\n runtime.apiClient.evictContainerWriterProjection(input.containerId);\n }\n throw error;\n }\n}\n\nfunction verifyListedContainerCreate(input: {\n readonly intent: ContainerCreateIntentSyncInput[\"intent\"];\n readonly parentState: ContainerState;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const adoption = {\n containerId: input.intent.containerId,\n expectedOrganizationId: input.parentState.container.organizationId,\n };\n return input.state.verifyCreateAdoption\n ? input.state.verifyCreateAdoption(adoption)\n : assertContainerCreateAdoptable({ ...adoption, state: input.state });\n}\n\n/** Settles a verified adoption against the row hydration installed. */\nasync function markContainerCreateIntentAdopted(input: {\n containerState: ContainerState;\n placement: AdoptedContainerPlacement;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<boolean> {\n const { containerState, placement, syncInput } = input;\n const remoteMetadataDocumentId = containerState.record.documentId;\n const remoteMetadataAccessStateHash = containerState.record.accessStateHash;\n\n if (!remoteMetadataDocumentId || !remoteMetadataAccessStateHash) {\n return false;\n }\n return settleContainerCreateIntent({\n createdParentContainerId: placement.createdParentId,\n desiredParentContainerId: syncInput.intent.parentContainerId,\n intent: syncInput.intent,\n isCurrent: syncInput.isCurrent,\n remoteContainerId: containerState.container.id,\n remoteMetadataAccessStateHash,\n remoteMetadataDocumentId,\n state: syncInput.state,\n supersededMovePreviousParentId: placement.currentParentId,\n });\n}\n\n/**\n * Records a failed adoption and leaves the lane's other intents to proceed. A\n * foreign create parks the intent: its signed facts never change, so later\n * passes neither re-read it nor report it again. Any other failure retries.\n */\nasync function recordAdoptionFailure(input: {\n readonly error: unknown;\n readonly organizationId: string;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"failed\"> {\n const { intent, isCurrent, state } = input.syncInput;\n if (!isCurrent()) return \"abandoned\";\n await reportKeyingVerificationErrorInCauseChain(\n input.error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.containerId,\n objectKind: \"container\",\n operation: \"container.create.replay\",\n organizationId: input.organizationId,\n },\n );\n if (!isCurrent()) return \"abandoned\";\n const action =\n input.error instanceof ForeignContainerCreateError\n ? CONTAINER_CREATE_ADOPTION_REFUSED\n : \"Container create adoption verification failed\";\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: `${action}: ${errorMessage(input.error)}`,\n stillCurrent: isCurrent,\n },\n );\n return isCurrent() ? \"failed\" : \"abandoned\";\n}\n\n/**\n * Adopts a pending create the listing already carries, once its signed create\n * proves it is this device's. A parked refusal stays blocked without a read.\n */\nexport async function syncListedContainerCreate(input: {\n readonly containerState: ContainerState;\n readonly parentState: ContainerState;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"blocked\" | \"created\" | \"failed\"> {\n const { containerState, parentState, syncInput } = input;\n const { intent, isCurrent, state } = syncInput;\n if (intent.lastError?.startsWith(CONTAINER_CREATE_ADOPTION_REFUSED)) {\n return \"blocked\";\n }\n let placement: AdoptedContainerPlacement;\n try {\n placement = await verifyListedContainerCreate({\n intent,\n parentState,\n state,\n });\n } catch (error) {\n return recordAdoptionFailure({\n error,\n organizationId: parentState.container.organizationId,\n syncInput,\n });\n }\n const marked = await markContainerCreateIntentAdopted({\n containerState,\n placement,\n syncInput,\n });\n if (!marked) return isCurrent() ? \"blocked\" : \"abandoned\";\n // The folder now sits elsewhere; list it there rather than waiting for the\n // next poll to correct the local parent.\n if (placement.currentParentId !== intent.parentContainerId) {\n syncInput.requestRemoteReconciliation(placement.currentParentId);\n }\n return \"created\";\n}\n"]}
|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AAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;IAC1D,2EAA2E;IAC3E,yCAAyC;IACzC,IAAI,SAAS,CAAC,eAAe,KAAK,MAAM,CAAC,iBAAiB,EAAE,CAAC;QAC3D,SAAS,CAAC,2BAA2B,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n} from \"../../../../data/shared/securityIncidents\";\n\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type {\n AdoptedContainerPlacement,\n ContainerCreateIntentSyncInput,\n ContainerCreateIntentSyncState,\n} from \"../types\";\nimport { settleContainerCreateIntent } from \"./createIntentSettlement\";\n\nconst LABEL = \"Container create conflict\";\n\n/** The recorded error that parks an intent whose listed create is foreign. */\nexport const CONTAINER_CREATE_ADOPTION_REFUSED =\n \"Container create adoption was refused\";\n\n/**\n * The listed create's signed identity is not this device's pending create: its\n * signed create names another signer, another organization, or a root. An honest server never lists that under the\n * id this device minted, and no later read can change those signed facts, so\n * the intent parks instead of re-verifying.\n */\nclass ForeignContainerCreateError extends KeyingVerificationError {}\n\nfunction foreignCreate(\n code: KeyingVerificationCode,\n message: string,\n): ForeignContainerCreateError {\n return new ForeignContainerCreateError(code, `${LABEL} ${message}`);\n}\n\nasync function verifyAdoptableProjection(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly projection: ContainerWriterProjectionResponse;\n readonly sessionUserId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { projection } = input;\n if (\n projection.containerId !== input.containerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n // The envelope is unsigned: a corrupt read is retried, not parked.\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection has the wrong identity`,\n );\n }\n const { path, verifiedByHash } = await verifyContainerDestinationProjection({\n execSql: input.state.runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n projection,\n resolveUserKey: input.state.resolveProjectionUserKey,\n warmReferencedPrincipalPolicies:\n input.state.runtime.principalPolicies.createWarmer(),\n });\n const head = path.at(-1);\n // One read naming another container says nothing signed about this id.\n if (!head || head.state.containerId !== input.containerId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection names another container`,\n );\n }\n const create = verifiedContainerCreateManifest({\n head,\n label: LABEL,\n verifiedByHash,\n });\n if (create.event.event.signerUserId !== input.sessionUserId) {\n throw foreignCreate(\"signer_mismatch\", \"was signed by another user\");\n }\n if (create.state.organizationId !== input.expectedOrganizationId) {\n throw foreignCreate(\"object_mismatch\", \"belongs to another organization\");\n }\n const createdParentId = create.state.parentContainerId;\n const currentParentId = head.state.parentContainerId;\n if (createdParentId === null || currentParentId === null) {\n throw foreignCreate(\"object_mismatch\", \"is an organization root\");\n }\n return { createdParentId, currentParentId };\n}\n\n/**\n * A pending create whose container the listing already carries is adopted\n * only when the container's signed epoch-1 `container.create` is this user's,\n * in the intended organization (#2365 finding 26). Listing metadata is\n * unsigned: a create by another writer that collides on the pending id, or one\n * a dishonest server invents, must not become this device's container.\n * Documents apply the same rule (`workflows/documents/createAdoption.ts`).\n *\n * Returns where the create committed and where the verified head sits now.\n * The user may have moved the pending container since, which rewrites its\n * intent's parent; that is a move still owed, not a mismatch.\n */\nasync function assertContainerCreateAdoptable(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { runtime } = input.state;\n const sessionUserId = runtime.auth.userId;\n // Without a session user there is no signer to compare: not tampering.\n if (!sessionUserId) {\n throw new Error(`${LABEL} needs a signed-in session user`);\n }\n const projection = await runtime.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!projection) {\n throw new Error(`${LABEL} is unavailable to verify`);\n }\n try {\n return await verifyAdoptableProjection({\n ...input,\n projection,\n sessionUserId,\n });\n } catch (error) {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error)) {\n runtime.apiClient.evictContainerWriterProjection(input.containerId);\n }\n throw error;\n }\n}\n\nfunction verifyListedContainerCreate(input: {\n readonly intent: ContainerCreateIntentSyncInput[\"intent\"];\n readonly parentState: ContainerState;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const adoption = {\n containerId: input.intent.containerId,\n expectedOrganizationId: input.parentState.container.organizationId,\n };\n return input.state.verifyCreateAdoption\n ? input.state.verifyCreateAdoption(adoption)\n : assertContainerCreateAdoptable({ ...adoption, state: input.state });\n}\n\n/** Settles a verified adoption against the row hydration installed. */\nasync function markContainerCreateIntentAdopted(input: {\n containerState: ContainerState;\n placement: AdoptedContainerPlacement;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<boolean> {\n const { containerState, placement, syncInput } = input;\n const remoteMetadataDocumentId = containerState.record.documentId;\n const remoteMetadataAccessStateHash = containerState.record.accessStateHash;\n\n if (!remoteMetadataDocumentId || !remoteMetadataAccessStateHash) {\n return false;\n }\n return settleContainerCreateIntent({\n createdParentContainerId: placement.createdParentId,\n desiredParentContainerId: syncInput.intent.parentContainerId,\n intent: syncInput.intent,\n isCurrent: syncInput.isCurrent,\n remoteContainerId: containerState.container.id,\n remoteMetadataAccessStateHash,\n remoteMetadataDocumentId,\n state: syncInput.state,\n supersededMovePreviousParentId: placement.currentParentId,\n });\n}\n\n/**\n * Records a failed adoption and leaves the lane's other intents to proceed. A\n * foreign create parks the intent: its signed facts never change, so later\n * passes neither re-read it nor report it again. Any other failure retries.\n */\nasync function recordAdoptionFailure(input: {\n readonly error: unknown;\n readonly organizationId: string;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"failed\"> {\n const { intent, isCurrent, state } = input.syncInput;\n if (!isCurrent()) return \"abandoned\";\n await reportKeyingVerificationErrorInCauseChain(\n input.error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.containerId,\n objectKind: \"container\",\n operation: \"container.create.replay\",\n organizationId: input.organizationId,\n },\n );\n if (!isCurrent()) return \"abandoned\";\n const action =\n input.error instanceof ForeignContainerCreateError\n ? CONTAINER_CREATE_ADOPTION_REFUSED\n : \"Container create adoption verification failed\";\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: `${action}: ${errorMessage(input.error)}`,\n stillCurrent: isCurrent,\n },\n );\n return isCurrent() ? \"failed\" : \"abandoned\";\n}\n\n/**\n * Adopts a pending create the listing already carries, once its signed create\n * proves it is this device's. A parked refusal stays blocked without a read.\n */\nexport async function syncListedContainerCreate(input: {\n readonly containerState: ContainerState;\n readonly parentState: ContainerState;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"blocked\" | \"created\" | \"failed\"> {\n const { containerState, parentState, syncInput } = input;\n const { intent, isCurrent, state } = syncInput;\n if (intent.lastError?.startsWith(CONTAINER_CREATE_ADOPTION_REFUSED)) {\n return \"blocked\";\n }\n let placement: AdoptedContainerPlacement;\n try {\n placement = await verifyListedContainerCreate({\n intent,\n parentState,\n state,\n });\n } catch (error) {\n return recordAdoptionFailure({\n error,\n organizationId: parentState.container.organizationId,\n syncInput,\n });\n }\n const marked = await markContainerCreateIntentAdopted({\n containerState,\n placement,\n syncInput,\n });\n if (!marked) return isCurrent() ? \"blocked\" : \"abandoned\";\n // The folder now sits elsewhere; list it there rather than waiting for the\n // next poll to correct the local parent.\n if (placement.currentParentId !== intent.parentContainerId) {\n syncInput.requestRemoteReconciliation(placement.currentParentId);\n }\n return \"created\";\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ContainerPathTooDeepError } from "../../../../data/containers/shared/containerPathLimits.js";
|
|
2
|
-
import { reportAndRethrowKeyingVerificationError } from "../../../../data/keyingProjectionVerification/error.js";
|
|
3
2
|
import { ContainerCreateIntentSupersededError } from "../../../../data/persistence/container-contents/containerIntentPersistence.js";
|
|
4
3
|
import { errorMessage } from "../../../../data/shared/errorMessage.js";
|
|
4
|
+
import { reportAndRethrowKeyingVerificationError } from "../../../../data/shared/securityIncidents.js";
|
|
5
5
|
import { createDetachedContainerMetadataState, installDetachedContainerMetadataState, } from "../../metadata/metadataStateIsolation.js";
|
|
6
6
|
import { hasRemoteContainerMetadataState } from "../../remoteHydration/reconciliation.js";
|
|
7
7
|
import { createRemoteContainer, discardOrphanedRemoteContainer, } from "../remote.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createIntentSync.js","sourceRoot":"","sources":["createIntentSync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,wDAAwD,CAAC;AACnG,OAAO,EAAE,uCAAuC,EAAE,MAAM,qDAAqD,CAAC;AAC9G,OAAO,EAAE,oCAAoC,EAAE,MAAM,4EAA4E,CAAC;AAClI,OAAO,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AACpE,OAAO,EACL,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AACvF,OAAO,EACL,qBAAqB,EACrB,8BAA8B,GAC/B,MAAM,WAAW,CAAC;AAOnB,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,q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,SAAS,EAAE,KAAK,CAAC,SAAS;gBAC1B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;gBAC9C,MAAM;gBACN,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;gBAC9D,KAAK;aACN,CACF,CAAC;YACF,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;gBAC3B,OAAO,YAAY,CAAC;YACtB,CAAC;YAED,IACE,wBAAwB,CACtB,MAAM,EACN,MAAM,CAAC,WAAW,EAClB,qBAAqB,EACrB,qBAAqB,CACtB,EACD,CAAC;gBACD,UAAU,GAAG,IAAI,CAAC;gBAClB,YAAY,IAAI,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import { ContainerPathTooDeepError } from \"../../../../data/containers/shared/containerPathLimits\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../../data/keyingProjectionVerification/error\";\nimport { ContainerCreateIntentSupersededError } from \"../../../../data/persistence/container-contents/containerIntentPersistence\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"../../metadata/metadataStateIsolation\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { hasRemoteContainerMetadataState } from \"../../remoteHydration/reconciliation\";\nimport {\n createRemoteContainer,\n discardOrphanedRemoteContainer,\n} from \"../remote\";\nimport type {\n ContainerCreateIntentSyncHost,\n ContainerCreateIntentSyncInput,\n ContainerCreateIntentSyncState,\n CreatedRemoteContainerState,\n} from \"../types\";\nimport { syncListedContainerCreate } from \"./createAdoption\";\nimport {\n deferTooDeepCreate,\n recordRefusedTooDeepCreate,\n} from \"./createIntentDepth\";\nimport {\n loadMetadataSeedUpdate,\n withPlannedMetadataDocumentId,\n withRegisteredMetadataSeed,\n} from \"./createIntentSeed\";\nimport { CONTAINER_ALREADY_COMMITTED } from \"./createWithMetadata\";\n\nclass IncompleteContainerCreateSettlementError extends Error {}\n\ntype CreateIntentSyncResult = \"abandoned\" | \"blocked\" | \"created\" | \"failed\";\n\nfunction currentCreateResult<\n Result extends Exclude<CreateIntentSyncResult, \"abandoned\">,\n>(isCurrent: () => boolean, result: Result): \"abandoned\" | Result {\n return isCurrent() ? result : \"abandoned\";\n}\n\nasync function reportContainerCreateIntegrityFailure(input: {\n readonly containerId: string;\n readonly error: unknown;\n readonly organizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<void> {\n await reportAndRethrowKeyingVerificationError(\n input.error,\n input.state.runtime.util.reportSecurityIncident,\n {\n objectId: input.containerId,\n objectKind: \"container\",\n operation: \"container.create.replay\",\n organizationId: input.organizationId,\n },\n );\n}\n\nasync function recordContainerCreateFailure(input: {\n readonly error: unknown;\n readonly isCurrent: () => boolean;\n readonly intent: ContainerCreateIntentSyncInput[\"intent\"];\n readonly organizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<\"abandoned\" | \"failed\"> {\n if (!input.isCurrent()) {\n return \"abandoned\";\n }\n await reportContainerCreateIntegrityFailure({\n containerId: input.intent.containerId,\n error: input.error,\n organizationId: input.organizationId,\n state: input.state,\n });\n if (!input.isCurrent()) {\n return \"abandoned\";\n }\n await input.state.persistence.recordCreateIntentRevisionError(\n input.state.runtime.infra.execSql,\n {\n containerId: input.intent.containerId,\n expectedIntentId: input.intent.id,\n expectedUpdatedAt: input.intent.updatedAt,\n message: `${input.error instanceof IncompleteContainerCreateSettlementError ? \"Container create persistence failed\" : \"Remote container create failed\"}: ${errorMessage(input.error)}`,\n stillCurrent: input.isCurrent,\n },\n );\n return currentCreateResult(input.isCurrent, \"failed\");\n}\n\nasync function persistCreatedRemoteContainerStateFromIntent(input: {\n containerState: ContainerState;\n created: CreatedRemoteContainerState;\n host: ContainerCreateIntentSyncHost;\n isCurrent: () => boolean;\n intent: ContainerCreateIntentSyncInput[\"intent\"];\n state: ContainerCreateIntentSyncState;\n}): Promise<\n | \"abandoned\"\n | \"identity-superseded\"\n | \"intent-superseded\"\n | \"missing\"\n | \"persisted\"\n> {\n const { containerState, created, host, intent, state } = input;\n if (!input.isCurrent()) return \"abandoned\";\n const persistenceCandidate =\n await createDetachedContainerMetadataState(containerState);\n if (!input.isCurrent()) return \"abandoned\";\n persistenceCandidate.container = {\n ...persistenceCandidate.container,\n createdAt: created.createdAt,\n serverCreatedAt: created.createdAt,\n serverUpdatedAt: created.updatedAt,\n updatedAt: created.updatedAt,\n };\n\n let persistenceResult: Awaited<\n ReturnType<ContainerCreateIntentSyncHost[\"persistContainerState\"]>\n >;\n try {\n persistenceResult = await host.persistContainerState(\n persistenceCandidate,\n {\n accessEpoch: 1,\n accessStateHash: created.accessManifestHash,\n // A committed seed stands in for the first metadata sync.\n lastCommitLsn: created.metadataSeed?.commitLsn ?? null,\n metadataDocumentId: created.metadataDocumentId,\n systemSlot: created.systemSlot,\n organizationId: created.organizationId,\n parentId: created.parentId,\n ...created.persistedMetadataState,\n },\n false,\n {\n serverTimestamps: {\n createdAt: created.createdAt,\n updatedAt: created.updatedAt,\n },\n },\n {\n ...(created.metadataSeed\n ? {\n acceptedPendingUpdateIds: [created.metadataSeed.updateId],\n clearSyncFailure: true,\n }\n : {}),\n createIntentSettlement: {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n remoteContainerId: created.containerId,\n remoteMetadataAccessStateHash: created.accessManifestHash,\n remoteMetadataDocumentId: created.metadataDocumentId,\n supersededMovePreviousParentId: created.parentId,\n },\n expectedStateWhenMissing: containerState,\n isCurrent: input.isCurrent,\n preserveDurableStructureWhenPending: true,\n },\n );\n } catch (error) {\n if (error instanceof ContainerCreateIntentSupersededError) {\n return \"intent-superseded\";\n }\n throw error;\n }\n if (!input.isCurrent() || persistenceResult.status === \"stale-generation\") {\n return \"abandoned\";\n }\n if (persistenceResult.status !== \"persisted\") return persistenceResult.status;\n if (persistenceResult.createIntentSettled !== true) {\n throw new IncompleteContainerCreateSettlementError(\n \"Container create persistence must settle the intent atomically\",\n );\n }\n const { record: nextRecord } = persistenceResult;\n if (!input.isCurrent()) return \"abandoned\";\n const currentContainerState = state.containersById.get(intent.containerId);\n if (!currentContainerState) return \"missing\";\n if (currentContainerState !== containerState) return \"identity-superseded\";\n\n installDetachedContainerMetadataState(containerState, persistenceCandidate, {\n candidateRecord: nextRecord,\n preserveConcurrentMetadataEdit: true,\n });\n containerState.container = {\n ...containerState.container,\n metadataDocumentId: created.metadataDocumentId,\n systemSlot: created.systemSlot,\n organizationId: created.organizationId,\n parentId: persistenceCandidate.container.parentId,\n serverCreatedAt: created.createdAt,\n serverUpdatedAt: created.updatedAt,\n createdAt: created.createdAt,\n updatedAt: created.updatedAt,\n };\n return \"persisted\";\n}\n\nasync function settleRemoteContainerCreate(input: {\n containerState: ContainerState;\n created: Awaited<ReturnType<typeof createRemoteContainer>>;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<CreateIntentSyncResult> {\n const { containerState, created, syncInput } = input;\n const { host, intent, state } = syncInput;\n if (created === CONTAINER_ALREADY_COMMITTED) {\n // A lost create response leaves the intent pending until hydration installs\n // the committed remote metadata state.\n state.runtime.util.log(\n `Container contents: deferred create intent for ${intent.containerId}; container already committed remotely, awaiting hydration.`,\n );\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return \"blocked\";\n }\n if (!created) {\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: \"Remote container create was rejected or unavailable\",\n stillCurrent: syncInput.isCurrent,\n },\n );\n return currentCreateResult(syncInput.isCurrent, \"failed\");\n }\n if (!state.containersById.has(intent.containerId)) {\n // A same-generation local delete wins; discard the remote orphan instead\n // of resurrecting the deleted local container.\n await discardOrphanedRemoteContainer({\n created,\n isCurrent: syncInput.isCurrent,\n state,\n });\n return currentCreateResult(syncInput.isCurrent, \"failed\");\n }\n\n const persistenceStatus = await persistCreatedRemoteContainerStateFromIntent({\n containerState,\n created,\n host,\n isCurrent: syncInput.isCurrent,\n intent,\n state,\n });\n if (persistenceStatus === \"abandoned\") {\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return \"abandoned\";\n }\n if (persistenceStatus === \"missing\") {\n await discardOrphanedRemoteContainer({\n created,\n isCurrent: syncInput.isCurrent,\n state,\n });\n return currentCreateResult(syncInput.isCurrent, \"failed\");\n }\n if (persistenceStatus === \"identity-superseded\") {\n state.runtime.util.log(\n `Container contents: deferred create intent for ${intent.containerId}; another writer persisted its remote identity.`,\n );\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return \"blocked\";\n }\n if (persistenceStatus === \"intent-superseded\") {\n state.runtime.util.log(\n `Container contents: deferred create intent for ${intent.containerId}; a newer local intent superseded this pass.`,\n );\n return \"blocked\";\n }\n state.runtime.util.log(\n `Container contents: synced local container create ${containerState.container.id}`,\n );\n return \"created\";\n}\n\nasync function createPendingRemoteContainer(input: {\n containerState: ContainerState;\n parentState: ContainerState;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<CreateIntentSyncResult> {\n const { containerState, parentState, syncInput } = input;\n const { intent, state } = syncInput;\n const metadataSeedUpdate = await loadMetadataSeedUpdate(\n syncInput.state,\n containerState,\n );\n if (!syncInput.isCurrent()) return \"abandoned\";\n let created: Awaited<ReturnType<typeof createRemoteContainer>>;\n try {\n created = await withRegisteredMetadataSeed(\n state.locallyAcceptedMetadataUpdateIds,\n metadataSeedUpdate,\n () =>\n createRemoteContainer({\n systemSlot: containerState.container.systemSlot,\n containerId: containerState.container.id,\n ...(metadataSeedUpdate ? { metadataSeedUpdate } : {}),\n parentContainerId: parentState.container.id,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n runtime: state.runtime,\n stillCurrent: syncInput.isCurrent,\n }),\n );\n } catch (error) {\n if (error instanceof ContainerPathTooDeepError)\n return recordRefusedTooDeepCreate(syncInput);\n return recordContainerCreateFailure({\n error,\n isCurrent: syncInput.isCurrent,\n intent,\n organizationId: parentState.container.organizationId,\n state,\n });\n }\n if (!syncInput.isCurrent()) {\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return \"abandoned\";\n }\n try {\n return await settleRemoteContainerCreate({\n containerState,\n created,\n syncInput,\n });\n } catch (error) {\n if (!(error instanceof IncompleteContainerCreateSettlementError))\n throw error;\n return recordContainerCreateFailure({\n error,\n isCurrent: syncInput.isCurrent,\n intent,\n organizationId: parentState.container.organizationId,\n state,\n });\n }\n}\n\nasync function trySyncPendingContainerContentsContainerCreateIntent(\n input: ContainerCreateIntentSyncInput,\n): Promise<CreateIntentSyncResult> {\n const { intent, state } = input;\n if (!input.isCurrent()) {\n return \"abandoned\";\n }\n const containerState = state.containersById.get(intent.containerId);\n const parentState = state.containersById.get(intent.parentContainerId);\n\n if (!containerState || !parentState) {\n const execSql = state.runtime.infra.execSql;\n await state.persistence.recordCreateIntentRevisionError(execSql, {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: \"Container create intent references a missing local container\",\n stillCurrent: input.isCurrent,\n });\n return currentCreateResult(input.isCurrent, \"failed\");\n }\n\n if (typeof state.persistence.markCreateIntentRevisionSynced !== \"function\") {\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: \"Container create replay requires revision-CAS persistence\",\n stillCurrent: input.isCurrent,\n },\n );\n return currentCreateResult(input.isCurrent, \"failed\");\n }\n\n if (input.isRemoteSyncBlocked(parentState.container.organizationId)) {\n return \"blocked\";\n }\n\n if (hasRemoteContainerMetadataState(containerState)) {\n return syncListedContainerCreate({\n containerState,\n parentState,\n syncInput: input,\n });\n }\n\n // A parent whose own create has not settled may carry a listed identity\n // adoption has not verified, or has refused; nothing is created under it.\n if (\n !hasRemoteContainerMetadataState(parentState) ||\n input.isCreatePending(parentState.container.id)\n ) {\n return \"blocked\";\n }\n\n if (await deferTooDeepCreate(input)) {\n return currentCreateResult(input.isCurrent, \"blocked\");\n }\n\n return withPlannedMetadataDocumentId(\n state.plannedMetadataDocumentIds,\n containerState.container.id,\n () =>\n createPendingRemoteContainer({\n containerState,\n parentState,\n syncInput: input,\n }),\n );\n}\n\n/** A blocked create stays for a later round; only a created one settles. */\nfunction settleCreateIntentResult(\n result: CreateIntentSyncResult,\n containerId: string,\n remaining: Set<string>,\n unsettled: Set<string>,\n): boolean {\n if (result === \"blocked\") return false;\n remaining.delete(containerId);\n if (result !== \"created\") return false;\n unsettled.delete(containerId);\n return true;\n}\n\nexport async function syncPendingContainerCreateIntents(input: {\n host: ContainerCreateIntentSyncHost;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerCreateIntentSyncState;\n}): Promise<number> {\n if (!input.isCurrent()) {\n return 0;\n }\n const { host } = input;\n const state = { ...input.state };\n const execSql = state.runtime.infra.execSql;\n const pendingIntents =\n await state.persistence.listPendingCreateIntents(execSql);\n if (!input.isCurrent()) {\n return 0;\n }\n const remainingContainerIds = new Set(\n pendingIntents.map((intent) => intent.containerId),\n );\n // Only a create that settles in this pass leaves the pending set; a failed\n // or parked one stays pending even though this pass stops retrying it.\n const unsettledContainerIds = new Set(remainingContainerIds);\n let createdCount = 0;\n let progressed = true;\n\n while (progressed && input.isCurrent()) {\n progressed = false;\n\n for (const intent of pendingIntents) {\n if (!remainingContainerIds.has(intent.containerId)) {\n continue;\n }\n\n const result = await trySyncPendingContainerContentsContainerCreateIntent(\n {\n host,\n isCreatePending: (containerId) =>\n unsettledContainerIds.has(containerId),\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n intent,\n requestRemoteReconciliation: input.requestRemoteReconciliation,\n state,\n },\n );\n if (result === \"abandoned\") {\n return createdCount;\n }\n\n if (\n settleCreateIntentResult(\n result,\n intent.containerId,\n remainingContainerIds,\n unsettledContainerIds,\n )\n ) {\n progressed = true;\n createdCount += 1;\n }\n }\n }\n\n return createdCount;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"createIntentSync.js","sourceRoot":"","sources":["createIntentSync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,wDAAwD,CAAC;AACnG,OAAO,EAAE,oCAAoC,EAAE,MAAM,4EAA4E,CAAC;AAClI,OAAO,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AACpE,OAAO,EAAE,uCAAuC,EAAE,MAAM,2CAA2C,CAAC;AACpG,OAAO,EACL,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AACvF,OAAO,EACL,qBAAqB,EACrB,8BAA8B,GAC/B,MAAM,WAAW,CAAC;AAOnB,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,sBAAsB,EACtB,6BAA6B,EAC7B,0BAA0B,GAC3B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AAEnE,MAAM,wCAAyC,SAAQ,KAAK;CAAG;AAI/D,SAAS,mBAAmB,CAE1B,SAAwB,EAAE,MAAc;IACxC,OAAO,SAAS,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC;AAC5C,CAAC;AAED,KAAK,UAAU,qCAAqC,CAAC,KAKpD;IACC,MAAM,uCAAuC,CAC3C,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,sBAAsB,EAC/C;QACE,QAAQ,EAAE,KAAK,CAAC,WAAW;QAC3B,UAAU,EAAE,WAAW;QACvB,SAAS,EAA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IAAI,GAAG,CACnC,cAAc,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,CACnD,CAAC;IACF,2EAA2E;IAC3E,uEAAuE;IACvE,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,qBAAqB,CAAC,CAAC;IAC7D,IAAI,YAAY,GAAG,CAAC,CAAC;IACrB,IAAI,UAAU,GAAG,IAAI,CAAC;IAEtB,OAAO,UAAU,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACvC,UAAU,GAAG,KAAK,CAAC;QAEnB,KAAK,MAAM,MAAM,IAAI,cAAc,EAAE,CAAC;YACpC,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC;gBACnD,SAAS;YACX,CAAC;YAED,MAAM,MAAM,GAAG,MAAM,oDAAoD,CACvE;gBACE,IAAI;gBACJ,eAAe,EAAE,CAAC,WAAW,EAAE,EAAE,CAC/B,qBAAqB,CAAC,GAAG,CAAC,WAAW,CAAC;gBACxC,SAAS,EAAE,KAAK,CAAC,SAAS;gBAC1B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;gBAC9C,MAAM;gBACN,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;gBAC9D,KAAK;aACN,CACF,CAAC;YACF,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;gBAC3B,OAAO,YAAY,CAAC;YACtB,CAAC;YAED,IACE,wBAAwB,CACtB,MAAM,EACN,MAAM,CAAC,WAAW,EAClB,qBAAqB,EACrB,qBAAqB,CACtB,EACD,CAAC;gBACD,UAAU,GAAG,IAAI,CAAC;gBAClB,YAAY,IAAI,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import { ContainerPathTooDeepError } from \"../../../../data/containers/shared/containerPathLimits\";\nimport { ContainerCreateIntentSupersededError } from \"../../../../data/persistence/container-contents/containerIntentPersistence\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../../data/shared/securityIncidents\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"../../metadata/metadataStateIsolation\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { hasRemoteContainerMetadataState } from \"../../remoteHydration/reconciliation\";\nimport {\n createRemoteContainer,\n discardOrphanedRemoteContainer,\n} from \"../remote\";\nimport type {\n ContainerCreateIntentSyncHost,\n ContainerCreateIntentSyncInput,\n ContainerCreateIntentSyncState,\n CreatedRemoteContainerState,\n} from \"../types\";\nimport { syncListedContainerCreate } from \"./createAdoption\";\nimport {\n deferTooDeepCreate,\n recordRefusedTooDeepCreate,\n} from \"./createIntentDepth\";\nimport {\n loadMetadataSeedUpdate,\n withPlannedMetadataDocumentId,\n withRegisteredMetadataSeed,\n} from \"./createIntentSeed\";\nimport { CONTAINER_ALREADY_COMMITTED } from \"./createWithMetadata\";\n\nclass IncompleteContainerCreateSettlementError extends Error {}\n\ntype CreateIntentSyncResult = \"abandoned\" | \"blocked\" | \"created\" | \"failed\";\n\nfunction currentCreateResult<\n Result extends Exclude<CreateIntentSyncResult, \"abandoned\">,\n>(isCurrent: () => boolean, result: Result): \"abandoned\" | Result {\n return isCurrent() ? result : \"abandoned\";\n}\n\nasync function reportContainerCreateIntegrityFailure(input: {\n readonly containerId: string;\n readonly error: unknown;\n readonly organizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<void> {\n await reportAndRethrowKeyingVerificationError(\n input.error,\n input.state.runtime.util.reportSecurityIncident,\n {\n objectId: input.containerId,\n objectKind: \"container\",\n operation: \"container.create.replay\",\n organizationId: input.organizationId,\n },\n );\n}\n\nasync function recordContainerCreateFailure(input: {\n readonly error: unknown;\n readonly isCurrent: () => boolean;\n readonly intent: ContainerCreateIntentSyncInput[\"intent\"];\n readonly organizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<\"abandoned\" | \"failed\"> {\n if (!input.isCurrent()) {\n return \"abandoned\";\n }\n await reportContainerCreateIntegrityFailure({\n containerId: input.intent.containerId,\n error: input.error,\n organizationId: input.organizationId,\n state: input.state,\n });\n if (!input.isCurrent()) {\n return \"abandoned\";\n }\n await input.state.persistence.recordCreateIntentRevisionError(\n input.state.runtime.infra.execSql,\n {\n containerId: input.intent.containerId,\n expectedIntentId: input.intent.id,\n expectedUpdatedAt: input.intent.updatedAt,\n message: `${input.error instanceof IncompleteContainerCreateSettlementError ? \"Container create persistence failed\" : \"Remote container create failed\"}: ${errorMessage(input.error)}`,\n stillCurrent: input.isCurrent,\n },\n );\n return currentCreateResult(input.isCurrent, \"failed\");\n}\n\nasync function persistCreatedRemoteContainerStateFromIntent(input: {\n containerState: ContainerState;\n created: CreatedRemoteContainerState;\n host: ContainerCreateIntentSyncHost;\n isCurrent: () => boolean;\n intent: ContainerCreateIntentSyncInput[\"intent\"];\n state: ContainerCreateIntentSyncState;\n}): Promise<\n | \"abandoned\"\n | \"identity-superseded\"\n | \"intent-superseded\"\n | \"missing\"\n | \"persisted\"\n> {\n const { containerState, created, host, intent, state } = input;\n if (!input.isCurrent()) return \"abandoned\";\n const persistenceCandidate =\n await createDetachedContainerMetadataState(containerState);\n if (!input.isCurrent()) return \"abandoned\";\n persistenceCandidate.container = {\n ...persistenceCandidate.container,\n createdAt: created.createdAt,\n serverCreatedAt: created.createdAt,\n serverUpdatedAt: created.updatedAt,\n updatedAt: created.updatedAt,\n };\n\n let persistenceResult: Awaited<\n ReturnType<ContainerCreateIntentSyncHost[\"persistContainerState\"]>\n >;\n try {\n persistenceResult = await host.persistContainerState(\n persistenceCandidate,\n {\n accessEpoch: 1,\n accessStateHash: created.accessManifestHash,\n // A committed seed stands in for the first metadata sync.\n lastCommitLsn: created.metadataSeed?.commitLsn ?? null,\n metadataDocumentId: created.metadataDocumentId,\n systemSlot: created.systemSlot,\n organizationId: created.organizationId,\n parentId: created.parentId,\n ...created.persistedMetadataState,\n },\n false,\n {\n serverTimestamps: {\n createdAt: created.createdAt,\n updatedAt: created.updatedAt,\n },\n },\n {\n ...(created.metadataSeed\n ? {\n acceptedPendingUpdateIds: [created.metadataSeed.updateId],\n clearSyncFailure: true,\n }\n : {}),\n createIntentSettlement: {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n remoteContainerId: created.containerId,\n remoteMetadataAccessStateHash: created.accessManifestHash,\n remoteMetadataDocumentId: created.metadataDocumentId,\n supersededMovePreviousParentId: created.parentId,\n },\n expectedStateWhenMissing: containerState,\n isCurrent: input.isCurrent,\n preserveDurableStructureWhenPending: true,\n },\n );\n } catch (error) {\n if (error instanceof ContainerCreateIntentSupersededError) {\n return \"intent-superseded\";\n }\n throw error;\n }\n if (!input.isCurrent() || persistenceResult.status === \"stale-generation\") {\n return \"abandoned\";\n }\n if (persistenceResult.status !== \"persisted\") return persistenceResult.status;\n if (persistenceResult.createIntentSettled !== true) {\n throw new IncompleteContainerCreateSettlementError(\n \"Container create persistence must settle the intent atomically\",\n );\n }\n const { record: nextRecord } = persistenceResult;\n if (!input.isCurrent()) return \"abandoned\";\n const currentContainerState = state.containersById.get(intent.containerId);\n if (!currentContainerState) return \"missing\";\n if (currentContainerState !== containerState) return \"identity-superseded\";\n\n installDetachedContainerMetadataState(containerState, persistenceCandidate, {\n candidateRecord: nextRecord,\n preserveConcurrentMetadataEdit: true,\n });\n containerState.container = {\n ...containerState.container,\n metadataDocumentId: created.metadataDocumentId,\n systemSlot: created.systemSlot,\n organizationId: created.organizationId,\n parentId: persistenceCandidate.container.parentId,\n serverCreatedAt: created.createdAt,\n serverUpdatedAt: created.updatedAt,\n createdAt: created.createdAt,\n updatedAt: created.updatedAt,\n };\n return \"persisted\";\n}\n\nasync function settleRemoteContainerCreate(input: {\n containerState: ContainerState;\n created: Awaited<ReturnType<typeof createRemoteContainer>>;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<CreateIntentSyncResult> {\n const { containerState, created, syncInput } = input;\n const { host, intent, state } = syncInput;\n if (created === CONTAINER_ALREADY_COMMITTED) {\n // A lost create response leaves the intent pending until hydration installs\n // the committed remote metadata state.\n state.runtime.util.log(\n `Container contents: deferred create intent for ${intent.containerId}; container already committed remotely, awaiting hydration.`,\n );\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return \"blocked\";\n }\n if (!created) {\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: \"Remote container create was rejected or unavailable\",\n stillCurrent: syncInput.isCurrent,\n },\n );\n return currentCreateResult(syncInput.isCurrent, \"failed\");\n }\n if (!state.containersById.has(intent.containerId)) {\n // A same-generation local delete wins; discard the remote orphan instead\n // of resurrecting the deleted local container.\n await discardOrphanedRemoteContainer({\n created,\n isCurrent: syncInput.isCurrent,\n state,\n });\n return currentCreateResult(syncInput.isCurrent, \"failed\");\n }\n\n const persistenceStatus = await persistCreatedRemoteContainerStateFromIntent({\n containerState,\n created,\n host,\n isCurrent: syncInput.isCurrent,\n intent,\n state,\n });\n if (persistenceStatus === \"abandoned\") {\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return \"abandoned\";\n }\n if (persistenceStatus === \"missing\") {\n await discardOrphanedRemoteContainer({\n created,\n isCurrent: syncInput.isCurrent,\n state,\n });\n return currentCreateResult(syncInput.isCurrent, \"failed\");\n }\n if (persistenceStatus === \"identity-superseded\") {\n state.runtime.util.log(\n `Container contents: deferred create intent for ${intent.containerId}; another writer persisted its remote identity.`,\n );\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return \"blocked\";\n }\n if (persistenceStatus === \"intent-superseded\") {\n state.runtime.util.log(\n `Container contents: deferred create intent for ${intent.containerId}; a newer local intent superseded this pass.`,\n );\n return \"blocked\";\n }\n state.runtime.util.log(\n `Container contents: synced local container create ${containerState.container.id}`,\n );\n return \"created\";\n}\n\nasync function createPendingRemoteContainer(input: {\n containerState: ContainerState;\n parentState: ContainerState;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<CreateIntentSyncResult> {\n const { containerState, parentState, syncInput } = input;\n const { intent, state } = syncInput;\n const metadataSeedUpdate = await loadMetadataSeedUpdate(\n syncInput.state,\n containerState,\n );\n if (!syncInput.isCurrent()) return \"abandoned\";\n let created: Awaited<ReturnType<typeof createRemoteContainer>>;\n try {\n created = await withRegisteredMetadataSeed(\n state.locallyAcceptedMetadataUpdateIds,\n metadataSeedUpdate,\n () =>\n createRemoteContainer({\n systemSlot: containerState.container.systemSlot,\n containerId: containerState.container.id,\n ...(metadataSeedUpdate ? { metadataSeedUpdate } : {}),\n parentContainerId: parentState.container.id,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n runtime: state.runtime,\n stillCurrent: syncInput.isCurrent,\n }),\n );\n } catch (error) {\n if (error instanceof ContainerPathTooDeepError)\n return recordRefusedTooDeepCreate(syncInput);\n return recordContainerCreateFailure({\n error,\n isCurrent: syncInput.isCurrent,\n intent,\n organizationId: parentState.container.organizationId,\n state,\n });\n }\n if (!syncInput.isCurrent()) {\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return \"abandoned\";\n }\n try {\n return await settleRemoteContainerCreate({\n containerState,\n created,\n syncInput,\n });\n } catch (error) {\n if (!(error instanceof IncompleteContainerCreateSettlementError))\n throw error;\n return recordContainerCreateFailure({\n error,\n isCurrent: syncInput.isCurrent,\n intent,\n organizationId: parentState.container.organizationId,\n state,\n });\n }\n}\n\nasync function trySyncPendingContainerContentsContainerCreateIntent(\n input: ContainerCreateIntentSyncInput,\n): Promise<CreateIntentSyncResult> {\n const { intent, state } = input;\n if (!input.isCurrent()) {\n return \"abandoned\";\n }\n const containerState = state.containersById.get(intent.containerId);\n const parentState = state.containersById.get(intent.parentContainerId);\n\n if (!containerState || !parentState) {\n const execSql = state.runtime.infra.execSql;\n await state.persistence.recordCreateIntentRevisionError(execSql, {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: \"Container create intent references a missing local container\",\n stillCurrent: input.isCurrent,\n });\n return currentCreateResult(input.isCurrent, \"failed\");\n }\n\n if (typeof state.persistence.markCreateIntentRevisionSynced !== \"function\") {\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: \"Container create replay requires revision-CAS persistence\",\n stillCurrent: input.isCurrent,\n },\n );\n return currentCreateResult(input.isCurrent, \"failed\");\n }\n\n if (input.isRemoteSyncBlocked(parentState.container.organizationId)) {\n return \"blocked\";\n }\n\n if (hasRemoteContainerMetadataState(containerState)) {\n return syncListedContainerCreate({\n containerState,\n parentState,\n syncInput: input,\n });\n }\n\n // A parent whose own create has not settled may carry a listed identity\n // adoption has not verified, or has refused; nothing is created under it.\n if (\n !hasRemoteContainerMetadataState(parentState) ||\n input.isCreatePending(parentState.container.id)\n ) {\n return \"blocked\";\n }\n\n if (await deferTooDeepCreate(input)) {\n return currentCreateResult(input.isCurrent, \"blocked\");\n }\n\n return withPlannedMetadataDocumentId(\n state.plannedMetadataDocumentIds,\n containerState.container.id,\n () =>\n createPendingRemoteContainer({\n containerState,\n parentState,\n syncInput: input,\n }),\n );\n}\n\n/** A blocked create stays for a later round; only a created one settles. */\nfunction settleCreateIntentResult(\n result: CreateIntentSyncResult,\n containerId: string,\n remaining: Set<string>,\n unsettled: Set<string>,\n): boolean {\n if (result === \"blocked\") return false;\n remaining.delete(containerId);\n if (result !== \"created\") return false;\n unsettled.delete(containerId);\n return true;\n}\n\nexport async function syncPendingContainerCreateIntents(input: {\n host: ContainerCreateIntentSyncHost;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerCreateIntentSyncState;\n}): Promise<number> {\n if (!input.isCurrent()) {\n return 0;\n }\n const { host } = input;\n const state = { ...input.state };\n const execSql = state.runtime.infra.execSql;\n const pendingIntents =\n await state.persistence.listPendingCreateIntents(execSql);\n if (!input.isCurrent()) {\n return 0;\n }\n const remainingContainerIds = new Set(\n pendingIntents.map((intent) => intent.containerId),\n );\n // Only a create that settles in this pass leaves the pending set; a failed\n // or parked one stays pending even though this pass stops retrying it.\n const unsettledContainerIds = new Set(remainingContainerIds);\n let createdCount = 0;\n let progressed = true;\n\n while (progressed && input.isCurrent()) {\n progressed = false;\n\n for (const intent of pendingIntents) {\n if (!remainingContainerIds.has(intent.containerId)) {\n continue;\n }\n\n const result = await trySyncPendingContainerContentsContainerCreateIntent(\n {\n host,\n isCreatePending: (containerId) =>\n unsettledContainerIds.has(containerId),\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n intent,\n requestRemoteReconciliation: input.requestRemoteReconciliation,\n state,\n },\n );\n if (result === \"abandoned\") {\n return createdCount;\n }\n\n if (\n settleCreateIntentResult(\n result,\n intent.containerId,\n remainingContainerIds,\n unsettledContainerIds,\n )\n ) {\n progressed = true;\n createdCount += 1;\n }\n }\n }\n\n return createdCount;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ContainerPathTooDeepError } from "../../../../data/containers/shared/containerPathLimits.js";
|
|
2
|
-
import { reportAndRethrowKeyingVerificationError } from "../../../../data/keyingProjectionVerification/error.js";
|
|
3
2
|
import { errorMessage } from "../../../../data/shared/errorMessage.js";
|
|
3
|
+
import { reportAndRethrowKeyingVerificationError } from "../../../../data/shared/securityIncidents.js";
|
|
4
4
|
import { createDetachedContainerMetadataState, installDetachedContainerMetadataState, } from "../../metadata/metadataStateIsolation.js";
|
|
5
5
|
import { hasRemoteContainerMetadataState } from "../../remoteHydration/reconciliation.js";
|
|
6
6
|
import { moveRemoteContainer } from "../remote.js";
|