@tearleads/client-sdk 0.1.204 → 0.1.206
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/data/persistence/container-contents/containerDeletionPersistence.js +3 -2
- package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerReconcilePersistence.js +3 -3
- package/data/persistence/container-contents/containerReconcilePersistence.js.map +1 -1
- package/data/persistence/container-contents/containerSyncWatermarkPersistence.d.ts +17 -10
- package/data/persistence/container-contents/containerSyncWatermarkPersistence.js +34 -37
- package/data/persistence/container-contents/containerSyncWatermarkPersistence.js.map +1 -1
- package/data/persistence/organizations/{organizationProvisioningAttemptPersistence.js → organizationProvisioningAttemptRepository.js} +26 -15
- package/data/persistence/organizations/organizationProvisioningAttemptRepository.js.map +1 -0
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/hydration/startupHydration.js +2 -2
- package/stores/container-contents/hydration/startupHydration.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +3 -15
- package/workflows/container-contents/containerPersistence.js +2 -20
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/documentQueries/index.js +3 -3
- package/workflows/container-contents/documentQueries/index.js.map +1 -1
- package/workflows/container-contents/index.d.ts +1 -1
- package/workflows/container-contents/index.js +1 -1
- package/workflows/container-contents/index.js.map +1 -1
- package/workflows/container-contents/info/containerInfo.js +4 -6
- package/workflows/container-contents/info/containerInfo.js.map +1 -1
- package/workflows/container-contents/remoteHydration/lanes/laneFetchMarkers.js +2 -2
- package/workflows/container-contents/remoteHydration/lanes/laneFetchMarkers.js.map +1 -1
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
- package/workflows/container-contents/syncPause/discoveryGuard.js +2 -2
- package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
- package/workflows/organizations/provisioning/organizationProvisioningAttempt.js +5 -5
- package/workflows/organizations/provisioning/organizationProvisioningAttempt.js.map +1 -1
- package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerInfo.js","sourceRoot":"","sources":["containerInfo.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EAEL,yBAAyB,EACzB,uBAAuB,EACvB,6BAA6B,EAC7B,oCAAoC,GACrC,MAAM,gFAAgF,CAAC;AACxF,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAwFlG,SAAS,uBAAuB,CAC9B,MAAoB;IAEpB,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,GAAG,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC,aAAa,CACnD,GAAG,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,SAAS,EAAE,CAC1C,CACF,CAAC;AACJ,CAAC;AAED,SAAS,oBAAoB,CAAC,KAAyB;IACrD,OAAO;QACL,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,WAAW,EAAE,KAAK,CAAC,WAAW;KAC/B,CAAC;AACJ,CAAC;AAED,SAAS,yBAAyB,CAChC,UAA6C;IAE7C,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QAC9C,MAAM,KAAK,GAAG,kBA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AAS,EAAE,yBAAyB,CAAC,UAAU,CAAC;YAChD,MAAM,EAAE,uBAAuB,CAC7B,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAC7C;YACD,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC;YACnB,QAAQ,EAAE,+BAA+B,CAAC,UAAU,CAAC;YACrD,WAAW;SACZ;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n ContainerGrantSubjectType,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { eq } from \"drizzle-orm\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport {\n type ContainerSyncWatermarkLane,\n containerContentsSyncLane,\n containerParentSyncLane,\n containerSyncWatermarkLaneKey,\n sqlContainerSyncWatermarkPersistence,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport { containers } from \"../../../data/sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationGroupSummary } from \"../../organizations/readModel\";\n\nexport type ContainerShareAccessLevel = ContainerAccessLevel;\n\nexport interface ContainerInfoGrant {\n accessLevel: ContainerAccessLevel;\n subjectId: string;\n subjectType: ContainerGrantSubjectType;\n}\n\nexport interface ContainerInfoGrantRow extends ContainerInfoGrant {\n inherited: boolean;\n sourceContainerId: string;\n}\n\nexport interface ContainerInfoSyncCursor {\n label: string;\n laneId: string;\n laneKind: string;\n savedAt: string | null;\n watermarkId: string | null;\n watermarkUpdatedAt: string | null;\n}\n\nexport interface ContainerInfoPathEntry {\n containerId: string;\n containerKeyEpoch: number;\n containerKeyEpochId: string;\n directGrantCount: number;\n eventHash: string;\n keyEpochHash: string;\n keyTargetHash: string;\n manifestHash: string;\n manifestHistoryCount: number;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargetCount: number;\n referencedPrincipalCount: number;\n wrapCount: number;\n}\n\nexport interface ContainerInfoSecurityDetails {\n currentContainerKeyEpoch: number;\n currentContainerKeyEpochId: string;\n currentManifestHash: string;\n currentManifestHistoryCount: number;\n currentParentContainerKeyEpochId: string | null;\n currentReferencedPrincipalCount: number;\n path: ContainerInfoPathEntry[];\n pathLength: number;\n}\n\nexport interface ContainerInfoRemoteDetails {\n grantRows: ContainerInfoGrantRow[];\n grants: ContainerInfoGrant[];\n groups: OrganizationGroupSummary[];\n security?: ContainerInfoSecurityDetails;\n syncCursors: ContainerInfoSyncCursor[];\n}\n\nexport interface ContainerInfoLocalDetails {\n createdAt: string | null;\n updatedAt: string | null;\n}\n\nexport interface ContainerInfo {\n local: ContainerInfoLocalDetails;\n remoteInfo: ContainerInfoRemoteDetails | null;\n}\n\ninterface ContainerInfoApi {\n getContainerWriterProjection: (\n containerId: string,\n ) => Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport type ContainerInfoRemoteMode = \"always\" | \"if-synced\" | \"never\";\n\ninterface LocalContainerInfoRecord {\n hasSyncedContainer: boolean;\n localCreatedAt: string | null;\n localUpdatedAt: string | null;\n organizationId: string | null;\n parentId: string | null;\n}\n\nfunction sortContainerInfoGrants<T extends ContainerInfoGrant>(\n grants: readonly T[],\n): T[] {\n return [...grants].sort((left, right) =>\n `${left.subjectType}:${left.subjectId}`.localeCompare(\n `${right.subjectType}:${right.subjectId}`,\n ),\n );\n}\n\nfunction toContainerInfoGrant(grant: ContainerInfoGrant): ContainerInfoGrant {\n return {\n accessLevel: grant.accessLevel,\n subjectId: grant.subjectId,\n subjectType: grant.subjectType,\n };\n}\n\nfunction getContainerInfoGrantRows(\n projection: ContainerWriterProjectionResponse,\n): ContainerInfoGrantRow[] {\n const rows = projection.path.flatMap((bundle) => {\n const state = readContainerState(bundle);\n\n return state.directGrants.map((grant) => ({\n ...toContainerInfoGrant(grant),\n inherited: state.containerId !== projection.containerId,\n sourceContainerId: state.containerId,\n }));\n });\n\n return sortContainerInfoGrants(rows);\n}\n\nfunction getContainerInfoPathEntries(\n projection: ContainerWriterProjectionResponse,\n): ContainerInfoPathEntry[] {\n return projection.path.map((bundle, index) => {\n const state = readContainerState(bundle);\n const kek = projection.containerKeks[index];\n if (!kek) {\n throw new Error(\"Container projection path and KEKs are inconsistent\");\n }\n\n return {\n containerId: state.containerId,\n containerKeyEpoch: kek.containerKeyEpoch,\n containerKeyEpochId: kek.containerKeyEpochId,\n directGrantCount: state.directGrants.length,\n eventHash: state.eventHash,\n keyEpochHash: kek.keyEpochHash,\n keyTargetHash: kek.keyTargetHash,\n manifestHash: bundle.manifestHash,\n manifestHistoryCount: kek.containerManifestHistory.length,\n parentContainerId: state.parentContainerId,\n parentManifestHash: state.parentManifestHash,\n recipientTargetCount: kek.recipientTargets.length,\n referencedPrincipalCount: state.referencedPrincipalHeads.length,\n wrapCount: kek.wraps.length,\n };\n });\n}\n\nfunction getContainerInfoSecurityDetails(\n projection: ContainerWriterProjectionResponse,\n): ContainerInfoSecurityDetails {\n const path = getContainerInfoPathEntries(projection);\n const targetPathEntry = path.at(-1);\n const targetKek = projection.containerKeks.at(-1);\n if (!targetPathEntry || !targetKek) {\n throw new Error(\"Container projection is empty\");\n }\n\n return {\n currentContainerKeyEpoch: targetPathEntry.containerKeyEpoch,\n currentContainerKeyEpochId: targetPathEntry.containerKeyEpochId,\n currentManifestHash: targetPathEntry.manifestHash,\n currentManifestHistoryCount: targetPathEntry.manifestHistoryCount,\n currentParentContainerKeyEpochId: targetKek.parentContainerKeyEpochId,\n currentReferencedPrincipalCount: targetPathEntry.referencedPrincipalCount,\n path,\n pathLength: path.length,\n };\n}\n\ninterface ContainerInfoSyncCursorDefinition {\n label: string;\n lane: ContainerSyncWatermarkLane;\n}\n\nfunction getContainerSyncCursorDefinitions(input: {\n containerId: string;\n parentId: string | null;\n}): ContainerInfoSyncCursorDefinition[] {\n return [\n {\n label: \"Parent Listing\",\n lane: containerParentSyncLane(input.parentId),\n },\n {\n label: \"Child Containers\",\n lane: containerParentSyncLane(input.containerId),\n },\n {\n label: \"Documents\",\n lane: containerContentsSyncLane(input.containerId),\n },\n ];\n}\n\nasync function loadContainerSyncCursors(input: {\n containerId: string;\n execSql: ExecSql | null;\n parentId: string | null;\n}): Promise<ContainerInfoSyncCursor[]> {\n const cursorDefinitions = getContainerSyncCursorDefinitions(input);\n let records: Awaited<\n ReturnType<typeof sqlContainerSyncWatermarkPersistence.loadWatermarkRecords>\n > = [];\n if (input.execSql) {\n await sqlContainerSyncWatermarkPersistence.ensureSchema(input.execSql);\n records = await sqlContainerSyncWatermarkPersistence.loadWatermarkRecords(\n input.execSql,\n cursorDefinitions.map(({ lane }) => lane),\n );\n }\n\n return cursorDefinitions.map((definition, index) => {\n const { laneId, laneKind } = containerSyncWatermarkLaneKey(definition.lane);\n const record = records[index] ?? null;\n\n return {\n label: definition.label,\n laneId,\n laneKind,\n savedAt: record?.updatedAt ?? null,\n watermarkId: record?.watermark.id ?? null,\n watermarkUpdatedAt: record?.watermark.updatedAt ?? null,\n };\n });\n}\n\nasync function loadLocalContainerInfoRecord(input: {\n containerId: string;\n execSql: ExecSql | null;\n parentId: string | null;\n}): Promise<LocalContainerInfoRecord> {\n const fallback: LocalContainerInfoRecord = {\n hasSyncedContainer: false,\n localCreatedAt: null,\n localUpdatedAt: null,\n organizationId: null,\n parentId: input.parentId,\n };\n\n if (!input.execSql) {\n return fallback;\n }\n\n await ensureContainerTables(input.execSql);\n\n const { db } = getClientSQLitePersistenceRuntime(input.execSql);\n const rows = await db\n .select({\n localCreatedAt: containers.localCreatedAt,\n localUpdatedAt: containers.localUpdatedAt,\n metadataDocumentId: containers.metadataDocumentId,\n organizationId: containers.organizationId,\n parentId: containers.parentId,\n })\n .from(containers)\n .where(eq(containers.id, input.containerId))\n .limit(1);\n const row = rows[0];\n\n if (!row) {\n return fallback;\n }\n\n return {\n hasSyncedContainer:\n typeof row.metadataDocumentId === \"string\" &&\n row.metadataDocumentId.length > 0,\n localCreatedAt: row.localCreatedAt,\n localUpdatedAt: row.localUpdatedAt,\n organizationId: row.organizationId,\n parentId: row.parentId,\n };\n}\n\nfunction shouldLoadRemoteContainerInfo(input: {\n localContainerInfo: LocalContainerInfoRecord;\n remoteInfoMode: ContainerInfoRemoteMode;\n}): boolean {\n switch (input.remoteInfoMode) {\n case \"always\":\n return true;\n case \"if-synced\":\n return input.localContainerInfo.hasSyncedContainer;\n case \"never\":\n return false;\n }\n}\n\nexport async function loadContainerInfo(input: {\n apiClient: ContainerInfoApi;\n containerId: string;\n containerProjection?: ContainerWriterProjectionResponse | null | undefined;\n execSql?: ExecSql | null;\n loadOrganizationGroups: () => Promise<\n ReadonlyArray<OrganizationGroupSummary>\n >;\n parentId?: string | null;\n remoteInfoMode?: ContainerInfoRemoteMode | undefined;\n}): Promise<ContainerInfo> {\n const localContainerInfo = await loadLocalContainerInfoRecord({\n containerId: input.containerId,\n execSql: input.execSql ?? null,\n parentId: input.parentId ?? null,\n });\n const local = {\n createdAt: localContainerInfo.localCreatedAt,\n updatedAt: localContainerInfo.localUpdatedAt,\n };\n\n if (\n !shouldLoadRemoteContainerInfo({\n localContainerInfo,\n remoteInfoMode: input.remoteInfoMode ?? \"always\",\n })\n ) {\n return {\n local,\n remoteInfo: null,\n };\n }\n\n const [projection, groups, syncCursors] = await Promise.all([\n input.containerProjection\n ? Promise.resolve(input.containerProjection)\n : input.apiClient.getContainerWriterProjection(input.containerId),\n input.loadOrganizationGroups(),\n loadContainerSyncCursors({\n containerId: input.containerId,\n execSql: input.execSql ?? null,\n parentId: localContainerInfo.parentId,\n }),\n ]);\n\n if (!projection) {\n throw new Error(\"Container info could not be loaded.\");\n }\n\n const target = getTargetContainerContext(projection);\n const state = readContainerState(target.manifest);\n\n return {\n local,\n remoteInfo: {\n grantRows: getContainerInfoGrantRows(projection),\n grants: sortContainerInfoGrants(\n state.directGrants.map(toContainerInfoGrant),\n ),\n groups: [...groups],\n security: getContainerInfoSecurityDetails(projection),\n syncCursors,\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerInfo.js","sourceRoot":"","sources":["containerInfo.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EAEL,gCAAgC,EAChC,yBAAyB,EACzB,uBAAuB,EACvB,6BAA6B,GAC9B,MAAM,gFAAgF,CAAC;AACxF,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAwFlG,SAAS,uBAAuB,CAC9B,MAAoB;IAEpB,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,GAAG,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC,aAAa,CACnD,GAAG,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,SAAS,EAAE,CAC1C,CACF,CAAC;AACJ,CAAC;AAED,SAAS,oBAAoB,CAAC,KAAyB;IACrD,OAAO;QACL,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,WAAW,EAAE,KAAK,CAAC,WAAW;KAC/B,CAAC;AACJ,CAAC;AAED,SAAS,yBAAyB,CAChC,UAA6C;IAE7C,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QAC9C,MAAM,KAAK,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;QAEzC,OAAO,KAAK,CAAC,YAAY,CAAC,GAAG,CA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AAG,MAAM,CAAC;YACnB,QAAQ,EAAE,+BAA+B,CAAC,UAAU,CAAC;YACrD,WAAW;SACZ;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n ContainerGrantSubjectType,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { eq } from \"drizzle-orm\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n containerContentsSyncLane,\n containerParentSyncLane,\n containerSyncWatermarkLaneKey,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport { containers } from \"../../../data/sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationGroupSummary } from \"../../organizations/readModel\";\n\nexport type ContainerShareAccessLevel = ContainerAccessLevel;\n\nexport interface ContainerInfoGrant {\n accessLevel: ContainerAccessLevel;\n subjectId: string;\n subjectType: ContainerGrantSubjectType;\n}\n\nexport interface ContainerInfoGrantRow extends ContainerInfoGrant {\n inherited: boolean;\n sourceContainerId: string;\n}\n\nexport interface ContainerInfoSyncCursor {\n label: string;\n laneId: string;\n laneKind: string;\n savedAt: string | null;\n watermarkId: string | null;\n watermarkUpdatedAt: string | null;\n}\n\nexport interface ContainerInfoPathEntry {\n containerId: string;\n containerKeyEpoch: number;\n containerKeyEpochId: string;\n directGrantCount: number;\n eventHash: string;\n keyEpochHash: string;\n keyTargetHash: string;\n manifestHash: string;\n manifestHistoryCount: number;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargetCount: number;\n referencedPrincipalCount: number;\n wrapCount: number;\n}\n\nexport interface ContainerInfoSecurityDetails {\n currentContainerKeyEpoch: number;\n currentContainerKeyEpochId: string;\n currentManifestHash: string;\n currentManifestHistoryCount: number;\n currentParentContainerKeyEpochId: string | null;\n currentReferencedPrincipalCount: number;\n path: ContainerInfoPathEntry[];\n pathLength: number;\n}\n\nexport interface ContainerInfoRemoteDetails {\n grantRows: ContainerInfoGrantRow[];\n grants: ContainerInfoGrant[];\n groups: OrganizationGroupSummary[];\n security?: ContainerInfoSecurityDetails;\n syncCursors: ContainerInfoSyncCursor[];\n}\n\nexport interface ContainerInfoLocalDetails {\n createdAt: string | null;\n updatedAt: string | null;\n}\n\nexport interface ContainerInfo {\n local: ContainerInfoLocalDetails;\n remoteInfo: ContainerInfoRemoteDetails | null;\n}\n\ninterface ContainerInfoApi {\n getContainerWriterProjection: (\n containerId: string,\n ) => Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport type ContainerInfoRemoteMode = \"always\" | \"if-synced\" | \"never\";\n\ninterface LocalContainerInfoRecord {\n hasSyncedContainer: boolean;\n localCreatedAt: string | null;\n localUpdatedAt: string | null;\n organizationId: string | null;\n parentId: string | null;\n}\n\nfunction sortContainerInfoGrants<T extends ContainerInfoGrant>(\n grants: readonly T[],\n): T[] {\n return [...grants].sort((left, right) =>\n `${left.subjectType}:${left.subjectId}`.localeCompare(\n `${right.subjectType}:${right.subjectId}`,\n ),\n );\n}\n\nfunction toContainerInfoGrant(grant: ContainerInfoGrant): ContainerInfoGrant {\n return {\n accessLevel: grant.accessLevel,\n subjectId: grant.subjectId,\n subjectType: grant.subjectType,\n };\n}\n\nfunction getContainerInfoGrantRows(\n projection: ContainerWriterProjectionResponse,\n): ContainerInfoGrantRow[] {\n const rows = projection.path.flatMap((bundle) => {\n const state = readContainerState(bundle);\n\n return state.directGrants.map((grant) => ({\n ...toContainerInfoGrant(grant),\n inherited: state.containerId !== projection.containerId,\n sourceContainerId: state.containerId,\n }));\n });\n\n return sortContainerInfoGrants(rows);\n}\n\nfunction getContainerInfoPathEntries(\n projection: ContainerWriterProjectionResponse,\n): ContainerInfoPathEntry[] {\n return projection.path.map((bundle, index) => {\n const state = readContainerState(bundle);\n const kek = projection.containerKeks[index];\n if (!kek) {\n throw new Error(\"Container projection path and KEKs are inconsistent\");\n }\n\n return {\n containerId: state.containerId,\n containerKeyEpoch: kek.containerKeyEpoch,\n containerKeyEpochId: kek.containerKeyEpochId,\n directGrantCount: state.directGrants.length,\n eventHash: state.eventHash,\n keyEpochHash: kek.keyEpochHash,\n keyTargetHash: kek.keyTargetHash,\n manifestHash: bundle.manifestHash,\n manifestHistoryCount: kek.containerManifestHistory.length,\n parentContainerId: state.parentContainerId,\n parentManifestHash: state.parentManifestHash,\n recipientTargetCount: kek.recipientTargets.length,\n referencedPrincipalCount: state.referencedPrincipalHeads.length,\n wrapCount: kek.wraps.length,\n };\n });\n}\n\nfunction getContainerInfoSecurityDetails(\n projection: ContainerWriterProjectionResponse,\n): ContainerInfoSecurityDetails {\n const path = getContainerInfoPathEntries(projection);\n const targetPathEntry = path.at(-1);\n const targetKek = projection.containerKeks.at(-1);\n if (!targetPathEntry || !targetKek) {\n throw new Error(\"Container projection is empty\");\n }\n\n return {\n currentContainerKeyEpoch: targetPathEntry.containerKeyEpoch,\n currentContainerKeyEpochId: targetPathEntry.containerKeyEpochId,\n currentManifestHash: targetPathEntry.manifestHash,\n currentManifestHistoryCount: targetPathEntry.manifestHistoryCount,\n currentParentContainerKeyEpochId: targetKek.parentContainerKeyEpochId,\n currentReferencedPrincipalCount: targetPathEntry.referencedPrincipalCount,\n path,\n pathLength: path.length,\n };\n}\n\ninterface ContainerInfoSyncCursorDefinition {\n label: string;\n lane: ContainerSyncWatermarkLane;\n}\n\nfunction getContainerSyncCursorDefinitions(input: {\n containerId: string;\n parentId: string | null;\n}): ContainerInfoSyncCursorDefinition[] {\n return [\n {\n label: \"Parent Listing\",\n lane: containerParentSyncLane(input.parentId),\n },\n {\n label: \"Child Containers\",\n lane: containerParentSyncLane(input.containerId),\n },\n {\n label: \"Documents\",\n lane: containerContentsSyncLane(input.containerId),\n },\n ];\n}\n\nasync function loadContainerSyncCursors(input: {\n containerId: string;\n execSql: ExecSql | null;\n parentId: string | null;\n}): Promise<ContainerInfoSyncCursor[]> {\n const cursorDefinitions = getContainerSyncCursorDefinitions(input);\n const records = input.execSql\n ? await new ContainerSyncWatermarkRepository(\n input.execSql,\n ).loadWatermarkRecords(cursorDefinitions.map(({ lane }) => lane))\n : [];\n\n return cursorDefinitions.map((definition, index) => {\n const { laneId, laneKind } = containerSyncWatermarkLaneKey(definition.lane);\n const record = records[index] ?? null;\n\n return {\n label: definition.label,\n laneId,\n laneKind,\n savedAt: record?.updatedAt ?? null,\n watermarkId: record?.watermark.id ?? null,\n watermarkUpdatedAt: record?.watermark.updatedAt ?? null,\n };\n });\n}\n\nasync function loadLocalContainerInfoRecord(input: {\n containerId: string;\n execSql: ExecSql | null;\n parentId: string | null;\n}): Promise<LocalContainerInfoRecord> {\n const fallback: LocalContainerInfoRecord = {\n hasSyncedContainer: false,\n localCreatedAt: null,\n localUpdatedAt: null,\n organizationId: null,\n parentId: input.parentId,\n };\n\n if (!input.execSql) {\n return fallback;\n }\n\n await ensureContainerTables(input.execSql);\n\n const { db } = getClientSQLitePersistenceRuntime(input.execSql);\n const rows = await db\n .select({\n localCreatedAt: containers.localCreatedAt,\n localUpdatedAt: containers.localUpdatedAt,\n metadataDocumentId: containers.metadataDocumentId,\n organizationId: containers.organizationId,\n parentId: containers.parentId,\n })\n .from(containers)\n .where(eq(containers.id, input.containerId))\n .limit(1);\n const row = rows[0];\n\n if (!row) {\n return fallback;\n }\n\n return {\n hasSyncedContainer:\n typeof row.metadataDocumentId === \"string\" &&\n row.metadataDocumentId.length > 0,\n localCreatedAt: row.localCreatedAt,\n localUpdatedAt: row.localUpdatedAt,\n organizationId: row.organizationId,\n parentId: row.parentId,\n };\n}\n\nfunction shouldLoadRemoteContainerInfo(input: {\n localContainerInfo: LocalContainerInfoRecord;\n remoteInfoMode: ContainerInfoRemoteMode;\n}): boolean {\n switch (input.remoteInfoMode) {\n case \"always\":\n return true;\n case \"if-synced\":\n return input.localContainerInfo.hasSyncedContainer;\n case \"never\":\n return false;\n }\n}\n\nexport async function loadContainerInfo(input: {\n apiClient: ContainerInfoApi;\n containerId: string;\n containerProjection?: ContainerWriterProjectionResponse | null | undefined;\n execSql?: ExecSql | null;\n loadOrganizationGroups: () => Promise<\n ReadonlyArray<OrganizationGroupSummary>\n >;\n parentId?: string | null;\n remoteInfoMode?: ContainerInfoRemoteMode | undefined;\n}): Promise<ContainerInfo> {\n const localContainerInfo = await loadLocalContainerInfoRecord({\n containerId: input.containerId,\n execSql: input.execSql ?? null,\n parentId: input.parentId ?? null,\n });\n const local = {\n createdAt: localContainerInfo.localCreatedAt,\n updatedAt: localContainerInfo.localUpdatedAt,\n };\n\n if (\n !shouldLoadRemoteContainerInfo({\n localContainerInfo,\n remoteInfoMode: input.remoteInfoMode ?? \"always\",\n })\n ) {\n return {\n local,\n remoteInfo: null,\n };\n }\n\n const [projection, groups, syncCursors] = await Promise.all([\n input.containerProjection\n ? Promise.resolve(input.containerProjection)\n : input.apiClient.getContainerWriterProjection(input.containerId),\n input.loadOrganizationGroups(),\n loadContainerSyncCursors({\n containerId: input.containerId,\n execSql: input.execSql ?? null,\n parentId: localContainerInfo.parentId,\n }),\n ]);\n\n if (!projection) {\n throw new Error(\"Container info could not be loaded.\");\n }\n\n const target = getTargetContainerContext(projection);\n const state = readContainerState(target.manifest);\n\n return {\n local,\n remoteInfo: {\n grantRows: getContainerInfoGrantRows(projection),\n grants: sortContainerInfoGrants(\n state.directGrants.map(toContainerInfoGrant),\n ),\n groups: [...groups],\n security: getContainerInfoSecurityDetails(projection),\n syncCursors,\n },\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ContainerSyncWatermarkRepository } from "../../../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
|
|
2
2
|
export async function markContainerParentLaneFetched(input) {
|
|
3
3
|
const { response, state, syncLane } = input;
|
|
4
4
|
if (response.hasMore && !response.nextWatermark) {
|
|
@@ -7,7 +7,7 @@ export async function markContainerParentLaneFetched(input) {
|
|
|
7
7
|
// A check marker suppresses startup polling, so record it only after the
|
|
8
8
|
// server confirms this parent lane is fully drained. The cursor and marker
|
|
9
9
|
// share one row and land in one guarded statement.
|
|
10
|
-
const recorded = await
|
|
10
|
+
const recorded = await new ContainerSyncWatermarkRepository(state.runtime.infra.execSql).recordLaneFetch(syncLane, { checked: !response.hasMore, watermark: response.nextWatermark }, { stillCurrent: input.isCurrent });
|
|
11
11
|
if (!recorded || input.isCurrent?.() === false) {
|
|
12
12
|
return false;
|
|
13
13
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"laneFetchMarkers.js","sourceRoot":"","sources":["laneFetchMarkers.ts"],"names":[],"mappings":"AACA,OAAO,
|
|
1
|
+
{"version":3,"file":"laneFetchMarkers.js","sourceRoot":"","sources":["laneFetchMarkers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,mFAAmF,CAAC;AAIrI,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAKpD;IACC,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IAC5C,IAAI,QAAQ,CAAC,OAAO,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC;QAChD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,yEAAyE;IACzE,2EAA2E;IAC3E,mDAAmD;IACnD,MAAM,QAAQ,GAAG,MAAM,IAAI,gCAAgC,CACzD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAC5B,CAAC,eAAe,CACf,QAAQ,EACR,EAAE,OAAO,EAAE,CAAC,QAAQ,CAAC,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAC,aAAa,EAAE,EACjE,EAAE,YAAY,EAAE,KAAK,CAAC,SAAS,EAAE,CAClC,CAAC;IACF,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QAC/C,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IACE,CAAC,QAAQ,CAAC,OAAO;QACjB,QAAQ,CAAC,IAAI,KAAK,kBAAkB;QACpC,QAAQ,CAAC,QAAQ,KAAK,IAAI,EAC1B,CAAC;QACD,KAAK,CAAC,gBAAgB,GAAG,IAAI,CAAC;IAChC,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { ListContainersResponse } from \"@tearleads/validators/response\";\nimport { ContainerSyncWatermarkRepository } from \"../../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport type { ContainerSyncWatermarkLane } from \"../../containerPersistence\";\nimport type { RemoteContainerHydrationState } from \"../types\";\n\nexport async function markContainerParentLaneFetched(input: {\n isCurrent?: (() => boolean) | undefined;\n response: ListContainersResponse;\n state: RemoteContainerHydrationState;\n syncLane: ContainerSyncWatermarkLane;\n}): Promise<boolean> {\n const { response, state, syncLane } = input;\n if (response.hasMore && !response.nextWatermark) {\n return false;\n }\n\n // A check marker suppresses startup polling, so record it only after the\n // server confirms this parent lane is fully drained. The cursor and marker\n // share one row and land in one guarded statement.\n const recorded = await new ContainerSyncWatermarkRepository(\n state.runtime.infra.execSql,\n ).recordLaneFetch(\n syncLane,\n { checked: !response.hasMore, watermark: response.nextWatermark },\n { stillCurrent: input.isCurrent },\n );\n if (!recorded || input.isCurrent?.() === false) {\n return false;\n }\n if (\n !response.hasMore &&\n syncLane.kind === \"container_parent\" &&\n syncLane.parentId === null\n ) {\n state.rootLaneHydrated = true;\n }\n\n return true;\n}\n"]}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ContainerSyncWatermarkRepository } from "../../../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
|
|
2
|
+
import { createContainerParentSyncLane } from "../../containerPersistence.js";
|
|
2
3
|
import { createContainerStateFingerprint } from "../remoteContainers/containerStateFingerprint.js";
|
|
3
4
|
async function prepareContainerParentLanePage(input) {
|
|
4
5
|
const { lane, laneId, state } = input;
|
|
5
6
|
const syncLane = createContainerParentSyncLane(lane.parentId);
|
|
6
7
|
const watermark = lane.watermark === undefined
|
|
7
|
-
? await
|
|
8
|
+
? await new ContainerSyncWatermarkRepository(state.runtime.infra.execSql).loadWatermark(syncLane)
|
|
8
9
|
: lane.watermark;
|
|
9
10
|
return {
|
|
10
11
|
lane,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parentLaneFetch.js","sourceRoot":"","sources":["parentLaneFetch.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"parentLaneFetch.js","sourceRoot":"","sources":["parentLaneFetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,mFAAmF,CAAC;AACrI,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC;AAOhG,KAAK,UAAU,8BAA8B,CAAC,KAI7C;IACC,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,KAAK,CAAC;IACtC,MAAM,QAAQ,GAAG,6BAA6B,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC9D,MAAM,SAAS,GACb,IAAI,CAAC,SAAS,KAAK,SAAS;QAC1B,CAAC,CAAC,MAAM,IAAI,gCAAgC,CACxC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAC5B,CAAC,aAAa,CAAC,QAAQ,CAAC;QAC3B,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC;IACrB,OAAO;QACL,IAAI;QACJ,OAAO,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE;QACvD,QAAQ;KACT,CAAC;AACJ,CAAC;AA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I,CAAC,OAAO,CAAC;KACjD,CAAC,CAAC;IACH,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,oEAAoE;QACpE,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;YAClC,KAAK,CAAC,wBAAwB;gBAC5B,CAAC,KAAK,CAAC,wBAAwB,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,aAAa,GAAG,IAAI,GAAG,CAC3B,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAC/D,CAAC;IACF,IACE,aAAa,CAAC,IAAI,KAAK,aAAa,CAAC,MAAM;QAC3C,QAAQ,CAAC,OAAO,CAAC,MAAM,KAAK,aAAa,CAAC,MAAM,EAChD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;IAED,OAAO,aAAa,CAAC,GAAG,CAAC,CAAC,YAAY,EAAE,EAAE;QACxC,MAAM,IAAI,GAAG,aAAa,CAAC,GAAG,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC5D,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QACnE,CAAC;QACD,OAAO;YACL,uBAAuB;YACvB,2BAA2B;YAC3B,IAAI,EAAE,YAAY,CAAC,IAAI;YACvB,QAAQ,EAAE,IAAI;YACd,QAAQ,EAAE,YAAY,CAAC,QAAQ;SAChC,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { ContainerSyncWatermarkRepository } from \"../../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport { createContainerParentSyncLane } from \"../../containerPersistence\";\nimport { createContainerStateFingerprint } from \"../remoteContainers/containerStateFingerprint\";\nimport type {\n ContainerParentHydrationLane,\n FetchedContainerParentLanePage,\n RemoteContainerHydrationState,\n} from \"../types\";\n\nasync function prepareContainerParentLanePage(input: {\n lane: ContainerParentHydrationLane;\n laneId: string;\n state: RemoteContainerHydrationState;\n}) {\n const { lane, laneId, state } = input;\n const syncLane = createContainerParentSyncLane(lane.parentId);\n const watermark =\n lane.watermark === undefined\n ? await new ContainerSyncWatermarkRepository(\n state.runtime.infra.execSql,\n ).loadWatermark(syncLane)\n : lane.watermark;\n return {\n lane,\n request: { laneId, parentId: lane.parentId, watermark },\n syncLane,\n };\n}\n\nexport async function fetchContainerParentLaneBatch(input: {\n batch: ReadonlyArray<ContainerParentHydrationLane>;\n isCurrent?: (() => boolean) | undefined;\n state: RemoteContainerHydrationState;\n}): Promise<ReadonlyArray<FetchedContainerParentLanePage> | null> {\n const { batch, state } = input;\n const expectedContainerStates = new Map(\n Array.from(state.containersById, ([containerId, containerState]) => [\n containerId,\n {\n container: { ...containerState.container },\n fingerprint: createContainerStateFingerprint(containerState),\n },\n ]),\n );\n const preparedPages = await Promise.all(\n batch.map((lane, index) =>\n prepareContainerParentLanePage({\n lane,\n laneId: `lane-${index}`,\n state,\n }),\n ),\n );\n if (input.isCurrent?.() === false) {\n return null;\n }\n const expectedHydrationTombstones = new Map(\n (\n await state.persistence.loadContainerHydrationTombstones(\n state.runtime.infra.execSql,\n )\n ).map((tombstone) => [tombstone.containerId, tombstone]),\n );\n if (input.isCurrent?.() === false) {\n return null;\n }\n const response = await state.runtime.apiClient.listContainerParentLanes({\n lanes: preparedPages.map((page) => page.request),\n });\n if (!response) {\n // A superseded crawl's failure says nothing about the current tree.\n if (input.isCurrent?.() !== false) {\n state.containerListingFailures =\n (state.containerListingFailures ?? 0) + 1;\n }\n return null;\n }\n\n const pagesByLaneId = new Map(\n response.results.map((result) => [result.laneId, result.page]),\n );\n if (\n pagesByLaneId.size !== preparedPages.length ||\n response.results.length !== preparedPages.length\n ) {\n throw new Error(\"Container parent lane batch response mismatch\");\n }\n\n return preparedPages.map((preparedPage) => {\n const page = pagesByLaneId.get(preparedPage.request.laneId);\n if (!page) {\n throw new Error(\"Container parent lane batch response mismatch\");\n }\n return {\n expectedContainerStates,\n expectedHydrationTombstones,\n lane: preparedPage.lane,\n response: page,\n syncLane: preparedPage.syncLane,\n };\n });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ContainerSyncWatermarkRepository, containerContentsSyncLane, } from "../../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
|
|
2
2
|
import { sqlDocumentContainerProjectionPersistence } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
|
|
3
3
|
import { upsertDiscoveredDocuments } from "../../../data/persistence/documents/documentsPersistence.js";
|
|
4
4
|
import { runSerializedSqlMutation } from "../../../data/sqlite/sqlExec.js";
|
|
@@ -17,7 +17,7 @@ export function guardDocumentDiscoveryWrites(input) {
|
|
|
17
17
|
return {
|
|
18
18
|
replaceDocumentLinksBatch: (inputs, stillCurrent) => whileCurrent(undefined, (lockedExecSql) => sqlDocumentContainerProjectionPersistence.replaceDocumentLinksBatch(lockedExecSql, inputs), stillCurrent),
|
|
19
19
|
saveContainerDocumentWatermark: (containerId, watermark, stillCurrent) => whileCurrent(undefined, async (lockedExecSql) => {
|
|
20
|
-
await
|
|
20
|
+
await new ContainerSyncWatermarkRepository(lockedExecSql).saveWatermark(containerContentsSyncLane(containerId), watermark);
|
|
21
21
|
}, stillCurrent),
|
|
22
22
|
upsertDiscoveredDocuments: (inputs, stillCurrent) => whileCurrent([], (lockedExecSql) => upsertDiscoveredDocuments(lockedExecSql, inputs), stillCurrent),
|
|
23
23
|
async verifyDiscoveredDocuments(...args) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discoveryGuard.js","sourceRoot":"","sources":["discoveryGuard.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,
|
|
1
|
+
{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C,aAAa,EAAE,MAAM,CAAC,EACnE,YAAY,CACb;QACH,KAAK,CAAC,yBAAyB,CAAC,GAAG,IAAI;YACrC,MAAM,YAAY,GAAG,MAAM,KAAK,CAAC,yBAAyB,CAAC,GAAG,IAAI,CAAC,CAAC;YACpE,OAAO;gBACL,GAAG,YAAY;gBACf,SAAS,EAAE,KAAK,IAAI,EAAE,CACpB,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,YAAY,CAAC,SAAS,EAAE,CAAC;aACxD,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n ContainerSyncWatermarkRepository,\n containerContentsSyncLane,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport { sqlDocumentContainerProjectionPersistence } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { upsertDiscoveredDocuments } from \"../../../data/persistence/documents/documentsPersistence\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { DiscoverContainerDocumentsOptions } from \"../documentDiscovery/documentDiscoveryTypes\";\n\ntype PauseGuardedDiscovery = Pick<\n DiscoverContainerDocumentsOptions,\n | \"replaceDocumentLinksBatch\"\n | \"saveContainerDocumentWatermark\"\n | \"upsertDiscoveredDocuments\"\n | \"verifyDiscoveredDocuments\"\n>;\n\n/**\n * Binds a discovery lane's writes to its generation and its organization staying\n * unpaused. Access changes and pauses invalidate in-flight listings, so the\n * apply stops at its next check. Each write already started rechecks under\n * the SQLite mutation lock held by the reset or pause cleanup. A stale listing therefore never restores documents, links, or the\n * watermark the cleanup removed; a watermark saved after the cleanup would\n * otherwise make the listing after a resume skip every unchanged document.\n */\nexport function guardDocumentDiscoveryWrites(input: {\n readonly execSql: ExecSql;\n readonly isPaused: () => boolean;\n readonly verifyDiscoveredDocuments: DiscoverContainerDocumentsOptions[\"verifyDiscoveredDocuments\"];\n}): PauseGuardedDiscovery {\n const whileCurrent = <T>(\n skipped: T,\n write: (lockedExecSql: ExecSql) => Promise<T>,\n stillCurrent: () => Promise<boolean>,\n ): Promise<T> =>\n runSerializedSqlMutation(input.execSql, async (lockedExecSql) =>\n input.isPaused() || !(await stillCurrent())\n ? skipped\n : write(lockedExecSql),\n );\n return {\n replaceDocumentLinksBatch: (inputs, stillCurrent) =>\n whileCurrent(\n undefined,\n (lockedExecSql) =>\n sqlDocumentContainerProjectionPersistence.replaceDocumentLinksBatch(\n lockedExecSql,\n inputs,\n ),\n stillCurrent,\n ),\n saveContainerDocumentWatermark: (containerId, watermark, stillCurrent) =>\n whileCurrent(\n undefined,\n async (lockedExecSql) => {\n await new ContainerSyncWatermarkRepository(\n lockedExecSql,\n ).saveWatermark(containerContentsSyncLane(containerId), watermark);\n },\n stillCurrent,\n ),\n upsertDiscoveredDocuments: (inputs, stillCurrent) =>\n whileCurrent(\n [],\n (lockedExecSql) => upsertDiscoveredDocuments(lockedExecSql, inputs),\n stillCurrent,\n ),\n async verifyDiscoveredDocuments(...args) {\n const verification = await input.verifyDiscoveredDocuments(...args);\n return {\n ...verification,\n isCurrent: async () =>\n !input.isPaused() && (await verification.isCurrent()),\n };\n },\n };\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { base64ToBytes, bytesToBase64 } from "../../../internal/encoding/index.j
|
|
|
2
2
|
import { isPlainObject } from "../../../internal/validators/isPlainObject.js";
|
|
3
3
|
import { isCreateOrganizationRequest, } from "../../../internal/validators/request/index.js";
|
|
4
4
|
import { isOrganizationReplacementAuthorization } from "../../../internal/validators/util/index.js";
|
|
5
|
-
import {
|
|
5
|
+
import { OrganizationProvisioningAttemptRepository } from "../../../data/persistence/organizations/organizationProvisioningAttemptRepository.js";
|
|
6
6
|
import { createExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
7
7
|
const BYTE_MARKER = "__tearleadsProvisioningBytes";
|
|
8
8
|
function buildCreateOrganizationRequest(input) {
|
|
@@ -35,7 +35,7 @@ function buildCreateOrganizationRequest(input) {
|
|
|
35
35
|
};
|
|
36
36
|
}
|
|
37
37
|
export async function loadOrganizationReplacementFinalizationRequest(input) {
|
|
38
|
-
const stored = await
|
|
38
|
+
const stored = await new OrganizationProvisioningAttemptRepository(input.execSql).load(input.replacedOrganizationId);
|
|
39
39
|
if (!stored) {
|
|
40
40
|
throw new Error("Organization replacement attempt is unavailable");
|
|
41
41
|
}
|
|
@@ -146,7 +146,7 @@ export async function makeOrganizationProvisioningAttemptDurable(input) {
|
|
|
146
146
|
(input.nativeSubscriptionRestore
|
|
147
147
|
? `native-subscription-restore:${input.userId}`
|
|
148
148
|
: input.artifacts.organizationId);
|
|
149
|
-
const stored = await
|
|
149
|
+
const stored = await new OrganizationProvisioningAttemptRepository(createExecSql(input.dbClient)).loadOrSave({
|
|
150
150
|
replacedOrganizationId: attemptKey,
|
|
151
151
|
userId: input.userId,
|
|
152
152
|
organizationId: input.artifacts.organizationId,
|
|
@@ -178,7 +178,7 @@ export async function makeOrganizationProvisioningAttemptDurable(input) {
|
|
|
178
178
|
export async function removeNativeSubscriptionRestoreProvisioningAttempt(input) {
|
|
179
179
|
const attemptKey = `native-subscription-restore:${input.userId}`;
|
|
180
180
|
const execSql = createExecSql(input.dbClient);
|
|
181
|
-
const stored = await
|
|
181
|
+
const stored = await new OrganizationProvisioningAttemptRepository(execSql).load(attemptKey);
|
|
182
182
|
if (!stored)
|
|
183
183
|
return true;
|
|
184
184
|
if (stored.userId !== input.userId ||
|
|
@@ -194,6 +194,6 @@ export async function removeNativeSubscriptionRestoreProvisioningAttempt(input)
|
|
|
194
194
|
});
|
|
195
195
|
}
|
|
196
196
|
export async function removeOrganizationProvisioningAttempt(input) {
|
|
197
|
-
return
|
|
197
|
+
return new OrganizationProvisioningAttemptRepository(input.execSql).remove(input, input.canCommit);
|
|
198
198
|
}
|
|
199
199
|
//# sourceMappingURL=organizationProvisioningAttempt.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,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AS,EAAE,KAAK,CAAC,SAAS;QAC1B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,sBAAsB,EAAE,UAAU;QAClC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAM3D;IACC,OAAO,6CAA6C,CAAC,MAAM,CACzD,KAAK,CAAC,OAAO,EACb,KAAK,EACL,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport {\n type CreateOrganizationRequest,\n isCreateOrganizationRequest,\n} from \"@tearleads/validators/request\";\nimport { isOrganizationReplacementAuthorization } from \"@tearleads/validators/util\";\nimport { sqlOrganizationProvisioningAttemptPersistence } from \"../../../data/persistence/organizations/organizationProvisioningAttemptPersistence\";\nimport type {\n ExecSql,\n ExecSqlClientLike,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"../../registration/organizationProvisioning\";\n\nconst BYTE_MARKER = \"__tearleadsProvisioningBytes\";\n\ninterface DurableOrganizationProvisioningAttempt {\n readonly artifacts: OrganizationProvisioningArtifacts;\n readonly request: CreateOrganizationRequest;\n readonly rootContainerId: string;\n}\n\nfunction buildCreateOrganizationRequest(input: {\n artifacts: OrganizationProvisioningArtifacts;\n finalizeReplacement?: boolean | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): CreateOrganizationRequest {\n const { artifacts } = input;\n return {\n userId: input.userId,\n ...(artifacts.replacementAuthorization\n ? { replacementAuthorization: artifacts.replacementAuthorization }\n : {}),\n organizationId: artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n initialRootContainer: artifacts.initialRootContainer,\n initialRootMetadataDocument: artifacts.rootMetadataDocumentRequest,\n initialRosterProfileContainer:\n artifacts.rosterProfileBootstrap.containerRequest,\n initialRosterProfileDocument:\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n initialOrganizationMetadataContainer:\n artifacts.organizationMetadataBootstrap.containerRequest,\n initialOrganizationProfileDocument:\n artifacts.organizationMetadataBootstrap\n .organizationProfileDocumentRequest,\n initialSystemContainers: artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n ...(input.finalizeReplacement ? { finalizeReplacement: true } : {}),\n ...(input.nativeSubscriptionRestore\n ? { nativeSubscriptionRestore: true as const }\n : {}),\n ...(input.replacesOrganizationId\n ? { replacesOrganizationId: input.replacesOrganizationId }\n : {}),\n };\n}\n\nexport async function loadOrganizationReplacementFinalizationRequest(input: {\n execSql: ExecSql;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<CreateOrganizationRequest> {\n const stored = await sqlOrganizationProvisioningAttemptPersistence.load(\n input.execSql,\n input.replacedOrganizationId,\n );\n if (!stored) {\n throw new Error(\"Organization replacement attempt is unavailable\");\n }\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n finalizeReplacement: true,\n replacesOrganizationId: input.replacedOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return request;\n}\n\nfunction serializeArtifacts(artifacts: OrganizationProvisioningArtifacts) {\n return JSON.stringify(artifacts, (_key, value: unknown) => {\n if (value instanceof Uint8Array) {\n return { [BYTE_MARKER]: bytesToBase64(value) };\n }\n return value;\n });\n}\n\nfunction hasRecord(value: Record<string, unknown>, key: string): boolean {\n return isPlainObject(Reflect.get(value, key));\n}\n\nfunction hasBytes(value: Record<string, unknown>, key: string): boolean {\n return Reflect.get(value, key) instanceof Uint8Array;\n}\n\nfunction isMaterializedDocument(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"contentKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction isMaterializedContainer(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"containerKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction hasContainerBootstrapCore(value: Record<string, unknown>): boolean {\n return (\n typeof Reflect.get(value, \"containerId\") === \"string\" &&\n isMaterializedDocument(Reflect.get(value, \"containerMetadataDocument\")) &&\n hasBytes(value, \"containerMetadataInitialUpdate\") &&\n isMaterializedContainer(Reflect.get(value, \"containerPlan\")) &&\n hasRecord(value, \"containerRequest\") &&\n Reflect.get(value, \"systemSlot\") !== undefined\n );\n}\n\nfunction isOrganizationProvisioningArtifacts(\n value: unknown,\n): value is OrganizationProvisioningArtifacts {\n if (!isPlainObject(value)) return false;\n const bootstrap = Reflect.get(value, \"bootstrap\");\n const roster = Reflect.get(value, \"rosterProfileBootstrap\");\n const metadata = Reflect.get(value, \"organizationMetadataBootstrap\");\n const systemContainers = Reflect.get(value, \"systemContainerBootstraps\");\n return (\n (Reflect.get(value, \"replacementAuthorization\") === null ||\n isOrganizationReplacementAuthorization(\n Reflect.get(value, \"replacementAuthorization\"),\n )) &&\n typeof Reflect.get(value, \"organizationId\") === \"string\" &&\n isPlainObject(bootstrap) &&\n hasBytes(bootstrap, \"initialUpdate\") &&\n typeof Reflect.get(bootstrap, \"metadataDocumentId\") === \"string\" &&\n hasRecord(value, \"initialAdminGroup\") &&\n hasRecord(value, \"initialMemberGroup\") &&\n hasRecord(value, \"initialOrganizationPolicy\") &&\n hasRecord(value, \"initialRootContainer\") &&\n isMaterializedContainer(Reflect.get(value, \"rootContainer\")) &&\n isMaterializedDocument(Reflect.get(value, \"rootMetadataDocument\")) &&\n hasRecord(value, \"rootMetadataDocumentRequest\") &&\n isPlainObject(roster) &&\n hasContainerBootstrapCore(roster) &&\n isMaterializedDocument(Reflect.get(roster, \"profileDocument\")) &&\n hasBytes(roster, \"profileDocumentInitialUpdate\") &&\n hasRecord(roster, \"profileDocumentRequest\") &&\n isPlainObject(metadata) &&\n hasContainerBootstrapCore(metadata) &&\n isMaterializedDocument(\n Reflect.get(metadata, \"organizationProfileDocument\"),\n ) &&\n hasRecord(metadata, \"organizationProfileDocumentRequest\") &&\n typeof Reflect.get(metadata, \"organizationProfileSnapshot\") === \"string\" &&\n Array.isArray(systemContainers) &&\n systemContainers.every(\n (container) =>\n isPlainObject(container) && hasContainerBootstrapCore(container),\n )\n );\n}\n\nfunction deserializeArtifacts(\n value: string,\n): OrganizationProvisioningArtifacts {\n const parsed: unknown = JSON.parse(value, (_key, candidate: unknown) => {\n if (\n typeof candidate === \"object\" &&\n candidate !== null &&\n Object.keys(candidate).length === 1 &&\n BYTE_MARKER in candidate\n ) {\n const encoded = Reflect.get(candidate, BYTE_MARKER);\n if (typeof encoded === \"string\") {\n return base64ToBytes(encoded);\n }\n }\n return candidate;\n });\n if (!isOrganizationProvisioningArtifacts(parsed)) {\n throw new Error(\"Stored organization provisioning attempt is invalid\");\n }\n return parsed;\n}\n\nexport async function makeOrganizationProvisioningAttemptDurable(input: {\n artifacts: OrganizationProvisioningArtifacts;\n canStartDurableMutation?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n creationIntent?: string | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): Promise<DurableOrganizationProvisioningAttempt | null> {\n const attemptKey =\n input.replacesOrganizationId ??\n (input.nativeSubscriptionRestore\n ? `native-subscription-restore:${input.userId}`\n : input.artifacts.organizationId);\n const stored = await sqlOrganizationProvisioningAttemptPersistence.loadOrSave(\n createExecSql(input.dbClient),\n {\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n organizationId: input.artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n serializedArtifacts: serializeArtifacts(input.artifacts),\n creationIntent: input.creationIntent,\n },\n input.canStartDurableMutation,\n );\n if (!stored) return null;\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return { artifacts, request, rootContainerId: stored.rootContainerId };\n}\n\nexport async function removeNativeSubscriptionRestoreProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n organizationId: string;\n userId: string;\n}): Promise<boolean> {\n const attemptKey = `native-subscription-restore:${input.userId}`;\n const execSql = createExecSql(input.dbClient);\n const stored = await sqlOrganizationProvisioningAttemptPersistence.load(\n execSql,\n attemptKey,\n );\n if (!stored) return true;\n if (\n stored.userId !== input.userId ||\n stored.organizationId !== input.organizationId\n ) {\n throw new Error(\n \"Stored native restore organization provisioning attempt is inconsistent\",\n );\n }\n return removeOrganizationProvisioningAttempt({\n canCommit: input.canCommit,\n execSql,\n organizationId: input.organizationId,\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n });\n}\n\nexport async function removeOrganizationProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n execSql: ExecSql;\n organizationId?: string | undefined;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<boolean> {\n return sqlOrganizationProvisioningAttemptPersistence.remove(\n input.execSql,\n input,\n input.canCommit,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationProvisioningAttempt.js","sourceRoot":"","sources":["organizationProvisioningAttempt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAEL,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sCAAsC,EAAE,MAAM,4BAA4B,CAAC;AACpF,OAAO,EAAE,yCAAyC,EAAE,MAAM,mFAAmF,CAAC;AAK9I,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAG/D,MAAM,WAAW,GAAG,8BAA8B,CAAC;AAQnD,SAAS,8BAA8B,CAAC,KAOvC;IACC,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAC5B,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,GAAG,CAAC,SAAS,CAAC,wBAAwB;YACpC,CAAC,CAAC,EAAE,wBAAwB,EAAE,SAAS,CAAC,wBAAwB,EAAE;YAClE,CAAC,CAAC,EAAE,CAAC;QACP,cAAc,EAAE,SAAS,CAAC,cAAc;QACxC,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;QAC9C,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;QAChD,yBAAyB,EAAE,SAAS,CAAC,yBAAyB;QAC9D,oBAAoB,EAAE,SAAS,CAAC,oBAAoB;QACpD,2BAA2B,EAAE,SAAS,CAAC,2BAA2B;QAClE,6BAA6B,EAC3B,SAAS,CAAC,sBAAsB,CAAC,gBAAgB;QACnD,4BAA4B,EAC1B,SAAS,CAAC,sBAAsB,CAAC,sBAAsB;QACzD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CAAC,MAAM;QAC9B,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc,EAC9C,CAAC;QACD,MAAM,IAAI,KAAK,CACb,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO,qCAAqC,CAAC;QAC3C,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,sBAAsB,EAAE,UAAU;QAClC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAM3D;IACC,OAAO,IAAI,yCAAyC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,MAAM,CACxE,KAAK,EACL,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport {\n type CreateOrganizationRequest,\n isCreateOrganizationRequest,\n} from \"@tearleads/validators/request\";\nimport { isOrganizationReplacementAuthorization } from \"@tearleads/validators/util\";\nimport { OrganizationProvisioningAttemptRepository } from \"../../../data/persistence/organizations/organizationProvisioningAttemptRepository\";\nimport type {\n ExecSql,\n ExecSqlClientLike,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"../../registration/organizationProvisioning\";\n\nconst BYTE_MARKER = \"__tearleadsProvisioningBytes\";\n\ninterface DurableOrganizationProvisioningAttempt {\n readonly artifacts: OrganizationProvisioningArtifacts;\n readonly request: CreateOrganizationRequest;\n readonly rootContainerId: string;\n}\n\nfunction buildCreateOrganizationRequest(input: {\n artifacts: OrganizationProvisioningArtifacts;\n finalizeReplacement?: boolean | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): CreateOrganizationRequest {\n const { artifacts } = input;\n return {\n userId: input.userId,\n ...(artifacts.replacementAuthorization\n ? { replacementAuthorization: artifacts.replacementAuthorization }\n : {}),\n organizationId: artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n initialRootContainer: artifacts.initialRootContainer,\n initialRootMetadataDocument: artifacts.rootMetadataDocumentRequest,\n initialRosterProfileContainer:\n artifacts.rosterProfileBootstrap.containerRequest,\n initialRosterProfileDocument:\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n initialOrganizationMetadataContainer:\n artifacts.organizationMetadataBootstrap.containerRequest,\n initialOrganizationProfileDocument:\n artifacts.organizationMetadataBootstrap\n .organizationProfileDocumentRequest,\n initialSystemContainers: artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n ...(input.finalizeReplacement ? { finalizeReplacement: true } : {}),\n ...(input.nativeSubscriptionRestore\n ? { nativeSubscriptionRestore: true as const }\n : {}),\n ...(input.replacesOrganizationId\n ? { replacesOrganizationId: input.replacesOrganizationId }\n : {}),\n };\n}\n\nexport async function loadOrganizationReplacementFinalizationRequest(input: {\n execSql: ExecSql;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<CreateOrganizationRequest> {\n const stored = await new OrganizationProvisioningAttemptRepository(\n input.execSql,\n ).load(input.replacedOrganizationId);\n if (!stored) {\n throw new Error(\"Organization replacement attempt is unavailable\");\n }\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n finalizeReplacement: true,\n replacesOrganizationId: input.replacedOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return request;\n}\n\nfunction serializeArtifacts(artifacts: OrganizationProvisioningArtifacts) {\n return JSON.stringify(artifacts, (_key, value: unknown) => {\n if (value instanceof Uint8Array) {\n return { [BYTE_MARKER]: bytesToBase64(value) };\n }\n return value;\n });\n}\n\nfunction hasRecord(value: Record<string, unknown>, key: string): boolean {\n return isPlainObject(Reflect.get(value, key));\n}\n\nfunction hasBytes(value: Record<string, unknown>, key: string): boolean {\n return Reflect.get(value, key) instanceof Uint8Array;\n}\n\nfunction isMaterializedDocument(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"contentKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction isMaterializedContainer(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"containerKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction hasContainerBootstrapCore(value: Record<string, unknown>): boolean {\n return (\n typeof Reflect.get(value, \"containerId\") === \"string\" &&\n isMaterializedDocument(Reflect.get(value, \"containerMetadataDocument\")) &&\n hasBytes(value, \"containerMetadataInitialUpdate\") &&\n isMaterializedContainer(Reflect.get(value, \"containerPlan\")) &&\n hasRecord(value, \"containerRequest\") &&\n Reflect.get(value, \"systemSlot\") !== undefined\n );\n}\n\nfunction isOrganizationProvisioningArtifacts(\n value: unknown,\n): value is OrganizationProvisioningArtifacts {\n if (!isPlainObject(value)) return false;\n const bootstrap = Reflect.get(value, \"bootstrap\");\n const roster = Reflect.get(value, \"rosterProfileBootstrap\");\n const metadata = Reflect.get(value, \"organizationMetadataBootstrap\");\n const systemContainers = Reflect.get(value, \"systemContainerBootstraps\");\n return (\n (Reflect.get(value, \"replacementAuthorization\") === null ||\n isOrganizationReplacementAuthorization(\n Reflect.get(value, \"replacementAuthorization\"),\n )) &&\n typeof Reflect.get(value, \"organizationId\") === \"string\" &&\n isPlainObject(bootstrap) &&\n hasBytes(bootstrap, \"initialUpdate\") &&\n typeof Reflect.get(bootstrap, \"metadataDocumentId\") === \"string\" &&\n hasRecord(value, \"initialAdminGroup\") &&\n hasRecord(value, \"initialMemberGroup\") &&\n hasRecord(value, \"initialOrganizationPolicy\") &&\n hasRecord(value, \"initialRootContainer\") &&\n isMaterializedContainer(Reflect.get(value, \"rootContainer\")) &&\n isMaterializedDocument(Reflect.get(value, \"rootMetadataDocument\")) &&\n hasRecord(value, \"rootMetadataDocumentRequest\") &&\n isPlainObject(roster) &&\n hasContainerBootstrapCore(roster) &&\n isMaterializedDocument(Reflect.get(roster, \"profileDocument\")) &&\n hasBytes(roster, \"profileDocumentInitialUpdate\") &&\n hasRecord(roster, \"profileDocumentRequest\") &&\n isPlainObject(metadata) &&\n hasContainerBootstrapCore(metadata) &&\n isMaterializedDocument(\n Reflect.get(metadata, \"organizationProfileDocument\"),\n ) &&\n hasRecord(metadata, \"organizationProfileDocumentRequest\") &&\n typeof Reflect.get(metadata, \"organizationProfileSnapshot\") === \"string\" &&\n Array.isArray(systemContainers) &&\n systemContainers.every(\n (container) =>\n isPlainObject(container) && hasContainerBootstrapCore(container),\n )\n );\n}\n\nfunction deserializeArtifacts(\n value: string,\n): OrganizationProvisioningArtifacts {\n const parsed: unknown = JSON.parse(value, (_key, candidate: unknown) => {\n if (\n typeof candidate === \"object\" &&\n candidate !== null &&\n Object.keys(candidate).length === 1 &&\n BYTE_MARKER in candidate\n ) {\n const encoded = Reflect.get(candidate, BYTE_MARKER);\n if (typeof encoded === \"string\") {\n return base64ToBytes(encoded);\n }\n }\n return candidate;\n });\n if (!isOrganizationProvisioningArtifacts(parsed)) {\n throw new Error(\"Stored organization provisioning attempt is invalid\");\n }\n return parsed;\n}\n\nexport async function makeOrganizationProvisioningAttemptDurable(input: {\n artifacts: OrganizationProvisioningArtifacts;\n canStartDurableMutation?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n creationIntent?: string | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): Promise<DurableOrganizationProvisioningAttempt | null> {\n const attemptKey =\n input.replacesOrganizationId ??\n (input.nativeSubscriptionRestore\n ? `native-subscription-restore:${input.userId}`\n : input.artifacts.organizationId);\n const stored = await new OrganizationProvisioningAttemptRepository(\n createExecSql(input.dbClient),\n ).loadOrSave(\n {\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n organizationId: input.artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n serializedArtifacts: serializeArtifacts(input.artifacts),\n creationIntent: input.creationIntent,\n },\n input.canStartDurableMutation,\n );\n if (!stored) return null;\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return { artifacts, request, rootContainerId: stored.rootContainerId };\n}\n\nexport async function removeNativeSubscriptionRestoreProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n organizationId: string;\n userId: string;\n}): Promise<boolean> {\n const attemptKey = `native-subscription-restore:${input.userId}`;\n const execSql = createExecSql(input.dbClient);\n const stored = await new OrganizationProvisioningAttemptRepository(\n execSql,\n ).load(attemptKey);\n if (!stored) return true;\n if (\n stored.userId !== input.userId ||\n stored.organizationId !== input.organizationId\n ) {\n throw new Error(\n \"Stored native restore organization provisioning attempt is inconsistent\",\n );\n }\n return removeOrganizationProvisioningAttempt({\n canCommit: input.canCommit,\n execSql,\n organizationId: input.organizationId,\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n });\n}\n\nexport async function removeOrganizationProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n execSql: ExecSql;\n organizationId?: string | undefined;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<boolean> {\n return new OrganizationProvisioningAttemptRepository(input.execSql).remove(\n input,\n input.canCommit,\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"organizationProvisioningAttemptPersistence.js","sourceRoot":"","sources":["organizationProvisioningAttemptPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,gCAAgC,EAChC,qCAAqC,GACtC,MAAM,2DAA2D,CAAC;AACnE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAUhC,MAAM,CAAC,MAAM,6CAA6C,GAAG;IAC3D,KAAK,CAAC,IAAI,CACR,OAAgB,EAChB,sBAA8B;QAE9B,MAAM,eAAe,CAAC,OAAO,EAAE,qCAAqC,CAAC,CAAC;QACtE,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,iCAAiC,CAAC,OAAO,CAAC;aAC9D,EAAE,CAAC,MAAM,CAAC;YACT,sBAAsB,EACpB,gCAAgC,CAAC,sBAAsB;YACzD,MAAM,EAAE,gCAAgC,CAAC,MAAM;YAC/C,cAAc,EAAE,gCAAgC,CAAC,cAAc;YAC/D,eAAe,EAAE,gCAAgC,CAAC,eAAe;YACjE,mBAAmB,EACjB,gCAAgC,CAAC,mBAAmB;SACvD,CAAC;aACD,IAAI,CAAC,gCAAgC,CAAC;aACtC,KAAK,CACJ,EAAE,CACA,gCAAgC,CAAC,sBAAsB,EACvD,sBAAsB,CACvB,CACF,CAAC;QACJ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M,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;YACzE,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,MAAM,CACV,OAAgB,EAChB,KAIC,EACD,SAAuC;QAEvC,MAAM,eAAe,CAAC,OAAO,EAAE,qCAAqC,CAAC,CAAC;QACtE,IAAI,SAAS,IAAI,CAAC,SAAS,EAAE;YAAE,OAAO,KAAK,CAAC;QAC5C,MAAM,OAAO,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;QAC3D,MAAM,MAAM,GAAG,KAAK,EAAE,EAAgC,EAAE,EAAE;YACxD,MAAM,EAAE;iBACL,MAAM,CAAC,gCAAgC,CAAC;iBACxC,KAAK,CACJ,GAAG,CACD,EAAE,CACA,gCAAgC,CAAC,sBAAsB,EACvD,KAAK,CAAC,sBAAsB,CAC7B,EACD,EAAE,CAAC,gCAAgC,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,EACzD,GAAG,CAAC,KAAK,CAAC,cAAc;gBACtB,CAAC,CAAC;oBACE,EAAE,CACA,gCAAgC,CAAC,cAAc,EAC/C,KAAK,CAAC,cAAc,CACrB;iBACF;gBACH,CAAC,CAAC,EAAE,CAAC,CACR,CACF;iBACA,GAAG,EAAE,CAAC;QACX,CAAC,CAAC;QACF,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YAClC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,CAAC,MAAM,OAAO,CAAC,kBAAkB,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;IACzE,CAAC;CACF,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n organizationProvisioningAttempts,\n organizationProvisioningAttemptTables,\n} from \"../../sqlite/schema/organizationProvisioningAttemptSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\n\ninterface OrganizationProvisioningAttemptRecord {\n readonly replacedOrganizationId: string;\n readonly userId: string;\n readonly organizationId: string;\n readonly rootContainerId: string;\n readonly serializedArtifacts: string;\n}\n\nexport const sqlOrganizationProvisioningAttemptPersistence = {\n async load(\n execSql: ExecSql,\n replacedOrganizationId: string,\n ): Promise<OrganizationProvisioningAttemptRecord | null> {\n await ensureSqlTables(execSql, organizationProvisioningAttemptTables);\n const [stored] = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({\n replacedOrganizationId:\n organizationProvisioningAttempts.replacedOrganizationId,\n userId: organizationProvisioningAttempts.userId,\n organizationId: organizationProvisioningAttempts.organizationId,\n rootContainerId: organizationProvisioningAttempts.rootContainerId,\n serializedArtifacts:\n organizationProvisioningAttempts.serializedArtifacts,\n })\n .from(organizationProvisioningAttempts)\n .where(\n eq(\n organizationProvisioningAttempts.replacedOrganizationId,\n replacedOrganizationId,\n ),\n );\n return stored ?? null;\n },\n\n async loadOrSave(\n execSql: ExecSql,\n candidate: OrganizationProvisioningAttemptRecord & {\n readonly creationIntent?: string | undefined;\n },\n canSave?: (() => boolean) | undefined,\n ): Promise<OrganizationProvisioningAttemptRecord | null> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureSqlTables(\n lockedExecSql,\n organizationProvisioningAttemptTables,\n );\n if (canSave && !canSave()) return null;\n const { db } = getClientSQLitePersistenceRuntime(lockedExecSql);\n await db\n .insert(organizationProvisioningAttempts)\n .values({ ...candidate, createdAt: new Date().toISOString() })\n .onConflictDoNothing()\n .run();\n const [stored] = await db\n .select({\n replacedOrganizationId:\n organizationProvisioningAttempts.replacedOrganizationId,\n userId: organizationProvisioningAttempts.userId,\n organizationId: organizationProvisioningAttempts.organizationId,\n rootContainerId: organizationProvisioningAttempts.rootContainerId,\n serializedArtifacts:\n organizationProvisioningAttempts.serializedArtifacts,\n })\n .from(organizationProvisioningAttempts)\n .where(\n candidate.creationIntent\n ? and(\n eq(organizationProvisioningAttempts.userId, candidate.userId),\n eq(\n organizationProvisioningAttempts.creationIntent,\n candidate.creationIntent,\n ),\n )\n : eq(\n organizationProvisioningAttempts.replacedOrganizationId,\n candidate.replacedOrganizationId,\n ),\n );\n if (!stored) {\n throw new Error(\"Organization provisioning attempt was not persisted\");\n }\n return stored;\n });\n },\n\n async remove(\n execSql: ExecSql,\n input: {\n organizationId?: string | undefined;\n replacedOrganizationId: string;\n userId: string;\n },\n canCommit?: (() => boolean) | undefined,\n ): Promise<boolean> {\n await ensureSqlTables(execSql, organizationProvisioningAttemptTables);\n if (canCommit && !canCommit()) return false;\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const remove = async (tx: ClientSQLiteTransactionScope) => {\n await tx\n .delete(organizationProvisioningAttempts)\n .where(\n and(\n eq(\n organizationProvisioningAttempts.replacedOrganizationId,\n input.replacedOrganizationId,\n ),\n eq(organizationProvisioningAttempts.userId, input.userId),\n ...(input.organizationId\n ? [\n eq(\n organizationProvisioningAttempts.organizationId,\n input.organizationId,\n ),\n ]\n : []),\n ),\n )\n .run();\n };\n if (!canCommit) {\n await runtime.transaction(remove);\n return true;\n }\n return (await runtime.guardedTransaction(remove, canCommit)).committed;\n },\n};\n"]}
|