@tearleads/client-sdk 0.1.218 → 0.1.219
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/index.d.ts +2 -2
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
- package/stores/documents/documentStore/rotation/index.js +10 -6
- package/stores/documents/documentStore/rotation/index.js.map +1 -1
- package/stores/documents/documentStore/sync/createdDocumentPersistence.js.map +1 -1
- package/stores/documents/documentStore/sync/syncRequest.js +9 -6
- package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
- package/stores/documents/documentStore/sync/syncShared.js +9 -6
- package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +4 -6
- package/workflows/container-contents/metadata/metadataRemoteSync.js +11 -7
- package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
- package/workflows/documents/create/index.d.ts +5 -42
- package/workflows/documents/create/index.js +12 -1
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +47 -0
- package/workflows/documents/create/remoteDocumentCreateRequest.js +2 -0
- package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -0
- package/workflows/documents/index.d.ts +5 -4
- package/workflows/documents/index.js +1 -2
- package/workflows/documents/index.js.map +1 -1
- package/workflows/documents/remote/remoteDocumentCollaborators.d.ts +6 -4
- package/workflows/documents/remote/remoteDocumentCollaborators.js.map +1 -1
- package/workflows/documents/remote/remoteDocumentService.d.ts +12 -5
- package/workflows/documents/remote/remoteDocumentService.js +14 -4
- package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
- package/workflows/documents/sync/index.js +18 -6
- package/workflows/documents/sync/index.js.map +1 -1
- package/workflows/documents/sync/readOnlySync.js.map +1 -1
- package/workflows/documents/sync/{readOnlySync.d.ts → remoteDocumentSyncPass.d.ts} +18 -18
- package/workflows/documents/sync/remoteDocumentSyncPass.js +2 -0
- package/workflows/documents/sync/remoteDocumentSyncPass.js.map +1 -0
- package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
- package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
- package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
- package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -1
- package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
- package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +4 -3
- package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js.map +1 -1
- package/workflows/documents/syncRekeys/syncContainerRekeys.js.map +1 -1
- package/workflows/documents/sync/index.d.ts +0 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAttemptPlanning.js","sourceRoot":"","sources":["syncAttemptPlanning.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,sCAAsC,EAAE,MAAM,wCAAwC,CAAC;AAChG,OAAO,EAAE,+BAA+B,EAAE,MAAM,+DAA+D,CAAC;AAChH,OAAO,EAEL,6BAA6B,GAC9B,MAAM,oDAAoD,CAAC;AAE5D,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,oCAAoC,EACpC,oCAAoC,GACrC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,iCAAiC,EAAE,MAAM,6CAA6C,CAAC;AAChG,OAAO,EAAE,2BAA2B,EAAE,MAAM,mCAAmC,CAAC;AAGhF;;;;;;;;;GASG;AACH,MAAM,UAAU,wBAAwB,CACtC,
|
|
1
|
+
{"version":3,"file":"syncAttemptPlanning.js","sourceRoot":"","sources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V,KAAK,CAAC,yBAAyB,CAChC;YACD,YAAY,EAAE,KAAK,CAAC,IAAI,CAAC,YAAY;YACrC,gBAAgB,EAAE,QAAQ,CAAC,UAAU;SACtC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,oCAAoC;YACvD,OAAO,OAAgB,CAAC;QAC1B,IAAI,KAAK,YAAY,oCAAoC,EAAE,CAAC;YAC1D,OAAO,qBAAqB,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAClD,CAAC;QACD,IAAI,KAAK,YAAY,mCAAmC,EAAE,CAAC;YACzD,OAAO,iCAAiC,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,CAAC,+BAA+B,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,wBAAwB,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC;AACH,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { assertDocumentManifestBundleConsistent } from \"../../../data/documents/shared/readers\";\nimport { isDocumentSyncRequestLimitError } from \"../../../data/documents/shared/sync/documentSyncOutgoingBatch\";\nimport {\n type DocumentSyncPullContinuation,\n resolvePullContinuationMinLsn,\n} from \"../../../data/documents/shared/sync/syncPagination\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { retrySyncPlanOrAbandon } from \"../syncFailures\";\nimport {\n abandonAncestorRepair,\n abandonBlockedSync,\n abandonInaccessibleAncestorRepair,\n abandonOversizedSyncPlan,\n} from \"../syncFailures/syncAbandon\";\nimport type { TerminalSubmitFailureHandler } from \"../syncFailures/syncFailureClassification\";\nimport {\n DocumentAncestorRepairAbandonedError,\n DocumentSyncPreparationRequiredError,\n} from \"../syncFailures/syncRepairAbandon\";\nimport { prepareSyncAttemptContainerRekeys } from \"../syncRekeys/syncContainerRekeyPreparation\";\nimport { buildRemoteDocumentSyncPlan } from \"../syncRekeys/syncContainerRekeys\";\nimport type { RemoteDocumentSyncPass } from \"./remoteDocumentSyncPass\";\n\n/**\n * A write-bearing pass records through the submit handler (its queued writes\n * are what the failure blocks). A read-only pass records through the\n * revalidation handler so the refusal still leaves a durable trail instead\n * of silently never revalidating (edge-case row 13). A cursor continuation is\n * wire-level read-only, but its failure still blocks the queued writes it\n * deliberately deferred. Update-id recovery likewise empties the in-flight\n * batch while durable rows remain. Both keep the submit classification and\n * its 403 handling.\n */\nexport function projectionFailureHandler(\n input: RemoteDocumentSyncPass,\n failureBlocksQueuedWrites: boolean,\n): TerminalSubmitFailureHandler | undefined {\n return failureBlocksQueuedWrites\n ? input.onTerminalSubmitFailure\n : input.onReadOnlyProjectionFailure;\n}\nexport async function planDocumentSyncAttempt(input: {\n /** The version the request advertises; defaults to the sync's live one. */\n localVersionVector?: string | null | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullContinuation?: DocumentSyncPullContinuation | undefined;\n regenerateQueuedCheckpoints: boolean;\n sync: RemoteDocumentSyncPass;\n failureBlocksQueuedWrites: boolean;\n writerProjection: DocumentWriterProjectionResponse;\n}) {\n try {\n const pendingUpdates =\n input.pullContinuation === undefined ? input.pendingUpdates : [];\n if (\n pendingUpdates.length &&\n input.sync.isRemoteSyncBlocked?.(\n (\n await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document sync manifest\",\n })\n ).organizationId,\n )\n ) {\n return abandonBlockedSync(input.sync);\n }\n // Durable repair happens once at this explicit attempt boundary. The\n // retryable builder below may only sign inline plans against its projection.\n const prepared =\n pendingUpdates.length &&\n !input.sync.buildContainerRekeys &&\n input.sync.buildRotationSnapshot\n ? await prepareSyncAttemptContainerRekeys(\n input.sync,\n input.writerProjection,\n )\n : { projection: input.writerProjection, plans: undefined };\n if (!prepared) return null;\n return await retrySyncPlanOrAbandon({\n apiClient: input.sync.apiClient,\n buildWithProjection: (projection) =>\n buildRemoteDocumentSyncPlan({\n pendingUpdates,\n localVersionVector: input.localVersionVector,\n preparedRekeys:\n projection === prepared.projection ? prepared.plans : undefined,\n minLsn: resolvePullContinuationMinLsn(\n input.pullContinuation,\n input.sync.minLsn,\n ),\n pullCursor: input.pullContinuation?.cursor,\n projection,\n regenerateQueuedCheckpoints: input.regenerateQueuedCheckpoints,\n sync: input.sync,\n }),\n documentId: input.sync.documentId,\n onRemoteDocumentDeleted: input.sync.onRemoteDocumentDeleted,\n onSyncAbandoned: input.sync.onSyncAbandoned,\n onSyncTrace: input.sync.onSyncTrace,\n onTerminalFailure: projectionFailureHandler(\n input.sync,\n input.failureBlocksQueuedWrites,\n ),\n stillCurrent: input.sync.stillCurrent,\n writerProjection: prepared.projection,\n });\n } catch (error) {\n if (error instanceof DocumentSyncPreparationRequiredError)\n return \"retry\" as const;\n if (error instanceof DocumentAncestorRepairAbandonedError) {\n return abandonAncestorRepair(input.sync, error);\n }\n if (error instanceof ContainerKekRepairInaccessibleError) {\n return abandonInaccessibleAncestorRepair(input.sync, error);\n }\n if (!isDocumentSyncRequestLimitError(error)) {\n throw error;\n }\n return abandonOversizedSyncPlan(input.sync, error);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncSubmittedResult.js","sourceRoot":"","sources":["syncSubmittedResult.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAKxH,OAAO,EAEL,2CAA2C,GAC5C,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,kDAAkD,CAAC;AAE7F,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,kCAAkC,EAAE,MAAM,6BAA6B,CAAC;AACj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CAAC,+BAA+B;iBAC7C,CAAC;aACL;SACF;QACH,CAAC,CAAC,KAAK,CAAC,gBAAgB,CAAC;IAC3B,yEAAyE;IACzE,6EAA6E;IAC7E,OAAO,2BAA2B,CAAC;QACjC,GAAG,KAAK;QACR,gBAAgB;QAChB,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuC;IAEvC,IAAI,CAAC;QACH,OAAO,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,iBAAiB,GACrB,yBAAyB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;QAC1E,IACE,CAAC,iBAAiB;YAClB,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,KAAK,KAAK;gBAC/B,CAAC,CAAC,KAAK,YAAY,kCAAkC,CAAC,CAAC,EACzD,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,yCAAyC,CAC9C,KAAK,EACL,KAAK,EACL,iBAAiB,CAClB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type {\n MaterializedDocumentSyncPlan,\n SyncRemoteDocumentResult,\n} from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport {\n type ProjectionUserKeyResolver,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../data/keyingProjectionVerification\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { DocumentRawHistoryUnavailableError } from \"../syncPlan/syncContentKeys\";\nimport {\n hasDeferredPendingUpdatesAfterSubmit,\n responseAcceptedRecoveryBaseline,\n} from \"../syncPlan/syncPlanRequestBounds\";\nimport type { SyncRemoteDocumentInput } from \"./readOnlySync\";\nimport { syncRemoteDocumentResultFromResponse } from \"./syncResponseResult\";\nimport { traceHealed } from \"./syncTrace\";\n\ntype SubmittedDocumentSyncResultInput = {\n materializedPlan: MaterializedDocumentSyncPlan;\n pendingUpdateIds: readonly string[];\n pullComplete: boolean;\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n response: DocumentSyncResponse;\n sync: SyncRemoteDocumentInput;\n writerProjection: DocumentWriterProjectionResponse;\n};\n\n/** @internal Applies post-verification heal effects under the sync generation. */\nexport function applyAcceptedHealSideEffects(input: {\n documentId: string;\n evictWriterProjection?: ((documentId: string) => void) | undefined;\n materializedPlan: MaterializedDocumentSyncPlan;\n onSyncTrace: SyncRemoteDocumentInput[\"onSyncTrace\"];\n response: DocumentSyncResponse;\n stillCurrent: SyncRemoteDocumentInput[\"stillCurrent\"];\n}): void {\n if (\n !input.materializedPlan.healedStaleContentKeyBundle ||\n !responseAcceptedRecoveryBaseline(input.materializedPlan, input.response) ||\n input.stillCurrent?.() === false\n ) {\n return;\n }\n input.evictWriterProjection?.(input.documentId);\n if (input.stillCurrent?.() === false) {\n return;\n }\n traceHealed(input.onSyncTrace, {\n accepted: input.response.acceptedOutgoingUpdateIds.length,\n documentId: input.materializedPlan.plan.documentId,\n epoch: input.materializedPlan.plan.contentKeyEpoch,\n });\n}\n\nasync function submittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult> {\n const result = await syncRemoteDocumentResultFromResponse({\n ...projectionVerificationOptions(input.sync),\n execSql: input.sync.execSql,\n materializedPlan: input.materializedPlan,\n onTerminalSubmitFailure: input.sync.onTerminalSubmitFailure,\n recoveryPendingUpdatesById: input.recoveryPendingUpdatesById,\n rekeyPendingUpdate: input.sync.rekeyPendingUpdate,\n resolveWriterPublicKey: input.sync.resolveWriterPublicKey,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n targetSecretKey: input.sync.targetSecretKey,\n validateIncomingUpdates: input.sync.validateIncomingUpdates,\n writerProjection: input.writerProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n });\n if (\n (input.materializedPlan.plan.request.containerRekeys?.length ?? 0) > 0 &&\n input.sync.stillCurrent?.() !== false\n ) {\n input.sync.apiClient.clearWriterProjectionCaches?.();\n }\n applyAcceptedHealSideEffects({\n documentId: input.sync.documentId,\n evictWriterProjection:\n input.sync.apiClient.evictDocumentWriterProjection?.bind(\n input.sync.apiClient,\n ),\n materializedPlan: input.materializedPlan,\n onSyncTrace: input.sync.onSyncTrace,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n });\n return {\n ...result,\n hasDeferredPendingUpdates:\n (input.materializedPlan.plan.request.pullCursor !== undefined &&\n input.pendingUpdateIds.length > 0 &&\n result.exhaustedPendingUpdateCount === 0) ||\n hasDeferredPendingUpdatesAfterSubmit({\n acceptedRecoveryBaseline: result.acceptedRecoveryBaseline,\n exhaustedPendingUpdateCount: result.exhaustedPendingUpdateCount,\n pendingUpdateIds: input.pendingUpdateIds,\n rekeyedPendingUpdateIds: result.rekeyedPendingUpdateIds,\n settledPendingUpdateIds: result.settledPendingUpdateIds,\n }),\n hasIncompletePull: !input.pullComplete,\n };\n}\n\nasync function retrySubmittedResponseWithFreshProjection(\n input: SubmittedDocumentSyncResultInput,\n unavailableError: unknown,\n refreshAuthorization: boolean,\n): Promise<SyncRemoteDocumentResult | null> {\n const writerProjection = await refreshSyncAttemptWriterProjection({\n apiClient: input.sync.apiClient,\n documentId: input.sync.documentId,\n onRemoteDocumentDeleted: input.sync.onRemoteDocumentDeleted,\n onSyncAbandoned: input.sync.onSyncAbandoned,\n onSyncTrace: input.sync.onSyncTrace,\n onTerminalFailure: input.sync.onReadOnlyProjectionFailure,\n stillCurrent: input.sync.stillCurrent,\n unavailableError,\n });\n if (!writerProjection) return null;\n const materializedPlan = refreshAuthorization\n ? {\n ...input.materializedPlan,\n plan: {\n ...input.materializedPlan.plan,\n documentWriterAuthorization:\n await verifyDocumentWriterProjectionAuthorization({\n execSql: input.sync.execSql,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.sync.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.sync.warmReferencedPrincipalPolicies,\n }),\n },\n }\n : input.materializedPlan;\n // Keep the submitted request, keys, and response frozen. Only refreshed,\n // verified evidence may be added; this retry never resubmits outgoing edits.\n return submittedDocumentSyncResult({\n ...input,\n materializedPlan,\n writerProjection,\n });\n}\n\nexport async function resolveSubmittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult | null> {\n try {\n return await submittedDocumentSyncResult(input);\n } catch (error) {\n const missingDependency =\n isKeyingVerificationError(error) && error.code === \"missing_dependency\";\n if (\n !missingDependency &&\n (input.sync.historyMode !== \"raw\" ||\n !(error instanceof DocumentRawHistoryUnavailableError))\n ) {\n throw error;\n }\n return retrySubmittedResponseWithFreshProjection(\n input,\n error,\n missingDependency,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncSubmittedResult.js","sourceRoot":"","sources":["syncSubmittedResult.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAKxH,OAAO,EAEL,2CAA2C,GAC5C,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,kDAAkD,CAAC;AAE7F,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,kCAAkC,EAAE,MAAM,6BAA6B,CAAC;AACjF,OAAO,EACL,oCAAoC,EACpC,gCAAgC,GACjC,MAAM,mCAAmC,CAAC;AAE3C,OAAO,EAAE,oCAAoC,EAAE,MAAM,sBAAsB,CAAC;AAC5E,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,2BAA2B,CAAC;QACjC,GAAG,KAAK;QACR,gBAAgB;QAChB,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuC;IAEvC,IAAI,CAAC;QACH,OAAO,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,iBAAiB,GACrB,yBAAyB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;QAC1E,IACE,CAAC,iBAAiB;YAClB,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,KAAK,KAAK;gBAC/B,CAAC,CAAC,KAAK,YAAY,kCAAkC,CAAC,CAAC,EACzD,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,yCAAyC,CAC9C,KAAK,EACL,KAAK,EACL,iBAAiB,CAClB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type {\n MaterializedDocumentSyncPlan,\n SyncRemoteDocumentResult,\n} from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport {\n type ProjectionUserKeyResolver,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../data/keyingProjectionVerification\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { DocumentRawHistoryUnavailableError } from \"../syncPlan/syncContentKeys\";\nimport {\n hasDeferredPendingUpdatesAfterSubmit,\n responseAcceptedRecoveryBaseline,\n} from \"../syncPlan/syncPlanRequestBounds\";\nimport type { RemoteDocumentSyncPass } from \"./remoteDocumentSyncPass\";\nimport { syncRemoteDocumentResultFromResponse } from \"./syncResponseResult\";\nimport { traceHealed } from \"./syncTrace\";\n\ntype SubmittedDocumentSyncResultInput = {\n materializedPlan: MaterializedDocumentSyncPlan;\n pendingUpdateIds: readonly string[];\n pullComplete: boolean;\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n response: DocumentSyncResponse;\n sync: RemoteDocumentSyncPass;\n writerProjection: DocumentWriterProjectionResponse;\n};\n\n/** @internal Applies post-verification heal effects under the sync generation. */\nexport function applyAcceptedHealSideEffects(input: {\n documentId: string;\n evictWriterProjection?: ((documentId: string) => void) | undefined;\n materializedPlan: MaterializedDocumentSyncPlan;\n onSyncTrace: RemoteDocumentSyncPass[\"onSyncTrace\"];\n response: DocumentSyncResponse;\n stillCurrent: RemoteDocumentSyncPass[\"stillCurrent\"];\n}): void {\n if (\n !input.materializedPlan.healedStaleContentKeyBundle ||\n !responseAcceptedRecoveryBaseline(input.materializedPlan, input.response) ||\n input.stillCurrent?.() === false\n ) {\n return;\n }\n input.evictWriterProjection?.(input.documentId);\n if (input.stillCurrent?.() === false) {\n return;\n }\n traceHealed(input.onSyncTrace, {\n accepted: input.response.acceptedOutgoingUpdateIds.length,\n documentId: input.materializedPlan.plan.documentId,\n epoch: input.materializedPlan.plan.contentKeyEpoch,\n });\n}\n\nasync function submittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult> {\n const result = await syncRemoteDocumentResultFromResponse({\n ...projectionVerificationOptions(input.sync),\n execSql: input.sync.execSql,\n materializedPlan: input.materializedPlan,\n onTerminalSubmitFailure: input.sync.onTerminalSubmitFailure,\n recoveryPendingUpdatesById: input.recoveryPendingUpdatesById,\n rekeyPendingUpdate: input.sync.rekeyPendingUpdate,\n resolveWriterPublicKey: input.sync.resolveWriterPublicKey,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n targetSecretKey: input.sync.targetSecretKey,\n validateIncomingUpdates: input.sync.validateIncomingUpdates,\n writerProjection: input.writerProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n });\n if (\n (input.materializedPlan.plan.request.containerRekeys?.length ?? 0) > 0 &&\n input.sync.stillCurrent?.() !== false\n ) {\n input.sync.apiClient.clearWriterProjectionCaches?.();\n }\n applyAcceptedHealSideEffects({\n documentId: input.sync.documentId,\n evictWriterProjection:\n input.sync.apiClient.evictDocumentWriterProjection?.bind(\n input.sync.apiClient,\n ),\n materializedPlan: input.materializedPlan,\n onSyncTrace: input.sync.onSyncTrace,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n });\n return {\n ...result,\n hasDeferredPendingUpdates:\n (input.materializedPlan.plan.request.pullCursor !== undefined &&\n input.pendingUpdateIds.length > 0 &&\n result.exhaustedPendingUpdateCount === 0) ||\n hasDeferredPendingUpdatesAfterSubmit({\n acceptedRecoveryBaseline: result.acceptedRecoveryBaseline,\n exhaustedPendingUpdateCount: result.exhaustedPendingUpdateCount,\n pendingUpdateIds: input.pendingUpdateIds,\n rekeyedPendingUpdateIds: result.rekeyedPendingUpdateIds,\n settledPendingUpdateIds: result.settledPendingUpdateIds,\n }),\n hasIncompletePull: !input.pullComplete,\n };\n}\n\nasync function retrySubmittedResponseWithFreshProjection(\n input: SubmittedDocumentSyncResultInput,\n unavailableError: unknown,\n refreshAuthorization: boolean,\n): Promise<SyncRemoteDocumentResult | null> {\n const writerProjection = await refreshSyncAttemptWriterProjection({\n apiClient: input.sync.apiClient,\n documentId: input.sync.documentId,\n onRemoteDocumentDeleted: input.sync.onRemoteDocumentDeleted,\n onSyncAbandoned: input.sync.onSyncAbandoned,\n onSyncTrace: input.sync.onSyncTrace,\n onTerminalFailure: input.sync.onReadOnlyProjectionFailure,\n stillCurrent: input.sync.stillCurrent,\n unavailableError,\n });\n if (!writerProjection) return null;\n const materializedPlan = refreshAuthorization\n ? {\n ...input.materializedPlan,\n plan: {\n ...input.materializedPlan.plan,\n documentWriterAuthorization:\n await verifyDocumentWriterProjectionAuthorization({\n execSql: input.sync.execSql,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.sync.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.sync.warmReferencedPrincipalPolicies,\n }),\n },\n }\n : input.materializedPlan;\n // Keep the submitted request, keys, and response frozen. Only refreshed,\n // verified evidence may be added; this retry never resubmits outgoing edits.\n return submittedDocumentSyncResult({\n ...input,\n materializedPlan,\n writerProjection,\n });\n}\n\nexport async function resolveSubmittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult | null> {\n try {\n return await submittedDocumentSyncResult(input);\n } catch (error) {\n const missingDependency =\n isKeyingVerificationError(error) && error.code === \"missing_dependency\";\n if (\n !missingDependency &&\n (input.sync.historyMode !== \"raw\" ||\n !(error instanceof DocumentRawHistoryUnavailableError))\n ) {\n throw error;\n }\n return retrySubmittedResponseWithFreshProjection(\n input,\n error,\n missingDependency,\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAbandon.js","sourceRoot":"","sources":["syncAbandon.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,oCAAoC,EAAE,MAAM,qBAAqB,CAAC;AAQ3E,MAAM,UAAU,kBAAkB,CAAC,KAAyB;IAC1D,KAAK,CAAC,WAAW,EAAE,CAAC,kCAAkC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IAC1E,KAAK,CAAC,eAAe,EAAE,CAAC,SAAS,CAAC,CAAC;IACnC,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,qBAAqB,CACnC,KAAyB,EACzB,KAA2C;IAE3C,uEAAuE;IACvE,yEAAyE;IACzE,yEAAyE;IACzE,4BAA4B,CAAC,KAAK,CAAC,WAAW,EAAE;QAC9C,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;IACH,KAAK,CAAC,eAAe,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,KAAyB,EACzB,KAA0C;IAE1C,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC;QACpC,IAAI,EAAE,uCAAuC;QAC7C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;QACvB,MAAM,EAAE,IAAI;KACb,CAAC,CAAC;IACH,OAAO,qBAAqB,CAC1B,KAAK,EACL,IAAI,oCAAoC,CAAC,cAAc,CAAC,CACzD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,KAAyB;IAEzB,KAAK,CAAC,eAAe,EAAE,CAAC,6CAA6C,CAAC,CAAC;IACvE,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,KAAyB,EACzB,KAAY;IAEZ,MAAM,OAAO,GAA8B;QACzC,IAAI,EAAE,iCAAiC;QACvC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;QACvB,MAAM,EAAE,IAAI;KACb,CAAC;IACF,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,OAAO,CAAC,CAAC;IAC/C,KAAK,CAAC,eAAe,EAAE,CACrB,mEAAmE,CACpE,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type {
|
|
1
|
+
{"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AAC;AAED,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,KAAyB,EACzB,KAAY;IAEZ,MAAM,OAAO,GAA8B;QACzC,IAAI,EAAE,iCAAiC;QACvC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;QACvB,MAAM,EAAE,IAAI;KACb,CAAC;IACF,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,OAAO,CAAC,CAAC;IAC/C,KAAK,CAAC,eAAe,EAAE,CACrB,mEAAmE,CACpE,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { traceAncestorRepairAbandoned } from \"../sync/syncTrace\";\nimport { DocumentAncestorRepairAbandonedError } from \"./syncRepairAbandon\";\n\n/** The ways a sync pass gives up without failing: writes stay queued. */\ntype AbandonedSyncInput = Pick<\n RemoteDocumentSyncPass,\n \"documentId\" | \"onSyncAbandoned\" | \"onSyncTrace\" | \"onTerminalSubmitFailure\"\n>;\n\nexport function abandonBlockedSync(input: AbandonedSyncInput): null {\n input.onSyncTrace?.(`document sync blocked document=${input.documentId}`);\n input.onSyncAbandoned?.(\"blocked\");\n return null;\n}\n\nexport function abandonAncestorRepair(\n input: AbandonedSyncInput,\n error: DocumentAncestorRepairAbandonedError,\n): null {\n // Trace as well as abandon: the store's onSyncAbandoned only parks the\n // document, and this path may already have issued server-side rekeys, so\n // abandoning untraced would leave a retrying loop with no way to see it.\n traceAncestorRepairAbandoned(input.onSyncTrace, {\n documentId: input.documentId,\n reason: error.reason,\n });\n input.onSyncAbandoned?.(error.reason);\n return null;\n}\n\n/**\n * The stale ancestor is one this writer can neither re-key nor be given the\n * key for, and one refetch has already confirmed nobody repaired it yet. The\n * writes stay queued; the durable row tells the write queue why, and the\n * dependent-path hint that follows the repair re-arms the pass.\n */\nexport async function abandonInaccessibleAncestorRepair(\n input: AbandonedSyncInput,\n error: ContainerKekRepairInaccessibleError,\n): Promise<null> {\n await input.onTerminalSubmitFailure?.({\n code: \"document_ancestor_repair_inaccessible\",\n message: error.message,\n ok: false,\n report: () => undefined,\n status: null,\n });\n return abandonAncestorRepair(\n input,\n new DocumentAncestorRepairAbandonedError(\"inaccessible\"),\n );\n}\n\nexport function abandonAfterRetryableConflicts(\n input: AbandonedSyncInput,\n): null {\n input.onSyncAbandoned?.(\"every sync attempt hit a retryable conflict\");\n return null;\n}\n\nexport async function abandonOversizedSyncPlan(\n input: AbandonedSyncInput,\n error: Error,\n): Promise<null> {\n const failure: DocumentSyncSubmitFailure = {\n code: \"document_sync_request_too_large\",\n message: error.message,\n ok: false,\n report: () => undefined,\n status: null,\n };\n await input.onTerminalSubmitFailure?.(failure);\n input.onSyncAbandoned?.(\n \"a queued update cannot fit within the document sync request limit\",\n );\n return null;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncRepairAccess.js","sourceRoot":"","sources":["syncRepairAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EACL,gCAAgC,EAChC,2CAA2C,GAC5C,MAAM,4CAA4C,CAAC;AAGpD,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,
|
|
1
|
+
{"version":3,"file":"syncRepairAccess.js","sourceRoot":"","sources":["syncRepairAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EACL,gCAAgC,EAChC,2CAA2C,GAC5C,MAAM,4CAA4C,CAAC;AAGpD,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,yBAAyB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C,cAAc,KAAK,QAAQ,CAAC,KAAK,CAAC,cAAc;YAC3D,CAAC,QAAQ,CAAC,KAAK,CAAC,kBAAkB,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC;YAEnE,OAAO,KAAK,CAAC;QACf,MAAM,MAAM,GAAG,mCAAmC,CAAC;YACjD,IAAI;YACJ,iBAAiB,EAAE,QAAQ,CAAC,iBAAiB;YAC7C,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,YAAY;SACjC,CAAC,CAAC;QACH,OAAO,MAAM,KAAK,OAAO,IAAI,MAAM,KAAK,OAAO,CAAC;IAClD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { resolveContainerPathUserAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n requireProjectionUserKeyResolver,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\n\n/** A repair refusal on one link does not revoke write access through another. */\nexport async function hasOtherLinkedWriteAccess(\n sync: RemoteDocumentSyncPass,\n projection: DocumentWriterProjectionResponse,\n inaccessibleContainerId: string,\n): Promise<boolean> {\n if (projection.authorizingContainerPaths.length < 2) return false;\n const verified = await verifyDocumentWriterProjectionAuthorization({\n execSql: sync.execSql,\n persistVerificationCheckpoints: false,\n projection,\n resolveUserKey: requireProjectionUserKeyResolver(\n sync.resolveProjectionUserKey,\n \"Document linked repair access\",\n ),\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n });\n const document = verified.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (\n !document ||\n document.state.documentId !== sync.documentId ||\n document.state.organizationId !== sync.author.organizationId\n )\n return false;\n // The map also contains historical paths. Only the verified current paths\n // named by this projection may establish present write authority.\n return projection.authorizingContainerPaths.some((candidate) => {\n const headHash = candidate.path.at(-1)?.manifestHash;\n const path = headHash\n ? verified.containerPathByManifestHash.get(headHash)\n : undefined;\n const leaf = path?.at(-1);\n if (\n !path ||\n !leaf ||\n leaf.state.containerId === inaccessibleContainerId ||\n leaf.state.organizationId !== document.state.organizationId ||\n !document.state.linkedContainerIds.includes(leaf.state.containerId)\n )\n return false;\n const access = resolveContainerPathUserAccessLevel({\n path,\n principalPolicies: verified.principalPolicies,\n userId: sync.author.signerUserId,\n });\n return access === \"write\" || access === \"admin\";\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAQzE,SAAS,mBAAmB,CAC1B,UAA4C;IAE5C,KAAK,MAAM,IAAI,IAAI,4BAA4B,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5D,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,KA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AAC,KAAK,CAAC,KAAK,EAAE,KAAc,EAAE,EAAE;YAChC,IAAI,KAAK,YAAY,0BAA0B,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;gBACtE,IACE,MAAM,yBAAyB,CAC7B,IAAI,EACJ,iBAAiB,EACjB,kBAAkB,CAAC,WAAW,CAC/B,EACD,CAAC;oBACD,MAAM,IAAI,mCAAmC,CAC3C,kBAAkB,CAAC,WAAW,CAC/B,CAAC;gBACJ,CAAC;gBACD,MAAM,IAAI,CAAC,uBAAuB,EAAE,CAAC;oBACnC,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,EAAE,EAAE,KAAK;oBACT,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;oBACvB,MAAM,EAAE,KAAK,CAAC,MAAM;iBACrB,CAAC,CAAC;gBACH,MAAM,IAAI,oCAAoC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YACD,qEAAqE;YACrE,uEAAuE;YACvE,uEAAuE;YACvE,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC;gBACtC,CAAC,CAAC,IAAI,mCAAmC,CACrC,kBAAkB,CAAC,WAAW,CAC/B;gBACH,CAAC,CAAC,KAAK,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAQzE,SAAS,mBAAmB,CAC1B,UAA4C;IAE5C,KAA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ectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: RemoteDocumentSyncPass,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
|
|
@@ -11,9 +11,10 @@ import { shouldRetrySyncWithFreshWriterProjection } from "../syncFailures/syncFa
|
|
|
11
11
|
import { DocumentAncestorRepairAbandonedError } from "../syncFailures/syncRepairAbandon.js";
|
|
12
12
|
import { buildAutomaticContainerRekeys } from "./syncAutomaticContainerRekeys.js";
|
|
13
13
|
/**
|
|
14
|
-
* Repairs committed during one sync pass, keyed by the pass
|
|
15
|
-
*
|
|
16
|
-
* attempt, so a counter local to one call would
|
|
14
|
+
* Repairs committed during one sync pass, keyed by the pass object that one
|
|
15
|
+
* `syncRemoteDocument` call builds and hands to all three attempts. The sync
|
|
16
|
+
* loop explicitly prepares each attempt, so a counter local to one call would
|
|
17
|
+
* not bound the whole pass.
|
|
17
18
|
*/
|
|
18
19
|
const passRepairTotals = new WeakMap();
|
|
19
20
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncContainerRekeyPrepar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AAK,CAAC,UAAU,KAAK,IAAI,CAAC,UAAU,EAAE,CAAC;YACzC,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;QACJ,CAAC;QACD,UAAU,GAAG,KAAK,CAAC;IACrB,CAAC;AACH,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,IAA6B,EAC7B,UAA4C;IAE5C,IAAI,CAAC;QACH,OAAO,MAAM,+BAA+B,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IACjE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IACE,CAAC,IAAI,CAAC,SAAS,CAAC,6BAA6B;YAC7C,CAAC,wCAAwC,CAAC,KAAK,CAAC;YAEhD,MAAM,KAAK,CAAC;IAChB,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC;QACrD,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;QACrD,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,iBAAiB,EAAE,IAAI,CAAC,uBAAuB;QAC/C,YAAY,EAAE,IAAI,CAAC,YAAY;KAChC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,CAAC,CAAC,+BAA+B,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { acknowledgeContainerMutationBatch } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n submitContainerRotation,\n submitRotationCarryingDescendants,\n} from \"../../containers/child/mutationSubmit\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { shouldRetrySyncWithFreshWriterProjection } from \"../syncFailures/syncFailureClassification\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\n\n/**\n * Repairs committed during one sync pass, keyed by the pass's own input object\n * (stable across all three attempts). The sync loop explicitly prepares each\n * attempt, so a counter local to one call would not bound the whole pass.\n */\nconst passRepairTotals = new WeakMap<SyncRemoteDocumentInput, number>();\n\n/**\n * Passes whose inline repairs the server refused for stranding a level above a\n * directly granted container. The write's flat rekey list cannot say which\n * descendants each repair must carry; a standalone rekey can, so the rest of\n * the pass commits every repair standalone before writing.\n */\nconst standaloneRepairPasses = new WeakSet<SyncRemoteDocumentInput>();\n\nexport function requiresStandaloneAncestorRepairs(\n sync: SyncRemoteDocumentInput,\n): boolean {\n return standaloneRepairPasses.has(sync);\n}\n\nexport function requireStandaloneAncestorRepairs(\n sync: SyncRemoteDocumentInput,\n): void {\n standaloneRepairPasses.add(sync);\n}\n\n/** A refusal the writer cannot clear by retrying, as opposed to 5xx/offline. */\nfunction isTerminalRepairStatus(status: number | null): boolean {\n return status === 401 || status === 402 || status === 403;\n}\n\n/**\n * One standalone repair. Prefers the status-bearing rekey: a permanent refusal\n * (403 once ancestor write access is revoked, 402) must leave a durable record,\n * while a 5xx or an offline blip must not, and plain `rekeyContainer` collapses\n * both to null. It is also the only way to learn which descendant rekeys this\n * repair must carry. An adapter without it still repairs; its refusals are just\n * reported as an ordinary abandon.\n */\nfunction submitStandaloneRepair(\n sync: SyncRemoteDocumentInput,\n plan: MaterializedContainerRekeyPlan[\"plan\"],\n writerProjection: MaterializedContainerRekeyPlan[\"writerProjection\"],\n) {\n const options = {\n expectedPaymentRequiredOrganizationId: plan.state.organizationId,\n };\n const { getContainerWriterProjection, rekeyContainerResult } = sync.apiClient;\n return submitRotationCarryingDescendants({\n carriedRekeys: getContainerWriterProjection && {\n planning: {\n apiClient: {\n getContainerWriterProjection: getContainerWriterProjection.bind(\n sync.apiClient,\n ),\n },\n author: sync.author,\n execSql: sync.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n sync.resolveProjectionUserKey,\n \"Document ancestor repair\",\n ),\n stillCurrent: sync.stillCurrent,\n targetSecretKey: sync.targetSecretKey,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n },\n rotated: async () => writerProjection,\n },\n stillCurrent: sync.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...plan.request, containerRekeys: [...carried] }\n : plan.request;\n return submitContainerRotation({\n plain: () =>\n sync.apiClient.rekeyContainer(plan.containerId, request, options),\n result: rekeyContainerResult\n ? () =>\n rekeyContainerResult.call(\n sync.apiClient,\n plan.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n\nasync function abandonRefusedRepair(\n sync: SyncRemoteDocumentInput,\n containerId: string,\n result: Awaited<ReturnType<typeof submitStandaloneRepair>>[\"result\"],\n): Promise<never> {\n if (!result.ok && isTerminalRepairStatus(result.status)) {\n await sync.onTerminalSubmitFailure?.({\n code: \"document_ancestor_repair_refused\",\n message: `Ancestor repair refused for ${containerId}`,\n ok: false,\n report: () => undefined,\n status: result.status,\n });\n }\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n}\n\n/** A repair and everything it carried committed together. */\nfunction markRepaired(\n repairedIds: Set<string>,\n plan: { readonly containerId: string },\n carriedPlans: readonly { readonly plan: { readonly containerId: string } }[],\n): void {\n repairedIds.add(plan.containerId);\n for (const carried of carriedPlans) {\n repairedIds.add(carried.plan.containerId);\n }\n}\n\nasync function commitRepairPrefix(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n repairedIds: Set<string>;\n sync: SyncRemoteDocumentInput;\n}): Promise<number> {\n let committed = 0;\n for (const { plan, writerProjection } of input.plans) {\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n if (input.sync.isRemoteSyncBlocked?.(plan.state.organizationId)) {\n throw new DocumentAncestorRepairAbandonedError(\"blocked\");\n }\n if (input.repairedIds.has(plan.containerId)) {\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n const { carriedPlans, result } = await submitStandaloneRepair(\n input.sync,\n plan,\n writerProjection,\n );\n const response = result.ok ? result.data : null;\n // Deliberately not ContainerKekRepairRequiredError: that is classified as\n // retryable, so a handled refusal would re-sign the whole prefix before\n // failing again, and the retry never reaches onTerminalSubmitFailure\n // regardless, because this throws before submission.\n if (!response) {\n return abandonRefusedRepair(input.sync, plan.containerId, result);\n }\n // What a repair carried committed with it, so the pins advance together.\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.sync.execSql,\n plans: [plan, ...carriedPlans.map((carried) => carried.plan)],\n responses: [response, ...(response.containerRekeys ?? [])],\n stillCurrent: input.sync.stillCurrent,\n });\n if (!acknowledged) {\n // A refused guarded transaction is usually a generation flip; surface it\n // as the shared cancellation so syncRemoteDocument returns null instead\n // of reporting a routine flip as a sync failure.\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n throw new Error(\"Document ancestor repair was superseded\");\n }\n markRepaired(input.repairedIds, plan, carriedPlans);\n committed += 1 + carriedPlans.length;\n // The rest of this prefix was signed before the carry. A plan for a carried\n // container extends a superseded head, and one below it pins an epoch that\n // was never minted. Stop here; the caller refetches and re-plans.\n if (carriedPlans.length > 0) return committed;\n }\n return committed;\n}\n\n/**\n * Large repairs commit a bounded prefix; the last batch stays atomic with content.\n * A tighter local resource budget may be used, but never above the protocol cap.\n */\nexport async function prepareAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n maxRepairs = MAX_CONTAINER_PATH_LENGTH,\n): Promise<{\n plans: readonly MaterializedContainerRekeyPlan[];\n projection: DocumentWriterProjectionResponse;\n}> {\n if (initialProjection.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n let projection = initialProjection;\n const repairedIds = new Set<string>();\n // `repairedIds` only breaks a loop within one preparation. An explicit sync\n // retry starts another preparation with a fresh set. Bound the\n // work by the deepest authorizing path the protocol allows, counted across\n // the whole pass rather than per call: no honest chain needs more repairs\n // than that, so re-entry cannot multiply the budget.\n for (;;) {\n const batch = await buildAutomaticContainerRekeys(sync, projection);\n const commitsStandalone =\n batch.hasMore ||\n (batch.plans.length > 0 && standaloneRepairPasses.has(sync));\n if (!commitsStandalone) return { plans: batch.plans, projection };\n // Standalone mutations require authentic document scope before any request.\n // Persist the verified heads here, unlike the inline path: a committed\n // repair is acknowledged against the latest durable pin, and a repaired\n // ancestor is always past epoch 1, so a device that has never pinned it\n // would reject its own acknowledgement after the server already committed\n // the rekey. The inline path needs no pin because the sync response\n // re-verifies and pins before anything is acknowledged.\n await assertDocumentWriterProjectionConsistent(projection, {\n ...projectionVerificationOptions(sync),\n persistVerificationCheckpoints: true,\n allowStaleContentKeyBundle: true,\n });\n // Charge what this prefix can still commit, then settle to what it did: it\n // stops early after a repair that carried something, and charging the plans\n // it never submitted would spend the budget on work that did not happen.\n const committedBefore = passRepairTotals.get(sync) ?? 0;\n if (\n committedBefore + batch.plans.length >\n Math.min(maxRepairs, MAX_CONTAINER_PATH_LENGTH)\n ) {\n throw new DocumentAncestorRepairAbandonedError(\"depth-budget\");\n }\n passRepairTotals.set(\n sync,\n committedBefore +\n (await commitRepairPrefix({ plans: batch.plans, repairedIds, sync })),\n );\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n // Always a write-bearing pass, so a terminal projection failure (a 403\n // after revocation mid-repair) must leave the durable record that the\n // queued writes are blocked. onReadOnlyProjectionFailure is documented\n // for passes without queued writes and would not apply here.\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n if (!fresh) {\n // refreshSyncAttemptWriterProjection returns null on a generation flip.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n // It has already called onSyncAbandoned by this point, and on a coded 404\n // ran the verified local teardown, so a bare Error would double-signal as\n // an abandon plus a sync-lane crash.\n throw new DocumentAncestorRepairAbandonedError(\"unrefreshable\");\n }\n // The scope check above guards the first round only; a refetched projection\n // is server-supplied too, and nothing in the refresh path proves it names\n // the document this repair is for.\n if (fresh.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n projection = fresh;\n }\n}\n\n/** An explicit preparation retry may commit repairs; plan retries never do. */\nexport async function prepareSyncAttemptContainerRekeys(\n sync: SyncRemoteDocumentInput,\n projection: DocumentWriterProjectionResponse,\n) {\n try {\n return await prepareAutomaticContainerRekeys(sync, projection);\n } catch (error) {\n if (\n !sync.apiClient.evictDocumentWriterProjection ||\n !shouldRetrySyncWithFreshWriterProjection(error)\n )\n throw error;\n }\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n return fresh ? prepareAutomaticContainerRekeys(sync, fresh) : null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":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mC;QACnC,IAAI,KAAK,CAAC,UAAU,KAAK,IAAI,CAAC,UAAU,EAAE,CAAC;YACzC,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;QACJ,CAAC;QACD,UAAU,GAAG,KAAK,CAAC;IACrB,CAAC;AACH,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,IAA4B,EAC5B,UAA4C;IAE5C,IAAI,CAAC;QACH,OAAO,MAAM,+BAA+B,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IACjE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IACE,CAAC,IAAI,CAAC,SAAS,CAAC,6BAA6B;YAC7C,CAAC,wCAAwC,CAAC,KAAK,CAAC;YAEhD,MAAM,KAAK,CAAC;IAChB,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC;QACrD,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;QACrD,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,iBAAiB,EAAE,IAAI,CAAC,uBAAuB;QAC/C,YAAY,EAAE,IAAI,CAAC,YAAY;KAChC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,CAAC,CAAC,+BAA+B,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { acknowledgeContainerMutationBatch } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n submitContainerRotation,\n submitRotationCarryingDescendants,\n} from \"../../containers/child/mutationSubmit\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { shouldRetrySyncWithFreshWriterProjection } from \"../syncFailures/syncFailureClassification\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\n\n/**\n * Repairs committed during one sync pass, keyed by the pass object that one\n * `syncRemoteDocument` call builds and hands to all three attempts. The sync\n * loop explicitly prepares each attempt, so a counter local to one call would\n * not bound the whole pass.\n */\nconst passRepairTotals = new WeakMap<RemoteDocumentSyncPass, number>();\n\n/**\n * Passes whose inline repairs the server refused for stranding a level above a\n * directly granted container. The write's flat rekey list cannot say which\n * descendants each repair must carry; a standalone rekey can, so the rest of\n * the pass commits every repair standalone before writing.\n */\nconst standaloneRepairPasses = new WeakSet<RemoteDocumentSyncPass>();\n\nexport function requiresStandaloneAncestorRepairs(\n sync: RemoteDocumentSyncPass,\n): boolean {\n return standaloneRepairPasses.has(sync);\n}\n\nexport function requireStandaloneAncestorRepairs(\n sync: RemoteDocumentSyncPass,\n): void {\n standaloneRepairPasses.add(sync);\n}\n\n/** A refusal the writer cannot clear by retrying, as opposed to 5xx/offline. */\nfunction isTerminalRepairStatus(status: number | null): boolean {\n return status === 401 || status === 402 || status === 403;\n}\n\n/**\n * One standalone repair. Prefers the status-bearing rekey: a permanent refusal\n * (403 once ancestor write access is revoked, 402) must leave a durable record,\n * while a 5xx or an offline blip must not, and plain `rekeyContainer` collapses\n * both to null. It is also the only way to learn which descendant rekeys this\n * repair must carry. An adapter without it still repairs; its refusals are just\n * reported as an ordinary abandon.\n */\nfunction submitStandaloneRepair(\n sync: RemoteDocumentSyncPass,\n plan: MaterializedContainerRekeyPlan[\"plan\"],\n writerProjection: MaterializedContainerRekeyPlan[\"writerProjection\"],\n) {\n const options = {\n expectedPaymentRequiredOrganizationId: plan.state.organizationId,\n };\n const { getContainerWriterProjection, rekeyContainerResult } = sync.apiClient;\n return submitRotationCarryingDescendants({\n carriedRekeys: getContainerWriterProjection && {\n planning: {\n apiClient: {\n getContainerWriterProjection: getContainerWriterProjection.bind(\n sync.apiClient,\n ),\n },\n author: sync.author,\n execSql: sync.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n sync.resolveProjectionUserKey,\n \"Document ancestor repair\",\n ),\n stillCurrent: sync.stillCurrent,\n targetSecretKey: sync.targetSecretKey,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n },\n rotated: async () => writerProjection,\n },\n stillCurrent: sync.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...plan.request, containerRekeys: [...carried] }\n : plan.request;\n return submitContainerRotation({\n plain: () =>\n sync.apiClient.rekeyContainer(plan.containerId, request, options),\n result: rekeyContainerResult\n ? () =>\n rekeyContainerResult.call(\n sync.apiClient,\n plan.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n\nasync function abandonRefusedRepair(\n sync: RemoteDocumentSyncPass,\n containerId: string,\n result: Awaited<ReturnType<typeof submitStandaloneRepair>>[\"result\"],\n): Promise<never> {\n if (!result.ok && isTerminalRepairStatus(result.status)) {\n await sync.onTerminalSubmitFailure?.({\n code: \"document_ancestor_repair_refused\",\n message: `Ancestor repair refused for ${containerId}`,\n ok: false,\n report: () => undefined,\n status: result.status,\n });\n }\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n}\n\n/** A repair and everything it carried committed together. */\nfunction markRepaired(\n repairedIds: Set<string>,\n plan: { readonly containerId: string },\n carriedPlans: readonly { readonly plan: { readonly containerId: string } }[],\n): void {\n repairedIds.add(plan.containerId);\n for (const carried of carriedPlans) {\n repairedIds.add(carried.plan.containerId);\n }\n}\n\nasync function commitRepairPrefix(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n repairedIds: Set<string>;\n sync: RemoteDocumentSyncPass;\n}): Promise<number> {\n let committed = 0;\n for (const { plan, writerProjection } of input.plans) {\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n if (input.sync.isRemoteSyncBlocked?.(plan.state.organizationId)) {\n throw new DocumentAncestorRepairAbandonedError(\"blocked\");\n }\n if (input.repairedIds.has(plan.containerId)) {\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n const { carriedPlans, result } = await submitStandaloneRepair(\n input.sync,\n plan,\n writerProjection,\n );\n const response = result.ok ? result.data : null;\n // Deliberately not ContainerKekRepairRequiredError: that is classified as\n // retryable, so a handled refusal would re-sign the whole prefix before\n // failing again, and the retry never reaches onTerminalSubmitFailure\n // regardless, because this throws before submission.\n if (!response) {\n return abandonRefusedRepair(input.sync, plan.containerId, result);\n }\n // What a repair carried committed with it, so the pins advance together.\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.sync.execSql,\n plans: [plan, ...carriedPlans.map((carried) => carried.plan)],\n responses: [response, ...(response.containerRekeys ?? [])],\n stillCurrent: input.sync.stillCurrent,\n });\n if (!acknowledged) {\n // A refused guarded transaction is usually a generation flip; surface it\n // as the shared cancellation so syncRemoteDocument returns null instead\n // of reporting a routine flip as a sync failure.\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n throw new Error(\"Document ancestor repair was superseded\");\n }\n markRepaired(input.repairedIds, plan, carriedPlans);\n committed += 1 + carriedPlans.length;\n // The rest of this prefix was signed before the carry. A plan for a carried\n // container extends a superseded head, and one below it pins an epoch that\n // was never minted. Stop here; the caller refetches and re-plans.\n if (carriedPlans.length > 0) return committed;\n }\n return committed;\n}\n\n/**\n * Large repairs commit a bounded prefix; the last batch stays atomic with content.\n * A tighter local resource budget may be used, but never above the protocol cap.\n */\nexport async function prepareAutomaticContainerRekeys(\n sync: RemoteDocumentSyncPass,\n initialProjection: DocumentWriterProjectionResponse,\n maxRepairs = MAX_CONTAINER_PATH_LENGTH,\n): Promise<{\n plans: readonly MaterializedContainerRekeyPlan[];\n projection: DocumentWriterProjectionResponse;\n}> {\n if (initialProjection.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n let projection = initialProjection;\n const repairedIds = new Set<string>();\n // `repairedIds` only breaks a loop within one preparation. An explicit sync\n // retry starts another preparation with a fresh set. Bound the\n // work by the deepest authorizing path the protocol allows, counted across\n // the whole pass rather than per call: no honest chain needs more repairs\n // than that, so re-entry cannot multiply the budget.\n for (;;) {\n const batch = await buildAutomaticContainerRekeys(sync, projection);\n const commitsStandalone =\n batch.hasMore ||\n (batch.plans.length > 0 && standaloneRepairPasses.has(sync));\n if (!commitsStandalone) return { plans: batch.plans, projection };\n // Standalone mutations require authentic document scope before any request.\n // Persist the verified heads here, unlike the inline path: a committed\n // repair is acknowledged against the latest durable pin, and a repaired\n // ancestor is always past epoch 1, so a device that has never pinned it\n // would reject its own acknowledgement after the server already committed\n // the rekey. The inline path needs no pin because the sync response\n // re-verifies and pins before anything is acknowledged.\n await assertDocumentWriterProjectionConsistent(projection, {\n ...projectionVerificationOptions(sync),\n persistVerificationCheckpoints: true,\n allowStaleContentKeyBundle: true,\n });\n // Charge what this prefix can still commit, then settle to what it did: it\n // stops early after a repair that carried something, and charging the plans\n // it never submitted would spend the budget on work that did not happen.\n const committedBefore = passRepairTotals.get(sync) ?? 0;\n if (\n committedBefore + batch.plans.length >\n Math.min(maxRepairs, MAX_CONTAINER_PATH_LENGTH)\n ) {\n throw new DocumentAncestorRepairAbandonedError(\"depth-budget\");\n }\n passRepairTotals.set(\n sync,\n committedBefore +\n (await commitRepairPrefix({ plans: batch.plans, repairedIds, sync })),\n );\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n // Always a write-bearing pass, so a terminal projection failure (a 403\n // after revocation mid-repair) must leave the durable record that the\n // queued writes are blocked. onReadOnlyProjectionFailure is documented\n // for passes without queued writes and would not apply here.\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n if (!fresh) {\n // refreshSyncAttemptWriterProjection returns null on a generation flip.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n // It has already called onSyncAbandoned by this point, and on a coded 404\n // ran the verified local teardown, so a bare Error would double-signal as\n // an abandon plus a sync-lane crash.\n throw new DocumentAncestorRepairAbandonedError(\"unrefreshable\");\n }\n // The scope check above guards the first round only; a refetched projection\n // is server-supplied too, and nothing in the refresh path proves it names\n // the document this repair is for.\n if (fresh.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n projection = fresh;\n }\n}\n\n/** An explicit preparation retry may commit repairs; plan retries never do. */\nexport async function prepareSyncAttemptContainerRekeys(\n sync: RemoteDocumentSyncPass,\n projection: DocumentWriterProjectionResponse,\n) {\n try {\n return await prepareAutomaticContainerRekeys(sync, projection);\n } catch (error) {\n if (\n !sync.apiClient.evictDocumentWriterProjection ||\n !shouldRetrySyncWithFreshWriterProjection(error)\n )\n throw error;\n }\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n return fresh ? prepareAutomaticContainerRekeys(sync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;QACnB,kBAAkB,EAChB,KAAK,CAAC,kBAAkB,KAAK,SAAS;YACpC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,kBAAkB;YAC/B,CAAC,CAAC,KAAK,CAAC,kBAAkB;QAC9B,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACnC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,8BAA8B,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;QACtE,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;QAC9D,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ;QAC7B,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe;QAC3C,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC,IAAI,CAAC;KAC7C,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport type {
|
|
1
|
+
{"version":3,"file":"syncContainerRekeys.js","sourceRoot":"","sources":["syncContainerRekeys.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAGxH,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,iCAAiC,EAAE,MAAM,8BAA8B,CAAC;AACjF,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC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EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ;QAC7B,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe;QAC3C,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC,IAAI,CAAC;KAC7C,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { DocumentSyncPreparationRequiredError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildMaterializedDocumentSyncPlan } from \"../syncPlan/syncPlanMaterial\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\nimport { requiresStandaloneAncestorRepairs } from \"./syncContainerRekeyPreparation\";\nimport { applyDocumentSyncContainerRekeys } from \"./syncContainerRekeyProjection\";\nimport { computeInlineRekeyCommitId } from \"./syncRekeyCommit\";\n\n/** Plan only: standalone server repairs belong to the outer sync attempt. */\nexport async function buildRemoteDocumentSyncPlan(input: {\n preparedRekeys?: readonly MaterializedContainerRekeyPlan[] | undefined;\n /** The version the request advertises; defaults to the sync's live one. */\n localVersionVector?: string | null | undefined;\n minLsn?: string | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullCursor?: string | undefined;\n projection: DocumentWriterProjectionResponse;\n regenerateQueuedCheckpoints: boolean;\n sync: RemoteDocumentSyncPass;\n}) {\n // Repairing this document's own container moves its key target hash, which\n // marks the content-key bundle stale. Only a pass that can build a rotation\n // snapshot is able to heal that; rotation settlement deliberately cannot\n // (`syncRequest.ts` omits the builder for `allowRecoveryBaseline: false`), so\n // repairing there would trade a classified \"ancestor repair required\" failure\n // for an unhealable bundle — after a standalone prefix may already have been\n // committed. Such a pass is left to fail as it did before automatic repair.\n const canHealStaleBundle = input.sync.buildRotationSnapshot !== undefined;\n let automaticPlans = input.preparedRekeys;\n if (\n input.pendingUpdates.length &&\n !input.sync.buildContainerRekeys &&\n canHealStaleBundle &&\n automaticPlans === undefined\n ) {\n const batch = await buildAutomaticContainerRekeys(\n input.sync,\n input.projection,\n );\n if (\n batch.hasMore ||\n (batch.plans.length > 0 && requiresStandaloneAncestorRepairs(input.sync))\n ) {\n throw new DocumentSyncPreparationRequiredError();\n }\n automaticPlans = batch.plans;\n }\n const rekeyPlans =\n input.pendingUpdates.length && input.sync.buildContainerRekeys\n ? await input.sync.buildContainerRekeys(input.projection, {\n persistVerificationCheckpoints: false,\n })\n : automaticPlans;\n const writerProjection = rekeyPlans?.length\n ? await applyDocumentSyncContainerRekeys({\n plans: rekeyPlans,\n writerProjection: input.projection,\n })\n : input.projection;\n let inlineRekeyCommitId: string | undefined;\n if (rekeyPlans?.length) {\n const headPendingUpdate = input.pendingUpdates[0];\n if (!headPendingUpdate) {\n throw new Error(\"Document inline rekey pending queue is empty\");\n }\n inlineRekeyCommitId = await computeInlineRekeyCommitId({\n headPendingUpdateId: headPendingUpdate.id,\n projection: input.projection,\n });\n }\n return buildMaterializedDocumentSyncPlan({\n author: input.sync.author,\n buildRotationSnapshot: input.sync.buildRotationSnapshot,\n containerRekeys: rekeyPlans?.map(({ plan }) => plan.request),\n execSql: input.sync.execSql,\n historyMode: input.sync.historyMode,\n inlineRekeyCommitId,\n localVersionVector:\n input.localVersionVector === undefined\n ? input.sync.localVersionVector\n : input.localVersionVector,\n minLsn: input.minLsn,\n onSyncTrace: input.sync.onSyncTrace,\n pendingUpdates: input.pendingUpdates,\n persistVerificationCheckpoints: rekeyPlans?.length ? false : undefined,\n pullCursor: input.pullCursor,\n regenerateQueuedCheckpoints: input.regenerateQueuedCheckpoints,\n signedAt: input.sync.signedAt,\n targetSecretKey: input.sync.targetSecretKey,\n writerProjection,\n ...projectionVerificationOptions(input.sync),\n });\n}\n"]}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import type { SyncRemoteDocumentResult } from "../../../data/documents/shared/sync/documentSyncTypes.js";
|
|
2
|
-
import { type SyncRemoteDocumentInput } from "./readOnlySync.js";
|
|
3
|
-
export declare function syncRemoteDocument(input: SyncRemoteDocumentInput): Promise<SyncRemoteDocumentResult | null>;
|