@tearleads/client-sdk 0.1.247 → 0.1.249

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 (151) hide show
  1. package/Tearleads.js +4 -2
  2. package/Tearleads.js.map +1 -1
  3. package/client/organizations/index.js +5 -3
  4. package/client/organizations/index.js.map +1 -1
  5. package/client/organizations/organizationGroupPresentation.d.ts +1 -1
  6. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  7. package/client/organizations/organizationLeaveRequestVerifier.js +21 -0
  8. package/client/organizations/organizationLeaveRequestVerifier.js.map +1 -0
  9. package/client/organizations/{organizationReadModels.d.ts → organizationReadModelCoordinator.d.ts} +18 -16
  10. package/client/organizations/organizationReadModelCoordinator.js +2 -0
  11. package/client/organizations/organizationReadModelCoordinator.js.map +1 -0
  12. package/client/organizations/organizationReadModelPresentation.js +51 -0
  13. package/client/organizations/organizationReadModelPresentation.js.map +1 -0
  14. package/client/organizations/organizationReadModelScopes.js +37 -0
  15. package/client/organizations/organizationReadModelScopes.js.map +1 -0
  16. package/client/organizations/organizationReadModels.js +131 -88
  17. package/client/organizations/organizationReadModels.js.map +1 -1
  18. package/client/organizations/organizationsTypes.d.ts +13 -5
  19. package/client/organizations/organizationsTypes.js.map +1 -1
  20. package/client/organizations/principalMutations.d.ts +18 -2
  21. package/client/organizations/principalMutations.js +29 -15
  22. package/client/organizations/principalMutations.js.map +1 -1
  23. package/client/runtime/principalMutationApi.d.ts +2 -0
  24. package/client/runtime/principalMutationApi.js +2 -0
  25. package/client/runtime/principalMutationApi.js.map +1 -1
  26. package/client/runtime/principalMutationDispatch.js +47 -10
  27. package/client/runtime/principalMutationDispatch.js.map +1 -1
  28. package/client/runtime/workflowRuntime.js +5 -4
  29. package/client/runtime/workflowRuntime.js.map +1 -1
  30. package/data/containers/shared/mutationRequestOptions.d.ts +2 -0
  31. package/data/containers/shared/mutationRequestOptions.js.map +1 -1
  32. package/data/containers/shared/types.d.ts +12 -2
  33. package/data/containers/shared/types.js.map +1 -1
  34. package/data/persistence/organizations/organizationReadModelRepository.js +20 -2
  35. package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -1
  36. package/data/persistence/principalPolicy/heldOrganizationDirectories.js +53 -0
  37. package/data/persistence/principalPolicy/heldOrganizationDirectories.js.map +1 -0
  38. package/data/persistence/verifiedManifestBundlePersistence.d.ts +8 -3
  39. package/data/persistence/verifiedManifestBundlePersistence.js +34 -15
  40. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  41. package/internal/api-client/ApiClient.d.ts +4 -1
  42. package/internal/api-client/client/containerMutations.d.ts +2 -2
  43. package/internal/api-client/client/containerMutations.js +2 -1
  44. package/internal/api-client/client/containerMutations.js.map +1 -1
  45. package/internal/api-client/client/principalPolicies.d.ts +3 -0
  46. package/internal/api-client/heldDirectoryCitations.d.ts +19 -0
  47. package/internal/api-client/heldDirectoryCitations.js +37 -0
  48. package/internal/api-client/heldDirectoryCitations.js.map +1 -0
  49. package/internal/api-client/index.d.ts +1 -1
  50. package/internal/api-client/index.js.map +1 -1
  51. package/internal/api-client/principalPolicyRequests.d.ts +2 -0
  52. package/internal/api-client/principalPolicyRequests.js +6 -4
  53. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  54. package/internal/api-client/routes/containers/mutations.js +3 -3
  55. package/internal/api-client/routes/containers/mutations.js.map +1 -1
  56. package/internal/api-client/routes/organizations/createGroup.js +3 -5
  57. package/internal/api-client/routes/organizations/createGroup.js.map +1 -1
  58. package/internal/api-client/routes/principals/policy.js +2 -5
  59. package/internal/api-client/routes/principals/policy.js.map +1 -1
  60. package/internal/api-client/types.d.ts +6 -0
  61. package/internal/api-client/types.js.map +1 -1
  62. package/internal/api-client/verifiedManifestCitations.d.ts +16 -6
  63. package/internal/api-client/verifiedManifestCitations.js +32 -13
  64. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  65. package/internal/api-client/writerProjectionRequests.js +5 -3
  66. package/internal/api-client/writerProjectionRequests.js.map +1 -1
  67. package/internal/validators/knownManifestsRefinements.js +1 -1
  68. package/internal/validators/knownManifestsRefinements.js.map +1 -1
  69. package/internal/validators/operation/containerMutations.d.ts +20 -3
  70. package/internal/validators/operation/containerMutations.js +18 -20
  71. package/internal/validators/operation/containerMutations.js.map +1 -1
  72. package/internal/validators/operation/index.d.ts +1 -1
  73. package/internal/validators/operation/index.js +1 -1
  74. package/internal/validators/operation/index.js.map +1 -1
  75. package/internal/validators/operation/organizations.d.ts +17 -1
  76. package/internal/validators/operation/organizations.js +4 -2
  77. package/internal/validators/operation/organizations.js.map +1 -1
  78. package/internal/validators/operation/principals.d.ts +17 -1
  79. package/internal/validators/operation/principals.js +5 -2
  80. package/internal/validators/operation/principals.js.map +1 -1
  81. package/internal/validators/operation/writerProjections.d.ts +11 -11
  82. package/internal/validators/operation/writerProjections.js +1 -1
  83. package/internal/validators/operation/writerProjections.js.map +1 -1
  84. package/internal/validators/request/index.d.ts +1 -1
  85. package/internal/validators/request/index.js +1 -1
  86. package/internal/validators/request/index.js.map +1 -1
  87. package/internal/validators/request/organization.d.ts +15 -0
  88. package/internal/validators/request/organization.js +8 -0
  89. package/internal/validators/request/organization.js.map +1 -1
  90. package/internal/validators/response/areas/organizations.d.ts +3 -2
  91. package/internal/validators/response/areas/organizations.js +3 -2
  92. package/internal/validators/response/areas/organizations.js.map +1 -1
  93. package/internal/validators/response/areas/principals.d.ts +3 -2
  94. package/internal/validators/response/areas/principals.js +2 -2
  95. package/internal/validators/response/areas/principals.js.map +1 -1
  96. package/internal/validators/response/committedReadModel.d.ts +697 -0
  97. package/internal/validators/response/committedReadModel.js +52 -0
  98. package/internal/validators/response/committedReadModel.js.map +1 -0
  99. package/internal/validators/response/container.d.ts +56 -4
  100. package/internal/validators/response/container.js +5 -5
  101. package/internal/validators/response/container.js.map +1 -1
  102. package/internal/validators/response/documentMutation.d.ts +4 -4
  103. package/internal/validators/response/documentMutation.js +2 -2
  104. package/internal/validators/response/documentMutation.js.map +1 -1
  105. package/internal/validators/response/organization.d.ts +0 -191
  106. package/internal/validators/response/organization.js +0 -7
  107. package/internal/validators/response/organization.js.map +1 -1
  108. package/internal/validators/response/organizationReadModel.d.ts +167 -0
  109. package/internal/validators/response/organizationReadModel.js +5 -0
  110. package/internal/validators/response/organizationReadModel.js.map +1 -1
  111. package/internal/validators/response/policyEvidenceWire.d.ts +17 -0
  112. package/internal/validators/response/policyEvidenceWire.js +36 -0
  113. package/internal/validators/response/policyEvidenceWire.js.map +1 -0
  114. package/internal/validators/response/principal.d.ts +0 -403
  115. package/internal/validators/response/principal.js +0 -8
  116. package/internal/validators/response/principal.js.map +1 -1
  117. package/internal/validators/response/projectionPolicyEvidence.d.ts +175 -0
  118. package/internal/validators/response/projectionPolicyEvidence.js +13 -0
  119. package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
  120. package/internal/validators/response/writerProjectionWire.d.ts +11 -7
  121. package/internal/validators/response/writerProjectionWire.js +19 -10
  122. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  123. package/internal/validators/util/index.d.ts +1 -1
  124. package/internal/validators/util/index.js +1 -1
  125. package/internal/validators/util/index.js.map +1 -1
  126. package/internal/validators/util/knownManifestWire.d.ts +9 -3
  127. package/internal/validators/util/knownManifestWire.js +24 -8
  128. package/internal/validators/util/knownManifestWire.js.map +1 -1
  129. package/package.json +1 -1
  130. package/workflows/container-contents/container-state/organizationHost.d.ts +9 -0
  131. package/workflows/container-contents/container-state/organizationHost.js.map +1 -1
  132. package/workflows/container-contents/container-state/remote.js +6 -0
  133. package/workflows/container-contents/container-state/remote.js.map +1 -1
  134. package/workflows/containers/child/share/index.d.ts +4 -2
  135. package/workflows/containers/child/share/index.js +37 -20
  136. package/workflows/containers/child/share/index.js.map +1 -1
  137. package/workflows/organizations/containerContentsHost.js +20 -1
  138. package/workflows/organizations/containerContentsHost.js.map +1 -1
  139. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +5 -1
  140. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
  141. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +8 -1
  142. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  143. package/workflows/organizations/index.d.ts +1 -0
  144. package/workflows/organizations/index.js +1 -0
  145. package/workflows/organizations/index.js.map +1 -1
  146. package/workflows/organizations/readModel/committedReadModel.d.ts +66 -0
  147. package/workflows/organizations/readModel/committedReadModel.js +150 -0
  148. package/workflows/organizations/readModel/committedReadModel.js.map +1 -0
  149. package/workflows/organizations/readModel/readModelProjection.d.ts +15 -2
  150. package/workflows/organizations/readModel/readModelProjection.js +26 -4
  151. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
@@ -1,6 +1,6 @@
1
1
  import type { AccessEvent, AccessManifest, ContainerAccessManifestState, ContainerCreateAccessEventBody, ContainerDirectGrant, ContainerGrantAccessEventBody, ContainerGrantPrincipalHead, ContainerKekKeyring, ContainerKekRecipientTarget, ContainerKeyEpoch, ContainerKeyWrap, ContainerMoveAccessEventBody, ContainerRekeyAccessEventBody, ContainerRevokeAccessEventBody, ContainerUserRecipientKey } from "../../../internal/crypto/index.js";
2
2
  import type { AccessManifestBundleWire, ContainerCreateWithMetadataDocumentRequest, ContainerMutationRequest, ContainerRotationRequest } from "../../../internal/validators/request/index.js";
3
- import type { ContainerCreateWithMetadataDocumentResponse, ContainerKekResponse, ContainerMutationResponse, ContainerRotationResponse, ContainerWriterProjectionResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
3
+ import type { ContainerCreateWithMetadataDocumentResponse, ContainerKekResponse, ContainerMutationResponse, ContainerRotationResponse, ContainerShareResponse, ContainerWriterProjectionResponse, OrganizationReadModelDeltaResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
4
4
  import type { PrincipalPolicyCurrentEvidence } from "../../principalContracts/principalPolicyEvidence.js";
5
5
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
6
6
  import type { ContainerMutationRequestOptions } from "./mutationRequestOptions.js";
@@ -92,9 +92,19 @@ export interface ContainerShareApi extends ContainerReciteApi {
92
92
  getContainerWriterProjection(containerId: string): Promise<ContainerWriterProjectionResponse | null>;
93
93
  shareContainer(containerId: string, input: ContainerMutationRequest, options?: ContainerMutationRequestOptions): Promise<ContainerMutationResponse | null>;
94
94
  /** Tells a stale path, which a fresh projection clears, from a refusal. */
95
- shareContainerResult?(containerId: string, input: ContainerMutationRequest, options?: ContainerMutationRequestOptions): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;
95
+ shareContainerResult?(containerId: string, input: ContainerMutationRequest, options?: ContainerMutationRequestOptions): Promise<ContainerMutationSubmitResult<ContainerShareResponse>>;
96
96
  evictContainerWriterProjection?(containerId: string): void;
97
97
  }
98
+ /**
99
+ * Sends the organization read-model cursor a share holds, so its response can
100
+ * carry the delta from it; the share settles the lease once it ends.
101
+ */
102
+ export interface ContainerShareCommittedReadModel {
103
+ begin(): Promise<{
104
+ readonly heldCursor: string | undefined;
105
+ settle(delta: OrganizationReadModelDeltaResponse | undefined): void;
106
+ }>;
107
+ }
98
108
  /**
99
109
  * A status-bearing rotation outcome. A refusal that names
100
110
  * `requiredContainerIds` is answerable: sign those descendant rekeys and
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerCreateAccessEventBody,\n ContainerDirectGrant,\n ContainerGrantAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKekKeyring,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerMoveAccessEventBody,\n ContainerRekeyAccessEventBody,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerCreateWithMetadataDocumentRequest,\n ContainerMutationRequest,\n ContainerRotationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerKekResponse,\n ContainerMutationResponse,\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { ContainerMutationRequestOptions } from \"./mutationRequestOptions\";\nimport type { ContainerReciteApi } from \"./reciteApi\";\n\nexport interface ContainerMutationAuthor {\n organizationId: string;\n signerDeviceId: string;\n signerKeyFingerprint: string;\n signerPrivateKey: Uint8Array;\n signerUserId: string;\n}\n\nexport interface BuildContainerCreatePlanInput {\n author: ContainerMutationAuthor;\n containerId?: string | undefined;\n containerKey: Uint8Array;\n containerKeyEpochId?: string | undefined;\n eventId?: string | undefined;\n /**\n * Optional group grant to bake into the\n * create manifest, wrapping the new container key to that principal in\n * addition to the normal parent-inheritance wrap. Used to birth a child\n * container that is directly readable by a group — e.g. the org public\n * metadata container granted to the reserved Members group. The principal's\n * verified policy must also be supplied via `principalPolicies` so the server\n * can derive the recipient target.\n */\n managedPrincipalGrant?:\n | {\n accessLevel: ContainerDirectGrant[\"accessLevel\"];\n principalEncapsulationPublicKey: string;\n principalHead: ContainerGrantPrincipalHead;\n }\n | undefined;\n metadataDocumentId?: string | undefined;\n systemSlot?: string | null | undefined;\n parentProjection: ContainerWriterProjectionResponse;\n principalPolicies?: readonly PrincipalPolicyCurrentEvidence[] | undefined;\n signedAt?: string | undefined;\n}\n\nexport interface ContainerCreatePlan {\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyEpochHash: string;\n keyTargetHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n metadataDocumentId: string;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargets: ContainerKekRecipientTarget[];\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerCreatePlan {\n containerKey: Uint8Array;\n plan: ContainerCreatePlan;\n}\n\nexport interface ContainerCreatePlanContext\n extends BuildContainerCreatePlanInput {\n containerKeyPublicKey: string;\n containerId: string;\n containerKeyEpochId: string;\n eventId: string;\n metadataDocumentId: string;\n parent: ParentContainerCreateContext;\n signedAt: string;\n}\n\nexport interface ContainerMutationSubmitFailure {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report: () => void;\n readonly stalePrincipalHeads?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n readonly status: number | null;\n}\n\nexport type ContainerMutationSubmitResult<T> =\n | {\n readonly data: T;\n readonly ok: true;\n }\n | ContainerMutationSubmitFailure;\n\nexport interface ContainerCreateApi {\n createContainerResult(\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n createContainerWithMetadataDocumentResult(\n input: ContainerCreateWithMetadataDocumentRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<\n ContainerMutationSubmitResult<ContainerCreateWithMetadataDocumentResponse>\n >;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport interface ContainerShareApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n shareContainer(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationResponse | null>;\n /** Tells a stale path, which a fresh projection clears, from a refusal. */\n shareContainerResult?(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n evictContainerWriterProjection?(containerId: string): void;\n}\n\n/**\n * A status-bearing rotation outcome. A refusal that names\n * `requiredContainerIds` is answerable: sign those descendant rekeys and\n * resubmit with them carried.\n */\nexport type ContainerRotationResult =\n | { readonly ok: true; readonly data: ContainerRotationResponse }\n | {\n readonly ok: false;\n readonly code?: string | undefined;\n /** Surface a failure that was submitted with `reportErrors: false`. */\n readonly report?: (() => void) | undefined;\n readonly requiredContainerIds?: readonly string[] | undefined;\n readonly status: number | null;\n };\n\nexport interface ContainerMoveApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n moveContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n moveContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerRevokeApi extends ContainerReciteApi {\n evictContainerWriterProjection?(containerId: string): void;\n evictWriterProjectionsCiting?(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n revokeContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n revokeContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface CreateRemoteContainerResult {\n containerKey: Uint8Array;\n containerId: string;\n metadataDocumentId: string;\n plan: ContainerCreatePlan;\n response: ContainerMutationResponse;\n}\n\nexport interface ContainerSharePlan {\n body: ContainerGrantAccessEventBody;\n /** The unchanged epoch's stored keyring, echoed back by the server. */\n previousKeyring?: Record<string, unknown> | null | undefined;\n containerId: string;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n recipientTarget: ContainerKekRecipientTarget;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerSharePlan {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n}\n\nexport interface ContainerRevokePlan {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRevokePlan {\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n}\n\nexport interface ContainerRekeyPlan {\n body: ContainerRekeyAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRekeyPlan {\n containerKey: Uint8Array;\n plan: ContainerRekeyPlan;\n writerProjection: ContainerWriterProjectionResponse;\n}\n\nexport interface ContainerRekeyApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n rekeyContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; see DocumentSyncApi. */\n rekeyContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerMovePlan {\n body: ContainerMoveAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerMovePlan {\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n}\n\nexport interface BuildMaterializedContainerMovePlanInput {\n author: ContainerMutationAuthor;\n containerKeyEpochId?: string | undefined;\n destinationParentProjection: ContainerWriterProjectionResponse;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\nexport interface ParentContainerCreateContext {\n manifest: ContainerWriterProjectionResponse[\"path\"][number];\n kek: ContainerKekResponse;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerCreateAccessEventBody,\n ContainerDirectGrant,\n ContainerGrantAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKekKeyring,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerMoveAccessEventBody,\n ContainerRekeyAccessEventBody,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerCreateWithMetadataDocumentRequest,\n ContainerMutationRequest,\n ContainerRotationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerKekResponse,\n ContainerMutationResponse,\n ContainerRotationResponse,\n ContainerShareResponse,\n ContainerWriterProjectionResponse,\n OrganizationReadModelDeltaResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { ContainerMutationRequestOptions } from \"./mutationRequestOptions\";\nimport type { ContainerReciteApi } from \"./reciteApi\";\n\nexport interface ContainerMutationAuthor {\n organizationId: string;\n signerDeviceId: string;\n signerKeyFingerprint: string;\n signerPrivateKey: Uint8Array;\n signerUserId: string;\n}\n\nexport interface BuildContainerCreatePlanInput {\n author: ContainerMutationAuthor;\n containerId?: string | undefined;\n containerKey: Uint8Array;\n containerKeyEpochId?: string | undefined;\n eventId?: string | undefined;\n /**\n * Optional group grant to bake into the\n * create manifest, wrapping the new container key to that principal in\n * addition to the normal parent-inheritance wrap. Used to birth a child\n * container that is directly readable by a group — e.g. the org public\n * metadata container granted to the reserved Members group. The principal's\n * verified policy must also be supplied via `principalPolicies` so the server\n * can derive the recipient target.\n */\n managedPrincipalGrant?:\n | {\n accessLevel: ContainerDirectGrant[\"accessLevel\"];\n principalEncapsulationPublicKey: string;\n principalHead: ContainerGrantPrincipalHead;\n }\n | undefined;\n metadataDocumentId?: string | undefined;\n systemSlot?: string | null | undefined;\n parentProjection: ContainerWriterProjectionResponse;\n principalPolicies?: readonly PrincipalPolicyCurrentEvidence[] | undefined;\n signedAt?: string | undefined;\n}\n\nexport interface ContainerCreatePlan {\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyEpochHash: string;\n keyTargetHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n metadataDocumentId: string;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargets: ContainerKekRecipientTarget[];\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerCreatePlan {\n containerKey: Uint8Array;\n plan: ContainerCreatePlan;\n}\n\nexport interface ContainerCreatePlanContext\n extends BuildContainerCreatePlanInput {\n containerKeyPublicKey: string;\n containerId: string;\n containerKeyEpochId: string;\n eventId: string;\n metadataDocumentId: string;\n parent: ParentContainerCreateContext;\n signedAt: string;\n}\n\nexport interface ContainerMutationSubmitFailure {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report: () => void;\n readonly stalePrincipalHeads?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n readonly status: number | null;\n}\n\nexport type ContainerMutationSubmitResult<T> =\n | {\n readonly data: T;\n readonly ok: true;\n }\n | ContainerMutationSubmitFailure;\n\nexport interface ContainerCreateApi {\n createContainerResult(\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n createContainerWithMetadataDocumentResult(\n input: ContainerCreateWithMetadataDocumentRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<\n ContainerMutationSubmitResult<ContainerCreateWithMetadataDocumentResponse>\n >;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport interface ContainerShareApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n shareContainer(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationResponse | null>;\n /** Tells a stale path, which a fresh projection clears, from a refusal. */\n shareContainerResult?(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerShareResponse>>;\n evictContainerWriterProjection?(containerId: string): void;\n}\n\n/**\n * Sends the organization read-model cursor a share holds, so its response can\n * carry the delta from it; the share settles the lease once it ends.\n */\nexport interface ContainerShareCommittedReadModel {\n begin(): Promise<{\n readonly heldCursor: string | undefined;\n settle(delta: OrganizationReadModelDeltaResponse | undefined): void;\n }>;\n}\n\n/**\n * A status-bearing rotation outcome. A refusal that names\n * `requiredContainerIds` is answerable: sign those descendant rekeys and\n * resubmit with them carried.\n */\nexport type ContainerRotationResult =\n | { readonly ok: true; readonly data: ContainerRotationResponse }\n | {\n readonly ok: false;\n readonly code?: string | undefined;\n /** Surface a failure that was submitted with `reportErrors: false`. */\n readonly report?: (() => void) | undefined;\n readonly requiredContainerIds?: readonly string[] | undefined;\n readonly status: number | null;\n };\n\nexport interface ContainerMoveApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n moveContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n moveContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerRevokeApi extends ContainerReciteApi {\n evictContainerWriterProjection?(containerId: string): void;\n evictWriterProjectionsCiting?(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n revokeContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n revokeContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface CreateRemoteContainerResult {\n containerKey: Uint8Array;\n containerId: string;\n metadataDocumentId: string;\n plan: ContainerCreatePlan;\n response: ContainerMutationResponse;\n}\n\nexport interface ContainerSharePlan {\n body: ContainerGrantAccessEventBody;\n /** The unchanged epoch's stored keyring, echoed back by the server. */\n previousKeyring?: Record<string, unknown> | null | undefined;\n containerId: string;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n recipientTarget: ContainerKekRecipientTarget;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerSharePlan {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n}\n\nexport interface ContainerRevokePlan {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRevokePlan {\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n}\n\nexport interface ContainerRekeyPlan {\n body: ContainerRekeyAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRekeyPlan {\n containerKey: Uint8Array;\n plan: ContainerRekeyPlan;\n writerProjection: ContainerWriterProjectionResponse;\n}\n\nexport interface ContainerRekeyApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n rekeyContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; see DocumentSyncApi. */\n rekeyContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerMovePlan {\n body: ContainerMoveAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerMovePlan {\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n}\n\nexport interface BuildMaterializedContainerMovePlanInput {\n author: ContainerMutationAuthor;\n containerKeyEpochId?: string | undefined;\n destinationParentProjection: ContainerWriterProjectionResponse;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\nexport interface ParentContainerCreateContext {\n manifest: ContainerWriterProjectionResponse[\"path\"][number];\n kek: ContainerKekResponse;\n}\n"]}
@@ -90,12 +90,17 @@ export class OrganizationReadModelRepository {
90
90
  });
91
91
  // The requester prune also retires pruned users' usage projections.
92
92
  await ensureSqlTables(this.execSql, organizationAccessProjectionTables);
93
- const disposition = await getClientSQLitePersistenceRuntime(this.execSql).transaction((tx) => applyOrganizationReadModelResponseInTransaction(tx, {
93
+ const runtime = getClientSQLitePersistenceRuntime(this.execSql);
94
+ const apply = (tx) => applyOrganizationReadModelResponseInTransaction(tx, {
94
95
  currentUserId: input.currentUserId,
95
96
  now: this.now,
96
97
  requestedCursor: input.requestedCursor,
97
98
  response: input.response,
98
- }));
99
+ });
100
+ const disposition = input.canCommit
101
+ ? ((await runtime.guardedTransaction(apply, input.canCommit)).result ??
102
+ "stale")
103
+ : await runtime.transaction(apply);
99
104
  // An applied change follows an organization hint or mutation; in-flight
100
105
  // operations recover the directory again instead of reusing their memo.
101
106
  if (disposition === "applied")
@@ -147,6 +152,19 @@ export class OrganizationReadModelRepository {
147
152
  // the organization's directory again instead of reusing their memo.
148
153
  getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(input.organizationId);
149
154
  }
155
+ /**
156
+ * The organization's stored projection cursor, shared by every requester on
157
+ * this device: the cursor a reconcile requests from. Null without one.
158
+ */
159
+ async loadOrganizationReadModelCursor(organizationId) {
160
+ await ensureSqlTables(this.execSql, organizationReadModelTables);
161
+ const [row] = await getClientSQLitePersistenceRuntime(this.execSql)
162
+ .db.select({ cursor: organizationReadModelState.cursor })
163
+ .from(organizationReadModelState)
164
+ .where(eq(organizationReadModelState.organizationId, organizationId))
165
+ .limit(1);
166
+ return row?.cursor ?? null;
167
+ }
150
168
  /**
151
169
  * The cursor this requester has applied, or null when it holds none. The
152
170
  * organization row's cursor is shared: another identity on this device may
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModelRepository.js","sourceRoot":"","sources":["organizationReadModelRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,qCAAqC,EAAE,MAAM,6CAA6C,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,iDAAiD,CAAC;AAC9F,OAAO,EACL,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,iDAAiD,EAAE,MAAM,oCAAoC,CAAC;AAKvG,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EACL,2DAA2D,GAE5D,MAAM,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KAAK,MAAM,UAAU,IAAI,IAAI,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;gBAC9C,MAAM,EAAE;qBACL,MAAM,CAAC,+BAA+B,CAAC;qBACvC,MAAM,CAAC;oBACN,cAAc,EAAE,KAAK,CAAC,cAAc;oBACpC,eAAe,EAAE,KAAK,CAAC,eAAe;oBACtC,UAAU;oBACV,QAAQ;iBACT,CAAC;qBACD,kBAAkB,CAAC;oBAClB,MAAM,EAAE;wBACN,+BAA+B,CAAC,cAAc;wBAC9C,+BAA+B,CAAC,eAAe;wBAC/C,+BAA+B,CAAC,UAAU;qBAC3C;oBACD,GAAG,EAAE,EAAE,QAAQ,EAAE;iBAClB,CAAC;qBACD,GAAG,EAAE,CAAC;YACX,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,iCAAiC,CACrC,KAA0C,EAC1C,UAAoD;QAEpD,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;QACjE,MAAM,IAAI,GAAG,MAAM,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC;aAC/D,EAAE,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,+BAA+B,CAAC,UAAU,EAAE,CAAC;aACrE,IAAI,CAAC,+BAA+B,CAAC;aACrC,KAAK,CACJ,GAAG,CACD,EAAE,CACA,+BAA+B,CAAC,cAAc,EAC9C,KAAK,CAAC,cAAc,CACrB,EACD,EAAE,CACA,+BAA+B,CAAC,eAAe,EAC/C,KAAK,CAAC,eAAe,CACtB,EACD,EAAE,CAAC,+BAA+B,CAAC,UAAU,EAAE,UAAU,CAAC,CAC3D,CACF;aACA,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;IACzB,CAAC;CACF","sourcesContent":["import type { OrganizationReadModelResponse } from \"@tearleads/validators/response\";\nimport { and, eq } from \"drizzle-orm\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../principals/principalPolicyCoordinator\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport { organizationDataUsageTables } from \"../../sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { purgeOrganizationDataUsageProjectionInTransaction } from \"./organizationDataUsagePersistence\";\nimport type {\n OrganizationPresentationDenialProjection,\n OrganizationPresentationDenialScope,\n} from \"./organizationPresentationDenialPersistence\";\nimport { notifyOrganizationReadModelInvalidated } from \"./organizationReadModelInvalidation\";\nimport {\n loadRequesterOrganizationReadModelGroupMembersInTransaction,\n type OrganizationReadModelGroupMembers,\n} from \"./organizationReadModelMemberLoad\";\nimport {\n type ApplyOrganizationReadModelResponseResult,\n applyOrganizationReadModelResponseInTransaction,\n} from \"./organizationReadModelPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport { OrganizationReadModelIntegrityError } from \"./organizationReadModelProtocol\";\nimport { purgeOrganizationReadModelProjectionInTransaction } from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nconst organizationAccessProjectionTables = [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n];\n\n/**\n * The durable organization read-model projection, its group display names,\n * and its presentation denial markers, over one database. Invalidation\n * notices and recovery invalidation are keyed by the executor this\n * repository was built from.\n */\nexport class OrganizationReadModelRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n /**\n * The ONE load shell for the durable read-model projection: run `load` in a\n * transaction and, if a stored row fails integrity validation, purge the\n * organization's projection and report null. The projection is a\n * server-refetchable cache, so the next reconcile requests a cursorless\n * snapshot instead of every read and repair pass failing on the same row.\n */\n private async loadWithOrganizationReadModelIntegrityPurge<T>(input: {\n readonly load: (tx: ClientSQLiteTransactionScope) => Promise<T | null>;\n readonly organizationId: string;\n }): Promise<T | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n let purgedInvalidRows = false;\n const result = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(async (tx) => {\n try {\n return await input.load(tx);\n } catch (error) {\n if (!(error instanceof OrganizationReadModelIntegrityError)) {\n throw error;\n }\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n purgedInvalidRows = true;\n return null;\n }\n });\n if (purgedInvalidRows) {\n // Realtime consumers may hold a caught-up lease over rows that no longer\n // exist; the notification lets them drop it and refetch authoritatively.\n notifyOrganizationReadModelInvalidated(\n this.execSql,\n input.organizationId,\n );\n }\n return result;\n }\n\n async loadOrganizationReadModelProjection(\n organizationId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelProjection | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n }\n\n async loadOrganizationReadModelGroupMembers(\n organizationId: string,\n groupId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelGroupMembers | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadRequesterOrganizationReadModelGroupMembersInTransaction(tx, {\n currentUserId,\n groupId,\n organizationId,\n }),\n });\n }\n\n async applyOrganizationReadModelResponse(input: {\n readonly currentUserId: string;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n }): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune also retires pruned users' usage projections.\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n\n const disposition = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(\n (tx): Promise<ApplyOrganizationReadModelResponseResult> =>\n applyOrganizationReadModelResponseInTransaction(tx, {\n currentUserId: input.currentUserId,\n now: this.now,\n requestedCursor: input.requestedCursor,\n response: input.response,\n }),\n );\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.response.organizationId,\n );\n return disposition;\n }\n\n async purgeOrganizationReadModelProjection(\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n },\n );\n }\n\n /**\n * Purge one requester's access to an organization's presentation projections\n * after the server denied that requester. The denial is requester-scoped: the\n * shared read-model rows stay while another local identity in the same\n * database still holds a requester row, and organization-wide rows fall with\n * the last requester.\n */\n async purgeOrganizationAccessProjection(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await tx\n .delete(organizationReadModelRequesters)\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .run();\n const [remainingRequester] = await tx\n .select({ userId: organizationReadModelRequesters.userId })\n .from(organizationReadModelRequesters)\n .where(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n )\n .limit(1);\n if (!remainingRequester) {\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n }\n await purgeOrganizationDataUsageProjectionInTransaction({\n organizationId: input.organizationId,\n requesterUserId: input.requesterUserId,\n tx,\n });\n },\n );\n // A denial is a realtime-hinted access change: in-flight operations recover\n // the organization's directory again instead of reusing their memo.\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.organizationId,\n );\n }\n\n /**\n * The cursor this requester has applied, or null when it holds none. The\n * organization row's cursor is shared: another identity on this device may\n * have advanced it while this requester's own fields (for example\n * `isOrgAdmin`) still reflect an older response. Only the requester's own\n * applied cursor, while it is still the stored projection's cursor, proves\n * this requester is current. Realtime hints compare against it so a hint for\n * a cursor already applied costs no read.\n */\n async loadAppliedOrganizationReadModelCursor(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<string | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ cursor: organizationReadModelRequesters.appliedCursor })\n .from(organizationReadModelRequesters)\n .innerJoin(\n organizationReadModelState,\n and(\n eq(\n organizationReadModelState.organizationId,\n organizationReadModelRequesters.organizationId,\n ),\n eq(\n organizationReadModelState.cursor,\n organizationReadModelRequesters.appliedCursor,\n ),\n ),\n )\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .limit(1);\n return row?.cursor ?? null;\n }\n\n /**\n * Every locally projected organization's pointer to its organization_profile\n * document, keyed by organization id.\n *\n * This is the only container-independent handle on that document. Callers\n * that need an org's display name from local state cannot rely on where the\n * document is linked: the provisioner writes it under a deterministic local\n * alias into the organization-metadata container, while a device that only\n * *synced* it (identity recovery, another member) keys it under the server\n * documentId in whichever container the grant arrived through.\n *\n * The local schema stores only the current read-model contract, so every\n * state row is eligible to provide its profile-document pointer.\n */\n async loadOrganizationProfileDocumentIds(): Promise<Map<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n organizationId: organizationReadModelState.organizationId,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n })\n .from(organizationReadModelState);\n\n return new Map(\n rows.flatMap((row) =>\n row.profileDocumentId\n ? [[row.organizationId, row.profileDocumentId]]\n : [],\n ),\n );\n }\n\n async loadOrganizationGroupDisplayNames(\n organizationId: string,\n ): Promise<ReadonlyMap<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n groupId: organizationReadModelGroups.groupId,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId));\n return new Map(\n rows\n .filter((row) => row.name.length > 0)\n .map((row) => [row.groupId, row.name]),\n );\n }\n\n /** Local display cache only: these labels never enter a server request. */\n async saveOrganizationGroupDisplayNames(input: {\n organizationId: string;\n names: readonly { groupId: string; name: string; stateHash: string }[];\n stillCurrent: () => boolean;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(\n async (tx) => {\n for (const group of input.names) {\n await tx\n .update(organizationReadModelGroups)\n .set({ name: group.name })\n .where(\n and(\n eq(\n organizationReadModelGroups.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelGroups.groupId, group.groupId),\n eq(organizationReadModelGroups.stateHash, group.stateHash),\n ),\n )\n .run();\n }\n },\n input.stillCurrent,\n );\n }\n\n /**\n * Durably record a server denial before the revoked projection rows are\n * purged. The marker is what keeps a failed purge plus an offline restart\n * from serving the revoked projection; it is cleared only when an\n * authoritative reconcile stores fresh server state for the same scope.\n */\n async recordOrganizationPresentationDenials(\n scope: OrganizationPresentationDenialScope,\n projections: readonly OrganizationPresentationDenialProjection[],\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const deniedAt = this.now().toISOString();\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n for (const projection of new Set(projections)) {\n await tx\n .insert(organizationPresentationDenials)\n .values({\n organizationId: scope.organizationId,\n requesterUserId: scope.requesterUserId,\n projection,\n deniedAt,\n })\n .onConflictDoUpdate({\n target: [\n organizationPresentationDenials.organizationId,\n organizationPresentationDenials.requesterUserId,\n organizationPresentationDenials.projection,\n ],\n set: { deniedAt },\n })\n .run();\n }\n },\n );\n }\n\n async hasOrganizationPresentationDenial(\n scope: OrganizationPresentationDenialScope,\n projection: OrganizationPresentationDenialProjection,\n ): Promise<boolean> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ projection: organizationPresentationDenials.projection })\n .from(organizationPresentationDenials)\n .where(\n and(\n eq(\n organizationPresentationDenials.organizationId,\n scope.organizationId,\n ),\n eq(\n organizationPresentationDenials.requesterUserId,\n scope.requesterUserId,\n ),\n eq(organizationPresentationDenials.projection, projection),\n ),\n )\n .limit(1);\n return rows.length > 0;\n }\n}\n"]}
1
+ {"version":3,"file":"organizationReadModelRepository.js","sourceRoot":"","sources":["organizationReadModelRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,qCAAqC,EAAE,MAAM,6CAA6C,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,iDAAiD,CAAC;AAC9F,OAAO,EACL,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,iDAAiD,EAAE,MAAM,oCAAoC,CAAC;AAKvG,OAAO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E;iBAClB,CAAC;qBACD,GAAG,EAAE,CAAC;YACX,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,iCAAiC,CACrC,KAA0C,EAC1C,UAAoD;QAEpD,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;QACjE,MAAM,IAAI,GAAG,MAAM,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC;aAC/D,EAAE,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,+BAA+B,CAAC,UAAU,EAAE,CAAC;aACrE,IAAI,CAAC,+BAA+B,CAAC;aACrC,KAAK,CACJ,GAAG,CACD,EAAE,CACA,+BAA+B,CAAC,cAAc,EAC9C,KAAK,CAAC,cAAc,CACrB,EACD,EAAE,CACA,+BAA+B,CAAC,eAAe,EAC/C,KAAK,CAAC,eAAe,CACtB,EACD,EAAE,CAAC,+BAA+B,CAAC,UAAU,EAAE,UAAU,CAAC,CAC3D,CACF;aACA,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;IACzB,CAAC;CACF","sourcesContent":["import type { OrganizationReadModelResponse } from \"@tearleads/validators/response\";\nimport { and, eq } from \"drizzle-orm\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../principals/principalPolicyCoordinator\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport { organizationDataUsageTables } from \"../../sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { purgeOrganizationDataUsageProjectionInTransaction } from \"./organizationDataUsagePersistence\";\nimport type {\n OrganizationPresentationDenialProjection,\n OrganizationPresentationDenialScope,\n} from \"./organizationPresentationDenialPersistence\";\nimport { notifyOrganizationReadModelInvalidated } from \"./organizationReadModelInvalidation\";\nimport {\n loadRequesterOrganizationReadModelGroupMembersInTransaction,\n type OrganizationReadModelGroupMembers,\n} from \"./organizationReadModelMemberLoad\";\nimport {\n type ApplyOrganizationReadModelResponseResult,\n applyOrganizationReadModelResponseInTransaction,\n} from \"./organizationReadModelPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport { OrganizationReadModelIntegrityError } from \"./organizationReadModelProtocol\";\nimport { purgeOrganizationReadModelProjectionInTransaction } from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nconst organizationAccessProjectionTables = [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n];\n\n/**\n * The durable organization read-model projection, its group display names,\n * and its presentation denial markers, over one database. Invalidation\n * notices and recovery invalidation are keyed by the executor this\n * repository was built from.\n */\nexport class OrganizationReadModelRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n /**\n * The ONE load shell for the durable read-model projection: run `load` in a\n * transaction and, if a stored row fails integrity validation, purge the\n * organization's projection and report null. The projection is a\n * server-refetchable cache, so the next reconcile requests a cursorless\n * snapshot instead of every read and repair pass failing on the same row.\n */\n private async loadWithOrganizationReadModelIntegrityPurge<T>(input: {\n readonly load: (tx: ClientSQLiteTransactionScope) => Promise<T | null>;\n readonly organizationId: string;\n }): Promise<T | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n let purgedInvalidRows = false;\n const result = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(async (tx) => {\n try {\n return await input.load(tx);\n } catch (error) {\n if (!(error instanceof OrganizationReadModelIntegrityError)) {\n throw error;\n }\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n purgedInvalidRows = true;\n return null;\n }\n });\n if (purgedInvalidRows) {\n // Realtime consumers may hold a caught-up lease over rows that no longer\n // exist; the notification lets them drop it and refetch authoritatively.\n notifyOrganizationReadModelInvalidated(\n this.execSql,\n input.organizationId,\n );\n }\n return result;\n }\n\n async loadOrganizationReadModelProjection(\n organizationId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelProjection | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n }\n\n async loadOrganizationReadModelGroupMembers(\n organizationId: string,\n groupId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelGroupMembers | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadRequesterOrganizationReadModelGroupMembersInTransaction(tx, {\n currentUserId,\n groupId,\n organizationId,\n }),\n });\n }\n\n async applyOrganizationReadModelResponse(input: {\n /** Checked in the commit's own synchronous slice; refused rolls back. */\n readonly canCommit?: (() => boolean) | undefined;\n readonly currentUserId: string;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n }): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune also retires pruned users' usage projections.\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const apply = (\n tx: Parameters<Parameters<typeof runtime.transaction>[0]>[0],\n ): Promise<ApplyOrganizationReadModelResponseResult> =>\n applyOrganizationReadModelResponseInTransaction(tx, {\n currentUserId: input.currentUserId,\n now: this.now,\n requestedCursor: input.requestedCursor,\n response: input.response,\n });\n const disposition = input.canCommit\n ? ((await runtime.guardedTransaction(apply, input.canCommit)).result ??\n \"stale\")\n : await runtime.transaction(apply);\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.response.organizationId,\n );\n return disposition;\n }\n\n async purgeOrganizationReadModelProjection(\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n },\n );\n }\n\n /**\n * Purge one requester's access to an organization's presentation projections\n * after the server denied that requester. The denial is requester-scoped: the\n * shared read-model rows stay while another local identity in the same\n * database still holds a requester row, and organization-wide rows fall with\n * the last requester.\n */\n async purgeOrganizationAccessProjection(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await tx\n .delete(organizationReadModelRequesters)\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .run();\n const [remainingRequester] = await tx\n .select({ userId: organizationReadModelRequesters.userId })\n .from(organizationReadModelRequesters)\n .where(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n )\n .limit(1);\n if (!remainingRequester) {\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n }\n await purgeOrganizationDataUsageProjectionInTransaction({\n organizationId: input.organizationId,\n requesterUserId: input.requesterUserId,\n tx,\n });\n },\n );\n // A denial is a realtime-hinted access change: in-flight operations recover\n // the organization's directory again instead of reusing their memo.\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.organizationId,\n );\n }\n\n /**\n * The organization's stored projection cursor, shared by every requester on\n * this device: the cursor a reconcile requests from. Null without one.\n */\n async loadOrganizationReadModelCursor(\n organizationId: string,\n ): Promise<string | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ cursor: organizationReadModelState.cursor })\n .from(organizationReadModelState)\n .where(eq(organizationReadModelState.organizationId, organizationId))\n .limit(1);\n return row?.cursor ?? null;\n }\n\n /**\n * The cursor this requester has applied, or null when it holds none. The\n * organization row's cursor is shared: another identity on this device may\n * have advanced it while this requester's own fields (for example\n * `isOrgAdmin`) still reflect an older response. Only the requester's own\n * applied cursor, while it is still the stored projection's cursor, proves\n * this requester is current. Realtime hints compare against it so a hint for\n * a cursor already applied costs no read.\n */\n async loadAppliedOrganizationReadModelCursor(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<string | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ cursor: organizationReadModelRequesters.appliedCursor })\n .from(organizationReadModelRequesters)\n .innerJoin(\n organizationReadModelState,\n and(\n eq(\n organizationReadModelState.organizationId,\n organizationReadModelRequesters.organizationId,\n ),\n eq(\n organizationReadModelState.cursor,\n organizationReadModelRequesters.appliedCursor,\n ),\n ),\n )\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .limit(1);\n return row?.cursor ?? null;\n }\n\n /**\n * Every locally projected organization's pointer to its organization_profile\n * document, keyed by organization id.\n *\n * This is the only container-independent handle on that document. Callers\n * that need an org's display name from local state cannot rely on where the\n * document is linked: the provisioner writes it under a deterministic local\n * alias into the organization-metadata container, while a device that only\n * *synced* it (identity recovery, another member) keys it under the server\n * documentId in whichever container the grant arrived through.\n *\n * The local schema stores only the current read-model contract, so every\n * state row is eligible to provide its profile-document pointer.\n */\n async loadOrganizationProfileDocumentIds(): Promise<Map<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n organizationId: organizationReadModelState.organizationId,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n })\n .from(organizationReadModelState);\n\n return new Map(\n rows.flatMap((row) =>\n row.profileDocumentId\n ? [[row.organizationId, row.profileDocumentId]]\n : [],\n ),\n );\n }\n\n async loadOrganizationGroupDisplayNames(\n organizationId: string,\n ): Promise<ReadonlyMap<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n groupId: organizationReadModelGroups.groupId,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId));\n return new Map(\n rows\n .filter((row) => row.name.length > 0)\n .map((row) => [row.groupId, row.name]),\n );\n }\n\n /** Local display cache only: these labels never enter a server request. */\n async saveOrganizationGroupDisplayNames(input: {\n organizationId: string;\n names: readonly { groupId: string; name: string; stateHash: string }[];\n stillCurrent: () => boolean;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(\n async (tx) => {\n for (const group of input.names) {\n await tx\n .update(organizationReadModelGroups)\n .set({ name: group.name })\n .where(\n and(\n eq(\n organizationReadModelGroups.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelGroups.groupId, group.groupId),\n eq(organizationReadModelGroups.stateHash, group.stateHash),\n ),\n )\n .run();\n }\n },\n input.stillCurrent,\n );\n }\n\n /**\n * Durably record a server denial before the revoked projection rows are\n * purged. The marker is what keeps a failed purge plus an offline restart\n * from serving the revoked projection; it is cleared only when an\n * authoritative reconcile stores fresh server state for the same scope.\n */\n async recordOrganizationPresentationDenials(\n scope: OrganizationPresentationDenialScope,\n projections: readonly OrganizationPresentationDenialProjection[],\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const deniedAt = this.now().toISOString();\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n for (const projection of new Set(projections)) {\n await tx\n .insert(organizationPresentationDenials)\n .values({\n organizationId: scope.organizationId,\n requesterUserId: scope.requesterUserId,\n projection,\n deniedAt,\n })\n .onConflictDoUpdate({\n target: [\n organizationPresentationDenials.organizationId,\n organizationPresentationDenials.requesterUserId,\n organizationPresentationDenials.projection,\n ],\n set: { deniedAt },\n })\n .run();\n }\n },\n );\n }\n\n async hasOrganizationPresentationDenial(\n scope: OrganizationPresentationDenialScope,\n projection: OrganizationPresentationDenialProjection,\n ): Promise<boolean> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ projection: organizationPresentationDenials.projection })\n .from(organizationPresentationDenials)\n .where(\n and(\n eq(\n organizationPresentationDenials.organizationId,\n scope.organizationId,\n ),\n eq(\n organizationPresentationDenials.requesterUserId,\n scope.requesterUserId,\n ),\n eq(organizationPresentationDenials.projection, projection),\n ),\n )\n .limit(1);\n return rows.length > 0;\n }\n}\n"]}
@@ -0,0 +1,53 @@
1
+ import { isPrincipalStatePayloadResponse, isPrincipalStateResponse, } from "../../../internal/validators/response/index.js";
2
+ import { KNOWN_DIRECTORY_HINT_LIMIT } from "../../../internal/validators/util/index.js";
3
+ import { and, asc, desc, eq } from "drizzle-orm";
4
+ import { principalPolicyBundles } from "../../sqlite/schema/principalPolicySchema.js";
5
+ import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
6
+ function parsed(json) {
7
+ try {
8
+ return JSON.parse(json);
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ }
14
+ /**
15
+ * The organization directory payloads this device holds in its verified
16
+ * policy bundles, its current state first, at most
17
+ * `KNOWN_DIRECTORY_HINT_LIMIT`. Each travels with its signed state: the
18
+ * request cites a payload only when its bytes hash to that state's
19
+ * `payloadCiphertextHash`, so a refill is exactly the bytes the server would
20
+ * send.
21
+ */
22
+ export async function heldDirectoryCitations(execSql, organizationId) {
23
+ // Citing only saves bytes: a device that has stored no policy bundle yet
24
+ // (so no table) or cannot read them cites no directory.
25
+ const rows = await heldDirectoryRows(getClientSQLitePersistenceRuntime(execSql).db, organizationId).catch(() => []);
26
+ const citations = [];
27
+ for (const row of rows) {
28
+ const directoryState = parsed(row.stateJson);
29
+ const directoryPayload = parsed(row.payloadJson);
30
+ // A row must name its own state of this organization, so a request
31
+ // never cites another organization's state hash.
32
+ if (isPrincipalStateResponse(directoryState) &&
33
+ isPrincipalStatePayloadResponse(directoryPayload) &&
34
+ directoryState.stateHash === row.stateHash &&
35
+ directoryState.principalType === "organization" &&
36
+ directoryState.principalId === organizationId)
37
+ citations.push({ directoryState, directoryPayload });
38
+ }
39
+ return citations;
40
+ }
41
+ function heldDirectoryRows(db, organizationId) {
42
+ return db
43
+ .select({
44
+ stateHash: principalPolicyBundles.stateHash,
45
+ stateJson: principalPolicyBundles.currentStateJson,
46
+ payloadJson: principalPolicyBundles.currentPayloadJson,
47
+ })
48
+ .from(principalPolicyBundles)
49
+ .where(and(eq(principalPolicyBundles.principalType, "organization"), eq(principalPolicyBundles.principalId, organizationId)))
50
+ .orderBy(desc(principalPolicyBundles.isCurrent), desc(principalPolicyBundles.updatedAt), asc(principalPolicyBundles.stateHash))
51
+ .limit(KNOWN_DIRECTORY_HINT_LIMIT);
52
+ }
53
+ //# sourceMappingURL=heldOrganizationDirectories.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"heldOrganizationDirectories.js","sourceRoot":"","sources":["heldOrganizationDirectories.ts"],"names":[],"mappings":"AACA,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,aA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AAsB,CAAC,SAAS;QAC3C,SAAS,EAAE,sBAAsB,CAAC,gBAAgB;QAClD,WAAW,EAAE,sBAAsB,CAAC,kBAAkB;KACvD,CAAC;SACD,IAAI,CAAC,sBAAsB,CAAC;SAC5B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,sBAAsB,CAAC,aAAa,EAAE,cAAc,CAAC,EACxD,EAAE,CAAC,sBAAsB,CAAC,WAAW,EAAE,cAAc,CAAC,CACvD,CACF;SACA,OAAO,CACN,IAAI,CAAC,sBAAsB,CAAC,SAAS,CAAC,EACtC,IAAI,CAAC,sBAAsB,CAAC,SAAS,CAAC,EACtC,GAAG,CAAC,sBAAsB,CAAC,SAAS,CAAC,CACtC;SACA,KAAK,CAAC,0BAA0B,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import type { HeldDirectoryCitation } from \"@tearleads/api-client\";\nimport {\n isPrincipalStatePayloadResponse,\n isPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { KNOWN_DIRECTORY_HINT_LIMIT } from \"@tearleads/validators/util\";\nimport { and, asc, desc, eq } from \"drizzle-orm\";\nimport { principalPolicyBundles } from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteDatabase,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nfunction parsed(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\n/**\n * The organization directory payloads this device holds in its verified\n * policy bundles, its current state first, at most\n * `KNOWN_DIRECTORY_HINT_LIMIT`. Each travels with its signed state: the\n * request cites a payload only when its bytes hash to that state's\n * `payloadCiphertextHash`, so a refill is exactly the bytes the server would\n * send.\n */\nexport async function heldDirectoryCitations(\n execSql: ExecSql,\n organizationId: string,\n): Promise<HeldDirectoryCitation[]> {\n // Citing only saves bytes: a device that has stored no policy bundle yet\n // (so no table) or cannot read them cites no directory.\n const rows = await heldDirectoryRows(\n getClientSQLitePersistenceRuntime(execSql).db,\n organizationId,\n ).catch(() => []);\n const citations: HeldDirectoryCitation[] = [];\n for (const row of rows) {\n const directoryState = parsed(row.stateJson);\n const directoryPayload = parsed(row.payloadJson);\n // A row must name its own state of this organization, so a request\n // never cites another organization's state hash.\n if (\n isPrincipalStateResponse(directoryState) &&\n isPrincipalStatePayloadResponse(directoryPayload) &&\n directoryState.stateHash === row.stateHash &&\n directoryState.principalType === \"organization\" &&\n directoryState.principalId === organizationId\n )\n citations.push({ directoryState, directoryPayload });\n }\n return citations;\n}\n\nfunction heldDirectoryRows(db: ClientSQLiteDatabase, organizationId: string) {\n return db\n .select({\n stateHash: principalPolicyBundles.stateHash,\n stateJson: principalPolicyBundles.currentStateJson,\n payloadJson: principalPolicyBundles.currentPayloadJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(principalPolicyBundles.principalType, \"organization\"),\n eq(principalPolicyBundles.principalId, organizationId),\n ),\n )\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n desc(principalPolicyBundles.updatedAt),\n asc(principalPolicyBundles.stateHash),\n )\n .limit(KNOWN_DIRECTORY_HINT_LIMIT);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { HeldProjectionCitation, VerifiedManifestCitations, WriterProjectionTarget } from "../../internal/api-client/index.js";
1
+ import type { HeldDirectoryCitation, HeldProjectionCitation, VerifiedManifestCitations, WriterProjectionTarget } from "../../internal/api-client/index.js";
2
2
  import { type ServedAccessManifestBundleWireResponse } from "../../internal/validators/util/index.js";
3
3
  import { verifiedAccessManifestBundles as bundles } from "../sqlite/schema/verifiedManifestBundleSchema.js";
4
4
  import { type ClientSQLiteTransactionScope } from "../sqlite/sqlitePersistenceRuntime.js";
@@ -47,7 +47,12 @@ export declare function writeVerifiedManifestBundlesInTransaction(tx: ClientSQLi
47
47
  * organization the device cannot place cites nothing. Damaged rows are
48
48
  * dropped.
49
49
  */
50
- export declare function loadVerifiedManifestCitations(execSql: ExecSql, target: WriterProjectionTarget, requestedLimit?: number): Promise<HeldProjectionCitation[]>;
50
+ /**
51
+ * The organization directory payloads a device holds, from the subsystem
52
+ * that stores policy bundles; the composition root wires it.
53
+ */
54
+ export type HeldDirectorySource = (execSql: ExecSql, organizationId: string) => Promise<readonly HeldDirectoryCitation[]>;
55
+ export declare function loadVerifiedManifestCitations(execSql: ExecSql, target: WriterProjectionTarget, requestedLimit?: number, heldDirectories?: HeldDirectorySource): Promise<HeldProjectionCitation[]>;
51
56
  /** Keeps these held bundles out of citations until the release runs. */
52
57
  export declare function suppressHeldCitations(manifestHashes: readonly string[]): () => void;
53
58
  /**
@@ -59,7 +64,7 @@ export declare function suppressHeldCitations(manifestHashes: readonly string[])
59
64
  */
60
65
  export declare function dropHeldManifestBundles(execSql: ExecSql, heldBundles: readonly ServedAccessManifestBundleWireResponse[], stillCurrent?: () => boolean): Promise<boolean>;
61
66
  /** Cites from whichever database the signed-in identity currently uses. */
62
- export declare function createVerifiedManifestCitations(resolveExecSql: () => ExecSql | null): VerifiedManifestCitations;
67
+ export declare function createVerifiedManifestCitations(resolveExecSql: () => ExecSql | null, heldDirectories?: HeldDirectorySource): VerifiedManifestCitations;
63
68
  /** Drops an organization's verified bundles when a remote reset forgets it. */
64
69
  export declare function deleteVerifiedManifestBundlesForOrganization(tx: ClientSQLiteTransactionScope, organizationId: string): Promise<void>;
65
70
  export {};
@@ -153,24 +153,35 @@ async function touchStoredDigests(tx, manifestHashes, verifiedAt) {
153
153
  return digests;
154
154
  }
155
155
  /**
156
- * The latest verified KEK level of each container the target's projection
157
- * walks (supplemented by organization-recency levels for a pending move,
158
- * or when the lineage has no stored level); then verified bundles of those
159
- * objects, newest epochs first; then
160
- * the most recently verified bundles of its organization, since a
161
- * just-verified parent is the likeliest part of a new child's projection.
162
- * Citations never leave the target's organization: an object whose
163
- * organization the device cannot place cites nothing. Damaged rows are
164
- * dropped.
156
+ * How long after the citation load began the directory read may still run.
157
+ * Directory citations are an extra: the load collects the manifest and
158
+ * KEK-level citations first, then reads directories only with the time left
159
+ * before this point, which stays inside the API client's 250 ms citation
160
+ * deadline with room for its own preparation. A slow or stalled directory
161
+ * read therefore never delays or discards the manifest hints.
165
162
  */
166
- export async function loadVerifiedManifestCitations(execSql, target, requestedLimit = KNOWN_MANIFEST_HINT_LIMIT) {
163
+ const DIRECTORY_CITATION_DEADLINE_MS = 150;
164
+ async function directoriesBeforeDeadline(source, execSql, organizationId, startedAt) {
165
+ const remaining = startedAt + DIRECTORY_CITATION_DEADLINE_MS - performance.now();
166
+ if (!source || remaining <= 0)
167
+ return [];
168
+ let timer;
169
+ const deadline = new Promise((resolve) => {
170
+ timer = setTimeout(() => resolve([]), remaining);
171
+ });
172
+ return Promise.race([
173
+ source(execSql, organizationId).catch(() => []),
174
+ deadline,
175
+ ]).finally(() => clearTimeout(timer));
176
+ }
177
+ export async function loadVerifiedManifestCitations(execSql, target, requestedLimit = KNOWN_MANIFEST_HINT_LIMIT, heldDirectories) {
167
178
  const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));
168
179
  if (!(limit > 0))
169
180
  return [];
170
181
  const loadGeneration = evictionGeneration;
171
182
  citationLoadsInFlight += 1;
172
183
  try {
173
- return await loadCitableManifestCitations(execSql, target, limit).then((cited) => cited.filter((citation) => citable(citation, loadGeneration)));
184
+ return await loadCitableManifestCitations(execSql, target, limit, heldDirectories).then((cited) => cited.filter((citation) => citable(citation, loadGeneration)));
174
185
  }
175
186
  finally {
176
187
  citationLoadsInFlight -= 1;
@@ -178,7 +189,8 @@ export async function loadVerifiedManifestCitations(execSql, target, requestedLi
178
189
  evictedInGeneration.clear();
179
190
  }
180
191
  }
181
- async function loadCitableManifestCitations(execSql, target, limit) {
192
+ async function loadCitableManifestCitations(execSql, target, limit, heldDirectories) {
193
+ const startedAt = performance.now();
182
194
  await ensureSqlTables(execSql, [
183
195
  ...verifiedManifestBundleTables,
184
196
  ...containerTables,
@@ -194,7 +206,12 @@ async function loadCitableManifestCitations(execSql, target, limit) {
194
206
  const { cited, damaged } = await collectVerifiedManifestCitations(db, organizationId, objects, target, limit);
195
207
  if (damaged.length > 0)
196
208
  await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);
197
- return cited;
209
+ // Directories are cited beside the manifest quota, never in its place,
210
+ // and read only after the manifest citations, with the time left.
211
+ return [
212
+ ...cited,
213
+ ...(await directoriesBeforeDeadline(heldDirectories, execSql, organizationId, startedAt)),
214
+ ];
198
215
  }
199
216
  // Manifest hashes whose held rows a refused read is dropping: no read cites
200
217
  // them meanwhile, so none can be rebuilt from the bytes being dropped. Each
@@ -279,11 +296,13 @@ async function dropVerifiedManifestBundles(execSql, manifestHashes) {
279
296
  });
280
297
  }
281
298
  /** Cites from whichever database the signed-in identity currently uses. */
282
- export function createVerifiedManifestCitations(resolveExecSql) {
299
+ export function createVerifiedManifestCitations(resolveExecSql, heldDirectories) {
283
300
  return {
284
301
  cite: async (target) => {
285
302
  const execSql = resolveExecSql();
286
- return execSql ? loadVerifiedManifestCitations(execSql, target) : [];
303
+ return execSql
304
+ ? loadVerifiedManifestCitations(execSql, target, KNOWN_MANIFEST_HINT_LIMIT, heldDirectories)
305
+ : [];
287
306
  },
288
307
  };
289
308
  }
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedManifestBundlePersistence.js","sourceRoot":"","sources":["verifiedManifestBundlePersistence.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACL,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,6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AC7D,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAC1D,KAAK,EAAE,MAAM,EAAE,EAAE;QACf,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;YACvD,MAAM,MAAM;iBACT,MAAM,CAAC,OAAO,CAAC;iBACf,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;iBAC3C,GAAG,EAAE,CAAC;IACb,CAAC,CACF,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,+BAA+B,CAC7C,cAAoC;IAEpC,OAAO;QACL,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YACrB,MAAM,OAAO,GAAG,cAAc,EAAE,CAAC;YACjC,OAAO,OAAO,CAAC,CAAC,CAAC,6BAA6B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACvE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,EAAgC,EAChC,cAAsB;IAEtB,MAAM,EAAE;SACL,MAAM,CAAC,OAAO,CAAC;SACf,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;SACjD,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import type {\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n KNOWN_MANIFEST_HINT_LIMIT,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq, inArray, notInArray, sql } from \"drizzle-orm\";\nimport { containerTables, localIntentTables } from \"../sqlite/schema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../sqlite/schema/documentProjectionSchema\";\nimport {\n verifiedAccessManifestBundles as bundles,\n verifiedManifestBundleTables,\n} from \"../sqlite/schema/verifiedManifestBundleSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { collectVerifiedManifestCitations } from \"./verifiedCitations/citationCollection\";\nimport {\n citedObjects,\n targetOrganization,\n} from \"./verifiedCitations/citationScope\";\nimport {\n KEK_LEVEL_OBJECT_KIND,\n kekLevelRow,\n type VerifiedKekLevel,\n} from \"./verifiedCitations/kekLevelCitations\";\n\n/**\n * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently\n * verified rows only makes a later read carry those bundles again.\n */\nexport const MAX_VERIFIED_MANIFEST_BUNDLES = 1024;\nconst STATEMENT_BATCH = 200;\n\ninterface VerifiedBundle {\n /** The served bytes; the decoded state is rebuilt from them on refill. */\n readonly bundle: ServedAccessManifestBundleWireResponse;\n readonly checkpoint: {\n readonly objectKind: string;\n readonly organizationId: string;\n readonly objectId: string;\n readonly epoch: number;\n };\n}\n\n/** Bytes a projection verification accepted: a bundle or a KEK level. */\nexport type VerifiedManifestBundle = VerifiedBundle | VerifiedKekLevel;\n\nfunction sha256Hex(text: string): Promise<string> {\n return toFingerprint(new TextEncoder().encode(text));\n}\n\nconst BUNDLE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(bundles);\n\nfunction slices<T>(values: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += size)\n result.push(values.slice(index, index + size));\n return result;\n}\n\nfunction batches<T>(values: readonly T[]): T[][] {\n return slices(values, STATEMENT_BATCH);\n}\n\nasync function pruneInTransaction(\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const [row] = await tx.select({ count: sql<number>`count(*)` }).from(bundles);\n const excess = (row?.count ?? 0) - MAX_VERIFIED_MANIFEST_BUNDLES;\n if (excess <= 0) return;\n const evicted = await tx\n .select({ manifestHash: bundles.manifestHash })\n .from(bundles)\n .orderBy(asc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(excess);\n for (const batch of batches(evicted.map((entry) => entry.manifestHash)))\n await tx.delete(bundles).where(inArray(bundles.manifestHash, batch)).run();\n}\n\n/** A verified bundle's exact JSON and that JSON's digest. */\nexport type VerifiedManifestBundleRow = Omit<\n typeof bundles.$inferInsert,\n \"verifiedAt\"\n>;\n\n/**\n * Prepares rows for bundles and KEK levels that just passed projection\n * verification. The digests are computed here, before the checkpoint\n * transaction that writes them begins.\n */\nexport async function verifiedManifestBundleRows(\n entries: readonly VerifiedManifestBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleEntries: VerifiedBundle[] = [];\n const levelEntries: VerifiedKekLevel[] = [];\n for (const entry of entries)\n if (\"kekLevel\" in entry) levelEntries.push(entry);\n else bundleEntries.push(entry);\n // One level per container: its newest epoch, the last one seen on a tie.\n const levelRows = new Map<string, VerifiedManifestBundleRow>();\n for (const level of levelEntries) {\n const row = await kekLevelRow(level);\n const held = row && levelRows.get(row.objectId);\n if (row && (!held || held.epoch <= row.epoch))\n levelRows.set(row.objectId, row);\n }\n return [...(await bundleRows(bundleEntries)), ...levelRows.values()];\n}\n\nfunction bundleRows(\n entries: readonly VerifiedBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const unique = new Map(\n entries.map((entry) => [entry.bundle.manifestHash, entry]),\n );\n return Promise.all(\n [...unique.values()].map(async ({ bundle, checkpoint }) => {\n const bundleJson = JSON.stringify(bundle);\n return {\n manifestHash: bundle.manifestHash,\n organizationId: checkpoint.organizationId,\n objectKind: checkpoint.objectKind,\n objectId: checkpoint.objectId,\n epoch: checkpoint.epoch,\n bundleJson,\n bundleDigest: await sha256Hex(bundleJson),\n };\n }),\n );\n}\n\n/**\n * Records verified bundles inside the transaction that finalizes their\n * projection's checkpoints, so they commit or roll back with it and no cache\n * work outlives the verification. Freshly verified bytes replace any stored\n * copy.\n */\nexport async function writeVerifiedManifestBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n if (rows.length === 0) return;\n const stored = await touchStoredDigests(\n tx,\n rows.map((row) => row.manifestHash),\n verifiedAt,\n );\n // A repeated hash keeps its last changed row, as sequential upserts would.\n const changed = new Map(\n rows\n .filter((row) => stored.get(row.manifestHash) !== row.bundleDigest)\n .map((row) => [row.manifestHash, { ...row, verifiedAt }]),\n );\n for (const batch of slices([...changed.values()], BUNDLE_WRITE_BATCH_SIZE))\n await tx\n .insert(bundles)\n .values(batch)\n .onConflictDoUpdate({\n target: bundles.manifestHash,\n set: {\n organizationId: excludedValue(bundles.organizationId),\n objectKind: excludedValue(bundles.objectKind),\n objectId: excludedValue(bundles.objectId),\n epoch: excludedValue(bundles.epoch),\n bundleJson: excludedValue(bundles.bundleJson),\n bundleDigest: excludedValue(bundles.bundleDigest),\n verifiedAt: excludedValue(bundles.verifiedAt),\n },\n })\n .run();\n // All incremental SDK level writes pass here. Both checkpoint callers\n // prepare them with verifiedManifestBundleRows (one level per container),\n // then write and drop siblings in the same serialized transaction. Thus an\n // unchanged level already removed its siblings; eviction/reset only delete.\n // Restored caches must preserve that invariant too: this fast path does not\n // repair externally injected stale siblings.\n await dropSupersededKekLevels(tx, [...changed.values()]);\n // Replacing or touching existing rows cannot grow the bounded cache.\n if (rows.some((row) => !stored.has(row.manifestHash))) {\n await pruneInTransaction(tx);\n }\n}\n\n/**\n * A container keeps only its latest verified level: the API serves its\n * current level, so an older one can never be cited usefully again.\n */\nasync function dropSupersededKekLevels(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n): Promise<void> {\n const levels = rows.filter((row) => row.objectKind === KEK_LEVEL_OBJECT_KIND);\n for (const batch of batches(levels))\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n inArray(\n bundles.objectId,\n batch.map((row) => row.objectId),\n ),\n notInArray(\n bundles.manifestHash,\n batch.map((row) => row.manifestHash),\n ),\n ),\n )\n .run();\n}\n\nasync function touchStoredDigests(\n tx: ClientSQLiteTransactionScope,\n manifestHashes: readonly string[],\n verifiedAt: string,\n): Promise<Map<string, string>> {\n const digests = new Map<string, string>();\n for (const batch of batches(manifestHashes)) {\n const rows = await tx\n .update(bundles)\n .set({ verifiedAt })\n .where(inArray(bundles.manifestHash, batch))\n .returning({\n bundleDigest: bundles.bundleDigest,\n manifestHash: bundles.manifestHash,\n });\n for (const row of rows) digests.set(row.manifestHash, row.bundleDigest);\n }\n return digests;\n}\n\n/**\n * The latest verified KEK level of each container the target's projection\n * walks (supplemented by organization-recency levels for a pending move,\n * or when the lineage has no stored level); then verified bundles of those\n * objects, newest epochs first; then\n * the most recently verified bundles of its organization, since a\n * just-verified parent is the likeliest part of a new child's projection.\n * Citations never leave the target's organization: an object whose\n * organization the device cannot place cites nothing. Damaged rows are\n * dropped.\n */\nexport async function loadVerifiedManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n requestedLimit = KNOWN_MANIFEST_HINT_LIMIT,\n): Promise<HeldProjectionCitation[]> {\n const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));\n if (!(limit > 0)) return [];\n const loadGeneration = evictionGeneration;\n citationLoadsInFlight += 1;\n try {\n return await loadCitableManifestCitations(execSql, target, limit).then(\n (cited) => cited.filter((citation) => citable(citation, loadGeneration)),\n );\n } finally {\n citationLoadsInFlight -= 1;\n if (citationLoadsInFlight === 0) evictedInGeneration.clear();\n }\n}\n\nasync function loadCitableManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n limit: number,\n): Promise<HeldProjectionCitation[]> {\n await ensureSqlTables(execSql, [\n ...verifiedManifestBundleTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...localIntentTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const objects = await citedObjects(db, target);\n const organizationId = await targetOrganization(db, target, objects);\n if (organizationId === null) return [];\n const { cited, damaged } = await collectVerifiedManifestCitations(\n db,\n organizationId,\n objects,\n target,\n limit,\n );\n if (damaged.length > 0)\n await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);\n return cited;\n}\n\n// Manifest hashes whose held rows a refused read is dropping: no read cites\n// them meanwhile, so none can be rebuilt from the bytes being dropped. Each\n// eviction also advances a generation, so a citation load that started\n// before it never returns the rows it read: they may already be gone.\nconst suppressedCitations = new Map<string, number>();\nconst evictedInGeneration = new Map<string, number>();\nlet evictionGeneration = 0;\n// Loads in flight; once none overlap, the eviction log has nothing to guard.\nlet citationLoadsInFlight = 0;\n\n/** Keeps these held bundles out of citations until the release runs. */\nexport function suppressHeldCitations(\n manifestHashes: readonly string[],\n): () => void {\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n suppressedCitations.set(hash, (suppressedCitations.get(hash) ?? 0) + 1);\n evictedInGeneration.set(hash, evictionGeneration);\n }\n return () => {\n // The drop is complete: a load that started before now may hold the\n // dropped bytes, so it is newer than none of them.\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n evictedInGeneration.set(hash, evictionGeneration);\n const count = (suppressedCitations.get(hash) ?? 1) - 1;\n if (count > 0) suppressedCitations.set(hash, count);\n else suppressedCitations.delete(hash);\n }\n };\n}\n\nfunction citable(\n citation: HeldProjectionCitation,\n loadGeneration: number,\n): boolean {\n if (!(\"manifestHash\" in citation)) return true;\n const { manifestHash } = citation;\n return (\n !suppressedCitations.has(manifestHash) &&\n (evictedInGeneration.get(manifestHash) ?? 0) <= loadGeneration\n );\n}\n\n/**\n * Drops the stored rows of held bundles a projection that cited them failed\n * to verify with, so the next read fetches them from the server. Only a row\n * still holding the exact bytes cited goes, so a newer verified copy written\n * meanwhile stays; nothing is dropped once `stillCurrent` turns false.\n * Resolves whether the drop committed.\n */\nexport async function dropHeldManifestBundles(\n execSql: ExecSql,\n heldBundles: readonly ServedAccessManifestBundleWireResponse[],\n stillCurrent?: () => boolean,\n): Promise<boolean> {\n if (heldBundles.length === 0) return true;\n const cited = await Promise.all(\n heldBundles.map(async (bundle) => ({\n manifestHash: bundle.manifestHash,\n bundleDigest: await sha256Hex(JSON.stringify(bundle)),\n })),\n );\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const drop = async (tx: ClientSQLiteTransactionScope) => {\n for (const row of cited)\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.manifestHash, row.manifestHash),\n eq(bundles.bundleDigest, row.bundleDigest),\n ),\n )\n .run();\n };\n if (!stillCurrent) {\n await runtime.transaction(drop, { behavior: \"immediate\" });\n return true;\n }\n const { committed } = await runtime.guardedTransaction(drop, stillCurrent, {\n behavior: \"immediate\",\n });\n return committed;\n}\n\n/** Drops damaged stored rows so no later read cites them. */\nasync function dropVerifiedManifestBundles(\n execSql: ExecSql,\n manifestHashes: readonly string[],\n): Promise<void> {\n if (manifestHashes.length === 0) return;\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(\n async (handle) => {\n for (const batch of batches([...new Set(manifestHashes)]))\n await handle\n .delete(bundles)\n .where(inArray(bundles.manifestHash, batch))\n .run();\n },\n );\n}\n\n/** Cites from whichever database the signed-in identity currently uses. */\nexport function createVerifiedManifestCitations(\n resolveExecSql: () => ExecSql | null,\n): VerifiedManifestCitations {\n return {\n cite: async (target) => {\n const execSql = resolveExecSql();\n return execSql ? loadVerifiedManifestCitations(execSql, target) : [];\n },\n };\n}\n\n/** Drops an organization's verified bundles when a remote reset forgets it. */\nexport async function deleteVerifiedManifestBundlesForOrganization(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n await tx\n .delete(bundles)\n .where(eq(bundles.organizationId, organizationId))\n .run();\n}\n"]}
1
+ {"version":3,"file":"verifiedManifestBundlePersistence.js","sourceRoot":"","sources":["verifiedManifestBundlePersistence.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACL,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,6BAA6B,IAAI,OAAO,EACxC,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,gCAAgC,EAAE,MAAM,wCAAwC,CAAC;AAC1F,OAAO,EACL,YAAY,EACZ,kBAAkB,GACnB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,qBAAqB,EACrB,WAAW,GAEZ,MAAM,uCAAuC,CAAC;AAE/C;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAClD,MAAM,eAAe,GAAG,GAAG,CAAC;AAgB5B,SAAS,SAAS,CAAC,IAAY;IAC7B,OAAO,aAAa,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,uBAAuB,GAAG,qBAAqB,CAAC,OAAO,CAAC,C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S,CAAC;AACnB,CAAC;AAED,6DAA6D;AAC7D,KAAK,UAAU,2BAA2B,CACxC,OAAgB,EAChB,cAAiC;IAEjC,IAAI,cAAc,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IACxC,MAAM,eAAe,CAAC,OAAO,EAAE,4BAA4B,CAAC,CAAC;IAC7D,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAC1D,KAAK,EAAE,MAAM,EAAE,EAAE;QACf,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;YACvD,MAAM,MAAM;iBACT,MAAM,CAAC,OAAO,CAAC;iBACf,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;iBAC3C,GAAG,EAAE,CAAC;IACb,CAAC,CACF,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,+BAA+B,CAC7C,cAAoC,EACpC,eAAqC;IAErC,OAAO;QACL,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YACrB,MAAM,OAAO,GAAG,cAAc,EAAE,CAAC;YACjC,OAAO,OAAO;gBACZ,CAAC,CAAC,6BAA6B,CAC3B,OAAO,EACP,MAAM,EACN,yBAAyB,EACzB,eAAe,CAChB;gBACH,CAAC,CAAC,EAAE,CAAC;QACT,CAAC;KACF,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,EAAgC,EAChC,cAAsB;IAEtB,MAAM,EAAE;SACL,MAAM,CAAC,OAAO,CAAC;SACf,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;SACjD,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import type {\n HeldDirectoryCitation,\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n KNOWN_MANIFEST_HINT_LIMIT,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq, inArray, notInArray, sql } from \"drizzle-orm\";\nimport { containerTables, localIntentTables } from \"../sqlite/schema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../sqlite/schema/documentProjectionSchema\";\nimport {\n verifiedAccessManifestBundles as bundles,\n verifiedManifestBundleTables,\n} from \"../sqlite/schema/verifiedManifestBundleSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { collectVerifiedManifestCitations } from \"./verifiedCitations/citationCollection\";\nimport {\n citedObjects,\n targetOrganization,\n} from \"./verifiedCitations/citationScope\";\nimport {\n KEK_LEVEL_OBJECT_KIND,\n kekLevelRow,\n type VerifiedKekLevel,\n} from \"./verifiedCitations/kekLevelCitations\";\n\n/**\n * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently\n * verified rows only makes a later read carry those bundles again.\n */\nexport const MAX_VERIFIED_MANIFEST_BUNDLES = 1024;\nconst STATEMENT_BATCH = 200;\n\ninterface VerifiedBundle {\n /** The served bytes; the decoded state is rebuilt from them on refill. */\n readonly bundle: ServedAccessManifestBundleWireResponse;\n readonly checkpoint: {\n readonly objectKind: string;\n readonly organizationId: string;\n readonly objectId: string;\n readonly epoch: number;\n };\n}\n\n/** Bytes a projection verification accepted: a bundle or a KEK level. */\nexport type VerifiedManifestBundle = VerifiedBundle | VerifiedKekLevel;\n\nfunction sha256Hex(text: string): Promise<string> {\n return toFingerprint(new TextEncoder().encode(text));\n}\n\nconst BUNDLE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(bundles);\n\nfunction slices<T>(values: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += size)\n result.push(values.slice(index, index + size));\n return result;\n}\n\nfunction batches<T>(values: readonly T[]): T[][] {\n return slices(values, STATEMENT_BATCH);\n}\n\nasync function pruneInTransaction(\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const [row] = await tx.select({ count: sql<number>`count(*)` }).from(bundles);\n const excess = (row?.count ?? 0) - MAX_VERIFIED_MANIFEST_BUNDLES;\n if (excess <= 0) return;\n const evicted = await tx\n .select({ manifestHash: bundles.manifestHash })\n .from(bundles)\n .orderBy(asc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(excess);\n for (const batch of batches(evicted.map((entry) => entry.manifestHash)))\n await tx.delete(bundles).where(inArray(bundles.manifestHash, batch)).run();\n}\n\n/** A verified bundle's exact JSON and that JSON's digest. */\nexport type VerifiedManifestBundleRow = Omit<\n typeof bundles.$inferInsert,\n \"verifiedAt\"\n>;\n\n/**\n * Prepares rows for bundles and KEK levels that just passed projection\n * verification. The digests are computed here, before the checkpoint\n * transaction that writes them begins.\n */\nexport async function verifiedManifestBundleRows(\n entries: readonly VerifiedManifestBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleEntries: VerifiedBundle[] = [];\n const levelEntries: VerifiedKekLevel[] = [];\n for (const entry of entries)\n if (\"kekLevel\" in entry) levelEntries.push(entry);\n else bundleEntries.push(entry);\n // One level per container: its newest epoch, the last one seen on a tie.\n const levelRows = new Map<string, VerifiedManifestBundleRow>();\n for (const level of levelEntries) {\n const row = await kekLevelRow(level);\n const held = row && levelRows.get(row.objectId);\n if (row && (!held || held.epoch <= row.epoch))\n levelRows.set(row.objectId, row);\n }\n return [...(await bundleRows(bundleEntries)), ...levelRows.values()];\n}\n\nfunction bundleRows(\n entries: readonly VerifiedBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const unique = new Map(\n entries.map((entry) => [entry.bundle.manifestHash, entry]),\n );\n return Promise.all(\n [...unique.values()].map(async ({ bundle, checkpoint }) => {\n const bundleJson = JSON.stringify(bundle);\n return {\n manifestHash: bundle.manifestHash,\n organizationId: checkpoint.organizationId,\n objectKind: checkpoint.objectKind,\n objectId: checkpoint.objectId,\n epoch: checkpoint.epoch,\n bundleJson,\n bundleDigest: await sha256Hex(bundleJson),\n };\n }),\n );\n}\n\n/**\n * Records verified bundles inside the transaction that finalizes their\n * projection's checkpoints, so they commit or roll back with it and no cache\n * work outlives the verification. Freshly verified bytes replace any stored\n * copy.\n */\nexport async function writeVerifiedManifestBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n if (rows.length === 0) return;\n const stored = await touchStoredDigests(\n tx,\n rows.map((row) => row.manifestHash),\n verifiedAt,\n );\n // A repeated hash keeps its last changed row, as sequential upserts would.\n const changed = new Map(\n rows\n .filter((row) => stored.get(row.manifestHash) !== row.bundleDigest)\n .map((row) => [row.manifestHash, { ...row, verifiedAt }]),\n );\n for (const batch of slices([...changed.values()], BUNDLE_WRITE_BATCH_SIZE))\n await tx\n .insert(bundles)\n .values(batch)\n .onConflictDoUpdate({\n target: bundles.manifestHash,\n set: {\n organizationId: excludedValue(bundles.organizationId),\n objectKind: excludedValue(bundles.objectKind),\n objectId: excludedValue(bundles.objectId),\n epoch: excludedValue(bundles.epoch),\n bundleJson: excludedValue(bundles.bundleJson),\n bundleDigest: excludedValue(bundles.bundleDigest),\n verifiedAt: excludedValue(bundles.verifiedAt),\n },\n })\n .run();\n // All incremental SDK level writes pass here. Both checkpoint callers\n // prepare them with verifiedManifestBundleRows (one level per container),\n // then write and drop siblings in the same serialized transaction. Thus an\n // unchanged level already removed its siblings; eviction/reset only delete.\n // Restored caches must preserve that invariant too: this fast path does not\n // repair externally injected stale siblings.\n await dropSupersededKekLevels(tx, [...changed.values()]);\n // Replacing or touching existing rows cannot grow the bounded cache.\n if (rows.some((row) => !stored.has(row.manifestHash))) {\n await pruneInTransaction(tx);\n }\n}\n\n/**\n * A container keeps only its latest verified level: the API serves its\n * current level, so an older one can never be cited usefully again.\n */\nasync function dropSupersededKekLevels(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n): Promise<void> {\n const levels = rows.filter((row) => row.objectKind === KEK_LEVEL_OBJECT_KIND);\n for (const batch of batches(levels))\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n inArray(\n bundles.objectId,\n batch.map((row) => row.objectId),\n ),\n notInArray(\n bundles.manifestHash,\n batch.map((row) => row.manifestHash),\n ),\n ),\n )\n .run();\n}\n\nasync function touchStoredDigests(\n tx: ClientSQLiteTransactionScope,\n manifestHashes: readonly string[],\n verifiedAt: string,\n): Promise<Map<string, string>> {\n const digests = new Map<string, string>();\n for (const batch of batches(manifestHashes)) {\n const rows = await tx\n .update(bundles)\n .set({ verifiedAt })\n .where(inArray(bundles.manifestHash, batch))\n .returning({\n bundleDigest: bundles.bundleDigest,\n manifestHash: bundles.manifestHash,\n });\n for (const row of rows) digests.set(row.manifestHash, row.bundleDigest);\n }\n return digests;\n}\n\n/**\n * The latest verified KEK level of each container the target's projection\n * walks (supplemented by organization-recency levels for a pending move,\n * or when the lineage has no stored level); then verified bundles of those\n * objects, newest epochs first; then\n * the most recently verified bundles of its organization, since a\n * just-verified parent is the likeliest part of a new child's projection.\n * Citations never leave the target's organization: an object whose\n * organization the device cannot place cites nothing. Damaged rows are\n * dropped.\n */\n/**\n * The organization directory payloads a device holds, from the subsystem\n * that stores policy bundles; the composition root wires it.\n */\nexport type HeldDirectorySource = (\n execSql: ExecSql,\n organizationId: string,\n) => Promise<readonly HeldDirectoryCitation[]>;\n\n/**\n * How long after the citation load began the directory read may still run.\n * Directory citations are an extra: the load collects the manifest and\n * KEK-level citations first, then reads directories only with the time left\n * before this point, which stays inside the API client's 250 ms citation\n * deadline with room for its own preparation. A slow or stalled directory\n * read therefore never delays or discards the manifest hints.\n */\nconst DIRECTORY_CITATION_DEADLINE_MS = 150;\n\nasync function directoriesBeforeDeadline(\n source: HeldDirectorySource | undefined,\n execSql: ExecSql,\n organizationId: string,\n startedAt: number,\n): Promise<readonly HeldDirectoryCitation[]> {\n const remaining =\n startedAt + DIRECTORY_CITATION_DEADLINE_MS - performance.now();\n if (!source || remaining <= 0) return [];\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<readonly HeldDirectoryCitation[]>((resolve) => {\n timer = setTimeout(() => resolve([]), remaining);\n });\n return Promise.race([\n source(execSql, organizationId).catch(() => []),\n deadline,\n ]).finally(() => clearTimeout(timer));\n}\n\nexport async function loadVerifiedManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n requestedLimit = KNOWN_MANIFEST_HINT_LIMIT,\n heldDirectories?: HeldDirectorySource,\n): Promise<HeldProjectionCitation[]> {\n const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));\n if (!(limit > 0)) return [];\n const loadGeneration = evictionGeneration;\n citationLoadsInFlight += 1;\n try {\n return await loadCitableManifestCitations(\n execSql,\n target,\n limit,\n heldDirectories,\n ).then((cited) =>\n cited.filter((citation) => citable(citation, loadGeneration)),\n );\n } finally {\n citationLoadsInFlight -= 1;\n if (citationLoadsInFlight === 0) evictedInGeneration.clear();\n }\n}\n\nasync function loadCitableManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n limit: number,\n heldDirectories: HeldDirectorySource | undefined,\n): Promise<HeldProjectionCitation[]> {\n const startedAt = performance.now();\n await ensureSqlTables(execSql, [\n ...verifiedManifestBundleTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...localIntentTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const objects = await citedObjects(db, target);\n const organizationId = await targetOrganization(db, target, objects);\n if (organizationId === null) return [];\n const { cited, damaged } = await collectVerifiedManifestCitations(\n db,\n organizationId,\n objects,\n target,\n limit,\n );\n if (damaged.length > 0)\n await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);\n // Directories are cited beside the manifest quota, never in its place,\n // and read only after the manifest citations, with the time left.\n return [\n ...cited,\n ...(await directoriesBeforeDeadline(\n heldDirectories,\n execSql,\n organizationId,\n startedAt,\n )),\n ];\n}\n\n// Manifest hashes whose held rows a refused read is dropping: no read cites\n// them meanwhile, so none can be rebuilt from the bytes being dropped. Each\n// eviction also advances a generation, so a citation load that started\n// before it never returns the rows it read: they may already be gone.\nconst suppressedCitations = new Map<string, number>();\nconst evictedInGeneration = new Map<string, number>();\nlet evictionGeneration = 0;\n// Loads in flight; once none overlap, the eviction log has nothing to guard.\nlet citationLoadsInFlight = 0;\n\n/** Keeps these held bundles out of citations until the release runs. */\nexport function suppressHeldCitations(\n manifestHashes: readonly string[],\n): () => void {\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n suppressedCitations.set(hash, (suppressedCitations.get(hash) ?? 0) + 1);\n evictedInGeneration.set(hash, evictionGeneration);\n }\n return () => {\n // The drop is complete: a load that started before now may hold the\n // dropped bytes, so it is newer than none of them.\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n evictedInGeneration.set(hash, evictionGeneration);\n const count = (suppressedCitations.get(hash) ?? 1) - 1;\n if (count > 0) suppressedCitations.set(hash, count);\n else suppressedCitations.delete(hash);\n }\n };\n}\n\nfunction citable(\n citation: HeldProjectionCitation,\n loadGeneration: number,\n): boolean {\n if (!(\"manifestHash\" in citation)) return true;\n const { manifestHash } = citation;\n return (\n !suppressedCitations.has(manifestHash) &&\n (evictedInGeneration.get(manifestHash) ?? 0) <= loadGeneration\n );\n}\n\n/**\n * Drops the stored rows of held bundles a projection that cited them failed\n * to verify with, so the next read fetches them from the server. Only a row\n * still holding the exact bytes cited goes, so a newer verified copy written\n * meanwhile stays; nothing is dropped once `stillCurrent` turns false.\n * Resolves whether the drop committed.\n */\nexport async function dropHeldManifestBundles(\n execSql: ExecSql,\n heldBundles: readonly ServedAccessManifestBundleWireResponse[],\n stillCurrent?: () => boolean,\n): Promise<boolean> {\n if (heldBundles.length === 0) return true;\n const cited = await Promise.all(\n heldBundles.map(async (bundle) => ({\n manifestHash: bundle.manifestHash,\n bundleDigest: await sha256Hex(JSON.stringify(bundle)),\n })),\n );\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const drop = async (tx: ClientSQLiteTransactionScope) => {\n for (const row of cited)\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.manifestHash, row.manifestHash),\n eq(bundles.bundleDigest, row.bundleDigest),\n ),\n )\n .run();\n };\n if (!stillCurrent) {\n await runtime.transaction(drop, { behavior: \"immediate\" });\n return true;\n }\n const { committed } = await runtime.guardedTransaction(drop, stillCurrent, {\n behavior: \"immediate\",\n });\n return committed;\n}\n\n/** Drops damaged stored rows so no later read cites them. */\nasync function dropVerifiedManifestBundles(\n execSql: ExecSql,\n manifestHashes: readonly string[],\n): Promise<void> {\n if (manifestHashes.length === 0) return;\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(\n async (handle) => {\n for (const batch of batches([...new Set(manifestHashes)]))\n await handle\n .delete(bundles)\n .where(inArray(bundles.manifestHash, batch))\n .run();\n },\n );\n}\n\n/** Cites from whichever database the signed-in identity currently uses. */\nexport function createVerifiedManifestCitations(\n resolveExecSql: () => ExecSql | null,\n heldDirectories?: HeldDirectorySource,\n): VerifiedManifestCitations {\n return {\n cite: async (target) => {\n const execSql = resolveExecSql();\n return execSql\n ? loadVerifiedManifestCitations(\n execSql,\n target,\n KNOWN_MANIFEST_HINT_LIMIT,\n heldDirectories,\n )\n : [];\n },\n };\n}\n\n/** Drops an organization's verified bundles when a remote reset forgets it. */\nexport async function deleteVerifiedManifestBundlesForOrganization(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n await tx\n .delete(bundles)\n .where(eq(bundles.organizationId, organizationId))\n .run();\n}\n"]}
@@ -929,6 +929,7 @@ export declare class ApiClient extends ApiClientAreas {
929
929
  version: number;
930
930
  };
931
931
  } | undefined;
932
+ readModel?: unknown;
932
933
  } | null>;
933
934
  commitOrganizationGroupPolicyResult: (organizationId: string, groupId: string, input: import("../validators/request/index.js").CommitOrganizationGroupPolicyRequest, options?: import("./types.js").RequestResultOptions) => Promise<import("./types.js").RequestResult<import("../validators/response/index.js").CommitOrganizationGroupPolicyResponse>>;
934
935
  getOrganizationPolicyHistoryResult: (organizationId: string, stateHash: string, options?: Parameters<typeof import("./organizationPolicyHistory.js").getOrganizationPolicyHistoryResult>[3]) => Promise<import("./types.js").RequestResult<import("../validators/response/index.js").OrganizationPolicyHistoryResponse>>;
@@ -1165,6 +1166,7 @@ export declare class ApiClient extends ApiClientAreas {
1165
1166
  version: number;
1166
1167
  };
1167
1168
  };
1169
+ readModel?: unknown;
1168
1170
  } | null>;
1169
1171
  createOrganizationGroupResult: (organizationId: string, input: {
1170
1172
  organizationPolicy: {
@@ -1399,6 +1401,7 @@ export declare class ApiClient extends ApiClientAreas {
1399
1401
  version: number;
1400
1402
  };
1401
1403
  };
1404
+ readModel?: unknown;
1402
1405
  }>>;
1403
1406
  deleteOrganizationGroup: (organizationId: string, groupId: string, input: {
1404
1407
  organizationPolicy: {
@@ -2304,7 +2307,7 @@ export declare class ApiClient extends ApiClientAreas {
2304
2307
  updatedAt: string;
2305
2308
  systemSlot?: string | null | undefined;
2306
2309
  } | null>;
2307
- shareContainerResult: (containerId: string, input: import("../validators/request/index.js").ContainerMutationRequest, options?: import("./types.js").RequestResultOptions) => Promise<import("./types.js").RequestResult<import("../validators/response/index.js").ContainerMutationResponse>>;
2310
+ shareContainerResult: (containerId: string, input: import("../validators/request/index.js").ContainerMutationRequest, options?: import("./types.js").RequestResultOptions) => Promise<import("./types.js").RequestResult<import("../validators/response/index.js").ContainerShareResponse>>;
2308
2311
  revokeContainer: (containerId: string, input: import("../validators/request/index.js").ContainerRotationRequest, options?: import("./types.js").RequestResultOptions) => Promise<{
2309
2312
  containerKek: {
2310
2313
  containerKeyEpoch: number;