@tearleads/client-sdk 0.1.243 → 0.1.244
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/client/organizations/principalMutations.d.ts +5 -0
- package/data/containers/shared/mutationAcknowledgement.d.ts +1 -1
- package/data/containers/shared/mutationAcknowledgement.js +3 -8
- package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
- package/data/documents/shared/sync/mutationAcknowledgement.js +11 -2
- package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -1
- package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.d.ts +26 -0
- package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js +46 -0
- package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js.map +1 -0
- package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +7 -4
- package/data/keyingProjectionVerification/container/containerDestinationVerification.js +5 -1
- package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js +9 -2
- package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/document/documentContainerProjections.js +2 -1
- package/data/keyingProjectionVerification/document/documentContainerProjections.js.map +1 -1
- package/data/keyingProjectionVerification/document/documentProjectionVerification.js +9 -2
- package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/index.d.ts +1 -0
- package/data/keyingProjectionVerification/index.js +1 -0
- package/data/keyingProjectionVerification/index.js.map +1 -1
- package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js +16 -4
- package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js.map +1 -1
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +13 -0
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +11 -0
- package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
- package/data/persistence/verifiedCitations/authoredBundleCitation.d.ts +20 -0
- package/data/persistence/verifiedCitations/authoredBundleCitation.js +32 -0
- package/data/persistence/verifiedCitations/authoredBundleCitation.js.map +1 -0
- package/data/persistence/verifiedManifestBundlePersistence.d.ts +10 -0
- package/data/persistence/verifiedManifestBundlePersistence.js +95 -9
- package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +55 -0
- package/internal/api-client/client/containerMutations.d.ts +11 -0
- package/internal/api-client/client/documents.d.ts +5 -0
- package/internal/api-client/client/organizations.d.ts +20 -0
- package/internal/api-client/client/principalPolicies.d.ts +9 -0
- package/internal/api-client/client/session.d.ts +10 -0
- package/internal/api-client/principalPolicyRequests.d.ts +7 -0
- package/internal/api-client/writerProjectionCitations.d.ts +3 -0
- package/internal/api-client/writerProjectionCitations.js +12 -0
- package/internal/api-client/writerProjectionCitations.js.map +1 -1
- package/internal/crypto/index.d.ts +1 -1
- package/internal/crypto/index.js +1 -1
- package/internal/crypto/index.js.map +1 -1
- package/internal/crypto/keying/canonicalJsonGuard.d.ts +13 -0
- package/internal/crypto/keying/canonicalJsonGuard.js +23 -0
- package/internal/crypto/keying/canonicalJsonGuard.js.map +1 -1
- package/internal/crypto/keying/index.d.ts +1 -1
- package/internal/crypto/keying/index.js +1 -1
- package/internal/crypto/keying/index.js.map +1 -1
- package/internal/crypto/keying/keyingHashDomains.d.ts +1 -1
- package/internal/crypto/keying/keyingHashDomains.js.map +1 -1
- package/internal/validators/operation/auth.d.ts +40 -0
- package/internal/validators/operation/containerMutations.d.ts +44 -0
- package/internal/validators/operation/documentMutations.d.ts +12 -0
- package/internal/validators/operation/organizations.d.ts +48 -0
- package/internal/validators/operation/principals.d.ts +16 -0
- package/internal/validators/response/areas/containers.d.ts +1 -1
- package/internal/validators/response/areas/containers.js +1 -1
- package/internal/validators/response/areas/containers.js.map +1 -1
- package/internal/validators/response/container.d.ts +16 -0
- package/internal/validators/response/container.js +3 -0
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/containerMetadata.d.ts +8 -0
- package/internal/validators/response/documentMutation.d.ts +8 -0
- package/internal/validators/response/documentMutation.js +2 -1
- package/internal/validators/response/documentMutation.js.map +1 -1
- package/internal/validators/response/organization.d.ts +8 -0
- package/internal/validators/response/organizationProvisioning.d.ts +113 -0
- package/internal/validators/response/organizationProvisioning.js +2 -1
- package/internal/validators/response/organizationProvisioning.js.map +1 -1
- package/internal/validators/response/principal.d.ts +16 -0
- package/internal/validators/response/registration.d.ts +40 -0
- package/internal/validators/response/writerProjectionWire.d.ts +25 -0
- package/internal/validators/response/writerProjectionWire.js +109 -3
- package/internal/validators/response/writerProjectionWire.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/rotation/index.js +3 -1
- package/stores/documents/documentStore/rotation/index.js.map +1 -1
- package/stores/documents/documentStore/sync/syncAttachments.js +4 -1
- package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
- package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -1
- package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
- package/stores/documents/documentStore/sync/syncRequest.js +3 -1
- package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
- package/workflows/container-contents/container-state/create/createAdoption.js +11 -3
- package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
- package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
- package/workflows/container-contents/container-state/projectionCache.js +3 -0
- package/workflows/container-contents/container-state/projectionCache.js.map +1 -1
- package/workflows/container-contents/metadata/index.js +5 -2
- package/workflows/container-contents/metadata/index.js.map +1 -1
- package/workflows/containers/child/recite.js +4 -2
- package/workflows/containers/child/recite.js.map +1 -1
- package/workflows/documents/create/createAdoption.js +11 -2
- package/workflows/documents/create/createAdoption.js.map +1 -1
- package/workflows/documents/create/createResponse.js +1 -0
- package/workflows/documents/create/createResponse.js.map +1 -1
- package/workflows/documents/linkSet/linkSetRemote.js +1 -0
- package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
- package/workflows/documents/sync/syncAttemptPlanning.js +8 -2
- package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
- package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +3 -2
- package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
- package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js +3 -2
- package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -1
- package/workflows/registration/organizationCreation/organizationCreationIntent.d.ts +10 -0
- package/workflows/registration/provisioningAcknowledgement.js +16 -11
- package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writerProjectionWire.js","sourceRoot":"","sources":["writerProjectionWire.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,kCAAkC,EAElC,4BAA4B,GAC7B,MAAM,SAAS,CAAC;AACjB,OAAO,EAOL,2CAA2C,EAC3C,wBAAwB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAGL,0CAA0C,GAC3C,MAAM,oBAAoB,CAAC;AAM5B;;;;;;GAMG;AACH,SAAS,eAAe,CAAC,KAA0B;IACjD,MAAM,MAAM,GAAG,IAAI,GAAG,EAAwB,CAAC;IAC/C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,OAAO;QACL,IAAI,CAAC,MAAc;YACjB,MAAM,IAAI,GAAG,MAAM,CAAC,YAAY,CAAC;YACjC,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;gBAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;iBAClC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;gBACxB,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,4BAA4B,CAAC,MAAM,CAAC,CAAC,CAAC;YACzD,OAAO,IA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AC9B,UAAU,CAAC,gCAAgC,CAAC,GAAG,CAAC,OAAO,CAAC;QAC1D,gBAAgB,EAAE,OAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC;QACtD,8BAA8B,EAC5B,UAAU,CAAC,8BAA8B,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAClB;QACH,uBAAuB,EAAE,UAAU,CAAC,uBAAuB,CAAC,GAAG,CAAC,OAAO,CAAC;KACzE,CAAC;AACJ,CAAC","sourcesContent":["import {\n type AccessManifestBundleWireResponse,\n completeServedAccessManifestBundle,\n type ServedAccessManifestBundleWireResponse,\n toServedAccessManifestBundle,\n} from \"../util\";\nimport {\n type ContainerKekResponse,\n type ContainerKekWireLevel,\n type ContainerKeyingPathResponse,\n type ContainerKeyingPathWireResponse,\n type ContainerWriterProjectionResponse,\n type ContainerWriterProjectionWireResponse,\n ContainerWriterProjectionWireResponseSchema,\n isCitedContainerKekLevel,\n} from \"./container\";\nimport {\n type DocumentWriterProjectionResponse,\n type DocumentWriterProjectionWireResponse,\n DocumentWriterProjectionWireResponseSchema,\n} from \"./documentMutation\";\n\ntype Bundle = AccessManifestBundleWireResponse;\ntype ServedBundle = ServedAccessManifestBundleWireResponse;\ntype HeldLevels = ReadonlyMap<string, ContainerKekWireLevel>;\n\n/**\n * Collects each distinct manifest once. Every slot a server fills for one\n * hash comes from the same stored row, and the client verifies the bundle it\n * receives wherever that hash is cited, so the first occurrence stands. A\n * hash the request declared known is cited but not served. A served bundle's\n * state leaves out what its own signed bytes name; decoding fills it back.\n */\nfunction bundleCitations(known: ReadonlySet<string>) {\n const byHash = new Map<string, ServedBundle>();\n const omitted = new Set<string>();\n return {\n cite(bundle: Bundle): string {\n const hash = bundle.manifestHash;\n if (known.has(hash)) omitted.add(hash);\n else if (!byHash.has(hash))\n byHash.set(hash, toServedAccessManifestBundle(bundle));\n return hash;\n },\n // fromEntries defines own data properties, even for a \"__proto__\" key.\n bundles: (): Record<string, ServedBundle> => Object.fromEntries(byHash),\n omitted: (): string[] => [...omitted],\n };\n}\n\n/** A KEK level's wire form: its manifest history cited by hash. */\nexport function containerKekWireLevel(\n kek: ContainerKekResponse,\n): ContainerKekWireLevel {\n return {\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(\n (bundle) => bundle.manifestHash,\n ),\n };\n}\n\n/**\n * The digest a request declared for a KEK level it holds, or null when the\n * level travels in full. The caller derives it from the level's own served\n * bytes, so a level is omitted only when the held copy is exactly these.\n */\nexport type HeldKekLevelDigest = (kek: ContainerKekResponse) => string | null;\n\nfunction encodeKeyingPath(\n path: ContainerKeyingPathResponse,\n cite: (bundle: Bundle) => string,\n heldLevel: HeldKekLevelDigest,\n): ContainerKeyingPathWireResponse {\n return {\n ...path,\n path: path.path.map(cite),\n containerKeks: path.containerKeks.map((kek) => {\n const level = {\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(cite),\n };\n const levelDigest = heldLevel(kek);\n return levelDigest === null\n ? level\n : {\n levelDigest,\n containerManifestHistory: level.containerManifestHistory,\n };\n }),\n };\n}\n\nconst noHeldLevels: HeldKekLevelDigest = () => null;\n\n/**\n * Call only after authorization and stored-evidence verification. `known`\n * holds the request's manifest hints; only hashes this projection cites are\n * omitted. `heldLevel` names each KEK level the request holds exactly.\n */\nexport function encodeContainerWriterProjection(\n projection: ContainerWriterProjectionResponse,\n known: ReadonlySet<string> = new Set(),\n heldLevel: HeldKekLevelDigest = noHeldLevels,\n): ContainerWriterProjectionWireResponse {\n const citations = bundleCitations(known);\n const encoded = encodeKeyingPath(projection, citations.cite, heldLevel);\n return {\n ...projection,\n ...encoded,\n bundles: citations.bundles(),\n omittedBundles: citations.omitted(),\n };\n}\n\n/** See {@link encodeContainerWriterProjection}. */\nexport function encodeDocumentWriterProjection(\n projection: DocumentWriterProjectionResponse,\n known: ReadonlySet<string> = new Set(),\n heldLevel: HeldKekLevelDigest = noHeldLevels,\n): DocumentWriterProjectionWireResponse {\n const { cite, bundles, omitted } = bundleCitations(known);\n const authorizingContainerPaths = projection.authorizingContainerPaths.map(\n (path) => encodeKeyingPath(path, cite, heldLevel),\n );\n return {\n ...projection,\n authorizingContainerPaths,\n documentContainerManifestHistory:\n projection.documentContainerManifestHistory.map(cite),\n documentManifest: cite(projection.documentManifest),\n documentManifestContainerPaths:\n projection.documentManifestContainerPaths.map((path) => path.map(cite)),\n documentManifestHistory: projection.documentManifestHistory.map(cite),\n bundles: bundles(),\n omittedBundles: omitted(),\n };\n}\n\n/**\n * Served bundles plus the exact held bytes for each omitted hash. An omission\n * the caller cannot fill from `held` (which carries only what its request\n * cited) makes the response unusable. Each bundle's state gets back the\n * fields its own signed bytes name. Each cited position receives its own\n * copy, as when every slot carried its own JSON.\n */\nfunction bundleResolver(\n bundles: Record<string, ServedBundle>,\n omittedBundles: readonly string[],\n held: ReadonlyMap<string, ServedBundle>,\n): ((hash: string) => Bundle) | null {\n const byHash = new Map(\n Object.entries(bundles).map(\n ([hash, bundle]) =>\n [hash, completeServedAccessManifestBundle(bundle)] as const,\n ),\n );\n for (const hash of omittedBundles) {\n const bundle = held.get(hash);\n if (bundle?.manifestHash !== hash) return null;\n byHash.set(hash, completeServedAccessManifestBundle(bundle));\n }\n return (hash: string): Bundle => {\n const bundle = byHash.get(hash);\n if (!bundle) {\n throw new Error(`manifest ${hash} is cited without a bundle`);\n }\n return structuredClone(bundle);\n };\n}\n\nfunction sameHashes(left: readonly string[], right: readonly string[]) {\n return (\n left.length === right.length &&\n left.every((hash, index) => hash === right[index])\n );\n}\n\n/**\n * Each cited KEK level becomes its own copy of the exact held level this\n * request declared under that digest. A digest the request did not cite, or\n * a held level whose manifest citations differ from the stub's, makes the\n * path unusable: the caller refetches in full.\n */\nfunction fillKekLevels(\n path: ContainerKeyingPathWireResponse,\n heldLevels: HeldLevels,\n): ContainerKekWireLevel[] | null {\n const levels: ContainerKekWireLevel[] = [];\n for (const kek of path.containerKeks) {\n if (!isCitedContainerKekLevel(kek)) {\n levels.push(kek);\n continue;\n }\n const held = heldLevels.get(kek.levelDigest);\n if (\n !held ||\n !sameHashes(held.containerManifestHistory, kek.containerManifestHistory)\n )\n return null;\n levels.push(structuredClone(held));\n }\n return levels;\n}\n\nfunction decodeKeyingPath(\n path: ContainerKeyingPathWireResponse,\n resolve: (hash: string) => Bundle,\n heldLevels: HeldLevels,\n): ContainerKeyingPathResponse | null {\n const levels = fillKekLevels(path, heldLevels);\n if (!levels) return null;\n return {\n ...path,\n path: path.path.map(resolve),\n containerKeks: levels.map((kek) => ({\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(resolve),\n })),\n };\n}\n\n/**\n * Null for any wire inconsistency or an omission `held` (bundles) or\n * `heldLevels` (KEK levels by digest) cannot fill; the caller treats either\n * as a shape failure.\n */\nexport function decodeContainerWriterProjection(\n value: unknown,\n held: ReadonlyMap<string, ServedBundle> = new Map(),\n heldLevels: HeldLevels = new Map(),\n): ContainerWriterProjectionResponse | null {\n const parsed = ContainerWriterProjectionWireResponseSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n const { bundles, omittedBundles, ...projection } = parsed.data;\n const resolve = bundleResolver(bundles, omittedBundles, held);\n const path = resolve\n ? decodeKeyingPath(projection, resolve, heldLevels)\n : null;\n return path ? { ...projection, ...path } : null;\n}\n\n/** See {@link decodeContainerWriterProjection}. */\nexport function decodeDocumentWriterProjection(\n value: unknown,\n held: ReadonlyMap<string, ServedBundle> = new Map(),\n heldLevels: HeldLevels = new Map(),\n): DocumentWriterProjectionResponse | null {\n const parsed = DocumentWriterProjectionWireResponseSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n const { bundles, omittedBundles, ...projection } = parsed.data;\n const resolve = bundleResolver(bundles, omittedBundles, held);\n if (!resolve) {\n return null;\n }\n const authorizingContainerPaths: ContainerKeyingPathResponse[] = [];\n for (const path of projection.authorizingContainerPaths) {\n const decoded = decodeKeyingPath(path, resolve, heldLevels);\n if (!decoded) return null;\n authorizingContainerPaths.push(decoded);\n }\n const [firstPath, ...otherPaths] = authorizingContainerPaths;\n if (!firstPath) return null;\n return {\n ...projection,\n authorizingContainerPaths: [firstPath, ...otherPaths],\n documentContainerManifestHistory:\n projection.documentContainerManifestHistory.map(resolve),\n documentManifest: resolve(projection.documentManifest),\n documentManifestContainerPaths:\n projection.documentManifestContainerPaths.map((path) =>\n path.map(resolve),\n ),\n documentManifestHistory: projection.documentManifestHistory.map(resolve),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"writerProjectionWire.js","sourceRoot":"","sources":["writerProjectionWire.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,kCAAkC,EAElC,4BAA4B,GAC7B,MAAM,SAAS,CAAC;AACjB,OAAO,EAOL,2CAA2C,EAC3C,wBAAwB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAGL,0CAA0C,GAC3C,MAAM,oBAAoB,CAAC;AAM5B;;;;;;GAMG;AACH,SAAS,eAAe,CAAC,KAA0B;IACjD,MAAM,MAAM,GAAG,IAAI,GAAG,EAAwB,CAAC;IAC/C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,OAAO;QACL,IAAI,CAAC,MAAc;YACjB,MAAM,IAAI,GAAG,MAAM,CAAC,YAAY,CAAC;YACjC,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;gBAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;iBAClC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;gBACxB,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,4BAA4B,CAAC,MAAM,CAAC,CAAC,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,uEAAuE;QACvE,OAAO,EAAE,GAAiC,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC;QACvE,OAAO,EAAE,GAAa,EAAE,CAAC,CAAC,GAAG,OAAO,CAAC;KACtC,CAAC;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C,8BAA8B,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAClB;QACH,uBAAuB,EAAE,UAAU,CAAC,uBAAuB,CAAC,GAAG,CAAC,OAAO,CAAC;KACzE,EACD,cAAc,EACd,IAAI,CACL,CAAC;AACJ,CAAC","sourcesContent":["import {\n type AccessManifestBundleWireResponse,\n completeServedAccessManifestBundle,\n type ServedAccessManifestBundleWireResponse,\n toServedAccessManifestBundle,\n} from \"../util\";\nimport {\n type ContainerKekResponse,\n type ContainerKekWireLevel,\n type ContainerKeyingPathResponse,\n type ContainerKeyingPathWireResponse,\n type ContainerWriterProjectionResponse,\n type ContainerWriterProjectionWireResponse,\n ContainerWriterProjectionWireResponseSchema,\n isCitedContainerKekLevel,\n} from \"./container\";\nimport {\n type DocumentWriterProjectionResponse,\n type DocumentWriterProjectionWireResponse,\n DocumentWriterProjectionWireResponseSchema,\n} from \"./documentMutation\";\n\ntype Bundle = AccessManifestBundleWireResponse;\ntype ServedBundle = ServedAccessManifestBundleWireResponse;\ntype HeldLevels = ReadonlyMap<string, ContainerKekWireLevel>;\n\n/**\n * Collects each distinct manifest once. Every slot a server fills for one\n * hash comes from the same stored row, and the client verifies the bundle it\n * receives wherever that hash is cited, so the first occurrence stands. A\n * hash the request declared known is cited but not served. A served bundle's\n * state leaves out what its own signed bytes name; decoding fills it back.\n */\nfunction bundleCitations(known: ReadonlySet<string>) {\n const byHash = new Map<string, ServedBundle>();\n const omitted = new Set<string>();\n return {\n cite(bundle: Bundle): string {\n const hash = bundle.manifestHash;\n if (known.has(hash)) omitted.add(hash);\n else if (!byHash.has(hash))\n byHash.set(hash, toServedAccessManifestBundle(bundle));\n return hash;\n },\n // fromEntries defines own data properties, even for a \"__proto__\" key.\n bundles: (): Record<string, ServedBundle> => Object.fromEntries(byHash),\n omitted: (): string[] => [...omitted],\n };\n}\n\n/** A KEK level's wire form: its manifest history cited by hash. */\nexport function containerKekWireLevel(\n kek: ContainerKekResponse,\n): ContainerKekWireLevel {\n return {\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(\n (bundle) => bundle.manifestHash,\n ),\n };\n}\n\n/**\n * The digest a request declared for a KEK level it holds, or null when the\n * level travels in full. The caller derives it from the level's own served\n * bytes, so a level is omitted only when the held copy is exactly these.\n */\nexport type HeldKekLevelDigest = (kek: ContainerKekResponse) => string | null;\n\nfunction encodeKeyingPath(\n path: ContainerKeyingPathResponse,\n cite: (bundle: Bundle) => string,\n heldLevel: HeldKekLevelDigest,\n): ContainerKeyingPathWireResponse {\n return {\n ...path,\n path: path.path.map(cite),\n containerKeks: path.containerKeks.map((kek) => {\n const level = {\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(cite),\n };\n const levelDigest = heldLevel(kek);\n return levelDigest === null\n ? level\n : {\n levelDigest,\n containerManifestHistory: level.containerManifestHistory,\n };\n }),\n };\n}\n\nconst noHeldLevels: HeldKekLevelDigest = () => null;\n\n/**\n * Call only after authorization and stored-evidence verification. `known`\n * holds the request's manifest hints; only hashes this projection cites are\n * omitted. `heldLevel` names each KEK level the request holds exactly.\n */\nexport function encodeContainerWriterProjection(\n projection: ContainerWriterProjectionResponse,\n known: ReadonlySet<string> = new Set(),\n heldLevel: HeldKekLevelDigest = noHeldLevels,\n): ContainerWriterProjectionWireResponse {\n const citations = bundleCitations(known);\n const encoded = encodeKeyingPath(projection, citations.cite, heldLevel);\n return {\n ...projection,\n ...encoded,\n bundles: citations.bundles(),\n omittedBundles: citations.omitted(),\n };\n}\n\n/** See {@link encodeContainerWriterProjection}. */\nexport function encodeDocumentWriterProjection(\n projection: DocumentWriterProjectionResponse,\n known: ReadonlySet<string> = new Set(),\n heldLevel: HeldKekLevelDigest = noHeldLevels,\n): DocumentWriterProjectionWireResponse {\n const { cite, bundles, omitted } = bundleCitations(known);\n const authorizingContainerPaths = projection.authorizingContainerPaths.map(\n (path) => encodeKeyingPath(path, cite, heldLevel),\n );\n return {\n ...projection,\n authorizingContainerPaths,\n documentContainerManifestHistory:\n projection.documentContainerManifestHistory.map(cite),\n documentManifest: cite(projection.documentManifest),\n documentManifestContainerPaths:\n projection.documentManifestContainerPaths.map((path) => path.map(cite)),\n documentManifestHistory: projection.documentManifestHistory.map(cite),\n bundles: bundles(),\n omittedBundles: omitted(),\n };\n}\n\n/**\n * Served bundles plus the exact held bytes for each omitted hash. An omission\n * the caller cannot fill from `held` (which carries only what its request\n * cited) makes the response unusable. Each bundle's state gets back the\n * fields its own signed bytes name. Each cited position receives its own\n * copy, as when every slot carried its own JSON.\n */\nfunction bundleResolver(\n bundles: Record<string, ServedBundle>,\n omittedBundles: readonly string[],\n held: ReadonlyMap<string, ServedBundle>,\n): ((hash: string) => Bundle) | null {\n const byHash = new Map(\n Object.entries(bundles).map(\n ([hash, bundle]) =>\n [hash, completeServedAccessManifestBundle(bundle)] as const,\n ),\n );\n for (const hash of omittedBundles) {\n const bundle = held.get(hash);\n if (bundle?.manifestHash !== hash) return null;\n byHash.set(hash, completeServedAccessManifestBundle(bundle));\n }\n return (hash: string): Bundle => {\n const bundle = byHash.get(hash);\n if (!bundle) {\n throw new Error(`manifest ${hash} is cited without a bundle`);\n }\n return structuredClone(bundle);\n };\n}\n\nfunction sameHashes(left: readonly string[], right: readonly string[]) {\n return (\n left.length === right.length &&\n left.every((hash, index) => hash === right[index])\n );\n}\n\n/**\n * Each cited KEK level becomes its own copy of the exact held level this\n * request declared under that digest. A digest the request did not cite, or\n * a held level whose manifest citations differ from the stub's, makes the\n * path unusable: the caller refetches in full.\n */\nfunction fillKekLevels(\n path: ContainerKeyingPathWireResponse,\n heldLevels: HeldLevels,\n): ContainerKekWireLevel[] | null {\n const levels: ContainerKekWireLevel[] = [];\n for (const kek of path.containerKeks) {\n if (!isCitedContainerKekLevel(kek)) {\n levels.push(kek);\n continue;\n }\n const held = heldLevels.get(kek.levelDigest);\n if (\n !held ||\n !sameHashes(held.containerManifestHistory, kek.containerManifestHistory)\n )\n return null;\n levels.push(structuredClone(held));\n }\n return levels;\n}\n\nfunction decodeKeyingPath(\n path: ContainerKeyingPathWireResponse,\n resolve: (hash: string) => Bundle,\n heldLevels: HeldLevels,\n): ContainerKeyingPathResponse | null {\n const levels = fillKekLevels(path, heldLevels);\n if (!levels) return null;\n return {\n ...path,\n path: path.path.map(resolve),\n containerKeks: levels.map((kek) => ({\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(resolve),\n })),\n };\n}\n\n// The held bundles each decoded projection took from the caller's citations\n// rather than from the response, exactly as the caller held them.\nconst heldBundlesByProjection = new WeakMap<object, readonly ServedBundle[]>();\n\n/**\n * The held bundles a decoded projection filled omissions from. A verifier\n * that refuses such a projection drops exactly those held rows, so the next\n * read fetches them from the server instead of failing the same way.\n */\nexport function heldBundlesUsedBy(projection: object): readonly ServedBundle[] {\n return heldBundlesByProjection.get(projection) ?? [];\n}\n\n// Decoded projections a verifier refused after they took held bundles: a\n// cache must not hand one out again.\nconst rejectedProjections = new WeakSet<object>();\n// A projection derived from a decoded one (a path of a document projection,\n// a sliced path) answers for the decoded projection it came from.\nconst decodedOrigins = new WeakMap<object, object>();\n\n/**\n * Carries a decoded projection's held bundles to a projection built from it,\n * so a refusal of the derived one drops those bundles and refuses the decoded\n * projection a cache holds.\n */\nexport function deriveDecodedProjection<T extends object>(\n from: object,\n to: T,\n): T {\n const held = heldBundlesByProjection.get(from);\n if (held) {\n // Only the held bundles this projection still carries: verifying it\n // vouches for those and no others.\n const carried = manifestHashesIn(to);\n const kept = held.filter((bundle) => carried.has(bundle.manifestHash));\n if (kept.length > 0) heldBundlesByProjection.set(to, kept);\n }\n decodedOrigins.set(to, decodedOrigins.get(from) ?? from);\n return to;\n}\n\nfunction manifestHashesIn(value: unknown, found = new Set<string>()) {\n if (Array.isArray(value)) {\n for (const item of value) manifestHashesIn(item, found);\n } else if (typeof value === \"object\" && value !== null) {\n for (const [key, child] of Object.entries(value)) {\n if (key === \"manifestHash\" && typeof child === \"string\") found.add(child);\n else manifestHashesIn(child, found);\n }\n }\n return found;\n}\n\n// The exact held bytes refused projections took: any other projection\n// rebuilt from the same bytes is refused with them.\nconst rejectedHeldBytes = new Set<string>();\nconst MAX_REJECTED_HELD_BUNDLES = 64;\n\n/** Marks a decoded projection refused, so no cache serves it again. */\nexport function rejectDecodedProjection(projection: object): void {\n rejectedProjections.add(projection);\n const origin = decodedOrigins.get(projection);\n if (origin) rejectedProjections.add(origin);\n for (const bundle of heldBundlesUsedBy(projection)) {\n rejectedHeldBytes.add(JSON.stringify(bundle));\n // Bounded: the oldest refusals go first. Their projections stay refused\n // by identity; only rebuilds from the same bytes are no longer caught.\n if (rejectedHeldBytes.size > MAX_REJECTED_HELD_BUNDLES) {\n const [oldest] = rejectedHeldBytes;\n if (oldest !== undefined) rejectedHeldBytes.delete(oldest);\n }\n }\n}\n\n/**\n * Whether a projection, or the decoded projection it was derived from, was\n * refused: refusing any projection built from a decoded one refuses every\n * other projection built from it too.\n */\n/**\n * A projection whose held bundles just verified: those bytes are good again\n * for every other projection rebuilt from them.\n */\nexport function acceptDecodedProjection(projection: object): void {\n if (rejectedHeldBytes.size === 0) return;\n for (const bundle of heldBundlesUsedBy(projection))\n rejectedHeldBytes.delete(JSON.stringify(bundle));\n}\n\nexport function isRejectedDecodedProjection(projection: unknown): boolean {\n if (typeof projection !== \"object\" || projection === null) return false;\n const origin = decodedOrigins.get(projection);\n return (\n rejectedProjections.has(projection) ||\n (origin !== undefined && rejectedProjections.has(origin)) ||\n (rejectedHeldBytes.size > 0 &&\n heldBundlesUsedBy(projection).some((bundle) =>\n rejectedHeldBytes.has(JSON.stringify(bundle)),\n ))\n );\n}\n\nfunction withHeldBundles<T extends object>(\n projection: T,\n omittedBundles: readonly string[],\n held: ReadonlyMap<string, ServedBundle>,\n): T {\n const used = omittedBundles.flatMap((hash) => {\n const bundle = held.get(hash);\n return bundle ? [bundle] : [];\n });\n if (used.length > 0) heldBundlesByProjection.set(projection, used);\n return projection;\n}\n\n/**\n * Null for any wire inconsistency or an omission `held` (bundles) or\n * `heldLevels` (KEK levels by digest) cannot fill; the caller treats either\n * as a shape failure.\n */\nexport function decodeContainerWriterProjection(\n value: unknown,\n held: ReadonlyMap<string, ServedBundle> = new Map(),\n heldLevels: HeldLevels = new Map(),\n): ContainerWriterProjectionResponse | null {\n const parsed = ContainerWriterProjectionWireResponseSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n const { bundles, omittedBundles, ...projection } = parsed.data;\n const resolve = bundleResolver(bundles, omittedBundles, held);\n const path = resolve\n ? decodeKeyingPath(projection, resolve, heldLevels)\n : null;\n return path\n ? withHeldBundles({ ...projection, ...path }, omittedBundles, held)\n : null;\n}\n\n/** See {@link decodeContainerWriterProjection}. */\nexport function decodeDocumentWriterProjection(\n value: unknown,\n held: ReadonlyMap<string, ServedBundle> = new Map(),\n heldLevels: HeldLevels = new Map(),\n): DocumentWriterProjectionResponse | null {\n const parsed = DocumentWriterProjectionWireResponseSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n const { bundles, omittedBundles, ...projection } = parsed.data;\n const resolve = bundleResolver(bundles, omittedBundles, held);\n if (!resolve) {\n return null;\n }\n const authorizingContainerPaths: ContainerKeyingPathResponse[] = [];\n for (const path of projection.authorizingContainerPaths) {\n const decoded = decodeKeyingPath(path, resolve, heldLevels);\n if (!decoded) return null;\n authorizingContainerPaths.push(decoded);\n }\n const [firstPath, ...otherPaths] = authorizingContainerPaths;\n if (!firstPath) return null;\n return withHeldBundles(\n {\n ...projection,\n authorizingContainerPaths: [firstPath, ...otherPaths],\n documentContainerManifestHistory:\n projection.documentContainerManifestHistory.map(resolve),\n documentManifest: resolve(projection.documentManifest),\n documentManifestContainerPaths:\n projection.documentManifestContainerPaths.map((path) =>\n path.map(resolve),\n ),\n documentManifestHistory: projection.documentManifestHistory.map(resolve),\n },\n omittedBundles,\n held,\n );\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { encodeVersionVector, versionVectorsEqual } from "../../../../internal/loro/index.js";
|
|
2
|
+
import { isRejectedDecodedProjection } from "../../../../internal/validators/response/index.js";
|
|
2
3
|
import { createDocumentWriterPublicKeyResolver, RemoteDocumentService, readPullContinuation, resolveDocumentCreateAuthor, validateDocumentSyncUpdateImports, } from "../../../../workflows/documents/index.js";
|
|
3
4
|
import { requestDocumentStoreSync } from "../../registry.js";
|
|
4
5
|
import { installRebuiltDocument } from "../history/historyRebuild.js";
|
|
@@ -62,7 +63,8 @@ async function pullVerifiedRawHistoryForRotation(input) {
|
|
|
62
63
|
let pullContinuation;
|
|
63
64
|
const seenPullCursors = new Set();
|
|
64
65
|
let planningRecord = input.currentRecord;
|
|
65
|
-
let writerProjection = input.state.writerProjection?.documentId === documentId
|
|
66
|
+
let writerProjection = input.state.writerProjection?.documentId === documentId &&
|
|
67
|
+
!isRejectedDecodedProjection(input.state.writerProjection)
|
|
66
68
|
? input.state.writerProjection
|
|
67
69
|
: undefined;
|
|
68
70
|
while (true) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EACL,qCAAqC,EAGrC,qBAAqB,EACrB,oBAAoB,EACpB,2BAA2B,EAE3B,iCAAiC,GAClC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAA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earleads/loro\";\nimport {\n createDocumentWriterPublicKeyResolver,\n type DocumentRotationProofMode,\n type DocumentSyncPullContinuation,\n RemoteDocumentService,\n readPullContinuation,\n resolveDocumentCreateAuthor,\n type SyncRemoteDocumentResult,\n validateDocumentSyncUpdateImports,\n} from \"../../../../workflows/documents\";\n\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { installRebuiltDocument } from \"../history/historyRebuild\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { listPendingUpdates } from \"../persistence\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { runDocumentRemoteWork } from \"../sync/remoteWork\";\nimport {\n captureDocumentStoreAttachmentSyncGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreSyncGeneration,\n type DocumentStoreSyncLaneGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { deleteUpstreamDeletedDocument } from \"../sync/syncRequest\";\nimport { documentIncomingUpdateIsolationFailureHandler } from \"../sync/syncShared\";\nimport { importSyncedDocumentUpdates } from \"../sync/syncUpdateImport\";\nimport {\n currentRecordedRotationProof,\n recordRotationProof,\n} from \"./rotationProofRecord\";\nimport {\n assertExactDocumentHistory,\n importProvenOrdinaryPendingHistory,\n} from \"./rotationProvenance\";\nimport {\n invalidatePullContinuationBeforeRotation,\n RotationPendingUpdatesChangedError,\n settleOrdinaryDocumentUpdatesBeforeRotation,\n} from \"./rotationSettlement\";\n\nfunction ordinaryRawHistoryUpdates<T extends { checkpointKind?: string }>(\n updates: readonly T[],\n): T[] {\n return updates.filter((update) => update.checkpointKind === undefined);\n}\n\nfunction assertRotationRecoveryPrerequisites(state: DocumentStoreState) {\n if (state.persistence.supportsAtomicRecoveryHistoryPruning !== true) {\n throw new Error(\n \"Rotation raw-history recovery requires an adapter with atomic local-history pruning\",\n );\n }\n const author = resolveDocumentCreateAuthor(state.runtime);\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n const documentId = state.record?.documentId;\n if (\n !author ||\n !encapsulationKeyPair ||\n !documentId ||\n !state.runtime.auth.isAuthenticated ||\n !state.runtime.state.online\n ) {\n throw new Error(\n \"Rotation requires verified full-history recovery, but remote sync prerequisites are unavailable\",\n );\n }\n return { author, documentId, encapsulationKeyPair };\n}\n\nfunction assertRotationRecoveryGeneration(input: {\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): void {\n if (!isDocumentStoreSyncGenerationCurrent(input.state, input.generation)) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n}\n\nfunction rotationIncomingUpdateIsolation(input: {\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n return {\n onIncomingUpdateIsolationFailure:\n documentIncomingUpdateIsolationFailureHandler(\n input.state,\n input.generation,\n ),\n validateIncomingUpdates: async (\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\" | \"response\">,\n ) => {\n await validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n });\n const decryptedUpdates = ordinaryRawHistoryUpdates(\n result.decryptedUpdates,\n );\n const ordinaryUpdateIds = new Set(\n decryptedUpdates.map((update) => update.id),\n );\n await validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates,\n responseUpdates: result.response.updates.filter((update) =>\n ordinaryUpdateIds.has(update.id),\n ),\n });\n },\n };\n}\n\nasync function pullVerifiedRawHistoryForRotation(input: {\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n rebuiltDocument: DocumentState;\n state: DocumentStoreState;\n}) {\n const { author, documentId, encapsulationKeyPair } =\n assertRotationRecoveryPrerequisites(input.state);\n let pullContinuation: DocumentSyncPullContinuation | undefined;\n const seenPullCursors = new Set<string>();\n let planningRecord = input.currentRecord;\n let writerProjection =\n input.state.writerProjection?.documentId === documentId\n ? input.state.writerProjection\n : undefined;\n\n while (true) {\n let abandonReason: string | null = null;\n // Each page reads the live runtime, as the bag it replaced did; the key\n // stays the one the prerequisites checked.\n const remoteDocuments = new RemoteDocumentService({\n api: input.state.runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: input.state.runtime.infra.execSql,\n isRemoteSyncBlocked: input.state.runtime.util.isRemoteSyncBlocked,\n });\n const synced = await remoteDocuments.syncRemoteDocument({\n author,\n documentId,\n historyMode: \"raw\",\n localVersionVector: null,\n minLsn: input.currentRecord.lastCommitLsn ?? undefined,\n onRemoteDocumentDeleted: ({ commitPurgeProof, documentId }) =>\n deleteUpstreamDeletedDocument(\n input.state,\n input.generation,\n input.currentRecord,\n documentId,\n commitPurgeProof,\n ),\n // Recorded, never parked: this pass submits no writes, so it plans no\n // ancestor repair and cannot abandon as `inaccessible`.\n onSyncAbandoned: (reason) => {\n abandonReason = reason;\n },\n ...rotationIncomingUpdateIsolation({\n currentDocument: input.rebuiltDocument,\n generation: input.generation,\n state: input.state,\n }),\n onSyncTrace: (line) => input.state.runtime.util.log(`Documents: ${line}`),\n pendingUpdates: [],\n persistedState: planningRecord,\n pullContinuation,\n resolveProjectionUserKey: input.state.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Documents\",\n runtime: input.state.runtime,\n writerKeyLabel: \"writer key\",\n }),\n warmReferencedPrincipalPolicies:\n input.state.runtime.principalPolicies.createWarmer(),\n writerProjection,\n });\n if (!synced) {\n throw new Error(\n `Rotation raw-history recovery could not complete (${abandonReason ?? \"sync did not finish\"}); key rotation was not started`,\n );\n }\n\n assertRotationRecoveryGeneration(input);\n\n importSyncedDocumentUpdates(\n input.rebuiltDocument,\n ordinaryRawHistoryUpdates(synced.decryptedUpdates),\n );\n if (!synced.hasIncompletePull) return synced;\n\n const nextContinuation = readPullContinuation(synced.response);\n if (!nextContinuation) {\n throw new Error(\n \"Rotation raw-history recovery ended before the retained history was complete\",\n );\n }\n if (seenPullCursors.has(nextContinuation.cursor)) {\n throw new Error(\n \"Rotation raw-history recovery encountered a repeated pull cursor\",\n );\n }\n seenPullCursors.add(nextContinuation.cursor);\n pullContinuation = nextContinuation;\n planningRecord = { ...planningRecord, ...synced.persistedState };\n writerProjection = synced.writerProjection;\n }\n}\n\nasync function collectVerifiedRawHistoryForRotation(input: {\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n const consumedPullContinuation = input.state.pullContinuation;\n const writerProjectionGeneration = input.state.writerProjectionGeneration;\n const rebuiltDocument = await createStoredDocument(input.state);\n try {\n const synced = await pullVerifiedRawHistoryForRotation({\n ...input,\n rebuiltDocument,\n });\n return {\n consumedPullContinuation,\n currentRecord: input.currentRecord,\n rebuiltDocument,\n synced,\n writerProjectionGeneration,\n };\n } catch (error) {\n rebuiltDocument.free();\n throw error;\n }\n}\n\nclass RotationDocumentChangedError extends Error {}\n\nfunction assertCapturedDocumentCurrent(input: {\n capturedVersion: string;\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): void {\n assertRotationRecoveryGeneration(input);\n if (\n !versionVectorsEqual(\n encodeVersionVector(input.currentDocument),\n input.capturedVersion,\n )\n ) {\n throw new RotationDocumentChangedError(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n}\n\nfunction currentRotationRecoveryRecord(\n state: DocumentStoreState,\n): NonNullable<DocumentStoreState[\"record\"]> {\n if (state.record) return state.record;\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n}\n\nfunction installRotationRecovery(input: {\n capturedVersion: string;\n collection: Awaited<ReturnType<typeof collectVerifiedRawHistoryForRotation>>;\n currentDoc: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n const { capturedVersion, collection, currentDoc, generation, state } = input;\n const installation = state.writeChain\n .catch(() => undefined)\n .then(() =>\n chainIdentityWrite(state, async () => {\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n assertExactDocumentHistory({\n currentDocument: currentDoc,\n rebuiltDocument: collection.rebuiltDocument,\n });\n return installRebuiltDocument({\n consumedPullContinuation: collection.consumedPullContinuation,\n currentRecord: collection.currentRecord,\n generation,\n rebuiltDoc: collection.rebuiltDocument,\n state,\n synced: collection.synced,\n writerProjectionGeneration: collection.writerProjectionGeneration,\n });\n }),\n );\n // Only the checked local install occupies the write queue. Network recovery\n // uses the remote queue, so an outage cannot hold new edits hostage.\n void chainQueuedWrite(\n state,\n installation.then(\n () => undefined,\n () => undefined,\n ),\n );\n return installation;\n}\n\nasync function recoverFullHistoryForRotation(\n state: DocumentStoreState,\n laneGeneration: DocumentStoreSyncLaneGeneration,\n): Promise<Uint8Array> {\n assertRotationRecoveryPrerequisites(state);\n await invalidatePullContinuationBeforeRotation(state);\n const currentDoc = state.doc;\n const currentRecord = state.record;\n if (!currentDoc || !currentRecord) {\n throw new Error(\n \"Document must finish loading before its content key can rotate\",\n );\n }\n // The teardown guard for the recovery's terminal-failure handler: captured\n // before the pull so a discard (row 21) racing this preflight invalidates\n // it, and the stale handler cannot resurrect a deleted failure row.\n const generation = captureDocumentStoreAttachmentSyncGeneration(\n state,\n currentDoc,\n laneGeneration,\n );\n if (!generation) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n\n const capturedVersion = encodeVersionVector(currentDoc);\n let settlementRequiresRetry = false;\n\n // A raw recovery starts from an empty scratch document, bypasses untrusted\n // rotation-baseline redirects, drains every retained page in memory, and\n // publishes nothing until all response updates have validated. Checkpoints\n // are authenticated and decrypted but are not reconstruction inputs: the\n // original ordinary update stream is the source of truth in this mode.\n let collection = await collectVerifiedRawHistoryForRotation({\n currentRecord,\n generation,\n state,\n });\n\n try {\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const pendingUpdates = await listPendingUpdates(state);\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const verifiedOrdinaryVersion = importProvenOrdinaryPendingHistory({\n currentDocument: currentDoc,\n pendingUpdates,\n rebuiltDocument: collection.rebuiltDocument,\n });\n if (pendingUpdates.some((update) => update.sourceVersionVector == null)) {\n // The first raw pass proves the exact ordinary frontier before any local\n // row can be published. Pull raw history again after settlement so the\n // installed snapshot also includes remote work that raced that submit.\n await settleOrdinaryDocumentUpdatesBeforeRotation(\n state,\n verifiedOrdinaryVersion,\n pendingUpdates,\n generation,\n );\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const definitiveCollection = await collectVerifiedRawHistoryForRotation({\n currentRecord: currentRotationRecoveryRecord(state),\n generation,\n state,\n });\n collection.rebuiltDocument.free();\n collection = definitiveCollection;\n }\n const installed = await installRotationRecovery({\n capturedVersion,\n collection,\n currentDoc,\n generation,\n state,\n });\n settlementRequiresRetry = installed.settlementRequiresRetry;\n if (settlementRequiresRetry) {\n throw new Error(\n \"Rotation raw-history recovery was superseded during its atomic install; retry key rotation\",\n );\n }\n return installed.fullHistorySnapshot;\n } finally {\n if (state.doc !== collection.rebuiltDocument) {\n collection.rebuiltDocument.free();\n }\n if (settlementRequiresRetry) {\n requestDocumentStoreSync(state);\n }\n }\n}\n\n/**\n * Wait for prior local writes and serialize with other remote work. Edits can\n * continue during the pull; the checked install rejects a changed document so\n * a stale recovery cannot replace them. This preflight can then be retried.\n * `reuse` returns the last completed proof while it still covers this exact\n * local document (rotationProofRecord); otherwise it proves like `prove`.\n */\nexport function assertDocumentStoreCanRotateContentKey(\n state: DocumentStoreState,\n proof: DocumentRotationProofMode = \"prove\",\n): Promise<Uint8Array> {\n const laneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n const generation = captureDocumentStoreAttachmentSyncGeneration(\n state,\n state.doc,\n laneGeneration,\n );\n return runDocumentRemoteWork(state, async () => {\n await state.writeChain.catch(() => undefined);\n if (\n !generation ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw new Error(\n \"Document changed before rotation recovery; retry key rotation\",\n );\n }\n const recorded =\n proof === \"reuse\" ? currentRecordedRotationProof(state) : null;\n if (recorded) return recorded;\n const snapshot = await proveFullHistoryForRotation(\n state,\n laneGeneration,\n generation,\n );\n recordRotationProof(state, snapshot);\n return snapshot;\n });\n}\n\nasync function proveFullHistoryForRotation(\n state: DocumentStoreState,\n laneGeneration: DocumentStoreSyncLaneGeneration,\n generation: DocumentStoreSyncGeneration,\n): Promise<Uint8Array> {\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await recoverFullHistoryForRotation(state, laneGeneration);\n } catch (error) {\n // Autosaves and conflict re-keying can invalidate the proven frontier.\n // Repeat the complete proof without blocking new local edits; repeated\n // changes remain bounded and leave the durable queue retryable.\n if (\n !(\n error instanceof RotationPendingUpdatesChangedError ||\n error instanceof RotationDocumentChangedError\n ) ||\n attempt >= 2 ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw error;\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAC7E,OAAO,EACL,qCAAqC,EAGrC,qBAAqB,EACrB,oBAAoB,EACpB,2BAA2B,EAE3B,iCAAiC,GAClC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE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YAAY,4BAA4B,CAC9C;gBACD,OAAO,IAAI,CAAC;gBACZ,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC,EACxD,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { encodeVersionVector, versionVectorsEqual } from \"@tearleads/loro\";\nimport { isRejectedDecodedProjection } from \"@tearleads/validators/response\";\nimport {\n createDocumentWriterPublicKeyResolver,\n type DocumentRotationProofMode,\n type DocumentSyncPullContinuation,\n RemoteDocumentService,\n readPullContinuation,\n resolveDocumentCreateAuthor,\n type SyncRemoteDocumentResult,\n validateDocumentSyncUpdateImports,\n} from \"../../../../workflows/documents\";\n\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { installRebuiltDocument } from \"../history/historyRebuild\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { listPendingUpdates } from \"../persistence\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { runDocumentRemoteWork } from \"../sync/remoteWork\";\nimport {\n captureDocumentStoreAttachmentSyncGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreSyncGeneration,\n type DocumentStoreSyncLaneGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { deleteUpstreamDeletedDocument } from \"../sync/syncRequest\";\nimport { documentIncomingUpdateIsolationFailureHandler } from \"../sync/syncShared\";\nimport { importSyncedDocumentUpdates } from \"../sync/syncUpdateImport\";\nimport {\n currentRecordedRotationProof,\n recordRotationProof,\n} from \"./rotationProofRecord\";\nimport {\n assertExactDocumentHistory,\n importProvenOrdinaryPendingHistory,\n} from \"./rotationProvenance\";\nimport {\n invalidatePullContinuationBeforeRotation,\n RotationPendingUpdatesChangedError,\n settleOrdinaryDocumentUpdatesBeforeRotation,\n} from \"./rotationSettlement\";\n\nfunction ordinaryRawHistoryUpdates<T extends { checkpointKind?: string }>(\n updates: readonly T[],\n): T[] {\n return updates.filter((update) => update.checkpointKind === undefined);\n}\n\nfunction assertRotationRecoveryPrerequisites(state: DocumentStoreState) {\n if (state.persistence.supportsAtomicRecoveryHistoryPruning !== true) {\n throw new Error(\n \"Rotation raw-history recovery requires an adapter with atomic local-history pruning\",\n );\n }\n const author = resolveDocumentCreateAuthor(state.runtime);\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n const documentId = state.record?.documentId;\n if (\n !author ||\n !encapsulationKeyPair ||\n !documentId ||\n !state.runtime.auth.isAuthenticated ||\n !state.runtime.state.online\n ) {\n throw new Error(\n \"Rotation requires verified full-history recovery, but remote sync prerequisites are unavailable\",\n );\n }\n return { author, documentId, encapsulationKeyPair };\n}\n\nfunction assertRotationRecoveryGeneration(input: {\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): void {\n if (!isDocumentStoreSyncGenerationCurrent(input.state, input.generation)) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n}\n\nfunction rotationIncomingUpdateIsolation(input: {\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n return {\n onIncomingUpdateIsolationFailure:\n documentIncomingUpdateIsolationFailureHandler(\n input.state,\n input.generation,\n ),\n validateIncomingUpdates: async (\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\" | \"response\">,\n ) => {\n await validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n });\n const decryptedUpdates = ordinaryRawHistoryUpdates(\n result.decryptedUpdates,\n );\n const ordinaryUpdateIds = new Set(\n decryptedUpdates.map((update) => update.id),\n );\n await validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates,\n responseUpdates: result.response.updates.filter((update) =>\n ordinaryUpdateIds.has(update.id),\n ),\n });\n },\n };\n}\n\nasync function pullVerifiedRawHistoryForRotation(input: {\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n rebuiltDocument: DocumentState;\n state: DocumentStoreState;\n}) {\n const { author, documentId, encapsulationKeyPair } =\n assertRotationRecoveryPrerequisites(input.state);\n let pullContinuation: DocumentSyncPullContinuation | undefined;\n const seenPullCursors = new Set<string>();\n let planningRecord = input.currentRecord;\n let writerProjection =\n input.state.writerProjection?.documentId === documentId &&\n !isRejectedDecodedProjection(input.state.writerProjection)\n ? input.state.writerProjection\n : undefined;\n\n while (true) {\n let abandonReason: string | null = null;\n // Each page reads the live runtime, as the bag it replaced did; the key\n // stays the one the prerequisites checked.\n const remoteDocuments = new RemoteDocumentService({\n api: input.state.runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: input.state.runtime.infra.execSql,\n isRemoteSyncBlocked: input.state.runtime.util.isRemoteSyncBlocked,\n });\n const synced = await remoteDocuments.syncRemoteDocument({\n author,\n documentId,\n historyMode: \"raw\",\n localVersionVector: null,\n minLsn: input.currentRecord.lastCommitLsn ?? undefined,\n onRemoteDocumentDeleted: ({ commitPurgeProof, documentId }) =>\n deleteUpstreamDeletedDocument(\n input.state,\n input.generation,\n input.currentRecord,\n documentId,\n commitPurgeProof,\n ),\n // Recorded, never parked: this pass submits no writes, so it plans no\n // ancestor repair and cannot abandon as `inaccessible`.\n onSyncAbandoned: (reason) => {\n abandonReason = reason;\n },\n ...rotationIncomingUpdateIsolation({\n currentDocument: input.rebuiltDocument,\n generation: input.generation,\n state: input.state,\n }),\n onSyncTrace: (line) => input.state.runtime.util.log(`Documents: ${line}`),\n pendingUpdates: [],\n persistedState: planningRecord,\n pullContinuation,\n resolveProjectionUserKey: input.state.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Documents\",\n runtime: input.state.runtime,\n writerKeyLabel: \"writer key\",\n }),\n warmReferencedPrincipalPolicies:\n input.state.runtime.principalPolicies.createWarmer(),\n writerProjection,\n });\n if (!synced) {\n throw new Error(\n `Rotation raw-history recovery could not complete (${abandonReason ?? \"sync did not finish\"}); key rotation was not started`,\n );\n }\n\n assertRotationRecoveryGeneration(input);\n\n importSyncedDocumentUpdates(\n input.rebuiltDocument,\n ordinaryRawHistoryUpdates(synced.decryptedUpdates),\n );\n if (!synced.hasIncompletePull) return synced;\n\n const nextContinuation = readPullContinuation(synced.response);\n if (!nextContinuation) {\n throw new Error(\n \"Rotation raw-history recovery ended before the retained history was complete\",\n );\n }\n if (seenPullCursors.has(nextContinuation.cursor)) {\n throw new Error(\n \"Rotation raw-history recovery encountered a repeated pull cursor\",\n );\n }\n seenPullCursors.add(nextContinuation.cursor);\n pullContinuation = nextContinuation;\n planningRecord = { ...planningRecord, ...synced.persistedState };\n writerProjection = synced.writerProjection;\n }\n}\n\nasync function collectVerifiedRawHistoryForRotation(input: {\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n const consumedPullContinuation = input.state.pullContinuation;\n const writerProjectionGeneration = input.state.writerProjectionGeneration;\n const rebuiltDocument = await createStoredDocument(input.state);\n try {\n const synced = await pullVerifiedRawHistoryForRotation({\n ...input,\n rebuiltDocument,\n });\n return {\n consumedPullContinuation,\n currentRecord: input.currentRecord,\n rebuiltDocument,\n synced,\n writerProjectionGeneration,\n };\n } catch (error) {\n rebuiltDocument.free();\n throw error;\n }\n}\n\nclass RotationDocumentChangedError extends Error {}\n\nfunction assertCapturedDocumentCurrent(input: {\n capturedVersion: string;\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): void {\n assertRotationRecoveryGeneration(input);\n if (\n !versionVectorsEqual(\n encodeVersionVector(input.currentDocument),\n input.capturedVersion,\n )\n ) {\n throw new RotationDocumentChangedError(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n}\n\nfunction currentRotationRecoveryRecord(\n state: DocumentStoreState,\n): NonNullable<DocumentStoreState[\"record\"]> {\n if (state.record) return state.record;\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n}\n\nfunction installRotationRecovery(input: {\n capturedVersion: string;\n collection: Awaited<ReturnType<typeof collectVerifiedRawHistoryForRotation>>;\n currentDoc: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n const { capturedVersion, collection, currentDoc, generation, state } = input;\n const installation = state.writeChain\n .catch(() => undefined)\n .then(() =>\n chainIdentityWrite(state, async () => {\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n assertExactDocumentHistory({\n currentDocument: currentDoc,\n rebuiltDocument: collection.rebuiltDocument,\n });\n return installRebuiltDocument({\n consumedPullContinuation: collection.consumedPullContinuation,\n currentRecord: collection.currentRecord,\n generation,\n rebuiltDoc: collection.rebuiltDocument,\n state,\n synced: collection.synced,\n writerProjectionGeneration: collection.writerProjectionGeneration,\n });\n }),\n );\n // Only the checked local install occupies the write queue. Network recovery\n // uses the remote queue, so an outage cannot hold new edits hostage.\n void chainQueuedWrite(\n state,\n installation.then(\n () => undefined,\n () => undefined,\n ),\n );\n return installation;\n}\n\nasync function recoverFullHistoryForRotation(\n state: DocumentStoreState,\n laneGeneration: DocumentStoreSyncLaneGeneration,\n): Promise<Uint8Array> {\n assertRotationRecoveryPrerequisites(state);\n await invalidatePullContinuationBeforeRotation(state);\n const currentDoc = state.doc;\n const currentRecord = state.record;\n if (!currentDoc || !currentRecord) {\n throw new Error(\n \"Document must finish loading before its content key can rotate\",\n );\n }\n // The teardown guard for the recovery's terminal-failure handler: captured\n // before the pull so a discard (row 21) racing this preflight invalidates\n // it, and the stale handler cannot resurrect a deleted failure row.\n const generation = captureDocumentStoreAttachmentSyncGeneration(\n state,\n currentDoc,\n laneGeneration,\n );\n if (!generation) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n\n const capturedVersion = encodeVersionVector(currentDoc);\n let settlementRequiresRetry = false;\n\n // A raw recovery starts from an empty scratch document, bypasses untrusted\n // rotation-baseline redirects, drains every retained page in memory, and\n // publishes nothing until all response updates have validated. Checkpoints\n // are authenticated and decrypted but are not reconstruction inputs: the\n // original ordinary update stream is the source of truth in this mode.\n let collection = await collectVerifiedRawHistoryForRotation({\n currentRecord,\n generation,\n state,\n });\n\n try {\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const pendingUpdates = await listPendingUpdates(state);\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const verifiedOrdinaryVersion = importProvenOrdinaryPendingHistory({\n currentDocument: currentDoc,\n pendingUpdates,\n rebuiltDocument: collection.rebuiltDocument,\n });\n if (pendingUpdates.some((update) => update.sourceVersionVector == null)) {\n // The first raw pass proves the exact ordinary frontier before any local\n // row can be published. Pull raw history again after settlement so the\n // installed snapshot also includes remote work that raced that submit.\n await settleOrdinaryDocumentUpdatesBeforeRotation(\n state,\n verifiedOrdinaryVersion,\n pendingUpdates,\n generation,\n );\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const definitiveCollection = await collectVerifiedRawHistoryForRotation({\n currentRecord: currentRotationRecoveryRecord(state),\n generation,\n state,\n });\n collection.rebuiltDocument.free();\n collection = definitiveCollection;\n }\n const installed = await installRotationRecovery({\n capturedVersion,\n collection,\n currentDoc,\n generation,\n state,\n });\n settlementRequiresRetry = installed.settlementRequiresRetry;\n if (settlementRequiresRetry) {\n throw new Error(\n \"Rotation raw-history recovery was superseded during its atomic install; retry key rotation\",\n );\n }\n return installed.fullHistorySnapshot;\n } finally {\n if (state.doc !== collection.rebuiltDocument) {\n collection.rebuiltDocument.free();\n }\n if (settlementRequiresRetry) {\n requestDocumentStoreSync(state);\n }\n }\n}\n\n/**\n * Wait for prior local writes and serialize with other remote work. Edits can\n * continue during the pull; the checked install rejects a changed document so\n * a stale recovery cannot replace them. This preflight can then be retried.\n * `reuse` returns the last completed proof while it still covers this exact\n * local document (rotationProofRecord); otherwise it proves like `prove`.\n */\nexport function assertDocumentStoreCanRotateContentKey(\n state: DocumentStoreState,\n proof: DocumentRotationProofMode = \"prove\",\n): Promise<Uint8Array> {\n const laneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n const generation = captureDocumentStoreAttachmentSyncGeneration(\n state,\n state.doc,\n laneGeneration,\n );\n return runDocumentRemoteWork(state, async () => {\n await state.writeChain.catch(() => undefined);\n if (\n !generation ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw new Error(\n \"Document changed before rotation recovery; retry key rotation\",\n );\n }\n const recorded =\n proof === \"reuse\" ? currentRecordedRotationProof(state) : null;\n if (recorded) return recorded;\n const snapshot = await proveFullHistoryForRotation(\n state,\n laneGeneration,\n generation,\n );\n recordRotationProof(state, snapshot);\n return snapshot;\n });\n}\n\nasync function proveFullHistoryForRotation(\n state: DocumentStoreState,\n laneGeneration: DocumentStoreSyncLaneGeneration,\n generation: DocumentStoreSyncGeneration,\n): Promise<Uint8Array> {\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await recoverFullHistoryForRotation(state, laneGeneration);\n } catch (error) {\n // Autosaves and conflict re-keying can invalidate the proven frontier.\n // Repeat the complete proof without blocking new local edits; repeated\n // changes remain bounded and leave the durable queue retryable.\n if (\n !(\n error instanceof RotationPendingUpdatesChangedError ||\n error instanceof RotationDocumentChangedError\n ) ||\n attempt >= 2 ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw error;\n }\n }\n }\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isRejectedDecodedProjection } from "../../../../internal/validators/response/index.js";
|
|
1
2
|
import { DOCUMENTS_APP_KIND, DocumentRecordRepository, resolveDocumentCreateAuthor, } from "../../../../workflows/documents/index.js";
|
|
2
3
|
import { markOriginatedDocuments } from "../../../../workflows/sync/coordination.js";
|
|
3
4
|
import { requestDocumentStoreSync } from "../../registry.js";
|
|
@@ -202,7 +203,9 @@ function createAttachmentBaseUploadInput(input) {
|
|
|
202
203
|
}
|
|
203
204
|
async function uploadPendingAttachmentBytes(input) {
|
|
204
205
|
const { pendingAttachment, state } = input.pendingUpload;
|
|
205
|
-
const writerProjection = state.writerProjection?.documentId ===
|
|
206
|
+
const writerProjection = state.writerProjection?.documentId ===
|
|
207
|
+
input.pendingUpload.remoteDocumentId &&
|
|
208
|
+
!isRejectedDecodedProjection(state.writerProjection)
|
|
206
209
|
? state.writerProjection
|
|
207
210
|
: null;
|
|
208
211
|
const writerProjectionGeneration = state.writerProjectionGeneration;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,yCAAyC,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EACL,gCAAgC,EAChC,8BAA8B,EAC9B,6BAA6B,GAC9B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yCAAyC,EAAE,MAAM,6CAA6C,CAAC;AACxG,OAAO,EAEL,kCAAkC,GACnC,MAAM,0CAA0C,CAAC;AAQlD,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC1E,OAAO,EAEL,uCAAuC,EACvC,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAiB1B,SAAS,wBAAwB,CAC/B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AO,CAAC,KAAK,CAAC,WAAW;QAC5C,iBAAiB;KAClB,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,+BAA+B,CAAC;QACtD,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,MAAM;QACN,MAAM;QACN,cAAc,EAAE,QAAQ;QACxB,UAAU;KACX,CAAC,CAAC;IACH,OAAO,4BAA4B,CAAC;QAClC,eAAe;QACf,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,eAAe;QAC9C,aAAa,EAAE,KAAK;QACpB,UAAU;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n BlobAttachmentService,\n BlobByteSource,\n BlobSourceSnapshot,\n} from \"../../../../workflows/blobs\";\nimport type { PreparedUploadDocumentAttachmentRequest } from \"../../../../workflows/blobs/upload\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { markOriginatedDocuments } from \"../../../../workflows/sync/coordination\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"../attachmentUpload/attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"../attachmentUpload/attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadLaneReporter,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"../attachmentUpload/attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"../state\";\nimport { reportAttachmentUploadFailure } from \"./attachmentUploadFailure\";\nimport {\n type CarriedFirstUpdate,\n ensureRemoteDocumentCarryingFirstUpdate,\n uploadCarryingFirstUpdate,\n} from \"./carriedFirstUpdate\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n let carriedFirstUpdate: CarriedFirstUpdate | undefined;\n const currentRecord = nextRecord.documentId\n ? nextRecord\n : await ensureRemoteDocumentCarryingFirstUpdate({\n currentDoc,\n encapsulationKeyPair,\n generation: attachmentGeneration,\n nextRecord,\n onCarried: (carried) => {\n carriedFirstUpdate = carried;\n },\n policyOperation,\n state,\n });\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n const step = await syncNextPendingAttachment(\n {\n attachmentGeneration,\n carriedFirstUpdate,\n encapsulationKeyPair,\n pendingAttachment,\n policyOperation,\n remoteDocumentId,\n state,\n },\n progress,\n currentDoc,\n );\n // Only the first bind may carry it; a failed one leaves the row queued.\n carriedFirstUpdate = undefined;\n if (step === \"stop\") {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await new DocumentRecordRepository(\n state.runtime.infra.execSql,\n ).clearDocumentSyncFailure({\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\n/** Settles one queued attachment; \"stop\" ends this pass early. */\nasync function syncNextPendingAttachment(\n upload: Omit<PendingAttachmentUploadInput, \"activeBindingBySlotId\">,\n progress: AttachmentSyncProgress,\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>,\n): Promise<\"continue\" | \"stop\"> {\n const { attachmentGeneration, pendingAttachment, state } = upload;\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n if (!(await loadRemoteAttachmentBindings({ ...upload, progress }))) {\n return \"stop\";\n }\n const outcome = await syncPendingAttachmentUpload({\n ...upload,\n activeBindingBySlotId: progress.activeBindingBySlotId,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return \"stop\";\n }\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") progress.uploadedAttachment = true;\n return \"continue\";\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n carriedFirstUpdate?: CarriedFirstUpdate | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: PreparedUploadDocumentAttachmentRequest[\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): PreparedUploadDocumentAttachmentRequest {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n documentSync: input.pendingUpload.carriedFirstUpdate?.request,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n warmReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer({\n operation: input.pendingUpload.policyOperation,\n }),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: PreparedUploadDocumentAttachmentRequest;\n /** Read from the runtime the base input was built from. */\n blobAttachments: BlobAttachmentService;\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId === input.pendingUpload.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadCarryingFirstUpdate({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n carried: input.pendingUpload.carriedFirstUpdate,\n committed: (attempt) => attempt.uploaded?.response.documentSync,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n upload: () =>\n uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n blobAttachments: input.blobAttachments,\n state,\n writerProjection,\n }),\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n blobAttachments: state.runtime.blobAttachments,\n pendingUpload: input,\n uploadLane,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAO7E,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,2BAA2B,GAC5B,MA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AAC,MAAM,EAAE,CAAC;QACZ,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CACpB,iFAAiF,CAClF,CAAC;QACF,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,6BAA6B,CAAC;QACnD,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,iBAAiB;QACjB,MAAM;QACN,KAAK;KACN,CAAC,CAAC;IACH,4EAA4E;IAC5E,wEAAwE;IACxE,0CAA0C;IAC1C,IACE,CAAC,oCAAoC,CAAC,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,EACxE,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,IAAI,CAAC,QAAQ;QAAE,OAAO,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAC9D,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC;IACtC,MAAM,UAAU,GAAG,kCAAkC,CAAC;QACpD,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,iBAAiB;KAClB,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,+BAA+B,CAAC;QACtD,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,MAAM;QACN,MAAM;QACN,cAAc,EAAE,QAAQ;QACxB,UAAU;KACX,CAAC,CAAC;IACH,OAAO,4BAA4B,CAAC;QAClC,eAAe;QACf,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,eAAe;QAC9C,aAAa,EAAE,KAAK;QACpB,UAAU;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { isRejectedDecodedProjection } from \"@tearleads/validators/response\";\nimport type {\n BlobAttachmentService,\n BlobByteSource,\n BlobSourceSnapshot,\n} from \"../../../../workflows/blobs\";\nimport type { PreparedUploadDocumentAttachmentRequest } from \"../../../../workflows/blobs/upload\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { markOriginatedDocuments } from \"../../../../workflows/sync/coordination\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"../attachmentUpload/attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"../attachmentUpload/attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadLaneReporter,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"../attachmentUpload/attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"../state\";\nimport { reportAttachmentUploadFailure } from \"./attachmentUploadFailure\";\nimport {\n type CarriedFirstUpdate,\n ensureRemoteDocumentCarryingFirstUpdate,\n uploadCarryingFirstUpdate,\n} from \"./carriedFirstUpdate\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n let carriedFirstUpdate: CarriedFirstUpdate | undefined;\n const currentRecord = nextRecord.documentId\n ? nextRecord\n : await ensureRemoteDocumentCarryingFirstUpdate({\n currentDoc,\n encapsulationKeyPair,\n generation: attachmentGeneration,\n nextRecord,\n onCarried: (carried) => {\n carriedFirstUpdate = carried;\n },\n policyOperation,\n state,\n });\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n const step = await syncNextPendingAttachment(\n {\n attachmentGeneration,\n carriedFirstUpdate,\n encapsulationKeyPair,\n pendingAttachment,\n policyOperation,\n remoteDocumentId,\n state,\n },\n progress,\n currentDoc,\n );\n // Only the first bind may carry it; a failed one leaves the row queued.\n carriedFirstUpdate = undefined;\n if (step === \"stop\") {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await new DocumentRecordRepository(\n state.runtime.infra.execSql,\n ).clearDocumentSyncFailure({\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\n/** Settles one queued attachment; \"stop\" ends this pass early. */\nasync function syncNextPendingAttachment(\n upload: Omit<PendingAttachmentUploadInput, \"activeBindingBySlotId\">,\n progress: AttachmentSyncProgress,\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>,\n): Promise<\"continue\" | \"stop\"> {\n const { attachmentGeneration, pendingAttachment, state } = upload;\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n if (!(await loadRemoteAttachmentBindings({ ...upload, progress }))) {\n return \"stop\";\n }\n const outcome = await syncPendingAttachmentUpload({\n ...upload,\n activeBindingBySlotId: progress.activeBindingBySlotId,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return \"stop\";\n }\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") progress.uploadedAttachment = true;\n return \"continue\";\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n carriedFirstUpdate?: CarriedFirstUpdate | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: PreparedUploadDocumentAttachmentRequest[\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): PreparedUploadDocumentAttachmentRequest {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n documentSync: input.pendingUpload.carriedFirstUpdate?.request,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n warmReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer({\n operation: input.pendingUpload.policyOperation,\n }),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: PreparedUploadDocumentAttachmentRequest;\n /** Read from the runtime the base input was built from. */\n blobAttachments: BlobAttachmentService;\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId ===\n input.pendingUpload.remoteDocumentId &&\n !isRejectedDecodedProjection(state.writerProjection)\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadCarryingFirstUpdate({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n carried: input.pendingUpload.carriedFirstUpdate,\n committed: (attempt) => attempt.uploaded?.response.documentSync,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n upload: () =>\n uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n blobAttachments: input.blobAttachments,\n state,\n writerProjection,\n }),\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n blobAttachments: state.runtime.blobAttachments,\n pendingUpload: input,\n uploadLane,\n });\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isRejectedDecodedProjection } from "../../../../internal/validators/response/index.js";
|
|
1
2
|
import { getDocumentAttachments } from "../../../../data/documents/documentContent.js";
|
|
2
3
|
import { resolveDocumentCreateAuthor, } from "../../../../workflows/documents/index.js";
|
|
3
4
|
import { deleteLocalAttachmentRecord } from "../attachments/attachmentPersistence.js";
|
|
@@ -82,7 +83,8 @@ async function syncDetachedAttachmentBinding(input) {
|
|
|
82
83
|
state.runtime.util.log("Documents: skipped attachment detach because the writer context is unavailable.");
|
|
83
84
|
return false;
|
|
84
85
|
}
|
|
85
|
-
const writerProjection = state.writerProjection?.documentId === input.remoteDocumentId
|
|
86
|
+
const writerProjection = state.writerProjection?.documentId === input.remoteDocumentId &&
|
|
87
|
+
!isRejectedDecodedProjection(state.writerProjection)
|
|
86
88
|
? state.writerProjection
|
|
87
89
|
: null;
|
|
88
90
|
const writerProjectionGeneration = state.writerProjectionGeneration;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncDetachedAttachments.js","sourceRoot":"","sources":["sync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AC5D,GAAG,eAAe;QAClB,gBAAgB,EAAE,gBAAgB,IAAI,SAAS;KAChD,CAAC,CAAC;IACH,IAAI,CAAC,gBAAgB,EAAE;QAAE,OAAO,KAAK,CAAC;IACtC,IAAI,CAAC,QAAQ,IAAI,gBAAgB,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACxD,KAAK,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAC9B,QAAQ,GAAG,MAAM,eAAe,CAAC,wBAAwB,CAAC,eAAe,CAAC,CAAC;QAC3E,IAAI,CAAC,gBAAgB,EAAE;YAAE,OAAO,KAAK,CAAC;IACxC,CAAC;IACD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,KAAK,CAAC;IACf,CAAC;IAED,+BAA+B,CAC7B,KAAK,EACL,QAAQ,CAAC,gBAAgB,EACzB,0BAA0B,CAC3B,CAAC;IACF,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CACpB,uBAAuB,OAAO,CAAC,MAAM,kBAAkB,KAAK,CAAC,gBAAgB,GAAG,CACjF,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { getDocumentAttachments } from \"../../../../data/documents/documentContent\";\nimport {\n type DocumentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { deleteLocalAttachmentRecord } from \"../attachments/attachmentPersistence\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport type {\n DocumentAttachmentBinding,\n DocumentState,\n DocumentStoreState,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { documentSyncContextMatches } from \"./syncUpdateImport\";\n\ninterface DetachedAttachmentMarker {\n slotId: string;\n storageKey: string;\n}\n\nexport async function syncDetachedAttachmentBindings(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n generation: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<void> {\n const currentDoc = generation.currentDoc;\n if (\n !currentDoc ||\n !detachedSyncContextIsCurrent(state, generation, nextRecord)\n ) {\n return;\n }\n\n const detachedMarkers = listDetachedAttachmentMarkers(state, currentDoc);\n if (detachedMarkers.length === 0) {\n return;\n }\n\n if (!nextRecord.documentId) {\n await cleanupDetachedAttachmentMarkers(\n state,\n currentDoc,\n nextRecord,\n detachedMarkers,\n generation,\n );\n return;\n }\n\n const remoteDocumentId = nextRecord.documentId;\n const remoteBindings =\n await state.runtime.apiClient.listDocumentAttachments(remoteDocumentId);\n if (\n !remoteBindings ||\n !detachedSyncContextIsCurrent(state, generation, nextRecord)\n ) {\n return;\n }\n\n const activeBindingBySlotId = new Map(\n remoteBindings.map((binding) => [binding.slotId, binding]),\n );\n\n for (const marker of detachedMarkers) {\n if (!detachedSyncContextIsCurrent(state, generation, nextRecord)) {\n return;\n }\n const activeBinding = activeBindingBySlotId.get(marker.slotId);\n if (\n activeBinding &&\n !(await syncDetachedAttachmentBinding({\n binding: activeBinding,\n generation,\n policyOperation,\n remoteDocumentId,\n requestRecord: nextRecord,\n state,\n }))\n ) {\n return;\n }\n\n const cleaned = await cleanupDetachedAttachmentMarker(\n state,\n currentDoc,\n nextRecord,\n marker,\n generation,\n );\n if (!cleaned) {\n return;\n }\n }\n}\n\nfunction detachedSyncContextIsCurrent(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n requestRecord: DocumentRecord,\n): boolean {\n return (\n isDocumentStoreSyncGenerationCurrent(state, generation) &&\n documentSyncContextMatches(\n state.record,\n requestRecord,\n requestRecord.documentId,\n )\n );\n}\n\nfunction listDetachedAttachmentMarkers(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n): DetachedAttachmentMarker[] {\n const currentSlotIds = new Set(\n getDocumentAttachments(currentDoc).map((attachment) => attachment.slotId),\n );\n\n return Object.entries(state.attachmentStorageKeyBySlotId).flatMap(\n ([slotId, storageKey]) =>\n currentSlotIds.has(slotId) ? [] : [{ slotId, storageKey }],\n );\n}\n\nasync function cleanupDetachedAttachmentMarkers(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n requestRecord: DocumentRecord,\n markers: readonly DetachedAttachmentMarker[],\n generation: DocumentStoreSyncGeneration,\n): Promise<void> {\n for (const marker of markers) {\n if (\n !(await cleanupDetachedAttachmentMarker(\n state,\n currentDoc,\n requestRecord,\n marker,\n generation,\n ))\n ) {\n return;\n }\n }\n}\n\nasync function cleanupDetachedAttachmentMarker(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n requestRecord: DocumentRecord,\n marker: DetachedAttachmentMarker,\n generation: DocumentStoreSyncGeneration,\n): Promise<boolean> {\n if (!detachedSyncContextIsCurrent(state, generation, requestRecord)) {\n return false;\n }\n await deleteLocalAttachmentRecord(\n state,\n marker.slotId,\n marker.storageKey,\n currentDoc,\n );\n // Deleting the row queued its bytes for the reference-checked reclaim.\n void runDocumentOrphanMaintenance(state);\n return detachedSyncContextIsCurrent(state, generation, requestRecord);\n}\n\nasync function syncDetachedAttachmentBinding(input: {\n binding: DocumentAttachmentBinding;\n generation: DocumentStoreSyncGeneration;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n requestRecord: DocumentRecord;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { binding, generation, requestRecord, state } = input;\n const contextIsCurrent = () =>\n detachedSyncContextIsCurrent(state, generation, requestRecord);\n if (!contextIsCurrent()) return false;\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment detach because the writer context is unavailable.\",\n );\n return false;\n }\n\n const writerProjection =\n state.writerProjection?.documentId === input.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n let remoteSyncBlocked = false;\n // Read with the currency check above, so its executor is this generation's.\n const { blobAttachments } = state.runtime;\n const baseDetachInput = {\n author,\n bindingId: binding.bindingId,\n blobId: binding.blobId,\n documentId: input.remoteDocumentId,\n isRemoteSyncBlocked: (organizationId: string) => {\n remoteSyncBlocked =\n state.runtime.util.isRemoteSyncBlocked?.(organizationId) ?? false;\n return remoteSyncBlocked;\n },\n resolveProjectionUserKey: generation.resolveProjectionUserKey,\n slotId: binding.slotId,\n stillCurrent: contextIsCurrent,\n warmReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n }),\n };\n let detached = await blobAttachments.detachDocumentAttachment({\n ...baseDetachInput,\n writerProjection: writerProjection ?? undefined,\n });\n if (!contextIsCurrent()) return false;\n if (!detached && writerProjection && !remoteSyncBlocked) {\n state.writerProjection = null;\n detached = await blobAttachments.detachDocumentAttachment(baseDetachInput);\n if (!contextIsCurrent()) return false;\n }\n if (!detached) {\n return false;\n }\n\n installDocumentWriterProjection(\n state,\n detached.writerProjection,\n writerProjectionGeneration,\n );\n state.runtime.util.log(\n `Detached attachment ${binding.slotId} from document ${input.remoteDocumentId}.`,\n );\n return true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncDetachedAttachments.js","sourceRoot":"","sources":["syncDetachedAttachments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAC7E,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAEL,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,2BAA2B,EAAE,MAAM,sCAAsC,CAAC;AACnF,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAMpE,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAOhE,MAAM,CAAC,KAAK,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;IACxC,CAAC;IACD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,KAAK,CAAC;IACf,CAAC;IAED,+BAA+B,CAC7B,KAAK,EACL,QAAQ,CAAC,gBAAgB,EACzB,0BAA0B,CAC3B,CAAC;IACF,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CACpB,uBAAuB,OAAO,CAAC,MAAM,kBAAkB,KAAK,CAAC,gBAAgB,GAAG,CACjF,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { isRejectedDecodedProjection } from \"@tearleads/validators/response\";\nimport { getDocumentAttachments } from \"../../../../data/documents/documentContent\";\nimport {\n type DocumentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { deleteLocalAttachmentRecord } from \"../attachments/attachmentPersistence\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport type {\n DocumentAttachmentBinding,\n DocumentState,\n DocumentStoreState,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { documentSyncContextMatches } from \"./syncUpdateImport\";\n\ninterface DetachedAttachmentMarker {\n slotId: string;\n storageKey: string;\n}\n\nexport async function syncDetachedAttachmentBindings(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n generation: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<void> {\n const currentDoc = generation.currentDoc;\n if (\n !currentDoc ||\n !detachedSyncContextIsCurrent(state, generation, nextRecord)\n ) {\n return;\n }\n\n const detachedMarkers = listDetachedAttachmentMarkers(state, currentDoc);\n if (detachedMarkers.length === 0) {\n return;\n }\n\n if (!nextRecord.documentId) {\n await cleanupDetachedAttachmentMarkers(\n state,\n currentDoc,\n nextRecord,\n detachedMarkers,\n generation,\n );\n return;\n }\n\n const remoteDocumentId = nextRecord.documentId;\n const remoteBindings =\n await state.runtime.apiClient.listDocumentAttachments(remoteDocumentId);\n if (\n !remoteBindings ||\n !detachedSyncContextIsCurrent(state, generation, nextRecord)\n ) {\n return;\n }\n\n const activeBindingBySlotId = new Map(\n remoteBindings.map((binding) => [binding.slotId, binding]),\n );\n\n for (const marker of detachedMarkers) {\n if (!detachedSyncContextIsCurrent(state, generation, nextRecord)) {\n return;\n }\n const activeBinding = activeBindingBySlotId.get(marker.slotId);\n if (\n activeBinding &&\n !(await syncDetachedAttachmentBinding({\n binding: activeBinding,\n generation,\n policyOperation,\n remoteDocumentId,\n requestRecord: nextRecord,\n state,\n }))\n ) {\n return;\n }\n\n const cleaned = await cleanupDetachedAttachmentMarker(\n state,\n currentDoc,\n nextRecord,\n marker,\n generation,\n );\n if (!cleaned) {\n return;\n }\n }\n}\n\nfunction detachedSyncContextIsCurrent(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n requestRecord: DocumentRecord,\n): boolean {\n return (\n isDocumentStoreSyncGenerationCurrent(state, generation) &&\n documentSyncContextMatches(\n state.record,\n requestRecord,\n requestRecord.documentId,\n )\n );\n}\n\nfunction listDetachedAttachmentMarkers(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n): DetachedAttachmentMarker[] {\n const currentSlotIds = new Set(\n getDocumentAttachments(currentDoc).map((attachment) => attachment.slotId),\n );\n\n return Object.entries(state.attachmentStorageKeyBySlotId).flatMap(\n ([slotId, storageKey]) =>\n currentSlotIds.has(slotId) ? [] : [{ slotId, storageKey }],\n );\n}\n\nasync function cleanupDetachedAttachmentMarkers(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n requestRecord: DocumentRecord,\n markers: readonly DetachedAttachmentMarker[],\n generation: DocumentStoreSyncGeneration,\n): Promise<void> {\n for (const marker of markers) {\n if (\n !(await cleanupDetachedAttachmentMarker(\n state,\n currentDoc,\n requestRecord,\n marker,\n generation,\n ))\n ) {\n return;\n }\n }\n}\n\nasync function cleanupDetachedAttachmentMarker(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n requestRecord: DocumentRecord,\n marker: DetachedAttachmentMarker,\n generation: DocumentStoreSyncGeneration,\n): Promise<boolean> {\n if (!detachedSyncContextIsCurrent(state, generation, requestRecord)) {\n return false;\n }\n await deleteLocalAttachmentRecord(\n state,\n marker.slotId,\n marker.storageKey,\n currentDoc,\n );\n // Deleting the row queued its bytes for the reference-checked reclaim.\n void runDocumentOrphanMaintenance(state);\n return detachedSyncContextIsCurrent(state, generation, requestRecord);\n}\n\nasync function syncDetachedAttachmentBinding(input: {\n binding: DocumentAttachmentBinding;\n generation: DocumentStoreSyncGeneration;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n requestRecord: DocumentRecord;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { binding, generation, requestRecord, state } = input;\n const contextIsCurrent = () =>\n detachedSyncContextIsCurrent(state, generation, requestRecord);\n if (!contextIsCurrent()) return false;\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment detach because the writer context is unavailable.\",\n );\n return false;\n }\n\n const writerProjection =\n state.writerProjection?.documentId === input.remoteDocumentId &&\n !isRejectedDecodedProjection(state.writerProjection)\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n let remoteSyncBlocked = false;\n // Read with the currency check above, so its executor is this generation's.\n const { blobAttachments } = state.runtime;\n const baseDetachInput = {\n author,\n bindingId: binding.bindingId,\n blobId: binding.blobId,\n documentId: input.remoteDocumentId,\n isRemoteSyncBlocked: (organizationId: string) => {\n remoteSyncBlocked =\n state.runtime.util.isRemoteSyncBlocked?.(organizationId) ?? false;\n return remoteSyncBlocked;\n },\n resolveProjectionUserKey: generation.resolveProjectionUserKey,\n slotId: binding.slotId,\n stillCurrent: contextIsCurrent,\n warmReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n }),\n };\n let detached = await blobAttachments.detachDocumentAttachment({\n ...baseDetachInput,\n writerProjection: writerProjection ?? undefined,\n });\n if (!contextIsCurrent()) return false;\n if (!detached && writerProjection && !remoteSyncBlocked) {\n state.writerProjection = null;\n detached = await blobAttachments.detachDocumentAttachment(baseDetachInput);\n if (!contextIsCurrent()) return false;\n }\n if (!detached) {\n return false;\n }\n\n installDocumentWriterProjection(\n state,\n detached.writerProjection,\n writerProjectionGeneration,\n );\n state.runtime.util.log(\n `Detached attachment ${binding.slotId} from document ${input.remoteDocumentId}.`,\n );\n return true;\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { encodeVersionVector, exportFullHistorySnapshot, } from "../../../../internal/loro/index.js";
|
|
2
|
+
import { isRejectedDecodedProjection } from "../../../../internal/validators/response/index.js";
|
|
2
3
|
import { createDocumentWriterPublicKeyResolver, deletePersistedDocument, RemoteDocumentService, resolveDocumentCreateAuthor, validateDocumentSyncUpdateImports, } from "../../../../workflows/documents/index.js";
|
|
3
4
|
import { requestDocumentStoreSync } from "../../registry.js";
|
|
4
5
|
import { parkForAncestorRepair } from "../ancestorRepairPark.js";
|
|
@@ -132,7 +133,8 @@ function runRemoteDocumentSync(input, author, documentId, requestedPullContinuat
|
|
|
132
133
|
warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({
|
|
133
134
|
operation: input.policyOperation,
|
|
134
135
|
}),
|
|
135
|
-
writerProjection: state.writerProjection?.documentId === currentRecord.documentId
|
|
136
|
+
writerProjection: state.writerProjection?.documentId === currentRecord.documentId &&
|
|
137
|
+
!isRejectedDecodedProjection(state.writerProjection)
|
|
136
138
|
? state.writerProjection
|
|
137
139
|
: undefined,
|
|
138
140
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncRequest.js","sourceRoot":"","sources":["syncRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MA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E,OAAO,IAAI,CAAC;IAEzB,MAAM,mBAAmB,GAAG,KAAK,CAAC,iBAAiB,IAAI,cAAc,CAAC,MAAM,CAAC;IAC7E,OAAO,yBAAyB,CAAC;QAC/B,aAAa;QACb,mBAAmB;QACnB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,yBAAyB;QACzB,MAAM;QACN,0BAA0B;KAC3B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport {\n createDocumentWriterPublicKeyResolver,\n type DocumentRecord,\n deletePersistedDocument,\n type ExecSql,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n validateDocumentSyncUpdateImports,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { parkForAncestorRepair } from \"../ancestorRepairPark\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type DocumentSyncAttempt,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { invalidateDocumentStorePullContinuation } from \"./pullContinuationInvalidation\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport {\n documentIncomingUpdateIsolationFailureHandler,\n documentRevalidationFailureHandler,\n documentTerminalSubmitFailureHandler,\n} from \"./syncShared\";\nimport { documentSyncContextMatches } from \"./syncUpdateImport\";\n\n/**\n * Destroying queued local edits here is settled policy, not an oversight\n * (docs/sync-edge-cases.md row 1): deletion is a privacy operation, so an\n * authoritative remote delete removes the document and its unsynced edits\n * everywhere with no preservation copy. Quarantine/export were rejected —\n * they retain or re-upload content the user deliberately destroyed.\n */\nexport async function deleteUpstreamDeletedDocument(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n requestRecord: DocumentRecord,\n remoteDocumentId: string,\n commitPurgeProof?: (transactionExecSql: ExecSql) => Promise<void>,\n) {\n await chainIdentityWrite(state, async () => {\n if (\n !isDocumentStoreSyncGenerationCurrent(state, generation) ||\n !documentSyncContextMatches(state.record, requestRecord, remoteDocumentId)\n ) {\n return;\n }\n\n const canDeleteCapturedDocument = () =>\n isDocumentStoreSyncGenerationCurrent(state, generation) &&\n documentSyncContextMatches(state.record, requestRecord, remoteDocumentId);\n let removedInMutation = false;\n const deletionStarted = await deletePersistedDocument({\n beforeDeleteInTransaction: commitPurgeProof,\n canStartDurableMutation: canDeleteCapturedDocument,\n deleteDocumentPlacements: state.runtime.deleteDocumentPlacements,\n documentProjectors: state.runtime.infra.documentProjectors,\n execSql: generation.execSql,\n expectedRecord: requestRecord,\n localId: requestRecord.id,\n // Invalidate the store generation INSIDE the deletion mutation: a\n // terminal failure handler queued behind it then observes the stale\n // generation and cannot resurrect a failure row the deletes removed.\n onDeletedInMutation: () => {\n if (canDeleteCapturedDocument()) {\n markDocumentStoreRemoved(state);\n removedInMutation = true;\n }\n },\n persistence: state.persistence,\n });\n if (!deletionStarted || !removedInMutation) {\n return;\n }\n void runDocumentOrphanMaintenance(state);\n state.runtime.util.log(\n `Documents: removed local document ${state.localId} after remote deletion.`,\n );\n });\n}\n\nfunction createDocumentSyncAttempt(input: {\n currentRecord: DocumentRecord;\n outgoingUpdateCount: number;\n policyOperation: PrincipalPolicyOperation;\n requestedPullContinuation: DocumentStoreState[\"pullContinuation\"];\n synced: DocumentSyncAttempt[\"synced\"];\n writerProjectionGeneration: number;\n}): DocumentSyncAttempt {\n return {\n consumedPullContinuation:\n input.synced.plan.request.pullCursor === undefined\n ? null\n : input.requestedPullContinuation,\n outgoingUpdateCount: input.outgoingUpdateCount,\n policyOperation: input.policyOperation,\n requestRecord: input.currentRecord,\n synced: input.synced,\n writerProjectionGeneration: input.writerProjectionGeneration,\n };\n}\n\ninterface RequestRemoteDocumentSyncInput {\n allowRecoveryBaseline?: boolean | undefined;\n currentDoc: DocumentState;\n currentRecord: DocumentRecord;\n encapsulationKeyPair: EncapsulationKeyPair;\n generation: DocumentStoreSyncGeneration;\n onOutgoingUpdatesMaterialized?:\n | ((updateIds: readonly string[]) => void)\n | undefined;\n pendingUpdates: PendingUpdateRecord[];\n /** The pass or workflow operation the sync's policy reads belong to. */\n policyOperation: PrincipalPolicyOperation;\n queuedUpdateCount?: number | undefined;\n state: DocumentStoreState;\n unavailableWriterLogMessage: string;\n}\n\n/** Where the document's pull stands, which decides whether a pause holds it. */\nfunction pullPosition(\n record: RequestRemoteDocumentSyncInput[\"currentRecord\"],\n continuation: DocumentStoreState[\"pullContinuation\"],\n) {\n return {\n minLsn: record.lastCommitLsn ?? undefined,\n pullContinuation: continuation ?? undefined,\n pullRecoveryRequired: record.pullContinuationRecoveryRequired === true,\n };\n}\n\nfunction runRemoteDocumentSync(\n input: RequestRemoteDocumentSyncInput,\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>,\n documentId: string,\n requestedPullContinuation: DocumentStoreState[\"pullContinuation\"],\n) {\n const { currentDoc, currentRecord, generation, pendingUpdates, state } =\n input;\n const runtime = state.runtime;\n const writerProjectionGenerationAtStart = state.writerProjectionGeneration;\n state.awaitingAncestorRepair = false;\n // The generation's API client and executor with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: input.encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n return remoteDocuments.syncRemoteDocument({\n author,\n // Heal a stale content-key bundle from this full-history snapshot. Rotation\n // settlement disables this: it may submit only the ordinary local stream.\n ...(input.allowRecoveryBaseline === false\n ? {}\n : {\n buildRotationSnapshot: async () =>\n exportFullHistorySnapshot(currentDoc),\n }),\n documentId,\n localVersionVector: encodeVersionVector(currentDoc),\n ...pullPosition(currentRecord, requestedPullContinuation),\n onRemoteDocumentDeleted: ({ commitPurgeProof, documentId }) =>\n deleteUpstreamDeletedDocument(\n state,\n generation,\n currentRecord,\n documentId,\n commitPurgeProof,\n ),\n onSyncAbandoned: (reason) => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return;\n const hintLandedMidPass = parkForAncestorRepair(\n state,\n reason,\n writerProjectionGenerationAtStart,\n );\n if (hintLandedMidPass) requestDocumentStoreSync(state);\n },\n onSyncTrace: (line) => runtime.util.log(`Documents: ${line}`),\n onReadOnlyProjectionFailure: documentRevalidationFailureHandler(\n state,\n generation,\n ),\n onIncomingUpdateIsolationFailure:\n documentIncomingUpdateIsolationFailureHandler(state, generation),\n onOutgoingUpdatesMaterialized: input.onOutgoingUpdatesMaterialized,\n onPullContinuationInvalidated: (continuation) =>\n invalidateDocumentStorePullContinuation({\n continuation,\n currentRecord,\n generation,\n state,\n }),\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n pendingUpdates,\n persistedState: currentRecord,\n rekeyPendingUpdate: state.persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Documents\",\n runtime,\n writerKeyLabel: \"writer key\",\n }),\n stillCurrent: () => isDocumentStoreSyncGenerationCurrent(state, generation),\n validateIncomingUpdates: (result) =>\n validateDocumentSyncUpdateImports({\n currentDocument: currentDoc,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n }),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n }),\n writerProjection:\n state.writerProjection?.documentId === currentRecord.documentId\n ? state.writerProjection\n : undefined,\n });\n}\n\nexport async function requestRemoteDocumentSync(\n input: RequestRemoteDocumentSyncInput,\n): Promise<DocumentSyncAttempt | null> {\n const {\n currentRecord,\n generation,\n pendingUpdates,\n state,\n unavailableWriterLogMessage,\n } = input;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n // Captured before the network round trip: a hint that lands meanwhile\n // must keep the response's projection out of the cache.\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n const runtime = state.runtime;\n if (!currentRecord.documentId) return null;\n\n const requestedPullContinuation = state.pullContinuation;\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(unavailableWriterLogMessage);\n return null;\n }\n\n const synced = await runRemoteDocumentSync(\n input,\n author,\n currentRecord.documentId,\n requestedPullContinuation,\n );\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n if (!synced) return null;\n\n const outgoingUpdateCount = input.queuedUpdateCount ?? pendingUpdates.length;\n return createDocumentSyncAttempt({\n currentRecord,\n outgoingUpdateCount,\n policyOperation: input.policyOperation,\n requestedPullContinuation,\n synced,\n writerProjectionGeneration,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncRequest.js","sourceRoot":"","sources":["syncRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAC7E,OAAO,EACL,qCAAqC,EAErC,uBAAuB,EAGvB,qBAAqB,EACrB,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAKL,wBAAwB,GACzB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,uCAAuC,EAAE,MAAM,gCAAgC,CAAC;AACzF,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAC1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EACL,2BAA2B,GAC5B,GAAG,KAAK,CAAC;IACV,IAAI,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1E,sEAAsE;IACtE,wDAAwD;IACxD,MAAM,0BAA0B,GAAG,KAAK,CAAC,0BAA0B,CAAC;IAEpE,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC9B,IAAI,CAAC,aAAa,CAAC,UAAU;QAAE,OAAO,IAAI,CAAC;IAE3C,MAAM,yBAAyB,GAAG,KAAK,CAAC,gBAAgB,CAAC;IAEzD,MAAM,MAAM,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;IACpD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,qBAAqB,CACxC,KAAK,EACL,MAAM,EACN,aAAa,CAAC,UAAU,EACxB,yBAAyB,CAC1B,CAAC;IACF,IAAI,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1E,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IAEzB,MAAM,mBAAmB,GAAG,KAAK,CAAC,iBAAiB,IAAI,cAAc,CAAC,MAAM,CAAC;IAC7E,OAAO,yBAAyB,CAAC;QAC/B,aAAa;QACb,mBAAmB;QACnB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,yBAAyB;QACzB,MAAM;QACN,0BAA0B;KAC3B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport { isRejectedDecodedProjection } from \"@tearleads/validators/response\";\nimport {\n createDocumentWriterPublicKeyResolver,\n type DocumentRecord,\n deletePersistedDocument,\n type ExecSql,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n validateDocumentSyncUpdateImports,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { parkForAncestorRepair } from \"../ancestorRepairPark\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type DocumentSyncAttempt,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { invalidateDocumentStorePullContinuation } from \"./pullContinuationInvalidation\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport {\n documentIncomingUpdateIsolationFailureHandler,\n documentRevalidationFailureHandler,\n documentTerminalSubmitFailureHandler,\n} from \"./syncShared\";\nimport { documentSyncContextMatches } from \"./syncUpdateImport\";\n\n/**\n * Destroying queued local edits here is settled policy, not an oversight\n * (docs/sync-edge-cases.md row 1): deletion is a privacy operation, so an\n * authoritative remote delete removes the document and its unsynced edits\n * everywhere with no preservation copy. Quarantine/export were rejected —\n * they retain or re-upload content the user deliberately destroyed.\n */\nexport async function deleteUpstreamDeletedDocument(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n requestRecord: DocumentRecord,\n remoteDocumentId: string,\n commitPurgeProof?: (transactionExecSql: ExecSql) => Promise<void>,\n) {\n await chainIdentityWrite(state, async () => {\n if (\n !isDocumentStoreSyncGenerationCurrent(state, generation) ||\n !documentSyncContextMatches(state.record, requestRecord, remoteDocumentId)\n ) {\n return;\n }\n\n const canDeleteCapturedDocument = () =>\n isDocumentStoreSyncGenerationCurrent(state, generation) &&\n documentSyncContextMatches(state.record, requestRecord, remoteDocumentId);\n let removedInMutation = false;\n const deletionStarted = await deletePersistedDocument({\n beforeDeleteInTransaction: commitPurgeProof,\n canStartDurableMutation: canDeleteCapturedDocument,\n deleteDocumentPlacements: state.runtime.deleteDocumentPlacements,\n documentProjectors: state.runtime.infra.documentProjectors,\n execSql: generation.execSql,\n expectedRecord: requestRecord,\n localId: requestRecord.id,\n // Invalidate the store generation INSIDE the deletion mutation: a\n // terminal failure handler queued behind it then observes the stale\n // generation and cannot resurrect a failure row the deletes removed.\n onDeletedInMutation: () => {\n if (canDeleteCapturedDocument()) {\n markDocumentStoreRemoved(state);\n removedInMutation = true;\n }\n },\n persistence: state.persistence,\n });\n if (!deletionStarted || !removedInMutation) {\n return;\n }\n void runDocumentOrphanMaintenance(state);\n state.runtime.util.log(\n `Documents: removed local document ${state.localId} after remote deletion.`,\n );\n });\n}\n\nfunction createDocumentSyncAttempt(input: {\n currentRecord: DocumentRecord;\n outgoingUpdateCount: number;\n policyOperation: PrincipalPolicyOperation;\n requestedPullContinuation: DocumentStoreState[\"pullContinuation\"];\n synced: DocumentSyncAttempt[\"synced\"];\n writerProjectionGeneration: number;\n}): DocumentSyncAttempt {\n return {\n consumedPullContinuation:\n input.synced.plan.request.pullCursor === undefined\n ? null\n : input.requestedPullContinuation,\n outgoingUpdateCount: input.outgoingUpdateCount,\n policyOperation: input.policyOperation,\n requestRecord: input.currentRecord,\n synced: input.synced,\n writerProjectionGeneration: input.writerProjectionGeneration,\n };\n}\n\ninterface RequestRemoteDocumentSyncInput {\n allowRecoveryBaseline?: boolean | undefined;\n currentDoc: DocumentState;\n currentRecord: DocumentRecord;\n encapsulationKeyPair: EncapsulationKeyPair;\n generation: DocumentStoreSyncGeneration;\n onOutgoingUpdatesMaterialized?:\n | ((updateIds: readonly string[]) => void)\n | undefined;\n pendingUpdates: PendingUpdateRecord[];\n /** The pass or workflow operation the sync's policy reads belong to. */\n policyOperation: PrincipalPolicyOperation;\n queuedUpdateCount?: number | undefined;\n state: DocumentStoreState;\n unavailableWriterLogMessage: string;\n}\n\n/** Where the document's pull stands, which decides whether a pause holds it. */\nfunction pullPosition(\n record: RequestRemoteDocumentSyncInput[\"currentRecord\"],\n continuation: DocumentStoreState[\"pullContinuation\"],\n) {\n return {\n minLsn: record.lastCommitLsn ?? undefined,\n pullContinuation: continuation ?? undefined,\n pullRecoveryRequired: record.pullContinuationRecoveryRequired === true,\n };\n}\n\nfunction runRemoteDocumentSync(\n input: RequestRemoteDocumentSyncInput,\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>,\n documentId: string,\n requestedPullContinuation: DocumentStoreState[\"pullContinuation\"],\n) {\n const { currentDoc, currentRecord, generation, pendingUpdates, state } =\n input;\n const runtime = state.runtime;\n const writerProjectionGenerationAtStart = state.writerProjectionGeneration;\n state.awaitingAncestorRepair = false;\n // The generation's API client and executor with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: input.encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n return remoteDocuments.syncRemoteDocument({\n author,\n // Heal a stale content-key bundle from this full-history snapshot. Rotation\n // settlement disables this: it may submit only the ordinary local stream.\n ...(input.allowRecoveryBaseline === false\n ? {}\n : {\n buildRotationSnapshot: async () =>\n exportFullHistorySnapshot(currentDoc),\n }),\n documentId,\n localVersionVector: encodeVersionVector(currentDoc),\n ...pullPosition(currentRecord, requestedPullContinuation),\n onRemoteDocumentDeleted: ({ commitPurgeProof, documentId }) =>\n deleteUpstreamDeletedDocument(\n state,\n generation,\n currentRecord,\n documentId,\n commitPurgeProof,\n ),\n onSyncAbandoned: (reason) => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return;\n const hintLandedMidPass = parkForAncestorRepair(\n state,\n reason,\n writerProjectionGenerationAtStart,\n );\n if (hintLandedMidPass) requestDocumentStoreSync(state);\n },\n onSyncTrace: (line) => runtime.util.log(`Documents: ${line}`),\n onReadOnlyProjectionFailure: documentRevalidationFailureHandler(\n state,\n generation,\n ),\n onIncomingUpdateIsolationFailure:\n documentIncomingUpdateIsolationFailureHandler(state, generation),\n onOutgoingUpdatesMaterialized: input.onOutgoingUpdatesMaterialized,\n onPullContinuationInvalidated: (continuation) =>\n invalidateDocumentStorePullContinuation({\n continuation,\n currentRecord,\n generation,\n state,\n }),\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n pendingUpdates,\n persistedState: currentRecord,\n rekeyPendingUpdate: state.persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Documents\",\n runtime,\n writerKeyLabel: \"writer key\",\n }),\n stillCurrent: () => isDocumentStoreSyncGenerationCurrent(state, generation),\n validateIncomingUpdates: (result) =>\n validateDocumentSyncUpdateImports({\n currentDocument: currentDoc,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n }),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n }),\n writerProjection:\n state.writerProjection?.documentId === currentRecord.documentId &&\n !isRejectedDecodedProjection(state.writerProjection)\n ? state.writerProjection\n : undefined,\n });\n}\n\nexport async function requestRemoteDocumentSync(\n input: RequestRemoteDocumentSyncInput,\n): Promise<DocumentSyncAttempt | null> {\n const {\n currentRecord,\n generation,\n pendingUpdates,\n state,\n unavailableWriterLogMessage,\n } = input;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n // Captured before the network round trip: a hint that lands meanwhile\n // must keep the response's projection out of the cache.\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n const runtime = state.runtime;\n if (!currentRecord.documentId) return null;\n\n const requestedPullContinuation = state.pullContinuation;\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(unavailableWriterLogMessage);\n return null;\n }\n\n const synced = await runRemoteDocumentSync(\n input,\n author,\n currentRecord.documentId,\n requestedPullContinuation,\n );\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n if (!synced) return null;\n\n const outgoingUpdateCount = input.queuedUpdateCount ?? pendingUpdates.length;\n return createDocumentSyncAttempt({\n currentRecord,\n outgoingUpdateCount,\n policyOperation: input.policyOperation,\n requestedPullContinuation,\n synced,\n writerProjectionGeneration,\n });\n}\n"]}
|