@tearleads/client-sdk 0.1.69 → 0.1.71
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/internal/api-client/ApiClient.d.ts +73 -3
- package/internal/api-client/apiRequestMetrics.d.ts +18 -4
- package/internal/api-client/apiRequestMetrics.js +55 -5
- package/internal/api-client/apiRequestMetrics.js.map +1 -1
- package/internal/api-client/durationSampleWindow.d.ts +26 -0
- package/internal/api-client/durationSampleWindow.js +42 -0
- package/internal/api-client/durationSampleWindow.js.map +1 -0
- package/internal/api-client/measureApiRequest.js +9 -4
- package/internal/api-client/measureApiRequest.js.map +1 -1
- package/internal/api-client/serverTiming.d.ts +12 -0
- package/internal/api-client/serverTiming.js +49 -0
- package/internal/api-client/serverTiming.js.map +1 -0
- package/internal/validators/documentCreateSeedRefinements.js +9 -0
- package/internal/validators/documentCreateSeedRefinements.js.map +1 -0
- package/internal/validators/operation/auth.d.ts +120 -0
- package/internal/validators/operation/containerMutations.d.ts +355 -0
- package/internal/validators/operation/containerMutations.js +7 -1
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/internal/validators/operation/documentMutations.d.ts +356 -0
- package/internal/validators/operation/documentMutations.js +6 -1
- package/internal/validators/operation/documentMutations.js.map +1 -1
- package/internal/validators/operation/documentSync.d.ts +9 -9
- package/internal/validators/operation/organizations.d.ts +120 -0
- package/internal/validators/request/containerMetadata.d.ts +313 -0
- package/internal/validators/request/containerMetadata.js +20 -3
- package/internal/validators/request/containerMetadata.js.map +1 -1
- package/internal/validators/request/document.d.ts +571 -0
- package/internal/validators/request/document.js +19 -1
- package/internal/validators/request/document.js.map +1 -1
- package/internal/validators/request/documentCreateSeed.js +35 -0
- package/internal/validators/request/documentCreateSeed.js.map +1 -0
- package/internal/validators/request/organizationProvisioning.js +9 -22
- package/internal/validators/request/organizationProvisioning.js.map +1 -1
- package/internal/validators/response/containerMetadata.d.ts +20 -0
- package/internal/validators/response/documentMutation.d.ts +43 -0
- package/internal/validators/response/documentMutation.js +12 -1
- package/internal/validators/response/documentMutation.js.map +1 -1
- package/internal/validators/response/documentSyncSchema.d.ts +13 -9
- package/internal/validators/response/documentSyncSchema.js +23 -18
- package/internal/validators/response/documentSyncSchema.js.map +1 -1
- package/internal/validators/response/index.d.ts +1 -1
- package/internal/validators/response/index.js.map +1 -1
- package/internal/validators/response/organizationProvisioning.d.ts +350 -0
- package/internal/validators/response/registration.d.ts +120 -0
- package/package.json +1 -1
- package/stores/container-contents/containerState/containerStatePersistence.js +2 -0
- package/stores/container-contents/containerState/containerStatePersistence.js.map +1 -1
- package/stores/container-contents/remoteEvents/remoteEventSync.js +1 -1
- package/stores/container-contents/remoteEvents/remoteEventSync.js.map +1 -1
- package/stores/container-contents/state.js +2 -0
- package/stores/container-contents/state.js.map +1 -1
- package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -0
- package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
- package/stores/documents/documentStore/sync/createdDocumentPersistence.js +71 -0
- package/stores/documents/documentStore/sync/createdDocumentPersistence.js.map +1 -0
- package/stores/documents/documentStore/sync/index.js +13 -2
- package/stores/documents/documentStore/sync/index.js.map +1 -1
- package/stores/documents/documentStore/sync/syncRemoteSignals.js +21 -3
- package/stores/documents/documentStore/sync/syncRemoteSignals.js.map +1 -1
- package/stores/documents/documentStore/sync/syncSeededCreate.js +50 -0
- package/stores/documents/documentStore/sync/syncSeededCreate.js.map +1 -0
- package/stores/documents/documentStore/sync/syncShared.js +16 -8
- package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
- package/workflows/container-contents/container-state/create/createIntentSeed.js +60 -0
- package/workflows/container-contents/container-state/create/createIntentSeed.js.map +1 -0
- package/workflows/container-contents/container-state/create/createIntentSync.js +18 -19
- package/workflows/container-contents/container-state/create/createIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadata.js +43 -6
- package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +5 -1
- package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +15 -0
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/metadata/metadataEvents.d.ts +7 -1
- package/workflows/container-contents/metadata/metadataEvents.js +8 -2
- package/workflows/container-contents/metadata/metadataEvents.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +3 -0
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/documents/create/index.d.ts +7 -0
- package/workflows/documents/create/index.js +40 -2
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/index.d.ts +1 -0
- package/workflows/documents/index.js +1 -0
- package/workflows/documents/index.js.map +1 -1
- package/workflows/documents/sync/initialSync.d.ts +39 -0
- package/workflows/documents/sync/initialSync.js +39 -6
- package/workflows/documents/sync/initialSync.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uCAAuC,EAAE,MAAM,qDAAqD,CAAC;AAC9G,OAAO,EAGL,0BAA0B,EAE1B,wBAAwB,EACxB,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAKL,kBAAkB,GACnB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,0BAA0B,IAAI,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,sCAAsC,EACtC,6BAA6B,EAC7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YAC1E,yEAAyE;YACzE,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC5D,CAAC;QACD,GAAG,EAAE,GAAG,EAAE;YACR,MAAM,kBAAkB,GAAG,qBAAqB,EAAE,CAAC;YACnD,IAAI,CAAC,kBAAkB;gBAAE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,UAAU,GAAG,2BAA2B,CAAC,KAAK,CAAC,CAAC;YACtD,IAAI,UAAU,EAAE,CAAC;gBACf,qEAAqE;gBACrE,uEAAuE;gBACvE,KAAK,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE;oBACxB,IACE,wCAAwC,CAAC,KAAK,EAAE,kBAAkB,CAAC,EACnE,CAAC;wBACD,wBAAwB,CAAC,KAAK,CAAC,CAAC;oBAClC,CAAC;gBACH,CAAC,CAAC,CAAC;gBACH,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;YAC3B,CAAC;YACD,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,CACvC,wCAAwC,CAAC,KAAK,EAAE,kBAAkB,CAAC;gBACjE,CAAC,CAAC,oBAAoB,CAAC,KAAK,EAAE,kBAAkB,CAAC;gBACjD,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,CACtB,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { reportAndRethrowKeyingVerificationError } from \"../../../../data/keyingProjectionVerification/error\";\nimport {\n type DocumentRecord,\n type DocumentSyncLane,\n isDatabaseUnavailableError,\n type PendingUpdateRecord,\n registerDocumentSyncLane,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { awaitInitializationForSync } from \"../initialization\";\nimport { listPendingUpdates } from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type DocumentSyncAttempt,\n type EncapsulationKeyPair,\n setDocumentSyncing,\n} from \"../state\";\nimport { logRevalidationUnavailable as logUnavailable } from \"./remoteRevalidationTelemetry\";\nimport {\n getActiveDocumentRemoteWork,\n runDocumentRemoteWork,\n} from \"./remoteWork\";\nimport {\n cleanupPreRegisteredUpdateIdsOnFailure,\n discardPreRegisteredUpdateIds,\n preRegisterMaterializedDocumentSyncUpdateIds,\n} from \"./syncAcceptedUpdateIds\";\nimport { syncPendingAttachments } from \"./syncAttachments\";\nimport { syncDetachedAttachmentBindings } from \"./syncDetachedAttachments\";\nimport { finalizeDocumentSync } from \"./syncFinalize\";\nimport {\n captureDocumentStoreAttachmentSyncGeneration,\n captureDocumentStoreRemoteSyncGeneration,\n captureDocumentStoreSyncGeneration,\n type DocumentStoreSyncGeneration,\n type DocumentStoreSyncLaneGeneration,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreSyncGenerationCurrent,\n isDocumentStoreSyncLaneGenerationCurrent,\n} from \"./syncGeneration\";\nimport { prepareDocumentOutgoingCoverage } from \"./syncOutgoingCoverage\";\nimport { requestRemoteDocumentSync } from \"./syncRequest\";\nimport {\n ensureRemoteDocument,\n isContainerAwaitingRemoteCreate,\n shouldSkipCleanScheduledDocumentSync,\n} from \"./syncShared\";\n\nfunction canRunScheduledSync(state: DocumentStoreState): boolean {\n return (\n // A deferred birth waits for its attach to carry it (see\n // deferredInitialUpdate.ts); a pass now would ship it on its own.\n state.deferInitialUpdate !== true &&\n state.doc !== null &&\n state.snapshot.ready &&\n state.runtime.state.online &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.crypto.encapsulationKeyPair !== null &&\n resolveDocumentCreateAuthor(state.runtime) !== null\n );\n}\n\nasync function requestOutgoingDocumentBatch(input: {\n readonly currentDoc: DocumentState;\n readonly encapsulationKeyPair: EncapsulationKeyPair;\n readonly generation: DocumentStoreSyncGeneration;\n readonly pendingUpdates: PendingUpdateRecord[];\n readonly record: DocumentRecord;\n readonly state: DocumentStoreState;\n}): Promise<{\n sentUpdateIds: string[];\n syncAttempt: DocumentSyncAttempt | null;\n}> {\n const { planningUpdates, queuedUpdateCount } = prepareDocumentStoreSyncQueue(\n input.pendingUpdates,\n );\n const sentUpdateIds: string[] = [];\n const syncAttempt = await cleanupPreRegisteredUpdateIdsOnFailure(\n input.state,\n sentUpdateIds,\n () =>\n requestRemoteDocumentSync({\n currentDoc: input.currentDoc,\n currentRecord: input.record,\n encapsulationKeyPair: input.encapsulationKeyPair,\n generation: input.generation,\n onOutgoingUpdatesMaterialized: (updateIds) =>\n preRegisterMaterializedDocumentSyncUpdateIds(\n input.state,\n sentUpdateIds,\n updateIds,\n ),\n pendingUpdates: planningUpdates,\n queuedUpdateCount,\n state: input.state,\n unavailableWriterLogMessage:\n \"Documents: skipped sync because the writer context is unavailable.\",\n }),\n );\n return { sentUpdateIds, syncAttempt };\n}\n\n/**\n * Keep the full durable queue visible to stale-heal/checkpoint classification.\n * The workflow planner owns the final count and byte bounds, and the exact\n * materialized batch is pre-registered immediately before each submit.\n */\nexport function prepareDocumentStoreSyncQueue(\n pendingUpdates: PendingUpdateRecord[],\n): {\n planningUpdates: PendingUpdateRecord[];\n queuedUpdateCount: number;\n} {\n return {\n planningUpdates: pendingUpdates,\n queuedUpdateCount: pendingUpdates.length,\n };\n}\n\nexport function canSyncDetachedAttachmentBindings(\n record: DocumentRecord,\n pendingUpdateCount: number,\n): boolean {\n return (\n pendingUpdateCount === 0 &&\n (record.pullContinuation ?? null) === null &&\n !record.pullContinuationRecoveryRequired\n );\n}\n\nasync function syncDocumentState(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation: DocumentStoreSyncGeneration,\n): Promise<DocumentRecord> {\n // Snapshot the remote-update signal sequence before any await. The GET below\n // fetches server state as of its own snapshot; any remote event delivered\n // after this point describes an update that may not be in that response, so\n // finalizeDocumentSync must not clear the signal if this sequence has moved.\n const consumedRemoteUpdateSignalSeq = state.remoteUpdateSignalSeq;\n const wasRemoteProbe = state.remoteUpdatePending;\n let pendingUpdates = await listPendingUpdates(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return state.record ?? nextRecord;\n }\n if (pendingUpdates.length === 0 && isDocumentStoreRemoteSyncBlocked(state)) {\n return nextRecord;\n }\n // Create the remote document even when nothing is queued to send: a note\n // created and never edited enqueues no updates, but its local row is still a\n // pending create the write queue reports — it must flush, not sit. Defer\n // while the container itself still awaits its remote create — with OR\n // without queued edits, since the create cannot succeed before its parent\n // exists and attempting it just records a spurious failure. The structural\n // lane primes this store again as soon as the container create lands.\n if (!nextRecord.documentId) {\n const containerAwaitsCreate = await isContainerAwaitingRemoteCreate(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return state.record ?? nextRecord;\n }\n if (containerAwaitsCreate) return nextRecord;\n }\n let nextRemoteRecord = await ensureRemoteDocument(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n );\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return state.record ?? nextRecord;\n }\n if (!nextRemoteRecord?.documentId) return nextRecord;\n\n const preparedCoverage = await prepareDocumentOutgoingCoverage({\n currentDoc,\n generation,\n pendingUpdates,\n state,\n });\n if (!preparedCoverage) {\n requestDocumentStoreSync(state);\n return state.record ?? nextRemoteRecord;\n }\n nextRemoteRecord = preparedCoverage.record;\n pendingUpdates = preparedCoverage.pendingUpdates;\n\n if (\n shouldSkipCleanScheduledDocumentSync({\n currentRecord: nextRemoteRecord,\n pendingUpdates,\n state,\n })\n ) {\n return nextRemoteRecord;\n }\n\n // Pre-register the IDs we are about to send so the author's OWN\n // `document_update_created` echo (fanned back over redis) is classified as\n // self-authored and never re-arms a redundant sync. Registering BEFORE the\n // network await closes the race where the echo lands before\n // finalizeDocumentSync records the accepted IDs — the gap that turned every\n // fast keystroke into an extra self-triggered sync.\n const { sentUpdateIds, syncAttempt } = await requestOutgoingDocumentBatch({\n currentDoc,\n encapsulationKeyPair,\n generation,\n pendingUpdates,\n record: nextRemoteRecord,\n state,\n });\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return state.record ?? nextRemoteRecord;\n }\n if (!syncAttempt) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n logUnavailable(state, wasRemoteProbe);\n return nextRemoteRecord;\n }\n\n return cleanupPreRegisteredUpdateIdsOnFailure(state, sentUpdateIds, () =>\n finalizeDocumentSync(\n state,\n currentDoc,\n nextRemoteRecord,\n syncAttempt,\n consumedRemoteUpdateSignalSeq,\n generation,\n sentUpdateIds,\n wasRemoteProbe,\n ),\n );\n}\n\nasync function revalidateRemoteDocumentBeforeAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation: DocumentStoreSyncGeneration,\n): Promise<{ canSyncAttachments: boolean; nextRecord: DocumentRecord }> {\n if (state.pendingAttachments.length === 0 || !nextRecord.documentId) {\n return { canSyncAttachments: true, nextRecord };\n }\n\n const consumedRemoteUpdateSignalSeq = state.remoteUpdateSignalSeq;\n const wasRemoteProbe = state.remoteUpdatePending;\n const syncAttempt = await requestRemoteDocumentSync({\n state,\n currentDoc,\n currentRecord: nextRecord,\n encapsulationKeyPair,\n generation,\n pendingUpdates: [],\n unavailableWriterLogMessage:\n \"Documents: skipped pre-attachment revalidation because the writer context is unavailable.\",\n });\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return { canSyncAttachments: false, nextRecord };\n }\n if (!syncAttempt) {\n logUnavailable(state, wasRemoteProbe);\n return { canSyncAttachments: false, nextRecord };\n }\n\n const refreshedRecord = await finalizeDocumentSync(\n state,\n currentDoc,\n nextRecord,\n syncAttempt,\n consumedRemoteUpdateSignalSeq,\n generation,\n [],\n wasRemoteProbe,\n );\n return {\n canSyncAttachments:\n !syncAttempt.synced.hasIncompletePull &&\n refreshedRecord.pullContinuation == null &&\n refreshedRecord.pullContinuationRecoveryRequired !== true &&\n isDocumentStoreSyncGenerationCurrent(state, generation),\n nextRecord: refreshedRecord,\n };\n}\n\nasync function runDocumentSyncPass(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n) {\n const currentDoc = state.doc;\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n let nextRecord = state.record;\n\n if (!currentDoc || !nextRecord || !encapsulationKeyPair) {\n return;\n }\n\n const generation = captureDocumentStoreRemoteSyncGeneration(\n state,\n currentDoc,\n syncLaneGeneration,\n );\n const attachmentGeneration = captureDocumentStoreAttachmentSyncGeneration(\n state,\n currentDoc,\n syncLaneGeneration,\n );\n if (!generation || !attachmentGeneration) {\n requestDocumentStoreSync(state);\n return;\n }\n\n const revalidation = await revalidateRemoteDocumentBeforeAttachments(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n );\n nextRecord = revalidation.nextRecord;\n if (!revalidation.canSyncAttachments) {\n return;\n }\n\n const attachmentResult = await syncPendingAttachments(\n state,\n nextRecord,\n encapsulationKeyPair,\n attachmentGeneration,\n );\n nextRecord = attachmentResult.nextRecord;\n if (state.pendingAttachments.length > 0) {\n return;\n }\n // A settled bind and the content update carrying its digest are two server\n // writes. Push the content in this same pass rather than re-arming a later\n // one, so a device lost between them is the only remaining window: peers\n // otherwise see the old digest against the new binding.\n\n nextRecord = await syncDocumentState(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n );\n\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return;\n }\n\n if (!state.doc || !state.record) return;\n\n const pendingUpdates = await listPendingUpdates(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return;\n }\n if (!canSyncDetachedAttachmentBindings(nextRecord, pendingUpdates.length)) {\n return;\n }\n\n await syncDetachedAttachmentBindings(state, nextRecord, generation);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nasync function runScheduledSyncIteration(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n) {\n if (!(await awaitInitializationForSync(state))) {\n return false;\n }\n if (!isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)) {\n return true;\n }\n\n if (!canRunScheduledSync(state)) {\n return true;\n }\n\n try {\n await runDocumentSyncPass(state, syncLaneGeneration);\n return true;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: state.record?.documentId ?? state.localId,\n objectKind: \"document\",\n operation: \"document.sync\",\n },\n );\n\n throw error;\n }\n}\n\nasync function runScheduledSyncLoop(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n) {\n const syncingGeneration = captureDocumentStoreSyncGeneration(\n state,\n state.doc,\n );\n setDocumentSyncing(state, true);\n\n try {\n await runScheduledSyncIteration(state, syncLaneGeneration);\n } finally {\n if (\n syncingGeneration &&\n isDocumentStoreSyncGenerationCurrent(state, syncingGeneration) &&\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ) {\n setDocumentSyncing(state, false);\n }\n }\n}\n\nexport function registerDocumentStoreSyncLane(\n state: DocumentStoreState,\n getSyncLaneGeneration: () => DocumentStoreSyncLaneGeneration | null,\n): DocumentSyncLane {\n return registerDocumentSyncLane({\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n priority: () =>\n state.remoteUpdatePending || state.record?.snapshotEndVersion === \"\"\n ? -1\n : 0,\n logError: (message, error) => {\n // Read the runtime lazily: a store's runtime is replaced in place, and a\n // reference captured here would report into a torn-down host.\n const { log, logError } = state.runtime.util;\n // Return the host's result: both callbacks are declared `=> void` but may\n // be async, and the lane reporter only catches a rejection it is handed.\n return logError ? logError(message, error) : log(message);\n },\n run: () => {\n const syncLaneGeneration = getSyncLaneGeneration();\n if (!syncLaneGeneration) return Promise.resolve();\n const activeWork = getActiveDocumentRemoteWork(state);\n if (activeWork) {\n // Re-arm on settlement, not immediately: immediate re-requests would\n // spin this lane and starve other work while the HTTP request is held.\n void activeWork.then(() => {\n if (\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ) {\n requestDocumentStoreSync(state);\n }\n });\n return Promise.resolve();\n }\n return runDocumentRemoteWork(state, () =>\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ? runScheduledSyncLoop(state, syncLaneGeneration)\n : Promise.resolve(),\n );\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uCAAuC,EAAE,MAAM,qDAAqD,CAAC;AAC9G,OAAO,EAGL,0BAA0B,EAE1B,wBAAwB,EACxB,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAKL,kBAAkB,GACnB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,0BAA0B,IAAI,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,sCAAsC,EACtC,6BAA6B,EAC7B,4CAA4C,GAC7C,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EA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E,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;YAC7C,0EAA0E;YAC1E,yEAAyE;YACzE,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC5D,CAAC;QACD,GAAG,EAAE,GAAG,EAAE;YACR,MAAM,kBAAkB,GAAG,qBAAqB,EAAE,CAAC;YACnD,IAAI,CAAC,kBAAkB;gBAAE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;YAClD,MAAM,UAAU,GAAG,2BAA2B,CAAC,KAAK,CAAC,CAAC;YACtD,IAAI,UAAU,EAAE,CAAC;gBACf,qEAAqE;gBACrE,uEAAuE;gBACvE,KAAK,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE;oBACxB,IACE,wCAAwC,CAAC,KAAK,EAAE,kBAAkB,CAAC,EACnE,CAAC;wBACD,wBAAwB,CAAC,KAAK,CAAC,CAAC;oBAClC,CAAC;gBACH,CAAC,CAAC,CAAC;gBACH,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;YAC3B,CAAC;YACD,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,CACvC,wCAAwC,CAAC,KAAK,EAAE,kBAAkB,CAAC;gBACjE,CAAC,CAAC,oBAAoB,CAAC,KAAK,EAAE,kBAAkB,CAAC;gBACjD,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,CACtB,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { reportAndRethrowKeyingVerificationError } from \"../../../../data/keyingProjectionVerification/error\";\nimport {\n type DocumentRecord,\n type DocumentSyncLane,\n isDatabaseUnavailableError,\n type PendingUpdateRecord,\n registerDocumentSyncLane,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { awaitInitializationForSync } from \"../initialization\";\nimport { listPendingUpdates } from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type DocumentSyncAttempt,\n type EncapsulationKeyPair,\n setDocumentSyncing,\n} from \"../state\";\nimport { logRevalidationUnavailable as logUnavailable } from \"./remoteRevalidationTelemetry\";\nimport {\n getActiveDocumentRemoteWork,\n runDocumentRemoteWork,\n} from \"./remoteWork\";\nimport {\n cleanupPreRegisteredUpdateIdsOnFailure,\n discardPreRegisteredUpdateIds,\n preRegisterMaterializedDocumentSyncUpdateIds,\n} from \"./syncAcceptedUpdateIds\";\nimport { syncPendingAttachments } from \"./syncAttachments\";\nimport { syncDetachedAttachmentBindings } from \"./syncDetachedAttachments\";\nimport { finalizeDocumentSync } from \"./syncFinalize\";\nimport {\n captureDocumentStoreAttachmentSyncGeneration,\n captureDocumentStoreRemoteSyncGeneration,\n captureDocumentStoreSyncGeneration,\n type DocumentStoreSyncGeneration,\n type DocumentStoreSyncLaneGeneration,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreSyncGenerationCurrent,\n isDocumentStoreSyncLaneGenerationCurrent,\n} from \"./syncGeneration\";\nimport { prepareDocumentOutgoingCoverage } from \"./syncOutgoingCoverage\";\nimport { requestRemoteDocumentSync } from \"./syncRequest\";\nimport { ensureSeededRemoteDocument } from \"./syncSeededCreate\";\nimport {\n isContainerAwaitingRemoteCreate,\n shouldSkipCleanScheduledDocumentSync,\n} from \"./syncShared\";\n\nfunction canRunScheduledSync(state: DocumentStoreState): boolean {\n return (\n // A deferred birth waits for its attach to carry it (see\n // deferredInitialUpdate.ts); a pass now would ship it on its own.\n state.deferInitialUpdate !== true &&\n state.doc !== null &&\n state.snapshot.ready &&\n state.runtime.state.online &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.crypto.encapsulationKeyPair !== null &&\n resolveDocumentCreateAuthor(state.runtime) !== null\n );\n}\n\nasync function requestOutgoingDocumentBatch(input: {\n readonly currentDoc: DocumentState;\n readonly encapsulationKeyPair: EncapsulationKeyPair;\n readonly generation: DocumentStoreSyncGeneration;\n readonly pendingUpdates: PendingUpdateRecord[];\n readonly record: DocumentRecord;\n readonly state: DocumentStoreState;\n}): Promise<{\n sentUpdateIds: string[];\n syncAttempt: DocumentSyncAttempt | null;\n}> {\n const { planningUpdates, queuedUpdateCount } = prepareDocumentStoreSyncQueue(\n input.pendingUpdates,\n );\n const sentUpdateIds: string[] = [];\n const syncAttempt = await cleanupPreRegisteredUpdateIdsOnFailure(\n input.state,\n sentUpdateIds,\n () =>\n requestRemoteDocumentSync({\n currentDoc: input.currentDoc,\n currentRecord: input.record,\n encapsulationKeyPair: input.encapsulationKeyPair,\n generation: input.generation,\n onOutgoingUpdatesMaterialized: (updateIds) =>\n preRegisterMaterializedDocumentSyncUpdateIds(\n input.state,\n sentUpdateIds,\n updateIds,\n ),\n pendingUpdates: planningUpdates,\n queuedUpdateCount,\n state: input.state,\n unavailableWriterLogMessage:\n \"Documents: skipped sync because the writer context is unavailable.\",\n }),\n );\n return { sentUpdateIds, syncAttempt };\n}\n\n/**\n * Keep the full durable queue visible to stale-heal/checkpoint classification.\n * The workflow planner owns the final count and byte bounds, and the exact\n * materialized batch is pre-registered immediately before each submit.\n */\nexport function prepareDocumentStoreSyncQueue(\n pendingUpdates: PendingUpdateRecord[],\n): {\n planningUpdates: PendingUpdateRecord[];\n queuedUpdateCount: number;\n} {\n return {\n planningUpdates: pendingUpdates,\n queuedUpdateCount: pendingUpdates.length,\n };\n}\n\nexport function canSyncDetachedAttachmentBindings(\n record: DocumentRecord,\n pendingUpdateCount: number,\n): boolean {\n return (\n pendingUpdateCount === 0 &&\n (record.pullContinuation ?? null) === null &&\n !record.pullContinuationRecoveryRequired\n );\n}\n\nasync function syncDocumentState(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation: DocumentStoreSyncGeneration,\n): Promise<DocumentRecord> {\n // Snapshot the remote-update signal sequence before any await. The GET below\n // fetches server state as of its own snapshot; any remote event delivered\n // after this point describes an update that may not be in that response, so\n // finalizeDocumentSync must not clear the signal if this sequence has moved.\n const consumedRemoteUpdateSignalSeq = state.remoteUpdateSignalSeq;\n const wasRemoteProbe = state.remoteUpdatePending;\n let pendingUpdates = await listPendingUpdates(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return state.record ?? nextRecord;\n }\n if (pendingUpdates.length === 0 && isDocumentStoreRemoteSyncBlocked(state)) {\n return nextRecord;\n }\n // Create the remote document even when nothing is queued to send: a note\n // created and never edited enqueues no updates, but its local row is still a\n // pending create the write queue reports — it must flush, not sit. Defer\n // while the container itself still awaits its remote create — with OR\n // without queued edits, since the create cannot succeed before its parent\n // exists and attempting it just records a spurious failure. The structural\n // lane primes this store again as soon as the container create lands.\n if (!nextRecord.documentId) {\n const containerAwaitsCreate = await isContainerAwaitingRemoteCreate(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return state.record ?? nextRecord;\n }\n if (containerAwaitsCreate) return nextRecord;\n }\n const created = await ensureSeededRemoteDocument({\n consumedRemoteUpdateSignalSeq,\n currentDoc,\n encapsulationKeyPair,\n generation,\n nextRecord,\n pendingUpdates,\n state,\n });\n let nextRemoteRecord = created.record;\n pendingUpdates = created.pendingUpdates;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return state.record ?? nextRecord;\n }\n if (!nextRemoteRecord?.documentId) return nextRecord;\n\n const preparedCoverage = await prepareDocumentOutgoingCoverage({\n currentDoc,\n generation,\n pendingUpdates,\n state,\n });\n if (!preparedCoverage) {\n requestDocumentStoreSync(state);\n return state.record ?? nextRemoteRecord;\n }\n nextRemoteRecord = preparedCoverage.record;\n pendingUpdates = preparedCoverage.pendingUpdates;\n\n if (\n shouldSkipCleanScheduledDocumentSync({\n currentRecord: nextRemoteRecord,\n pendingUpdates,\n state,\n })\n ) {\n return nextRemoteRecord;\n }\n\n // Pre-register the IDs we are about to send so the author's OWN\n // `document_update_created` echo (fanned back over redis) is classified as\n // self-authored and never re-arms a redundant sync. Registering BEFORE the\n // network await closes the race where the echo lands before\n // finalizeDocumentSync records the accepted IDs — the gap that turned every\n // fast keystroke into an extra self-triggered sync.\n const { sentUpdateIds, syncAttempt } = await requestOutgoingDocumentBatch({\n currentDoc,\n encapsulationKeyPair,\n generation,\n pendingUpdates,\n record: nextRemoteRecord,\n state,\n });\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n requestDocumentStoreSync(state);\n return state.record ?? nextRemoteRecord;\n }\n if (!syncAttempt) {\n discardPreRegisteredUpdateIds(state, sentUpdateIds);\n logUnavailable(state, wasRemoteProbe);\n return nextRemoteRecord;\n }\n\n return cleanupPreRegisteredUpdateIdsOnFailure(state, sentUpdateIds, () =>\n finalizeDocumentSync(\n state,\n currentDoc,\n nextRemoteRecord,\n syncAttempt,\n consumedRemoteUpdateSignalSeq,\n generation,\n sentUpdateIds,\n wasRemoteProbe,\n ),\n );\n}\n\nasync function revalidateRemoteDocumentBeforeAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation: DocumentStoreSyncGeneration,\n): Promise<{ canSyncAttachments: boolean; nextRecord: DocumentRecord }> {\n if (state.pendingAttachments.length === 0 || !nextRecord.documentId) {\n return { canSyncAttachments: true, nextRecord };\n }\n\n const consumedRemoteUpdateSignalSeq = state.remoteUpdateSignalSeq;\n const wasRemoteProbe = state.remoteUpdatePending;\n const syncAttempt = await requestRemoteDocumentSync({\n state,\n currentDoc,\n currentRecord: nextRecord,\n encapsulationKeyPair,\n generation,\n pendingUpdates: [],\n unavailableWriterLogMessage:\n \"Documents: skipped pre-attachment revalidation because the writer context is unavailable.\",\n });\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return { canSyncAttachments: false, nextRecord };\n }\n if (!syncAttempt) {\n logUnavailable(state, wasRemoteProbe);\n return { canSyncAttachments: false, nextRecord };\n }\n\n const refreshedRecord = await finalizeDocumentSync(\n state,\n currentDoc,\n nextRecord,\n syncAttempt,\n consumedRemoteUpdateSignalSeq,\n generation,\n [],\n wasRemoteProbe,\n );\n return {\n canSyncAttachments:\n !syncAttempt.synced.hasIncompletePull &&\n refreshedRecord.pullContinuation == null &&\n refreshedRecord.pullContinuationRecoveryRequired !== true &&\n isDocumentStoreSyncGenerationCurrent(state, generation),\n nextRecord: refreshedRecord,\n };\n}\n\nasync function runDocumentSyncPass(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n) {\n const currentDoc = state.doc;\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n let nextRecord = state.record;\n\n if (!currentDoc || !nextRecord || !encapsulationKeyPair) {\n return;\n }\n\n const generation = captureDocumentStoreRemoteSyncGeneration(\n state,\n currentDoc,\n syncLaneGeneration,\n );\n const attachmentGeneration = captureDocumentStoreAttachmentSyncGeneration(\n state,\n currentDoc,\n syncLaneGeneration,\n );\n if (!generation || !attachmentGeneration) {\n requestDocumentStoreSync(state);\n return;\n }\n\n const revalidation = await revalidateRemoteDocumentBeforeAttachments(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n );\n nextRecord = revalidation.nextRecord;\n if (!revalidation.canSyncAttachments) {\n return;\n }\n\n const attachmentResult = await syncPendingAttachments(\n state,\n nextRecord,\n encapsulationKeyPair,\n attachmentGeneration,\n );\n nextRecord = attachmentResult.nextRecord;\n if (state.pendingAttachments.length > 0) {\n return;\n }\n // A settled bind and the content update carrying its digest are two server\n // writes. Push the content in this same pass rather than re-arming a later\n // one, so a device lost between them is the only remaining window: peers\n // otherwise see the old digest against the new binding.\n\n nextRecord = await syncDocumentState(\n state,\n currentDoc,\n nextRecord,\n encapsulationKeyPair,\n generation,\n );\n\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return;\n }\n\n if (!state.doc || !state.record) return;\n\n const pendingUpdates = await listPendingUpdates(state);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n return;\n }\n if (!canSyncDetachedAttachmentBindings(nextRecord, pendingUpdates.length)) {\n return;\n }\n\n await syncDetachedAttachmentBindings(state, nextRecord, generation);\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nasync function runScheduledSyncIteration(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n) {\n if (!(await awaitInitializationForSync(state))) {\n return false;\n }\n if (!isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)) {\n return true;\n }\n\n if (!canRunScheduledSync(state)) {\n return true;\n }\n\n try {\n await runDocumentSyncPass(state, syncLaneGeneration);\n return true;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: state.record?.documentId ?? state.localId,\n objectKind: \"document\",\n operation: \"document.sync\",\n },\n );\n\n throw error;\n }\n}\n\nasync function runScheduledSyncLoop(\n state: DocumentStoreState,\n syncLaneGeneration: DocumentStoreSyncLaneGeneration,\n) {\n const syncingGeneration = captureDocumentStoreSyncGeneration(\n state,\n state.doc,\n );\n setDocumentSyncing(state, true);\n\n try {\n await runScheduledSyncIteration(state, syncLaneGeneration);\n } finally {\n if (\n syncingGeneration &&\n isDocumentStoreSyncGenerationCurrent(state, syncingGeneration) &&\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ) {\n setDocumentSyncing(state, false);\n }\n }\n}\n\nexport function registerDocumentStoreSyncLane(\n state: DocumentStoreState,\n getSyncLaneGeneration: () => DocumentStoreSyncLaneGeneration | null,\n): DocumentSyncLane {\n return registerDocumentSyncLane({\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n priority: () =>\n state.remoteUpdatePending || state.record?.snapshotEndVersion === \"\"\n ? -1\n : 0,\n logError: (message, error) => {\n // Read the runtime lazily: a store's runtime is replaced in place, and a\n // reference captured here would report into a torn-down host.\n const { log, logError } = state.runtime.util;\n // Return the host's result: both callbacks are declared `=> void` but may\n // be async, and the lane reporter only catches a rejection it is handed.\n return logError ? logError(message, error) : log(message);\n },\n run: () => {\n const syncLaneGeneration = getSyncLaneGeneration();\n if (!syncLaneGeneration) return Promise.resolve();\n const activeWork = getActiveDocumentRemoteWork(state);\n if (activeWork) {\n // Re-arm on settlement, not immediately: immediate re-requests would\n // spin this lane and starve other work while the HTTP request is held.\n void activeWork.then(() => {\n if (\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ) {\n requestDocumentStoreSync(state);\n }\n });\n return Promise.resolve();\n }\n return runDocumentRemoteWork(state, () =>\n isDocumentStoreSyncLaneGenerationCurrent(state, syncLaneGeneration)\n ? runScheduledSyncLoop(state, syncLaneGeneration)\n : Promise.resolve(),\n );\n },\n });\n}\n"]}
|
|
@@ -3,11 +3,27 @@ import { sequenceUnchanged } from "../../../../workflows/documents/sync/syncLane
|
|
|
3
3
|
import { resumeAfterAncestorRepairHint } from "../ancestorRepairPark.js";
|
|
4
4
|
import { invalidateDocumentWriterProjection } from "../writerProjectionGeneration.js";
|
|
5
5
|
import { allowDocumentStoreRemoteSync, markDocumentStoreRemoteSyncPending, } from "./syncGeneration.js";
|
|
6
|
+
/**
|
|
7
|
+
* The client-chosen id each store last submitted a remote create under. A peer
|
|
8
|
+
* can edit the document between the create's commit and the creator
|
|
9
|
+
* installing the id, and a seeded create answers the pass's earlier signal
|
|
10
|
+
* without a pull, so that edit's hint must still mark the store pending.
|
|
11
|
+
*/
|
|
12
|
+
const plannedRemoteDocumentIds = new WeakMap();
|
|
13
|
+
export function recordPlannedRemoteDocumentId(state, documentId) {
|
|
14
|
+
plannedRemoteDocumentIds.set(state, documentId);
|
|
15
|
+
}
|
|
16
|
+
function remoteUpdateHintDocumentId(state) {
|
|
17
|
+
if (!state.record)
|
|
18
|
+
return null;
|
|
19
|
+
return state.record.documentId ?? plannedRemoteDocumentIds.get(state) ?? null;
|
|
20
|
+
}
|
|
6
21
|
export function hasRemoteDocumentUpdateEvent(state, events) {
|
|
22
|
+
const documentId = remoteUpdateHintDocumentId(state);
|
|
7
23
|
let remoteUpdateFound = false;
|
|
8
24
|
for (const event of events) {
|
|
9
25
|
if (!isDocumentUpdateCreatedEvent(event) ||
|
|
10
|
-
event.documentId !==
|
|
26
|
+
event.documentId !== documentId) {
|
|
11
27
|
continue;
|
|
12
28
|
}
|
|
13
29
|
if (event.updateIds && event.updateIds.length > 0) {
|
|
@@ -48,12 +64,14 @@ export function handleDocumentRemoteEvents(state, scheduleSync) {
|
|
|
48
64
|
const projectionInvalidated = nextEvents.some(isContainerProjectionInvalidationHint);
|
|
49
65
|
if (projectionInvalidated)
|
|
50
66
|
invalidateDocumentWriterProjection(state);
|
|
51
|
-
if (!state
|
|
67
|
+
if (!remoteUpdateHintDocumentId(state))
|
|
52
68
|
return;
|
|
53
69
|
// Writes parked behind an ancestor another member must re-key: this hint is
|
|
54
70
|
// the only signal that the repair may have landed. It names no ancestor, so
|
|
55
71
|
// any one re-runs the pass, which parks again if the path is still stale.
|
|
56
|
-
if (
|
|
72
|
+
if (state.record?.documentId &&
|
|
73
|
+
projectionInvalidated &&
|
|
74
|
+
resumeAfterAncestorRepairHint(state)) {
|
|
57
75
|
scheduleSync();
|
|
58
76
|
}
|
|
59
77
|
if (hasRemoteDocumentUpdateEvent(state, nextEvents)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncRemoteSignals.js","sourceRoot":"","sources":["syncRemoteSignals.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE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AK,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;IAC1E,KAAK,CAAC,cAAc,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC;IAEzD,yEAAyE;IACzE,2EAA2E;IAC3E,4EAA4E;IAC5E,uEAAuE;IACvE,2EAA2E;IAC3E,MAAM,qBAAqB,GAAG,UAAU,CAAC,IAAI,CAC3C,qCAAqC,CACtC,CAAC;IACF,IAAI,qBAAqB;QAAE,kCAAkC,CAAC,KAAK,CAAC,CAAC;IAErE,IAAI,CAAC,0BAA0B,CAAC,KAAK,CAAC;QAAE,OAAO;IAE/C,4EAA4E;IAC5E,4EAA4E;IAC5E,0EAA0E;IAC1E,IACE,KAAK,CAAC,MAAM,EAAE,UAAU;QACxB,qBAAqB;QACrB,6BAA6B,CAAC,KAAK,CAAC,EACpC,CAAC;QACD,YAAY,EAAE,CAAC;IACjB,CAAC;IAED,IAAI,4BAA4B,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC;QACpD,4BAA4B,CAAC,KAAK,CAAC,CAAC;QACpC,oEAAoE;QACpE,uCAAuC;QACvC,kCAAkC,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QACzD,YAAY,EAAE,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["import {\n isContainerProjectionInvalidationHint,\n isDocumentUpdateCreatedEvent,\n} from \"../../../../data/documents/documentSync\";\nimport { sequenceUnchanged } from \"../../../../workflows/documents/sync/syncLane\";\nimport { resumeAfterAncestorRepairHint } from \"../ancestorRepairPark\";\nimport type { DocumentStoreState } from \"../state\";\nimport { invalidateDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n allowDocumentStoreRemoteSync,\n markDocumentStoreRemoteSyncPending,\n} from \"./syncGeneration\";\n\n/**\n * The client-chosen id each store last submitted a remote create under. A peer\n * can edit the document between the create's commit and the creator\n * installing the id, and a seeded create answers the pass's earlier signal\n * without a pull, so that edit's hint must still mark the store pending.\n */\nconst plannedRemoteDocumentIds = new WeakMap<DocumentStoreState, string>();\n\nexport function recordPlannedRemoteDocumentId(\n state: DocumentStoreState,\n documentId: string,\n): void {\n plannedRemoteDocumentIds.set(state, documentId);\n}\n\nfunction remoteUpdateHintDocumentId(state: DocumentStoreState): string | null {\n if (!state.record) return null;\n return state.record.documentId ?? plannedRemoteDocumentIds.get(state) ?? null;\n}\n\nexport function hasRemoteDocumentUpdateEvent(\n state: DocumentStoreState,\n events: ReadonlyArray<unknown>,\n): boolean {\n const documentId = remoteUpdateHintDocumentId(state);\n let remoteUpdateFound = false;\n\n for (const event of events) {\n if (\n !isDocumentUpdateCreatedEvent(event) ||\n event.documentId !== documentId\n ) {\n continue;\n }\n\n if (event.updateIds && event.updateIds.length > 0) {\n for (const updateId of event.updateIds) {\n if (!state.locallyAcceptedUpdateIds.has(updateId)) {\n remoteUpdateFound = true;\n continue;\n }\n\n state.locallyAcceptedUpdateIds.delete(updateId);\n }\n continue;\n }\n\n remoteUpdateFound = true;\n }\n\n return remoteUpdateFound;\n}\n\n/** Clear the remote-update signal only when its consumed sequence is unchanged.\n * A moved sequence means a newer remote event arrived mid-pass and must survive\n * for the coalesced re-run to avoid the convergence-stall race.\n */\nexport const canClearRemoteUpdateSignalAfterSync = sequenceUnchanged;\n\nexport function clearConsumedRemoteUpdateSignal(\n state: DocumentStoreState,\n consumedSignalSequence: number,\n): void {\n // A peer event can arrive while the HTTP request is in flight. Clear only\n // the sequence this pass consumed so the newer event survives for a re-run.\n if (\n canClearRemoteUpdateSignalAfterSync(\n state.remoteUpdateSignalSeq,\n consumedSignalSequence,\n )\n ) {\n state.remoteUpdateCompletedSignalSeq = consumedSignalSequence;\n state.remoteUpdatePending = false;\n }\n}\n\nexport function handleDocumentRemoteEvents(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): void {\n const nextEvents = state.runtime.state.events.slice(state.lastEventCount);\n state.lastEventCount = state.runtime.state.events.length;\n\n // A container the document's path cites may have moved its manifest; the\n // store cannot tell which containers this document links into, so the held\n // projection goes and the next mutation fetches a fresh one. This runs even\n // before the document has a remote id: a create in flight captured the\n // generation when it started and must not install its pre-hint projection.\n const projectionInvalidated = nextEvents.some(\n isContainerProjectionInvalidationHint,\n );\n if (projectionInvalidated) invalidateDocumentWriterProjection(state);\n\n if (!remoteUpdateHintDocumentId(state)) return;\n\n // Writes parked behind an ancestor another member must re-key: this hint is\n // the only signal that the repair may have landed. It names no ancestor, so\n // any one re-runs the pass, which parks again if the path is still stale.\n if (\n state.record?.documentId &&\n projectionInvalidated &&\n resumeAfterAncestorRepairHint(state)\n ) {\n scheduleSync();\n }\n\n if (hasRemoteDocumentUpdateEvent(state, nextEvents)) {\n allowDocumentStoreRemoteSync(state);\n // Let an in-flight pass distinguish this new signal from the one it\n // consumed before its network request.\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n scheduleSync();\n }\n}\n"]}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { encodeVersionVector } from "../../../../internal/loro/index.js";
|
|
2
|
+
import { documentCreateSeedCandidate, } from "../../../../workflows/documents/index.js";
|
|
3
|
+
import { listPendingUpdates } from "../persistence.js";
|
|
4
|
+
import { cleanupPreRegisteredUpdateIdsOnFailure, discardPreRegisteredUpdateIds, preRegisterMaterializedDocumentSyncUpdateIds, } from "./syncAcceptedUpdateIds.js";
|
|
5
|
+
import { clearConsumedRemoteUpdateSignal } from "./syncRemoteSignals.js";
|
|
6
|
+
import { ensureRemoteDocument } from "./syncShared.js";
|
|
7
|
+
/**
|
|
8
|
+
* Creates a document that does not exist remotely yet. When its whole content
|
|
9
|
+
* is one queued row (see `documentCreateSeedCandidate`), the create commits
|
|
10
|
+
* that row as its seed and stands in for this pass's sync: the row settles and
|
|
11
|
+
* a signal raised before the pass is answered, since no remote content can
|
|
12
|
+
* predate the create. A deferred birth with nothing queued keeps the ordinary
|
|
13
|
+
* path, where the coverage pass materializes it.
|
|
14
|
+
*/
|
|
15
|
+
export async function ensureSeededRemoteDocument(input) {
|
|
16
|
+
const { state } = input;
|
|
17
|
+
const seedUpdate = input.nextRecord.documentId
|
|
18
|
+
? null
|
|
19
|
+
: documentCreateSeedCandidate({
|
|
20
|
+
documentVersion: encodeVersionVector(input.currentDoc),
|
|
21
|
+
pendingUpdates: input.pendingUpdates,
|
|
22
|
+
});
|
|
23
|
+
const ensure = (seed) => ensureRemoteDocument(state, input.currentDoc, input.nextRecord, input.encapsulationKeyPair, input.generation, seed);
|
|
24
|
+
if (!seedUpdate) {
|
|
25
|
+
return {
|
|
26
|
+
pendingUpdates: input.pendingUpdates,
|
|
27
|
+
record: await ensure(undefined),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
// Registered before the network await, as a sync registers its sent ids, so
|
|
31
|
+
// the create's own update echo is classified as self-authored.
|
|
32
|
+
const seedUpdateIds = [];
|
|
33
|
+
preRegisterMaterializedDocumentSyncUpdateIds(state, seedUpdateIds, [
|
|
34
|
+
seedUpdate.id,
|
|
35
|
+
]);
|
|
36
|
+
let committed = false;
|
|
37
|
+
const record = await cleanupPreRegisteredUpdateIdsOnFailure(state, seedUpdateIds, () => ensure({
|
|
38
|
+
onCommitted: () => {
|
|
39
|
+
committed = true;
|
|
40
|
+
},
|
|
41
|
+
update: seedUpdate,
|
|
42
|
+
}));
|
|
43
|
+
if (!committed) {
|
|
44
|
+
discardPreRegisteredUpdateIds(state, seedUpdateIds);
|
|
45
|
+
return { pendingUpdates: input.pendingUpdates, record };
|
|
46
|
+
}
|
|
47
|
+
clearConsumedRemoteUpdateSignal(state, input.consumedRemoteUpdateSignalSeq);
|
|
48
|
+
return { pendingUpdates: await listPendingUpdates(state), record };
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=syncSeededCreate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"syncSeededCreate.js","sourceRoot":"","sources":["syncSeededCreate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBA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AAK,EACL,aAAa,EACb,GAAG,EAAE,CACH,MAAM,CAAC;QACL,WAAW,EAAE,GAAG,EAAE;YAChB,SAAS,GAAG,IAAI,CAAC;QACnB,CAAC;QACD,MAAM,EAAE,UAAU;KACnB,CAAC,CACL,CAAC;IACF,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,6BAA6B,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QACpD,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,cAAc,EAAE,MAAM,EAAE,CAAC;IAC1D,CAAC;IACD,+BAA+B,CAAC,KAAK,EAAE,KAAK,CAAC,6BAA6B,CAAC,CAAC;IAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;AACrE,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport {\n type DocumentRecord,\n documentCreateSeedCandidate,\n type PendingUpdateRecord,\n} from \"../../../../workflows/documents\";\nimport { listPendingUpdates } from \"../persistence\";\nimport type {\n DocumentState,\n DocumentStoreState,\n EncapsulationKeyPair,\n} from \"../state\";\nimport {\n cleanupPreRegisteredUpdateIdsOnFailure,\n discardPreRegisteredUpdateIds,\n preRegisterMaterializedDocumentSyncUpdateIds,\n} from \"./syncAcceptedUpdateIds\";\nimport type { DocumentStoreSyncGeneration } from \"./syncGeneration\";\nimport { clearConsumedRemoteUpdateSignal } from \"./syncRemoteSignals\";\nimport { ensureRemoteDocument } from \"./syncShared\";\n\n/**\n * Creates a document that does not exist remotely yet. When its whole content\n * is one queued row (see `documentCreateSeedCandidate`), the create commits\n * that row as its seed and stands in for this pass's sync: the row settles and\n * a signal raised before the pass is answered, since no remote content can\n * predate the create. A deferred birth with nothing queued keeps the ordinary\n * path, where the coverage pass materializes it.\n */\nexport async function ensureSeededRemoteDocument(input: {\n readonly consumedRemoteUpdateSignalSeq: number;\n readonly currentDoc: DocumentState;\n readonly encapsulationKeyPair: EncapsulationKeyPair;\n readonly generation: DocumentStoreSyncGeneration;\n readonly nextRecord: DocumentRecord;\n readonly pendingUpdates: PendingUpdateRecord[];\n readonly state: DocumentStoreState;\n}): Promise<{\n readonly pendingUpdates: PendingUpdateRecord[];\n readonly record: DocumentRecord | null;\n}> {\n const { state } = input;\n const seedUpdate = input.nextRecord.documentId\n ? null\n : documentCreateSeedCandidate({\n documentVersion: encodeVersionVector(input.currentDoc),\n pendingUpdates: input.pendingUpdates,\n });\n const ensure = (seed: Parameters<typeof ensureRemoteDocument>[5]) =>\n ensureRemoteDocument(\n state,\n input.currentDoc,\n input.nextRecord,\n input.encapsulationKeyPair,\n input.generation,\n seed,\n );\n if (!seedUpdate) {\n return {\n pendingUpdates: input.pendingUpdates,\n record: await ensure(undefined),\n };\n }\n\n // Registered before the network await, as a sync registers its sent ids, so\n // the create's own update echo is classified as self-authored.\n const seedUpdateIds: string[] = [];\n preRegisterMaterializedDocumentSyncUpdateIds(state, seedUpdateIds, [\n seedUpdate.id,\n ]);\n let committed = false;\n const record = await cleanupPreRegisteredUpdateIdsOnFailure(\n state,\n seedUpdateIds,\n () =>\n ensure({\n onCommitted: () => {\n committed = true;\n },\n update: seedUpdate,\n }),\n );\n if (!committed) {\n discardPreRegisteredUpdateIds(state, seedUpdateIds);\n return { pendingUpdates: input.pendingUpdates, record };\n }\n clearConsumedRemoteUpdateSignal(state, input.consumedRemoteUpdateSignalSeq);\n return { pendingUpdates: await listPendingUpdates(state), record };\n}\n"]}
|
|
@@ -3,10 +3,11 @@ import { createRemoteDocument, DOCUMENTS_APP_KIND, describeDocumentRevalidationF
|
|
|
3
3
|
import { reportDocumentSyncQuarantine } from "../../../../workflows/documents/sync/reportDocumentSyncQuarantine.js";
|
|
4
4
|
import { createRuntimePrincipalPolicyWarmer } from "../../../../workflows/principals/runtimePolicyWarmer.js";
|
|
5
5
|
import { chainIdentityWrite } from "../identityWriteChain.js";
|
|
6
|
-
import { persistDocument } from "../persistence.js";
|
|
7
6
|
import { markDocumentStoreRemoved, } from "../state.js";
|
|
8
7
|
import { installDocumentWriterProjection } from "../writerProjectionGeneration.js";
|
|
8
|
+
import { persistCreatedRemoteDocument, } from "./createdDocumentPersistence.js";
|
|
9
9
|
import { isDocumentStoreSyncGenerationCurrent, } from "./syncGeneration.js";
|
|
10
|
+
import { recordPlannedRemoteDocumentId } from "./syncRemoteSignals.js";
|
|
10
11
|
/**
|
|
11
12
|
* Record a refused read-only revalidation on this document's failure row, so
|
|
12
13
|
* a document that can never refresh stops failing silently (edge-case row
|
|
@@ -123,7 +124,7 @@ async function hasDurableDocumentForCreate(state, isCurrent) {
|
|
|
123
124
|
markDocumentStoreRemoved(state);
|
|
124
125
|
return false;
|
|
125
126
|
}
|
|
126
|
-
export async function ensureRemoteDocument(state, currentDoc, nextRecord, encapsulationKeyPair, generation) {
|
|
127
|
+
export async function ensureRemoteDocument(state, currentDoc, nextRecord, encapsulationKeyPair, generation, seed) {
|
|
127
128
|
const generationIsCurrent = () => !generation || isDocumentStoreSyncGenerationCurrent(state, generation);
|
|
128
129
|
if (!generationIsCurrent())
|
|
129
130
|
return state.record ?? nextRecord;
|
|
@@ -152,6 +153,9 @@ export async function ensureRemoteDocument(state, currentDoc, nextRecord, encaps
|
|
|
152
153
|
(await deriveStableDocumentId(state.localId));
|
|
153
154
|
if (!generationIsCurrent())
|
|
154
155
|
return state.record ?? nextRecord;
|
|
156
|
+
// Hints for the document can arrive before the create's response installs
|
|
157
|
+
// its id; see recordPlannedRemoteDocumentId.
|
|
158
|
+
recordPlannedRemoteDocumentId(state, documentId);
|
|
155
159
|
if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))
|
|
156
160
|
return state.record;
|
|
157
161
|
const writerProjectionGeneration = state.writerProjectionGeneration;
|
|
@@ -167,6 +171,7 @@ export async function ensureRemoteDocument(state, currentDoc, nextRecord, encaps
|
|
|
167
171
|
isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,
|
|
168
172
|
onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(state, generation),
|
|
169
173
|
resolveProjectionUserKey: state.resolveProjectionUserKey,
|
|
174
|
+
seedUpdate: seed?.update,
|
|
170
175
|
stillCurrent: generationIsCurrent,
|
|
171
176
|
targetSecretKey: encapsulationKeyPair.secretKey,
|
|
172
177
|
warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(runtime),
|
|
@@ -199,12 +204,15 @@ export async function ensureRemoteDocument(state, currentDoc, nextRecord, encaps
|
|
|
199
204
|
// (the new-note "type immediately" race). Preserve the optimistic snapshot —
|
|
200
205
|
// documentId/keys still propagate via state.record, independent of the
|
|
201
206
|
// snapshot text — matching finalizeDocumentSync and the keystroke writes.
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
207
|
+
// A committed seed settles its row in this persist, so the pass needs no
|
|
208
|
+
// sync request.
|
|
209
|
+
const persisted = await persistCreatedRemoteDocument({
|
|
210
|
+
created,
|
|
211
|
+
currentDoc,
|
|
212
|
+
generation,
|
|
213
|
+
seed,
|
|
214
|
+
state,
|
|
215
|
+
});
|
|
208
216
|
return persisted?.record ?? state.record ?? nextRecord;
|
|
209
217
|
});
|
|
210
218
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oDAAoD,CAAC;AAC5F,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAGlB,mCAAmC,EACnC,iCAAiC,EAEjC,yBAAyB,EACzB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mEAAmE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,eAA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QAC5E,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,2EAA2E;QAC3E,6EAA6E;QAC7E,uEAAuE;QACvE,0EAA0E;QAC1E,MAAM,YAAY,GAAG,EAAE,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;QACnD,MAAM,cAAc,GAAG;YACrB,gCAAgC,EAAE,IAAI;YACtC,oBAAoB,EAAE,IAAI;SAC3B,CAAC;QACF,MAAM,SAAS,GAAG,MAAM,eAAe,CACrC,KAAK,EACL,UAAU,EACV,YAAY,EACZ,cAAc,EACd,UAAU,CACX,CAAC;QACF,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n createRemoteDocument,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n recordDocumentSyncFailure,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { persistDocument } from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await recordDocumentSyncFailure(\n lockedExecSql,\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation?: DocumentStoreSyncGeneration,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n const created = await createRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n containerId: runtime.state.containerId,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n stillCurrent: generationIsCurrent,\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n const persistPatch = { ...created.persistedState };\n const persistOptions = {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n };\n const persisted = await persistDocument(\n state,\n currentDoc,\n persistPatch,\n persistOptions,\n generation,\n );\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oDAAoD,CAAC;AAC5F,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAGlB,mCAAmC,EACnC,iCAAiC,EAEjC,yBAAyB,EACzB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,iCAAiC,CAA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D;QAC7D,MAAM,cAAc,GAAG,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC;QAChD,IAAI,cAAc,IAAI,cAAc,KAAK,OAAO,CAAC,UAAU,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAC,MAAM,CAAC;QACtB,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,qBAAqB,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QAC5D,+BAA+B,CAC7B,KAAK,EACL,OAAO,CAAC,gBAAgB,EACxB,0BAA0B,CAC3B,CAAC;QAEF,6EAA6E;QAC7E,4EAA4E;QAC5E,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,2EAA2E;QAC3E,6EAA6E;QAC7E,uEAAuE;QACvE,0EAA0E;QAC1E,yEAAyE;QACzE,gBAAgB;QAChB,MAAM,SAAS,GAAG,MAAM,4BAA4B,CAAC;YACnD,OAAO;YACP,UAAU;YACV,UAAU;YACV,IAAI;YACJ,KAAK;SACN,CAAC,CAAC;QACH,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n createRemoteDocument,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n recordDocumentSyncFailure,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await recordDocumentSyncFailure(\n lockedExecSql,\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n const created = await createRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n containerId: runtime.state.containerId,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { encodeVersionVector } from "../../../../internal/loro/index.js";
|
|
2
|
+
import { documentCreateSeedCandidate } from "../../../documents/sync/initialSync.js";
|
|
3
|
+
import { discardUnacceptedContainerMetadataUpdateIds, preRegisterMaterializedContainerMetadataUpdateIds, } from "../../metadata/metadataSyncRegistrations.js";
|
|
4
|
+
import { plannedContainerMetadataDocumentId } from "./createWithMetadataPlan.js";
|
|
5
|
+
/**
|
|
6
|
+
* The queued first metadata update, when it holds the whole document, commits
|
|
7
|
+
* with the create instead of a following metadata sync. A seed only saves that
|
|
8
|
+
* sync, so a queue that cannot be read means no seed rather than a failed pass.
|
|
9
|
+
*/
|
|
10
|
+
export async function loadMetadataSeedUpdate(state, containerState) {
|
|
11
|
+
try {
|
|
12
|
+
return documentCreateSeedCandidate({
|
|
13
|
+
documentVersion: encodeVersionVector(containerState.doc),
|
|
14
|
+
pendingUpdates: await state.persistence.listPendingUpdates(state.runtime.infra.execSql, containerState.container.id),
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Runs a seeded create with the seed's id registered as self-authored first,
|
|
23
|
+
* as a metadata sync registers the ids it sends, so the create's own update
|
|
24
|
+
* echo cannot arm the metadata sync the seed replaces. An id the create did
|
|
25
|
+
* not commit is discarded.
|
|
26
|
+
*/
|
|
27
|
+
export async function withRegisteredMetadataSeed(locallyAcceptedUpdateIds, seed, create) {
|
|
28
|
+
const registered = [];
|
|
29
|
+
if (seed) {
|
|
30
|
+
preRegisterMaterializedContainerMetadataUpdateIds(locallyAcceptedUpdateIds, registered, [seed.id]);
|
|
31
|
+
}
|
|
32
|
+
let accepted = [];
|
|
33
|
+
try {
|
|
34
|
+
const created = await create();
|
|
35
|
+
if (created && typeof created !== "symbol" && created.metadataSeed) {
|
|
36
|
+
accepted = [created.metadataSeed.updateId];
|
|
37
|
+
}
|
|
38
|
+
return created;
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
discardUnacceptedContainerMetadataUpdateIds(locallyAcceptedUpdateIds, registered, accepted);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Runs a folder's create with its planned metadata document id registered, so
|
|
46
|
+
* a peer's metadata hint that arrives before the response installs the id
|
|
47
|
+
* still queues the folder's first read (see
|
|
48
|
+
* `listContainerMetadataDocumentUpdateIds`).
|
|
49
|
+
*/
|
|
50
|
+
export async function withPlannedMetadataDocumentId(plannedDocumentIds, containerId, create) {
|
|
51
|
+
const documentId = plannedContainerMetadataDocumentId(containerId);
|
|
52
|
+
plannedDocumentIds?.add(documentId);
|
|
53
|
+
try {
|
|
54
|
+
return await create();
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
plannedDocumentIds?.delete(documentId);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=createIntentSeed.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createIntentSeed.js","sourceRoot":"","sources":["createIntentSeed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEtD,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,EACL,2CAA2C,EAC3C,iDAAiD,GAClD,MAAM,0CAA0C,CAAC;AAIlD,OAAO,EAAE,kCAAkC,EAAE,MAAM,0BAA0B,CAAC;AAE9E;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAqC,EACrC,cAA8B;IAE9B,IAAI,CAAC;QACH,OAAO,2BAA2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AC;YAAS,CAAC;QACT,kBAAkB,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IACzC,CAAC;AACH,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport type { PendingUpdateRecord } from \"../../../../data/sqlite/documentPersistence\";\nimport { documentCreateSeedCandidate } from \"../../../documents/sync/initialSync\";\nimport {\n discardUnacceptedContainerMetadataUpdateIds,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"../../metadata/metadataSyncRegistrations\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type { createRemoteContainer } from \"../remote\";\nimport type { ContainerCreateIntentSyncState } from \"../types\";\nimport { plannedContainerMetadataDocumentId } from \"./createWithMetadataPlan\";\n\n/**\n * The queued first metadata update, when it holds the whole document, commits\n * with the create instead of a following metadata sync. A seed only saves that\n * sync, so a queue that cannot be read means no seed rather than a failed pass.\n */\nexport async function loadMetadataSeedUpdate(\n state: ContainerCreateIntentSyncState,\n containerState: ContainerState,\n) {\n try {\n return documentCreateSeedCandidate({\n documentVersion: encodeVersionVector(containerState.doc),\n pendingUpdates: await state.persistence.listPendingUpdates(\n state.runtime.infra.execSql,\n containerState.container.id,\n ),\n });\n } catch {\n return null;\n }\n}\n\n/**\n * Runs a seeded create with the seed's id registered as self-authored first,\n * as a metadata sync registers the ids it sends, so the create's own update\n * echo cannot arm the metadata sync the seed replaces. An id the create did\n * not commit is discarded.\n */\nexport async function withRegisteredMetadataSeed(\n locallyAcceptedUpdateIds: Set<string> | undefined,\n seed: PendingUpdateRecord | null,\n create: () => ReturnType<typeof createRemoteContainer>,\n): ReturnType<typeof createRemoteContainer> {\n const registered: string[] = [];\n if (seed) {\n preRegisterMaterializedContainerMetadataUpdateIds(\n locallyAcceptedUpdateIds,\n registered,\n [seed.id],\n );\n }\n let accepted: string[] = [];\n try {\n const created = await create();\n if (created && typeof created !== \"symbol\" && created.metadataSeed) {\n accepted = [created.metadataSeed.updateId];\n }\n return created;\n } finally {\n discardUnacceptedContainerMetadataUpdateIds(\n locallyAcceptedUpdateIds,\n registered,\n accepted,\n );\n }\n}\n\n/**\n * Runs a folder's create with its planned metadata document id registered, so\n * a peer's metadata hint that arrives before the response installs the id\n * still queues the folder's first read (see\n * `listContainerMetadataDocumentUpdateIds`).\n */\nexport async function withPlannedMetadataDocumentId<T>(\n plannedDocumentIds: Set<string> | undefined,\n containerId: string,\n create: () => Promise<T>,\n): Promise<T> {\n const documentId = plannedContainerMetadataDocumentId(containerId);\n plannedDocumentIds?.add(documentId);\n try {\n return await create();\n } finally {\n plannedDocumentIds?.delete(documentId);\n }\n}\n"]}
|
|
@@ -4,9 +4,10 @@ import { ContainerCreateIntentSupersededError } from "../../../../data/persisten
|
|
|
4
4
|
import { errorMessage } from "../../../../data/shared/errorMessage.js";
|
|
5
5
|
import { createDetachedContainerMetadataState, installDetachedContainerMetadataState, } from "../../metadata/metadataStateIsolation.js";
|
|
6
6
|
import { hasRemoteContainerMetadataState } from "../../remoteHydration/reconciliation.js";
|
|
7
|
-
import { createRemoteContainer,
|
|
7
|
+
import { createRemoteContainer, discardOrphanedRemoteContainer, } from "../remote.js";
|
|
8
8
|
import { syncListedContainerCreate } from "./createAdoption.js";
|
|
9
9
|
import { deferTooDeepCreate, recordRefusedTooDeepCreate, } from "./createIntentDepth.js";
|
|
10
|
+
import { loadMetadataSeedUpdate, withPlannedMetadataDocumentId, withRegisteredMetadataSeed, } from "./createIntentSeed.js";
|
|
10
11
|
import { CONTAINER_ALREADY_COMMITTED } from "./createWithMetadata.js";
|
|
11
12
|
class IncompleteContainerCreateSettlementError extends Error {
|
|
12
13
|
}
|
|
@@ -62,7 +63,8 @@ async function persistCreatedRemoteContainerStateFromIntent(input) {
|
|
|
62
63
|
persistenceResult = await host.persistContainerState(persistenceCandidate, {
|
|
63
64
|
accessEpoch: 1,
|
|
64
65
|
accessStateHash: created.accessManifestHash,
|
|
65
|
-
|
|
66
|
+
// A committed seed stands in for the first metadata sync.
|
|
67
|
+
lastCommitLsn: created.metadataSeed?.commitLsn ?? null,
|
|
66
68
|
metadataDocumentId: created.metadataDocumentId,
|
|
67
69
|
systemSlot: created.systemSlot,
|
|
68
70
|
organizationId: created.organizationId,
|
|
@@ -74,6 +76,12 @@ async function persistCreatedRemoteContainerStateFromIntent(input) {
|
|
|
74
76
|
updatedAt: created.updatedAt,
|
|
75
77
|
},
|
|
76
78
|
}, {
|
|
79
|
+
...(created.metadataSeed
|
|
80
|
+
? {
|
|
81
|
+
acceptedPendingUpdateIds: [created.metadataSeed.updateId],
|
|
82
|
+
clearSyncFailure: true,
|
|
83
|
+
}
|
|
84
|
+
: {}),
|
|
77
85
|
createIntentSettlement: {
|
|
78
86
|
containerId: intent.containerId,
|
|
79
87
|
expectedIntentId: intent.id,
|
|
@@ -127,19 +135,6 @@ async function persistCreatedRemoteContainerStateFromIntent(input) {
|
|
|
127
135
|
};
|
|
128
136
|
return "persisted";
|
|
129
137
|
}
|
|
130
|
-
async function discardOrphanedRemoteContainer(input) {
|
|
131
|
-
if (!input.isCurrent()) {
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
const discardFailure = await deleteRemoteContainer({
|
|
135
|
-
containerId: input.created.containerId,
|
|
136
|
-
organizationId: input.created.organizationId,
|
|
137
|
-
runtime: input.state.runtime,
|
|
138
|
-
}).then((deleted) => (deleted ? null : "the server rejected the delete"), (error) => errorMessage(error));
|
|
139
|
-
if (input.isCurrent() && discardFailure !== null) {
|
|
140
|
-
input.state.runtime.util.log(`Container contents: failed to discard orphaned remote container ${input.created.containerId} after local delete: ${discardFailure}`);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
138
|
async function settleRemoteContainerCreate(input) {
|
|
144
139
|
const { containerState, created, syncInput } = input;
|
|
145
140
|
const { host, intent, state } = syncInput;
|
|
@@ -205,16 +200,20 @@ async function settleRemoteContainerCreate(input) {
|
|
|
205
200
|
async function createPendingRemoteContainer(input) {
|
|
206
201
|
const { containerState, parentState, syncInput } = input;
|
|
207
202
|
const { intent, state } = syncInput;
|
|
203
|
+
const metadataSeedUpdate = await loadMetadataSeedUpdate(syncInput.state, containerState);
|
|
204
|
+
if (!syncInput.isCurrent())
|
|
205
|
+
return "abandoned";
|
|
208
206
|
let created;
|
|
209
207
|
try {
|
|
210
|
-
created = await createRemoteContainer({
|
|
208
|
+
created = await withRegisteredMetadataSeed(state.locallyAcceptedMetadataUpdateIds, metadataSeedUpdate, () => createRemoteContainer({
|
|
211
209
|
systemSlot: containerState.container.systemSlot,
|
|
212
210
|
containerId: containerState.container.id,
|
|
211
|
+
...(metadataSeedUpdate ? { metadataSeedUpdate } : {}),
|
|
213
212
|
parentContainerId: parentState.container.id,
|
|
214
213
|
resolveProjectionUserKey: state.resolveProjectionUserKey,
|
|
215
214
|
runtime: state.runtime,
|
|
216
215
|
stillCurrent: syncInput.isCurrent,
|
|
217
|
-
});
|
|
216
|
+
}));
|
|
218
217
|
}
|
|
219
218
|
catch (error) {
|
|
220
219
|
if (error instanceof ContainerPathTooDeepError)
|
|
@@ -297,11 +296,11 @@ async function trySyncPendingContainerContentsContainerCreateIntent(input) {
|
|
|
297
296
|
if (await deferTooDeepCreate(input)) {
|
|
298
297
|
return currentCreateResult(input.isCurrent, "blocked");
|
|
299
298
|
}
|
|
300
|
-
return createPendingRemoteContainer({
|
|
299
|
+
return withPlannedMetadataDocumentId(state.plannedMetadataDocumentIds, containerState.container.id, () => createPendingRemoteContainer({
|
|
301
300
|
containerState,
|
|
302
301
|
parentState,
|
|
303
302
|
syncInput: input,
|
|
304
|
-
});
|
|
303
|
+
}));
|
|
305
304
|
}
|
|
306
305
|
export async function syncPendingContainerCreateIntents(input) {
|
|
307
306
|
if (!input.isCurrent()) {
|