@tearleads/client-sdk 0.1.58 → 0.1.60
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.d.ts +17 -17
- package/Tearleads.js +15 -15
- package/Tearleads.js.map +1 -1
- package/client/{blobs.d.ts → blobs/index.d.ts} +1 -1
- package/client/{blobs.js → blobs/index.js} +3 -3
- package/client/blobs/index.js.map +1 -0
- package/client/{containerDocumentDiscovery.js → containerContents/documentDiscovery.js} +11 -11
- package/client/containerContents/documentDiscovery.js.map +1 -0
- package/client/{containerContents.d.ts → containerContents/index.d.ts} +13 -13
- package/client/{containerContents.js → containerContents/index.js} +18 -18
- package/client/containerContents/index.js.map +1 -0
- package/client/{containerContentsTypes.d.ts → containerContents/types.d.ts} +14 -14
- package/client/containerContents/types.js +2 -0
- package/client/containerContents/types.js.map +1 -0
- package/client/{deviceFirst.d.ts → deviceFirst/index.d.ts} +7 -7
- package/client/{deviceFirst.js → deviceFirst/index.js} +11 -11
- package/client/deviceFirst/index.js.map +1 -0
- package/client/{reconciledDocumentContentPull.js → deviceFirst/reconciledDocumentContentPull.js} +1 -1
- package/client/deviceFirst/reconciledDocumentContentPull.js.map +1 -0
- package/client/{documents.d.ts → documents/index.d.ts} +5 -5
- package/client/{documents.js → documents/index.js} +5 -5
- package/client/documents/index.js.map +1 -0
- package/client/{identity.d.ts → identity/index.d.ts} +2 -2
- package/client/{identity.js → identity/index.js} +5 -5
- package/client/identity/index.js.map +1 -0
- package/client/{identityKeyPackage.d.ts → identity/keyPackage.d.ts} +1 -1
- package/client/{identityKeyPackage.js → identity/keyPackage.js} +4 -4
- package/client/identity/keyPackage.js.map +1 -0
- package/client/{userIdentities.d.ts → identity/userIdentities.d.ts} +2 -2
- package/client/{userIdentities.js → identity/userIdentities.js} +4 -4
- package/client/identity/userIdentities.js.map +1 -0
- package/client/index.d.ts +18 -18
- package/client/index.js +9 -9
- package/client/index.js.map +1 -1
- package/client/organizations/currentPrincipalMutations.js.map +1 -1
- package/client/organizations/index.d.ts +2 -2
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationAccessRestoration.js.map +1 -1
- package/client/organizations/organizationDataUsage.d.ts +1 -1
- package/client/organizations/organizationDataUsage.js.map +1 -1
- package/client/organizations/organizationGroupNameHydration.js.map +1 -1
- package/client/organizations/organizationGroupPresentation.d.ts +1 -1
- package/client/organizations/organizationGroupPresentation.js.map +1 -1
- package/client/organizations/organizationMetadataProfileSync.js +1 -1
- package/client/organizations/organizationMetadataProfileSync.js.map +1 -1
- package/client/organizations/organizationReadModels.d.ts +1 -1
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
- package/client/organizations/organizationsTypes.d.ts +1 -1
- package/client/organizations/organizationsTypes.js.map +1 -1
- package/client/organizations/principalContainerMutations.js.map +1 -1
- package/client/organizations/principalMutationRecovery.d.ts +1 -1
- package/client/organizations/principalMutationRecovery.js.map +1 -1
- package/client/organizations/principalMutationScope.js.map +1 -1
- package/client/organizations/principalMutations.d.ts +2 -2
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/root/index.d.ts +1 -1
- package/client/root/index.js.map +1 -1
- package/client/{database.d.ts → runtime/database.d.ts} +1 -1
- package/client/{database.js → runtime/database.js} +1 -1
- package/client/runtime/database.js.map +1 -0
- package/client/{principalHistoryProtection.d.ts → runtime/principalHistoryProtection.d.ts} +1 -1
- package/client/{principalHistoryProtection.js → runtime/principalHistoryProtection.js} +2 -2
- package/client/runtime/principalHistoryProtection.js.map +1 -0
- package/client/{principalMutationApi.d.ts → runtime/principalMutationApi.d.ts} +4 -4
- package/client/{principalMutationApi.js → runtime/principalMutationApi.js} +2 -2
- package/client/runtime/principalMutationApi.js.map +1 -0
- package/client/{principalMutationDispatch.js → runtime/principalMutationDispatch.js} +2 -2
- package/client/runtime/principalMutationDispatch.js.map +1 -0
- package/client/runtime/rootContainerAdoption.js.map +1 -0
- package/client/{workflowRuntime.d.ts → runtime/workflowRuntime.d.ts} +12 -12
- package/client/{workflowRuntime.js → runtime/workflowRuntime.js} +5 -5
- package/client/runtime/workflowRuntime.js.map +1 -0
- package/client/{securityIncidents.d.ts → securityIncidents/index.d.ts} +3 -3
- package/client/{securityIncidents.js → securityIncidents/index.js} +5 -5
- package/client/securityIncidents/index.js.map +1 -0
- package/client/session/index.js +1 -1
- package/client/session/index.js.map +1 -1
- package/client/session/sessionIdentityTrust.d.ts +1 -1
- package/client/session/sessionLoginRefusal.js.map +1 -1
- package/client/session/sessionOrganizationCreation.js.map +1 -1
- package/client/session/sessionPurgeRecovery.js.map +1 -1
- package/client/session/sessionRootAuthority.js.map +1 -1
- package/client/session/sessionTypes.d.ts +3 -3
- package/client/session/sessionTypes.js.map +1 -1
- package/data/blobs/createBlobStore.d.ts +1 -1
- package/data/blobs/createBlobStore.js.map +1 -1
- package/data/blobs/encryptedBlobByteSource.js +1 -1
- package/data/blobs/encryptedBlobByteSource.js.map +1 -1
- package/data/blobs/encryptedBlobEnvelope.d.ts +1 -1
- package/data/blobs/encryptedBlobEnvelope.js +2 -2
- package/data/blobs/encryptedBlobEnvelope.js.map +1 -1
- package/data/blobs/encryptedBlobStore.d.ts +1 -1
- package/data/blobs/encryptedBlobStore.js +1 -1
- package/data/blobs/encryptedBlobStore.js.map +1 -1
- package/data/blobs/memoryBlobStore.d.ts +1 -1
- package/data/blobs/memoryBlobStore.js +1 -1
- package/data/blobs/memoryBlobStore.js.map +1 -1
- package/data/blobs/opfsBlobStore.d.ts +1 -1
- package/data/blobs/opfsBlobStore.js +1 -1
- package/data/blobs/opfsBlobStore.js.map +1 -1
- package/data/containers/containerMetadataDocument.js +1 -1
- package/data/containers/containerMetadataDocument.js.map +1 -1
- package/data/containers/shared/events.js +1 -1
- package/data/containers/shared/events.js.map +1 -1
- package/data/containers/shared/heldContainerHeads.js +1 -1
- package/data/containers/shared/heldContainerHeads.js.map +1 -1
- package/data/containers/shared/mutationAcknowledgement.js +1 -1
- package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
- package/data/containers/shared/principalPolicies.js +1 -1
- package/data/containers/shared/principalPolicies.js.map +1 -1
- package/data/containers/shared/readers.js +2 -2
- package/data/containers/shared/readers.js.map +1 -1
- package/data/documents/attachmentContentIdentity.js +1 -1
- package/data/documents/attachmentContentIdentity.js.map +1 -1
- package/data/documents/blob/shared/blobEnvelopeStream.js.map +1 -1
- package/data/documents/blob/shared/blobSourceSnapshot.d.ts +1 -1
- package/data/documents/blob/shared/blobSourceSnapshot.js.map +1 -1
- package/data/documents/blob/shared/chunkedBlobCrypto.js.map +1 -1
- package/data/documents/blob/shared/encryptedUploadParts.js.map +1 -1
- package/data/documents/blob/shared/events.js +1 -1
- package/data/documents/blob/shared/events.js.map +1 -1
- package/data/documents/blob/shared/types.d.ts +2 -2
- package/data/documents/blob/shared/types.js.map +1 -1
- package/data/documents/shared/containerKekPathHistory.js +1 -1
- package/data/documents/shared/containerKekPathHistory.js.map +1 -1
- package/data/documents/shared/containerKekPathVerification.d.ts +1 -1
- package/data/documents/shared/containerKekPathVerification.js +1 -1
- package/data/documents/shared/events.js +1 -1
- package/data/documents/shared/events.js.map +1 -1
- package/data/documents/shared/manifestBundleReaders.js +2 -2
- package/data/documents/shared/manifestBundleReaders.js.map +1 -1
- package/data/documents/shared/projection.d.ts +1 -1
- package/data/documents/shared/projection.js +2 -2
- package/data/documents/shared/projection.js.map +1 -1
- package/data/documents/shared/projectionContentKeys.d.ts +1 -1
- package/data/documents/shared/readers.js +3 -3
- package/data/documents/shared/readers.js.map +1 -1
- package/data/documents/shared/stableDocumentId.js +1 -1
- package/data/documents/shared/stableDocumentId.js.map +1 -1
- package/data/documents/shared/types.d.ts +1 -1
- package/data/documents/shared/types.js +1 -1
- package/data/{keyingCanonicalJson.js → keying/canonicalJson.js} +3 -3
- package/data/keying/canonicalJson.js.map +1 -0
- package/data/keyingProjectionVerification/bundleVerification.js +1 -1
- package/data/keyingProjectionVerification/bundleVerification.js.map +1 -1
- package/data/keyingProjectionVerification/containerAncestorCitations.js +1 -1
- package/data/keyingProjectionVerification/containerAncestorCitations.js.map +1 -1
- package/data/keyingProjectionVerification/containerManifestVerification.js +1 -1
- package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentManifestVerification.js +1 -1
- package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js +1 -1
- package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +1 -1
- package/data/keyingProjectionVerification/error.js +1 -1
- package/data/keyingProjectionVerification/error.js.map +1 -1
- package/data/keyingProjectionVerification/index.d.ts +9 -0
- package/data/{keyingProjectionVerification.js → keyingProjectionVerification/index.js} +8 -8
- package/data/keyingProjectionVerification/index.js.map +1 -0
- package/data/keyingProjectionVerification/principalPolicyCache.js +1 -1
- package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyVerification.js +1 -1
- package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/readers.d.ts +1 -1
- package/data/keyingProjectionVerification/readers.js +3 -3
- package/data/keyingProjectionVerification/readers.js.map +1 -1
- package/data/keyingProjectionVerification/userKeyResolver.d.ts +1 -1
- package/data/keyingProjectionVerification/userKeyResolver.js.map +1 -1
- package/data/persistence/containers/containerPersistence.js +1 -1
- package/data/persistence/containers/containerPersistence.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryCandidate.js +1 -1
- package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
- package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
- package/data/persistence/documents/internal/documentRows.js +1 -1
- package/data/persistence/documents/internal/documentRows.js.map +1 -1
- package/data/persistence/principalPolicyBundleIntegrity.js +1 -1
- package/data/persistence/principalPolicyBundleIntegrity.js.map +1 -1
- package/data/persistence/principalPolicyReferenceCheckpoint.js +1 -1
- package/data/persistence/principalPolicyReferenceCheckpoint.js.map +1 -1
- package/data/persistence/principalPolicyReferenceIndexPersistence.js +1 -1
- package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +1 -1
- package/data/persistence/principalPolicyReferencePersistence.js +1 -1
- package/data/persistence/principalPolicyReferencePersistence.js.map +1 -1
- package/data/persistence/securityIncidentPersistence.js.map +1 -1
- package/data/persistence/verifiedPrincipalPolicyBundle.js +1 -1
- package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
- package/data/persistence/verifiedPrincipalPolicyCurrent.js +1 -1
- package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -1
- package/data/principals/principalMutationJournal.js +1 -1
- package/data/principals/principalMutationJournal.js.map +1 -1
- package/data/{securityIncidents.d.ts → shared/securityIncidents.d.ts} +1 -1
- package/data/sqlite/documentRecordPersistence.js +1 -1
- package/data/sqlite/documentRecordPersistence.js.map +1 -1
- package/data/sync/crdtPeerSeed.d.ts +18 -0
- package/data/sync/originatedDocuments.d.ts +1 -1
- package/data/sync/originatedDocuments.js.map +1 -1
- package/data/sync/syncCoordinator.d.ts +1 -1
- package/data/sync/syncCoordinator.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/backgroundHydration.js +1 -1
- package/stores/container-contents/backgroundHydration.js.map +1 -1
- package/stores/container-contents/containerContentsStore.d.ts +1 -1
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/localRefresh.js +1 -1
- package/stores/container-contents/localRefresh.js.map +1 -1
- package/stores/container-contents/remoteContainerIngestion.js +1 -1
- package/stores/container-contents/remoteContainerIngestion.js.map +1 -1
- package/stores/container-contents/remoteWriteQueue.js +1 -1
- package/stores/container-contents/remoteWriteQueue.js.map +1 -1
- package/stores/container-contents/systemContainerHydration.js +1 -1
- package/stores/container-contents/systemContainerHydration.js.map +1 -1
- package/stores/container-contents/utils.js +1 -1
- package/stores/container-contents/utils.js.map +1 -1
- package/stores/documents/documentStore/attachmentIntents.js +1 -1
- package/stores/documents/documentStore/attachmentIntents.js.map +1 -1
- package/stores/documents/documentStore/attachmentSourceUpload.js.map +1 -1
- package/stores/documents/documentStore/attachmentStaging.js +1 -1
- package/stores/documents/documentStore/attachmentStaging.js.map +1 -1
- package/stores/documents/documentStore/attachmentUploadLane.js.map +1 -1
- package/stores/documents/documentStore/persistence.js +2 -2
- package/stores/documents/documentStore/persistence.js.map +1 -1
- package/stores/documents/documentStore/state.js +1 -1
- package/stores/documents/documentStore/state.js.map +1 -1
- package/stores/documents/documentStore/storedDocument.js +1 -1
- package/stores/documents/documentStore/storedDocument.js.map +1 -1
- package/stores/documents/documentStore/syncAttachments.js.map +1 -1
- package/stores/documents/documentStore.d.ts +1 -1
- package/stores/documents/documentStore.js.map +1 -1
- package/stores/documents/registry.d.ts +1 -1
- package/stores/documents/registry.js.map +1 -1
- package/stores/documents/types.d.ts +1 -1
- package/stores/documents/types.js.map +1 -1
- package/stores/local-projection/registry.d.ts +1 -1
- package/stores/local-projection/registry.js.map +1 -1
- package/sync/reconciliation/serviceTypes.d.ts +1 -1
- package/sync/reconciliation/serviceTypes.js.map +1 -1
- package/sync/reconciliation/triggers.d.ts +1 -1
- package/sync/reconciliation/triggers.js.map +1 -1
- package/workflows/blobs/attachmentBindingVerification.js +2 -2
- package/workflows/blobs/attachmentBindingVerification.js.map +1 -1
- package/workflows/blobs/blobChunkDecryption.js.map +1 -1
- package/workflows/blobs/decrypt.d.ts +1 -1
- package/workflows/blobs/decrypt.js +2 -2
- package/workflows/blobs/decrypt.js.map +1 -1
- package/workflows/blobs/detach.js +2 -2
- package/workflows/blobs/detach.js.map +1 -1
- package/workflows/blobs/hydrate.d.ts +3 -3
- package/workflows/blobs/hydrate.js +1 -1
- package/workflows/blobs/hydrate.js.map +1 -1
- package/workflows/blobs/hydrationResults.js.map +1 -1
- package/workflows/blobs/index.d.ts +2 -2
- package/workflows/blobs/index.js +1 -1
- package/workflows/blobs/index.js.map +1 -1
- package/workflows/blobs/multipartFirstParts.js.map +1 -1
- package/workflows/blobs/retainedAttachmentVerification.js +1 -1
- package/workflows/blobs/upload.js +3 -3
- package/workflows/blobs/upload.js.map +1 -1
- package/workflows/container-contents/container-state/createAdoption.js +1 -1
- package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
- package/workflows/container-contents/container-state/createChild.js +1 -1
- package/workflows/container-contents/container-state/createChild.js.map +1 -1
- package/workflows/container-contents/container-state/createIntentSync.js +1 -1
- package/workflows/container-contents/container-state/createIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/groupGrantVerification.js +1 -1
- package/workflows/container-contents/container-state/moveIntentSync.js +1 -1
- package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/purgeTreeScope.js +1 -1
- package/workflows/container-contents/container-state/purgeTreeScope.js.map +1 -1
- package/workflows/container-contents/container-state/share.js +1 -1
- package/workflows/container-contents/documentDiscoveryInputs.js +1 -1
- package/workflows/container-contents/documentDiscoveryInputs.js.map +1 -1
- package/workflows/container-contents/documentInfo.d.ts +1 -1
- package/workflows/container-contents/documentInfo.js.map +1 -1
- package/workflows/container-contents/documentLinks.d.ts +1 -1
- package/workflows/container-contents/documentLinks.js +1 -1
- package/workflows/container-contents/documentLinks.js.map +1 -1
- package/workflows/container-contents/documentMoveIntentSync.js +1 -1
- package/workflows/container-contents/documentMoveIntentSync.js.map +1 -1
- package/workflows/container-contents/documentPurge.d.ts +1 -1
- package/workflows/container-contents/documentPurge.js +1 -1
- package/workflows/container-contents/documentPurge.js.map +1 -1
- package/workflows/container-contents/documentQueries/rows.js +1 -1
- package/workflows/container-contents/documentQueries/rows.js.map +1 -1
- package/workflows/container-contents/metadata.d.ts +1 -1
- package/workflows/container-contents/metadataMutationPreparation.js +1 -1
- package/workflows/container-contents/metadataMutationPreparation.js.map +1 -1
- package/workflows/container-contents/metadataRemoteSync.d.ts +1 -1
- package/workflows/container-contents/metadataSyncErrors.js.map +1 -1
- package/workflows/container-contents/projectionKeys.d.ts +1 -1
- package/workflows/container-contents/syncLane.d.ts +1 -1
- package/workflows/container-contents/syncLane.js.map +1 -1
- package/workflows/containers/child/carriedDescendantRekeys.js +1 -1
- package/workflows/containers/child/create.d.ts +1 -1
- package/workflows/containers/child/create.js +2 -2
- package/workflows/containers/child/create.js.map +1 -1
- package/workflows/containers/child/createProjection.js +1 -1
- package/workflows/containers/child/createProjection.js.map +1 -1
- package/workflows/containers/child/createSubmission.d.ts +2 -2
- package/workflows/containers/child/createSubmission.js.map +1 -1
- package/workflows/containers/child/move.d.ts +2 -2
- package/workflows/containers/child/move.js +2 -2
- package/workflows/containers/child/move.js.map +1 -1
- package/workflows/containers/child/moveWraps.js +1 -1
- package/workflows/containers/child/mutationRequestCore.js +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/mutationSubmit.js.map +1 -1
- package/workflows/containers/child/recite.js.map +1 -1
- package/workflows/containers/child/recitePlan.js +1 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/child/rekey.d.ts +1 -1
- package/workflows/containers/child/rekey.js +2 -2
- package/workflows/containers/child/rekey.js.map +1 -1
- package/workflows/containers/child/rekeyProjection.js +1 -1
- package/workflows/containers/child/rekeyProjection.js.map +1 -1
- package/workflows/containers/child/rekeyRemote.d.ts +2 -2
- package/workflows/containers/child/rekeyRemote.js.map +1 -1
- package/workflows/containers/child/revoke.d.ts +2 -2
- package/workflows/containers/child/revoke.js +2 -2
- package/workflows/containers/child/revoke.js.map +1 -1
- package/workflows/containers/child/rotationPrincipalPolicies.js +1 -1
- package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
- package/workflows/containers/child/share.d.ts +2 -2
- package/workflows/containers/child/share.js +1 -1
- package/workflows/containers/child/share.js.map +1 -1
- package/workflows/containers/child/shareAncestorRepair.js.map +1 -1
- package/workflows/containers/child/shareMaterialization.d.ts +1 -1
- package/workflows/containers/child/sharePlanCore.d.ts +1 -1
- package/workflows/containers/child/sharePlanCore.js +1 -1
- package/workflows/containers/root/create.js +1 -1
- package/workflows/containers/root/create.js.map +1 -1
- package/workflows/containers/root/initialGroupPolicy.js +1 -1
- package/workflows/containers/root/initialGroupPolicy.js.map +1 -1
- package/workflows/documents/create.d.ts +1 -1
- package/workflows/documents/create.js +1 -1
- package/workflows/documents/documentMutationPreparation.js +1 -1
- package/workflows/documents/documentMutationPreparation.js.map +1 -1
- package/workflows/documents/historyContent.js +1 -1
- package/workflows/documents/historyContent.js.map +1 -1
- package/workflows/documents/linkSet.js +1 -1
- package/workflows/documents/linkSet.js.map +1 -1
- package/workflows/documents/linkSetAuthority.js +1 -1
- package/workflows/documents/linkSetBlobRewraps.js +2 -2
- package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
- package/workflows/documents/linkSetRemote.d.ts +1 -1
- package/workflows/documents/linkSetRemote.js +1 -1
- package/workflows/documents/orphanBlobReclaims.js +1 -1
- package/workflows/documents/orphanBlobReclaims.js.map +1 -1
- package/workflows/documents/projectionKeys.d.ts +1 -1
- package/workflows/documents/purge.d.ts +1 -1
- package/workflows/documents/purge.js +2 -2
- package/workflows/documents/purge.js.map +1 -1
- package/workflows/documents/readOnlySync.d.ts +1 -1
- package/workflows/documents/readOnlySync.js +1 -1
- package/workflows/documents/readOnlySync.js.map +1 -1
- package/workflows/documents/sync.js +1 -1
- package/workflows/documents/syncContainerRekeyPreparation.js +1 -1
- package/workflows/documents/syncLane.d.ts +1 -1
- package/workflows/documents/syncLane.js.map +1 -1
- package/workflows/documents/syncPlanIdentity.js +1 -1
- package/workflows/documents/syncPlanIdentity.js.map +1 -1
- package/workflows/documents/syncRepairAccess.js +1 -1
- package/workflows/documents/syncSubmittedResult.js +1 -1
- package/workflows/organizations/authoredPrincipalPolicyWarmer.js +1 -1
- package/workflows/organizations/authoredPrincipalPolicyWarmer.js.map +1 -1
- package/workflows/organizations/containerGrantRevocation.d.ts +2 -2
- package/workflows/organizations/containerGrantRevocation.js.map +1 -1
- package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
- package/workflows/organizations/currentPolicyMutationAcknowledgement.js +1 -1
- package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -1
- package/workflows/organizations/groupCreation.d.ts +1 -1
- package/workflows/organizations/groupCreation.js.map +1 -1
- package/workflows/organizations/groupMetadataAccess.d.ts +1 -1
- package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
- package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
- package/workflows/organizations/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -1
- package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
- package/workflows/organizations/groupPolicyRequests.js.map +1 -1
- package/workflows/organizations/loadPolicyHistoryDetails.js.map +1 -1
- package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/organizationProfile.js +1 -1
- package/workflows/organizations/organizationProfile.js.map +1 -1
- package/workflows/organizations/policyHistoryCache.js.map +1 -1
- package/workflows/organizations/principalContainerRematerialization.js +1 -1
- package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
- package/workflows/organizations/principalMutationJournalManagement.js +1 -1
- package/workflows/organizations/principalMutationJournalManagement.js.map +1 -1
- package/workflows/organizations/principalMutationReceipt.js +1 -1
- package/workflows/organizations/principalMutationReceipt.js.map +1 -1
- package/workflows/organizations/principalPolicy.d.ts +1 -1
- package/workflows/organizations/principalPolicy.js.map +1 -1
- package/workflows/organizations/principalPolicyReceiptArtifacts.js +1 -1
- package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -1
- package/workflows/organizations/rosterProfileContainer.js +1 -1
- package/workflows/organizations/rosterProfileContainer.js.map +1 -1
- package/workflows/principals/policyCache.d.ts +1 -1
- package/workflows/principals/policyCache.js +2 -2
- package/workflows/principals/policyCache.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
- package/workflows/principals/runtimePolicyWarmer.js +1 -1
- package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
- package/workflows/registration/persistRegistrationBootstrap.js +1 -1
- package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
- package/workflows/runtimeInput.d.ts +3 -3
- package/workflows/runtimeInput.js.map +1 -1
- package/workflows/sync/index.d.ts +2 -1
- package/workflows/sync/index.js +2 -1
- package/workflows/sync/index.js.map +1 -1
- package/client/blobs.js.map +0 -1
- package/client/containerContents.js.map +0 -1
- package/client/containerContentsTypes.js +0 -2
- package/client/containerContentsTypes.js.map +0 -1
- package/client/containerDocumentDiscovery.js.map +0 -1
- package/client/database.js.map +0 -1
- package/client/deviceFirst.js.map +0 -1
- package/client/documents.js.map +0 -1
- package/client/identity.js.map +0 -1
- package/client/identityKeyPackage.js.map +0 -1
- package/client/principalHistoryProtection.js.map +0 -1
- package/client/principalMutationApi.js.map +0 -1
- package/client/principalMutationDispatch.js.map +0 -1
- package/client/reconciledDocumentContentPull.js.map +0 -1
- package/client/rootContainerAdoption.js.map +0 -1
- package/client/securityIncidents.js.map +0 -1
- package/client/userIdentities.js.map +0 -1
- package/client/workflowRuntime.js.map +0 -1
- package/data/keyingCanonicalJson.js.map +0 -1
- package/data/keyingProjectionVerification.d.ts +0 -9
- package/data/keyingProjectionVerification.js.map +0 -1
- /package/client/{fileSaver.d.ts → host/fileSaver.d.ts} +0 -0
- /package/client/{fileSaver.js → host/fileSaver.js} +0 -0
- /package/client/{fileSaver.js.map → host/fileSaver.js.map} +0 -0
- /package/client/{logger.d.ts → host/logger.d.ts} +0 -0
- /package/client/{logger.js → host/logger.js} +0 -0
- /package/client/{logger.js.map → host/logger.js.map} +0 -0
- /package/client/{apiVersion.d.ts → runtime/apiVersion.d.ts} +0 -0
- /package/client/{apiVersion.js → runtime/apiVersion.js} +0 -0
- /package/client/{apiVersion.js.map → runtime/apiVersion.js.map} +0 -0
- /package/client/{events.d.ts → runtime/events.d.ts} +0 -0
- /package/client/{events.js → runtime/events.js} +0 -0
- /package/client/{events.js.map → runtime/events.js.map} +0 -0
- /package/client/{listenerSet.js → runtime/listenerSet.js} +0 -0
- /package/client/{listenerSet.js.map → runtime/listenerSet.js.map} +0 -0
- /package/client/{network.d.ts → runtime/network.d.ts} +0 -0
- /package/client/{network.js → runtime/network.js} +0 -0
- /package/client/{network.js.map → runtime/network.js.map} +0 -0
- /package/client/{principalMutationDeadline.js → runtime/principalMutationDeadline.js} +0 -0
- /package/client/{principalMutationDeadline.js.map → runtime/principalMutationDeadline.js.map} +0 -0
- /package/client/{rootContainerAdoption.js → runtime/rootContainerAdoption.js} +0 -0
- /package/client/{syncBillingGate.d.ts → runtime/syncBillingGate.d.ts} +0 -0
- /package/client/{syncBillingGate.js → runtime/syncBillingGate.js} +0 -0
- /package/client/{syncBillingGate.js.map → runtime/syncBillingGate.js.map} +0 -0
- /package/data/{blobContracts.d.ts → blobs/blobContracts.d.ts} +0 -0
- /package/data/{blobContracts.js → blobs/blobContracts.js} +0 -0
- /package/data/{blobContracts.js.map → blobs/blobContracts.js.map} +0 -0
- /package/data/{accessLevel.js → keying/accessLevel.js} +0 -0
- /package/data/{accessLevel.js.map → keying/accessLevel.js.map} +0 -0
- /package/data/{stableUuid.js → keying/stableUuid.js} +0 -0
- /package/data/{stableUuid.js.map → keying/stableUuid.js.map} +0 -0
- /package/data/{principalPolicyStates.js → principals/principalPolicyStates.js} +0 -0
- /package/data/{principalPolicyStates.js.map → principals/principalPolicyStates.js.map} +0 -0
- /package/data/{domainScope.d.ts → shared/domainScope.d.ts} +0 -0
- /package/data/{domainScope.js → shared/domainScope.js} +0 -0
- /package/data/{domainScope.js.map → shared/domainScope.js.map} +0 -0
- /package/data/{errorMessage.js → shared/errorMessage.js} +0 -0
- /package/data/{errorMessage.js.map → shared/errorMessage.js.map} +0 -0
- /package/data/{recordReaders.d.ts → shared/recordReaders.d.ts} +0 -0
- /package/data/{recordReaders.js → shared/recordReaders.js} +0 -0
- /package/data/{recordReaders.js.map → shared/recordReaders.js.map} +0 -0
- /package/data/{securityIncidents.js → shared/securityIncidents.js} +0 -0
- /package/data/{securityIncidents.js.map → shared/securityIncidents.js.map} +0 -0
- /package/data/{crdtPeerSeed.js → sync/crdtPeerSeed.js} +0 -0
- /package/data/{crdtPeerSeed.js.map → sync/crdtPeerSeed.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentSourceUpload.js","sourceRoot":"","sources":["attachmentSourceUpload.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"attachmentSourceUpload.js","sourceRoot":"","sources":["attachmentSourceUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,iBAAiB,GAClB,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAC3F,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AAGjF,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAEL,6BAA6B,GAC9B,MAAM,0BAA0B,CAAC;AAUlC,MAAM,UAAU,8BAA8B,CAC5C,KAAyB;IAEzB,OAAO,CACL,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,IAAI;QACxB,sBAAsB,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAC1C,CAAC,IAAI,EAAE,EAAE,CACP,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,iBAAiB,CAAC,MAAM;YAC9C,IAAI,CAAC,aAAa,KAAK,KAAK,CAAC,iBAAiB,CAAC,aAAa,CAC/D,CACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAyB;IAEzB,MAAM,E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AM,EAAE,QAAQ,EAAE,CAAC;QAC9B,CAAC;QACD,SAAS,GAAG,iBAAiB,CAAC;IAChC,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import {\n type BlobSourceSnapshot,\n inspectBlobSource,\n} from \"../../../data/documents/blob/shared/blobSourceSnapshot\";\nimport { DEFAULT_BLOB_CHUNK_SIZE_BYTES } from \"../../../data/documents/blob/shared/crypto\";\nimport { getDocumentAttachments } from \"../../../data/documents/documentContent\";\nimport type { BlobByteSource } from \"../../../workflows/blobs\";\nimport type { PendingAttachmentRecord } from \"../../../workflows/documents\";\nimport { deletePendingAttachment } from \"./attachmentPersistence\";\nimport {\n type AttachmentUploadResume,\n resolveAttachmentUploadResume,\n} from \"./attachmentUploadResume\";\nimport type { DocumentStoreState } from \"./state\";\nimport type { DocumentStoreSyncGeneration } from \"./syncGeneration\";\n\ninterface PendingSourceInput {\n attachmentGeneration: DocumentStoreSyncGeneration;\n pendingAttachment: PendingAttachmentRecord;\n state: DocumentStoreState;\n}\n\nexport function pendingAttachmentMatchesIntent(\n input: PendingSourceInput,\n): boolean {\n return (\n input.state.doc !== null &&\n getDocumentAttachments(input.state.doc).some(\n (item) =>\n item.slotId === input.pendingAttachment.slotId &&\n item.contentSha256 === input.pendingAttachment.contentSha256,\n )\n );\n}\n\nexport async function dropUnavailablePendingAttachment(\n input: PendingSourceInput,\n): Promise<\"dropped\"> {\n const { state, pendingAttachment, attachmentGeneration } = input;\n // Unusable bytes or superseded intent cannot be retried. Delete only this\n // storage identity so a concurrently queued replacement survives.\n state.runtime.util.log(\n `Documents: dropping pending attachment ${pendingAttachment.slotId}; its bytes are unavailable or changed, or its content intent was superseded.`,\n );\n await deletePendingAttachment(\n state,\n pendingAttachment.slotId,\n pendingAttachment.storageKey,\n attachmentGeneration,\n );\n return \"dropped\";\n}\n\nexport async function resolveAttachmentSourceUpload(\n input: PendingSourceInput & {\n source: BlobByteSource;\n },\n): Promise<{\n readonly resume: AttachmentUploadResume;\n readonly snapshot: BlobSourceSnapshot;\n} | null> {\n let chunkSize =\n input.pendingAttachment.upload?.partSize ?? DEFAULT_BLOB_CHUNK_SIZE_BYTES;\n\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const snapshot = await inspectBlobSource(input.source, chunkSize);\n if (!pendingAttachmentMatchesIntent(input)) return null;\n if (input.pendingAttachment.contentSha256 !== snapshot.sha256) {\n return null;\n }\n const resume = await resolveAttachmentUploadResume(\n input.state,\n input.pendingAttachment,\n snapshot.sha256,\n input.attachmentGeneration,\n );\n const resolvedChunkSize =\n resume.multipart?.partSize ?? DEFAULT_BLOB_CHUNK_SIZE_BYTES;\n if (!pendingAttachmentMatchesIntent(input)) return null;\n if (resolvedChunkSize === snapshot.chunkSize) {\n return { resume, snapshot };\n }\n chunkSize = resolvedChunkSize;\n }\n\n throw new Error(\"Blob source changed while preparing its upload identity\");\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createBlobByteSource } from "../../../
|
|
1
|
+
import { createBlobByteSource } from "../../../workflows/blobs/index.js";
|
|
2
2
|
import { runSerializedDocumentBlobMutation, runSerializedSqlMutation, } from "../../../workflows/documents/index.js";
|
|
3
3
|
import { assignLocalAttachmentSlots, upsertPendingAttachments, } from "./attachmentPersistence.js";
|
|
4
4
|
import { setReadySnapshot } from "./state.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentStaging.js","sourceRoot":"","sources":["attachmentStaging.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"attachmentStaging.js","sourceRoot":"","sources":["attachmentStaging.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAIL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,0BAA0B,E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2BAA2B,CAAC,EAAE,kBAAkB,EAAE,KAAK,EAAE,CAAC,CAAC;QACjE,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { createBlobByteSource } from \"../../../workflows/blobs\";\nimport {\n type AttachmentStagingRows,\n type LocalAttachmentRecord,\n type PendingAttachmentRecord,\n runSerializedDocumentBlobMutation,\n runSerializedSqlMutation,\n} from \"../../../workflows/documents\";\nimport type { DocumentAttachmentUpload } from \"../types\";\nimport {\n assignLocalAttachmentSlots,\n upsertPendingAttachments,\n} from \"./attachmentPersistence\";\nimport { type DocumentStoreState, setReadySnapshot } from \"./state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\ninterface StagePendingAttachmentsInput {\n files: ReadonlyArray<DocumentAttachmentUpload>;\n generation: DocumentStoreSyncGeneration;\n pendingAttachments: PendingAttachmentRecord[];\n state: DocumentStoreState;\n}\n\nfunction localAttachmentRecords(\n localId: string,\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>,\n): LocalAttachmentRecord[] {\n return pendingAttachments.map((pendingAttachment) => ({\n blobId: null,\n byteLength: pendingAttachment.byteLength,\n contentSha256: pendingAttachment.contentSha256,\n detachedAt: null,\n localId,\n mimeType: pendingAttachment.mimeType,\n slotId: pendingAttachment.slotId,\n storageKey: pendingAttachment.storageKey,\n }));\n}\n\nasync function deleteStagedAttachmentBytes(input: {\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n state: DocumentStoreState;\n}) {\n const { state } = input;\n const cleanupResults = await Promise.allSettled(\n input.pendingAttachments.map((attachment) =>\n state.runtime.infra.blobStore.deleteBytes(attachment.storageKey),\n ),\n );\n const failedCleanupCount = cleanupResults.filter(\n (result) => result.status === \"rejected\",\n ).length;\n if (failedCleanupCount > 0) {\n state.runtime.util.log(\n `Documents: failed to roll back ${failedCleanupCount} staged attachment operation${failedCleanupCount === 1 ? \"\" : \"s\"}.`,\n );\n }\n}\n\n/**\n * Roll back staged bytes that no committed row references. Like orphan\n * reclaim, check every held and pending reference under the key's lock: an\n * overlapping reset can leave a committed key referenced only by an upload.\n */\nexport async function deleteUnreferencedStagedAttachmentBytes(input: {\n generation: DocumentStoreSyncGeneration;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n state: DocumentStoreState;\n}): Promise<void> {\n const { execSql } = input.generation;\n const { state } = input;\n let failedCleanupCount = 0;\n for (const { storageKey } of input.pendingAttachments) {\n try {\n await runSerializedDocumentBlobMutation(execSql, storageKey, async () => {\n const referenced = await runSerializedSqlMutation(\n execSql,\n (lockedExecSql) =>\n state.persistence.orphanBlobs.isReferenced(\n lockedExecSql,\n storageKey,\n ),\n );\n if (!referenced)\n await state.runtime.infra.blobStore.deleteBytes(storageKey);\n });\n } catch {\n // A failed probe cannot prove that the atomic mutation rolled back, so\n // the bytes stay; a failed delete leaves them for a later sweep.\n failedCleanupCount += 1;\n }\n }\n if (failedCleanupCount > 0)\n state.runtime.util.log(\n `Documents: failed to roll back ${failedCleanupCount} staged attachment operation${failedCleanupCount === 1 ? \"\" : \"s\"}.`,\n );\n}\n\nasync function writePendingAttachmentBytes(\n input: StagePendingAttachmentsInput,\n): Promise<void> {\n for (const [index, pendingAttachment] of input.pendingAttachments.entries()) {\n const sourceFile = input.files[index];\n if (!sourceFile) continue;\n await input.state.runtime.infra.blobStore.writeByteSource(\n pendingAttachment.storageKey,\n createBlobByteSource(sourceFile.bytes),\n );\n }\n}\n\nexport function installPendingAttachmentRows(input: {\n localAttachments: ReadonlyArray<LocalAttachmentRecord>;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n state: DocumentStoreState;\n}): void {\n const { localAttachments, pendingAttachments, state } = input;\n assignLocalAttachmentSlots(state, localAttachments);\n upsertPendingAttachments(state, pendingAttachments);\n if (state.doc) {\n setReadySnapshot(\n state,\n state.doc,\n state.snapshot.syncing,\n state.snapshot.text,\n state.snapshot.structuredFields,\n );\n }\n}\n\nexport async function stagePendingAttachments(\n input: StagePendingAttachmentsInput,\n): Promise<AttachmentStagingRows | null> {\n const { pendingAttachments, state } = input;\n const localAttachments = localAttachmentRecords(\n state.localId,\n pendingAttachments,\n );\n\n try {\n await writePendingAttachmentBytes(input);\n\n if (!isDocumentStoreSyncGenerationCurrent(state, input.generation)) {\n await deleteStagedAttachmentBytes({ pendingAttachments, state });\n return null;\n }\n return { localAttachments, pendingAttachments };\n } catch (error) {\n await deleteStagedAttachmentBytes({ pendingAttachments, state });\n throw error;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentUploadLane.js","sourceRoot":"","sources":["attachmentUploadLane.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,yBAAyB,GAE1B,MAAM,yBAAyB,CAAC;AASjC,SAAS,4BAA4B,CAAC,IAA+B;IACnE,OAAO,IAAI,CAAC,CAAC,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,CAAC,mBAAmB,CAAC;AACvD,CAAC;AAED,SAAS,gCAAgC,CACvC,iBAA0C;IAE1C,OAAO,iBAAiB,CAAC,IAAI;QAC3B,CAAC,CAAC,GAAG,iBAAiB,CAAC,IAAI,UAAU,iBAAiB,CAAC,MAAM,GAAG;QAChE,CAAC,CAAC,QAAQ,iBAAiB,CAAC,MAAM,EAAE,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,iBAA0C,EAC1C,KAAc;IAEd,MAAM,KAAK,GAAG,IAAI,KAAK,CACrB,gCAAgC,gCAAgC,CAAC,iBAAiB,CAAC,GAAG,CACvF,CAAC;IACF,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IAE5D,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kCAAkC,CAAC,KAIlD;IACC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACzD,MAAM,OAAO,GAAuC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAEtE,MAAM,UAAU,GAAG,GAAmB,EAAE;QACtC,OAAO,CAAC,OAAO,KAAK,yBAAyB,CAC3C,WAAW,EACX,eAAe,MAAM,EAAE,EACvB;YACE,cAAc,EAAE,iBAAiB,CAAC,UAAU;YAC5C,KAAK,EAAE,4BAA4B,CAAC,iBAAiB,CAAC,IAAI,CAAC;SAC5D,CACF,CAAC;QACF,OAAO,OAAO,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC;IAEF,OAAO;QACL,QAAQ;YACN,oEAAoE;YACpE,8DAA8D;YAC9D,UAAU,EAAE,CAAC,QAAQ,EAAE,CAAC;QAC1B,CAAC;QACD,IAAI,CAAC,KAAc;YACjB,UAAU,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC3B,CAAC;QACD,aAAa,CAAC,KAAc;YAC1B,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QACD,mBAAmB,CAAC,QAAQ;YAC1B,UAAU,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;QACxC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../../data/domainScope\";\nimport type { MultipartUploadProgressListener } from \"../../../workflows/blobs\";\nimport type { PendingAttachmentRecord } from \"../../../workflows/documents\";\nimport {\n beginDomainSyncUploadLane,\n type UploadSyncLane,\n} from \"../../../workflows/sync\";\n\nexport interface AttachmentUploadLaneReporter {\n complete: () => void;\n fail: (error: unknown) => void;\n failIfStarted: (error: unknown) => void;\n onMultipartProgress: MultipartUploadProgressListener;\n}\n\nfunction getAttachmentUploadLaneLabel(name: string | null | undefined): string {\n return name ? `Upload ${name}` : \"Attachment upload\";\n}\n\nfunction getAttachmentUploadFailureTarget(\n pendingAttachment: PendingAttachmentRecord,\n): string {\n return pendingAttachment.name\n ? `${pendingAttachment.name} (slot ${pendingAttachment.slotId})`\n : `slot ${pendingAttachment.slotId}`;\n}\n\nexport function createAttachmentUploadFailedError(\n pendingAttachment: PendingAttachmentRecord,\n cause: unknown,\n): Error {\n const error = new Error(\n `Attachment upload failed for ${getAttachmentUploadFailureTarget(pendingAttachment)}.`,\n );\n if (cause !== undefined) Reflect.set(error, \"cause\", cause);\n\n return error;\n}\n\n/**\n * Surfaces attachment uploads as observational lanes. The persisted blob id is\n * the lane identity: slot ids repeat across documents, while a retry must keep\n * updating the same row. Lane creation stays lazy until progress, failure, or\n * completion so a billing block before any upload work does not add noise.\n */\nexport function createAttachmentUploadLaneReporter(input: {\n blobId: string;\n domainScope: DomainScope;\n pendingAttachment: PendingAttachmentRecord;\n}): AttachmentUploadLaneReporter {\n const { blobId, domainScope, pendingAttachment } = input;\n const laneRef: { current: UploadSyncLane | null } = { current: null };\n\n const ensureLane = (): UploadSyncLane => {\n laneRef.current ??= beginDomainSyncUploadLane(\n domainScope,\n `blob-upload:${blobId}`,\n {\n blobStorageKey: pendingAttachment.storageKey,\n label: getAttachmentUploadLaneLabel(pendingAttachment.name),\n },\n );\n return laneRef.current;\n };\n\n return {\n complete() {\n // Completion must create/re-begin the lane too: a resumed stage can\n // already be complete before it emits any per-part callbacks.\n ensureLane().complete();\n },\n fail(error: unknown) {\n ensureLane().fail(error);\n },\n failIfStarted(error: unknown) {\n laneRef.current?.fail(error);\n },\n onMultipartProgress(progress) {\n ensureLane().reportProgress(progress);\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"attachmentUploadLane.js","sourceRoot":"","sources":["attachmentUploadLane.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,yBAAyB,GAE1B,MAAM,yBAAyB,CAAC;AASjC,SAAS,4BAA4B,CAAC,IAA+B;IACnE,OAAO,IAAI,CAAC,CAAC,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,CAAC,mBAAmB,CAAC;AACvD,CAAC;AAED,SAAS,gCA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KAAK,CAAC,CAAC;QAC/B,CAAC;QACD,mBAAmB,CAAC,QAAQ;YAC1B,UAAU,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;QACxC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { MultipartUploadProgressListener } from \"../../../workflows/blobs\";\nimport type { PendingAttachmentRecord } from \"../../../workflows/documents\";\nimport {\n beginDomainSyncUploadLane,\n type UploadSyncLane,\n} from \"../../../workflows/sync\";\n\nexport interface AttachmentUploadLaneReporter {\n complete: () => void;\n fail: (error: unknown) => void;\n failIfStarted: (error: unknown) => void;\n onMultipartProgress: MultipartUploadProgressListener;\n}\n\nfunction getAttachmentUploadLaneLabel(name: string | null | undefined): string {\n return name ? `Upload ${name}` : \"Attachment upload\";\n}\n\nfunction getAttachmentUploadFailureTarget(\n pendingAttachment: PendingAttachmentRecord,\n): string {\n return pendingAttachment.name\n ? `${pendingAttachment.name} (slot ${pendingAttachment.slotId})`\n : `slot ${pendingAttachment.slotId}`;\n}\n\nexport function createAttachmentUploadFailedError(\n pendingAttachment: PendingAttachmentRecord,\n cause: unknown,\n): Error {\n const error = new Error(\n `Attachment upload failed for ${getAttachmentUploadFailureTarget(pendingAttachment)}.`,\n );\n if (cause !== undefined) Reflect.set(error, \"cause\", cause);\n\n return error;\n}\n\n/**\n * Surfaces attachment uploads as observational lanes. The persisted blob id is\n * the lane identity: slot ids repeat across documents, while a retry must keep\n * updating the same row. Lane creation stays lazy until progress, failure, or\n * completion so a billing block before any upload work does not add noise.\n */\nexport function createAttachmentUploadLaneReporter(input: {\n blobId: string;\n domainScope: DomainScope;\n pendingAttachment: PendingAttachmentRecord;\n}): AttachmentUploadLaneReporter {\n const { blobId, domainScope, pendingAttachment } = input;\n const laneRef: { current: UploadSyncLane | null } = { current: null };\n\n const ensureLane = (): UploadSyncLane => {\n laneRef.current ??= beginDomainSyncUploadLane(\n domainScope,\n `blob-upload:${blobId}`,\n {\n blobStorageKey: pendingAttachment.storageKey,\n label: getAttachmentUploadLaneLabel(pendingAttachment.name),\n },\n );\n return laneRef.current;\n };\n\n return {\n complete() {\n // Completion must create/re-begin the lane too: a resumed stage can\n // already be complete before it emits any per-part callbacks.\n ensureLane().complete();\n },\n fail(error: unknown) {\n ensureLane().fail(error);\n },\n failIfStarted(error: unknown) {\n laneRef.current?.fail(error);\n },\n onMultipartProgress(progress) {\n ensureLane().reportProgress(progress);\n },\n };\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { encodeVersionVector, exportUpdatesSince } from "../../../internal/loro/index.js";
|
|
2
|
-
import { normalizeEffectiveAccessLevel } from "../../../data/accessLevel.js";
|
|
3
2
|
import { DEFAULT_DOCUMENT_KIND } from "../../../data/documents/documentConstants.js";
|
|
4
3
|
import { projectStoredDocumentState, } from "../../../data/documents/documentKinds.js";
|
|
5
|
-
import {
|
|
4
|
+
import { normalizeEffectiveAccessLevel } from "../../../data/keying/accessLevel.js";
|
|
5
|
+
import { errorMessage } from "../../../data/shared/errorMessage.js";
|
|
6
6
|
import { enqueuePendingDocumentUpdate, listPendingDocumentUpdates, persistDocumentState, runSerializedSqlMutation, } from "../../../workflows/documents/index.js";
|
|
7
7
|
import { requestDocumentStoreSync } from "../registry.js";
|
|
8
8
|
import { maybeCompactDocumentHistory } from "./documentHistoryCompaction.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"persistence.js","sourceRoot":"","sources":["persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,0BAA0B,GAC3B,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC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I,CAAC,uBAAuB,CAAC,KAAK,EAAE,kBAAkB,CAAC,EAAE,CAAC;YACxD,OAAO;QACT,CAAC;QACD,MAAM,KAAK,CAAC,aAAa,CAAC,CAAC;QAC3B,GAAG,GAAG,IAAI,CAAC;IACb,CAAC,CACF,CAAC;IACF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAyB,EACzB,MAAkB,EAClB,mBAAmC,EACnC,kBAAgD;IAEhD,MAAM,kBAAkB,GAAG,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC;IACpD,MAAM,0BAA0B,GAAG,KAAK,CAAC,MAAM,EAAE,kBAAkB,IAAI,CAAC,CAAC;IACzE,IAAI,kBAAkB,KAAK,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,MAAM,GAAG,GAAG,MAAM,6BAA6B,CAC7C,KAAK,EACL,kBAAkB,EAClB,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,QAAQ,GAAG,MAAM,4BAA4B,CAAC;YAC5C,OAAO;YACP,kBAAkB;YAClB,0BAA0B;YAC1B,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,GAAG,CAAC,mBAAmB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC;YACrE,MAAM;SACP,CAAC,CAAC;IACL,CAAC,CACF,CAAC;IACF,OAAO,GAAG,IAAI,QAAQ,CAAC;AACzB,CAAC","sourcesContent":["import { encodeVersionVector, exportUpdatesSince } from \"@tearleads/loro\";\nimport { normalizeEffectiveAccessLevel } from \"../../../data/accessLevel\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n projectStoredDocumentState,\n} from \"../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { errorMessage } from \"../../../data/errorMessage\";\nimport {\n type DocumentRecord,\n type ExecSql,\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n type PendingUpdateRecord,\n persistDocumentState,\n runSerializedSqlMutation,\n} from \"../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport { maybeCompactDocumentHistory } from \"./documentHistoryCompaction\";\nimport {\n importDurableDocumentHistory,\n installDurableDocumentReload,\n} from \"./durableDocumentReload\";\nimport { runDocumentOrphanMaintenance } from \"./orphanMaintenance\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n markDocumentStoreRemoved,\n type PersistedDocumentRecord,\n type SaveDocumentRecordOptions,\n setReadySnapshot,\n} from \"./state\";\nimport { createFreshPeerStoredDocument } from \"./storedDocument\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport function documentSummaryFromRecord(\n record: DocumentRecord,\n updatedAt: string,\n documentProjectors: DocumentProjectorRegistry,\n): DocumentSummary {\n return {\n accessStateHash: record.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n record.effectiveAccessLevel,\n ),\n id: record.id,\n containerId: record.containerId,\n documentKind: record.documentKind ?? DEFAULT_DOCUMENT_KIND,\n documentId: record.documentId,\n title:\n record.title ??\n projectStoredDocumentState(\n {\n documentKind: record.documentKind ?? DEFAULT_DOCUMENT_KIND,\n structuredFields: {},\n text: record.text,\n },\n documentProjectors,\n ).title,\n updatedAt,\n };\n}\n\nfunction toPersistedDocumentRecord(\n persisted: NonNullable<Awaited<ReturnType<typeof persistDocumentState>>>,\n): PersistedDocumentRecord {\n const { record, updatedAt } = persisted;\n return {\n ...(persisted.creationSuperseded\n ? { creationSuperseded: true as const }\n : {}),\n historyRestoreState: persisted.historyRestoreState,\n ...(persisted.pullContinuationSuperseded\n ? { pullContinuationSuperseded: true as const }\n : {}),\n record,\n ...(persisted.syncIdentitySuperseded\n ? { syncIdentitySuperseded: true as const }\n : {}),\n ...(updatedAt !== undefined ? { updatedAt } : {}),\n };\n}\n\n// Nullable without a generation too: an update-persist refuses (returns\n// null) when the durable row was deleted while the persist was queued — the\n// resurrect guard in persistDocumentState — so callers must stop follow-up\n// state changes on null.\nexport async function saveDocumentRecord(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n patch: Partial<DocumentRecord> = {},\n options: SaveDocumentRecordOptions = {},\n expectedGeneration?: DocumentStoreSyncGeneration,\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<PersistedDocumentRecord | null> {\n const isCurrent = () =>\n (!expectedGeneration ||\n isSyncGenerationCurrent(state, expectedGeneration)) &&\n options.stillCurrent?.() !== false;\n const createsPlacement = state.record === null;\n const previousDocumentId = state.record?.documentId ?? null;\n const pendingBaseVersion =\n options.pendingBaseVersionOverride === undefined\n ? state.pendingBaseVersion\n : options.pendingBaseVersionOverride;\n const persistenceInput = {\n acceptedPendingUpdateIds: options.acceptedPendingUpdateIds,\n attachmentRemoval: options.attachmentRemoval,\n attachmentStaging: options.attachmentStaging,\n clearSyncFailure: options.clearSyncFailure,\n ...(commitSideEffect ? { commitSideEffect } : {}),\n containerId: state.runtime.state.containerId,\n currentDoc,\n currentRecord: state.record,\n documentProjectors: state.runtime.infra.documentProjectors,\n execSql: state.runtime.infra.execSql,\n expectedSyncState: options.expectedSyncState,\n historyCheckpoint: options.historyCheckpoint,\n historyUpdateOrigin: options.historyUpdateOrigin,\n historyUpdates: options.historyUpdates,\n pendingUpdate: options.pendingUpdate,\n localId: state.localId,\n // Persist the durable outgoing-delta marker with every snapshot write so a\n // restart restores it (see initializeDocumentStore). A device-first\n // deferRemoteSync write leaves it BEHIND the snapshot version on purpose;\n // capturing state.pendingBaseVersion here is what lets the next edit\n // re-derive that deferred op after a restart instead of dropping it.\n patch: { ...patch, pendingBaseVersion },\n persistence: state.persistence,\n };\n const persistedDocumentState =\n expectedGeneration || options.stillCurrent\n ? await persistDocumentState({\n ...persistenceInput,\n // persistDocumentState rechecks after its own pre-save awaits and then\n // immediately claims the executor mutation queue. A reset before that\n // point aborts; a reset afterward cannot let replacement writes overtake.\n canStartDurableMutation: isCurrent,\n })\n : await persistDocumentState(persistenceInput);\n if (!persistedDocumentState) {\n // With a stale generation the teardown that invalidated it owns the\n // state. With a current (or absent) generation, the refusal means the\n // durable row was deleted by ANOTHER subsystem while this persist was\n // queued (the resurrect guard): this store is a zombie — clear it so\n // callers that ignore the result stop advancing state or scheduling\n // sync against a document that no longer exists.\n if (isCurrent()) {\n markDocumentStoreRemoved(state);\n }\n void runDocumentOrphanMaintenance(state);\n return null;\n }\n const { record: nextRecord, updatedAt } = persistedDocumentState;\n if (!isCurrent()) {\n return null;\n }\n\n state.record = persistedDocumentState.record;\n state.pullContinuation = nextRecord.pullContinuation ?? null;\n if (persistedDocumentState.pullContinuationSuperseded) {\n state.pendingBaseVersion =\n nextRecord.pendingBaseVersion ?? nextRecord.snapshotEndVersion;\n }\n if (previousDocumentId !== nextRecord.documentId) {\n state.effects.registerDocumentIdentity(\n state.runtime.state.domainScope,\n nextRecord.id,\n nextRecord.documentId,\n );\n }\n if (updatedAt !== undefined) {\n state.effects.emitPersistedDocument(\n state.runtime.state.domainScope,\n documentSummaryFromRecord(\n nextRecord,\n updatedAt,\n state.runtime.infra.documentProjectors,\n ),\n createsPlacement ||\n Object.hasOwn(patch, \"containerId\") ||\n previousDocumentId !== nextRecord.documentId,\n );\n }\n return toPersistedDocumentRecord(persistedDocumentState);\n}\n\nasync function reloadSupersededDocumentState(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n historyRestoreState: PersistedDocumentRecord[\"historyRestoreState\"],\n previousDocumentId: string | null,\n durableRecord: DocumentRecord,\n): Promise<DocumentState | null> {\n if (historyRestoreState === undefined) {\n throw new Error(\"Superseded document state omitted its durable history\");\n }\n const replacementDoc = await createFreshPeerStoredDocument();\n importDurableDocumentHistory(replacementDoc, historyRestoreState);\n if (!isCurrent()) {\n return null;\n }\n installDurableDocumentReload({\n durableRecord,\n previousDocumentId,\n preserveQueuedWritesWhenIdentityMatches: true,\n registerIdentityChange: false,\n replacementDoc,\n state,\n });\n return replacementDoc;\n}\n\nexport async function persistDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n patch: Partial<DocumentRecord> = {},\n options: SaveDocumentRecordOptions = {},\n expectedGeneration?: DocumentStoreSyncGeneration,\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<PersistedDocumentRecord | null> {\n const isCurrent = () =>\n (!expectedGeneration ||\n isSyncGenerationCurrent(state, expectedGeneration)) &&\n options.stillCurrent?.() !== false;\n const previousDocumentId = state.record?.documentId ?? null;\n const persistedRecord = await saveDocumentRecord(\n state,\n currentDoc,\n patch,\n options,\n expectedGeneration,\n commitSideEffect,\n );\n return publishPersistedDocument(\n state,\n currentDoc,\n persistedRecord,\n previousDocumentId,\n options,\n isCurrent,\n );\n}\n\n/** Publish only after the durable claim succeeds and its live context remains. */\nexport async function publishPersistedDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n persistedRecord: PersistedDocumentRecord | null,\n previousDocumentId: string | null,\n options: SaveDocumentRecordOptions,\n isCurrent: () => boolean,\n): Promise<PersistedDocumentRecord | null> {\n if (!persistedRecord) return null;\n if (!isCurrent()) return null;\n\n if (\n persistedRecord.syncIdentitySuperseded ||\n persistedRecord.pullContinuationSuperseded\n ) {\n // Reload the winning durable checkpoint/tail on every CAS loss, including\n // another pane's history or security-context changes. A rejected sync\n // candidate remains isolated from the live document and editor.\n const replacementDoc = await reloadSupersededDocumentState(\n state,\n isCurrent,\n persistedRecord.historyRestoreState,\n previousDocumentId,\n persistedRecord.record,\n );\n if (!replacementDoc) return null;\n return persistedRecord;\n }\n\n setReadySnapshot(\n state,\n currentDoc,\n state.snapshot.syncing,\n options.preserveSnapshotText && !persistedRecord.pullContinuationSuperseded\n ? state.snapshot.text\n : persistedRecord.record.text,\n options.preserveSnapshotStructuredFields &&\n !persistedRecord.pullContinuationSuperseded\n ? state.snapshot.structuredFields\n : undefined,\n );\n // Compaction never fails the persist that triggered it: an unexpected\n // compaction error simply keeps the tail growing until a later pass\n // succeeds, and the content stays durable either way.\n try {\n await maybeCompactDocumentHistory(state, currentDoc, options.stillCurrent);\n } catch (error) {\n state.runtime.util.log(\n `Documents: history compaction skipped: ${errorMessage(error)}`,\n );\n }\n return persistedRecord;\n}\n\nexport async function listPendingUpdates(\n state: DocumentStoreState,\n): Promise<PendingUpdateRecord[]> {\n return listPendingDocumentUpdates({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n}\n\n/**\n * Export the outgoing delta for the current edit. The base is `pendingBaseVersion`\n * (the version through which ops are already durably enqueued or synced), NOT the\n * live doc version, so any delta orphaned by a prior failed enqueue is folded back\n * in here. In the success path the marker equals the pre-edit version, so this is\n * identical to exporting \"since the last edit\".\n *\n * Initialization sets `pendingBaseVersion` whenever it sets `doc`, and every\n * caller checks `doc` first, so the marker is non-null here. Assert that rather\n * than falling back to the live version: callers invoke this AFTER mutating the\n * doc, so a live-version fallback would export an empty (post-mutation) delta and\n * silently drop the edit.\n */\nexport function pendingDeltaSinceBase(\n state: DocumentStoreState,\n doc: DocumentState,\n): Uint8Array {\n if (state.pendingBaseVersion === null) {\n throw new Error(\n \"pendingDeltaSinceBase requires an initialized pendingBaseVersion\",\n );\n }\n return exportUpdatesSince(doc, state.pendingBaseVersion);\n}\n\n/**\n * Advance the durable marker to the doc's current version. Call this ONLY after\n * an edit's delta has been durably enqueued and persisted, or after remote\n * updates have been imported (those ops are already on the server).\n */\nexport function advancePendingBaseVersion(\n state: DocumentStoreState,\n doc: DocumentState,\n): void {\n state.pendingBaseVersion = encodeVersionVector(doc);\n // Every op through here is enqueued or remote, so a deferred birth is now\n // covered: lift its scheduled-sync hold and request the pass it skipped.\n if (state.deferInitialUpdate) {\n state.deferInitialUpdate = false;\n requestDocumentStoreSync(state);\n }\n}\n\n/**\n * Runs a durable write either ungated — no generation: the caller serializes\n * with teardown via the write-chain drain, and the persistence implementation\n * may legitimately park inside the write WITHOUT holding the global mutation\n * mutex — or inside the serialized mutation with an in-mutex currency check:\n * a teardown (reset/discard) that already ran was ordered strictly before the\n * mutation claim and invalidated the generation, so a stale caller can no\n * longer slip its write in after the teardown's wipe; a write that wins the\n * ordering instead lands before the teardown and is wiped by it. Returns\n * whether the write ran.\n */\nexport async function withGenerationGuardedMutation(\n state: DocumentStoreState,\n expectedGeneration: DocumentStoreSyncGeneration | undefined,\n write: (execSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n if (!expectedGeneration) {\n await write(state.runtime.infra.execSql);\n return true;\n }\n\n let ran = false;\n await runSerializedSqlMutation(\n state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (!isSyncGenerationCurrent(state, expectedGeneration)) {\n return;\n }\n await write(lockedExecSql);\n ran = true;\n },\n );\n return ran;\n}\n\nexport async function enqueuePendingUpdate(\n state: DocumentStoreState,\n update: Uint8Array,\n sourceVersionVector?: string | null,\n expectedGeneration?: DocumentStoreSyncGeneration,\n): Promise<boolean> {\n const expectedDocumentId = state.record?.documentId;\n const expectedRecoveryGeneration = state.record?.recoveryGeneration ?? 0;\n if (expectedDocumentId === undefined) {\n return false;\n }\n let enqueued = false;\n const ran = await withGenerationGuardedMutation(\n state,\n expectedGeneration,\n async (execSql) => {\n enqueued = await enqueuePendingDocumentUpdate({\n execSql,\n expectedDocumentId,\n expectedRecoveryGeneration,\n localId: state.localId,\n persistence: state.persistence,\n ...(sourceVersionVector === undefined ? {} : { sourceVersionVector }),\n update,\n });\n },\n );\n return ran && enqueued;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"persistence.js","sourceRoot":"","sources":["persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OA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["import { encodeVersionVector, exportUpdatesSince } from \"@tearleads/loro\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n projectStoredDocumentState,\n} from \"../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { normalizeEffectiveAccessLevel } from \"../../../data/keying/accessLevel\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type DocumentRecord,\n type ExecSql,\n enqueuePendingDocumentUpdate,\n listPendingDocumentUpdates,\n type PendingUpdateRecord,\n persistDocumentState,\n runSerializedSqlMutation,\n} from \"../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport { maybeCompactDocumentHistory } from \"./documentHistoryCompaction\";\nimport {\n importDurableDocumentHistory,\n installDurableDocumentReload,\n} from \"./durableDocumentReload\";\nimport { runDocumentOrphanMaintenance } from \"./orphanMaintenance\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n markDocumentStoreRemoved,\n type PersistedDocumentRecord,\n type SaveDocumentRecordOptions,\n setReadySnapshot,\n} from \"./state\";\nimport { createFreshPeerStoredDocument } from \"./storedDocument\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport function documentSummaryFromRecord(\n record: DocumentRecord,\n updatedAt: string,\n documentProjectors: DocumentProjectorRegistry,\n): DocumentSummary {\n return {\n accessStateHash: record.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n record.effectiveAccessLevel,\n ),\n id: record.id,\n containerId: record.containerId,\n documentKind: record.documentKind ?? DEFAULT_DOCUMENT_KIND,\n documentId: record.documentId,\n title:\n record.title ??\n projectStoredDocumentState(\n {\n documentKind: record.documentKind ?? DEFAULT_DOCUMENT_KIND,\n structuredFields: {},\n text: record.text,\n },\n documentProjectors,\n ).title,\n updatedAt,\n };\n}\n\nfunction toPersistedDocumentRecord(\n persisted: NonNullable<Awaited<ReturnType<typeof persistDocumentState>>>,\n): PersistedDocumentRecord {\n const { record, updatedAt } = persisted;\n return {\n ...(persisted.creationSuperseded\n ? { creationSuperseded: true as const }\n : {}),\n historyRestoreState: persisted.historyRestoreState,\n ...(persisted.pullContinuationSuperseded\n ? { pullContinuationSuperseded: true as const }\n : {}),\n record,\n ...(persisted.syncIdentitySuperseded\n ? { syncIdentitySuperseded: true as const }\n : {}),\n ...(updatedAt !== undefined ? { updatedAt } : {}),\n };\n}\n\n// Nullable without a generation too: an update-persist refuses (returns\n// null) when the durable row was deleted while the persist was queued — the\n// resurrect guard in persistDocumentState — so callers must stop follow-up\n// state changes on null.\nexport async function saveDocumentRecord(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n patch: Partial<DocumentRecord> = {},\n options: SaveDocumentRecordOptions = {},\n expectedGeneration?: DocumentStoreSyncGeneration,\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<PersistedDocumentRecord | null> {\n const isCurrent = () =>\n (!expectedGeneration ||\n isSyncGenerationCurrent(state, expectedGeneration)) &&\n options.stillCurrent?.() !== false;\n const createsPlacement = state.record === null;\n const previousDocumentId = state.record?.documentId ?? null;\n const pendingBaseVersion =\n options.pendingBaseVersionOverride === undefined\n ? state.pendingBaseVersion\n : options.pendingBaseVersionOverride;\n const persistenceInput = {\n acceptedPendingUpdateIds: options.acceptedPendingUpdateIds,\n attachmentRemoval: options.attachmentRemoval,\n attachmentStaging: options.attachmentStaging,\n clearSyncFailure: options.clearSyncFailure,\n ...(commitSideEffect ? { commitSideEffect } : {}),\n containerId: state.runtime.state.containerId,\n currentDoc,\n currentRecord: state.record,\n documentProjectors: state.runtime.infra.documentProjectors,\n execSql: state.runtime.infra.execSql,\n expectedSyncState: options.expectedSyncState,\n historyCheckpoint: options.historyCheckpoint,\n historyUpdateOrigin: options.historyUpdateOrigin,\n historyUpdates: options.historyUpdates,\n pendingUpdate: options.pendingUpdate,\n localId: state.localId,\n // Persist the durable outgoing-delta marker with every snapshot write so a\n // restart restores it (see initializeDocumentStore). A device-first\n // deferRemoteSync write leaves it BEHIND the snapshot version on purpose;\n // capturing state.pendingBaseVersion here is what lets the next edit\n // re-derive that deferred op after a restart instead of dropping it.\n patch: { ...patch, pendingBaseVersion },\n persistence: state.persistence,\n };\n const persistedDocumentState =\n expectedGeneration || options.stillCurrent\n ? await persistDocumentState({\n ...persistenceInput,\n // persistDocumentState rechecks after its own pre-save awaits and then\n // immediately claims the executor mutation queue. A reset before that\n // point aborts; a reset afterward cannot let replacement writes overtake.\n canStartDurableMutation: isCurrent,\n })\n : await persistDocumentState(persistenceInput);\n if (!persistedDocumentState) {\n // With a stale generation the teardown that invalidated it owns the\n // state. With a current (or absent) generation, the refusal means the\n // durable row was deleted by ANOTHER subsystem while this persist was\n // queued (the resurrect guard): this store is a zombie — clear it so\n // callers that ignore the result stop advancing state or scheduling\n // sync against a document that no longer exists.\n if (isCurrent()) {\n markDocumentStoreRemoved(state);\n }\n void runDocumentOrphanMaintenance(state);\n return null;\n }\n const { record: nextRecord, updatedAt } = persistedDocumentState;\n if (!isCurrent()) {\n return null;\n }\n\n state.record = persistedDocumentState.record;\n state.pullContinuation = nextRecord.pullContinuation ?? null;\n if (persistedDocumentState.pullContinuationSuperseded) {\n state.pendingBaseVersion =\n nextRecord.pendingBaseVersion ?? nextRecord.snapshotEndVersion;\n }\n if (previousDocumentId !== nextRecord.documentId) {\n state.effects.registerDocumentIdentity(\n state.runtime.state.domainScope,\n nextRecord.id,\n nextRecord.documentId,\n );\n }\n if (updatedAt !== undefined) {\n state.effects.emitPersistedDocument(\n state.runtime.state.domainScope,\n documentSummaryFromRecord(\n nextRecord,\n updatedAt,\n state.runtime.infra.documentProjectors,\n ),\n createsPlacement ||\n Object.hasOwn(patch, \"containerId\") ||\n previousDocumentId !== nextRecord.documentId,\n );\n }\n return toPersistedDocumentRecord(persistedDocumentState);\n}\n\nasync function reloadSupersededDocumentState(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n historyRestoreState: PersistedDocumentRecord[\"historyRestoreState\"],\n previousDocumentId: string | null,\n durableRecord: DocumentRecord,\n): Promise<DocumentState | null> {\n if (historyRestoreState === undefined) {\n throw new Error(\"Superseded document state omitted its durable history\");\n }\n const replacementDoc = await createFreshPeerStoredDocument();\n importDurableDocumentHistory(replacementDoc, historyRestoreState);\n if (!isCurrent()) {\n return null;\n }\n installDurableDocumentReload({\n durableRecord,\n previousDocumentId,\n preserveQueuedWritesWhenIdentityMatches: true,\n registerIdentityChange: false,\n replacementDoc,\n state,\n });\n return replacementDoc;\n}\n\nexport async function persistDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n patch: Partial<DocumentRecord> = {},\n options: SaveDocumentRecordOptions = {},\n expectedGeneration?: DocumentStoreSyncGeneration,\n commitSideEffect?: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<PersistedDocumentRecord | null> {\n const isCurrent = () =>\n (!expectedGeneration ||\n isSyncGenerationCurrent(state, expectedGeneration)) &&\n options.stillCurrent?.() !== false;\n const previousDocumentId = state.record?.documentId ?? null;\n const persistedRecord = await saveDocumentRecord(\n state,\n currentDoc,\n patch,\n options,\n expectedGeneration,\n commitSideEffect,\n );\n return publishPersistedDocument(\n state,\n currentDoc,\n persistedRecord,\n previousDocumentId,\n options,\n isCurrent,\n );\n}\n\n/** Publish only after the durable claim succeeds and its live context remains. */\nexport async function publishPersistedDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n persistedRecord: PersistedDocumentRecord | null,\n previousDocumentId: string | null,\n options: SaveDocumentRecordOptions,\n isCurrent: () => boolean,\n): Promise<PersistedDocumentRecord | null> {\n if (!persistedRecord) return null;\n if (!isCurrent()) return null;\n\n if (\n persistedRecord.syncIdentitySuperseded ||\n persistedRecord.pullContinuationSuperseded\n ) {\n // Reload the winning durable checkpoint/tail on every CAS loss, including\n // another pane's history or security-context changes. A rejected sync\n // candidate remains isolated from the live document and editor.\n const replacementDoc = await reloadSupersededDocumentState(\n state,\n isCurrent,\n persistedRecord.historyRestoreState,\n previousDocumentId,\n persistedRecord.record,\n );\n if (!replacementDoc) return null;\n return persistedRecord;\n }\n\n setReadySnapshot(\n state,\n currentDoc,\n state.snapshot.syncing,\n options.preserveSnapshotText && !persistedRecord.pullContinuationSuperseded\n ? state.snapshot.text\n : persistedRecord.record.text,\n options.preserveSnapshotStructuredFields &&\n !persistedRecord.pullContinuationSuperseded\n ? state.snapshot.structuredFields\n : undefined,\n );\n // Compaction never fails the persist that triggered it: an unexpected\n // compaction error simply keeps the tail growing until a later pass\n // succeeds, and the content stays durable either way.\n try {\n await maybeCompactDocumentHistory(state, currentDoc, options.stillCurrent);\n } catch (error) {\n state.runtime.util.log(\n `Documents: history compaction skipped: ${errorMessage(error)}`,\n );\n }\n return persistedRecord;\n}\n\nexport async function listPendingUpdates(\n state: DocumentStoreState,\n): Promise<PendingUpdateRecord[]> {\n return listPendingDocumentUpdates({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n}\n\n/**\n * Export the outgoing delta for the current edit. The base is `pendingBaseVersion`\n * (the version through which ops are already durably enqueued or synced), NOT the\n * live doc version, so any delta orphaned by a prior failed enqueue is folded back\n * in here. In the success path the marker equals the pre-edit version, so this is\n * identical to exporting \"since the last edit\".\n *\n * Initialization sets `pendingBaseVersion` whenever it sets `doc`, and every\n * caller checks `doc` first, so the marker is non-null here. Assert that rather\n * than falling back to the live version: callers invoke this AFTER mutating the\n * doc, so a live-version fallback would export an empty (post-mutation) delta and\n * silently drop the edit.\n */\nexport function pendingDeltaSinceBase(\n state: DocumentStoreState,\n doc: DocumentState,\n): Uint8Array {\n if (state.pendingBaseVersion === null) {\n throw new Error(\n \"pendingDeltaSinceBase requires an initialized pendingBaseVersion\",\n );\n }\n return exportUpdatesSince(doc, state.pendingBaseVersion);\n}\n\n/**\n * Advance the durable marker to the doc's current version. Call this ONLY after\n * an edit's delta has been durably enqueued and persisted, or after remote\n * updates have been imported (those ops are already on the server).\n */\nexport function advancePendingBaseVersion(\n state: DocumentStoreState,\n doc: DocumentState,\n): void {\n state.pendingBaseVersion = encodeVersionVector(doc);\n // Every op through here is enqueued or remote, so a deferred birth is now\n // covered: lift its scheduled-sync hold and request the pass it skipped.\n if (state.deferInitialUpdate) {\n state.deferInitialUpdate = false;\n requestDocumentStoreSync(state);\n }\n}\n\n/**\n * Runs a durable write either ungated — no generation: the caller serializes\n * with teardown via the write-chain drain, and the persistence implementation\n * may legitimately park inside the write WITHOUT holding the global mutation\n * mutex — or inside the serialized mutation with an in-mutex currency check:\n * a teardown (reset/discard) that already ran was ordered strictly before the\n * mutation claim and invalidated the generation, so a stale caller can no\n * longer slip its write in after the teardown's wipe; a write that wins the\n * ordering instead lands before the teardown and is wiped by it. Returns\n * whether the write ran.\n */\nexport async function withGenerationGuardedMutation(\n state: DocumentStoreState,\n expectedGeneration: DocumentStoreSyncGeneration | undefined,\n write: (execSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n if (!expectedGeneration) {\n await write(state.runtime.infra.execSql);\n return true;\n }\n\n let ran = false;\n await runSerializedSqlMutation(\n state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (!isSyncGenerationCurrent(state, expectedGeneration)) {\n return;\n }\n await write(lockedExecSql);\n ran = true;\n },\n );\n return ran;\n}\n\nexport async function enqueuePendingUpdate(\n state: DocumentStoreState,\n update: Uint8Array,\n sourceVersionVector?: string | null,\n expectedGeneration?: DocumentStoreSyncGeneration,\n): Promise<boolean> {\n const expectedDocumentId = state.record?.documentId;\n const expectedRecoveryGeneration = state.record?.recoveryGeneration ?? 0;\n if (expectedDocumentId === undefined) {\n return false;\n }\n let enqueued = false;\n const ran = await withGenerationGuardedMutation(\n state,\n expectedGeneration,\n async (execSql) => {\n enqueued = await enqueuePendingDocumentUpdate({\n execSql,\n expectedDocumentId,\n expectedRecoveryGeneration,\n localId: state.localId,\n persistence: state.persistence,\n ...(sourceVersionVector === undefined ? {} : { sourceVersionVector }),\n update,\n });\n },\n );\n return ran && enqueued;\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { canWriteEffectiveAccessLevel, normalizeEffectiveAccessLevel, } from "../../../data/accessLevel.js";
|
|
2
1
|
import { DEFAULT_DOCUMENT_KIND } from "../../../data/documents/documentConstants.js";
|
|
3
2
|
import { getDocumentAttachments, sameDocumentAttachments, } from "../../../data/documents/documentContent.js";
|
|
4
3
|
import { projectStoredDocumentState, readStoredDocumentState, } from "../../../data/documents/documentKinds.js";
|
|
5
4
|
import { listDocumentRows, sameDocumentRows, } from "../../../data/documents/documentRowList.js";
|
|
5
|
+
import { canWriteEffectiveAccessLevel, normalizeEffectiveAccessLevel, } from "../../../data/keying/accessLevel.js";
|
|
6
6
|
import { createDocumentProjectionUserKeyResolver, resolveDocumentCreateAuthor, } from "../../../workflows/documents/index.js";
|
|
7
7
|
import { getAttachmentStatuses, getAttachmentStorageKeys, } from "./attachmentSnapshot.js";
|
|
8
8
|
const EMPTY_DOCUMENT_SNAPSHOT = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,GAExB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,yCAAyC,CAAC;AAKjD,OAAO,EAGL,uCAAuC,EAOvC,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,sBAAsB,CAAC;AAgJ9B,MAAM,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K,CAAC;QAChC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC;QACjC,oBAAoB,EAAE,6BAA6B,CACjD,KAAK,CAAC,MAAM,EAAE,oBAAoB,CACnC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAyB,EACzB,QAAoB;IAEpB,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,OAAO,GAAG,EAAE,CAAC,KAAK,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { createDocument } from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n canWriteEffectiveAccessLevel,\n normalizeEffectiveAccessLevel,\n} from \"../../../data/accessLevel\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n sameDocumentAttachments,\n} from \"../../../data/documents/documentContent\";\nimport {\n projectStoredDocumentState,\n readStoredDocumentState,\n type StoredDocumentKind,\n} from \"../../../data/documents/documentKinds\";\nimport {\n type DocumentRow,\n listDocumentRows,\n sameDocumentRows,\n} from \"../../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../../data/documents/shared/syncPagination\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/types\";\nimport type { DomainScope } from \"../../../data/domainScope\";\nimport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionUserKeyResolver,\n type DocumentRecord,\n type DocumentSyncLane,\n type DocumentsPersistence,\n type PendingAttachmentRecord,\n type PendingUpdateInsert,\n resolveDocumentCreateAuthor,\n} from \"../../../workflows/documents\";\nimport type { DocumentSnapshot, DocumentsRuntime } from \"../types\";\nimport {\n getAttachmentStatuses,\n getAttachmentStorageKeys,\n} from \"./attachmentSnapshot\";\nexport type DocumentState = Awaited<ReturnType<typeof createDocument>>;\nexport type EncapsulationKeyPair = NonNullable<\n DocumentsRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n>;\nexport type DocumentAttachmentBinding = NonNullable<\n Awaited<ReturnType<DocumentsRuntime[\"apiClient\"][\"listDocumentAttachments\"]>>\n>[number];\nexport type PendingMutationSyncResult = {\n completed: boolean;\n nextRecord: DocumentRecord;\n};\nexport interface PersistedDocumentRecord {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: DocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\nexport interface SaveDocumentRecordOptions {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedSyncState?:\n | {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord;\n }\n | undefined;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: Omit<PendingUpdateInsert, \"localId\"> | undefined;\n pendingBaseVersionOverride?: string | null | undefined;\n preserveSnapshotStructuredFields?: boolean | undefined;\n preserveSnapshotText?: boolean | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\nexport interface DocumentSyncAttempt {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n outgoingUpdateCount: number;\n requestRecord: DocumentRecord;\n synced: SyncRemoteDocumentResult;\n /** `writerProjectionGeneration` when the request left; gates the install. */\n writerProjectionGeneration: number;\n}\nexport interface DocumentStorePersistenceEffects {\n emitPersistedDocument: (\n domainScope: DomainScope,\n persistedDocument: DocumentSummary,\n placementChanged?: boolean | undefined,\n ) => void;\n registerDocumentIdentity: (\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n ) => void;\n}\nexport interface DocumentStoreState {\n attachmentBlobIdBySlotId: Record<string, string | null>;\n /** Plaintext digest of the held bytes per slot; see `getAttachmentStatuses`. */\n attachmentContentSha256BySlotId: Record<string, string>;\n attachmentStorageKeyBySlotId: Record<string, string>;\n /** Creation's birth rides the first attach; see `deferredInitialUpdate.ts`. */\n deferInitialUpdate?: boolean;\n doc: DocumentState | null;\n effects: DocumentStorePersistenceEffects;\n initialDocumentId: string | null;\n initialDocumentKind: StoredDocumentKind;\n initialText: string;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n lastEventCount: number;\n /** Invalidates queued local-write closures when this store is cleared. */\n localWriteGeneration: number;\n locallyAcceptedUpdateIds: Set<string>;\n localId: string;\n listeners: Set<() => void>;\n pendingAttachments: PendingAttachmentRecord[];\n /**\n * Oplog version through which every op in `doc` is already durably enqueued as\n * a pending update or synced from a remote peer. It advances only after an\n * edit's enqueue+persist succeeds, so a later edit can recover any orphaned\n * delta left by a failed write instead of silently dropping it from sync.\n * `null` only before initialization sets it to the loaded doc's version.\n */\n pendingBaseVersion: string | null;\n /**\n * Local text/structured writes queued on `writeChain` but not yet drained.\n * While positive, sync MUST preserve the optimistic text/fields because `doc`\n * can lag the latest keystroke. Remote merges remain in `doc` and publish when\n * the final write settles.\n */\n pendingLocalWrites: number;\n persistence: DocumentsPersistence;\n /**\n * Durable continuation for a bounded remote pull, mirrored from the document\n * record so the live lane can advance it without re-reading SQLite.\n */\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord | null;\n /** Served bindings hydration refused for a held copy; see `hydrate.ts`. */\n rejectedServedAttachmentBindings: Set<string>;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything. Bounds the rekey-driven self re-arm so a server\n * that keeps conflicting fresh ids cannot drive a network-speed loop; see\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount: number;\n resolveProjectionUserKey: DocumentProjectionUserKeyResolver;\n /** Latest remote-update sequence durably applied by a completed probe. */\n remoteUpdateCompletedSignalSeq: number;\n /** A cancelled remote-only owner blocks late responses until fresh work. */\n remoteSyncBlocked: boolean;\n scheduleStartupRemoteSync: boolean;\n remoteUpdatePending: boolean;\n /** Sequence used to keep an older pass from clearing a newer remote event. */\n remoteUpdateSignalSeq: number;\n runtime: DocumentsRuntime;\n snapshot: DocumentSnapshot;\n syncLane: DocumentSyncLane | null;\n /** Parked behind another member's ancestor repair; a path hint re-runs. */\n awaitingAncestorRepair: boolean;\n writeChain: Promise<void>;\n writerProjection: DocumentWriterProjectionResponse | null;\n /**\n * Bumped whenever a realtime hint drops `writerProjection`; an operation that\n * fetched or was handed a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration: number;\n}\nconst EMPTY_DOCUMENT_SNAPSHOT: DocumentSnapshot = {\n attachments: [],\n attachmentStatusBySlotId: {},\n attachmentStorageKeyBySlotId: {},\n canAttach: false,\n canWrite: true,\n currentAuthorId: null,\n documentId: null,\n documentKind: DEFAULT_DOCUMENT_KIND,\n effectiveAccessLevel: \"admin\",\n fieldValidationIssues: [],\n ready: false,\n rows: [],\n structuredFields: {},\n text: \"\",\n title: \"\",\n syncing: false,\n};\nfunction shallowEqualRecord<Value>(\n left: Readonly<Record<string, Value>>,\n right: Readonly<Record<string, Value>>,\n): boolean {\n let leftKeyCount = 0;\n for (const key in left) {\n if (!Object.hasOwn(left, key)) continue;\n\n leftKeyCount += 1;\n if (!Object.hasOwn(right, key) || !Object.is(left[key], right[key])) {\n return false;\n }\n }\n\n let rightKeyCount = 0;\n for (const key in right) {\n if (Object.hasOwn(right, key)) {\n rightKeyCount += 1;\n }\n }\n\n return leftKeyCount === rightKeyCount;\n}\n\nfunction sameValidationIssues(\n left: DocumentSnapshot[\"fieldValidationIssues\"],\n right: DocumentSnapshot[\"fieldValidationIssues\"],\n): boolean {\n return (\n left.length === right.length &&\n left.every((issue, index) => {\n const nextIssue = right[index];\n return (\n nextIssue !== undefined &&\n issue.field === nextIssue.field &&\n issue.message === nextIssue.message &&\n Object.is(issue.value, nextIssue.value)\n );\n })\n );\n}\n\nexport function createDocumentStoreState(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n effects: DocumentStorePersistenceEffects,\n initialDocumentId: string | null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n scheduleStartupRemoteSync = true,\n): DocumentStoreState {\n return {\n attachmentBlobIdBySlotId: {},\n attachmentContentSha256BySlotId: {},\n attachmentStorageKeyBySlotId: {},\n doc: null,\n effects,\n initialDocumentId,\n initialDocumentKind,\n initialText,\n initializePromise: null,\n initialized: false,\n lastEventCount: 0,\n localWriteGeneration: 0,\n locallyAcceptedUpdateIds: new Set(),\n localId,\n listeners: new Set(),\n pendingAttachments: [],\n pendingBaseVersion: null,\n pendingLocalWrites: 0,\n persistence,\n pullContinuation: null,\n record: null,\n rejectedServedAttachmentBindings: new Set(),\n rekeyOnlyPassCount: 0,\n resolveProjectionUserKey:\n createDocumentProjectionUserKeyResolver(initialRuntime),\n remoteUpdateCompletedSignalSeq: 0,\n remoteSyncBlocked: !scheduleStartupRemoteSync,\n scheduleStartupRemoteSync,\n awaitingAncestorRepair: false,\n remoteUpdatePending: false,\n remoteUpdateSignalSeq: 0,\n runtime: initialRuntime,\n snapshot: { ...EMPTY_DOCUMENT_SNAPSHOT },\n syncLane: null,\n writeChain: Promise.resolve(),\n writerProjection: null,\n writerProjectionGeneration: 0,\n };\n}\n\nfunction emitDocumentStore(state: DocumentStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nexport function setDocumentSnapshot(\n state: DocumentStoreState,\n next: DocumentSnapshot,\n) {\n if (\n sameDocumentAttachments(state.snapshot.attachments, next.attachments) &&\n shallowEqualRecord(\n state.snapshot.attachmentStatusBySlotId,\n next.attachmentStatusBySlotId,\n ) &&\n shallowEqualRecord(\n state.snapshot.attachmentStorageKeyBySlotId,\n next.attachmentStorageKeyBySlotId,\n ) &&\n state.snapshot.canAttach === next.canAttach &&\n state.snapshot.canWrite === next.canWrite &&\n state.snapshot.currentAuthorId === next.currentAuthorId &&\n state.snapshot.documentId === next.documentId &&\n state.snapshot.documentKind === next.documentKind &&\n state.snapshot.effectiveAccessLevel === next.effectiveAccessLevel &&\n sameValidationIssues(\n state.snapshot.fieldValidationIssues,\n next.fieldValidationIssues,\n ) &&\n state.snapshot.ready === next.ready &&\n sameDocumentRows(state.snapshot.rows, next.rows) &&\n shallowEqualRecord(\n state.snapshot.structuredFields,\n next.structuredFields,\n ) &&\n state.snapshot.text === next.text &&\n state.snapshot.title === next.title &&\n state.snapshot.syncing === next.syncing\n ) {\n return;\n }\n\n state.snapshot = next;\n emitDocumentStore(state);\n}\n\nfunction clearDocumentStoreState(\n state: DocumentStoreState,\n { initialized }: { initialized: boolean },\n) {\n state.deferInitialUpdate = false;\n state.doc = null;\n state.localWriteGeneration += 1;\n state.record = null;\n state.pendingAttachments = [];\n state.pendingBaseVersion = null;\n state.pendingLocalWrites = 0;\n state.pullContinuation = null;\n state.attachmentBlobIdBySlotId = {};\n state.attachmentContentSha256BySlotId = {};\n state.attachmentStorageKeyBySlotId = {};\n state.locallyAcceptedUpdateIds = new Set();\n state.rejectedServedAttachmentBindings = new Set();\n state.remoteUpdateCompletedSignalSeq = 0;\n state.remoteSyncBlocked = !state.scheduleStartupRemoteSync;\n state.awaitingAncestorRepair = false;\n state.remoteUpdatePending = false;\n state.remoteUpdateSignalSeq = 0;\n state.writerProjection = null;\n state.initialized = initialized;\n state.initializePromise = null;\n state.writeChain = Promise.resolve();\n setDocumentSnapshot(state, { ...EMPTY_DOCUMENT_SNAPSHOT });\n}\n\nexport function resetDocumentStore(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: false });\n}\n\nexport function markDocumentStoreRemoved(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: true });\n}\n\nexport function canAttachFiles(state: DocumentStoreState): boolean {\n return (\n canWriteDocument(state) &&\n state.runtime.infra.dbStatus === \"ready\" &&\n !!state.runtime.crypto.encapsulationKeyPair\n );\n}\n\nexport function canWriteDocument(state: DocumentStoreState): boolean {\n return canWriteEffectiveAccessLevel(state.record?.effectiveAccessLevel);\n}\n\nfunction getSnapshotAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentAttachment[] {\n return currentDoc ? getDocumentAttachments(currentDoc) : [];\n}\n\nfunction getSnapshotRows(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentRow[] {\n return currentDoc ? listDocumentRows(currentDoc) : [];\n}\n\nfunction resolveCurrentAuthorId(state: DocumentStoreState): string | null {\n return resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? null;\n}\n\nexport function setReadySnapshot(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n syncing: boolean,\n textOverride?: string,\n structuredFieldsOverride?: DocumentSnapshot[\"structuredFields\"],\n) {\n const attachments = getSnapshotAttachments(state, currentDoc);\n const rows = getSnapshotRows(state, currentDoc);\n const documentState = readStoredDocumentState(\n currentDoc,\n state.runtime.infra.documentProjectors,\n );\n const text = textOverride ?? documentState.text;\n const structuredFields =\n structuredFieldsOverride ?? documentState.structuredFields;\n const projectedState =\n textOverride === undefined && structuredFieldsOverride === undefined\n ? documentState\n : projectStoredDocumentState(\n {\n documentKind: documentState.documentKind,\n structuredFields,\n text,\n rows: rows.map((row) => ({ id: row.id, fields: row.fields })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n attachments,\n attachmentStatusBySlotId: getAttachmentStatuses({\n attachments,\n contentSha256BySlotId: state.attachmentContentSha256BySlotId,\n pendingSlotIds: new Set(\n state.pendingAttachments.map((attachment) => attachment.slotId),\n ),\n }),\n attachmentStorageKeyBySlotId: getAttachmentStorageKeys(\n state.attachmentStorageKeyBySlotId,\n attachments,\n ),\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n currentAuthorId: resolveCurrentAuthorId(state),\n documentId: state.record?.documentId ?? null,\n documentKind: projectedState.documentKind,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n fieldValidationIssues: projectedState.fieldValidationIssues,\n ready: true,\n rows,\n structuredFields: projectedState.structuredFields,\n text,\n title: projectedState.title,\n syncing,\n });\n}\n\nexport function setDocumentSyncing(\n state: DocumentStoreState,\n syncing: boolean,\n) {\n setDocumentSnapshot(state, { ...state.snapshot, syncing });\n}\n\nexport function refreshAttachabilitySnapshot(state: DocumentStoreState) {\n if (!state.snapshot.ready) {\n return;\n }\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n });\n}\n\nexport function subscribeToDocumentStore(\n state: DocumentStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => void state.listeners.delete(listener);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,GAExB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAGL,uCAAuC,EAOvC,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAEtC,OA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K,EAAE;QACzB,GAAG,KAAK,CAAC,QAAQ;QACjB,SAAS,EAAE,cAAc,CAAC,KAAK,CAAC;QAChC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC;QACjC,oBAAoB,EAAE,6BAA6B,CACjD,KAAK,CAAC,MAAM,EAAE,oBAAoB,CACnC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAyB,EACzB,QAAoB;IAEpB,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,OAAO,GAAG,EAAE,CAAC,KAAK,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { createDocument } from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n sameDocumentAttachments,\n} from \"../../../data/documents/documentContent\";\nimport {\n projectStoredDocumentState,\n readStoredDocumentState,\n type StoredDocumentKind,\n} from \"../../../data/documents/documentKinds\";\nimport {\n type DocumentRow,\n listDocumentRows,\n sameDocumentRows,\n} from \"../../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../../data/documents/shared/syncPagination\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/types\";\nimport {\n canWriteEffectiveAccessLevel,\n normalizeEffectiveAccessLevel,\n} from \"../../../data/keying/accessLevel\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionUserKeyResolver,\n type DocumentRecord,\n type DocumentSyncLane,\n type DocumentsPersistence,\n type PendingAttachmentRecord,\n type PendingUpdateInsert,\n resolveDocumentCreateAuthor,\n} from \"../../../workflows/documents\";\nimport type { DocumentSnapshot, DocumentsRuntime } from \"../types\";\nimport {\n getAttachmentStatuses,\n getAttachmentStorageKeys,\n} from \"./attachmentSnapshot\";\nexport type DocumentState = Awaited<ReturnType<typeof createDocument>>;\nexport type EncapsulationKeyPair = NonNullable<\n DocumentsRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n>;\nexport type DocumentAttachmentBinding = NonNullable<\n Awaited<ReturnType<DocumentsRuntime[\"apiClient\"][\"listDocumentAttachments\"]>>\n>[number];\nexport type PendingMutationSyncResult = {\n completed: boolean;\n nextRecord: DocumentRecord;\n};\nexport interface PersistedDocumentRecord {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: DocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\nexport interface SaveDocumentRecordOptions {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedSyncState?:\n | {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord;\n }\n | undefined;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: Omit<PendingUpdateInsert, \"localId\"> | undefined;\n pendingBaseVersionOverride?: string | null | undefined;\n preserveSnapshotStructuredFields?: boolean | undefined;\n preserveSnapshotText?: boolean | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\nexport interface DocumentSyncAttempt {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n outgoingUpdateCount: number;\n requestRecord: DocumentRecord;\n synced: SyncRemoteDocumentResult;\n /** `writerProjectionGeneration` when the request left; gates the install. */\n writerProjectionGeneration: number;\n}\nexport interface DocumentStorePersistenceEffects {\n emitPersistedDocument: (\n domainScope: DomainScope,\n persistedDocument: DocumentSummary,\n placementChanged?: boolean | undefined,\n ) => void;\n registerDocumentIdentity: (\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n ) => void;\n}\nexport interface DocumentStoreState {\n attachmentBlobIdBySlotId: Record<string, string | null>;\n /** Plaintext digest of the held bytes per slot; see `getAttachmentStatuses`. */\n attachmentContentSha256BySlotId: Record<string, string>;\n attachmentStorageKeyBySlotId: Record<string, string>;\n /** Creation's birth rides the first attach; see `deferredInitialUpdate.ts`. */\n deferInitialUpdate?: boolean;\n doc: DocumentState | null;\n effects: DocumentStorePersistenceEffects;\n initialDocumentId: string | null;\n initialDocumentKind: StoredDocumentKind;\n initialText: string;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n lastEventCount: number;\n /** Invalidates queued local-write closures when this store is cleared. */\n localWriteGeneration: number;\n locallyAcceptedUpdateIds: Set<string>;\n localId: string;\n listeners: Set<() => void>;\n pendingAttachments: PendingAttachmentRecord[];\n /**\n * Oplog version through which every op in `doc` is already durably enqueued as\n * a pending update or synced from a remote peer. It advances only after an\n * edit's enqueue+persist succeeds, so a later edit can recover any orphaned\n * delta left by a failed write instead of silently dropping it from sync.\n * `null` only before initialization sets it to the loaded doc's version.\n */\n pendingBaseVersion: string | null;\n /**\n * Local text/structured writes queued on `writeChain` but not yet drained.\n * While positive, sync MUST preserve the optimistic text/fields because `doc`\n * can lag the latest keystroke. Remote merges remain in `doc` and publish when\n * the final write settles.\n */\n pendingLocalWrites: number;\n persistence: DocumentsPersistence;\n /**\n * Durable continuation for a bounded remote pull, mirrored from the document\n * record so the live lane can advance it without re-reading SQLite.\n */\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord | null;\n /** Served bindings hydration refused for a held copy; see `hydrate.ts`. */\n rejectedServedAttachmentBindings: Set<string>;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything. Bounds the rekey-driven self re-arm so a server\n * that keeps conflicting fresh ids cannot drive a network-speed loop; see\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount: number;\n resolveProjectionUserKey: DocumentProjectionUserKeyResolver;\n /** Latest remote-update sequence durably applied by a completed probe. */\n remoteUpdateCompletedSignalSeq: number;\n /** A cancelled remote-only owner blocks late responses until fresh work. */\n remoteSyncBlocked: boolean;\n scheduleStartupRemoteSync: boolean;\n remoteUpdatePending: boolean;\n /** Sequence used to keep an older pass from clearing a newer remote event. */\n remoteUpdateSignalSeq: number;\n runtime: DocumentsRuntime;\n snapshot: DocumentSnapshot;\n syncLane: DocumentSyncLane | null;\n /** Parked behind another member's ancestor repair; a path hint re-runs. */\n awaitingAncestorRepair: boolean;\n writeChain: Promise<void>;\n writerProjection: DocumentWriterProjectionResponse | null;\n /**\n * Bumped whenever a realtime hint drops `writerProjection`; an operation that\n * fetched or was handed a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration: number;\n}\nconst EMPTY_DOCUMENT_SNAPSHOT: DocumentSnapshot = {\n attachments: [],\n attachmentStatusBySlotId: {},\n attachmentStorageKeyBySlotId: {},\n canAttach: false,\n canWrite: true,\n currentAuthorId: null,\n documentId: null,\n documentKind: DEFAULT_DOCUMENT_KIND,\n effectiveAccessLevel: \"admin\",\n fieldValidationIssues: [],\n ready: false,\n rows: [],\n structuredFields: {},\n text: \"\",\n title: \"\",\n syncing: false,\n};\nfunction shallowEqualRecord<Value>(\n left: Readonly<Record<string, Value>>,\n right: Readonly<Record<string, Value>>,\n): boolean {\n let leftKeyCount = 0;\n for (const key in left) {\n if (!Object.hasOwn(left, key)) continue;\n\n leftKeyCount += 1;\n if (!Object.hasOwn(right, key) || !Object.is(left[key], right[key])) {\n return false;\n }\n }\n\n let rightKeyCount = 0;\n for (const key in right) {\n if (Object.hasOwn(right, key)) {\n rightKeyCount += 1;\n }\n }\n\n return leftKeyCount === rightKeyCount;\n}\n\nfunction sameValidationIssues(\n left: DocumentSnapshot[\"fieldValidationIssues\"],\n right: DocumentSnapshot[\"fieldValidationIssues\"],\n): boolean {\n return (\n left.length === right.length &&\n left.every((issue, index) => {\n const nextIssue = right[index];\n return (\n nextIssue !== undefined &&\n issue.field === nextIssue.field &&\n issue.message === nextIssue.message &&\n Object.is(issue.value, nextIssue.value)\n );\n })\n );\n}\n\nexport function createDocumentStoreState(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n effects: DocumentStorePersistenceEffects,\n initialDocumentId: string | null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n scheduleStartupRemoteSync = true,\n): DocumentStoreState {\n return {\n attachmentBlobIdBySlotId: {},\n attachmentContentSha256BySlotId: {},\n attachmentStorageKeyBySlotId: {},\n doc: null,\n effects,\n initialDocumentId,\n initialDocumentKind,\n initialText,\n initializePromise: null,\n initialized: false,\n lastEventCount: 0,\n localWriteGeneration: 0,\n locallyAcceptedUpdateIds: new Set(),\n localId,\n listeners: new Set(),\n pendingAttachments: [],\n pendingBaseVersion: null,\n pendingLocalWrites: 0,\n persistence,\n pullContinuation: null,\n record: null,\n rejectedServedAttachmentBindings: new Set(),\n rekeyOnlyPassCount: 0,\n resolveProjectionUserKey:\n createDocumentProjectionUserKeyResolver(initialRuntime),\n remoteUpdateCompletedSignalSeq: 0,\n remoteSyncBlocked: !scheduleStartupRemoteSync,\n scheduleStartupRemoteSync,\n awaitingAncestorRepair: false,\n remoteUpdatePending: false,\n remoteUpdateSignalSeq: 0,\n runtime: initialRuntime,\n snapshot: { ...EMPTY_DOCUMENT_SNAPSHOT },\n syncLane: null,\n writeChain: Promise.resolve(),\n writerProjection: null,\n writerProjectionGeneration: 0,\n };\n}\n\nfunction emitDocumentStore(state: DocumentStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nexport function setDocumentSnapshot(\n state: DocumentStoreState,\n next: DocumentSnapshot,\n) {\n if (\n sameDocumentAttachments(state.snapshot.attachments, next.attachments) &&\n shallowEqualRecord(\n state.snapshot.attachmentStatusBySlotId,\n next.attachmentStatusBySlotId,\n ) &&\n shallowEqualRecord(\n state.snapshot.attachmentStorageKeyBySlotId,\n next.attachmentStorageKeyBySlotId,\n ) &&\n state.snapshot.canAttach === next.canAttach &&\n state.snapshot.canWrite === next.canWrite &&\n state.snapshot.currentAuthorId === next.currentAuthorId &&\n state.snapshot.documentId === next.documentId &&\n state.snapshot.documentKind === next.documentKind &&\n state.snapshot.effectiveAccessLevel === next.effectiveAccessLevel &&\n sameValidationIssues(\n state.snapshot.fieldValidationIssues,\n next.fieldValidationIssues,\n ) &&\n state.snapshot.ready === next.ready &&\n sameDocumentRows(state.snapshot.rows, next.rows) &&\n shallowEqualRecord(\n state.snapshot.structuredFields,\n next.structuredFields,\n ) &&\n state.snapshot.text === next.text &&\n state.snapshot.title === next.title &&\n state.snapshot.syncing === next.syncing\n ) {\n return;\n }\n\n state.snapshot = next;\n emitDocumentStore(state);\n}\n\nfunction clearDocumentStoreState(\n state: DocumentStoreState,\n { initialized }: { initialized: boolean },\n) {\n state.deferInitialUpdate = false;\n state.doc = null;\n state.localWriteGeneration += 1;\n state.record = null;\n state.pendingAttachments = [];\n state.pendingBaseVersion = null;\n state.pendingLocalWrites = 0;\n state.pullContinuation = null;\n state.attachmentBlobIdBySlotId = {};\n state.attachmentContentSha256BySlotId = {};\n state.attachmentStorageKeyBySlotId = {};\n state.locallyAcceptedUpdateIds = new Set();\n state.rejectedServedAttachmentBindings = new Set();\n state.remoteUpdateCompletedSignalSeq = 0;\n state.remoteSyncBlocked = !state.scheduleStartupRemoteSync;\n state.awaitingAncestorRepair = false;\n state.remoteUpdatePending = false;\n state.remoteUpdateSignalSeq = 0;\n state.writerProjection = null;\n state.initialized = initialized;\n state.initializePromise = null;\n state.writeChain = Promise.resolve();\n setDocumentSnapshot(state, { ...EMPTY_DOCUMENT_SNAPSHOT });\n}\n\nexport function resetDocumentStore(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: false });\n}\n\nexport function markDocumentStoreRemoved(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: true });\n}\n\nexport function canAttachFiles(state: DocumentStoreState): boolean {\n return (\n canWriteDocument(state) &&\n state.runtime.infra.dbStatus === \"ready\" &&\n !!state.runtime.crypto.encapsulationKeyPair\n );\n}\n\nexport function canWriteDocument(state: DocumentStoreState): boolean {\n return canWriteEffectiveAccessLevel(state.record?.effectiveAccessLevel);\n}\n\nfunction getSnapshotAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentAttachment[] {\n return currentDoc ? getDocumentAttachments(currentDoc) : [];\n}\n\nfunction getSnapshotRows(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentRow[] {\n return currentDoc ? listDocumentRows(currentDoc) : [];\n}\n\nfunction resolveCurrentAuthorId(state: DocumentStoreState): string | null {\n return resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? null;\n}\n\nexport function setReadySnapshot(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n syncing: boolean,\n textOverride?: string,\n structuredFieldsOverride?: DocumentSnapshot[\"structuredFields\"],\n) {\n const attachments = getSnapshotAttachments(state, currentDoc);\n const rows = getSnapshotRows(state, currentDoc);\n const documentState = readStoredDocumentState(\n currentDoc,\n state.runtime.infra.documentProjectors,\n );\n const text = textOverride ?? documentState.text;\n const structuredFields =\n structuredFieldsOverride ?? documentState.structuredFields;\n const projectedState =\n textOverride === undefined && structuredFieldsOverride === undefined\n ? documentState\n : projectStoredDocumentState(\n {\n documentKind: documentState.documentKind,\n structuredFields,\n text,\n rows: rows.map((row) => ({ id: row.id, fields: row.fields })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n attachments,\n attachmentStatusBySlotId: getAttachmentStatuses({\n attachments,\n contentSha256BySlotId: state.attachmentContentSha256BySlotId,\n pendingSlotIds: new Set(\n state.pendingAttachments.map((attachment) => attachment.slotId),\n ),\n }),\n attachmentStorageKeyBySlotId: getAttachmentStorageKeys(\n state.attachmentStorageKeyBySlotId,\n attachments,\n ),\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n currentAuthorId: resolveCurrentAuthorId(state),\n documentId: state.record?.documentId ?? null,\n documentKind: projectedState.documentKind,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n fieldValidationIssues: projectedState.fieldValidationIssues,\n ready: true,\n rows,\n structuredFields: projectedState.structuredFields,\n text,\n title: projectedState.title,\n syncing,\n });\n}\n\nexport function setDocumentSyncing(\n state: DocumentStoreState,\n syncing: boolean,\n) {\n setDocumentSnapshot(state, { ...state.snapshot, syncing });\n}\n\nexport function refreshAttachabilitySnapshot(state: DocumentStoreState) {\n if (!state.snapshot.ready) {\n return;\n }\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n });\n}\n\nexport function subscribeToDocumentStore(\n state: DocumentStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => void state.listeners.delete(listener);\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createDocument } from "../../../internal/loro/index.js";
|
|
2
|
-
import { getRuntimePeerSeed } from "../../../data/crdtPeerSeed.js";
|
|
3
2
|
import { ensureDocumentAttachmentStructure } from "../../../data/documents/documentContent.js";
|
|
4
3
|
import { ensureDocumentRowsStructure } from "../../../data/documents/documentRowList.js";
|
|
5
4
|
import { DOCUMENTS_APP_KIND } from "../../../workflows/documents/index.js";
|
|
5
|
+
import { getRuntimePeerSeed } from "../../../workflows/sync/index.js";
|
|
6
6
|
async function createStoredDocumentWithSeed(peerSeed) {
|
|
7
7
|
const createdDoc = await createDocument(peerSeed);
|
|
8
8
|
ensureDocumentAttachmentStructure(createdDoc);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storedDocument.js","sourceRoot":"","sources":["storedDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"storedDocument.js","sourceRoot":"","sources":["storedDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,iCAAiC,EAAE,MAAM,yCAAyC,CAAC;AAC5F,OAAO,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAG7D,KAAK,UAAU,4BAA4B,CACzC,QAAgB;IAEhB,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,QAAQ,CAAC,CAAC;IAClD,iCAAiC,CAAC,UAAU,CAAC,CAAC;IAC9C,2BAA2B,CAAC,UAAU,CAAC,CAAC;IACxC,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAyB;IAEzB,6EAA6E;IAC7E,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;IAChD,MAAM,KAAK,GAAG,SAAS;QACrB,CAAC,CAAC,GAAG,kBAAkB,IAAI,SAAS,EAAE;QACtC,CAAC,CAAC,kBAAkB,CAAC;IACvB,OAAO,4BAA4B,CACjC,MAAM,kBAAkB,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CACjE,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,6BAA6B;IAC3C,OAAO,4BAA4B,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { createDocument } from \"@tearleads/loro\";\nimport { ensureDocumentAttachmentStructure } from \"../../../data/documents/documentContent\";\nimport { ensureDocumentRowsStructure } from \"../../../data/documents/documentRowList\";\nimport { DOCUMENTS_APP_KIND } from \"../../../workflows/documents\";\nimport { getRuntimePeerSeed } from \"../../../workflows/sync\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\n\nasync function createStoredDocumentWithSeed(\n peerSeed: string,\n): Promise<DocumentState> {\n const createdDoc = await createDocument(peerSeed);\n ensureDocumentAttachmentStructure(createdDoc);\n ensureDocumentRowsStructure(createdDoc);\n return createdDoc;\n}\n\nexport async function createStoredDocument(\n state: DocumentStoreState,\n): Promise<DocumentState> {\n // Persistent pane namespaces retain stable seeds. Concurrent runtimes in one\n // namespace receive distinct memory-only seeds after the first owner, while\n // the usual single runtime can reuse its device seed after a page reload.\n const peerScope = state.runtime.state.peerScope;\n const scope = peerScope\n ? `${DOCUMENTS_APP_KIND}:${peerScope}`\n : DOCUMENTS_APP_KIND;\n return createStoredDocumentWithSeed(\n await getRuntimePeerSeed(scope, state.runtime.state.domainScope),\n );\n}\n\n/**\n * Rebuild after discarding non-durable local ops under a new peer. Reusing the\n * normal peer would reuse the discarded counters and corrupt the next edit.\n */\nexport function createFreshPeerStoredDocument(): Promise<DocumentState> {\n return createStoredDocumentWithSeed(crypto.randomUUID());\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,wBAAwB,EACxB,kBAAkB,EAGlB,yBAAyB,EACzB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,uBAAuB,EAAE,M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AAC,SAAS,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["import type { BlobByteSource } from \"../../../data/blobContracts\";\nimport type { BlobSourceSnapshot } from \"../../../data/documents/blob/shared/blobSourceSnapshot\";\nimport type { uploadPreparedDocumentAttachment as uploadDocumentAttachment } from \"../../../workflows/blobs/upload\";\nimport {\n clearDocumentSyncFailure,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type PendingAttachmentRecord,\n recordDocumentSyncFailure,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../workflows/documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../workflows/principals/runtimePolicyWarmer\";\nimport { markOriginatedDocuments } from \"../../../workflows/sync\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"./attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"./attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadFailedError,\n createAttachmentUploadLaneReporter,\n} from \"./attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"./attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentState,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"./state\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { ensureRemoteDocument } from \"./syncShared\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n const currentRecord = await ensureRemoteDocumentForAttachmentSync(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n attachmentGeneration,\n );\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n const bindingsReady = await loadRemoteAttachmentBindings({\n pendingAttachment,\n progress,\n remoteDocumentId,\n state,\n });\n if (!bindingsReady) {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n\n const outcome = await syncPendingAttachmentUpload({\n activeBindingBySlotId: progress.activeBindingBySlotId,\n attachmentGeneration,\n encapsulationKeyPair,\n pendingAttachment,\n remoteDocumentId,\n state,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") {\n progress.uploadedAttachment = true;\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await clearDocumentSyncFailure(state.runtime.infra.execSql, {\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\nasync function ensureRemoteDocumentForAttachmentSync(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation?: DocumentStoreSyncGeneration,\n): Promise<DocumentRecord | null> {\n if (nextRecord.documentId) {\n return nextRecord;\n }\n\n return ensureRemoteDocument(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n );\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: Parameters<typeof uploadDocumentAttachment>[0][\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): Parameters<typeof uploadDocumentAttachment>[0] {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n apiClient: state.runtime.apiClient,\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n execSql: state.runtime.infra.execSql,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n targetSecretKey: input.pendingUpload.encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n state.runtime,\n ),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: Parameters<typeof uploadDocumentAttachment>[0];\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId === input.pendingUpload.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n state,\n writerProjection,\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n pendingUpload: input,\n uploadLane,\n });\n}\n\nfunction reportAttachmentUploadFailure(input: {\n attachmentGeneration: DocumentStoreSyncGeneration;\n error: unknown;\n pendingAttachment: PendingAttachmentRecord;\n state: DocumentStoreState;\n uploadLane: AttachmentUploadLaneReporter;\n}): void {\n const error = createAttachmentUploadFailedError(\n input.pendingAttachment,\n input.error,\n );\n input.uploadLane.fail(error);\n input.state.runtime.util.log(`Documents: ${error.message}`);\n // Surface the stuck upload in the write queue; a later successful sync pass\n // for the document clears the record. Validated inside the serialized\n // mutation: a teardown (reset/discard) racing this pass just cleared the\n // failure row, and re-recording it would resurrect a phantom queue entry\n // for work that no longer exists.\n void runSerializedSqlMutation(\n input.state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n !isDocumentStoreSyncGenerationCurrent(\n input.state,\n input.attachmentGeneration,\n )\n ) {\n return;\n }\n await recordDocumentSyncFailure(\n lockedExecSql,\n { appKind: DOCUMENTS_APP_KIND, localId: input.state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: error.message,\n status: null,\n },\n );\n },\n ).catch(() => undefined);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,wBAAwB,EACxB,kBAAkB,EAGlB,yBAAyB,EACzB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,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from \"../../../data/documents/blob/shared/blobSourceSnapshot\";\nimport type { BlobByteSource } from \"../../../workflows/blobs\";\nimport type { uploadPreparedDocumentAttachment as uploadDocumentAttachment } from \"../../../workflows/blobs/upload\";\nimport {\n clearDocumentSyncFailure,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type PendingAttachmentRecord,\n recordDocumentSyncFailure,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../workflows/documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../workflows/principals/runtimePolicyWarmer\";\nimport { markOriginatedDocuments } from \"../../../workflows/sync\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"./attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"./attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadFailedError,\n createAttachmentUploadLaneReporter,\n} from \"./attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"./attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentState,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"./state\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { ensureRemoteDocument } from \"./syncShared\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n const currentRecord = await ensureRemoteDocumentForAttachmentSync(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n attachmentGeneration,\n );\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n const bindingsReady = await loadRemoteAttachmentBindings({\n pendingAttachment,\n progress,\n remoteDocumentId,\n state,\n });\n if (!bindingsReady) {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n\n const outcome = await syncPendingAttachmentUpload({\n activeBindingBySlotId: progress.activeBindingBySlotId,\n attachmentGeneration,\n encapsulationKeyPair,\n pendingAttachment,\n remoteDocumentId,\n state,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") {\n progress.uploadedAttachment = true;\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await clearDocumentSyncFailure(state.runtime.infra.execSql, {\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\nasync function ensureRemoteDocumentForAttachmentSync(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation?: DocumentStoreSyncGeneration,\n): Promise<DocumentRecord | null> {\n if (nextRecord.documentId) {\n return nextRecord;\n }\n\n return ensureRemoteDocument(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n );\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: Parameters<typeof uploadDocumentAttachment>[0][\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): Parameters<typeof uploadDocumentAttachment>[0] {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n apiClient: state.runtime.apiClient,\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n execSql: state.runtime.infra.execSql,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n targetSecretKey: input.pendingUpload.encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n state.runtime,\n ),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: Parameters<typeof uploadDocumentAttachment>[0];\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId === input.pendingUpload.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n state,\n writerProjection,\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n pendingUpload: input,\n uploadLane,\n });\n}\n\nfunction reportAttachmentUploadFailure(input: {\n attachmentGeneration: DocumentStoreSyncGeneration;\n error: unknown;\n pendingAttachment: PendingAttachmentRecord;\n state: DocumentStoreState;\n uploadLane: AttachmentUploadLaneReporter;\n}): void {\n const error = createAttachmentUploadFailedError(\n input.pendingAttachment,\n input.error,\n );\n input.uploadLane.fail(error);\n input.state.runtime.util.log(`Documents: ${error.message}`);\n // Surface the stuck upload in the write queue; a later successful sync pass\n // for the document clears the record. Validated inside the serialized\n // mutation: a teardown (reset/discard) racing this pass just cleared the\n // failure row, and re-recording it would resurrect a phantom queue entry\n // for work that no longer exists.\n void runSerializedSqlMutation(\n input.state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n !isDocumentStoreSyncGenerationCurrent(\n input.state,\n input.attachmentGeneration,\n )\n ) {\n return;\n }\n await recordDocumentSyncFailure(\n lockedExecSql,\n { appKind: DOCUMENTS_APP_KIND, localId: input.state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: error.message,\n status: null,\n },\n );\n },\n ).catch(() => undefined);\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { StoredDocumentKind } from "../../data/documents/documentKinds.js";
|
|
2
|
-
import type { DomainScope } from "../../data/domainScope.js";
|
|
2
|
+
import type { DomainScope } from "../../data/shared/domainScope.js";
|
|
3
3
|
import { type DocumentsPersistence } from "../../workflows/documents/index.js";
|
|
4
4
|
import type { DocumentStore, DocumentStoreFacade, DocumentStoreOpenOptions, DocumentsRuntime } from "./types.js";
|
|
5
5
|
export { discardRegisteredDocumentLocalState, requestDomainDocumentSync, subscribeToPersistedDocuments, } from "./registry.js";
|