@tearleads/client-sdk 0.1.212 → 0.1.214
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/containerContents/documentDiscovery.js +2 -2
- package/client/containerContents/documentDiscovery.js.map +1 -1
- package/client/organizations/organizationReadModels.js +3 -3
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +11 -2
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +89 -77
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/persistence/organizations/organizationPresentationDenialPersistence.js +0 -43
- package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelMemberLoad.d.ts +7 -2
- package/data/persistence/organizations/organizationReadModelMemberLoad.js +22 -27
- package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPersistence.js +38 -81
- package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPurge.js +0 -38
- package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelRepository.js +264 -0
- package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -0
- package/package.json +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +6 -2
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
- package/workflows/organizations/index.d.ts +0 -1
- package/workflows/organizations/index.js +0 -1
- package/workflows/organizations/index.js.map +1 -1
- package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js +7 -4
- package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js.map +1 -1
- package/workflows/organizations/readModel/dataUsageReadModel.js +2 -2
- package/workflows/organizations/readModel/dataUsageReadModel.js.map +1 -1
- package/workflows/organizations/readModel/listLocalOrganizations.js +4 -2
- package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
- package/workflows/organizations/readModel/localReadModelDetails.js +8 -9
- package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
- package/workflows/organizations/readModel/organizationPresentationAccessState.js +2 -2
- package/workflows/organizations/readModel/organizationPresentationAccessState.js.map +1 -1
- package/workflows/organizations/readModel/readModelProjection.d.ts +1 -1
- package/workflows/organizations/readModel/readModelProjection.js +12 -13
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/data/persistence/organizations/organizationAccessRevocationPersistence.js +0 -49
- package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +0 -1
- package/data/persistence/organizations/organizationGroupNamePersistence.js +0 -33
- package/data/persistence/organizations/organizationGroupNamePersistence.js.map +0 -1
- package/data/persistence/organizations/organizationProfileDocumentPointers.js +0 -32
- package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +0 -1
- package/data/persistence/organizations/organizationReadModelCursorPersistence.d.ts +0 -15
- package/data/persistence/organizations/organizationReadModelCursorPersistence.js +0 -25
- package/data/persistence/organizations/organizationReadModelCursorPersistence.js.map +0 -1
|
@@ -2,7 +2,7 @@ import { readStoredDocumentState } from "../../../data/documents/documentKinds.j
|
|
|
2
2
|
import { sqlContainerContentsPersistence } from "../../../data/persistence/container-contents/containerContentsPersistence.js";
|
|
3
3
|
import { DOCUMENTS_APP_KIND, sqlDocumentsPersistence, } from "../../../data/persistence/documents/documentsPersistence.js";
|
|
4
4
|
import { DocumentRecordRepository } from "../../../data/persistence/documents/records/index.js";
|
|
5
|
-
import {
|
|
5
|
+
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
6
6
|
import { loadPersistedDocumentContent } from "../../documents/index.js";
|
|
7
7
|
import { getOrganizationProfileDocumentLocalId, readOrganizationProfileName, } from "../organizationProfile.js";
|
|
8
8
|
import { deriveOrganizationMetadataContainerSystemSlot } from "../rosterProfileContainer.js";
|
|
@@ -143,7 +143,9 @@ export async function listLocalOrganizations(input) {
|
|
|
143
143
|
const containers = await sqlContainerContentsPersistence.loadContainers(input.execSql);
|
|
144
144
|
// A projected read model is not a precondition for listing organizations, so
|
|
145
145
|
// an unreadable one degrades to the container-derived lookups below.
|
|
146
|
-
const profileDocumentIdsByOrganizationId = await
|
|
146
|
+
const profileDocumentIdsByOrganizationId = await new OrganizationReadModelRepository(input.execSql)
|
|
147
|
+
.loadOrganizationProfileDocumentIds()
|
|
148
|
+
.catch(() => new Map());
|
|
147
149
|
const organizations = [...indexLocalOrganizations(containers)].sort(compareLocalOrganizations);
|
|
148
150
|
// Read each organization's profile name concurrently; readLocalOrganizationName
|
|
149
151
|
// already falls back to null per organization, so a single corrupt profile
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listLocalOrganizations.js","sourceRoot":"","sources":["listLocalOrganizations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAChF,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,6CAA6C,CAAC;AACvF,OAAO,EAAE,kCAAkC,EAAE,MAAM,6EAA6E,CAAC;AAEjI,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EACL,qCAAqC,EACrC,2BAA2B,GAC5B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,6CAA6C,EAAE,MAAM,2BAA2B,CAAC;AA0B1F,2EAA2E;AAC3E,wEAAwE;AACxE,gFAAgF;AAChF,sDAAsD;AACtD,KAAK,UAAU,gCAAgC,CAC7C,OAAgB,EAChB,eAAuB;IAEvB,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,4BAA4B,CAAC;YAC7C,OAAO;YACP,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AAM,kCAAkC,GACtC,MAAM,kCAAkC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,KAAK,CAC3D,GAAG,EAAE,CAAC,IAAI,GAAG,EAAkB,CAChC,CAAC;IACJ,MAAM,aAAa,GAAG,CAAC,GAAG,uBAAuB,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CACjE,yBAAyB,CAC1B,CAAC;IAEF,gFAAgF;IAChF,2EAA2E;IAC3E,2BAA2B;IAC3B,OAAO,OAAO,CAAC,GAAG,CAChB,aAAa,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,cAAc,EAAE,YAAY,CAAC,EAAE,EAAE,CAAC,CAAC;QAC3D,IAAI,EAAE,MAAM,yBAAyB,CACnC,KAAK,CAAC,OAAO,EACb,cAAc,EACd,YAAY,CAAC,UAAU,EACvB,kCAAkC,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,IAAI,CAC/D;QACD,cAAc;QACd,eAAe,EAAE,YAAY,CAAC,IAAI,EAAE,EAAE,IAAI,IAAI;KAC/C,CAAC,CAAC,CACJ,CAAC;AACJ,CAAC","sourcesContent":["import { readStoredDocumentState } from \"../../../data/documents/documentKinds\";\nimport { sqlContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport {\n DOCUMENTS_APP_KIND,\n sqlDocumentsPersistence,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport { DocumentRecordRepository } from \"../../../data/persistence/documents/records\";\nimport { loadOrganizationProfileDocumentIds } from \"../../../data/persistence/organizations/organizationProfileDocumentPointers\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { loadPersistedDocumentContent } from \"../../documents\";\nimport {\n getOrganizationProfileDocumentLocalId,\n readOrganizationProfileName,\n} from \"../organizationProfile\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"../rosterProfileContainer\";\n\n// Just the container fields this module needs to locate an org's metadata\n// container among the locally-persisted containers.\ninterface LocalContainerForNameLookup {\n id: string;\n systemSlot: string | null;\n}\n\n/**\n * A locally-known organization: one the user holds at least one persisted\n * container of. `name` is the decrypted organization-profile display name when\n * one is stored locally, or null when it has not synced yet.\n *\n * `rootContainerId` is the organization's workspace root when this user can\n * reach it. It is null for an organization the user reaches only through its\n * Members-granted metadata container or through folders shared from beneath a\n * root the user cannot see; such an organization can be browsed but not made\n * the active workspace.\n */\nexport interface LocalOrganizationSummary {\n name: string | null;\n organizationId: string;\n rootContainerId: string | null;\n}\n\n// Reads and decrypts the `name` field of the organization_profile document\n// persisted under `documentLocalId`, or null if it is absent, empty, or\n// unparseable. A single corrupt profile must not break the whole list, so every\n// failure collapses to a null (unnamed) organization.\nasync function readOrganizationNameFromDocument(\n execSql: ExecSql,\n documentLocalId: string,\n): Promise<string | null> {\n try {\n const doc = await loadPersistedDocumentContent({\n execSql,\n localId: documentLocalId,\n persistence: sqlDocumentsPersistence,\n });\n if (!doc) {\n return null;\n }\n\n return readOrganizationProfileName(\n readStoredDocumentState(doc).structuredFields,\n );\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves an organization's decrypted display name from local state.\n *\n * The same organization_profile document is addressed by several different\n * local-id conventions depending on how it arrived, so one lookup by id is not\n * enough:\n *\n * - The org's own **provisioner** (and any admin who later edits the name)\n * writes the document under the deterministic alias\n * `org-profile:<organizationId>` — resolved by the fast path below.\n * - A **device that only synced it** — a member of another org, or this same\n * user's freshly re-hydrated device after an identity restore — never runs\n * that write. The sync ingest keys the document under the server documentId\n * (there is no local alias to reuse — see `upsertDiscoveredDocumentWithExec`),\n * so the alias lookup misses.\n *\n * Two fallbacks cover the synced case, in order of authority:\n *\n * 1. The **organization read model** records the org's `profileDocumentId`.\n * That pointer is container-independent, so it resolves the name wherever\n * the document happens to be linked — including a profile document created\n * by an admin through the org-manager editor rather than by provisioning.\n * 2. Failing that, locate the org's metadata container by its deterministic\n * system slot and read whichever profile document is linked there. Keying on\n * the system slot (rather than the document kind) keeps it correct even\n * before the projected document kind has been rebuilt from a freshly-synced\n * snapshot, and it still works before the read model has been projected.\n */\nasync function readLocalOrganizationName(\n execSql: ExecSql,\n organizationId: string,\n organizationContainers: ReadonlyArray<LocalContainerForNameLookup>,\n profileDocumentId: string | null,\n): Promise<string | null> {\n const aliasName = await readOrganizationNameFromDocument(\n execSql,\n getOrganizationProfileDocumentLocalId({ organizationId }),\n );\n if (aliasName !== null) {\n return aliasName;\n }\n\n if (profileDocumentId) {\n // Reach the row wherever it landed: a device that only synced the document\n // keys it under the server documentId rather than any local alias.\n const syncedLocalId = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, profileDocumentId);\n const syncedName = syncedLocalId\n ? await readOrganizationNameFromDocument(execSql, syncedLocalId)\n : null;\n if (syncedName !== null) {\n return syncedName;\n }\n }\n\n const metadataSystemSlot =\n await deriveOrganizationMetadataContainerSystemSlot({ organizationId });\n const metadataContainer = organizationContainers.find(\n (container) => container.systemSlot === metadataSystemSlot,\n );\n if (!metadataContainer) {\n return null;\n }\n\n const documentLocalIds =\n await sqlDocumentsPersistence.findDocumentLocalIdsByContainerId(\n execSql,\n metadataContainer.id,\n );\n for (const documentLocalId of documentLocalIds) {\n const name = await readOrganizationNameFromDocument(\n execSql,\n documentLocalId,\n );\n if (name !== null) {\n return name;\n }\n }\n return null;\n}\n\ninterface LocalOrganizationContainers {\n readonly containers: LocalContainerForNameLookup[];\n earliestLocalCreatedAt: string;\n root: { readonly id: string; readonly localCreatedAt: string } | null;\n}\n\ntype PersistedContainers = Awaited<\n ReturnType<typeof sqlContainerContentsPersistence.loadContainers>\n>;\n\n// Groups every persisted container by organization, keeping the first\n// workspace root (a parentless, non-system container) and the earliest local\n// creation time. Name resolution reuses the grouped containers to locate an\n// organization's independent metadata root without a second DB scan.\nfunction indexLocalOrganizations(\n containers: PersistedContainers,\n): Map<string, LocalOrganizationContainers> {\n const organizations = new Map<string, LocalOrganizationContainers>();\n for (const { container } of containers) {\n const localCreatedAt = container.localCreatedAt ?? \"\";\n let organization = organizations.get(container.organizationId);\n if (!organization) {\n organization = {\n containers: [],\n earliestLocalCreatedAt: localCreatedAt,\n root: null,\n };\n organizations.set(container.organizationId, organization);\n }\n organization.containers.push({\n id: container.id,\n systemSlot: container.systemSlot ?? null,\n });\n if (localCreatedAt < organization.earliestLocalCreatedAt) {\n organization.earliestLocalCreatedAt = localCreatedAt;\n }\n if (\n organization.root === null &&\n container.parentId === null &&\n !container.systemSlot\n ) {\n organization.root = { id: container.id, localCreatedAt };\n }\n }\n return organizations;\n}\n\n// Workspaces (organizations with a reachable root) come first in root\n// creation order, so the personal organization provisioned with this device\n// keeps its place. Organizations reached without a root follow in the order\n// their first container arrived locally.\nfunction compareLocalOrganizations(\n [leftId, left]: [string, LocalOrganizationContainers],\n [rightId, right]: [string, LocalOrganizationContainers],\n): number {\n if (left.root && right.root) {\n return (\n left.root.localCreatedAt.localeCompare(right.root.localCreatedAt) ||\n leftId.localeCompare(rightId) ||\n left.root.id.localeCompare(right.root.id)\n );\n }\n if (left.root || right.root) {\n return left.root ? -1 : 1;\n }\n return (\n left.earliestLocalCreatedAt.localeCompare(right.earliestLocalCreatedAt) ||\n leftId.localeCompare(rightId)\n );\n}\n\n/**\n * Enumerates every organization the user holds a persisted container of, from\n * local state alone. This is intentionally offline: membership is visible\n * locally because every Members recipient can read the organization's metadata\n * root, and shared folders arrive with their organization attached, so listing\n * organizations needs no server round-trip.\n */\nexport async function listLocalOrganizations(input: {\n execSql: ExecSql;\n}): Promise<LocalOrganizationSummary[]> {\n const containers = await sqlContainerContentsPersistence.loadContainers(\n input.execSql,\n );\n // A projected read model is not a precondition for listing organizations, so\n // an unreadable one degrades to the container-derived lookups below.\n const profileDocumentIdsByOrganizationId =\n await loadOrganizationProfileDocumentIds(input.execSql).catch(\n () => new Map<string, string>(),\n );\n const organizations = [...indexLocalOrganizations(containers)].sort(\n compareLocalOrganizations,\n );\n\n // Read each organization's profile name concurrently; readLocalOrganizationName\n // already falls back to null per organization, so a single corrupt profile\n // cannot reject the batch.\n return Promise.all(\n organizations.map(async ([organizationId, organization]) => ({\n name: await readLocalOrganizationName(\n input.execSql,\n organizationId,\n organization.containers,\n profileDocumentIdsByOrganizationId.get(organizationId) ?? null,\n ),\n organizationId,\n rootContainerId: organization.root?.id ?? null,\n })),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"listLocalOrganizations.js","sourceRoot":"","sources":["listLocalOrganizations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAChF,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,6CAA6C,CAAC;AACvF,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAE1H,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EACL,qCAAqC,EACrC,2BAA2B,GAC5B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,6CAA6C,EAAE,MAAM,2BAA2B,CAAC;AA0B1F,2EAA2E;AAC3E,wEAAwE;AACxE,gFAAgF;AAChF,sDAAsD;AACtD,KAAK,UAAU,gCAAgC,CAC7C,OAAgB,EAChB,eAAuB;IAEvB,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,4BAA4B,CAAC;YAC7C,OAAO;YACP,OAAO,EAAE,eAAe;YACxB,WAAW,EAAE,uBAAuB;SACrC,CAAC,CAAC;QACH,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,2BAA2B,CAChC,uBAAuB,CAAC,GAAG,CAAC,CAAC,gBAAgB,CAC9C,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;;;;;;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E,2BAA2B;IAC3B,OAAO,OAAO,CAAC,GAAG,CAChB,aAAa,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,cAAc,EAAE,YAAY,CAAC,EAAE,EAAE,CAAC,CAAC;QAC3D,IAAI,EAAE,MAAM,yBAAyB,CACnC,KAAK,CAAC,OAAO,EACb,cAAc,EACd,YAAY,CAAC,UAAU,EACvB,kCAAkC,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,IAAI,CAC/D;QACD,cAAc;QACd,eAAe,EAAE,YAAY,CAAC,IAAI,EAAE,EAAE,IAAI,IAAI;KAC/C,CAAC,CAAC,CACJ,CAAC;AACJ,CAAC","sourcesContent":["import { readStoredDocumentState } from \"../../../data/documents/documentKinds\";\nimport { sqlContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport {\n DOCUMENTS_APP_KIND,\n sqlDocumentsPersistence,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport { DocumentRecordRepository } from \"../../../data/persistence/documents/records\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { loadPersistedDocumentContent } from \"../../documents\";\nimport {\n getOrganizationProfileDocumentLocalId,\n readOrganizationProfileName,\n} from \"../organizationProfile\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"../rosterProfileContainer\";\n\n// Just the container fields this module needs to locate an org's metadata\n// container among the locally-persisted containers.\ninterface LocalContainerForNameLookup {\n id: string;\n systemSlot: string | null;\n}\n\n/**\n * A locally-known organization: one the user holds at least one persisted\n * container of. `name` is the decrypted organization-profile display name when\n * one is stored locally, or null when it has not synced yet.\n *\n * `rootContainerId` is the organization's workspace root when this user can\n * reach it. It is null for an organization the user reaches only through its\n * Members-granted metadata container or through folders shared from beneath a\n * root the user cannot see; such an organization can be browsed but not made\n * the active workspace.\n */\nexport interface LocalOrganizationSummary {\n name: string | null;\n organizationId: string;\n rootContainerId: string | null;\n}\n\n// Reads and decrypts the `name` field of the organization_profile document\n// persisted under `documentLocalId`, or null if it is absent, empty, or\n// unparseable. A single corrupt profile must not break the whole list, so every\n// failure collapses to a null (unnamed) organization.\nasync function readOrganizationNameFromDocument(\n execSql: ExecSql,\n documentLocalId: string,\n): Promise<string | null> {\n try {\n const doc = await loadPersistedDocumentContent({\n execSql,\n localId: documentLocalId,\n persistence: sqlDocumentsPersistence,\n });\n if (!doc) {\n return null;\n }\n\n return readOrganizationProfileName(\n readStoredDocumentState(doc).structuredFields,\n );\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves an organization's decrypted display name from local state.\n *\n * The same organization_profile document is addressed by several different\n * local-id conventions depending on how it arrived, so one lookup by id is not\n * enough:\n *\n * - The org's own **provisioner** (and any admin who later edits the name)\n * writes the document under the deterministic alias\n * `org-profile:<organizationId>` — resolved by the fast path below.\n * - A **device that only synced it** — a member of another org, or this same\n * user's freshly re-hydrated device after an identity restore — never runs\n * that write. The sync ingest keys the document under the server documentId\n * (there is no local alias to reuse — see `upsertDiscoveredDocumentWithExec`),\n * so the alias lookup misses.\n *\n * Two fallbacks cover the synced case, in order of authority:\n *\n * 1. The **organization read model** records the org's `profileDocumentId`.\n * That pointer is container-independent, so it resolves the name wherever\n * the document happens to be linked — including a profile document created\n * by an admin through the org-manager editor rather than by provisioning.\n * 2. Failing that, locate the org's metadata container by its deterministic\n * system slot and read whichever profile document is linked there. Keying on\n * the system slot (rather than the document kind) keeps it correct even\n * before the projected document kind has been rebuilt from a freshly-synced\n * snapshot, and it still works before the read model has been projected.\n */\nasync function readLocalOrganizationName(\n execSql: ExecSql,\n organizationId: string,\n organizationContainers: ReadonlyArray<LocalContainerForNameLookup>,\n profileDocumentId: string | null,\n): Promise<string | null> {\n const aliasName = await readOrganizationNameFromDocument(\n execSql,\n getOrganizationProfileDocumentLocalId({ organizationId }),\n );\n if (aliasName !== null) {\n return aliasName;\n }\n\n if (profileDocumentId) {\n // Reach the row wherever it landed: a device that only synced the document\n // keys it under the server documentId rather than any local alias.\n const syncedLocalId = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, profileDocumentId);\n const syncedName = syncedLocalId\n ? await readOrganizationNameFromDocument(execSql, syncedLocalId)\n : null;\n if (syncedName !== null) {\n return syncedName;\n }\n }\n\n const metadataSystemSlot =\n await deriveOrganizationMetadataContainerSystemSlot({ organizationId });\n const metadataContainer = organizationContainers.find(\n (container) => container.systemSlot === metadataSystemSlot,\n );\n if (!metadataContainer) {\n return null;\n }\n\n const documentLocalIds =\n await sqlDocumentsPersistence.findDocumentLocalIdsByContainerId(\n execSql,\n metadataContainer.id,\n );\n for (const documentLocalId of documentLocalIds) {\n const name = await readOrganizationNameFromDocument(\n execSql,\n documentLocalId,\n );\n if (name !== null) {\n return name;\n }\n }\n return null;\n}\n\ninterface LocalOrganizationContainers {\n readonly containers: LocalContainerForNameLookup[];\n earliestLocalCreatedAt: string;\n root: { readonly id: string; readonly localCreatedAt: string } | null;\n}\n\ntype PersistedContainers = Awaited<\n ReturnType<typeof sqlContainerContentsPersistence.loadContainers>\n>;\n\n// Groups every persisted container by organization, keeping the first\n// workspace root (a parentless, non-system container) and the earliest local\n// creation time. Name resolution reuses the grouped containers to locate an\n// organization's independent metadata root without a second DB scan.\nfunction indexLocalOrganizations(\n containers: PersistedContainers,\n): Map<string, LocalOrganizationContainers> {\n const organizations = new Map<string, LocalOrganizationContainers>();\n for (const { container } of containers) {\n const localCreatedAt = container.localCreatedAt ?? \"\";\n let organization = organizations.get(container.organizationId);\n if (!organization) {\n organization = {\n containers: [],\n earliestLocalCreatedAt: localCreatedAt,\n root: null,\n };\n organizations.set(container.organizationId, organization);\n }\n organization.containers.push({\n id: container.id,\n systemSlot: container.systemSlot ?? null,\n });\n if (localCreatedAt < organization.earliestLocalCreatedAt) {\n organization.earliestLocalCreatedAt = localCreatedAt;\n }\n if (\n organization.root === null &&\n container.parentId === null &&\n !container.systemSlot\n ) {\n organization.root = { id: container.id, localCreatedAt };\n }\n }\n return organizations;\n}\n\n// Workspaces (organizations with a reachable root) come first in root\n// creation order, so the personal organization provisioned with this device\n// keeps its place. Organizations reached without a root follow in the order\n// their first container arrived locally.\nfunction compareLocalOrganizations(\n [leftId, left]: [string, LocalOrganizationContainers],\n [rightId, right]: [string, LocalOrganizationContainers],\n): number {\n if (left.root && right.root) {\n return (\n left.root.localCreatedAt.localeCompare(right.root.localCreatedAt) ||\n leftId.localeCompare(rightId) ||\n left.root.id.localeCompare(right.root.id)\n );\n }\n if (left.root || right.root) {\n return left.root ? -1 : 1;\n }\n return (\n left.earliestLocalCreatedAt.localeCompare(right.earliestLocalCreatedAt) ||\n leftId.localeCompare(rightId)\n );\n}\n\n/**\n * Enumerates every organization the user holds a persisted container of, from\n * local state alone. This is intentionally offline: membership is visible\n * locally because every Members recipient can read the organization's metadata\n * root, and shared folders arrive with their organization attached, so listing\n * organizations needs no server round-trip.\n */\nexport async function listLocalOrganizations(input: {\n execSql: ExecSql;\n}): Promise<LocalOrganizationSummary[]> {\n const containers = await sqlContainerContentsPersistence.loadContainers(\n input.execSql,\n );\n // A projected read model is not a precondition for listing organizations, so\n // an unreadable one degrades to the container-derived lookups below.\n const profileDocumentIdsByOrganizationId =\n await new OrganizationReadModelRepository(input.execSql)\n .loadOrganizationProfileDocumentIds()\n .catch(() => new Map<string, string>());\n const organizations = [...indexLocalOrganizations(containers)].sort(\n compareLocalOrganizations,\n );\n\n // Read each organization's profile name concurrently; readLocalOrganizationName\n // already falls back to null per organization, so a single corrupt profile\n // cannot reject the batch.\n return Promise.all(\n organizations.map(async ([organizationId, organization]) => ({\n name: await readLocalOrganizationName(\n input.execSql,\n organizationId,\n organization.containers,\n profileDocumentIdsByOrganizationId.get(organizationId) ?? null,\n ),\n organizationId,\n rootContainerId: organization.root?.id ?? null,\n })),\n );\n}\n"]}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { loadContainerDisplayNamesByIds } from "../../../data/persistence/container-contents/containerPersistence.js";
|
|
2
|
-
import {
|
|
3
|
-
import { loadOrganizationReadModelProjection } from "../../../data/persistence/organizations/organizationReadModelPersistence.js";
|
|
2
|
+
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
4
3
|
import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
|
|
5
4
|
import { loadVerifiedOrganizationGroupRoles } from "../../../data/principals/organizationGroupRoles.js";
|
|
6
5
|
import { buildOrganizationGroupPolicyHistory, buildOrganizationPolicyHistory, } from "../policyHistory/policyHistoryReadModel.js";
|
|
@@ -11,7 +10,7 @@ function uniqueContainerIds(grants) {
|
|
|
11
10
|
}
|
|
12
11
|
async function enrichGrants(execSql, grants, organizationId) {
|
|
13
12
|
const containerIds = uniqueContainerIds(grants);
|
|
14
|
-
const groupNames = await loadOrganizationGroupDisplayNames(
|
|
13
|
+
const groupNames = await new OrganizationReadModelRepository(execSql).loadOrganizationGroupDisplayNames(organizationId);
|
|
15
14
|
const groupRoles = await loadVerifiedOrganizationGroupRoles(execSql, organizationId);
|
|
16
15
|
const displayNames = new Map();
|
|
17
16
|
for (let index = 0; index < containerIds.length; index += DISPLAY_NAME_BATCH_SIZE) {
|
|
@@ -58,7 +57,7 @@ function reachableGroupIds(input) {
|
|
|
58
57
|
}
|
|
59
58
|
export async function loadLocalOrganizationContainerGrants(input) {
|
|
60
59
|
return runOrganizationPresentationRead({ ...input, requesterUserId: input.currentUserId }, "readModel", async () => {
|
|
61
|
-
const projection = await
|
|
60
|
+
const projection = await new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelProjection(input.organizationId, input.currentUserId);
|
|
62
61
|
if (!projection?.requester) {
|
|
63
62
|
return null;
|
|
64
63
|
}
|
|
@@ -70,7 +69,7 @@ export async function loadLocalOrganizationContainerGrants(input) {
|
|
|
70
69
|
}
|
|
71
70
|
export async function loadLocalOrganizationGroupContainers(input) {
|
|
72
71
|
return runOrganizationPresentationRead({ ...input, requesterUserId: input.currentUserId }, "readModel", async () => {
|
|
73
|
-
const projection = await
|
|
72
|
+
const projection = await new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelProjection(input.organizationId, input.currentUserId);
|
|
74
73
|
if (!projection?.requester) {
|
|
75
74
|
return null;
|
|
76
75
|
}
|
|
@@ -89,7 +88,7 @@ export async function loadLocalOrganizationGroupContainers(input) {
|
|
|
89
88
|
}
|
|
90
89
|
export async function loadLocalOrganizationGroupPolicyHistory(input) {
|
|
91
90
|
return runOrganizationPresentationRead({ ...input, requesterUserId: input.currentUserId }, "readModel", async () => {
|
|
92
|
-
const projection = await
|
|
91
|
+
const projection = await new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelProjection(input.organizationId, input.currentUserId);
|
|
93
92
|
if (!projection?.requester) {
|
|
94
93
|
return null;
|
|
95
94
|
}
|
|
@@ -116,7 +115,7 @@ function policyBundleMatchesProjectedHead(bundle, projectedHead) {
|
|
|
116
115
|
}
|
|
117
116
|
export async function loadLocalOrganizationPolicyHistory(input) {
|
|
118
117
|
return runOrganizationPresentationRead({ ...input, requesterUserId: input.currentUserId }, "readModel", async () => {
|
|
119
|
-
const projection = await
|
|
118
|
+
const projection = await new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelProjection(input.organizationId, input.currentUserId);
|
|
120
119
|
if (!projection?.requester) {
|
|
121
120
|
return null;
|
|
122
121
|
}
|
|
@@ -133,7 +132,7 @@ export async function loadLocalOrganizationPolicyHistory(input) {
|
|
|
133
132
|
}
|
|
134
133
|
export async function loadLocalOrganizationPolicyReference(input) {
|
|
135
134
|
return runOrganizationPresentationRead({ ...input, requesterUserId: input.currentUserId }, "readModel", async () => {
|
|
136
|
-
const projection = await
|
|
135
|
+
const projection = await new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelProjection(input.organizationId, input.currentUserId);
|
|
137
136
|
if (!projection?.requester) {
|
|
138
137
|
return null;
|
|
139
138
|
}
|
|
@@ -153,7 +152,7 @@ export async function loadLocalOrganizationPolicyReference(input) {
|
|
|
153
152
|
}
|
|
154
153
|
export async function loadLocalOrganizationUserDetail(input) {
|
|
155
154
|
return runOrganizationPresentationRead({ ...input, requesterUserId: input.currentUserId }, "readModel", async () => {
|
|
156
|
-
const projection = await
|
|
155
|
+
const projection = await new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelProjection(input.organizationId, input.currentUserId);
|
|
157
156
|
const user = projection?.directory.users.find((candidate) => candidate.userId === input.userId);
|
|
158
157
|
if (!projection?.requester || !user) {
|
|
159
158
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDetails.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mEAAmE,CAAC;AACnH,OAAO,EAAE,iCAAiC,EAAE,MAAM,0EAA0E,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAAE,MAAM,0EAA0E,CAAC;AAC/H,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAErG,OAAO,EACL,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,yCAAyC,CAAC;AAUjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAUxF,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,SAAS,kBAAkB,CACzB,MAAqD;IAErD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,KAAK,UAAU,YAAY,CACzB,OAAgB,EAChB,MAAqD,EACrD,cAAsB;IAEtB,MAAM,YAAY,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAChD,MAAM,UAAU,GAAG,MAAM,iC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ipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { loadOrganizationGroupDisplayNames } from \"../../../data/persistence/organizations/organizationGroupNamePersistence\";\nimport { loadOrganizationReadModelProjection } from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await loadOrganizationGroupDisplayNames(\n execSql,\n organizationId,\n );\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"group\", input.groupId);\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"localReadModelDetails.js","sourceRoot":"","sources":["localReadModelDetails.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mEAAmE,CAAC;AACnH,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAC1H,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AAErG,OAAO,EACL,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,yCAAyC,CAAC;AAUjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAUxF,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,SAAS,kBAAkB,CACzB,MAAqD;IAErD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,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ACN,YAAY,EAAE,MAAM,CAAC,MAAM,CACzB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,MAAM,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,CACnE;gBACD,WAAW,EAAE,MAAM,CAAC,MAAM,CACxB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAClE;aACF;SACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n OrganizationContainerGrantResponse,\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { loadContainerDisplayNamesByIds } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { loadVerifiedOrganizationGroupRoles } from \"../../../data/principals/organizationGroupRoles\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationGroupPolicyHistory,\n buildOrganizationPolicyHistory,\n} from \"../policyHistory/policyHistoryReadModel\";\nimport type {\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationUserDetail,\n} from \"./index\";\nimport { runOrganizationPresentationRead } from \"./organizationPresentationAccessState\";\n\ninterface LocalReadModelInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\ntype PolicyPrincipalType = ReferencedPrincipalStateResponse[\"principalType\"];\n\nconst DISPLAY_NAME_BATCH_SIZE = 400;\n\nfunction uniqueContainerIds(\n grants: readonly OrganizationContainerGrantResponse[],\n): string[] {\n return [...new Set(grants.map((grant) => grant.containerId))];\n}\n\nasync function enrichGrants(\n execSql: ExecSql,\n grants: readonly OrganizationContainerGrantResponse[],\n organizationId: string,\n): Promise<OrganizationContainerGrant[]> {\n const containerIds = uniqueContainerIds(grants);\n const groupNames = await new OrganizationReadModelRepository(\n execSql,\n ).loadOrganizationGroupDisplayNames(organizationId);\n const groupRoles = await loadVerifiedOrganizationGroupRoles(\n execSql,\n organizationId,\n );\n const displayNames = new Map<string, string>();\n for (\n let index = 0;\n index < containerIds.length;\n index += DISPLAY_NAME_BATCH_SIZE\n ) {\n const batch = await loadContainerDisplayNamesByIds(\n execSql,\n containerIds.slice(index, index + DISPLAY_NAME_BATCH_SIZE),\n );\n for (const [containerId, displayName] of batch) {\n displayNames.set(containerId, displayName);\n }\n }\n return grants.map((grant) => ({\n ...grant,\n containerDisplayName: displayNames.get(grant.containerId) ?? null,\n groupName:\n grant.subjectType === \"group\"\n ? (groupRoles.get(grant.subjectId) ??\n groupNames.get(grant.subjectId) ??\n null)\n : null,\n }));\n}\n\nfunction toGroupContainer(\n grant: OrganizationContainerGrant,\n): OrganizationGroupContainer {\n return {\n accessLevel: grant.accessLevel,\n containerId: grant.containerId,\n containerDisplayName: grant.containerDisplayName,\n createdAt: grant.createdAt,\n depth: grant.depth,\n isBuiltin: grant.isBuiltin,\n metadataAccessEpoch: grant.metadataAccessEpoch,\n metadataAccessStateHash: grant.metadataAccessStateHash,\n metadataDocumentId: grant.metadataDocumentId,\n parentId: grant.parentId,\n updatedAt: grant.updatedAt,\n };\n}\n\n/**\n * The groups a user belongs to is exactly the set naming them as a member.\n *\n * This used to be a breadth-first walk over group-in-group edges. Groups\n * contain only users now, so the walk had no second level to visit.\n */\nfunction reachableGroupIds(input: {\n readonly edges: ReadonlyArray<{\n readonly groupId: string;\n readonly userId: string;\n }>;\n readonly userId: string;\n}): Set<string> {\n return new Set(\n input.edges\n .filter((edge) => edge.userId === input.userId)\n .map((edge) => edge.groupId),\n );\n}\n\nexport async function loadLocalOrganizationContainerGrants(\n input: LocalReadModelInput,\n): Promise<OrganizationContainerGrants | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n return {\n organizationId: input.organizationId,\n grants: await enrichGrants(\n input.execSql,\n projection.grants.grants,\n input.organizationId,\n ),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupContainers(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupContainers | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const groupIsInOrganization =\n input.groupId === projection.groups.memberGroupId ||\n projection.groups.groups.some(\n (group) => group.groupId === input.groupId,\n );\n if (!groupIsInOrganization) {\n return null;\n }\n const grants = projection.grants.grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n );\n return {\n organizationId: input.organizationId,\n groupId: input.groupId,\n containers: (\n await enrichGrants(input.execSql, grants, input.organizationId)\n ).map(toGroupContainer),\n };\n },\n );\n}\n\nexport async function loadLocalOrganizationGroupPolicyHistory(\n input: LocalReadModelInput & { readonly groupId: string },\n): Promise<OrganizationGroupPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n );\n if (!projectedHead) {\n return null;\n }\n\n const bundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"group\", input.groupId);\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationGroupPolicyHistory(bundle, input.organizationId)\n : null;\n },\n );\n}\n\nfunction policyBundleMatchesProjectedHead(\n bundle: PrincipalPolicyBundleResponse | null,\n projectedHead: {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n readonly stateHash: string;\n readonly version: number;\n },\n): bundle is PrincipalPolicyBundleResponse {\n const storedHead = bundle?.currentState;\n return Boolean(\n storedHead &&\n storedHead.principalType === projectedHead.principalType &&\n storedHead.principalId === projectedHead.principalId &&\n storedHead.stateHash === projectedHead.stateHash &&\n storedHead.version === projectedHead.version &&\n storedHead.keyEpoch === projectedHead.keyEpoch &&\n storedHead.keyFingerprint === projectedHead.keyFingerprint &&\n storedHead.memberCount === projectedHead.memberCount,\n );\n}\n\nexport async function loadLocalOrganizationPolicyHistory(\n input: LocalReadModelInput,\n): Promise<OrganizationPolicyHistory | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const projectedHead = projection.policyHeads.find(\n (head) =>\n head.principalType === \"organization\" &&\n head.principalId === input.organizationId,\n );\n if (!projectedHead) {\n return null;\n }\n const bundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n return policyBundleMatchesProjectedHead(bundle, projectedHead)\n ? buildOrganizationPolicyHistory(bundle)\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationPolicyReference(\n input: LocalReadModelInput & {\n readonly principalId: string;\n readonly principalType: PolicyPrincipalType;\n },\n): Promise<ReferencedPrincipalStateResponse | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n if (!projection?.requester) {\n return null;\n }\n const head = projection.policyHeads.find(\n (candidate) =>\n candidate.principalType === input.principalType &&\n candidate.principalId === input.principalId,\n );\n return head\n ? {\n principalType: head.principalType,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n }\n : null;\n },\n );\n}\n\nexport async function loadLocalOrganizationUserDetail(\n input: LocalReadModelInput & { readonly userId: string },\n): Promise<OrganizationUserDetail | null> {\n return runOrganizationPresentationRead(\n { ...input, requesterUserId: input.currentUserId },\n \"readModel\",\n async () => {\n const projection = await new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n const user = projection?.directory.users.find(\n (candidate) => candidate.userId === input.userId,\n );\n if (!projection?.requester || !user) {\n return null;\n }\n\n const reachable = reachableGroupIds({\n edges: projection.membershipEdges,\n userId: input.userId,\n });\n const groups = projection.groups.groups\n .filter((group) => reachable.has(group.groupId))\n .map((group) => ({ ...group, nameUnreadable: false }));\n const relevantGrants = projection.grants.grants.filter(\n (grant) =>\n (grant.subjectType === \"user\" && grant.subjectId === input.userId) ||\n (grant.subjectType === \"group\" && reachable.has(grant.subjectId)),\n );\n const grants = await enrichGrants(\n input.execSql,\n relevantGrants,\n input.organizationId,\n );\n return {\n organizationId: input.organizationId,\n user,\n groups,\n grants: {\n directGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"user\" && grant.subjectId === input.userId,\n ),\n groupGrants: grants.filter(\n (grant) =>\n grant.subjectType === \"group\" && reachable.has(grant.subjectId),\n ),\n },\n };\n },\n );\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
2
2
|
const accessByExecutor = new WeakMap();
|
|
3
3
|
export function organizationAccessScopeKey(organizationId, requesterUserId) {
|
|
4
4
|
return JSON.stringify([organizationId, requesterUserId]);
|
|
@@ -105,7 +105,7 @@ export async function runOrganizationPresentationRead(input, projection, operati
|
|
|
105
105
|
// In-memory denial dies with the process. The durable marker keeps a
|
|
106
106
|
// revoked projection unreadable when its purge failed and the app
|
|
107
107
|
// restarted; a successful reconcile clears it.
|
|
108
|
-
if (await hasOrganizationPresentationDenial(input, projection)) {
|
|
108
|
+
if (await new OrganizationReadModelRepository(input.execSql).hasOrganizationPresentationDenial(input, projection)) {
|
|
109
109
|
return null;
|
|
110
110
|
}
|
|
111
111
|
const value = await operation();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationPresentationAccessState.js","sourceRoot":"","sources":["organizationPresentationAccessState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,mFAAmF,CAAC;AA4CtI,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAgC,CAAC;AAErE,MAAM,UAAU,0BAA0B,CACxC,cAAsB,EACtB,eAAuB;IAEvB,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,cAAc,EAAE,eAAe,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED,SAAS,mBAAmB,CAAC,OAAgB;IAC3C,IAAI,KAAK,GAAG,gBAAgB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC1C,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,KAAK,GAAG;YACN,wBAAwB,EAAE,IAAI,GAAG,EAAE;YACnC,wBAAwB,EAAE,IAAI,GAAG,EAAE;YACnC,MAAM,EAAE,IAAI,GAAG,EAAE;SAClB,CAAC;QACF,gBAAgB,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;IACD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C,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IACxD,MAAM,aAAa,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC;IAC1D,QAAQ,CAAC,aAAa,GAAG,aAAa,CAAC;IACvC,MAAM,eAAe,CAAC;IAEtB,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,EAAE,CAAC;IAC3B,CAAC;YAAS,CAAC;QACT,cAAc,EAAE,CAAC;QACjB,IAAI,QAAQ,CAAC,aAAa,KAAK,aAAa,EAAE,CAAC;YAC7C,QAAQ,CAAC,aAAa,GAAG,SAAS,CAAC;QACrC,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,OAAgB,EAChB,cAAsB,EACtB,SAA2B;IAE3B,wCAAwC,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;IAClE,IAAI,CAAC;QACH,OAAO,MAAM,mCAAmC,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACvE,CAAC;YAAS,CAAC;QACT,yCAAyC,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;IACrE,CAAC;AACH,CAAC","sourcesContent":["import { hasOrganizationPresentationDenial } from \"../../../data/persistence/organizations/organizationPresentationDenialPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\nexport type OrganizationPresentationProjection = \"readModel\" | \"usage\";\n\nexport interface OrganizationPresentationAccessInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly requesterUserId: string;\n}\n\ninterface ProjectionAccessState {\n denied: boolean;\n /**\n * True only when the server itself denied the projection (a 403/404 read).\n * A session reset also flips `denied`, but that is a local lifecycle event —\n * consumers reacting specifically to lost-then-regained org access (e.g.\n * re-arming write lanes) must not treat a routine reset as a denial.\n */\n deniedByServer: boolean;\n generation: number;\n}\n\ninterface AccessScopeState {\n readonly organizationId: string;\n readonly readModel: ProjectionAccessState;\n readonly usage: ProjectionAccessState;\n}\n\ninterface AccessExecutorState {\n readonly generationByOrganization: Map<string, number>;\n mutationQueue?: Promise<void> | undefined;\n readonly resetDepthByOrganization: Map<string, number>;\n readonly scopes: Map<string, AccessScopeState>;\n}\n\nexport interface OrganizationPresentationAccessAttempt {\n readonly executorGeneration: number;\n readonly projection: OrganizationPresentationProjection;\n readonly projectionGeneration: number;\n readonly startedDenied: boolean;\n readonly startedDuringReset: boolean;\n}\n\nconst accessByExecutor = new WeakMap<ExecSql, AccessExecutorState>();\n\nexport function organizationAccessScopeKey(\n organizationId: string,\n requesterUserId: string,\n): string {\n return JSON.stringify([organizationId, requesterUserId]);\n}\n\nfunction accessExecutorState(execSql: ExecSql): AccessExecutorState {\n let state = accessByExecutor.get(execSql);\n if (!state) {\n state = {\n generationByOrganization: new Map(),\n resetDepthByOrganization: new Map(),\n scopes: new Map(),\n };\n accessByExecutor.set(execSql, state);\n }\n return state;\n}\n\nfunction newProjectionState(denied: boolean): ProjectionAccessState {\n return { denied, deniedByServer: false, generation: 0 };\n}\n\nfunction organizationResetDepth(\n executor: AccessExecutorState,\n organizationId: string,\n): number {\n return executor.resetDepthByOrganization.get(organizationId) ?? 0;\n}\n\nfunction organizationGeneration(\n executor: AccessExecutorState,\n organizationId: string,\n): number {\n return executor.generationByOrganization.get(organizationId) ?? 0;\n}\n\nfunction accessScopeState(\n executor: AccessExecutorState,\n organizationId: string,\n requesterUserId: string,\n): AccessScopeState {\n const key = organizationAccessScopeKey(organizationId, requesterUserId);\n let scope = executor.scopes.get(key);\n if (!scope) {\n const denied = organizationResetDepth(executor, organizationId) > 0;\n scope = {\n organizationId,\n readModel: newProjectionState(denied),\n usage: newProjectionState(denied),\n };\n executor.scopes.set(key, scope);\n }\n return scope;\n}\n\nfunction projectionState(\n scope: AccessScopeState,\n projection: OrganizationPresentationProjection,\n): ProjectionAccessState {\n return scope[projection];\n}\n\nexport function captureOrganizationPresentationAccessAttempt(\n input: OrganizationPresentationAccessInput,\n projection: OrganizationPresentationProjection,\n): OrganizationPresentationAccessAttempt {\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n projection,\n );\n return {\n executorGeneration: organizationGeneration(executor, input.organizationId),\n projection,\n projectionGeneration: state.generation,\n startedDenied: state.denied,\n startedDuringReset:\n organizationResetDepth(executor, input.organizationId) > 0,\n };\n}\n\nexport function isOrganizationPresentationAccessAttemptCurrent(\n input: OrganizationPresentationAccessInput,\n attempt: OrganizationPresentationAccessAttempt,\n): boolean {\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n attempt.projection,\n );\n return (\n !attempt.startedDuringReset &&\n organizationResetDepth(executor, input.organizationId) === 0 &&\n organizationGeneration(executor, input.organizationId) ===\n attempt.executorGeneration &&\n state.generation === attempt.projectionGeneration\n );\n}\n\nexport function isOrganizationPresentationAccessReadable(\n input: OrganizationPresentationAccessInput,\n projection: OrganizationPresentationProjection,\n): boolean {\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n projection,\n );\n return (\n organizationResetDepth(executor, input.organizationId) === 0 &&\n !state.denied\n );\n}\n\nexport function denyOrganizationPresentationAccess(\n input: OrganizationPresentationAccessInput,\n projections: readonly OrganizationPresentationProjection[],\n): void {\n const executor = accessExecutorState(input.execSql);\n const scope = accessScopeState(\n executor,\n input.organizationId,\n input.requesterUserId,\n );\n for (const projection of new Set(projections)) {\n const state = projectionState(scope, projection);\n state.denied = true;\n state.deniedByServer = true;\n state.generation += 1;\n }\n}\n\n/**\n * Whether the scope's projection is currently denied because the server\n * refused it (as opposed to a local session reset). The flip back to readable\n * after this returns true is the \"org access was just restored\" edge.\n */\nexport function wasOrganizationPresentationAccessDeniedByServer(\n input: OrganizationPresentationAccessInput,\n projection: OrganizationPresentationProjection,\n): boolean {\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n projection,\n );\n return state.denied && state.deniedByServer;\n}\n\nexport function restoreOrganizationPresentationAccess(\n input: OrganizationPresentationAccessInput,\n attempt: OrganizationPresentationAccessAttempt,\n): boolean {\n if (!isOrganizationPresentationAccessAttemptCurrent(input, attempt)) {\n return false;\n }\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n attempt.projection,\n );\n state.denied = false;\n state.deniedByServer = false;\n return true;\n}\n\nexport async function runOrganizationPresentationRead<T>(\n input: OrganizationPresentationAccessInput,\n projection: OrganizationPresentationProjection,\n operation: () => Promise<T>,\n): Promise<T | null> {\n const attempt = captureOrganizationPresentationAccessAttempt(\n input,\n projection,\n );\n if (!isOrganizationPresentationAccessReadable(input, projection)) {\n return null;\n }\n // In-memory denial dies with the process. The durable marker keeps a\n // revoked projection unreadable when its purge failed and the app\n // restarted; a successful reconcile clears it.\n if (await hasOrganizationPresentationDenial(input, projection)) {\n return null;\n }\n const value = await operation();\n return isOrganizationPresentationAccessAttemptCurrent(input, attempt) &&\n isOrganizationPresentationAccessReadable(input, projection)\n ? value\n : null;\n}\n\nfunction beginOrganizationPresentationAccessReset(\n execSql: ExecSql,\n organizationId: string,\n): void {\n const executor = accessExecutorState(execSql);\n executor.generationByOrganization.set(\n organizationId,\n organizationGeneration(executor, organizationId) + 1,\n );\n executor.resetDepthByOrganization.set(\n organizationId,\n organizationResetDepth(executor, organizationId) + 1,\n );\n for (const scope of executor.scopes.values()) {\n if (scope.organizationId !== organizationId) continue;\n // A reset denies presentation locally but is not a server denial: the next\n // session re-derives server state, and startup sync already re-drives the\n // lanes, so the lost-access memory must not survive into it.\n scope.readModel.denied = true;\n scope.readModel.deniedByServer = false;\n scope.usage.denied = true;\n scope.usage.deniedByServer = false;\n }\n}\n\nfunction finishOrganizationPresentationAccessReset(\n execSql: ExecSql,\n organizationId: string,\n): void {\n const executor = accessExecutorState(execSql);\n const nextDepth = Math.max(\n 0,\n organizationResetDepth(executor, organizationId) - 1,\n );\n if (nextDepth === 0) {\n executor.resetDepthByOrganization.delete(organizationId);\n } else {\n executor.resetDepthByOrganization.set(organizationId, nextDepth);\n }\n}\n\nexport async function runOrganizationPresentationMutation<T>(\n execSql: ExecSql,\n operation: () => Promise<T>,\n): Promise<T> {\n const executor = accessExecutorState(execSql);\n const previous = executor.mutationQueue ?? Promise.resolve();\n let releaseCurrent = () => {};\n const current = new Promise<void>((resolve) => {\n releaseCurrent = resolve;\n });\n const waitForPrevious = previous.catch(() => undefined);\n const queuedCurrent = waitForPrevious.then(() => current);\n executor.mutationQueue = queuedCurrent;\n await waitForPrevious;\n\n try {\n return await operation();\n } finally {\n releaseCurrent();\n if (executor.mutationQueue === queuedCurrent) {\n executor.mutationQueue = undefined;\n }\n }\n}\n\nexport async function runOrganizationPresentationReset<T>(\n execSql: ExecSql,\n organizationId: string,\n operation: () => Promise<T>,\n): Promise<T> {\n beginOrganizationPresentationAccessReset(execSql, organizationId);\n try {\n return await runOrganizationPresentationMutation(execSql, operation);\n } finally {\n finishOrganizationPresentationAccessReset(execSql, organizationId);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationPresentationAccessState.js","sourceRoot":"","sources":["organizationPresentationAccessState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AA4C1H,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAgC,CAAC;AAErE,MAAM,UAAU,0BAA0B,CACxC,cAAsB,EACtB,eAAuB;IAEvB,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,cAAc,EAAE,eAAe,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED,SAAS,mBAAmB,CAAC,OAAgB;IAC3C,IAAI,KAAK,GAAG,gBAAgB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC1C,IAAI,CAAC,KAAK,EAAE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CAAC,OAAO,CAAC,CAAC;IAC9C,MAAM,QAAQ,GAAG,QAAQ,CAAC,aAAa,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;IAC7D,IAAI,cAAc,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC;IAC9B,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;QAC5C,cAAc,GAAG,OAAO,CAAC;IAC3B,CAAC,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IACxD,MAAM,aAAa,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC;IAC1D,QAAQ,CAAC,aAAa,GAAG,aAAa,CAAC;IACvC,MAAM,eAAe,CAAC;IAEtB,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,EAAE,CAAC;IAC3B,CAAC;YAAS,CAAC;QACT,cAAc,EAAE,CAAC;QACjB,IAAI,QAAQ,CAAC,aAAa,KAAK,aAAa,EAAE,CAAC;YAC7C,QAAQ,CAAC,aAAa,GAAG,SAAS,CAAC;QACrC,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,OAAgB,EAChB,cAAsB,EACtB,SAA2B;IAE3B,wCAAwC,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;IAClE,IAAI,CAAC;QACH,OAAO,MAAM,mCAAmC,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACvE,CAAC;YAAS,CAAC;QACT,yCAAyC,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;IACrE,CAAC;AACH,CAAC","sourcesContent":["import { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\nexport type OrganizationPresentationProjection = \"readModel\" | \"usage\";\n\nexport interface OrganizationPresentationAccessInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly requesterUserId: string;\n}\n\ninterface ProjectionAccessState {\n denied: boolean;\n /**\n * True only when the server itself denied the projection (a 403/404 read).\n * A session reset also flips `denied`, but that is a local lifecycle event —\n * consumers reacting specifically to lost-then-regained org access (e.g.\n * re-arming write lanes) must not treat a routine reset as a denial.\n */\n deniedByServer: boolean;\n generation: number;\n}\n\ninterface AccessScopeState {\n readonly organizationId: string;\n readonly readModel: ProjectionAccessState;\n readonly usage: ProjectionAccessState;\n}\n\ninterface AccessExecutorState {\n readonly generationByOrganization: Map<string, number>;\n mutationQueue?: Promise<void> | undefined;\n readonly resetDepthByOrganization: Map<string, number>;\n readonly scopes: Map<string, AccessScopeState>;\n}\n\nexport interface OrganizationPresentationAccessAttempt {\n readonly executorGeneration: number;\n readonly projection: OrganizationPresentationProjection;\n readonly projectionGeneration: number;\n readonly startedDenied: boolean;\n readonly startedDuringReset: boolean;\n}\n\nconst accessByExecutor = new WeakMap<ExecSql, AccessExecutorState>();\n\nexport function organizationAccessScopeKey(\n organizationId: string,\n requesterUserId: string,\n): string {\n return JSON.stringify([organizationId, requesterUserId]);\n}\n\nfunction accessExecutorState(execSql: ExecSql): AccessExecutorState {\n let state = accessByExecutor.get(execSql);\n if (!state) {\n state = {\n generationByOrganization: new Map(),\n resetDepthByOrganization: new Map(),\n scopes: new Map(),\n };\n accessByExecutor.set(execSql, state);\n }\n return state;\n}\n\nfunction newProjectionState(denied: boolean): ProjectionAccessState {\n return { denied, deniedByServer: false, generation: 0 };\n}\n\nfunction organizationResetDepth(\n executor: AccessExecutorState,\n organizationId: string,\n): number {\n return executor.resetDepthByOrganization.get(organizationId) ?? 0;\n}\n\nfunction organizationGeneration(\n executor: AccessExecutorState,\n organizationId: string,\n): number {\n return executor.generationByOrganization.get(organizationId) ?? 0;\n}\n\nfunction accessScopeState(\n executor: AccessExecutorState,\n organizationId: string,\n requesterUserId: string,\n): AccessScopeState {\n const key = organizationAccessScopeKey(organizationId, requesterUserId);\n let scope = executor.scopes.get(key);\n if (!scope) {\n const denied = organizationResetDepth(executor, organizationId) > 0;\n scope = {\n organizationId,\n readModel: newProjectionState(denied),\n usage: newProjectionState(denied),\n };\n executor.scopes.set(key, scope);\n }\n return scope;\n}\n\nfunction projectionState(\n scope: AccessScopeState,\n projection: OrganizationPresentationProjection,\n): ProjectionAccessState {\n return scope[projection];\n}\n\nexport function captureOrganizationPresentationAccessAttempt(\n input: OrganizationPresentationAccessInput,\n projection: OrganizationPresentationProjection,\n): OrganizationPresentationAccessAttempt {\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n projection,\n );\n return {\n executorGeneration: organizationGeneration(executor, input.organizationId),\n projection,\n projectionGeneration: state.generation,\n startedDenied: state.denied,\n startedDuringReset:\n organizationResetDepth(executor, input.organizationId) > 0,\n };\n}\n\nexport function isOrganizationPresentationAccessAttemptCurrent(\n input: OrganizationPresentationAccessInput,\n attempt: OrganizationPresentationAccessAttempt,\n): boolean {\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n attempt.projection,\n );\n return (\n !attempt.startedDuringReset &&\n organizationResetDepth(executor, input.organizationId) === 0 &&\n organizationGeneration(executor, input.organizationId) ===\n attempt.executorGeneration &&\n state.generation === attempt.projectionGeneration\n );\n}\n\nexport function isOrganizationPresentationAccessReadable(\n input: OrganizationPresentationAccessInput,\n projection: OrganizationPresentationProjection,\n): boolean {\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n projection,\n );\n return (\n organizationResetDepth(executor, input.organizationId) === 0 &&\n !state.denied\n );\n}\n\nexport function denyOrganizationPresentationAccess(\n input: OrganizationPresentationAccessInput,\n projections: readonly OrganizationPresentationProjection[],\n): void {\n const executor = accessExecutorState(input.execSql);\n const scope = accessScopeState(\n executor,\n input.organizationId,\n input.requesterUserId,\n );\n for (const projection of new Set(projections)) {\n const state = projectionState(scope, projection);\n state.denied = true;\n state.deniedByServer = true;\n state.generation += 1;\n }\n}\n\n/**\n * Whether the scope's projection is currently denied because the server\n * refused it (as opposed to a local session reset). The flip back to readable\n * after this returns true is the \"org access was just restored\" edge.\n */\nexport function wasOrganizationPresentationAccessDeniedByServer(\n input: OrganizationPresentationAccessInput,\n projection: OrganizationPresentationProjection,\n): boolean {\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n projection,\n );\n return state.denied && state.deniedByServer;\n}\n\nexport function restoreOrganizationPresentationAccess(\n input: OrganizationPresentationAccessInput,\n attempt: OrganizationPresentationAccessAttempt,\n): boolean {\n if (!isOrganizationPresentationAccessAttemptCurrent(input, attempt)) {\n return false;\n }\n const executor = accessExecutorState(input.execSql);\n const state = projectionState(\n accessScopeState(executor, input.organizationId, input.requesterUserId),\n attempt.projection,\n );\n state.denied = false;\n state.deniedByServer = false;\n return true;\n}\n\nexport async function runOrganizationPresentationRead<T>(\n input: OrganizationPresentationAccessInput,\n projection: OrganizationPresentationProjection,\n operation: () => Promise<T>,\n): Promise<T | null> {\n const attempt = captureOrganizationPresentationAccessAttempt(\n input,\n projection,\n );\n if (!isOrganizationPresentationAccessReadable(input, projection)) {\n return null;\n }\n // In-memory denial dies with the process. The durable marker keeps a\n // revoked projection unreadable when its purge failed and the app\n // restarted; a successful reconcile clears it.\n if (\n await new OrganizationReadModelRepository(\n input.execSql,\n ).hasOrganizationPresentationDenial(input, projection)\n ) {\n return null;\n }\n const value = await operation();\n return isOrganizationPresentationAccessAttemptCurrent(input, attempt) &&\n isOrganizationPresentationAccessReadable(input, projection)\n ? value\n : null;\n}\n\nfunction beginOrganizationPresentationAccessReset(\n execSql: ExecSql,\n organizationId: string,\n): void {\n const executor = accessExecutorState(execSql);\n executor.generationByOrganization.set(\n organizationId,\n organizationGeneration(executor, organizationId) + 1,\n );\n executor.resetDepthByOrganization.set(\n organizationId,\n organizationResetDepth(executor, organizationId) + 1,\n );\n for (const scope of executor.scopes.values()) {\n if (scope.organizationId !== organizationId) continue;\n // A reset denies presentation locally but is not a server denial: the next\n // session re-derives server state, and startup sync already re-drives the\n // lanes, so the lost-access memory must not survive into it.\n scope.readModel.denied = true;\n scope.readModel.deniedByServer = false;\n scope.usage.denied = true;\n scope.usage.deniedByServer = false;\n }\n}\n\nfunction finishOrganizationPresentationAccessReset(\n execSql: ExecSql,\n organizationId: string,\n): void {\n const executor = accessExecutorState(execSql);\n const nextDepth = Math.max(\n 0,\n organizationResetDepth(executor, organizationId) - 1,\n );\n if (nextDepth === 0) {\n executor.resetDepthByOrganization.delete(organizationId);\n } else {\n executor.resetDepthByOrganization.set(organizationId, nextDepth);\n }\n}\n\nexport async function runOrganizationPresentationMutation<T>(\n execSql: ExecSql,\n operation: () => Promise<T>,\n): Promise<T> {\n const executor = accessExecutorState(execSql);\n const previous = executor.mutationQueue ?? Promise.resolve();\n let releaseCurrent = () => {};\n const current = new Promise<void>((resolve) => {\n releaseCurrent = resolve;\n });\n const waitForPrevious = previous.catch(() => undefined);\n const queuedCurrent = waitForPrevious.then(() => current);\n executor.mutationQueue = queuedCurrent;\n await waitForPrevious;\n\n try {\n return await operation();\n } finally {\n releaseCurrent();\n if (executor.mutationQueue === queuedCurrent) {\n executor.mutationQueue = undefined;\n }\n }\n}\n\nexport async function runOrganizationPresentationReset<T>(\n execSql: ExecSql,\n organizationId: string,\n operation: () => Promise<T>,\n): Promise<T> {\n beginOrganizationPresentationAccessReset(execSql, organizationId);\n try {\n return await runOrganizationPresentationMutation(execSql, operation);\n } finally {\n finishOrganizationPresentationAccessReset(execSql, organizationId);\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { RequestResult, RequestResultOptions } from "../../../internal/api-client/index.js";
|
|
2
2
|
import { type OrganizationReadModelResponse } from "../../../internal/validators/response/index.js";
|
|
3
|
-
import {
|
|
3
|
+
import type { OrganizationReadModelGroupMembers } from "../../../data/persistence/organizations/organizationReadModelMemberLoad.js";
|
|
4
4
|
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
5
5
|
import type { OrganizationDirectoryAndGroups } from "./index.js";
|
|
6
6
|
interface OrganizationReadModelApi {
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import { ORGANIZATION_READ_MODEL_ERROR_CODES, } from "../../../internal/validators/response/index.js";
|
|
2
|
-
import { purgeOrganizationAccessProjection } from "../../../data/persistence/organizations/organizationAccessRevocationPersistence.js";
|
|
3
|
-
import { recordOrganizationPresentationDenials } from "../../../data/persistence/organizations/organizationPresentationDenialPersistence.js";
|
|
4
|
-
import { loadOrganizationReadModelGroupMembers, } from "../../../data/persistence/organizations/organizationReadModelMemberLoad.js";
|
|
5
2
|
import { OrganizationReadModelBindingError } from "../../../data/persistence/organizations/organizationReadModelMembershipPersistence.js";
|
|
6
|
-
import {
|
|
3
|
+
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
7
4
|
import { captureOrganizationPresentationAccessAttempt, denyOrganizationPresentationAccess, isOrganizationPresentationAccessAttemptCurrent, isOrganizationPresentationAccessReadable, restoreOrganizationPresentationAccess, runOrganizationPresentationMutation, runOrganizationPresentationRead, } from "./organizationPresentationAccessState.js";
|
|
8
5
|
import { isOrganizationPresentationAccessDeniedFailure } from "./organizationPresentationFailures.js";
|
|
9
6
|
const MAX_READ_MODEL_PAGES = 100;
|
|
@@ -31,7 +28,7 @@ async function loadProjection(input) {
|
|
|
31
28
|
return runOrganizationPresentationRead(organizationPresentationAccessInput(input), "readModel", () => loadRawProjection(input));
|
|
32
29
|
}
|
|
33
30
|
function loadRawProjection(input) {
|
|
34
|
-
return
|
|
31
|
+
return new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelProjection(input.organizationId, input.currentUserId);
|
|
35
32
|
}
|
|
36
33
|
function organizationPresentationAccessInput(input) {
|
|
37
34
|
return {
|
|
@@ -81,10 +78,11 @@ async function requestReadModelPage(input, state) {
|
|
|
81
78
|
if (isOrganizationPresentationAccessDeniedFailure(result)) {
|
|
82
79
|
const accessInput = organizationPresentationAccessInput(input);
|
|
83
80
|
denyOrganizationPresentationAccess(accessInput, ["readModel", "usage"]);
|
|
81
|
+
const repository = new OrganizationReadModelRepository(input.execSql);
|
|
84
82
|
// The durable marker lands before the purge attempt: if the purge fails,
|
|
85
83
|
// an offline restart must still refuse to serve the revoked projection.
|
|
86
84
|
try {
|
|
87
|
-
await runOrganizationPresentationMutation(input.execSql, () => recordOrganizationPresentationDenials(accessInput, [
|
|
85
|
+
await runOrganizationPresentationMutation(input.execSql, () => repository.recordOrganizationPresentationDenials(accessInput, [
|
|
88
86
|
"readModel",
|
|
89
87
|
"usage",
|
|
90
88
|
]));
|
|
@@ -93,8 +91,7 @@ async function requestReadModelPage(input, state) {
|
|
|
93
91
|
input.logError?.("Failed to record denied organization access", error);
|
|
94
92
|
}
|
|
95
93
|
try {
|
|
96
|
-
await runOrganizationPresentationMutation(input.execSql, () => purgeOrganizationAccessProjection({
|
|
97
|
-
execSql: input.execSql,
|
|
94
|
+
await runOrganizationPresentationMutation(input.execSql, () => repository.purgeOrganizationAccessProjection({
|
|
98
95
|
organizationId: input.organizationId,
|
|
99
96
|
requesterUserId: input.currentUserId,
|
|
100
97
|
}));
|
|
@@ -129,12 +126,12 @@ function reconciliationIsCurrent(input, state) {
|
|
|
129
126
|
return isOrganizationPresentationAccessAttemptCurrent(organizationPresentationAccessInput(input), state.accessAttempt);
|
|
130
127
|
}
|
|
131
128
|
async function applyResponse(input, state, response) {
|
|
129
|
+
const repository = new OrganizationReadModelRepository(input.execSql);
|
|
132
130
|
try {
|
|
133
131
|
return {
|
|
134
132
|
kind: "applied",
|
|
135
|
-
result: await applyOrganizationReadModelResponse({
|
|
133
|
+
result: await repository.applyOrganizationReadModelResponse({
|
|
136
134
|
currentUserId: input.currentUserId,
|
|
137
|
-
execSql: input.execSql,
|
|
138
135
|
requestedCursor: state.expectedLocalCursor,
|
|
139
136
|
response,
|
|
140
137
|
}),
|
|
@@ -147,7 +144,7 @@ async function applyResponse(input, state, response) {
|
|
|
147
144
|
return localResult(input, state, { failed: true });
|
|
148
145
|
}
|
|
149
146
|
state.retriedBindingFailure = true;
|
|
150
|
-
await purgeOrganizationReadModelProjection(input.
|
|
147
|
+
await repository.purgeOrganizationReadModelProjection(input.organizationId);
|
|
151
148
|
if (!reconciliationIsCurrent(input, state)) {
|
|
152
149
|
return { kind: "done", value: null };
|
|
153
150
|
}
|
|
@@ -164,7 +161,9 @@ async function prepareDeniedProjectionForApply(input, state) {
|
|
|
164
161
|
// The apply that follows replaces the shared rows authoritatively, so
|
|
165
162
|
// only this requester's row is dropped: another local identity sharing
|
|
166
163
|
// the database keeps its access and reads the replacement.
|
|
167
|
-
await
|
|
164
|
+
await new OrganizationReadModelRepository(input.execSql).purgeOrganizationReadModelProjection(input.organizationId, {
|
|
165
|
+
onlyRequesterUserId: input.currentUserId,
|
|
166
|
+
});
|
|
168
167
|
}
|
|
169
168
|
catch (error) {
|
|
170
169
|
input.logError?.("Failed to replace denied organization read model", error);
|
|
@@ -220,7 +219,7 @@ export async function loadLocalOrganizationDirectoryAndGroups(input) {
|
|
|
220
219
|
return toDirectoryAndGroups(await loadProjection(input));
|
|
221
220
|
}
|
|
222
221
|
export async function loadLocalOrganizationGroupMembers(input) {
|
|
223
|
-
return runOrganizationPresentationRead(organizationPresentationAccessInput(input), "readModel", () =>
|
|
222
|
+
return runOrganizationPresentationRead(organizationPresentationAccessInput(input), "readModel", () => new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelGroupMembers(input.organizationId, input.groupId, input.currentUserId));
|
|
224
223
|
}
|
|
225
224
|
/**
|
|
226
225
|
* Resolves the reconciled projection, `null` when the pass completed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readModelProjection.js","sourceRoot":"","sources":["readModelProjection.ts"],"names":[],"mappings":"AAIA,OAAO,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AAM,cAAc,CAAC,KAAK,CAAC;QACvC,aAAa,EAAE,SAAS;QACxB,qBAAqB,EAAE,KAAK;QAC5B,oBAAoB,EAAE,KAAK;QAC3B,YAAY,EAAE,CAAC;KAChB,CAAC;IACF,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAE1B,KAAK,IAAI,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG,oBAAoB,EAAE,IAAI,IAAI,CAAC,EAAE,CAAC;QAC1D,MAAM,OAAO,GAAG,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACzD,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;QACD,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAChC,SAAS;QACX,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;QACzE,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;IACH,CAAC;IAED,KAAK,CAAC,QAAQ,EAAE,CACd,4DAA4D,CAC7D,CAAC;IACF,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,OAAO,QAAQ,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n ORGANIZATION_READ_MODEL_ERROR_CODES,\n type OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport { purgeOrganizationAccessProjection } from \"../../../data/persistence/organizations/organizationAccessRevocationPersistence\";\nimport { recordOrganizationPresentationDenials } from \"../../../data/persistence/organizations/organizationPresentationDenialPersistence\";\nimport {\n loadOrganizationReadModelGroupMembers,\n type OrganizationReadModelGroupMembers,\n} from \"../../../data/persistence/organizations/organizationReadModelMemberLoad\";\nimport { OrganizationReadModelBindingError } from \"../../../data/persistence/organizations/organizationReadModelMembershipPersistence\";\nimport {\n applyOrganizationReadModelResponse,\n loadOrganizationReadModelProjection,\n type OrganizationReadModelProjection,\n purgeOrganizationReadModelProjection,\n} from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n type OrganizationPresentationAccessInput,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nconst MAX_READ_MODEL_PAGES = 100;\nconst MAX_STALE_RETRIES = 1;\n\ninterface OrganizationReadModelApi {\n getOrganizationReadModelResult(\n organizationId: string,\n cursor?: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationReadModelResponse>>;\n}\n\ninterface OrganizationReadModelProjectionInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\nexport interface ReconcileOrganizationDirectoryAndGroupsInput\n extends OrganizationReadModelProjectionInput {\n readonly apiClient: OrganizationReadModelApi;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n}\n\nfunction toDirectoryAndGroups(\n projection: OrganizationReadModelProjection | null,\n): OrganizationDirectoryAndGroups | null {\n if (!projection?.requester) {\n return null;\n }\n\n return {\n directory: {\n ...projection.directory,\n currentUser: projection.requester,\n },\n // Hydration decides whether a name is unreadable; a stored blank name may\n // only mean the group has not been hydrated yet.\n groups: projection.groups.groups.map((group) => ({\n ...group,\n nameUnreadable: false,\n })),\n memberGroupId: projection.groups.memberGroupId,\n readModelCursor: projection.cursor,\n };\n}\n\nasync function loadProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () => loadRawProjection(input),\n );\n}\n\nfunction loadRawProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return loadOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n input.currentUserId,\n );\n}\n\nfunction organizationPresentationAccessInput(\n input: OrganizationReadModelProjectionInput,\n): OrganizationPresentationAccessInput {\n return {\n execSql: input.execSql,\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n };\n}\n\ninterface ReconciliationState {\n readonly accessAttempt: OrganizationPresentationAccessAttempt;\n expectedLocalCursor: string | null;\n preparedDeniedProjection: boolean;\n projection: OrganizationReadModelProjection | null;\n requestCursor: string | undefined;\n retriedBindingFailure: boolean;\n retriedInvalidCursor: boolean;\n staleRetries: number;\n}\n\ntype ReconciliationStep =\n | { readonly kind: \"continue\" }\n | {\n readonly kind: \"done\";\n readonly value: OrganizationDirectoryAndGroups | null | undefined;\n };\n\ntype PageRequestStep =\n | ReconciliationStep\n | {\n readonly kind: \"response\";\n readonly response: OrganizationReadModelResponse;\n };\n\nfunction localResult(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n outcome: { readonly failed: boolean },\n): ReconciliationStep {\n const accessInput = organizationPresentationAccessInput(input);\n const readable =\n isOrganizationPresentationAccessAttemptCurrent(\n accessInput,\n state.accessAttempt,\n ) && isOrganizationPresentationAccessReadable(accessInput, \"readModel\");\n if (!readable) {\n return { kind: \"done\", value: null };\n }\n // Retained rows are available through the local loader, but are not proof\n // that this pass caught up. Returning them after a failed post-commit read\n // makes mutation callers skip their retry and repaint pre-mutation status.\n if (outcome.failed) {\n return { kind: \"done\", value: undefined };\n }\n return { kind: \"done\", value: toDirectoryAndGroups(state.projection) };\n}\n\nfunction resetRequestCursor(state: ReconciliationState): void {\n state.expectedLocalCursor = state.projection?.cursor ?? null;\n state.requestCursor = state.projection?.cursor ?? undefined;\n}\n\n/** Replays a page that applied stale, up to the retry budget. */\nfunction retryStaleApply(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): ReconciliationStep {\n if (state.staleRetries >= MAX_STALE_RETRIES) {\n return localResult(input, state, { failed: true });\n }\n state.staleRetries += 1;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n}\n\nfunction isInvalidReadModelCursorFailure(\n result: RequestResult<OrganizationReadModelResponse>,\n): boolean {\n return (\n !result.ok &&\n result.kind === \"http\" &&\n result.status === 400 &&\n result.code === ORGANIZATION_READ_MODEL_ERROR_CODES.cursorInvalid\n );\n}\n\nasync function requestReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<PageRequestStep> {\n const result = await input.apiClient.getOrganizationReadModelResult(\n input.organizationId,\n state.requestCursor,\n { reportErrors: false },\n );\n if (result.ok) {\n return { kind: \"response\", response: result.data };\n }\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n const accessInput = organizationPresentationAccessInput(input);\n denyOrganizationPresentationAccess(accessInput, [\"readModel\", \"usage\"]);\n // The durable marker lands before the purge attempt: if the purge fails,\n // an offline restart must still refuse to serve the revoked projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n recordOrganizationPresentationDenials(accessInput, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError?.(\"Failed to record denied organization access\", error);\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n purgeOrganizationAccessProjection({\n execSql: input.execSql,\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n }),\n );\n } catch (error) {\n input.logError?.(\"Failed to purge denied organization access\", error);\n }\n return { kind: \"done\", value: null };\n }\n if (\n isInvalidReadModelCursorFailure(result) &&\n state.requestCursor !== undefined &&\n !state.retriedInvalidCursor\n ) {\n state.requestCursor = undefined;\n state.retriedInvalidCursor = true;\n return { kind: \"continue\" };\n }\n\n result.report();\n return localResult(input, state, { failed: true });\n}\n\nfunction responseMatchesRequest(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): boolean {\n if (response.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization read-model response scope does not match ${input.organizationId}`,\n );\n return false;\n }\n if (response.hasMore && response.nextCursor === state.expectedLocalCursor) {\n input.logError?.(\"Organization read-model page did not advance its cursor\");\n return false;\n }\n return true;\n}\n\nfunction reconciliationIsCurrent(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): boolean {\n return isOrganizationPresentationAccessAttemptCurrent(\n organizationPresentationAccessInput(input),\n state.accessAttempt,\n );\n}\n\ntype ApplyResponseStep =\n | ReconciliationStep\n | {\n readonly kind: \"applied\";\n readonly result: Awaited<\n ReturnType<typeof applyOrganizationReadModelResponse>\n >;\n };\n\nasync function applyResponse(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ApplyResponseStep> {\n try {\n return {\n kind: \"applied\",\n result: await applyOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n execSql: input.execSql,\n requestedCursor: state.expectedLocalCursor,\n response,\n }),\n };\n } catch (error) {\n input.logError?.(\"Failed to apply organization read-model response\", error);\n if (\n !(error instanceof OrganizationReadModelBindingError) ||\n state.retriedBindingFailure\n ) {\n return localResult(input, state, { failed: true });\n }\n state.retriedBindingFailure = true;\n await purgeOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n );\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.projection = null;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n }\n}\n\nasync function prepareDeniedProjectionForApply(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<ReconciliationStep | null> {\n if (state.preparedDeniedProjection) {\n return null;\n }\n try {\n // The apply that follows replaces the shared rows authoritatively, so\n // only this requester's row is dropped: another local identity sharing\n // the database keeps its access and reads the replacement.\n await purgeOrganizationReadModelProjection(\n input.execSql,\n input.organizationId,\n { onlyRequesterUserId: input.currentUserId },\n );\n } catch (error) {\n input.logError?.(\"Failed to replace denied organization read model\", error);\n return { kind: \"done\", value: null };\n }\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.expectedLocalCursor = null;\n state.preparedDeniedProjection = true;\n state.projection = null;\n return null;\n}\n\n/** The last page settles only if presentation access is still restorable. */\nfunction finalPageStep(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n accessInput: OrganizationPresentationAccessInput,\n): ReconciliationStep {\n return restoreOrganizationPresentationAccess(accessInput, state.accessAttempt)\n ? localResult(input, state, { failed: false })\n : { kind: \"done\", value: null };\n}\n\nasync function applyReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ReconciliationStep> {\n if (!responseMatchesRequest(input, state, response)) {\n return localResult(input, state, { failed: true });\n }\n\n const accessInput = organizationPresentationAccessInput(input);\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n const preparation = await prepareDeniedProjectionForApply(input, state);\n if (preparation) {\n return preparation;\n }\n\n const applied = await applyResponse(input, state, response);\n if (applied.kind !== \"applied\") {\n return applied;\n }\n\n state.projection = await loadRawProjection(input);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n if (applied.result === \"stale\") {\n return retryStaleApply(input, state);\n }\n\n state.expectedLocalCursor = state.projection?.cursor ?? response.nextCursor;\n if (!response.hasMore) {\n return finalPageStep(input, state, accessInput);\n }\n state.requestCursor = response.nextCursor;\n return { kind: \"continue\" };\n });\n}\n\nexport async function loadLocalOrganizationDirectoryAndGroups(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationDirectoryAndGroups | null> {\n return toDirectoryAndGroups(await loadProjection(input));\n}\n\nexport async function loadLocalOrganizationGroupMembers(\n input: OrganizationReadModelProjectionInput & { readonly groupId: string },\n): Promise<OrganizationReadModelGroupMembers | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () =>\n loadOrganizationReadModelGroupMembers(\n input.execSql,\n input.organizationId,\n input.groupId,\n input.currentUserId,\n ),\n );\n}\n\n/**\n * Resolves the reconciled projection, `null` when the pass completed\n * authoritatively with nothing presentable (including a denial that purged\n * the projection), or `undefined` when the feed failed — even when local\n * rows remain available. A failed pass must not count as caught up.\n */\nexport async function reconcileOrganizationDirectoryAndGroups(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessInput = organizationPresentationAccessInput(input);\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n accessInput,\n \"readModel\",\n );\n const state: ReconciliationState = {\n accessAttempt,\n expectedLocalCursor: null,\n preparedDeniedProjection: !accessAttempt.startedDenied,\n projection: await loadProjection(input),\n requestCursor: undefined,\n retriedBindingFailure: false,\n retriedInvalidCursor: false,\n staleRetries: 0,\n };\n resetRequestCursor(state);\n\n for (let page = 0; page < MAX_READ_MODEL_PAGES; page += 1) {\n const request = await requestReadModelPage(input, state);\n if (request.kind === \"done\") {\n return request.value;\n }\n if (request.kind === \"continue\") {\n continue;\n }\n const applied = await applyReadModelPage(input, state, request.response);\n if (applied.kind === \"done\") {\n return applied.value;\n }\n }\n\n input.logError?.(\n \"Organization read-model reconciliation exceeded page limit\",\n );\n const retained = localResult(input, state, { failed: true });\n return retained.kind === \"done\" ? retained.value : null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"readModelProjection.js","sourceRoot":"","sources":["readModelProjection.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,mCAAmC,GAEpC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,iCAAiC,EAAE,MAAM,oFAAoF,CAAC;AAKvI,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAG1H,OAAO,EACL,4CAA4C,EAC5C,kCAAkC,EAClC,8CAA8C,EAC9C,wCAAwC,EAGxC,qCAAqC,EACrC,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,6CAA6C,EAAE,MAAM,oCAAoC,CAAC;AAEnG,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAwB5B,SAAS,oBAAoB,CAC3B,UAAkD;IAElD,IAAI,CAAC,UAAU,EAAE,SAAS,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,SAAS,EAAE;YACT,GAAG,UAAU,CAAC,SAAS;YACvB,WAAW,EAAE,UAAU,CAAC,SAAS;SAClC;QACD,0EAA0E;QAC1E,iDAAiD;QACjD,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YAC/C,GAAG,KAAK;YACR,cAAc,EAAE,KAAK;SACtB,CAAC,CAAC;QACH,aAAa,EAAE,UAAU,CAAC,MAAM,CAAC,aAAa;QAC9C,eAAe,EAAE,UAAU,CAAC,MAAM;KACnC,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,cAAc,CAC3B,KAA2C;IAE3C,OAAO,+BAA+B,CACpC,mCAAmC,CAAC,KAAK,CAAC,EAC1C,WAAW,EACX,GAAG,EAAE,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAC/B,CAAC;AACJ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ROR_CODES,\n type OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport type { OrganizationReadModelGroupMembers } from \"../../../data/persistence/organizations/organizationReadModelMemberLoad\";\nimport { OrganizationReadModelBindingError } from \"../../../data/persistence/organizations/organizationReadModelMembershipPersistence\";\nimport type {\n ApplyOrganizationReadModelResponseResult,\n OrganizationReadModelProjection,\n} from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n type OrganizationPresentationAccessInput,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nconst MAX_READ_MODEL_PAGES = 100;\nconst MAX_STALE_RETRIES = 1;\n\ninterface OrganizationReadModelApi {\n getOrganizationReadModelResult(\n organizationId: string,\n cursor?: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationReadModelResponse>>;\n}\n\ninterface OrganizationReadModelProjectionInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\nexport interface ReconcileOrganizationDirectoryAndGroupsInput\n extends OrganizationReadModelProjectionInput {\n readonly apiClient: OrganizationReadModelApi;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n}\n\nfunction toDirectoryAndGroups(\n projection: OrganizationReadModelProjection | null,\n): OrganizationDirectoryAndGroups | null {\n if (!projection?.requester) {\n return null;\n }\n\n return {\n directory: {\n ...projection.directory,\n currentUser: projection.requester,\n },\n // Hydration decides whether a name is unreadable; a stored blank name may\n // only mean the group has not been hydrated yet.\n groups: projection.groups.groups.map((group) => ({\n ...group,\n nameUnreadable: false,\n })),\n memberGroupId: projection.groups.memberGroupId,\n readModelCursor: projection.cursor,\n };\n}\n\nasync function loadProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () => loadRawProjection(input),\n );\n}\n\nfunction loadRawProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n}\n\nfunction organizationPresentationAccessInput(\n input: OrganizationReadModelProjectionInput,\n): OrganizationPresentationAccessInput {\n return {\n execSql: input.execSql,\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n };\n}\n\ninterface ReconciliationState {\n readonly accessAttempt: OrganizationPresentationAccessAttempt;\n expectedLocalCursor: string | null;\n preparedDeniedProjection: boolean;\n projection: OrganizationReadModelProjection | null;\n requestCursor: string | undefined;\n retriedBindingFailure: boolean;\n retriedInvalidCursor: boolean;\n staleRetries: number;\n}\n\ntype ReconciliationStep =\n | { readonly kind: \"continue\" }\n | {\n readonly kind: \"done\";\n readonly value: OrganizationDirectoryAndGroups | null | undefined;\n };\n\ntype PageRequestStep =\n | ReconciliationStep\n | {\n readonly kind: \"response\";\n readonly response: OrganizationReadModelResponse;\n };\n\nfunction localResult(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n outcome: { readonly failed: boolean },\n): ReconciliationStep {\n const accessInput = organizationPresentationAccessInput(input);\n const readable =\n isOrganizationPresentationAccessAttemptCurrent(\n accessInput,\n state.accessAttempt,\n ) && isOrganizationPresentationAccessReadable(accessInput, \"readModel\");\n if (!readable) {\n return { kind: \"done\", value: null };\n }\n // Retained rows are available through the local loader, but are not proof\n // that this pass caught up. Returning them after a failed post-commit read\n // makes mutation callers skip their retry and repaint pre-mutation status.\n if (outcome.failed) {\n return { kind: \"done\", value: undefined };\n }\n return { kind: \"done\", value: toDirectoryAndGroups(state.projection) };\n}\n\nfunction resetRequestCursor(state: ReconciliationState): void {\n state.expectedLocalCursor = state.projection?.cursor ?? null;\n state.requestCursor = state.projection?.cursor ?? undefined;\n}\n\n/** Replays a page that applied stale, up to the retry budget. */\nfunction retryStaleApply(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): ReconciliationStep {\n if (state.staleRetries >= MAX_STALE_RETRIES) {\n return localResult(input, state, { failed: true });\n }\n state.staleRetries += 1;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n}\n\nfunction isInvalidReadModelCursorFailure(\n result: RequestResult<OrganizationReadModelResponse>,\n): boolean {\n return (\n !result.ok &&\n result.kind === \"http\" &&\n result.status === 400 &&\n result.code === ORGANIZATION_READ_MODEL_ERROR_CODES.cursorInvalid\n );\n}\n\nasync function requestReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<PageRequestStep> {\n const result = await input.apiClient.getOrganizationReadModelResult(\n input.organizationId,\n state.requestCursor,\n { reportErrors: false },\n );\n if (result.ok) {\n return { kind: \"response\", response: result.data };\n }\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n const accessInput = organizationPresentationAccessInput(input);\n denyOrganizationPresentationAccess(accessInput, [\"readModel\", \"usage\"]);\n const repository = new OrganizationReadModelRepository(input.execSql);\n // The durable marker lands before the purge attempt: if the purge fails,\n // an offline restart must still refuse to serve the revoked projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.recordOrganizationPresentationDenials(accessInput, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError?.(\"Failed to record denied organization access\", error);\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.purgeOrganizationAccessProjection({\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n }),\n );\n } catch (error) {\n input.logError?.(\"Failed to purge denied organization access\", error);\n }\n return { kind: \"done\", value: null };\n }\n if (\n isInvalidReadModelCursorFailure(result) &&\n state.requestCursor !== undefined &&\n !state.retriedInvalidCursor\n ) {\n state.requestCursor = undefined;\n state.retriedInvalidCursor = true;\n return { kind: \"continue\" };\n }\n\n result.report();\n return localResult(input, state, { failed: true });\n}\n\nfunction responseMatchesRequest(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): boolean {\n if (response.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization read-model response scope does not match ${input.organizationId}`,\n );\n return false;\n }\n if (response.hasMore && response.nextCursor === state.expectedLocalCursor) {\n input.logError?.(\"Organization read-model page did not advance its cursor\");\n return false;\n }\n return true;\n}\n\nfunction reconciliationIsCurrent(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): boolean {\n return isOrganizationPresentationAccessAttemptCurrent(\n organizationPresentationAccessInput(input),\n state.accessAttempt,\n );\n}\n\ntype ApplyResponseStep =\n | ReconciliationStep\n | {\n readonly kind: \"applied\";\n readonly result: ApplyOrganizationReadModelResponseResult;\n };\n\nasync function applyResponse(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ApplyResponseStep> {\n const repository = new OrganizationReadModelRepository(input.execSql);\n try {\n return {\n kind: \"applied\",\n result: await repository.applyOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n requestedCursor: state.expectedLocalCursor,\n response,\n }),\n };\n } catch (error) {\n input.logError?.(\"Failed to apply organization read-model response\", error);\n if (\n !(error instanceof OrganizationReadModelBindingError) ||\n state.retriedBindingFailure\n ) {\n return localResult(input, state, { failed: true });\n }\n state.retriedBindingFailure = true;\n await repository.purgeOrganizationReadModelProjection(input.organizationId);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.projection = null;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n }\n}\n\nasync function prepareDeniedProjectionForApply(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<ReconciliationStep | null> {\n if (state.preparedDeniedProjection) {\n return null;\n }\n try {\n // The apply that follows replaces the shared rows authoritatively, so\n // only this requester's row is dropped: another local identity sharing\n // the database keeps its access and reads the replacement.\n await new OrganizationReadModelRepository(\n input.execSql,\n ).purgeOrganizationReadModelProjection(input.organizationId, {\n onlyRequesterUserId: input.currentUserId,\n });\n } catch (error) {\n input.logError?.(\"Failed to replace denied organization read model\", error);\n return { kind: \"done\", value: null };\n }\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.expectedLocalCursor = null;\n state.preparedDeniedProjection = true;\n state.projection = null;\n return null;\n}\n\n/** The last page settles only if presentation access is still restorable. */\nfunction finalPageStep(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n accessInput: OrganizationPresentationAccessInput,\n): ReconciliationStep {\n return restoreOrganizationPresentationAccess(accessInput, state.accessAttempt)\n ? localResult(input, state, { failed: false })\n : { kind: \"done\", value: null };\n}\n\nasync function applyReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ReconciliationStep> {\n if (!responseMatchesRequest(input, state, response)) {\n return localResult(input, state, { failed: true });\n }\n\n const accessInput = organizationPresentationAccessInput(input);\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n const preparation = await prepareDeniedProjectionForApply(input, state);\n if (preparation) {\n return preparation;\n }\n\n const applied = await applyResponse(input, state, response);\n if (applied.kind !== \"applied\") {\n return applied;\n }\n\n state.projection = await loadRawProjection(input);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n if (applied.result === \"stale\") {\n return retryStaleApply(input, state);\n }\n\n state.expectedLocalCursor = state.projection?.cursor ?? response.nextCursor;\n if (!response.hasMore) {\n return finalPageStep(input, state, accessInput);\n }\n state.requestCursor = response.nextCursor;\n return { kind: \"continue\" };\n });\n}\n\nexport async function loadLocalOrganizationDirectoryAndGroups(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationDirectoryAndGroups | null> {\n return toDirectoryAndGroups(await loadProjection(input));\n}\n\nexport async function loadLocalOrganizationGroupMembers(\n input: OrganizationReadModelProjectionInput & { readonly groupId: string },\n): Promise<OrganizationReadModelGroupMembers | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () =>\n new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelGroupMembers(\n input.organizationId,\n input.groupId,\n input.currentUserId,\n ),\n );\n}\n\n/**\n * Resolves the reconciled projection, `null` when the pass completed\n * authoritatively with nothing presentable (including a denial that purged\n * the projection), or `undefined` when the feed failed — even when local\n * rows remain available. A failed pass must not count as caught up.\n */\nexport async function reconcileOrganizationDirectoryAndGroups(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessInput = organizationPresentationAccessInput(input);\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n accessInput,\n \"readModel\",\n );\n const state: ReconciliationState = {\n accessAttempt,\n expectedLocalCursor: null,\n preparedDeniedProjection: !accessAttempt.startedDenied,\n projection: await loadProjection(input),\n requestCursor: undefined,\n retriedBindingFailure: false,\n retriedInvalidCursor: false,\n staleRetries: 0,\n };\n resetRequestCursor(state);\n\n for (let page = 0; page < MAX_READ_MODEL_PAGES; page += 1) {\n const request = await requestReadModelPage(input, state);\n if (request.kind === \"done\") {\n return request.value;\n }\n if (request.kind === \"continue\") {\n continue;\n }\n const applied = await applyReadModelPage(input, state, request.response);\n if (applied.kind === \"done\") {\n return applied.value;\n }\n }\n\n input.logError?.(\n \"Organization read-model reconciliation exceeded page limit\",\n );\n const retained = localResult(input, state, { failed: true });\n return retained.kind === \"done\" ? retained.value : null;\n}\n"]}
|