@tearleads/client-sdk 0.1.243 → 0.1.246
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/container-contents/containerContentsPersistence.js +2 -0
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataRevalidations.d.ts +22 -0
- package/data/persistence/container-contents/containerMetadataRevalidations.js +52 -0
- package/data/persistence/container-contents/containerMetadataRevalidations.js.map +1 -0
- 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/data/sqlite/schema/containerSchema.d.ts +173 -0
- package/data/sqlite/schema/containerSchema.js +18 -0
- package/data/sqlite/schema/containerSchema.js.map +1 -1
- package/data/sqlite/schema/index.d.ts +84 -1
- package/data/sqlite/schema/index.js +1 -1
- package/data/sqlite/schema/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +56 -8
- package/internal/api-client/client/apiClientContext.d.ts +1 -0
- package/internal/api-client/client/containerMutations.d.ts +11 -0
- package/internal/api-client/client/containerReads.d.ts +1 -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/accessManifestVerificationTypes.d.ts +8 -2
- package/internal/crypto/keying/accessManifestVerificationTypes.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/containerAccess.js +1 -1
- package/internal/crypto/keying/containerAccess.js.map +1 -1
- package/internal/crypto/keying/documentAccess.js +1 -1
- package/internal/crypto/keying/documentAccess.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/crypto/organizationReplacement.js +5 -6
- package/internal/crypto/organizationReplacement.js.map +1 -1
- package/internal/loro/document.d.ts +5 -0
- package/internal/loro/document.js +17 -0
- package/internal/loro/document.js.map +1 -1
- package/internal/loro/index.d.ts +1 -1
- package/internal/loro/index.js +1 -1
- package/internal/loro/index.js.map +1 -1
- package/internal/validators/operation/attachments.d.ts +0 -12
- package/internal/validators/operation/auth.d.ts +40 -76
- package/internal/validators/operation/containerMutations.d.ts +45 -49
- package/internal/validators/operation/containerMutations.js +1 -1
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/internal/validators/operation/containerReads.d.ts +2 -0
- package/internal/validators/operation/documentMutations.d.ts +12 -24
- package/internal/validators/operation/documentSync.d.ts +0 -4
- package/internal/validators/operation/organizations.d.ts +48 -88
- package/internal/validators/operation/principals.d.ts +16 -16
- package/internal/validators/request/blob.d.ts +0 -12
- package/internal/validators/request/container.d.ts +0 -16
- package/internal/validators/request/container.js +0 -2
- package/internal/validators/request/container.js.map +1 -1
- package/internal/validators/request/containerMetadata.d.ts +0 -20
- package/internal/validators/request/document.d.ts +0 -22
- package/internal/validators/request/document.js +0 -1
- package/internal/validators/request/document.js.map +1 -1
- package/internal/validators/request/documentSyncSchema.d.ts +0 -4
- package/internal/validators/request/documentSyncSchema.js +0 -1
- package/internal/validators/request/documentSyncSchema.js.map +1 -1
- package/internal/validators/request/organization.d.ts +0 -16
- package/internal/validators/request/organizationProvisioning.d.ts +0 -242
- package/internal/validators/request/principal.d.ts +0 -20
- package/internal/validators/request/registration.d.ts +0 -76
- 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 +24 -0
- package/internal/validators/response/container.js +4 -0
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/containerMetadata.d.ts +8 -0
- package/internal/validators/response/containerParentLanes.d.ts +2 -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/container-contents/containerContentsStore.js +2 -0
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/hydration/startupHydration.js +6 -2
- package/stores/container-contents/hydration/startupHydration.js.map +1 -1
- package/stores/container-contents/state.js +5 -1
- package/stores/container-contents/state.js.map +1 -1
- package/stores/container-contents/syncAgent/metadataRevalidation.js +79 -0
- package/stores/container-contents/syncAgent/metadataRevalidation.js.map +1 -0
- package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +6 -0
- package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
- package/stores/container-contents/syncAgent/syncLaneIteration.js +110 -23
- package/stores/container-contents/syncAgent/syncLaneIteration.js.map +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/move/acceptedMoveSettlement.js +3 -0
- package/workflows/container-contents/container-state/move/acceptedMoveSettlement.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/container-state/remote.js +3 -0
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +1 -0
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/metadata/index.js +9 -3
- package/workflows/container-contents/metadata/index.js.map +1 -1
- package/workflows/container-contents/metadata/metadataSyncFollowup.js +9 -0
- package/workflows/container-contents/metadata/metadataSyncFollowup.js.map +1 -1
- package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -0
- package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
- package/workflows/container-contents/remoteHydration/index.js +9 -0
- package/workflows/container-contents/remoteHydration/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +31 -0
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +9 -1
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/containers/child/mutationRequestCore.js +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/recite.js +4 -2
- package/workflows/containers/child/recite.js.map +1 -1
- package/workflows/containers/child/recitePlan.js +0 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/root/create.js +0 -1
- package/workflows/containers/root/create.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/index.js +0 -1
- package/workflows/documents/linkSet/index.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/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +17 -10
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.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
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -2
|
@@ -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,O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C,CAAC;IAC9D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,yBAAyB,GAAkC,EAAE,CAAC;IACpE,KAAK,MAAM,IAAI,IAAI,UAAU,CAAC,yBAAyB,EAAE,CAAC;QACxD,MAAM,OAAO,GAAG,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;QAC5D,IAAI,CAAC,OAAO;YAAE,OAAO,IAAI,CAAC;QAC1B,yBAAyB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC1C,CAAC;IACD,MAAM,CAAC,SAAS,EAAE,GAAG,UAAU,CAAC,GAAG,yBAAyB,CAAC;IAC7D,IAAI,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;IAC5B,OAAO;QACL,GAAG,UAAU;QACb,yBAAyB,EAAE,CAAC,SAAS,EAAE,GAAG,UAAU,CAAC;QACrD,gCAAgC,EAC9B,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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yBAAyB,EAAE,CAAC;QACxD,MAAM,OAAO,GAAG,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;QAC5D,IAAI,CAAC,OAAO;YAAE,OAAO,IAAI,CAAC;QAC1B,yBAAyB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC1C,CAAC;IACD,MAAM,CAAC,SAAS,EAAE,GAAG,UAAU,CAAC,GAAG,yBAAyB,CAAC;IAC7D,IAAI,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;IAC5B,OAAO,eAAe,CACpB;QACE,GAAG,UAAU;QACb,yBAAyB,EAAE,CAAC,SAAS,EAAE,GAAG,UAAU,CAAC;QACrD,gCAAgC,EAC9B,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,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
|
@@ -15,6 +15,7 @@ import { chainRemoteContainerTask } from "./remoteWrites/remoteWriteQueue.js";
|
|
|
15
15
|
import { captureContainerWriteGeneration } from "./remoteWrites/writeGeneration.js";
|
|
16
16
|
import { createContainerContentsStoreState, subscribeToContainerContentsStore, updateContainerContentsSnapshot, updateContainerContentsStorePersistence, updateContainerContentsStoreRuntime, } from "./state.js";
|
|
17
17
|
import { createContainerContentsStoreSyncAgent, } from "./syncAgent/index.js";
|
|
18
|
+
import { oweContainerMetadataRead } from "./syncAgent/metadataRevalidation.js";
|
|
18
19
|
import { findRootContainerState } from "./systemContainers/systemContainerLookup.js";
|
|
19
20
|
const containerContentsStoresByScope = new WeakMap();
|
|
20
21
|
function applyContainerContentsStoreOptions(state, syncAgent, options) {
|
|
@@ -42,6 +43,7 @@ function createContainerContentsStoreSyncHost(state) {
|
|
|
42
43
|
requestDocumentPriming: () => {
|
|
43
44
|
state.documentStoresNeedPriming = true;
|
|
44
45
|
},
|
|
46
|
+
requestMetadataRevalidation: (request) => oweContainerMetadataRead(state, request),
|
|
45
47
|
updateSnapshot: () => updateContainerContentsSnapshot(state),
|
|
46
48
|
};
|
|
47
49
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerContentsStore.js","sourceRoot":"","sources":["containerContentsStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kCAAkC,EAAE,MAAM,oEAAoE,CAAC;AACxH,OAAO,EAEL,mCAAmC,GACpC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACnF,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,aAAa,EACb,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAC9D,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAC1E,OAAO,EAAE,2BAA2B,EAAE,MAAM,mDAAmD,CAAC;AAChG,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EACL,iCAAiC,EACjC,iCAAiC,EACjC,+BAA+B,EAC/B,uCAAuC,EACvC,mCAAmC,GACpC,MAAM,SAAS,CAAC;AACjB,OAAO,EAGL,qCAAqC,GACtC,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,0CAA0C,CAAC;AAOl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,GAAG,iCAAiC,CACjD,OAAO,EACP,mCAAmC,EACnC,OAAO,CACR,CAAC;IACF,8BAA8B,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IAC3D,OAAO,SAAS,CAAC,KAAK,CAAC;AACzB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,uCAAuC,CACrD,WAAwB;IAExB,MAAM,KAAK,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC9D,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,CAAC,sBAAsB,EAAE,CAAC;IAC/B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport { getCachedContainerWriterProjection } from \"../../workflows/container-contents/container-state/projectionCache\";\nimport {\n type ContainerContentsPersistence,\n defaultContainerContentsPersistence,\n} from \"../../workflows/container-contents/containerPersistence\";\nimport { persistContainerState } from \"./containerState/containerStatePersistence\";\nimport { createTreeRefreshMethods } from \"./hydration/remoteHydrationRefresh\";\nimport {\n createChildContainer,\n deleteContainer,\n ensureSystemContainer,\n moveContainer,\n renameContainer,\n} from \"./operations\";\nimport { emptyTrash } from \"./operations/emptyTrashOperation\";\nimport {\n prepareContainerGroupRewrap,\n verifyContainerGroupRewrapCurrent,\n} from \"./operations/groupRewrapOperation\";\nimport { purgeContainer } from \"./operations/purgeContainerOperation\";\nimport { chainPurgeAfterScopeMoves } from \"./operations/purgeMoveSettlementOperation\";\nimport { setContainerIcon } from \"./operations/setContainerIconOperation\";\nimport { setContainerPrimaryDocument } from \"./operations/setContainerPrimaryDocumentOperation\";\nimport {\n shareContainerWithGroup,\n shareContainerWithUser,\n} from \"./operations/shareOperations\";\nimport { chainContainerWrite } from \"./remoteWrites/localWriteQueue\";\nimport { chainRemoteContainerTask } from \"./remoteWrites/remoteWriteQueue\";\nimport { captureContainerWriteGeneration } from \"./remoteWrites/writeGeneration\";\nimport {\n createContainerContentsStoreState,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStorePersistence,\n updateContainerContentsStoreRuntime,\n} from \"./state\";\nimport {\n type ContainerContentsStoreRuntime,\n type ContainerContentsStoreSyncAgent,\n createContainerContentsStoreSyncAgent,\n} from \"./syncAgent\";\nimport { findRootContainerState } from \"./systemContainers/systemContainerLookup\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreState,\n} from \"./types\";\n\nconst containerContentsStoresByScope = new WeakMap<\n DomainScope,\n ContainerContentsStoreEntry\n>();\n\ninterface ContainerContentsStoreEntry {\n requestDocumentPriming: () => void;\n store: ContainerContentsStore;\n updateOptions: (options: ContainerContentsStoreOptions) => void;\n}\n\nfunction applyContainerContentsStoreOptions(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n options: ContainerContentsStoreOptions,\n): void {\n if (\"logLabel\" in options) {\n state.logLabel = options.logLabel;\n }\n\n if (\"persistence\" in options) {\n updateContainerContentsStorePersistence(\n state,\n options.persistence ?? defaultContainerContentsPersistence,\n syncAgent,\n );\n }\n}\n\nfunction getCachedContainerWriterProjectionForStore(\n state: ContainerContentsStoreState,\n containerId: string,\n) {\n const containerState = state.containersById.get(containerId);\n return containerState\n ? getCachedContainerWriterProjection(containerState)\n : null;\n}\n\nfunction createContainerContentsStoreSyncHost(\n state: ContainerContentsStoreState,\n): Parameters<typeof createContainerContentsStoreSyncAgent>[0][\"host\"] {\n return {\n persistContainerState: (\n containerState,\n patch,\n updateView,\n saveOptions,\n mutationOptions,\n ) =>\n persistContainerState(state, containerState, {\n patch,\n updateView,\n saveOptions,\n ...mutationOptions,\n }),\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n },\n updateSnapshot: () => updateContainerContentsSnapshot(state),\n };\n}\n\ntype ContainerWriteMethods = Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"moveContainer\"\n | \"prepareGroupRewrap\"\n | \"purgeContainer\"\n | \"renameContainer\"\n | \"setContainerIcon\"\n | \"setContainerPrimaryDocument\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n>;\n\n// The group-rewrap builder verifies any required existing grant before capturing\n// the container KEK, then returns a check/rewrap pair. A verified non-match is\n// distinct from an unavailable preparation so security-critical callers can\n// no-op unrelated groups without failing open for a real grant.\nfunction createPrepareGroupRewrapMethod(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerContentsStore[\"prepareGroupRewrap\"] {\n return async (containerId, groupId, accessLevel, options) => {\n const preparation = await chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n prepareContainerGroupRewrap(\n state,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n );\n return preparation?.status === \"prepared\"\n ? {\n isCurrent: (\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n ) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n verifyContainerGroupRewrapCurrent(\n state,\n containerId,\n groupId,\n accessLevel,\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n isCurrent,\n ),\n containerId,\n ),\n rewrap: () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n {\n ...options,\n knownContainerKeks: preparation.knownContainerKeks,\n // A prepared re-wrap is grant-preserving by definition, so\n // it never mints a grant and never needs the chosen name.\n requireExistingGrant: true,\n },\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n status: \"prepared\" as const,\n }\n : (preparation ?? null);\n };\n}\n\nfunction createContainerSharingMethods(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): Pick<ContainerWriteMethods, \"shareWithUser\" | \"shareWithGroup\"> {\n return {\n shareWithUser: (containerId, userId, accessLevel) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n async (isCurrent) => {\n // Sharing admits the recipient, so a pin observed on first sight is\n // not enough: a verified identity link (or this device's keys) must\n // have established it, or the full-bundle signed roster. The\n // check runs inside the write scope, which must still be current\n // once it returns.\n await state.runtime.requireVerifiedRecipient(userId, accessLevel);\n if (!isCurrent()) return false;\n return shareContainerWithUser(\n state,\n syncAgent,\n containerId,\n userId,\n accessLevel,\n isCurrent,\n );\n },\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n shareWithGroup: (containerId, groupId, accessLevel, options) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n };\n}\n\nfunction createDeleteContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"deleteContainer\"] {\n return (containerId) => {\n const current = captureContainerWriteGeneration(state);\n const remoteDelete = () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n deleteContainer(state, syncAgent, containerId, isCurrent),\n containerId,\n ).then((node) => node !== null);\n if (state.containersById.get(containerId)?.record.documentId)\n return remoteDelete();\n let promoted = false;\n return chainContainerWrite(\n state,\n (isCurrent) => {\n // Promotion can win while this local operation was queued. Hand it to\n // the remote queue after releasing the local chain, before any HTTP I/O.\n promoted = Boolean(\n state.containersById.get(containerId)?.record.documentId,\n );\n return promoted\n ? Promise.resolve(null)\n : deleteContainer(state, syncAgent, containerId, isCurrent);\n },\n [containerId],\n ).then((node) => (promoted && current() ? remoteDelete() : node !== null));\n };\n}\n\nfunction createEnsureSystemContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"ensureSystemContainer\"] {\n return (systemSlot, name, options) => {\n const work = (isCurrent: () => boolean) =>\n ensureSystemContainer(\n state,\n syncAgent,\n systemSlot,\n name,\n options,\n isCurrent,\n );\n const rootId = findRootContainerState(state)?.container.id;\n return options?.deferRemoteBootstrap\n ? chainContainerWrite(state, work, [])\n : chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n work,\n rootId ? { rootId, systemSlot } : undefined,\n );\n };\n}\n\nexport function createContainerWriteMethods(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerWriteMethods {\n return {\n ...createContainerSharingMethods(state, syncAgent),\n createChild: (parentId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n createChildContainer(state, syncAgent, parentId, name, isCurrent),\n [parentId],\n ),\n deleteContainer: createDeleteContainerMethod(state, syncAgent),\n purgeContainer: (containerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n containerId,\n options,\n (isCurrent) =>\n purgeContainer(state, syncAgent, containerId, options, isCurrent),\n ),\n emptyTrash: (trashContainerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n trashContainerId,\n options,\n (isCurrent) =>\n emptyTrash(state, syncAgent, trashContainerId, options, isCurrent),\n ),\n ensureSystemContainer: createEnsureSystemContainerMethod(state, syncAgent),\n moveContainer: (containerId, parentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n moveContainer(state, syncAgent, containerId, parentId, isCurrent),\n [containerId, parentId],\n containerId,\n ),\n prepareGroupRewrap: createPrepareGroupRewrapMethod(state, syncAgent),\n renameContainer: (containerId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n renameContainer(state, syncAgent, containerId, name, isCurrent),\n [containerId],\n ),\n setContainerPrimaryDocument: (containerId, documentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerPrimaryDocument(\n state,\n syncAgent,\n containerId,\n documentId,\n isCurrent,\n ),\n [containerId],\n ),\n setContainerIcon: (containerId, icon) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerIcon(state, syncAgent, containerId, icon, isCurrent),\n [containerId],\n ),\n };\n}\n\nfunction createContainerContentsStoreEntry(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStoreEntry {\n const state = createContainerContentsStoreState(\n initialRuntime,\n options.persistence ?? persistence,\n options.logLabel,\n );\n const syncAgent = createContainerContentsStoreSyncAgent({\n host: createContainerContentsStoreSyncHost(state),\n state,\n });\n const writeMethods = createContainerWriteMethods(state, syncAgent);\n\n return {\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n syncAgent.scheduleSync();\n },\n store: {\n ...writeMethods,\n ...createTreeRefreshMethods(state, syncAgent),\n // Force an on-demand local SQLite re-read (see the interface doc): arm the\n // gate refreshLocalContainerStates otherwise requires, which the runtime\n // auto-arms only on a context transition an on-demand caller cannot rely on.\n refreshLocalContainers: () => {\n state.localContainersNeedRefresh = true;\n return syncAgent.refreshLocalContainers();\n },\n requestSync: () => syncAgent.scheduleSync(),\n getCachedContainerWriterProjection: (containerId) =>\n getCachedContainerWriterProjectionForStore(state, containerId),\n getSnapshot: () => state.snapshot,\n subscribe: (listener) =>\n subscribeToContainerContentsStore(state, listener),\n updateRuntime: (runtime) =>\n updateContainerContentsStoreRuntime(state, runtime, syncAgent),\n },\n updateOptions: (nextOptions) =>\n applyContainerContentsStoreOptions(state, syncAgent, nextOptions),\n };\n}\n\nexport function createContainerContentsStore(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n return createContainerContentsStoreEntry(initialRuntime, persistence, options)\n .store;\n}\n\nexport function getOrCreateContainerContentsStore(\n domainScope: DomainScope,\n runtime: ContainerContentsStoreRuntime,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n const existingEntry = containerContentsStoresByScope.get(domainScope);\n if (existingEntry) {\n existingEntry.updateOptions(options);\n return existingEntry.store;\n }\n\n const nextEntry = createContainerContentsStoreEntry(\n runtime,\n defaultContainerContentsPersistence,\n options,\n );\n containerContentsStoresByScope.set(domainScope, nextEntry);\n return nextEntry.store;\n}\n\n/**\n * Arm the next structural pass's document-priming scan for a domain scope.\n * Priming normally re-arms only on store creation and topology changes, so a\n * caller that just tore down a document's local state uses this to have the\n * still-listed server document re-created without waiting for an app\n * restart. Returns false when the scope has no container-contents store yet;\n * the startup priming pass covers that case.\n */\nexport function requestContainerContentsDocumentPriming(\n domainScope: DomainScope,\n): boolean {\n const entry = containerContentsStoresByScope.get(domainScope);\n if (!entry) {\n return false;\n }\n\n entry.requestDocumentPriming();\n return true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerContentsStore.js","sourceRoot":"","sources":["containerContentsStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kCAAkC,EAAE,MAAM,oEAAoE,CAAC;AACxH,OAAO,EAEL,mCAAmC,GACpC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACnF,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,aAAa,EACb,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAC9D,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAC1E,OAAO,EAAE,2BAA2B,E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AO,EAAE,SAAS,CAAC;SACjE;QACD,aAAa,EAAE,CAAC,WAAW,EAAE,EAAE,CAC7B,kCAAkC,CAAC,KAAK,EAAE,SAAS,EAAE,WAAW,CAAC;KACpE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,cAA6C,EAC7C,cAA4C,mCAAmC,EAC/E,UAAyC,EAAE;IAE3C,OAAO,iCAAiC,CAAC,cAAc,EAAE,WAAW,EAAE,OAAO,CAAC;SAC3E,KAAK,CAAC;AACX,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,WAAwB,EACxB,OAAsC,EACtC,UAAyC,EAAE;IAE3C,MAAM,aAAa,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACtE,IAAI,aAAa,EAAE,CAAC;QAClB,aAAa,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QACrC,OAAO,aAAa,CAAC,KAAK,CAAC;IAC7B,CAAC;IAED,MAAM,SAAS,GAAG,iCAAiC,CACjD,OAAO,EACP,mCAAmC,EACnC,OAAO,CACR,CAAC;IACF,8BAA8B,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IAC3D,OAAO,SAAS,CAAC,KAAK,CAAC;AACzB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,uCAAuC,CACrD,WAAwB;IAExB,MAAM,KAAK,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC9D,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,CAAC,sBAAsB,EAAE,CAAC;IAC/B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport { getCachedContainerWriterProjection } from \"../../workflows/container-contents/container-state/projectionCache\";\nimport {\n type ContainerContentsPersistence,\n defaultContainerContentsPersistence,\n} from \"../../workflows/container-contents/containerPersistence\";\nimport { persistContainerState } from \"./containerState/containerStatePersistence\";\nimport { createTreeRefreshMethods } from \"./hydration/remoteHydrationRefresh\";\nimport {\n createChildContainer,\n deleteContainer,\n ensureSystemContainer,\n moveContainer,\n renameContainer,\n} from \"./operations\";\nimport { emptyTrash } from \"./operations/emptyTrashOperation\";\nimport {\n prepareContainerGroupRewrap,\n verifyContainerGroupRewrapCurrent,\n} from \"./operations/groupRewrapOperation\";\nimport { purgeContainer } from \"./operations/purgeContainerOperation\";\nimport { chainPurgeAfterScopeMoves } from \"./operations/purgeMoveSettlementOperation\";\nimport { setContainerIcon } from \"./operations/setContainerIconOperation\";\nimport { setContainerPrimaryDocument } from \"./operations/setContainerPrimaryDocumentOperation\";\nimport {\n shareContainerWithGroup,\n shareContainerWithUser,\n} from \"./operations/shareOperations\";\nimport { chainContainerWrite } from \"./remoteWrites/localWriteQueue\";\nimport { chainRemoteContainerTask } from \"./remoteWrites/remoteWriteQueue\";\nimport { captureContainerWriteGeneration } from \"./remoteWrites/writeGeneration\";\nimport {\n createContainerContentsStoreState,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStorePersistence,\n updateContainerContentsStoreRuntime,\n} from \"./state\";\nimport {\n type ContainerContentsStoreRuntime,\n type ContainerContentsStoreSyncAgent,\n createContainerContentsStoreSyncAgent,\n} from \"./syncAgent\";\nimport { oweContainerMetadataRead } from \"./syncAgent/metadataRevalidation\";\nimport { findRootContainerState } from \"./systemContainers/systemContainerLookup\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreState,\n} from \"./types\";\n\nconst containerContentsStoresByScope = new WeakMap<\n DomainScope,\n ContainerContentsStoreEntry\n>();\n\ninterface ContainerContentsStoreEntry {\n requestDocumentPriming: () => void;\n store: ContainerContentsStore;\n updateOptions: (options: ContainerContentsStoreOptions) => void;\n}\n\nfunction applyContainerContentsStoreOptions(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n options: ContainerContentsStoreOptions,\n): void {\n if (\"logLabel\" in options) {\n state.logLabel = options.logLabel;\n }\n\n if (\"persistence\" in options) {\n updateContainerContentsStorePersistence(\n state,\n options.persistence ?? defaultContainerContentsPersistence,\n syncAgent,\n );\n }\n}\n\nfunction getCachedContainerWriterProjectionForStore(\n state: ContainerContentsStoreState,\n containerId: string,\n) {\n const containerState = state.containersById.get(containerId);\n return containerState\n ? getCachedContainerWriterProjection(containerState)\n : null;\n}\n\nfunction createContainerContentsStoreSyncHost(\n state: ContainerContentsStoreState,\n): Parameters<typeof createContainerContentsStoreSyncAgent>[0][\"host\"] {\n return {\n persistContainerState: (\n containerState,\n patch,\n updateView,\n saveOptions,\n mutationOptions,\n ) =>\n persistContainerState(state, containerState, {\n patch,\n updateView,\n saveOptions,\n ...mutationOptions,\n }),\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n },\n requestMetadataRevalidation: (request) =>\n oweContainerMetadataRead(state, request),\n updateSnapshot: () => updateContainerContentsSnapshot(state),\n };\n}\n\ntype ContainerWriteMethods = Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"moveContainer\"\n | \"prepareGroupRewrap\"\n | \"purgeContainer\"\n | \"renameContainer\"\n | \"setContainerIcon\"\n | \"setContainerPrimaryDocument\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n>;\n\n// The group-rewrap builder verifies any required existing grant before capturing\n// the container KEK, then returns a check/rewrap pair. A verified non-match is\n// distinct from an unavailable preparation so security-critical callers can\n// no-op unrelated groups without failing open for a real grant.\nfunction createPrepareGroupRewrapMethod(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerContentsStore[\"prepareGroupRewrap\"] {\n return async (containerId, groupId, accessLevel, options) => {\n const preparation = await chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n prepareContainerGroupRewrap(\n state,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n );\n return preparation?.status === \"prepared\"\n ? {\n isCurrent: (\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n ) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n verifyContainerGroupRewrapCurrent(\n state,\n containerId,\n groupId,\n accessLevel,\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n isCurrent,\n ),\n containerId,\n ),\n rewrap: () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n {\n ...options,\n knownContainerKeks: preparation.knownContainerKeks,\n // A prepared re-wrap is grant-preserving by definition, so\n // it never mints a grant and never needs the chosen name.\n requireExistingGrant: true,\n },\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n status: \"prepared\" as const,\n }\n : (preparation ?? null);\n };\n}\n\nfunction createContainerSharingMethods(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): Pick<ContainerWriteMethods, \"shareWithUser\" | \"shareWithGroup\"> {\n return {\n shareWithUser: (containerId, userId, accessLevel) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n async (isCurrent) => {\n // Sharing admits the recipient, so a pin observed on first sight is\n // not enough: a verified identity link (or this device's keys) must\n // have established it, or the full-bundle signed roster. The\n // check runs inside the write scope, which must still be current\n // once it returns.\n await state.runtime.requireVerifiedRecipient(userId, accessLevel);\n if (!isCurrent()) return false;\n return shareContainerWithUser(\n state,\n syncAgent,\n containerId,\n userId,\n accessLevel,\n isCurrent,\n );\n },\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n shareWithGroup: (containerId, groupId, accessLevel, options) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n };\n}\n\nfunction createDeleteContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"deleteContainer\"] {\n return (containerId) => {\n const current = captureContainerWriteGeneration(state);\n const remoteDelete = () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n deleteContainer(state, syncAgent, containerId, isCurrent),\n containerId,\n ).then((node) => node !== null);\n if (state.containersById.get(containerId)?.record.documentId)\n return remoteDelete();\n let promoted = false;\n return chainContainerWrite(\n state,\n (isCurrent) => {\n // Promotion can win while this local operation was queued. Hand it to\n // the remote queue after releasing the local chain, before any HTTP I/O.\n promoted = Boolean(\n state.containersById.get(containerId)?.record.documentId,\n );\n return promoted\n ? Promise.resolve(null)\n : deleteContainer(state, syncAgent, containerId, isCurrent);\n },\n [containerId],\n ).then((node) => (promoted && current() ? remoteDelete() : node !== null));\n };\n}\n\nfunction createEnsureSystemContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"ensureSystemContainer\"] {\n return (systemSlot, name, options) => {\n const work = (isCurrent: () => boolean) =>\n ensureSystemContainer(\n state,\n syncAgent,\n systemSlot,\n name,\n options,\n isCurrent,\n );\n const rootId = findRootContainerState(state)?.container.id;\n return options?.deferRemoteBootstrap\n ? chainContainerWrite(state, work, [])\n : chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n work,\n rootId ? { rootId, systemSlot } : undefined,\n );\n };\n}\n\nexport function createContainerWriteMethods(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerWriteMethods {\n return {\n ...createContainerSharingMethods(state, syncAgent),\n createChild: (parentId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n createChildContainer(state, syncAgent, parentId, name, isCurrent),\n [parentId],\n ),\n deleteContainer: createDeleteContainerMethod(state, syncAgent),\n purgeContainer: (containerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n containerId,\n options,\n (isCurrent) =>\n purgeContainer(state, syncAgent, containerId, options, isCurrent),\n ),\n emptyTrash: (trashContainerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n trashContainerId,\n options,\n (isCurrent) =>\n emptyTrash(state, syncAgent, trashContainerId, options, isCurrent),\n ),\n ensureSystemContainer: createEnsureSystemContainerMethod(state, syncAgent),\n moveContainer: (containerId, parentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n moveContainer(state, syncAgent, containerId, parentId, isCurrent),\n [containerId, parentId],\n containerId,\n ),\n prepareGroupRewrap: createPrepareGroupRewrapMethod(state, syncAgent),\n renameContainer: (containerId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n renameContainer(state, syncAgent, containerId, name, isCurrent),\n [containerId],\n ),\n setContainerPrimaryDocument: (containerId, documentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerPrimaryDocument(\n state,\n syncAgent,\n containerId,\n documentId,\n isCurrent,\n ),\n [containerId],\n ),\n setContainerIcon: (containerId, icon) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerIcon(state, syncAgent, containerId, icon, isCurrent),\n [containerId],\n ),\n };\n}\n\nfunction createContainerContentsStoreEntry(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStoreEntry {\n const state = createContainerContentsStoreState(\n initialRuntime,\n options.persistence ?? persistence,\n options.logLabel,\n );\n const syncAgent = createContainerContentsStoreSyncAgent({\n host: createContainerContentsStoreSyncHost(state),\n state,\n });\n const writeMethods = createContainerWriteMethods(state, syncAgent);\n\n return {\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n syncAgent.scheduleSync();\n },\n store: {\n ...writeMethods,\n ...createTreeRefreshMethods(state, syncAgent),\n // Force an on-demand local SQLite re-read (see the interface doc): arm the\n // gate refreshLocalContainerStates otherwise requires, which the runtime\n // auto-arms only on a context transition an on-demand caller cannot rely on.\n refreshLocalContainers: () => {\n state.localContainersNeedRefresh = true;\n return syncAgent.refreshLocalContainers();\n },\n requestSync: () => syncAgent.scheduleSync(),\n getCachedContainerWriterProjection: (containerId) =>\n getCachedContainerWriterProjectionForStore(state, containerId),\n getSnapshot: () => state.snapshot,\n subscribe: (listener) =>\n subscribeToContainerContentsStore(state, listener),\n updateRuntime: (runtime) =>\n updateContainerContentsStoreRuntime(state, runtime, syncAgent),\n },\n updateOptions: (nextOptions) =>\n applyContainerContentsStoreOptions(state, syncAgent, nextOptions),\n };\n}\n\nexport function createContainerContentsStore(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n return createContainerContentsStoreEntry(initialRuntime, persistence, options)\n .store;\n}\n\nexport function getOrCreateContainerContentsStore(\n domainScope: DomainScope,\n runtime: ContainerContentsStoreRuntime,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n const existingEntry = containerContentsStoresByScope.get(domainScope);\n if (existingEntry) {\n existingEntry.updateOptions(options);\n return existingEntry.store;\n }\n\n const nextEntry = createContainerContentsStoreEntry(\n runtime,\n defaultContainerContentsPersistence,\n options,\n );\n containerContentsStoresByScope.set(domainScope, nextEntry);\n return nextEntry.store;\n}\n\n/**\n * Arm the next structural pass's document-priming scan for a domain scope.\n * Priming normally re-arms only on store creation and topology changes, so a\n * caller that just tore down a document's local state uses this to have the\n * still-listed server document re-created without waiting for an app\n * restart. Returns false when the scope has no container-contents store yet;\n * the startup priming pass covers that case.\n */\nexport function requestContainerContentsDocumentPriming(\n domainScope: DomainScope,\n): boolean {\n const entry = containerContentsStoresByScope.get(domainScope);\n if (!entry) {\n return false;\n }\n\n entry.requestDocumentPriming();\n return true;\n}\n"]}
|
|
@@ -100,11 +100,15 @@ export async function hasStartupContainerSyncWork(state) {
|
|
|
100
100
|
if (containerIds.length === 0) {
|
|
101
101
|
return false;
|
|
102
102
|
}
|
|
103
|
-
const [containersWithPendingMetadata, containersWithPullContinuations] = await Promise.all([
|
|
103
|
+
const [containersWithPendingMetadata, containersWithPullContinuations, owedMetadataReads,] = await Promise.all([
|
|
104
104
|
state.persistence.listContainerIdsWithPendingUpdates(execSql, containerIds),
|
|
105
105
|
state.persistence.listContainerIdsWithPullContinuations(execSql, containerIds),
|
|
106
|
+
// A read a listing owed before the restart needs a pass even when the
|
|
107
|
+
// cached tree is fresh and no connection is acknowledged.
|
|
108
|
+
state.persistence.listContainerMetadataRevalidations(execSql),
|
|
106
109
|
]);
|
|
107
110
|
return (containersWithPendingMetadata.length > 0 ||
|
|
108
|
-
containersWithPullContinuations.length > 0
|
|
111
|
+
containersWithPullContinuations.length > 0 ||
|
|
112
|
+
owedMetadataReads.length > 0);
|
|
109
113
|
}
|
|
110
114
|
//# sourceMappingURL=startupHydration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"startupHydration.js","sourceRoot":"","sources":["startupHydration.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,gCAAgC,EAChC,6BAA6B,GAE9B,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,0BAA0B,EAAE,MAAM,gDAAgD,CAAC;AAE5F,MAAM,iCAAiC,GAAG,EAAE,GAAG,MAAM,CAAC;AAqBtD,SAAS,kCAAkC,CACzC,SAAiB,EACjB,KAAa;IAEb,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IAC1C,OAAO,CACL,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC;QAC5B,KAAK,GAAG,WAAW,IAAI,iCAAiC,CACzD,CAAC;AACJ,CAAC;AAED,SAAS,gCAAgC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IACf,CAAC;IACD,MAAM,CAAC,6BAA6B,EAAE,+BAA+B,CAAC,GACpE,MAAM,OAAO,CAAC,GAAG,CAAC;QAChB,KAAK,CAAC,WAAW,CAAC,kCAAkC,CAClD,OAAO,EACP,YAAY,CACb;QACD,KAAK,CAAC,WAAW,CAAC,qCAAqC,CACrD,OAAO,EACP,YAAY,CACb;KACF,CAAC,CAAC;IACL,OAAO,CACL,6BAA6B,CAAC,MAAM,GAAG,CAAC;QACxC,+BAA+B,CAAC,MAAM,GAAG,CAAC,CAC3C,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerContentsPersistence,\n ContainerSyncWatermarkRepository,\n createContainerParentSyncLane,\n type ExecSql,\n} from \"../../../workflows/container-contents/containerPersistence\";\nimport { hasStartupDocumentSyncWork } from \"../../../workflows/container-contents/documentPriming\";\nimport { isDatabaseUnavailableError } from \"../../../workflows/container-contents/syncLane\";\n\nconst STARTUP_REMOTE_HYDRATION_FRESH_MS = 15 * 60_000;\n\ninterface StartupHydrationState {\n containerParentIdsNeedingHydration: Set<string | null>;\n containersById: ReadonlyMap<\n string,\n {\n container: {\n metadataDocumentId?: string | null | undefined;\n parentId: string | null;\n };\n }\n >;\n rootLaneHydrated: boolean;\n runtime: {\n auth: { isAuthenticated: boolean; organizationId?: string | null };\n infra: { execSql: ExecSql };\n state: { containerId: string | null; online: boolean };\n };\n}\n\nfunction isFreshStartupRemoteHydrationCheck(\n checkedAt: string,\n nowMs: number,\n): boolean {\n const checkedAtMs = Date.parse(checkedAt);\n return (\n Number.isFinite(checkedAtMs) &&\n nowMs - checkedAtMs <= STARTUP_REMOTE_HYDRATION_FRESH_MS\n );\n}\n\nfunction shouldHydrateUnmarkedStartupRoot(\n state: StartupHydrationState,\n): boolean {\n // An empty authenticated cache needs one root probe to discover the remote\n // tree. Existing local-only roots are deliberately left cache-first; explicit\n // refresh and remote events can reconcile them without polling every startup.\n return state.containersById.size === 0;\n}\n\nasync function getStaleStartupRemoteHydrationParentIds(\n state: StartupHydrationState,\n isCurrent?: (() => boolean) | undefined,\n): Promise<Array<string | null> | null> {\n const parentIds = [null, ...state.containersById.keys()];\n const syncLanes = parentIds.map((parentId) =>\n createContainerParentSyncLane(parentId),\n );\n const checkRecords = await new ContainerSyncWatermarkRepository(\n state.runtime.infra.execSql,\n ).loadCheckRecords(syncLanes);\n if (isCurrent?.() === false) {\n return null;\n }\n const nowMs = Date.now();\n const rootCheckRecord = checkRecords[0];\n state.rootLaneHydrated = rootCheckRecord\n ? isFreshStartupRemoteHydrationCheck(rootCheckRecord.checkedAt, nowMs)\n : false;\n const hydrateUnmarkedRoot = shouldHydrateUnmarkedStartupRoot(state);\n\n return parentIds.filter((_, index) => {\n const checkRecord = checkRecords[index];\n if (!checkRecord) {\n return hydrateUnmarkedRoot && index === 0;\n }\n\n return !isFreshStartupRemoteHydrationCheck(checkRecord.checkedAt, nowMs);\n });\n}\n\nfunction reportStartupHydrationError(message: string, error: unknown) {\n if (isDatabaseUnavailableError(error)) {\n return;\n }\n\n console.error(message, error);\n}\n\nexport async function scheduleStaleStartupRemoteHydration(input: {\n isCurrent?: (() => boolean) | undefined;\n requestHydration: () => Promise<void>;\n state: StartupHydrationState;\n}): Promise<boolean> {\n const { requestHydration, state } = input;\n if (!state.runtime.auth.isAuthenticated || !state.runtime.state.online) {\n return false;\n }\n\n let parentIds: Array<string | null> | null;\n try {\n parentIds = await getStaleStartupRemoteHydrationParentIds(\n state,\n input.isCurrent,\n );\n } catch (error: unknown) {\n if (input.isCurrent?.() === false) {\n return false;\n }\n reportStartupHydrationError(\n \"Failed to inspect startup container contents hydration:\",\n error,\n );\n return false;\n }\n if (!parentIds || input.isCurrent?.() === false) {\n return false;\n }\n const activeContainerId = state.runtime.state.containerId;\n const shouldScheduleStaleRootRecovery =\n state.rootLaneHydrated &&\n activeContainerId !== null &&\n !state.containersById.has(activeContainerId);\n if (parentIds.length === 0) {\n return shouldScheduleStaleRootRecovery;\n }\n\n for (const parentId of parentIds) {\n state.containerParentIdsNeedingHydration.add(parentId);\n }\n // Startup stays cache-first: only the local freshness-marker read is awaited.\n // Missing markers on an existing remote cache do not force a first-open poll;\n // stale checked lanes and empty caches hydrate behind the cached tree.\n // WebSocket events and explicit refresh bypass this.\n void requestHydration().catch((error: unknown) => {\n reportStartupHydrationError(\n \"Failed to schedule startup container contents hydration:\",\n error,\n );\n });\n return shouldScheduleStaleRootRecovery;\n}\n\nexport async function hasStartupContainerSyncWork(state: {\n containersById: ReadonlyMap<string, unknown>;\n persistence: ContainerContentsPersistence;\n runtime: { infra: { execSql: ExecSql } };\n}): Promise<boolean> {\n const execSql = state.runtime.infra.execSql;\n const [createIntents, moveIntents] = await Promise.all([\n state.persistence.listPendingCreateIntents(execSql),\n state.persistence.listUnsyncedMoveIntents(execSql),\n ]);\n if (createIntents.length > 0 || moveIntents.length > 0) {\n return true;\n }\n\n // Durable document-level work (pending creates, queued Loro updates or\n // attachments, pending document move intents) is drained by lane passes too:\n // the pass primes the owning document stores, which register and request\n // their own sync lanes. Without this probe, a relaunch whose only pending\n // work is document-level never schedules any lane and the write queue sits\n // unattempted forever.\n if (await hasStartupDocumentSyncWork(execSql)) {\n return true;\n }\n\n const containerIds = Array.from(state.containersById.keys());\n if (containerIds.length === 0) {\n return false;\n }\n const [containersWithPendingMetadata, containersWithPullContinuations] =\n await Promise.all([\n state.persistence.listContainerIdsWithPendingUpdates(\n execSql,\n containerIds,\n ),\n state.persistence.listContainerIdsWithPullContinuations(\n execSql,\n containerIds,\n ),\n ]);\n return (\n containersWithPendingMetadata.length > 0 ||\n containersWithPullContinuations.length > 0\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"startupHydration.js","sourceRoot":"","sources":["startupHydration.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,gCAAgC,EAChC,6BAA6B,GAE9B,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,0BAA0B,EAAE,MA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EAAyE;IACzE,0EAA0E;IAC1E,2EAA2E;IAC3E,uBAAuB;IACvB,IAAI,MAAM,0BAA0B,CAAC,OAAO,CAAC,EAAE,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,YAAY,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC;IAC7D,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,CACJ,6BAA6B,EAC7B,+BAA+B,EAC/B,iBAAiB,EAClB,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACpB,KAAK,CAAC,WAAW,CAAC,kCAAkC,CAAC,OAAO,EAAE,YAAY,CAAC;QAC3E,KAAK,CAAC,WAAW,CAAC,qCAAqC,CACrD,OAAO,EACP,YAAY,CACb;QACD,sEAAsE;QACtE,0DAA0D;QAC1D,KAAK,CAAC,WAAW,CAAC,kCAAkC,CAAC,OAAO,CAAC;KAC9D,CAAC,CAAC;IACH,OAAO,CACL,6BAA6B,CAAC,MAAM,GAAG,CAAC;QACxC,+BAA+B,CAAC,MAAM,GAAG,CAAC;QAC1C,iBAAiB,CAAC,MAAM,GAAG,CAAC,CAC7B,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerContentsPersistence,\n ContainerSyncWatermarkRepository,\n createContainerParentSyncLane,\n type ExecSql,\n} from \"../../../workflows/container-contents/containerPersistence\";\nimport { hasStartupDocumentSyncWork } from \"../../../workflows/container-contents/documentPriming\";\nimport { isDatabaseUnavailableError } from \"../../../workflows/container-contents/syncLane\";\n\nconst STARTUP_REMOTE_HYDRATION_FRESH_MS = 15 * 60_000;\n\ninterface StartupHydrationState {\n containerParentIdsNeedingHydration: Set<string | null>;\n containersById: ReadonlyMap<\n string,\n {\n container: {\n metadataDocumentId?: string | null | undefined;\n parentId: string | null;\n };\n }\n >;\n rootLaneHydrated: boolean;\n runtime: {\n auth: { isAuthenticated: boolean; organizationId?: string | null };\n infra: { execSql: ExecSql };\n state: { containerId: string | null; online: boolean };\n };\n}\n\nfunction isFreshStartupRemoteHydrationCheck(\n checkedAt: string,\n nowMs: number,\n): boolean {\n const checkedAtMs = Date.parse(checkedAt);\n return (\n Number.isFinite(checkedAtMs) &&\n nowMs - checkedAtMs <= STARTUP_REMOTE_HYDRATION_FRESH_MS\n );\n}\n\nfunction shouldHydrateUnmarkedStartupRoot(\n state: StartupHydrationState,\n): boolean {\n // An empty authenticated cache needs one root probe to discover the remote\n // tree. Existing local-only roots are deliberately left cache-first; explicit\n // refresh and remote events can reconcile them without polling every startup.\n return state.containersById.size === 0;\n}\n\nasync function getStaleStartupRemoteHydrationParentIds(\n state: StartupHydrationState,\n isCurrent?: (() => boolean) | undefined,\n): Promise<Array<string | null> | null> {\n const parentIds = [null, ...state.containersById.keys()];\n const syncLanes = parentIds.map((parentId) =>\n createContainerParentSyncLane(parentId),\n );\n const checkRecords = await new ContainerSyncWatermarkRepository(\n state.runtime.infra.execSql,\n ).loadCheckRecords(syncLanes);\n if (isCurrent?.() === false) {\n return null;\n }\n const nowMs = Date.now();\n const rootCheckRecord = checkRecords[0];\n state.rootLaneHydrated = rootCheckRecord\n ? isFreshStartupRemoteHydrationCheck(rootCheckRecord.checkedAt, nowMs)\n : false;\n const hydrateUnmarkedRoot = shouldHydrateUnmarkedStartupRoot(state);\n\n return parentIds.filter((_, index) => {\n const checkRecord = checkRecords[index];\n if (!checkRecord) {\n return hydrateUnmarkedRoot && index === 0;\n }\n\n return !isFreshStartupRemoteHydrationCheck(checkRecord.checkedAt, nowMs);\n });\n}\n\nfunction reportStartupHydrationError(message: string, error: unknown) {\n if (isDatabaseUnavailableError(error)) {\n return;\n }\n\n console.error(message, error);\n}\n\nexport async function scheduleStaleStartupRemoteHydration(input: {\n isCurrent?: (() => boolean) | undefined;\n requestHydration: () => Promise<void>;\n state: StartupHydrationState;\n}): Promise<boolean> {\n const { requestHydration, state } = input;\n if (!state.runtime.auth.isAuthenticated || !state.runtime.state.online) {\n return false;\n }\n\n let parentIds: Array<string | null> | null;\n try {\n parentIds = await getStaleStartupRemoteHydrationParentIds(\n state,\n input.isCurrent,\n );\n } catch (error: unknown) {\n if (input.isCurrent?.() === false) {\n return false;\n }\n reportStartupHydrationError(\n \"Failed to inspect startup container contents hydration:\",\n error,\n );\n return false;\n }\n if (!parentIds || input.isCurrent?.() === false) {\n return false;\n }\n const activeContainerId = state.runtime.state.containerId;\n const shouldScheduleStaleRootRecovery =\n state.rootLaneHydrated &&\n activeContainerId !== null &&\n !state.containersById.has(activeContainerId);\n if (parentIds.length === 0) {\n return shouldScheduleStaleRootRecovery;\n }\n\n for (const parentId of parentIds) {\n state.containerParentIdsNeedingHydration.add(parentId);\n }\n // Startup stays cache-first: only the local freshness-marker read is awaited.\n // Missing markers on an existing remote cache do not force a first-open poll;\n // stale checked lanes and empty caches hydrate behind the cached tree.\n // WebSocket events and explicit refresh bypass this.\n void requestHydration().catch((error: unknown) => {\n reportStartupHydrationError(\n \"Failed to schedule startup container contents hydration:\",\n error,\n );\n });\n return shouldScheduleStaleRootRecovery;\n}\n\nexport async function hasStartupContainerSyncWork(state: {\n containersById: ReadonlyMap<string, unknown>;\n persistence: ContainerContentsPersistence;\n runtime: { infra: { execSql: ExecSql } };\n}): Promise<boolean> {\n const execSql = state.runtime.infra.execSql;\n const [createIntents, moveIntents] = await Promise.all([\n state.persistence.listPendingCreateIntents(execSql),\n state.persistence.listUnsyncedMoveIntents(execSql),\n ]);\n if (createIntents.length > 0 || moveIntents.length > 0) {\n return true;\n }\n\n // Durable document-level work (pending creates, queued Loro updates or\n // attachments, pending document move intents) is drained by lane passes too:\n // the pass primes the owning document stores, which register and request\n // their own sync lanes. Without this probe, a relaunch whose only pending\n // work is document-level never schedules any lane and the write queue sits\n // unattempted forever.\n if (await hasStartupDocumentSyncWork(execSql)) {\n return true;\n }\n\n const containerIds = Array.from(state.containersById.keys());\n if (containerIds.length === 0) {\n return false;\n }\n const [\n containersWithPendingMetadata,\n containersWithPullContinuations,\n owedMetadataReads,\n ] = await Promise.all([\n state.persistence.listContainerIdsWithPendingUpdates(execSql, containerIds),\n state.persistence.listContainerIdsWithPullContinuations(\n execSql,\n containerIds,\n ),\n // A read a listing owed before the restart needs a pass even when the\n // cached tree is fresh and no connection is acknowledged.\n state.persistence.listContainerMetadataRevalidations(execSql),\n ]);\n return (\n containersWithPendingMetadata.length > 0 ||\n containersWithPullContinuations.length > 0 ||\n owedMetadataReads.length > 0\n );\n}\n"]}
|
|
@@ -64,12 +64,15 @@ export function createContainerContentsStoreState(initialRuntime, persistence, l
|
|
|
64
64
|
logLabel,
|
|
65
65
|
metadataDocumentIdsNeedingSync: new Set(),
|
|
66
66
|
metadataSyncSignalSeqById: new Map(),
|
|
67
|
+
owedMetadataReadsRestored: false,
|
|
67
68
|
persistence,
|
|
68
69
|
plannedMetadataDocumentIds: new Set(),
|
|
69
70
|
remoteHydrationPromise: null,
|
|
70
71
|
remoteHydrationGeneration: null,
|
|
71
72
|
remoteHydrationStructuralGeneration: null,
|
|
72
|
-
|
|
73
|
+
// A store opened after the socket's interest was acknowledged missed that
|
|
74
|
+
// acknowledgement's re-list, which is how hints lost earlier are recovered.
|
|
75
|
+
remoteReconnectRefreshPending: (initialRuntime.state.serverEventsConnectionGeneration ?? 0) > 0,
|
|
73
76
|
resolveProjectionUserKey: createContainerContentsProjectionUserKeyResolver(initialRuntime),
|
|
74
77
|
rootLaneHydrated: false,
|
|
75
78
|
runtime: initialRuntime,
|
|
@@ -121,6 +124,7 @@ function resetContainerContentsStore(state) {
|
|
|
121
124
|
state.locallyAcceptedMetadataUpdateIds = new Set();
|
|
122
125
|
state.metadataDocumentIdsNeedingSync = new Set();
|
|
123
126
|
state.metadataSyncSignalSeqById = new Map();
|
|
127
|
+
state.owedMetadataReadsRestored = false;
|
|
124
128
|
state.plannedMetadataDocumentIds = new Set();
|
|
125
129
|
state.rootLaneHydr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ainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport {\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"../../workflows/container-contents/projectionKeys\";\nimport { didRegainSyncPrerequisites } from \"../../workflows/container-contents/syncLane\";\nimport { ContainerStateMap } from \"./containerState/containerStateMap\";\nimport { didContainerWriteRuntimeChange } from \"./remoteWrites/writeGeneration\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n} from \"./syncAgent/syncAgentTypes\";\nimport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreState,\n ContainerNode,\n} from \"./types\";\nimport { getSnapshotNodes } from \"./utils\";\n\nfunction areSyncStatesEqual(\n left: ContainerNode[\"syncState\"],\n right: ContainerNode[\"syncState\"],\n): boolean {\n return (\n left.lastError === right.lastError &&\n left.pendingAttachmentBytes === right.pendingAttachmentBytes &&\n left.pendingAttachmentCount === right.pendingAttachmentCount &&\n left.pendingUpdateCount === right.pendingUpdateCount &&\n left.status === right.status\n );\n}\n\nfunction areSnapshotNodesEqual(\n left: ReadonlyArray<ContainerNode>,\n right: ReadonlyArray<ContainerNode>,\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n return left.every((leftNode, index) => {\n const rightNode = right[index];\n return (\n rightNode !== undefined &&\n leftNode.createdAt === rightNode.createdAt &&\n leftNode.effectiveAccessLevel === rightNode.effectiveAccessLevel &&\n leftNode.id === rightNode.id &&\n leftNode.icon === rightNode.icon &&\n leftNode.kind === rightNode.kind &&\n leftNode.metadataDocumentId === rightNode.metadataDocumentId &&\n leftNode.metadataReady === rightNode.metadataReady &&\n leftNode.name === rightNode.name &&\n leftNode.organizationId === rightNode.organizationId &&\n leftNode.parentId === rightNode.parentId &&\n leftNode.primaryDocumentId === rightNode.primaryDocumentId &&\n areSyncStatesEqual(leftNode.syncState, rightNode.syncState) &&\n leftNode.systemSlot === rightNode.systemSlot &&\n leftNode.updatedAt === rightNode.updatedAt\n );\n });\n}\n\nfunction didStructuralRuntimeChange(\n previousRuntime: ContainerContentsStoreRuntime,\n nextRuntime: ContainerContentsStoreRuntime,\n): boolean {\n // Structural sync also depends on connectivity and event delivery. Local\n // writes use only the identity and storage checks shared below.\n return (\n didContainerWriteRuntimeChange(previousRuntime, nextRuntime) ||\n previousRuntime.state.online !== nextRuntime.state.online ||\n previousRuntime.state.peerScope !== nextRuntime.state.peerScope ||\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration ||\n previousRuntime.util.isRemoteSyncBlocked !==\n nextRuntime.util.isRemoteSyncBlocked\n );\n}\n\nexport function createContainerContentsStoreState(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence,\n logLabel?: string | undefined,\n): ContainerContentsStoreState {\n return {\n containerListingFailures: 0,\n containersById: new ContainerStateMap(),\n containerParentIdsNeedingHydration: new Set(),\n documentStoresNeedPriming: true,\n initializeGeneration: null,\n initializePromise: null,\n initialized: false,\n localContainerRefreshPromise: null,\n localContainerRefreshGeneration: null,\n localContainerRefreshStructuralGeneration: null,\n localContainersNeedRefresh: false,\n lifecycleGeneration: 0,\n lastEventCount: 0,\n listeners: new Set(),\n locallyAcceptedMetadataUpdateIds: new Set(),\n logLabel,\n metadataDocumentIdsNeedingSync: new Set(),\n metadataSyncSignalSeqById: new Map(),\n persistence,\n plannedMetadataDocumentIds: new Set(),\n remoteHydrationPromise: null,\n remoteHydrationGeneration: null,\n remoteHydrationStructuralGeneration: null,\n remoteReconnectRefreshPending: false,\n resolveProjectionUserKey:\n createContainerContentsProjectionUserKeyResolver(initialRuntime),\n rootLaneHydrated: false,\n runtime: initialRuntime,\n snapshot: {\n nodes: [],\n ready: false,\n },\n syncLane: null,\n structuralGeneration: 0,\n writeGeneration: 0,\n writeChain: Promise.resolve<ContainerNode | null>(null),\n };\n}\n\nfunction emitContainerContentsStore(state: ContainerContentsStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nfunction setContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n next: ContainerContentsSnapshot,\n) {\n if (\n next.ready === state.snapshot.ready &&\n areSnapshotNodesEqual(next.nodes, state.snapshot.nodes)\n ) {\n return;\n }\n\n state.snapshot = next;\n emitContainerContentsStore(state);\n}\n\nexport function updateContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n) {\n setContainerContentsSnapshot(state, {\n nodes: getSnapshotNodes(state.containersById),\n ready: true,\n });\n}\n\nfunction resetContainerContentsStore(state: ContainerContentsStoreState) {\n state.lifecycleGeneration += 1;\n state.containersById = new ContainerStateMap();\n state.containerParentIdsNeedingHydration = new Set();\n state.documentStoresNeedPriming = true;\n state.initialized = false;\n state.localContainersNeedRefresh = false;\n // Runtime events are snapshots, not a destructive queue. A replacement\n // executor or persistence adapter has not observed any of them, even when\n // their effects were already applied to the previous database. Replay the\n // snapshot after replacement initialization rebuilds metadata identities.\n state.lastEventCount = 0;\n // Accepted-echo suppression state must not survive a reset: after a\n // database loss the tree rehydrates from remote, and a retained id would\n // suppress the next matching remote update signal. Mirrors\n // clearDocumentStoreState in the document store lane.\n state.locallyAcceptedMetadataUpdateIds = new Set();\n state.metadataDocumentIdsNeedingSync = new Set();\n state.metadataSyncSignalSeqById = new Map();\n state.plannedMetadataDocumentIds = new Set();\n state.rootLaneHydrated = false;\n state.writeChain = Promise.resolve<ContainerNode | null>(null);\n setContainerContentsSnapshot(state, {\n nodes: [],\n ready: false,\n });\n}\n\nexport function subscribeToContainerContentsStore(\n state: ContainerContentsStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n\nfunction hasContainerContentsLoadState(\n state: ContainerContentsStoreState,\n): boolean {\n return Boolean(\n state.snapshot.ready || state.initialized || state.initializePromise,\n );\n}\n\nexport function updateContainerContentsStoreRuntime(\n state: ContainerContentsStoreState,\n nextRuntime: ContainerContentsStoreRuntime,\n syncAgent: ContainerContentsStoreSyncAgent,\n) {\n const previousRuntime = state.runtime;\n const runtimeReplaced = didStructuralRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (didContainerWriteRuntimeChange(previousRuntime, nextRuntime)) {\n state.writeGeneration += 1;\n }\n const executorReplaced =\n previousRuntime.infra.execSql !== nextRuntime.infra.execSql;\n const serverEventsConnectionChanged =\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration;\n if (runtimeReplaced) {\n state.structuralGeneration += 1;\n state.localContainersNeedRefresh = true;\n }\n const contextChanged =\n previousRuntime.auth.organizationId !== nextRuntime.auth.organizationId ||\n previousRuntime.state.containerId !== nextRuntime.state.containerId;\n if (\n didContainerContentsProjectionKeyRuntimeChange(previousRuntime, nextRuntime)\n ) {\n state.resolveProjectionUserKey =\n createContainerContentsProjectionUserKeyResolver(nextRuntime);\n }\n state.runtime = nextRuntime;\n if (serverEventsConnectionChanged) {\n state.remoteReconnectRefreshPending = true;\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (hasContainerContentsLoadState(state)) {\n resetContainerContentsStore(state);\n }\n return;\n }\n\n if (executorReplaced) {\n // The in-memory tree and lane markers belong to the previous executor.\n // Rebuild them from the replacement database before any remote sync can\n // observe or persist the old database's state.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n syncAgent.handleRemoteEvents();\n return;\n }\n\n // Gaining authentication within a domain scope does not change identity\n // (the scope is keyed on the signing fingerprint), so the locally-loaded\n // tree stays valid. Reconcile it in place instead of resetting — resetting\n // here is what blanked Explorer and forced a re-read on first open after\n // register. Identity/storage changes are handled by scope rotation and the\n // dbStatus-loss branch above.\n if (\n state.snapshot.ready &&\n (contextChanged || didRegainSyncPrerequisites(previousRuntime, nextRuntime))\n ) {\n state.localContainersNeedRefresh = true;\n state.documentStoresNeedPriming = true;\n void syncAgent.refreshLocalContainers();\n // The refresh alone does not run the sync lane; schedule it so newly\n // eligible documents (e.g. this organization's orphans) prime now.\n syncAgent.scheduleSync();\n }\n\n syncAgent.ensureInitialized();\n\n syncAgent.handleRemoteEvents();\n\n if (runtimeReplaced) {\n void syncAgent.refreshLocalContainers();\n syncAgent.scheduleSync();\n }\n\n consumePendingContainerContentsReconnectRefresh(state, syncAgent.refresh);\n\n if (\n state.snapshot.ready &&\n didRegainSyncPrerequisites(previousRuntime, nextRuntime)\n ) {\n // A pass blocked by missing prerequisites consumes its lane request before\n // returning early. Re-arm it directly when they return even if hydration\n // finds no remote delta; this also primes unopened document stores.\n syncAgent.scheduleSync();\n syncAgent.scheduleRemoteHydration();\n }\n}\n\nexport function consumePendingContainerContentsReconnectRefresh(\n state: {\n remoteReconnectRefreshPending: boolean;\n snapshot: { ready: boolean };\n },\n refresh: () => Promise<boolean>,\n): void {\n if (!state.snapshot.ready || !state.remoteReconnectRefreshPending) return;\n state.remoteReconnectRefreshPending = false;\n void refresh().then(\n (refreshed) => {\n if (!refreshed) state.remoteReconnectRefreshPending = true;\n },\n () => {\n state.remoteReconnectRefreshPending = true;\n },\n );\n}\n\nexport function updateContainerContentsStorePersistence(\n state: ContainerContentsStoreState,\n nextPersistence: ContainerContentsPersistence,\n syncAgent: ContainerContentsStoreSyncAgent,\n): void {\n if (state.persistence === nextPersistence) {\n return;\n }\n state.persistence = nextPersistence;\n state.structuralGeneration += 1;\n state.writeGeneration += 1;\n // Persistence replacement changes the authoritative local data source even\n // when the SQLite executor itself is stable. Clear storage-backed state and\n // let initialization load the replacement before scheduling remote work.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,6CAA6C,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAA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0B,CAAC,eAAe,EAAE,WAAW,CAAC,EACxD,CAAC;QACD,2EAA2E;QAC3E,yEAAyE;QACzE,oEAAoE;QACpE,SAAS,CAAC,YAAY,EAAE,CAAC;QACzB,SAAS,CAAC,uBAAuB,EAAE,CAAC;IACtC,CAAC;AACH,CAAC;AAED,MAAM,UAAU,+CAA+C,CAC7D,KAGC,EACD,OAA+B;IAE/B,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,6BAA6B;QAAE,OAAO;IAC1E,KAAK,CAAC,6BAA6B,GAAG,KAAK,CAAC;IAC5C,KAAK,OAAO,EAAE,CAAC,IAAI,CACjB,CAAC,SAAS,EAAE,EAAE;QACZ,IAAI,CAAC,SAAS;YAAE,KAAK,CAAC,6BAA6B,GAAG,IAAI,CAAC;IAC7D,CAAC,EACD,GAAG,EAAE;QACH,KAAK,CAAC,6BAA6B,GAAG,IAAI,CAAC;IAC7C,CAAC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,uCAAuC,CACrD,KAAkC,EAClC,eAA6C,EAC7C,SAA0C;IAE1C,IAAI,KAAK,CAAC,WAAW,KAAK,eAAe,EAAE,CAAC;QAC1C,OAAO;IACT,CAAC;IACD,KAAK,CAAC,WAAW,GAAG,eAAe,CAAC;IACpC,KAAK,CAAC,oBAAoB,IAAI,CAAC,CAAC;IAChC,KAAK,CAAC,eAAe,IAAI,CAAC,CAAC;IAC3B,2EAA2E;IAC3E,4EAA4E;IAC5E,yEAAyE;IACzE,2BAA2B,CAAC,KAAK,CAAC,CAAC;IACnC,SAAS,CAAC,iBAAiB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import type { ContainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport {\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"../../workflows/container-contents/projectionKeys\";\nimport { didRegainSyncPrerequisites } from \"../../workflows/container-contents/syncLane\";\nimport { ContainerStateMap } from \"./containerState/containerStateMap\";\nimport { didContainerWriteRuntimeChange } from \"./remoteWrites/writeGeneration\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n} from \"./syncAgent/syncAgentTypes\";\nimport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreState,\n ContainerNode,\n} from \"./types\";\nimport { getSnapshotNodes } from \"./utils\";\n\nfunction areSyncStatesEqual(\n left: ContainerNode[\"syncState\"],\n right: ContainerNode[\"syncState\"],\n): boolean {\n return (\n left.lastError === right.lastError &&\n left.pendingAttachmentBytes === right.pendingAttachmentBytes &&\n left.pendingAttachmentCount === right.pendingAttachmentCount &&\n left.pendingUpdateCount === right.pendingUpdateCount &&\n left.status === right.status\n );\n}\n\nfunction areSnapshotNodesEqual(\n left: ReadonlyArray<ContainerNode>,\n right: ReadonlyArray<ContainerNode>,\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n return left.every((leftNode, index) => {\n const rightNode = right[index];\n return (\n rightNode !== undefined &&\n leftNode.createdAt === rightNode.createdAt &&\n leftNode.effectiveAccessLevel === rightNode.effectiveAccessLevel &&\n leftNode.id === rightNode.id &&\n leftNode.icon === rightNode.icon &&\n leftNode.kind === rightNode.kind &&\n leftNode.metadataDocumentId === rightNode.metadataDocumentId &&\n leftNode.metadataReady === rightNode.metadataReady &&\n leftNode.name === rightNode.name &&\n leftNode.organizationId === rightNode.organizationId &&\n leftNode.parentId === rightNode.parentId &&\n leftNode.primaryDocumentId === rightNode.primaryDocumentId &&\n areSyncStatesEqual(leftNode.syncState, rightNode.syncState) &&\n leftNode.systemSlot === rightNode.systemSlot &&\n leftNode.updatedAt === rightNode.updatedAt\n );\n });\n}\n\nfunction didStructuralRuntimeChange(\n previousRuntime: ContainerContentsStoreRuntime,\n nextRuntime: ContainerContentsStoreRuntime,\n): boolean {\n // Structural sync also depends on connectivity and event delivery. Local\n // writes use only the identity and storage checks shared below.\n return (\n didContainerWriteRuntimeChange(previousRuntime, nextRuntime) ||\n previousRuntime.state.online !== nextRuntime.state.online ||\n previousRuntime.state.peerScope !== nextRuntime.state.peerScope ||\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration ||\n previousRuntime.util.isRemoteSyncBlocked !==\n nextRuntime.util.isRemoteSyncBlocked\n );\n}\n\nexport function createContainerContentsStoreState(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence,\n logLabel?: string | undefined,\n): ContainerContentsStoreState {\n return {\n containerListingFailures: 0,\n containersById: new ContainerStateMap(),\n containerParentIdsNeedingHydration: new Set(),\n documentStoresNeedPriming: true,\n initializeGeneration: null,\n initializePromise: null,\n initialized: false,\n localContainerRefreshPromise: null,\n localContainerRefreshGeneration: null,\n localContainerRefreshStructuralGeneration: null,\n localContainersNeedRefresh: false,\n lifecycleGeneration: 0,\n lastEventCount: 0,\n listeners: new Set(),\n locallyAcceptedMetadataUpdateIds: new Set(),\n logLabel,\n metadataDocumentIdsNeedingSync: new Set(),\n metadataSyncSignalSeqById: new Map(),\n owedMetadataReadsRestored: false,\n persistence,\n plannedMetadataDocumentIds: new Set(),\n remoteHydrationPromise: null,\n remoteHydrationGeneration: null,\n remoteHydrationStructuralGeneration: null,\n // A store opened after the socket's interest was acknowledged missed that\n // acknowledgement's re-list, which is how hints lost earlier are recovered.\n remoteReconnectRefreshPending:\n (initialRuntime.state.serverEventsConnectionGeneration ?? 0) > 0,\n resolveProjectionUserKey:\n createContainerContentsProjectionUserKeyResolver(initialRuntime),\n rootLaneHydrated: false,\n runtime: initialRuntime,\n snapshot: {\n nodes: [],\n ready: false,\n },\n syncLane: null,\n structuralGeneration: 0,\n writeGeneration: 0,\n writeChain: Promise.resolve<ContainerNode | null>(null),\n };\n}\n\nfunction emitContainerContentsStore(state: ContainerContentsStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nfunction setContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n next: ContainerContentsSnapshot,\n) {\n if (\n next.ready === state.snapshot.ready &&\n areSnapshotNodesEqual(next.nodes, state.snapshot.nodes)\n ) {\n return;\n }\n\n state.snapshot = next;\n emitContainerContentsStore(state);\n}\n\nexport function updateContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n) {\n setContainerContentsSnapshot(state, {\n nodes: getSnapshotNodes(state.containersById),\n ready: true,\n });\n}\n\nfunction resetContainerContentsStore(state: ContainerContentsStoreState) {\n state.lifecycleGeneration += 1;\n state.containersById = new ContainerStateMap();\n state.containerParentIdsNeedingHydration = new Set();\n state.documentStoresNeedPriming = true;\n state.initialized = false;\n state.localContainersNeedRefresh = false;\n // Runtime events are snapshots, not a destructive queue. A replacement\n // executor or persistence adapter has not observed any of them, even when\n // their effects were already applied to the previous database. Replay the\n // snapshot after replacement initialization rebuilds metadata identities.\n state.lastEventCount = 0;\n // Accepted-echo suppression state must not survive a reset: after a\n // database loss the tree rehydrates from remote, and a retained id would\n // suppress the next matching remote update signal. Mirrors\n // clearDocumentStoreState in the document store lane.\n state.locallyAcceptedMetadataUpdateIds = new Set();\n state.metadataDocumentIdsNeedingSync = new Set();\n state.metadataSyncSignalSeqById = new Map();\n state.owedMetadataReadsRestored = false;\n state.plannedMetadataDocumentIds = new Set();\n state.rootLaneHydrated = false;\n state.writeChain = Promise.resolve<ContainerNode | null>(null);\n setContainerContentsSnapshot(state, {\n nodes: [],\n ready: false,\n });\n}\n\nexport function subscribeToContainerContentsStore(\n state: ContainerContentsStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n\nfunction hasContainerContentsLoadState(\n state: ContainerContentsStoreState,\n): boolean {\n return Boolean(\n state.snapshot.ready || state.initialized || state.initializePromise,\n );\n}\n\nexport function updateContainerContentsStoreRuntime(\n state: ContainerContentsStoreState,\n nextRuntime: ContainerContentsStoreRuntime,\n syncAgent: ContainerContentsStoreSyncAgent,\n) {\n const previousRuntime = state.runtime;\n const runtimeReplaced = didStructuralRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (didContainerWriteRuntimeChange(previousRuntime, nextRuntime)) {\n state.writeGeneration += 1;\n }\n const executorReplaced =\n previousRuntime.infra.execSql !== nextRuntime.infra.execSql;\n const serverEventsConnectionChanged =\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration;\n if (runtimeReplaced) {\n state.structuralGeneration += 1;\n state.localContainersNeedRefresh = true;\n }\n const contextChanged =\n previousRuntime.auth.organizationId !== nextRuntime.auth.organizationId ||\n previousRuntime.state.containerId !== nextRuntime.state.containerId;\n if (\n didContainerContentsProjectionKeyRuntimeChange(previousRuntime, nextRuntime)\n ) {\n state.resolveProjectionUserKey =\n createContainerContentsProjectionUserKeyResolver(nextRuntime);\n }\n state.runtime = nextRuntime;\n if (serverEventsConnectionChanged) {\n state.remoteReconnectRefreshPending = true;\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (hasContainerContentsLoadState(state)) {\n resetContainerContentsStore(state);\n }\n return;\n }\n\n if (executorReplaced) {\n // The in-memory tree and lane markers belong to the previous executor.\n // Rebuild them from the replacement database before any remote sync can\n // observe or persist the old database's state.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n syncAgent.handleRemoteEvents();\n return;\n }\n\n // Gaining authentication within a domain scope does not change identity\n // (the scope is keyed on the signing fingerprint), so the locally-loaded\n // tree stays valid. Reconcile it in place instead of resetting — resetting\n // here is what blanked Explorer and forced a re-read on first open after\n // register. Identity/storage changes are handled by scope rotation and the\n // dbStatus-loss branch above.\n if (\n state.snapshot.ready &&\n (contextChanged || didRegainSyncPrerequisites(previousRuntime, nextRuntime))\n ) {\n state.localContainersNeedRefresh = true;\n state.documentStoresNeedPriming = true;\n void syncAgent.refreshLocalContainers();\n // The refresh alone does not run the sync lane; schedule it so newly\n // eligible documents (e.g. this organization's orphans) prime now.\n syncAgent.scheduleSync();\n }\n\n syncAgent.ensureInitialized();\n\n syncAgent.handleRemoteEvents();\n\n if (runtimeReplaced) {\n void syncAgent.refreshLocalContainers();\n syncAgent.scheduleSync();\n }\n\n consumePendingContainerContentsReconnectRefresh(state, syncAgent.refresh);\n\n if (\n state.snapshot.ready &&\n didRegainSyncPrerequisites(previousRuntime, nextRuntime)\n ) {\n // A pass blocked by missing prerequisites consumes its lane request before\n // returning early. Re-arm it directly when they return even if hydration\n // finds no remote delta; this also primes unopened document stores.\n syncAgent.scheduleSync();\n syncAgent.scheduleRemoteHydration();\n }\n}\n\nexport function consumePendingContainerContentsReconnectRefresh(\n state: {\n remoteReconnectRefreshPending: boolean;\n snapshot: { ready: boolean };\n },\n refresh: () => Promise<boolean>,\n): void {\n if (!state.snapshot.ready || !state.remoteReconnectRefreshPending) return;\n state.remoteReconnectRefreshPending = false;\n void refresh().then(\n (refreshed) => {\n if (!refreshed) state.remoteReconnectRefreshPending = true;\n },\n () => {\n state.remoteReconnectRefreshPending = true;\n },\n );\n}\n\nexport function updateContainerContentsStorePersistence(\n state: ContainerContentsStoreState,\n nextPersistence: ContainerContentsPersistence,\n syncAgent: ContainerContentsStoreSyncAgent,\n): void {\n if (state.persistence === nextPersistence) {\n return;\n }\n state.persistence = nextPersistence;\n state.structuralGeneration += 1;\n state.writeGeneration += 1;\n // Persistence replacement changes the authoritative local data source even\n // when the SQLite executor itself is stable. Clear storage-backed state and\n // let initialization load the replacement before scheduling remote work.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n}\n"]}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable reads owed to container metadata documents.
|
|
3
|
+
*
|
|
4
|
+
* A clean metadata document skips its read until a hint names it, and hints
|
|
5
|
+
* are lost while this client is offline or not yet subscribed. Hydration owes a
|
|
6
|
+
* read when a listing shows the container changed since this client recorded
|
|
7
|
+
* it. The owed read joins the in-memory needs-sync queue first, so a pass
|
|
8
|
+
* already reading the document sees the sequence move and keeps it, and is
|
|
9
|
+
* then written down, before hydration advances the timestamps and the lane
|
|
10
|
+
* watermark that revealed it. A store's first sync pass reloads what is still
|
|
11
|
+
* owed. Each request carries a revision; a read settles only the revision it
|
|
12
|
+
* saw before its request, so a newer request from another tab survives.
|
|
13
|
+
*/
|
|
14
|
+
import { decodeVersionVector, encodeVersionVector, satisfiesVersionVector, } from "../../../internal/loro/index.js";
|
|
15
|
+
import { bumpMetadataSyncSeq } from "./metadataSyncSignal.js";
|
|
16
|
+
function queueMetadataRead(state, documentId) {
|
|
17
|
+
state.metadataDocumentIdsNeedingSync.add(documentId);
|
|
18
|
+
bumpMetadataSyncSeq(state.metadataSyncSignalSeqById, documentId);
|
|
19
|
+
}
|
|
20
|
+
/** Owe a metadata document one read, in memory and then durably. */
|
|
21
|
+
export async function oweContainerMetadataRead(state, request) {
|
|
22
|
+
queueMetadataRead(state, request.documentId);
|
|
23
|
+
await state.persistence.requestContainerMetadataRevalidation(state.runtime.infra.execSql, request);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Whether the local copy covers the version a listing advertised. A read
|
|
27
|
+
* served by a replica that lags the listing can succeed without the edit; its
|
|
28
|
+
* debt then stays for a later pass. An unreadable version is covered: the read
|
|
29
|
+
* it caused already pulled the truth.
|
|
30
|
+
*/
|
|
31
|
+
export function coversAdvertisedMetadataVersion(doc, owed) {
|
|
32
|
+
try {
|
|
33
|
+
const advertised = owed.advertisedVersionVector;
|
|
34
|
+
if (decodeVersionVector(advertised).toJSON().size === 0)
|
|
35
|
+
return true;
|
|
36
|
+
return satisfiesVersionVector(encodeVersionVector(doc), advertised);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Requeue reads a previous run still owed for the containers now held, and
|
|
44
|
+
* return how many. A debt for a container this store does not hold is left
|
|
45
|
+
* alone: another tab sharing the database may hold it. Work stops once
|
|
46
|
+
* `isCurrent` reports a replaced store or database.
|
|
47
|
+
*/
|
|
48
|
+
export async function restoreOwedContainerMetadataReads(state, isCurrent) {
|
|
49
|
+
const { execSql } = state.runtime.infra;
|
|
50
|
+
const heldDocumentIds = new Set([...state.containersById.values()].map(({ record }) => record.documentId));
|
|
51
|
+
const owed = await state.persistence.listContainerMetadataRevalidations(execSql);
|
|
52
|
+
if (!isCurrent())
|
|
53
|
+
return 0;
|
|
54
|
+
let restored = 0;
|
|
55
|
+
for (const { documentId } of owed) {
|
|
56
|
+
if (heldDocumentIds.has(documentId)) {
|
|
57
|
+
queueMetadataRead(state, documentId);
|
|
58
|
+
restored += 1;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return restored;
|
|
62
|
+
}
|
|
63
|
+
/** The durable request a read is about to answer, read before its request. */
|
|
64
|
+
export async function findOwedContainerMetadataRead(state, input) {
|
|
65
|
+
const owed = await state.persistence.listContainerMetadataRevalidations(input.execSql);
|
|
66
|
+
return owed.find(({ documentId }) => documentId === input.documentId) ?? null;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Forget the request a completed read answered, once that read also cleared
|
|
70
|
+
* the queued one. The read's own database is passed in, so a pass that
|
|
71
|
+
* outlived a database swap never settles a debt the replacement owes.
|
|
72
|
+
*/
|
|
73
|
+
export async function settleOwedContainerMetadataRead(state, input) {
|
|
74
|
+
if (state.metadataDocumentIdsNeedingSync.has(input.revalidation.documentId)) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
await state.persistence.settleContainerMetadataRevalidation(input.execSql, input.revalidation);
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=metadataRevalidation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metadataRevalidation.js","sourceRoot":"","sources":["metadataRevalidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AAKzB,OAAO,EAAE,mBAAmB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MAAM,IAAI,GACR,MAAM,KAAK,CAAC,WAAW,CAAC,kCAAkC,CAAC,OAAO,CAAC,CAAC;IACtE,IAAI,CAAC,SAAS,EAAE;QAAE,OAAO,CAAC,CAAC;IAC3B,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,KAAK,MAAM,EAAE,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC;QAClC,IAAI,eAAe,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YACpC,iBAAiB,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;YACrC,QAAQ,IAAI,CAAC,CAAC;QAChB,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,KAAgC,EAChC,KAAiE;IAEjE,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,WAAW,CAAC,kCAAkC,CACrE,KAAK,CAAC,OAAO,CACd,CAAC;IACF,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC;AAChF,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,KAAgC,EAChC,KAGC;IAED,IAAI,KAAK,CAAC,8BAA8B,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5E,OAAO;IACT,CAAC;IACD,MAAM,KAAK,CAAC,WAAW,CAAC,mCAAmC,CACzD,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,YAAY,CACnB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Durable reads owed to container metadata documents.\n *\n * A clean metadata document skips its read until a hint names it, and hints\n * are lost while this client is offline or not yet subscribed. Hydration owes a\n * read when a listing shows the container changed since this client recorded\n * it. The owed read joins the in-memory needs-sync queue first, so a pass\n * already reading the document sees the sequence move and keeps it, and is\n * then written down, before hydration advances the timestamps and the lane\n * watermark that revealed it. A store's first sync pass reloads what is still\n * owed. Each request carries a revision; a read settles only the revision it\n * saw before its request, so a newer request from another tab survives.\n */\n\nimport {\n decodeVersionVector,\n encodeVersionVector,\n satisfiesVersionVector,\n} from \"@tearleads/loro\";\nimport type {\n ContainerMetadataRevalidation,\n ExecSql,\n} from \"../../../workflows/container-contents/containerPersistence\";\nimport { bumpMetadataSyncSeq } from \"./metadataSyncSignal\";\nimport type { ContainerContentsStoreSyncState } from \"./syncAgentTypes\";\n\ntype MetadataRevalidationState = Pick<\n ContainerContentsStoreSyncState,\n | \"containersById\"\n | \"metadataDocumentIdsNeedingSync\"\n | \"metadataSyncSignalSeqById\"\n | \"persistence\"\n | \"runtime\"\n>;\n\nfunction queueMetadataRead(\n state: MetadataRevalidationState,\n documentId: string,\n): void {\n state.metadataDocumentIdsNeedingSync.add(documentId);\n bumpMetadataSyncSeq(state.metadataSyncSignalSeqById, documentId);\n}\n\n/** Owe a metadata document one read, in memory and then durably. */\nexport async function oweContainerMetadataRead(\n state: MetadataRevalidationState,\n request: {\n readonly advertisedVersionVector: string;\n readonly documentId: string;\n },\n): Promise<void> {\n queueMetadataRead(state, request.documentId);\n await state.persistence.requestContainerMetadataRevalidation(\n state.runtime.infra.execSql,\n request,\n );\n}\n\n/**\n * Whether the local copy covers the version a listing advertised. A read\n * served by a replica that lags the listing can succeed without the edit; its\n * debt then stays for a later pass. An unreadable version is covered: the read\n * it caused already pulled the truth.\n */\nexport function coversAdvertisedMetadataVersion(\n doc: Parameters<typeof encodeVersionVector>[0],\n owed: ContainerMetadataRevalidation,\n): boolean {\n try {\n const advertised = owed.advertisedVersionVector;\n if (decodeVersionVector(advertised).toJSON().size === 0) return true;\n return satisfiesVersionVector(encodeVersionVector(doc), advertised);\n } catch {\n return true;\n }\n}\n\n/**\n * Requeue reads a previous run still owed for the containers now held, and\n * return how many. A debt for a container this store does not hold is left\n * alone: another tab sharing the database may hold it. Work stops once\n * `isCurrent` reports a replaced store or database.\n */\nexport async function restoreOwedContainerMetadataReads(\n state: MetadataRevalidationState,\n isCurrent: () => boolean,\n): Promise<number> {\n const { execSql } = state.runtime.infra;\n const heldDocumentIds = new Set(\n [...state.containersById.values()].map(({ record }) => record.documentId),\n );\n const owed =\n await state.persistence.listContainerMetadataRevalidations(execSql);\n if (!isCurrent()) return 0;\n let restored = 0;\n for (const { documentId } of owed) {\n if (heldDocumentIds.has(documentId)) {\n queueMetadataRead(state, documentId);\n restored += 1;\n }\n }\n return restored;\n}\n\n/** The durable request a read is about to answer, read before its request. */\nexport async function findOwedContainerMetadataRead(\n state: MetadataRevalidationState,\n input: { readonly documentId: string; readonly execSql: ExecSql },\n): Promise<ContainerMetadataRevalidation | null> {\n const owed = await state.persistence.listContainerMetadataRevalidations(\n input.execSql,\n );\n return owed.find(({ documentId }) => documentId === input.documentId) ?? null;\n}\n\n/**\n * Forget the request a completed read answered, once that read also cleared\n * the queued one. The read's own database is passed in, so a pass that\n * outlived a database swap never settles a debt the replacement owes.\n */\nexport async function settleOwedContainerMetadataRead(\n state: MetadataRevalidationState,\n input: {\n readonly execSql: ExecSql;\n readonly revalidation: ContainerMetadataRevalidation;\n },\n): Promise<void> {\n if (state.metadataDocumentIdsNeedingSync.has(input.revalidation.documentId)) {\n return;\n }\n await state.persistence.settleContainerMetadataRevalidation(\n input.execSql,\n input.revalidation,\n );\n}\n"]}
|
|
@@ -66,6 +66,12 @@ export interface ContainerContentsStoreSyncState {
|
|
|
66
66
|
* `clearMetadataSyncQueueIfUnchanged`.
|
|
67
67
|
*/
|
|
68
68
|
metadataSyncSignalSeqById: Map<string, number>;
|
|
69
|
+
/**
|
|
70
|
+
* Whether this store's first sync pass has requeued the metadata reads a
|
|
71
|
+
* previous run still owed (`container_metadata_revalidations`). Reset with
|
|
72
|
+
* the store, so a replacement database is restored on its own first pass.
|
|
73
|
+
*/
|
|
74
|
+
owedMetadataReadsRestored: boolean;
|
|
69
75
|
/**
|
|
70
76
|
* Metadata document ids of folder creates in flight. A remote hint for one
|
|
71
77
|
* queues the folder's first read before the create response installs the id.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAgentTypes.js","sourceRoot":"","sources":["syncAgentTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerContentsPersistence } from \"../../../workflows/container-contents/containerPersistence\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../../../workflows/container-contents/projectionKeys\";\nimport type {\n ContainerState,\n RemoteContainer,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport type { ContainerContentsStoreWorkflowRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { ContainerContentsSyncLane } from \"../../../workflows/container-contents/syncLane\";\n\nexport type ContainerContentsStoreRuntime =\n ContainerContentsStoreWorkflowRuntime;\n\nexport interface RefreshRootLaneOptions {\n readonly includeActiveRootChildLane?: boolean | undefined;\n // Extra parent lanes to re-list alongside the root lane. Used by the\n // resync_required handler to re-list affected containers' parent lanes so a\n // tombstone only visible there is still applied without the full crawl.\n readonly parentIds?: ReadonlyArray<string | null> | undefined;\n}\n\nexport interface ContainerContentsStoreSyncAgent {\n ensureInitialized: () => void;\n handleRemoteEvents: () => void;\n ingestRemoteContainer: (remoteContainer: RemoteContainer) => Promise<void>;\n primeDocumentsForSharedSubtree: (\n rootContainerId: string,\n isCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n refreshLocalContainers: () => Promise<void>;\n refresh: (options?: { resetAllLaneWatermarks?: boolean }) => Promise<boolean>;\n refreshRootLane: (options?: RefreshRootLaneOptions) => Promise<boolean>;\n requestRemoteHydration: (options?: {\n followDiscoveredParentLanes?: boolean | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n }) => Promise<void>;\n scheduleRemoteHydration: () => void;\n scheduleSync: () => void;\n}\n\nexport interface ContainerContentsStoreSyncState {\n /** Container listing requests that failed or timed out in a current crawl. */\n containerListingFailures: number;\n containersById: Map<string, ContainerState>;\n documentStoresNeedPriming: boolean;\n initializeGeneration: number | null;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n localContainerRefreshPromise: Promise<void> | null;\n localContainerRefreshGeneration: number | null;\n localContainerRefreshStructuralGeneration: number | null;\n localContainersNeedRefresh: boolean;\n /** Invalidates asynchronous hydration work when this store is reset. */\n lifecycleGeneration: number;\n /** Invalidates structural work when its runtime or persistence is replaced. */\n structuralGeneration: number;\n /** Invalidates writes across write-relevant runtime ABA transitions. */\n writeGeneration: number;\n lastEventCount: number;\n /**\n * Update ids this client sent for container metadata documents, registered\n * before the network await of each metadata sync pass. The author's own\n * `document_update_created` echo consumes its ids here instead of arming a\n * redundant forced read-sync; a genuine peer update always carries unknown\n * ids and still forces one. Shared across all metadata docs in the store —\n * update ids are globally unique.\n */\n locallyAcceptedMetadataUpdateIds: Set<string>;\n logLabel?: string | undefined;\n metadataDocumentIdsNeedingSync: Set<string>;\n /**\n * Per-metadata-document enqueue sequence. Bumped for a specific id whenever a\n * remote event re-queues it in {@link metadataDocumentIdsNeedingSync}. A sync\n * pass snapshots the id's sequence before its GET and only clears the id if it\n * is unchanged at pass end, so a mid-pass re-queue of THIS container is not\n * erased. Keyed per id (not a single global counter) so a remote event for an\n * unrelated container does not force a redundant re-sync of this one. See\n * `clearMetadataSyncQueueIfUnchanged`.\n */\n metadataSyncSignalSeqById: Map<string, number>;\n /**\n * Metadata document ids of folder creates in flight. A remote hint for one\n * queues the folder's first read before the create response installs the id.\n */\n plannedMetadataDocumentIds: Set<string>;\n containerParentIdsNeedingHydration: Set<string | null>;\n persistence: ContainerContentsPersistence;\n remoteHydrationPromise: Promise<void> | null;\n remoteHydrationGeneration: number | null;\n remoteHydrationStructuralGeneration: number | null;\n remoteReconnectRefreshPending: boolean;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n /** True after this store has fully applied an authoritative root lane. */\n rootLaneHydrated: boolean;\n runtime: ContainerContentsStoreRuntime;\n snapshot: { ready: boolean };\n syncLane: ContainerContentsSyncLane | null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncAgentTypes.js","sourceRoot":"","sources":["syncAgentTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerContentsPersistence } from \"../../../workflows/container-contents/containerPersistence\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../../../workflows/container-contents/projectionKeys\";\nimport type {\n ContainerState,\n RemoteContainer,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport type { ContainerContentsStoreWorkflowRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { ContainerContentsSyncLane } from \"../../../workflows/container-contents/syncLane\";\n\nexport type ContainerContentsStoreRuntime =\n ContainerContentsStoreWorkflowRuntime;\n\nexport interface RefreshRootLaneOptions {\n readonly includeActiveRootChildLane?: boolean | undefined;\n // Extra parent lanes to re-list alongside the root lane. Used by the\n // resync_required handler to re-list affected containers' parent lanes so a\n // tombstone only visible there is still applied without the full crawl.\n readonly parentIds?: ReadonlyArray<string | null> | undefined;\n}\n\nexport interface ContainerContentsStoreSyncAgent {\n ensureInitialized: () => void;\n handleRemoteEvents: () => void;\n ingestRemoteContainer: (remoteContainer: RemoteContainer) => Promise<void>;\n primeDocumentsForSharedSubtree: (\n rootContainerId: string,\n isCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n refreshLocalContainers: () => Promise<void>;\n refresh: (options?: { resetAllLaneWatermarks?: boolean }) => Promise<boolean>;\n refreshRootLane: (options?: RefreshRootLaneOptions) => Promise<boolean>;\n requestRemoteHydration: (options?: {\n followDiscoveredParentLanes?: boolean | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n }) => Promise<void>;\n scheduleRemoteHydration: () => void;\n scheduleSync: () => void;\n}\n\nexport interface ContainerContentsStoreSyncState {\n /** Container listing requests that failed or timed out in a current crawl. */\n containerListingFailures: number;\n containersById: Map<string, ContainerState>;\n documentStoresNeedPriming: boolean;\n initializeGeneration: number | null;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n localContainerRefreshPromise: Promise<void> | null;\n localContainerRefreshGeneration: number | null;\n localContainerRefreshStructuralGeneration: number | null;\n localContainersNeedRefresh: boolean;\n /** Invalidates asynchronous hydration work when this store is reset. */\n lifecycleGeneration: number;\n /** Invalidates structural work when its runtime or persistence is replaced. */\n structuralGeneration: number;\n /** Invalidates writes across write-relevant runtime ABA transitions. */\n writeGeneration: number;\n lastEventCount: number;\n /**\n * Update ids this client sent for container metadata documents, registered\n * before the network await of each metadata sync pass. The author's own\n * `document_update_created` echo consumes its ids here instead of arming a\n * redundant forced read-sync; a genuine peer update always carries unknown\n * ids and still forces one. Shared across all metadata docs in the store —\n * update ids are globally unique.\n */\n locallyAcceptedMetadataUpdateIds: Set<string>;\n logLabel?: string | undefined;\n metadataDocumentIdsNeedingSync: Set<string>;\n /**\n * Per-metadata-document enqueue sequence. Bumped for a specific id whenever a\n * remote event re-queues it in {@link metadataDocumentIdsNeedingSync}. A sync\n * pass snapshots the id's sequence before its GET and only clears the id if it\n * is unchanged at pass end, so a mid-pass re-queue of THIS container is not\n * erased. Keyed per id (not a single global counter) so a remote event for an\n * unrelated container does not force a redundant re-sync of this one. See\n * `clearMetadataSyncQueueIfUnchanged`.\n */\n metadataSyncSignalSeqById: Map<string, number>;\n /**\n * Whether this store's first sync pass has requeued the metadata reads a\n * previous run still owed (`container_metadata_revalidations`). Reset with\n * the store, so a replacement database is restored on its own first pass.\n */\n owedMetadataReadsRestored: boolean;\n /**\n * Metadata document ids of folder creates in flight. A remote hint for one\n * queues the folder's first read before the create response installs the id.\n */\n plannedMetadataDocumentIds: Set<string>;\n containerParentIdsNeedingHydration: Set<string | null>;\n persistence: ContainerContentsPersistence;\n remoteHydrationPromise: Promise<void> | null;\n remoteHydrationGeneration: number | null;\n remoteHydrationStructuralGeneration: number | null;\n remoteReconnectRefreshPending: boolean;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n /** True after this store has fully applied an authoritative root lane. */\n rootLaneHydrated: boolean;\n runtime: ContainerContentsStoreRuntime;\n snapshot: { ready: boolean };\n syncLane: ContainerContentsSyncLane | null;\n}\n"]}
|