@tearleads/client-sdk 0.1.212 → 0.1.214

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.
Files changed (47) hide show
  1. package/client/containerContents/documentDiscovery.js +2 -2
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/organizations/organizationReadModels.js +3 -3
  4. package/client/organizations/organizationReadModels.js.map +1 -1
  5. package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +11 -2
  6. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +89 -77
  7. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  8. package/data/persistence/organizations/organizationPresentationDenialPersistence.js +0 -43
  9. package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
  10. package/data/persistence/organizations/organizationReadModelMemberLoad.d.ts +7 -2
  11. package/data/persistence/organizations/organizationReadModelMemberLoad.js +22 -27
  12. package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
  13. package/data/persistence/organizations/organizationReadModelPersistence.js +38 -81
  14. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  15. package/data/persistence/organizations/organizationReadModelPurge.js +0 -38
  16. package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
  17. package/data/persistence/organizations/organizationReadModelRepository.js +264 -0
  18. package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -0
  19. package/package.json +1 -1
  20. package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
  21. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +6 -2
  22. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  23. package/workflows/organizations/index.d.ts +0 -1
  24. package/workflows/organizations/index.js +0 -1
  25. package/workflows/organizations/index.js.map +1 -1
  26. package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js +7 -4
  27. package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js.map +1 -1
  28. package/workflows/organizations/readModel/dataUsageReadModel.js +2 -2
  29. package/workflows/organizations/readModel/dataUsageReadModel.js.map +1 -1
  30. package/workflows/organizations/readModel/listLocalOrganizations.js +4 -2
  31. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
  32. package/workflows/organizations/readModel/localReadModelDetails.js +8 -9
  33. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  34. package/workflows/organizations/readModel/organizationPresentationAccessState.js +2 -2
  35. package/workflows/organizations/readModel/organizationPresentationAccessState.js.map +1 -1
  36. package/workflows/organizations/readModel/readModelProjection.d.ts +1 -1
  37. package/workflows/organizations/readModel/readModelProjection.js +12 -13
  38. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  39. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +0 -49
  40. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +0 -1
  41. package/data/persistence/organizations/organizationGroupNamePersistence.js +0 -33
  42. package/data/persistence/organizations/organizationGroupNamePersistence.js.map +0 -1
  43. package/data/persistence/organizations/organizationProfileDocumentPointers.js +0 -32
  44. package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +0 -1
  45. package/data/persistence/organizations/organizationReadModelCursorPersistence.d.ts +0 -15
  46. package/data/persistence/organizations/organizationReadModelCursorPersistence.js +0 -25
  47. package/data/persistence/organizations/organizationReadModelCursorPersistence.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { sqlContainerContentsPersistence } from "../../data/persistence/container-contents/containerContentsPersistence.js";
2
2
  import { ContainerDocumentTombstoneHoldRepository } from "../../data/persistence/documents/containerDocumentTombstoneHoldRepository.js";
3
- import { createDocumentDiscoveryEvidenceStore } from "../../data/persistence/documents/documentDiscoveryEvidencePersistence.js";
3
+ import { DocumentDiscoveryEvidenceRepository } from "../../data/persistence/documents/documentDiscoveryEvidencePersistence.js";
4
4
  import { getOrCreateOrganizationSyncPauses } from "../../data/sync/organizationSyncPauses.js";
5
5
  import { listContainerDocumentLanesFromApi } from "../../workflows/container-contents/documentDiscovery/containerDocumentListing.js";
6
6
  import { createDiscoveredDocumentVerifier } from "../../workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js";
@@ -55,7 +55,7 @@ export async function discoverContainerDocumentLanesForRuntime({ onOutcome, requ
55
55
  }
56
56
  const runtime = createContainerContentsWorkflowRuntime(input);
57
57
  const execSql = input.infra.execSql;
58
- const evidenceStore = createDocumentDiscoveryEvidenceStore(execSql);
58
+ const evidenceStore = new DocumentDiscoveryEvidenceRepository(execSql);
59
59
  const holdRepository = new ContainerDocumentTombstoneHoldRepository(execSql);
60
60
  const queries = createContainerDocumentQueriesFromRuntime(runtime);
61
61
  // Capture the reset fence before reading any lane's scope, so a reset
@@ -1 +1 @@
1
- {"version":3,"file":"documentDiscovery.js","sourceRoot":"","sources":["documentDiscovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,+BAA+B,EAAE,MAAM,wEAAwE,CAAC;AACzH,OAAO,EAAE,wCAAwC,EAAE,MAAM,2EAA2E,CAAC;AACrI,OAAO,EAAE,oCAAoC,EAAE,MAAM,uEAAuE,CAAC;AAC7H,OAAO,EAAE,iCAAiC,EAAE,MAAM,wCAAwC,CAAC;AAC3F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+EAA+E,CAAC;AAClI,OAAO,EAAE,gCAAgC,EAAE,MAAM,gFAAgF,CAAC;AAClI,OAAO,EAIL,8BAA8B,GAC/B,MAAM,6EAA6E,CAAC;AACrF,OAAO,EAAE,wCAAwC,EAAE,MAAM,6EAA6E,CAAC;AACvI,OAAO,EAAE,yCAAyC,EAAE,MAAM,oDAAoD,CAAC;AAC/G,OAAO,EAEL,sCAAsC,GACvC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,4BAA4B,EAAE,MAAM,6DAA6D,CAAC;AAC3G,OAAO,EACL,wCAAwC,EACxC,+BAA+B,GAChC,MAAM,yEAAyE,CAAC;AACjF,OAAO,EACL,8BAA8B,EAC9B,kCAAkC,GAEnC,MA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CAAC,WAAW,CAAC,CACjE,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,EACzD,cAAc,EACd,GAAG,OAAO,EAGX;IACC,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,wCAAwC,CAAC;QAC/D,QAAQ,EAAE,CAAC,OAAO,CAAC;QACnB,cAAc;KACf,CAAC,CAAC;IACH,IAAI,OAAO,EAAE,MAAM,KAAK,UAAU,EAAE,CAAC;QACnC,IAAI,OAAO,CAAC,MAAM,YAAY,wCAAwC,EAAE,CAAC;YACvE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,OAAO,CAAC,MAAM,CAAC;IACvB,CAAC;IACD,OAAO,OAAO,EAAE,KAAK,IAAI,IAAI,CAAC;AAChC,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport { ContainerDocumentTombstoneHoldRepository } from \"../../data/persistence/documents/containerDocumentTombstoneHoldRepository\";\nimport { createDocumentDiscoveryEvidenceStore } from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../data/sync/organizationSyncPauses\";\nimport { listContainerDocumentLanesFromApi } from \"../../workflows/container-contents/documentDiscovery/containerDocumentListing\";\nimport { createDiscoveredDocumentVerifier } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryEvidence\";\nimport {\n type ContainerDocumentDiscoveryLane,\n type ContainerDocumentDiscoveryOutcome,\n type ContainerDocumentDiscoveryOutcomeHandler,\n discoverContainerDocumentLanes,\n} from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryLanes\";\nimport { ContainerDocumentListingUnavailableError } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryTypes\";\nimport { createContainerDocumentQueriesFromRuntime } from \"../../workflows/container-contents/documentQueries\";\nimport {\n type ContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n} from \"../../workflows/container-contents/runtime\";\nimport { guardDocumentDiscoveryWrites } from \"../../workflows/container-contents/syncPause/discoveryGuard\";\nimport {\n createContainerDocumentTombstoneVerifier,\n createDocumentHeadLinkSetLoader,\n} from \"../../workflows/container-contents/tombstones/documentTombstoneEvidence\";\nimport {\n createPrincipalPolicyOperation,\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../workflows/principals/runtimePolicyWarmer\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\n\nexport type { ContainerDocumentDiscoveryOutcome } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryLanes\";\n\n/** One container to discover, with the reconciler's per-lane callbacks. */\nexport interface ContainerDocumentDiscoveryRequest {\n readonly containerId: string;\n readonly onFullListing?:\n | ((documentIds: ReadonlyArray<string>) => void)\n | undefined;\n readonly onPendingDiscovery?: ((delayMs: number) => void) | undefined;\n}\n\ntype ExecSql = ReturnType<InternalRuntime[\"workflowInput\"]>[\"infra\"][\"execSql\"];\n\nfunction createDiscoveryLane(input: {\n readonly containerOrganizationId: string | undefined;\n readonly isContainerPaused: () => boolean;\n readonly evidenceStore: ReturnType<\n typeof createDocumentDiscoveryEvidenceStore\n >;\n readonly execSql: ExecSql;\n readonly holdRepository: ContainerDocumentTombstoneHoldRepository;\n /** The discovery pass's token: its lanes share one directory discovery. */\n readonly policyOperation: PrincipalPolicyOperation;\n readonly queries: ReturnType<\n typeof createContainerDocumentQueriesFromRuntime\n >;\n readonly request: ContainerDocumentDiscoveryRequest;\n readonly runtime: ContainerContentsWorkflowRuntime;\n}): ContainerDocumentDiscoveryLane {\n const { containerOrganizationId, execSql, holdRepository, request, runtime } =\n input;\n const warmReferencedPrincipalPolicies = createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: input.policyOperation },\n );\n const loadHead = createDocumentHeadLinkSetLoader(\n runtime,\n undefined,\n input.policyOperation,\n );\n const loadEpoch = (documentId: string) =>\n holdRepository.loadLocalDocumentAccessEpoch(documentId);\n return {\n ...input.queries,\n cacheReferencedPrincipalPolicies: (references) =>\n containerOrganizationId\n ? warmReferencedPrincipalPolicies({\n organizationId: containerOrganizationId,\n references,\n })\n : Promise.resolve(),\n containerId: request.containerId,\n holdContainerDocumentTombstones: (tombstones) =>\n holdRepository.holdContainerDocumentTombstones(tombstones),\n listHeldContainerDocumentTombstones: (containerIds) =>\n holdRepository.listRetryableHeldContainerDocumentTombstones(containerIds),\n listKnownContainerDocumentPlacements: (placements) =>\n holdRepository.listKnownContainerDocumentPlacements(placements),\n onFullListing: request.onFullListing,\n refuteContainerDocumentTombstoneHolds: (placements) =>\n holdRepository.refuteContainerDocumentTombstoneHolds(placements),\n verifyContainerDocumentTombstones: createContainerDocumentTombstoneVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n ),\n ...guardDocumentDiscoveryWrites({\n execSql,\n isPaused: input.isContainerPaused,\n verifyDiscoveredDocuments: createDiscoveredDocumentVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n input.evidenceStore,\n request.onPendingDiscovery,\n ),\n }),\n };\n}\n\n/**\n * Internal adapter shared by explicit discovery and background reconciliation:\n * one batched listing for every requested container, then per-container\n * verification scoped to each container's durable organization.\n */\nexport async function discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n}: {\n readonly onOutcome?: ContainerDocumentDiscoveryOutcomeHandler | undefined;\n readonly requests: ReadonlyArray<ContainerDocumentDiscoveryRequest>;\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<ContainerDocumentDiscoveryOutcome>> {\n const unlisted = (\n containerId: string,\n ): ContainerDocumentDiscoveryOutcome => ({\n containerId,\n status: \"fulfilled\",\n value: null,\n });\n const input = runtimeService.workflowInput();\n if (input.infra.dbStatus !== \"ready\") {\n return requests.map(({ containerId }) => unlisted(containerId));\n }\n const runtime = createContainerContentsWorkflowRuntime(input);\n const execSql = input.infra.execSql;\n const evidenceStore = createDocumentDiscoveryEvidenceStore(execSql);\n const holdRepository = new ContainerDocumentTombstoneHoldRepository(execSql);\n const queries = createContainerDocumentQueriesFromRuntime(runtime);\n // Capture the reset fence before reading any lane's scope, so a reset\n // between these reads and the listing cannot publish old-organization\n // evidence into its replacement.\n const generation = await evidenceStore.begin();\n const syncPauses = getOrCreateOrganizationSyncPauses(input.state.domainScope);\n await syncPauses.load(execSql);\n const lanes: ContainerDocumentDiscoveryLane[] = [];\n const policyOperation = createPrincipalPolicyOperation();\n for (const request of requests) {\n const stored =\n await sqlContainerContentsPersistence.loadContainerMetadataState(\n execSql,\n request.containerId,\n );\n if (!stored) continue;\n const isContainerPaused = () =>\n syncPauses.isContainerPaused(\n stored.container,\n runtimeService.workflowInput().auth.organizationId ?? null,\n );\n // A paused organization's container lists like one that is not stored,\n // and a pause landing mid-listing stops its write.\n if (!isContainerPaused())\n lanes.push(\n createDiscoveryLane({\n containerOrganizationId: stored.container.organizationId,\n isContainerPaused,\n evidenceStore,\n execSql,\n holdRepository,\n policyOperation,\n queries,\n request,\n runtime,\n }),\n );\n }\n const outcomes = await discoverContainerDocumentLanes({\n generation,\n lanes,\n listContainerDocumentLanes: (listed) =>\n listContainerDocumentLanesFromApi(runtime.apiClient, listed),\n loadContainerDocumentWatermark: queries.loadContainerDocumentWatermark,\n onOutcome,\n });\n const outcomeByContainerId = new Map(\n outcomes.map((outcome) => [outcome.containerId, outcome]),\n );\n return requests.map(\n ({ containerId }) =>\n outcomeByContainerId.get(containerId) ?? unlisted(containerId),\n );\n}\n\n/**\n * Discovers one container; a rejected lane rethrows its failure, except an\n * unavailable listing, which this contract reports as `null`.\n */\nexport async function discoverContainerDocumentsForRuntime({\n runtimeService,\n ...request\n}: ContainerDocumentDiscoveryRequest & {\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<DocumentSummary> | null> {\n const [outcome] = await discoverContainerDocumentLanesForRuntime({\n requests: [request],\n runtimeService,\n });\n if (outcome?.status === \"rejected\") {\n if (outcome.reason instanceof ContainerDocumentListingUnavailableError) {\n return null;\n }\n throw outcome.reason;\n }\n return outcome?.value ?? null;\n}\n"]}
1
+ {"version":3,"file":"documentDiscovery.js","sourceRoot":"","sources":["documentDiscovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,+BAA+B,EAAE,MAAM,wEAAwE,CAAC;AACzH,OAAO,EAAE,wCAAwC,EAAE,MAAM,2EAA2E,CAAC;AACrI,OAAO,EAAE,mCAAmC,EAAE,MAAM,uEAAuE,CAAC;AAC5H,OAAO,EAAE,iCAAiC,EAAE,MAAM,wCAAwC,CAAC;AAC3F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+EAA+E,CAAC;AAClI,OAAO,EAAE,gCAAgC,EAAE,MAAM,gFAAgF,CAAC;AAClI,OAAO,EAIL,8BAA8B,GAC/B,MAAM,6EAA6E,CAAC;AACrF,OAAO,EAAE,wCAAwC,EAAE,MAAM,6EAA6E,CAAC;AACvI,OAAO,EAAE,yCAAyC,EAAE,MAAM,oDAAoD,CAAC;AAC/G,OAAO,EAEL,sCAAsC,GACvC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,4BAA4B,EAAE,MAAM,6DAA6D,CAAC;AAC3G,OAAO,EACL,wCAAwC,EACxC,+BAA+B,GAChC,MAAM,yEAAyE,CAAC;AACjF,OAAO,EACL,8BAA8B,EAC9B,kCAAkC,GAEnC,MAAM,gDAAgD,CAAC;AAgBxD,SAAS,mBAAmB,CAAC,KAa5B;IACC,MAAM,EAAE,uBAAuB,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,EAAE,GAC1E,KAAK,CAAC;IACR,MAAM,+BAA+B,GAAG,kCAAkC,CACxE,OAAO,EACP,EAAE,SAAS,EAAE,KAAK,CAAC,eAAe,EAAE,CACrC,CAAC;IACF,MAAM,QAAQ,GAAG,+BAA+B,CAC9C,OAAO,EACP,SAAS,EACT,KAAK,CAAC,eAAe,CACtB,CAAC;IACF,MAAM,SAA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E,CAAC;YACvE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,OAAO,CAAC,MAAM,CAAC;IACvB,CAAC;IACD,OAAO,OAAO,EAAE,KAAK,IAAI,IAAI,CAAC;AAChC,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport { ContainerDocumentTombstoneHoldRepository } from \"../../data/persistence/documents/containerDocumentTombstoneHoldRepository\";\nimport { DocumentDiscoveryEvidenceRepository } from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../data/sync/organizationSyncPauses\";\nimport { listContainerDocumentLanesFromApi } from \"../../workflows/container-contents/documentDiscovery/containerDocumentListing\";\nimport { createDiscoveredDocumentVerifier } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryEvidence\";\nimport {\n type ContainerDocumentDiscoveryLane,\n type ContainerDocumentDiscoveryOutcome,\n type ContainerDocumentDiscoveryOutcomeHandler,\n discoverContainerDocumentLanes,\n} from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryLanes\";\nimport { ContainerDocumentListingUnavailableError } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryTypes\";\nimport { createContainerDocumentQueriesFromRuntime } from \"../../workflows/container-contents/documentQueries\";\nimport {\n type ContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n} from \"../../workflows/container-contents/runtime\";\nimport { guardDocumentDiscoveryWrites } from \"../../workflows/container-contents/syncPause/discoveryGuard\";\nimport {\n createContainerDocumentTombstoneVerifier,\n createDocumentHeadLinkSetLoader,\n} from \"../../workflows/container-contents/tombstones/documentTombstoneEvidence\";\nimport {\n createPrincipalPolicyOperation,\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../workflows/principals/runtimePolicyWarmer\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\n\nexport type { ContainerDocumentDiscoveryOutcome } from \"../../workflows/container-contents/documentDiscovery/documentDiscoveryLanes\";\n\n/** One container to discover, with the reconciler's per-lane callbacks. */\nexport interface ContainerDocumentDiscoveryRequest {\n readonly containerId: string;\n readonly onFullListing?:\n | ((documentIds: ReadonlyArray<string>) => void)\n | undefined;\n readonly onPendingDiscovery?: ((delayMs: number) => void) | undefined;\n}\n\ntype ExecSql = ReturnType<InternalRuntime[\"workflowInput\"]>[\"infra\"][\"execSql\"];\n\nfunction createDiscoveryLane(input: {\n readonly containerOrganizationId: string | undefined;\n readonly isContainerPaused: () => boolean;\n readonly evidenceStore: DocumentDiscoveryEvidenceRepository;\n readonly execSql: ExecSql;\n readonly holdRepository: ContainerDocumentTombstoneHoldRepository;\n /** The discovery pass's token: its lanes share one directory discovery. */\n readonly policyOperation: PrincipalPolicyOperation;\n readonly queries: ReturnType<\n typeof createContainerDocumentQueriesFromRuntime\n >;\n readonly request: ContainerDocumentDiscoveryRequest;\n readonly runtime: ContainerContentsWorkflowRuntime;\n}): ContainerDocumentDiscoveryLane {\n const { containerOrganizationId, execSql, holdRepository, request, runtime } =\n input;\n const warmReferencedPrincipalPolicies = createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: input.policyOperation },\n );\n const loadHead = createDocumentHeadLinkSetLoader(\n runtime,\n undefined,\n input.policyOperation,\n );\n const loadEpoch = (documentId: string) =>\n holdRepository.loadLocalDocumentAccessEpoch(documentId);\n return {\n ...input.queries,\n cacheReferencedPrincipalPolicies: (references) =>\n containerOrganizationId\n ? warmReferencedPrincipalPolicies({\n organizationId: containerOrganizationId,\n references,\n })\n : Promise.resolve(),\n containerId: request.containerId,\n holdContainerDocumentTombstones: (tombstones) =>\n holdRepository.holdContainerDocumentTombstones(tombstones),\n listHeldContainerDocumentTombstones: (containerIds) =>\n holdRepository.listRetryableHeldContainerDocumentTombstones(containerIds),\n listKnownContainerDocumentPlacements: (placements) =>\n holdRepository.listKnownContainerDocumentPlacements(placements),\n onFullListing: request.onFullListing,\n refuteContainerDocumentTombstoneHolds: (placements) =>\n holdRepository.refuteContainerDocumentTombstoneHolds(placements),\n verifyContainerDocumentTombstones: createContainerDocumentTombstoneVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n ),\n ...guardDocumentDiscoveryWrites({\n execSql,\n isPaused: input.isContainerPaused,\n verifyDiscoveredDocuments: createDiscoveredDocumentVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n input.evidenceStore,\n request.onPendingDiscovery,\n ),\n }),\n };\n}\n\n/**\n * Internal adapter shared by explicit discovery and background reconciliation:\n * one batched listing for every requested container, then per-container\n * verification scoped to each container's durable organization.\n */\nexport async function discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n}: {\n readonly onOutcome?: ContainerDocumentDiscoveryOutcomeHandler | undefined;\n readonly requests: ReadonlyArray<ContainerDocumentDiscoveryRequest>;\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<ContainerDocumentDiscoveryOutcome>> {\n const unlisted = (\n containerId: string,\n ): ContainerDocumentDiscoveryOutcome => ({\n containerId,\n status: \"fulfilled\",\n value: null,\n });\n const input = runtimeService.workflowInput();\n if (input.infra.dbStatus !== \"ready\") {\n return requests.map(({ containerId }) => unlisted(containerId));\n }\n const runtime = createContainerContentsWorkflowRuntime(input);\n const execSql = input.infra.execSql;\n const evidenceStore = new DocumentDiscoveryEvidenceRepository(execSql);\n const holdRepository = new ContainerDocumentTombstoneHoldRepository(execSql);\n const queries = createContainerDocumentQueriesFromRuntime(runtime);\n // Capture the reset fence before reading any lane's scope, so a reset\n // between these reads and the listing cannot publish old-organization\n // evidence into its replacement.\n const generation = await evidenceStore.begin();\n const syncPauses = getOrCreateOrganizationSyncPauses(input.state.domainScope);\n await syncPauses.load(execSql);\n const lanes: ContainerDocumentDiscoveryLane[] = [];\n const policyOperation = createPrincipalPolicyOperation();\n for (const request of requests) {\n const stored =\n await sqlContainerContentsPersistence.loadContainerMetadataState(\n execSql,\n request.containerId,\n );\n if (!stored) continue;\n const isContainerPaused = () =>\n syncPauses.isContainerPaused(\n stored.container,\n runtimeService.workflowInput().auth.organizationId ?? null,\n );\n // A paused organization's container lists like one that is not stored,\n // and a pause landing mid-listing stops its write.\n if (!isContainerPaused())\n lanes.push(\n createDiscoveryLane({\n containerOrganizationId: stored.container.organizationId,\n isContainerPaused,\n evidenceStore,\n execSql,\n holdRepository,\n policyOperation,\n queries,\n request,\n runtime,\n }),\n );\n }\n const outcomes = await discoverContainerDocumentLanes({\n generation,\n lanes,\n listContainerDocumentLanes: (listed) =>\n listContainerDocumentLanesFromApi(runtime.apiClient, listed),\n loadContainerDocumentWatermark: queries.loadContainerDocumentWatermark,\n onOutcome,\n });\n const outcomeByContainerId = new Map(\n outcomes.map((outcome) => [outcome.containerId, outcome]),\n );\n return requests.map(\n ({ containerId }) =>\n outcomeByContainerId.get(containerId) ?? unlisted(containerId),\n );\n}\n\n/**\n * Discovers one container; a rejected lane rethrows its failure, except an\n * unavailable listing, which this contract reports as `null`.\n */\nexport async function discoverContainerDocumentsForRuntime({\n runtimeService,\n ...request\n}: ContainerDocumentDiscoveryRequest & {\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<DocumentSummary> | null> {\n const [outcome] = await discoverContainerDocumentLanesForRuntime({\n requests: [request],\n runtimeService,\n });\n if (outcome?.status === \"rejected\") {\n if (outcome.reason instanceof ContainerDocumentListingUnavailableError) {\n return null;\n }\n throw outcome.reason;\n }\n return outcome?.value ?? null;\n}\n"]}
@@ -1,5 +1,6 @@
1
+ import { OrganizationReadModelRepository } from "../../data/persistence/organizations/organizationReadModelRepository.js";
1
2
  import { recoverOrganizationAccess } from "../../workflows/container-contents/recovery/accessRestoration.js";
2
- import { loadAppliedOrganizationReadModelCursor, loadLocalOrganizationContainerGrants, loadLocalOrganizationDirectoryAndGroups, loadLocalOrganizationGroupContainers, loadLocalOrganizationGroupMembers, loadLocalOrganizationUserDetail, reconcileOrganizationDirectoryAndGroups, withVerifiedLeaveRequests, withVerifiedUserLeaveRequest, } from "../../workflows/organizations/index.js";
3
+ import { loadLocalOrganizationContainerGrants, loadLocalOrganizationDirectoryAndGroups, loadLocalOrganizationGroupContainers, loadLocalOrganizationGroupMembers, loadLocalOrganizationUserDetail, reconcileOrganizationDirectoryAndGroups, withVerifiedLeaveRequests, withVerifiedUserLeaveRequest, } from "../../workflows/organizations/index.js";
3
4
  import { createRuntimeLeaveRequestMembershipCheck } from "../../workflows/organizations/memberships/leaveRequestMembersEvidence.js";
4
5
  import { organizationAccessScopeKey, wasOrganizationPresentationAccessDeniedByServer, } from "../../workflows/organizations/readModel/organizationPresentationAccessState.js";
5
6
  import { loadBoundedOrganizationGroupHistory } from "./organizationGroupHistory.js";
@@ -207,8 +208,7 @@ class OrganizationReadModelCoordinatorImpl {
207
208
  return null;
208
209
  }
209
210
  await this.settleInFlightReconcile(active);
210
- const applied = await loadAppliedOrganizationReadModelCursor({
211
- execSql: active.runtime.infra.execSql,
211
+ const applied = await new OrganizationReadModelRepository(active.runtime.infra.execSql).loadAppliedOrganizationReadModelCursor({
212
212
  organizationId: active.organizationId,
213
213
  requesterUserId: active.userId,
214
214
  });
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModels.js","sourceRoot":"","sources":["organizationReadModels.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+DAA+D,CAAC;AAC1G,OAAO,EACL,sCAAsC,EACtC,oCAAoC,EACpC,uCAAuC,EACvC,oCAAoC,EACpC,iCAAiC,EACjC,+BAA+B,EAQ/B,uCAAuC,EACvC,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,wCAAwC,EAAE,MAAM,uEAAuE,CAAC;AAEjI,OAAO,EACL,0BAA0B,EAC1B,+CAA+C,GAChD,MAAM,6EAA6E,CAAC;AAKrF,OAAO,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AACjF,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AAI,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC/B,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,KAAK,GAAG,IAAI,GAAG,EAAE,CAAC;QAClB,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAC5B,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,cAA+B;IAE/B,MAAM,QAAQ,GAAG,qBAAqB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC3D,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,oCAAoC,CAAC,cAAc,CAAC,CAAC;IAC7E,qBAAqB,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACvD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport { recoverOrganizationAccess } from \"../../workflows/container-contents/recovery/accessRestoration\";\nimport {\n loadAppliedOrganizationReadModelCursor,\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupMembers,\n loadLocalOrganizationUserDetail,\n type OrganizationContainerGrants,\n type OrganizationDirectoryAndGroups,\n type OrganizationGroupContainers,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationPolicyHistory,\n type OrganizationUserDetail,\n reconcileOrganizationDirectoryAndGroups,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"../../workflows/organizations\";\nimport { createRuntimeLeaveRequestMembershipCheck } from \"../../workflows/organizations/memberships/leaveRequestMembersEvidence\";\nimport type { LeaveRequestVerifier } from \"../../workflows/organizations/memberships/leaveRequestVerification\";\nimport {\n organizationAccessScopeKey,\n wasOrganizationPresentationAccessDeniedByServer,\n} from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\nimport { loadBoundedOrganizationGroupHistory } from \"./organizationGroupHistory\";\nimport { hydrateOrganizationGroupNamesForRuntime } from \"./organizationGroupNameHydration\";\nimport { loadBoundedOrganizationHistory } from \"./organizationHistory\";\nimport {\n type ActiveOrganizationDataRuntime,\n activeOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\nconst coordinatorsByRuntime = new WeakMap<\n InternalRuntime,\n OrganizationReadModelCoordinator\n>();\n\n/**\n * What one view's leave requests are checked against. The signer comes from\n * the device's durable pin first, so a request already stored still verifies\n * offline, then a trusted remote resolution for a member not pinned yet. The\n * membership comes from this device's verified organization policy.\n */\nexport function leaveRequestVerifier(\n runtimeService: InternalRuntime,\n runtime: InternalWorkflowRuntimeInput,\n organization: { readonly organizationId: string; readonly userId: string },\n): LeaveRequestVerifier {\n const { domainScope } = runtime.state;\n return {\n resolveTrustedUserIdentity: async (userId) =>\n (await runtimeService.identityLinks.resolvePinned(userId)) ??\n runtime.resolveTrustedUserIdentity(userId),\n membershipIsCurrent: createRuntimeLeaveRequestMembershipCheck({\n currentUserId: organization.userId,\n organizationId: organization.organizationId,\n runtime,\n stillCurrent: () =>\n runtimeService.workflowInput().state.domainScope === domainScope,\n }),\n };\n}\n\nexport interface OrganizationReadModelCoordinator {\n loadLocal(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null>;\n loadLocalGroupMembers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupMembers | null>;\n loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationGroupPolicyHistory | null>;\n loadOrganizationPolicyHistory(\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationPolicyHistory | null>;\n loadLocalGrants(\n organizationId?: string | undefined,\n ): Promise<OrganizationContainerGrants | null>;\n loadLocalGroupContainers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupContainers | null>;\n loadLocalUserDetail(\n userId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationUserDetail | null>;\n /**\n * Resolves `undefined` when the runtime declines without I/O (offline,\n * database not ready, organization mismatch) or when the feed failed,\n * even with locally retained data — passes that must not count as caught\n * up; `null` when the reconcile completed but produced nothing presentable\n * — including an authoritative denial that purged the projection, which\n * consumers must repaint.\n */\n reconcile(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n reconcileAfterMutation(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n /** The applied cursor once this scope's in-flight reconcile settles. */\n loadAppliedCursor(\n organizationId?: string | undefined,\n ): Promise<string | null>;\n}\n\nclass OrganizationReadModelCoordinatorImpl\n implements OrganizationReadModelCoordinator\n{\n private readonly reconciliationsByScope = new WeakMap<\n DomainScope,\n Map<string, Promise<OrganizationDirectoryAndGroups | null | undefined>>\n >();\n // The cursor each requester's last reconcile fully presented: applied,\n // group names hydrated and leave requests verified. A stored cursor whose\n // presentation work failed does not count as applied, so the next hint\n // reconciles and retries that work.\n private readonly presentedCursorsByScope = new WeakMap<\n DomainScope,\n Map<string, string>\n >();\n constructor(private readonly runtimeService: InternalRuntime) {}\n\n private reconciliationMap(active: ActiveOrganizationDataRuntime) {\n return scopedMap(this.reconciliationsByScope, active);\n }\n\n async loadLocal(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return withVerifiedLeaveRequests(\n await loadLocalOrganizationDirectoryAndGroups({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n }),\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n async loadLocalGrants(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationContainerGrants({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupContainers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupContainers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupMembers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupMembers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationGroupHistory({\n active,\n groupId,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadOrganizationPolicyHistory(\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationHistory({\n active,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadLocalUserDetail(userId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || userId.length === 0) {\n return null;\n }\n return withVerifiedUserLeaveRequest(\n await loadLocalOrganizationUserDetail({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n userId,\n }),\n active.organizationId,\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n reconcile(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return Promise.resolve(undefined);\n }\n\n const byKey = this.reconciliationMap(active);\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n const existing = byKey.get(key);\n if (existing) {\n return existing;\n }\n const presentedCursors = scopedMap(this.presentedCursorsByScope, active);\n\n // Snapshot the server-denied flag before reconciling. A reconcile that\n // flips it back to readable means org access was just restored (e.g. the\n // user was re-added to a group), and any write lanes idled by\n // permission-denied submissions have no self re-arm — regaining access is\n // their retry signal, mirroring how billing recovery re-requests all\n // lanes. Only a genuine server denial counts: a local session reset also\n // marks scopes denied, and re-arming on its first reconcile would race the\n // startup sync passes (e.g. pending-create adoption between panes).\n const accessWasDenied = wasOrganizationPresentationAccessDeniedByServer(\n {\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n },\n \"readModel\",\n );\n const domainScope = active.runtime.state.domainScope;\n const stillCurrent = () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n );\n\n const reconciliation = reconcileOrganizationDirectoryAndGroups({\n apiClient: active.runtime.apiClient,\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n })\n .then(async (directoryAndGroups) => {\n if (!stillCurrent()) return null;\n // Feed success restores retry eligibility even if name decryption fails.\n const accessWasRestored =\n accessWasDenied &&\n directoryAndGroups !== null &&\n directoryAndGroups !== undefined;\n if (accessWasRestored)\n await recoverOrganizationAccess({\n domainScope,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n stillCurrent,\n userId: active.userId,\n });\n if (!stillCurrent()) return null;\n return withVerifiedLeaveRequests(\n await hydrateOrganizationGroupNamesForRuntime(\n this.runtimeService,\n active,\n domainScope,\n directoryAndGroups,\n ),\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n })\n .then(\n (presented) => {\n if (presented) presentedCursors.set(key, presented.readModelCursor);\n else presentedCursors.delete(key);\n return presented;\n },\n (error: unknown) => {\n presentedCursors.delete(key);\n throw error;\n },\n )\n .finally(() => {\n if (byKey.get(key) === reconciliation) {\n byKey.delete(key);\n }\n });\n byKey.set(key, reconciliation);\n return reconciliation;\n }\n\n async reconcileAfterMutation(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return undefined;\n }\n await this.settleInFlightReconcile(active);\n return this.reconcile(active.organizationId);\n }\n\n async loadAppliedCursor(organizationId?: string): Promise<string | null> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n await this.settleInFlightReconcile(active);\n const applied = await loadAppliedOrganizationReadModelCursor({\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n });\n const presented = scopedMap(this.presentedCursorsByScope, active).get(\n organizationAccessScopeKey(active.organizationId, active.userId),\n );\n return applied !== null && applied === presented ? applied : null;\n }\n\n private async settleInFlightReconcile(\n active: ActiveOrganizationDataRuntime,\n ): Promise<void> {\n await this.reconciliationMap(active)\n .get(organizationAccessScopeKey(active.organizationId, active.userId))\n ?.catch(() => null);\n }\n}\n\nfunction scopedMap<T>(\n byScope: WeakMap<DomainScope, Map<string, T>>,\n active: ActiveOrganizationDataRuntime,\n): Map<string, T> {\n const scope = active.runtime.state.domainScope;\n let byKey = byScope.get(scope);\n if (!byKey) {\n byKey = new Map();\n byScope.set(scope, byKey);\n }\n return byKey;\n}\n\nexport function createOrganizationReadModelCoordinator(\n runtimeService: InternalRuntime,\n): OrganizationReadModelCoordinator {\n const existing = coordinatorsByRuntime.get(runtimeService);\n if (existing) {\n return existing;\n }\n\n const coordinator = new OrganizationReadModelCoordinatorImpl(runtimeService);\n coordinatorsByRuntime.set(runtimeService, coordinator);\n return coordinator;\n}\n"]}
1
+ {"version":3,"file":"organizationReadModels.js","sourceRoot":"","sources":["organizationReadModels.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,sEAAsE,CAAC;AAEvH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+DAA+D,CAAC;AAC1G,OAAO,EACL,oCAAoC,EACpC,uCAAuC,EACvC,oCAAoC,EACpC,iCAAiC,EACjC,+BAA+B,EAQ/B,uCAAuC,EACvC,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,wCAAwC,EAAE,MAAM,uEAAuE,CAAC;AAEjI,OAAO,EACL,0BAA0B,EAC1B,+CAA+C,GAChD,MAAM,6EAA6E,CAAC;AAKrF,OAAO,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,uCAAuC,EAAE,MAAM,kCAAkC,CAAC;AAC3F,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAEL,6BAA6B,EAC7B,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAEvC,MAAM,qBAAqB,GAAG,IAAI,OAAO,EAGtC,CAAC;AAEJ;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAClC,cAA+B,EAC/B,OAAqC,EACrC,YAA0E;IAE1E,MAAM,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC,KAAK,CAAC;IACtC,OAAO;QACL,0BAA0B,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,CAC3C,CAAC,MAAM,cAAc,CAAC,aAAa,CAAC,aAAa,CAAC,MAAM,CAAC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C;IAC7E,qBAAqB,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACvD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { OrganizationReadModelRepository } from \"../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport { recoverOrganizationAccess } from \"../../workflows/container-contents/recovery/accessRestoration\";\nimport {\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupMembers,\n loadLocalOrganizationUserDetail,\n type OrganizationContainerGrants,\n type OrganizationDirectoryAndGroups,\n type OrganizationGroupContainers,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationPolicyHistory,\n type OrganizationUserDetail,\n reconcileOrganizationDirectoryAndGroups,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"../../workflows/organizations\";\nimport { createRuntimeLeaveRequestMembershipCheck } from \"../../workflows/organizations/memberships/leaveRequestMembersEvidence\";\nimport type { LeaveRequestVerifier } from \"../../workflows/organizations/memberships/leaveRequestVerification\";\nimport {\n organizationAccessScopeKey,\n wasOrganizationPresentationAccessDeniedByServer,\n} from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\nimport { loadBoundedOrganizationGroupHistory } from \"./organizationGroupHistory\";\nimport { hydrateOrganizationGroupNamesForRuntime } from \"./organizationGroupNameHydration\";\nimport { loadBoundedOrganizationHistory } from \"./organizationHistory\";\nimport {\n type ActiveOrganizationDataRuntime,\n activeOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\nconst coordinatorsByRuntime = new WeakMap<\n InternalRuntime,\n OrganizationReadModelCoordinator\n>();\n\n/**\n * What one view's leave requests are checked against. The signer comes from\n * the device's durable pin first, so a request already stored still verifies\n * offline, then a trusted remote resolution for a member not pinned yet. The\n * membership comes from this device's verified organization policy.\n */\nexport function leaveRequestVerifier(\n runtimeService: InternalRuntime,\n runtime: InternalWorkflowRuntimeInput,\n organization: { readonly organizationId: string; readonly userId: string },\n): LeaveRequestVerifier {\n const { domainScope } = runtime.state;\n return {\n resolveTrustedUserIdentity: async (userId) =>\n (await runtimeService.identityLinks.resolvePinned(userId)) ??\n runtime.resolveTrustedUserIdentity(userId),\n membershipIsCurrent: createRuntimeLeaveRequestMembershipCheck({\n currentUserId: organization.userId,\n organizationId: organization.organizationId,\n runtime,\n stillCurrent: () =>\n runtimeService.workflowInput().state.domainScope === domainScope,\n }),\n };\n}\n\nexport interface OrganizationReadModelCoordinator {\n loadLocal(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null>;\n loadLocalGroupMembers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupMembers | null>;\n loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationGroupPolicyHistory | null>;\n loadOrganizationPolicyHistory(\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationPolicyHistory | null>;\n loadLocalGrants(\n organizationId?: string | undefined,\n ): Promise<OrganizationContainerGrants | null>;\n loadLocalGroupContainers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupContainers | null>;\n loadLocalUserDetail(\n userId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationUserDetail | null>;\n /**\n * Resolves `undefined` when the runtime declines without I/O (offline,\n * database not ready, organization mismatch) or when the feed failed,\n * even with locally retained data — passes that must not count as caught\n * up; `null` when the reconcile completed but produced nothing presentable\n * — including an authoritative denial that purged the projection, which\n * consumers must repaint.\n */\n reconcile(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n reconcileAfterMutation(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n /** The applied cursor once this scope's in-flight reconcile settles. */\n loadAppliedCursor(\n organizationId?: string | undefined,\n ): Promise<string | null>;\n}\n\nclass OrganizationReadModelCoordinatorImpl\n implements OrganizationReadModelCoordinator\n{\n private readonly reconciliationsByScope = new WeakMap<\n DomainScope,\n Map<string, Promise<OrganizationDirectoryAndGroups | null | undefined>>\n >();\n // The cursor each requester's last reconcile fully presented: applied,\n // group names hydrated and leave requests verified. A stored cursor whose\n // presentation work failed does not count as applied, so the next hint\n // reconciles and retries that work.\n private readonly presentedCursorsByScope = new WeakMap<\n DomainScope,\n Map<string, string>\n >();\n constructor(private readonly runtimeService: InternalRuntime) {}\n\n private reconciliationMap(active: ActiveOrganizationDataRuntime) {\n return scopedMap(this.reconciliationsByScope, active);\n }\n\n async loadLocal(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return withVerifiedLeaveRequests(\n await loadLocalOrganizationDirectoryAndGroups({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n }),\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n async loadLocalGrants(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationContainerGrants({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupContainers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupContainers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupMembers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupMembers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationGroupHistory({\n active,\n groupId,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadOrganizationPolicyHistory(\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationHistory({\n active,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadLocalUserDetail(userId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || userId.length === 0) {\n return null;\n }\n return withVerifiedUserLeaveRequest(\n await loadLocalOrganizationUserDetail({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n userId,\n }),\n active.organizationId,\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n reconcile(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return Promise.resolve(undefined);\n }\n\n const byKey = this.reconciliationMap(active);\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n const existing = byKey.get(key);\n if (existing) {\n return existing;\n }\n const presentedCursors = scopedMap(this.presentedCursorsByScope, active);\n\n // Snapshot the server-denied flag before reconciling. A reconcile that\n // flips it back to readable means org access was just restored (e.g. the\n // user was re-added to a group), and any write lanes idled by\n // permission-denied submissions have no self re-arm — regaining access is\n // their retry signal, mirroring how billing recovery re-requests all\n // lanes. Only a genuine server denial counts: a local session reset also\n // marks scopes denied, and re-arming on its first reconcile would race the\n // startup sync passes (e.g. pending-create adoption between panes).\n const accessWasDenied = wasOrganizationPresentationAccessDeniedByServer(\n {\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n },\n \"readModel\",\n );\n const domainScope = active.runtime.state.domainScope;\n const stillCurrent = () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n );\n\n const reconciliation = reconcileOrganizationDirectoryAndGroups({\n apiClient: active.runtime.apiClient,\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n })\n .then(async (directoryAndGroups) => {\n if (!stillCurrent()) return null;\n // Feed success restores retry eligibility even if name decryption fails.\n const accessWasRestored =\n accessWasDenied &&\n directoryAndGroups !== null &&\n directoryAndGroups !== undefined;\n if (accessWasRestored)\n await recoverOrganizationAccess({\n domainScope,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n stillCurrent,\n userId: active.userId,\n });\n if (!stillCurrent()) return null;\n return withVerifiedLeaveRequests(\n await hydrateOrganizationGroupNamesForRuntime(\n this.runtimeService,\n active,\n domainScope,\n directoryAndGroups,\n ),\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n })\n .then(\n (presented) => {\n if (presented) presentedCursors.set(key, presented.readModelCursor);\n else presentedCursors.delete(key);\n return presented;\n },\n (error: unknown) => {\n presentedCursors.delete(key);\n throw error;\n },\n )\n .finally(() => {\n if (byKey.get(key) === reconciliation) {\n byKey.delete(key);\n }\n });\n byKey.set(key, reconciliation);\n return reconciliation;\n }\n\n async reconcileAfterMutation(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return undefined;\n }\n await this.settleInFlightReconcile(active);\n return this.reconcile(active.organizationId);\n }\n\n async loadAppliedCursor(organizationId?: string): Promise<string | null> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n await this.settleInFlightReconcile(active);\n const applied = await new OrganizationReadModelRepository(\n active.runtime.infra.execSql,\n ).loadAppliedOrganizationReadModelCursor({\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n });\n const presented = scopedMap(this.presentedCursorsByScope, active).get(\n organizationAccessScopeKey(active.organizationId, active.userId),\n );\n return applied !== null && applied === presented ? applied : null;\n }\n\n private async settleInFlightReconcile(\n active: ActiveOrganizationDataRuntime,\n ): Promise<void> {\n await this.reconciliationMap(active)\n .get(organizationAccessScopeKey(active.organizationId, active.userId))\n ?.catch(() => null);\n }\n}\n\nfunction scopedMap<T>(\n byScope: WeakMap<DomainScope, Map<string, T>>,\n active: ActiveOrganizationDataRuntime,\n): Map<string, T> {\n const scope = active.runtime.state.domainScope;\n let byKey = byScope.get(scope);\n if (!byKey) {\n byKey = new Map();\n byScope.set(scope, byKey);\n }\n return byKey;\n}\n\nexport function createOrganizationReadModelCoordinator(\n runtimeService: InternalRuntime,\n): OrganizationReadModelCoordinator {\n const existing = coordinatorsByRuntime.get(runtimeService);\n if (existing) {\n return existing;\n }\n\n const coordinator = new OrganizationReadModelCoordinatorImpl(runtimeService);\n coordinatorsByRuntime.set(runtimeService, coordinator);\n return coordinator;\n}\n"]}
@@ -12,7 +12,17 @@ interface RemovedDiscoveryPlacement {
12
12
  readonly containerId: string;
13
13
  readonly documentId: string;
14
14
  }
15
- export interface DocumentDiscoveryEvidenceStore {
15
+ /**
16
+ * Untrusted document discovery evidence bound to one executor and clock. The
17
+ * clock (epoch milliseconds, like the `retryAt` column) schedules and reports
18
+ * pending-discovery retries.
19
+ */
20
+ export declare class DocumentDiscoveryEvidenceRepository {
21
+ private readonly execSql;
22
+ private readonly now;
23
+ constructor(execSql: ExecSql, now?: () => number);
24
+ private read;
25
+ private write;
16
26
  begin(): Promise<number>;
17
27
  isCurrent(generation: number): Promise<boolean>;
18
28
  stage(inputs: readonly DiscoveredDocumentCandidate[], generation: number, removed?: readonly RemovedDiscoveryPlacement[]): Promise<boolean>;
@@ -40,4 +50,3 @@ export interface AuthoredDiscoveryHead {
40
50
  }
41
51
  /** Writes authored heads inside the caller's serialized write transaction. */
42
52
  export declare function primeAuthoredDocumentDiscoveryHeads(execSql: ExecSql, authored: readonly AuthoredDiscoveryHead[]): Promise<void>;
43
- export declare function createDocumentDiscoveryEvidenceStore(execSql: ExecSql, now?: () => number): DocumentDiscoveryEvidenceStore;
@@ -19,22 +19,29 @@ const ID_BATCH_SIZE = 400;
19
19
  const batches = (ids) => Array.from({ length: Math.ceil(ids.length / ID_BATCH_SIZE) }, (_, i) => ids.slice(i * ID_BATCH_SIZE, (i + 1) * ID_BATCH_SIZE));
20
20
  const chunked = (rows, size) => Array.from({ length: Math.ceil(rows.length / size) }, (_, i) => rows.slice(i * size, (i + 1) * size));
21
21
  const identity = (input) => and(eq(pending.containerId, input.containerId), eq(pending.documentId, input.documentId), eq(pending.inputJson, JSON.stringify(input)));
22
- class SqlDocumentDiscoveryEvidenceStore {
22
+ /**
23
+ * Untrusted document discovery evidence bound to one executor and clock. The
24
+ * clock (epoch milliseconds, like the `retryAt` column) schedules and reports
25
+ * pending-discovery retries.
26
+ */
27
+ export class DocumentDiscoveryEvidenceRepository {
23
28
  execSql;
24
29
  now;
25
- constructor(execSql, now) {
30
+ constructor(execSql, now = Date.now) {
26
31
  this.execSql = execSql;
27
32
  this.now = now;
28
33
  }
29
- read = async () => {
34
+ async read() {
30
35
  await ensureSqlTables(this.execSql, documentContainerProjectionTables);
31
36
  return getClientSQLitePersistenceRuntime(this.execSql).db;
32
- };
33
- write = async (operation) => runSerializedSqlMutation(this.execSql, async (locked) => {
34
- await ensureSqlTables(locked, documentContainerProjectionTables);
35
- return operation(getClientSQLitePersistenceRuntime(locked).db);
36
- });
37
- begin = async () => {
37
+ }
38
+ write(operation) {
39
+ return runSerializedSqlMutation(this.execSql, async (locked) => {
40
+ await ensureSqlTables(locked, documentContainerProjectionTables);
41
+ return operation(getClientSQLitePersistenceRuntime(locked).db);
42
+ });
43
+ }
44
+ async begin() {
38
45
  let generation = 0;
39
46
  await this.write(async (db) => {
40
47
  const [row] = await db
@@ -52,9 +59,11 @@ class SqlDocumentDiscoveryEvidenceStore {
52
59
  generation = row.generation;
53
60
  });
54
61
  return generation;
55
- };
56
- isCurrent = async (generation) => isDocumentDiscoveryGenerationCurrent(await this.read(), generation);
57
- stage = (inputs, generation, removed = []) => {
62
+ }
63
+ async isCurrent(generation) {
64
+ return isDocumentDiscoveryGenerationCurrent(await this.read(), generation);
65
+ }
66
+ stage(inputs, generation, removed = []) {
58
67
  return this.write(async (db) => {
59
68
  if (!(await isDocumentDiscoveryGenerationCurrent(db, generation)))
60
69
  return false;
@@ -107,8 +116,8 @@ class SqlDocumentDiscoveryEvidenceStore {
107
116
  });
108
117
  return true;
109
118
  });
110
- };
111
- pending = async (containerIds, limit) => {
119
+ }
120
+ async pending(containerIds, limit) {
112
121
  const db = await this.read();
113
122
  const result = [];
114
123
  for (const batch of batches(containerIds)) {
@@ -123,39 +132,43 @@ class SqlDocumentDiscoveryEvidenceStore {
123
132
  result.push(...rows.map((row) => readStoredDiscoveryCandidate(row.inputJson)));
124
133
  }
125
134
  return result;
126
- };
127
- defer = (input, generation) => this.write(async (db) => {
128
- if (!(await isDocumentDiscoveryGenerationCurrent(db, generation)))
129
- return;
130
- const [row] = await db
131
- .select({ attempts: pending.attempts })
132
- .from(pending)
133
- .where(identity(input))
134
- .limit(1);
135
- if (!row)
136
- return;
137
- const attempts = Math.min(row.attempts + 1, 8);
138
- await db
139
- .update(pending)
140
- .set({
141
- attempts,
142
- retryAt: this.now() + heldTombstoneRetryDelayMs(attempts),
143
- })
144
- .where(identity(input))
145
- .run();
146
- });
147
- acknowledge = (inputs, generation) => this.write(async (db) => {
148
- if (!(await isDocumentDiscoveryGenerationCurrent(db, generation)))
149
- return;
150
- await db.transaction(async (tx) => {
151
- for (const batch of remoteResetBatches(inputs))
152
- await tx
153
- .delete(pending)
154
- .where(or(...batch.map(identity)))
155
- .run();
135
+ }
136
+ defer(input, generation) {
137
+ return this.write(async (db) => {
138
+ if (!(await isDocumentDiscoveryGenerationCurrent(db, generation)))
139
+ return;
140
+ const [row] = await db
141
+ .select({ attempts: pending.attempts })
142
+ .from(pending)
143
+ .where(identity(input))
144
+ .limit(1);
145
+ if (!row)
146
+ return;
147
+ const attempts = Math.min(row.attempts + 1, 8);
148
+ await db
149
+ .update(pending)
150
+ .set({
151
+ attempts,
152
+ retryAt: this.now() + heldTombstoneRetryDelayMs(attempts),
153
+ })
154
+ .where(identity(input))
155
+ .run();
156
+ });
157
+ }
158
+ acknowledge(inputs, generation) {
159
+ return this.write(async (db) => {
160
+ if (!(await isDocumentDiscoveryGenerationCurrent(db, generation)))
161
+ return;
162
+ await db.transaction(async (tx) => {
163
+ for (const batch of remoteResetBatches(inputs))
164
+ await tx
165
+ .delete(pending)
166
+ .where(or(...batch.map(identity)))
167
+ .run();
168
+ });
156
169
  });
157
- });
158
- hasPending = async (containerIds) => {
170
+ }
171
+ async hasPending(containerIds) {
159
172
  const db = await this.read();
160
173
  for (const batch of batches(containerIds)) {
161
174
  if ((await db
@@ -166,8 +179,8 @@ class SqlDocumentDiscoveryEvidenceStore {
166
179
  return true;
167
180
  }
168
181
  return false;
169
- };
170
- retryDelay = async (containerIds) => {
182
+ }
183
+ async retryDelay(containerIds) {
171
184
  const db = await this.read();
172
185
  let due = null;
173
186
  for (const batch of batches(containerIds)) {
@@ -179,8 +192,8 @@ class SqlDocumentDiscoveryEvidenceStore {
179
192
  due = Math.min(due ?? row.due, row.due);
180
193
  }
181
194
  return due === null ? null : Math.max(0, due - this.now());
182
- };
183
- loadHead = async (documentId, manifestHash) => {
195
+ }
196
+ async loadHead(documentId, manifestHash) {
184
197
  if (await new KeyingCheckpointRepository(this.execSql).loadDocumentPurgeCheckpoint(documentId))
185
198
  return {
186
199
  organizationId: null,
@@ -211,30 +224,32 @@ class SqlDocumentDiscoveryEvidenceStore {
211
224
  accessStateHash: row.manifestHash,
212
225
  linkedContainerIds: readStringArray(JSON.parse(row.linksJson), "stored discovery links"),
213
226
  };
214
- };
215
- saveHead = (documentId, head, generation) => this.write(async (db) => {
216
- if (!head.accessStateHash ||
217
- !head.organizationId ||
218
- !(await isDocumentDiscoveryGenerationCurrent(db, generation)))
219
- return false;
220
- const row = {
221
- documentId,
222
- organizationId: head.organizationId,
223
- manifestHash: head.accessStateHash,
224
- accessEpoch: head.accessEpoch,
225
- linksJson: JSON.stringify(head.linkedContainerIds),
226
- };
227
- await db
228
- .insert(heads)
229
- .values(row)
230
- .onConflictDoUpdate({
231
- target: [heads.documentId, heads.organizationId],
232
- set: row,
233
- setWhere: lte(heads.accessEpoch, head.accessEpoch),
234
- })
235
- .run();
236
- return true;
237
- });
227
+ }
228
+ saveHead(documentId, head, generation) {
229
+ return this.write(async (db) => {
230
+ if (!head.accessStateHash ||
231
+ !head.organizationId ||
232
+ !(await isDocumentDiscoveryGenerationCurrent(db, generation)))
233
+ return false;
234
+ const row = {
235
+ documentId,
236
+ organizationId: head.organizationId,
237
+ manifestHash: head.accessStateHash,
238
+ accessEpoch: head.accessEpoch,
239
+ linksJson: JSON.stringify(head.linkedContainerIds),
240
+ };
241
+ await db
242
+ .insert(heads)
243
+ .values(row)
244
+ .onConflictDoUpdate({
245
+ target: [heads.documentId, heads.organizationId],
246
+ set: row,
247
+ setWhere: lte(heads.accessEpoch, head.accessEpoch),
248
+ })
249
+ .run();
250
+ return true;
251
+ });
252
+ }
238
253
  }
239
254
  /** Writes authored heads inside the caller's serialized write transaction. */
240
255
  export async function primeAuthoredDocumentDiscoveryHeads(execSql, authored) {
@@ -258,7 +273,4 @@ export async function primeAuthoredDocumentDiscoveryHeads(execSql, authored) {
258
273
  .run();
259
274
  }
260
275
  }
261
- export function createDocumentDiscoveryEvidenceStore(execSql, now = Date.now) {
262
- return new SqlDocumentDiscoveryEvidenceStore(execSql, now);
263
- }
264
276
  //# sourceMappingURL=documentDiscoveryEvidencePersistence.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"documentDiscoveryEvidencePersistence.js","sourceRoot":"","sources":["documentDiscoveryEvidencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,8CAA8C,CAAC;AACjG,OAAO,EACL,kBAAkB,EAClB,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,0BAA0B,EAAE,MAAM,iDAAiD,CAAC;AAC7F,OAAO,EAAE,yBAAyB,EAAE,MAAM,8CAA8C,CAAC;AACzF,OAAO,EAEL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,mBAAmB,EAAE,MAAM,4CAA4C,CAA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AC,SAAS,CAAC,mBAAmB,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;SACxE,CAAC;QACF,MAAM,EAAE;aACL,MAAM,CAAC,KAAK,CAAC;aACb,MAAM,CAAC,GAAG,CAAC;aACX,kBAAkB,CAAC;YAClB,MAAM,EAAE,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,cAAc,CAAC;YAChD,GAAG,EAAE,GAAG;YACR,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC;SACnD,CAAC;aACD,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,OAAgB,EAChB,GAAG,GAAG,IAAI,CAAC,GAAG;IAEd,OAAO,IAAI,iCAAiC,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { and, asc, eq, inArray, lte, min, or, sql } from \"drizzle-orm\";\nimport { uniqueSortedStrings } from \"../../documents/shared/readers\";\nimport { readStringArray } from \"../../shared/recordReaders\";\nimport {\n documentDiscoveryHeads,\n documentDiscoverySequence,\n pendingDocumentDiscoveries,\n} from \"../../sqlite/schema/documentDiscoveryEvidenceSchema\";\nimport { documentContainerProjectionTables } from \"../../sqlite/schema/documentProjectionSchema\";\nimport {\n remoteResetBatches,\n sqliteInsertBatchSize,\n} from \"../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../../sqlite/sqliteUpsert\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { KeyingCheckpointRepository } from \"../keyingCheckpoints/keyingCheckpointRepository\";\nimport { heldTombstoneRetryDelayMs } from \"./containerDocumentTombstoneHoldsPersistence\";\nimport {\n type DiscoveredDocumentCandidate,\n isDiscoveredDocumentCandidate,\n readStoredDiscoveryCandidate,\n} from \"./documentDiscoveryCandidate\";\nimport { isDocumentDiscoveryGenerationCurrent } from \"./documentDiscoveryReset\";\nimport { placementPairsMatch } from \"./internal/containerDocumentTombstoneHolds\";\n\nexport type { DiscoveredDocumentCandidate } from \"./documentDiscoveryCandidate\";\nexport { clearDocumentDiscoveryEvidenceOnRemoteReset } from \"./documentDiscoveryReset\";\nexport interface CachedDiscoveryHead {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n readonly accessStateHash?: string;\n readonly linkedContainerIds: readonly string[];\n}\ninterface RemovedDiscoveryPlacement {\n readonly containerId: string;\n readonly documentId: string;\n}\nexport interface DocumentDiscoveryEvidenceStore {\n begin(): Promise<number>;\n isCurrent(generation: number): Promise<boolean>;\n stage(\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n removed?: readonly RemovedDiscoveryPlacement[],\n ): Promise<boolean>;\n pending(\n containerIds: readonly string[],\n limit: number,\n ): Promise<readonly DiscoveredDocumentCandidate[]>;\n defer(input: DiscoveredDocumentCandidate, generation: number): Promise<void>;\n acknowledge(\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n ): Promise<void>;\n hasPending(containerIds: readonly string[]): Promise<boolean>;\n retryDelay(containerIds: readonly string[]): Promise<number | null>;\n loadHead(\n documentId: string,\n manifestHash: string | null | undefined,\n ): Promise<CachedDiscoveryHead | null>;\n saveHead(\n documentId: string,\n head: CachedDiscoveryHead,\n generation: number,\n ): Promise<boolean>;\n}\n\nconst pending = pendingDocumentDiscoveries;\nconst heads = documentDiscoveryHeads;\nconst ID_BATCH_SIZE = 400;\nconst batches = (ids: readonly string[]) =>\n Array.from({ length: Math.ceil(ids.length / ID_BATCH_SIZE) }, (_, i) =>\n ids.slice(i * ID_BATCH_SIZE, (i + 1) * ID_BATCH_SIZE),\n );\nconst chunked = <T>(rows: readonly T[], size: number): T[][] =>\n Array.from({ length: Math.ceil(rows.length / size) }, (_, i) =>\n rows.slice(i * size, (i + 1) * size),\n );\nconst identity = (input: DiscoveredDocumentCandidate) =>\n and(\n eq(pending.containerId, input.containerId),\n eq(pending.documentId, input.documentId),\n eq(pending.inputJson, JSON.stringify(input)),\n );\n\nclass SqlDocumentDiscoveryEvidenceStore\n implements DocumentDiscoveryEvidenceStore\n{\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => number,\n ) {}\n\n private read = async () => {\n await ensureSqlTables(this.execSql, documentContainerProjectionTables);\n return getClientSQLitePersistenceRuntime(this.execSql).db;\n };\n private write = async <T>(\n operation: (\n db: ReturnType<typeof getClientSQLitePersistenceRuntime>[\"db\"],\n ) => Promise<T>,\n ) =>\n runSerializedSqlMutation(this.execSql, async (locked) => {\n await ensureSqlTables(locked, documentContainerProjectionTables);\n return operation(getClientSQLitePersistenceRuntime(locked).db);\n });\n begin = async () => {\n let generation = 0;\n await this.write(async (db) => {\n const [row] = await db\n .insert(documentDiscoverySequence)\n .values({ id: \"requests\", generation: 1 })\n .onConflictDoUpdate({\n target: documentDiscoverySequence.id,\n set: {\n generation: sql`${documentDiscoverySequence.generation} + 1`,\n },\n })\n .returning({ generation: documentDiscoverySequence.generation });\n if (!row || !Number.isSafeInteger(row.generation))\n throw new Error(\"Document discovery generation is exhausted\");\n generation = row.generation;\n });\n return generation;\n };\n isCurrent = async (generation: number) =>\n isDocumentDiscoveryGenerationCurrent(await this.read(), generation);\n stage = (\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n removed: readonly RemovedDiscoveryPlacement[] = [],\n ) => {\n return this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation)))\n return false;\n if (inputs.length === 0 && removed.length === 0) return true;\n await db.transaction(async (tx) => {\n const rows = inputs.flatMap((input) =>\n isDiscoveredDocumentCandidate(input)\n ? input.listedContainerIds.map((containerId) => ({\n containerId,\n documentId: input.documentId,\n accessEpoch: input.accessEpoch,\n generation,\n inputJson: JSON.stringify({\n ...input,\n containerId,\n listedContainerIds: [containerId],\n }),\n retryAt: 0,\n }))\n : [],\n );\n // One multi-row upsert per chunk. SQLite applies a statement's rows\n // in order, so a repeated placement updates the row the previous\n // entry wrote, exactly as one statement per entry did.\n const unchanged = sql`${pending.inputJson} = excluded.input_json`;\n for (const chunk of chunked(rows, sqliteInsertBatchSize(pending))) {\n await tx\n .insert(pending)\n .values(chunk)\n .onConflictDoUpdate({\n target: [pending.containerId, pending.documentId],\n set: {\n accessEpoch: excludedValue(pending.accessEpoch),\n generation: excludedValue(pending.generation),\n inputJson: excludedValue(pending.inputJson),\n retryAt: sql`case when ${unchanged} then ${pending.retryAt} else 0 end`,\n attempts: sql`case when ${unchanged} then ${pending.attempts} else 0 end`,\n },\n setWhere: lte(pending.generation, generation),\n })\n .run();\n }\n // These are untrusted, unapplied hints only. Removing an existing local\n // placement still requires the separate signed tombstone evidence gate.\n for (const batch of remoteResetBatches(removed)) {\n await tx\n .delete(pending)\n .where(\n and(\n placementPairsMatch(\n batch,\n pending.documentId,\n pending.containerId,\n ),\n lte(pending.generation, generation),\n ),\n )\n .run();\n }\n });\n return true;\n });\n };\n pending = async (containerIds: readonly string[], limit: number) => {\n const db = await this.read();\n const result: DiscoveredDocumentCandidate[] = [];\n for (const batch of batches(containerIds)) {\n if (result.length >= limit) break;\n const rows = await db\n .select({ inputJson: pending.inputJson })\n .from(pending)\n .where(\n and(\n inArray(pending.containerId, [...batch]),\n lte(pending.retryAt, this.now()),\n ),\n )\n .orderBy(asc(pending.retryAt), asc(pending.documentId))\n .limit(limit - result.length);\n result.push(\n ...rows.map((row) => readStoredDiscoveryCandidate(row.inputJson)),\n );\n }\n return result;\n };\n defer = (input: DiscoveredDocumentCandidate, generation: number) =>\n this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation))) return;\n const [row] = await db\n .select({ attempts: pending.attempts })\n .from(pending)\n .where(identity(input))\n .limit(1);\n if (!row) return;\n const attempts = Math.min(row.attempts + 1, 8);\n await db\n .update(pending)\n .set({\n attempts,\n retryAt: this.now() + heldTombstoneRetryDelayMs(attempts),\n })\n .where(identity(input))\n .run();\n });\n acknowledge = (\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n ) =>\n this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation))) return;\n await db.transaction(async (tx) => {\n for (const batch of remoteResetBatches(inputs))\n await tx\n .delete(pending)\n .where(or(...batch.map(identity)))\n .run();\n });\n });\n hasPending = async (containerIds: readonly string[]) => {\n const db = await this.read();\n for (const batch of batches(containerIds)) {\n if (\n (\n await db\n .select({ documentId: pending.documentId })\n .from(pending)\n .where(inArray(pending.containerId, [...batch]))\n .limit(1)\n ).length\n )\n return true;\n }\n return false;\n };\n retryDelay = async (containerIds: readonly string[]) => {\n const db = await this.read();\n let due: number | null = null;\n for (const batch of batches(containerIds)) {\n const [row] = await db\n .select({ due: min(pending.retryAt) })\n .from(pending)\n .where(inArray(pending.containerId, [...batch]));\n if (row?.due !== null && row?.due !== undefined)\n due = Math.min(due ?? row.due, row.due);\n }\n return due === null ? null : Math.max(0, due - this.now());\n };\n loadHead = async (\n documentId: string,\n manifestHash: string | null | undefined,\n ) => {\n if (\n await new KeyingCheckpointRepository(\n this.execSql,\n ).loadDocumentPurgeCheckpoint(documentId)\n )\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n if (!manifestHash) return null;\n const db = await this.read();\n const [row] = await db\n .select()\n .from(heads)\n .where(\n and(\n eq(heads.documentId, documentId),\n eq(heads.manifestHash, manifestHash),\n ),\n )\n .limit(1);\n if (!row) return null;\n // A different verifier (for example tombstone removal) can advance the\n // signed checkpoint without updating documents.accessEpoch or this cache.\n // Old-organization pins survive recovery; only the cached signed head's\n // organization can authorize reuse. Missing pins require full verification.\n const checkpoint = await new KeyingCheckpointRepository(\n this.execSql,\n ).loadAccessManifestCheckpoint(\"document\", row.organizationId, documentId);\n if (\n checkpoint?.manifestHash !== row.manifestHash ||\n checkpoint.epoch !== row.accessEpoch\n )\n return null;\n return {\n organizationId: row.organizationId,\n accessEpoch: row.accessEpoch,\n accessStateHash: row.manifestHash,\n linkedContainerIds: readStringArray(\n JSON.parse(row.linksJson),\n \"stored discovery links\",\n ),\n };\n };\n saveHead = (\n documentId: string,\n head: CachedDiscoveryHead,\n generation: number,\n ) =>\n this.write(async (db) => {\n if (\n !head.accessStateHash ||\n !head.organizationId ||\n !(await isDocumentDiscoveryGenerationCurrent(db, generation))\n )\n return false;\n const row = {\n documentId,\n organizationId: head.organizationId,\n manifestHash: head.accessStateHash,\n accessEpoch: head.accessEpoch,\n linksJson: JSON.stringify(head.linkedContainerIds),\n };\n await db\n .insert(heads)\n .values(row)\n .onConflictDoUpdate({\n target: [heads.documentId, heads.organizationId],\n set: row,\n setWhere: lte(heads.accessEpoch, head.accessEpoch),\n })\n .run();\n return true;\n });\n}\n\n/**\n * A document head this client signed, already checked against the server's\n * create acknowledgement and pinned as its access-manifest checkpoint in the\n * same transaction. It is the same signed head a discovery projection would\n * verify, so it seeds the exact-head cache; `loadHead` still reuses it only\n * while that checkpoint matches.\n */\nexport interface AuthoredDiscoveryHead {\n readonly documentId: string;\n readonly organizationId: string;\n readonly accessEpoch: number;\n readonly accessStateHash: string;\n readonly linkedContainerIds: readonly string[];\n}\n\n/** Writes authored heads inside the caller's serialized write transaction. */\nexport async function primeAuthoredDocumentDiscoveryHeads(\n execSql: ExecSql,\n authored: readonly AuthoredDiscoveryHead[],\n): Promise<void> {\n const db = getClientSQLitePersistenceRuntime(execSql).db;\n for (const head of authored) {\n const row = {\n documentId: head.documentId,\n organizationId: head.organizationId,\n manifestHash: head.accessStateHash,\n accessEpoch: head.accessEpoch,\n linksJson: JSON.stringify(uniqueSortedStrings(head.linkedContainerIds)),\n };\n await db\n .insert(heads)\n .values(row)\n .onConflictDoUpdate({\n target: [heads.documentId, heads.organizationId],\n set: row,\n setWhere: lte(heads.accessEpoch, head.accessEpoch),\n })\n .run();\n }\n}\n\nexport function createDocumentDiscoveryEvidenceStore(\n execSql: ExecSql,\n now = Date.now,\n): DocumentDiscoveryEvidenceStore {\n return new SqlDocumentDiscoveryEvidenceStore(execSql, now);\n}\n"]}
1
+ {"version":3,"file":"documentDiscoveryEvidencePersistence.js","sourceRoot":"","sources":["documentDiscoveryEvidencePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,8CAA8C,CAAC;AACjG,OAAO,EACL,kBAAkB,EAClB,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,0BAA0B,EAAE,MAAM,iDAAiD,CAAC;AAC7F,OAAO,EAAE,yBAAyB,EAAE,MAAM,8CAA8C,CAAC;AACzF,OAAO,EAEL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,oCAAoC,EAAE,MAAM,0BAA0B,CAAC;AAChF,OAAO,EAAE,mBAAmB,EAAE,MAAM,4CAA4C,CAAC;AAGjF,OAAO,EAAE,2CAA2C,EAAE,MAAM,0BAA0B,CAAC;AAYvF,MAAM,OAAO,GAAG,0BAA0B,CAAC;AAC3C,MAAM,KAAK,GAAG,sBAAsB,CAAC;AACrC,MAAM,aAAa,GA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,UAAU,EAAE,KAAK,CAAC,cAAc,CAAC;YAChD,GAAG,EAAE,GAAG;YACR,QAAQ,EAAE,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC;SACnD,CAAC;aACD,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC","sourcesContent":["import { and, asc, eq, inArray, lte, min, or, sql } from \"drizzle-orm\";\nimport { uniqueSortedStrings } from \"../../documents/shared/readers\";\nimport { readStringArray } from \"../../shared/recordReaders\";\nimport {\n documentDiscoveryHeads,\n documentDiscoverySequence,\n pendingDocumentDiscoveries,\n} from \"../../sqlite/schema/documentDiscoveryEvidenceSchema\";\nimport { documentContainerProjectionTables } from \"../../sqlite/schema/documentProjectionSchema\";\nimport {\n remoteResetBatches,\n sqliteInsertBatchSize,\n} from \"../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../../sqlite/sqliteUpsert\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\nimport { KeyingCheckpointRepository } from \"../keyingCheckpoints/keyingCheckpointRepository\";\nimport { heldTombstoneRetryDelayMs } from \"./containerDocumentTombstoneHoldsPersistence\";\nimport {\n type DiscoveredDocumentCandidate,\n isDiscoveredDocumentCandidate,\n readStoredDiscoveryCandidate,\n} from \"./documentDiscoveryCandidate\";\nimport { isDocumentDiscoveryGenerationCurrent } from \"./documentDiscoveryReset\";\nimport { placementPairsMatch } from \"./internal/containerDocumentTombstoneHolds\";\n\nexport type { DiscoveredDocumentCandidate } from \"./documentDiscoveryCandidate\";\nexport { clearDocumentDiscoveryEvidenceOnRemoteReset } from \"./documentDiscoveryReset\";\nexport interface CachedDiscoveryHead {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n readonly accessStateHash?: string;\n readonly linkedContainerIds: readonly string[];\n}\ninterface RemovedDiscoveryPlacement {\n readonly containerId: string;\n readonly documentId: string;\n}\n\nconst pending = pendingDocumentDiscoveries;\nconst heads = documentDiscoveryHeads;\nconst ID_BATCH_SIZE = 400;\nconst batches = (ids: readonly string[]) =>\n Array.from({ length: Math.ceil(ids.length / ID_BATCH_SIZE) }, (_, i) =>\n ids.slice(i * ID_BATCH_SIZE, (i + 1) * ID_BATCH_SIZE),\n );\nconst chunked = <T>(rows: readonly T[], size: number): T[][] =>\n Array.from({ length: Math.ceil(rows.length / size) }, (_, i) =>\n rows.slice(i * size, (i + 1) * size),\n );\nconst identity = (input: DiscoveredDocumentCandidate) =>\n and(\n eq(pending.containerId, input.containerId),\n eq(pending.documentId, input.documentId),\n eq(pending.inputJson, JSON.stringify(input)),\n );\n\n/**\n * Untrusted document discovery evidence bound to one executor and clock. The\n * clock (epoch milliseconds, like the `retryAt` column) schedules and reports\n * pending-discovery retries.\n */\nexport class DocumentDiscoveryEvidenceRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => number = Date.now,\n ) {}\n\n private async read() {\n await ensureSqlTables(this.execSql, documentContainerProjectionTables);\n return getClientSQLitePersistenceRuntime(this.execSql).db;\n }\n private write<T>(\n operation: (\n db: ReturnType<typeof getClientSQLitePersistenceRuntime>[\"db\"],\n ) => Promise<T>,\n ): Promise<T> {\n return runSerializedSqlMutation(this.execSql, async (locked) => {\n await ensureSqlTables(locked, documentContainerProjectionTables);\n return operation(getClientSQLitePersistenceRuntime(locked).db);\n });\n }\n async begin(): Promise<number> {\n let generation = 0;\n await this.write(async (db) => {\n const [row] = await db\n .insert(documentDiscoverySequence)\n .values({ id: \"requests\", generation: 1 })\n .onConflictDoUpdate({\n target: documentDiscoverySequence.id,\n set: {\n generation: sql`${documentDiscoverySequence.generation} + 1`,\n },\n })\n .returning({ generation: documentDiscoverySequence.generation });\n if (!row || !Number.isSafeInteger(row.generation))\n throw new Error(\"Document discovery generation is exhausted\");\n generation = row.generation;\n });\n return generation;\n }\n async isCurrent(generation: number): Promise<boolean> {\n return isDocumentDiscoveryGenerationCurrent(await this.read(), generation);\n }\n stage(\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n removed: readonly RemovedDiscoveryPlacement[] = [],\n ): Promise<boolean> {\n return this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation)))\n return false;\n if (inputs.length === 0 && removed.length === 0) return true;\n await db.transaction(async (tx) => {\n const rows = inputs.flatMap((input) =>\n isDiscoveredDocumentCandidate(input)\n ? input.listedContainerIds.map((containerId) => ({\n containerId,\n documentId: input.documentId,\n accessEpoch: input.accessEpoch,\n generation,\n inputJson: JSON.stringify({\n ...input,\n containerId,\n listedContainerIds: [containerId],\n }),\n retryAt: 0,\n }))\n : [],\n );\n // One multi-row upsert per chunk. SQLite applies a statement's rows\n // in order, so a repeated placement updates the row the previous\n // entry wrote, exactly as one statement per entry did.\n const unchanged = sql`${pending.inputJson} = excluded.input_json`;\n for (const chunk of chunked(rows, sqliteInsertBatchSize(pending))) {\n await tx\n .insert(pending)\n .values(chunk)\n .onConflictDoUpdate({\n target: [pending.containerId, pending.documentId],\n set: {\n accessEpoch: excludedValue(pending.accessEpoch),\n generation: excludedValue(pending.generation),\n inputJson: excludedValue(pending.inputJson),\n retryAt: sql`case when ${unchanged} then ${pending.retryAt} else 0 end`,\n attempts: sql`case when ${unchanged} then ${pending.attempts} else 0 end`,\n },\n setWhere: lte(pending.generation, generation),\n })\n .run();\n }\n // These are untrusted, unapplied hints only. Removing an existing local\n // placement still requires the separate signed tombstone evidence gate.\n for (const batch of remoteResetBatches(removed)) {\n await tx\n .delete(pending)\n .where(\n and(\n placementPairsMatch(\n batch,\n pending.documentId,\n pending.containerId,\n ),\n lte(pending.generation, generation),\n ),\n )\n .run();\n }\n });\n return true;\n });\n }\n async pending(\n containerIds: readonly string[],\n limit: number,\n ): Promise<readonly DiscoveredDocumentCandidate[]> {\n const db = await this.read();\n const result: DiscoveredDocumentCandidate[] = [];\n for (const batch of batches(containerIds)) {\n if (result.length >= limit) break;\n const rows = await db\n .select({ inputJson: pending.inputJson })\n .from(pending)\n .where(\n and(\n inArray(pending.containerId, [...batch]),\n lte(pending.retryAt, this.now()),\n ),\n )\n .orderBy(asc(pending.retryAt), asc(pending.documentId))\n .limit(limit - result.length);\n result.push(\n ...rows.map((row) => readStoredDiscoveryCandidate(row.inputJson)),\n );\n }\n return result;\n }\n defer(input: DiscoveredDocumentCandidate, generation: number): Promise<void> {\n return this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation))) return;\n const [row] = await db\n .select({ attempts: pending.attempts })\n .from(pending)\n .where(identity(input))\n .limit(1);\n if (!row) return;\n const attempts = Math.min(row.attempts + 1, 8);\n await db\n .update(pending)\n .set({\n attempts,\n retryAt: this.now() + heldTombstoneRetryDelayMs(attempts),\n })\n .where(identity(input))\n .run();\n });\n }\n acknowledge(\n inputs: readonly DiscoveredDocumentCandidate[],\n generation: number,\n ): Promise<void> {\n return this.write(async (db) => {\n if (!(await isDocumentDiscoveryGenerationCurrent(db, generation))) return;\n await db.transaction(async (tx) => {\n for (const batch of remoteResetBatches(inputs))\n await tx\n .delete(pending)\n .where(or(...batch.map(identity)))\n .run();\n });\n });\n }\n async hasPending(containerIds: readonly string[]): Promise<boolean> {\n const db = await this.read();\n for (const batch of batches(containerIds)) {\n if (\n (\n await db\n .select({ documentId: pending.documentId })\n .from(pending)\n .where(inArray(pending.containerId, [...batch]))\n .limit(1)\n ).length\n )\n return true;\n }\n return false;\n }\n async retryDelay(containerIds: readonly string[]): Promise<number | null> {\n const db = await this.read();\n let due: number | null = null;\n for (const batch of batches(containerIds)) {\n const [row] = await db\n .select({ due: min(pending.retryAt) })\n .from(pending)\n .where(inArray(pending.containerId, [...batch]));\n if (row?.due !== null && row?.due !== undefined)\n due = Math.min(due ?? row.due, row.due);\n }\n return due === null ? null : Math.max(0, due - this.now());\n }\n async loadHead(\n documentId: string,\n manifestHash: string | null | undefined,\n ): Promise<CachedDiscoveryHead | null> {\n if (\n await new KeyingCheckpointRepository(\n this.execSql,\n ).loadDocumentPurgeCheckpoint(documentId)\n )\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n if (!manifestHash) return null;\n const db = await this.read();\n const [row] = await db\n .select()\n .from(heads)\n .where(\n and(\n eq(heads.documentId, documentId),\n eq(heads.manifestHash, manifestHash),\n ),\n )\n .limit(1);\n if (!row) return null;\n // A different verifier (for example tombstone removal) can advance the\n // signed checkpoint without updating documents.accessEpoch or this cache.\n // Old-organization pins survive recovery; only the cached signed head's\n // organization can authorize reuse. Missing pins require full verification.\n const checkpoint = await new KeyingCheckpointRepository(\n this.execSql,\n ).loadAccessManifestCheckpoint(\"document\", row.organizationId, documentId);\n if (\n checkpoint?.manifestHash !== row.manifestHash ||\n checkpoint.epoch !== row.accessEpoch\n )\n return null;\n return {\n organizationId: row.organizationId,\n accessEpoch: row.accessEpoch,\n accessStateHash: row.manifestHash,\n linkedContainerIds: readStringArray(\n JSON.parse(row.linksJson),\n \"stored discovery links\",\n ),\n };\n }\n saveHead(\n documentId: string,\n head: CachedDiscoveryHead,\n generation: number,\n ): Promise<boolean> {\n return this.write(async (db) => {\n if (\n !head.accessStateHash ||\n !head.organizationId ||\n !(await isDocumentDiscoveryGenerationCurrent(db, generation))\n )\n return false;\n const row = {\n documentId,\n organizationId: head.organizationId,\n manifestHash: head.accessStateHash,\n accessEpoch: head.accessEpoch,\n linksJson: JSON.stringify(head.linkedContainerIds),\n };\n await db\n .insert(heads)\n .values(row)\n .onConflictDoUpdate({\n target: [heads.documentId, heads.organizationId],\n set: row,\n setWhere: lte(heads.accessEpoch, head.accessEpoch),\n })\n .run();\n return true;\n });\n }\n}\n\n/**\n * A document head this client signed, already checked against the server's\n * create acknowledgement and pinned as its access-manifest checkpoint in the\n * same transaction. It is the same signed head a discovery projection would\n * verify, so it seeds the exact-head cache; `loadHead` still reuses it only\n * while that checkpoint matches.\n */\nexport interface AuthoredDiscoveryHead {\n readonly documentId: string;\n readonly organizationId: string;\n readonly accessEpoch: number;\n readonly accessStateHash: string;\n readonly linkedContainerIds: readonly string[];\n}\n\n/** Writes authored heads inside the caller's serialized write transaction. */\nexport async function primeAuthoredDocumentDiscoveryHeads(\n execSql: ExecSql,\n authored: readonly AuthoredDiscoveryHead[],\n): Promise<void> {\n const db = getClientSQLitePersistenceRuntime(execSql).db;\n for (const head of authored) {\n const row = {\n documentId: head.documentId,\n organizationId: head.organizationId,\n manifestHash: head.accessStateHash,\n accessEpoch: head.accessEpoch,\n linksJson: JSON.stringify(uniqueSortedStrings(head.linkedContainerIds)),\n };\n await db\n .insert(heads)\n .values(row)\n .onConflictDoUpdate({\n target: [heads.documentId, heads.organizationId],\n set: row,\n setWhere: lte(heads.accessEpoch, head.accessEpoch),\n })\n .run();\n }\n}\n"]}