@tearleads/client-sdk 0.1.248 → 0.1.249
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/organizations/index.js +5 -3
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationGroupPresentation.d.ts +1 -1
- package/client/organizations/organizationGroupPresentation.js.map +1 -1
- package/client/organizations/organizationLeaveRequestVerifier.js +21 -0
- package/client/organizations/organizationLeaveRequestVerifier.js.map +1 -0
- package/client/organizations/{organizationReadModels.d.ts → organizationReadModelCoordinator.d.ts} +18 -16
- package/client/organizations/organizationReadModelCoordinator.js +2 -0
- package/client/organizations/organizationReadModelCoordinator.js.map +1 -0
- package/client/organizations/organizationReadModelPresentation.js +51 -0
- package/client/organizations/organizationReadModelPresentation.js.map +1 -0
- package/client/organizations/organizationReadModelScopes.js +37 -0
- package/client/organizations/organizationReadModelScopes.js.map +1 -0
- package/client/organizations/organizationReadModels.js +131 -88
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationsTypes.d.ts +13 -5
- package/client/organizations/organizationsTypes.js.map +1 -1
- package/client/organizations/principalMutations.d.ts +18 -2
- package/client/organizations/principalMutations.js +29 -15
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/runtime/principalMutationApi.d.ts +2 -0
- package/client/runtime/principalMutationApi.js +2 -0
- package/client/runtime/principalMutationApi.js.map +1 -1
- package/client/runtime/principalMutationDispatch.js +47 -10
- package/client/runtime/principalMutationDispatch.js.map +1 -1
- package/client/runtime/workflowRuntime.js +5 -4
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/data/containers/shared/mutationRequestOptions.d.ts +2 -0
- package/data/containers/shared/mutationRequestOptions.js.map +1 -1
- package/data/containers/shared/types.d.ts +12 -2
- package/data/containers/shared/types.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelRepository.js +20 -2
- package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +4 -1
- package/internal/api-client/client/containerMutations.d.ts +2 -2
- package/internal/api-client/client/containerMutations.js +2 -1
- package/internal/api-client/client/containerMutations.js.map +1 -1
- package/internal/api-client/client/principalPolicies.d.ts +3 -0
- package/internal/api-client/principalPolicyRequests.d.ts +2 -0
- package/internal/api-client/principalPolicyRequests.js +6 -4
- package/internal/api-client/principalPolicyRequests.js.map +1 -1
- package/internal/api-client/routes/containers/mutations.js +3 -3
- package/internal/api-client/routes/containers/mutations.js.map +1 -1
- package/internal/api-client/routes/organizations/createGroup.js +3 -5
- package/internal/api-client/routes/organizations/createGroup.js.map +1 -1
- package/internal/api-client/routes/principals/policy.js +2 -5
- package/internal/api-client/routes/principals/policy.js.map +1 -1
- package/internal/api-client/types.d.ts +6 -0
- package/internal/api-client/types.js.map +1 -1
- package/internal/validators/operation/containerMutations.d.ts +20 -3
- package/internal/validators/operation/containerMutations.js +18 -20
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/internal/validators/operation/index.d.ts +1 -1
- package/internal/validators/operation/index.js +1 -1
- package/internal/validators/operation/index.js.map +1 -1
- package/internal/validators/operation/organizations.d.ts +17 -1
- package/internal/validators/operation/organizations.js +4 -2
- package/internal/validators/operation/organizations.js.map +1 -1
- package/internal/validators/operation/principals.d.ts +17 -1
- package/internal/validators/operation/principals.js +5 -2
- package/internal/validators/operation/principals.js.map +1 -1
- package/internal/validators/request/index.d.ts +1 -1
- package/internal/validators/request/index.js +1 -1
- package/internal/validators/request/index.js.map +1 -1
- package/internal/validators/request/organization.d.ts +15 -0
- package/internal/validators/request/organization.js +8 -0
- package/internal/validators/request/organization.js.map +1 -1
- package/internal/validators/response/areas/organizations.d.ts +3 -2
- package/internal/validators/response/areas/organizations.js +3 -2
- package/internal/validators/response/areas/organizations.js.map +1 -1
- package/internal/validators/response/areas/principals.d.ts +1 -1
- package/internal/validators/response/areas/principals.js +1 -1
- package/internal/validators/response/areas/principals.js.map +1 -1
- package/internal/validators/response/committedReadModel.d.ts +697 -0
- package/internal/validators/response/committedReadModel.js +52 -0
- package/internal/validators/response/committedReadModel.js.map +1 -0
- package/internal/validators/response/container.d.ts +52 -0
- package/internal/validators/response/container.js +3 -3
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/organization.d.ts +0 -191
- package/internal/validators/response/organization.js +0 -7
- package/internal/validators/response/organization.js.map +1 -1
- package/internal/validators/response/organizationReadModel.d.ts +167 -0
- package/internal/validators/response/organizationReadModel.js +5 -0
- package/internal/validators/response/organizationReadModel.js.map +1 -1
- package/internal/validators/response/principal.d.ts +0 -403
- package/internal/validators/response/principal.js +0 -8
- package/internal/validators/response/principal.js.map +1 -1
- package/package.json +1 -1
- package/workflows/container-contents/container-state/organizationHost.d.ts +9 -0
- package/workflows/container-contents/container-state/organizationHost.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +6 -0
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/containers/child/share/index.d.ts +4 -2
- package/workflows/containers/child/share/index.js +37 -20
- package/workflows/containers/child/share/index.js.map +1 -1
- package/workflows/organizations/containerContentsHost.js +20 -1
- package/workflows/organizations/containerContentsHost.js.map +1 -1
- package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +5 -1
- package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js +8 -1
- package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
- package/workflows/organizations/index.d.ts +1 -0
- package/workflows/organizations/index.js +1 -0
- package/workflows/organizations/index.js.map +1 -1
- package/workflows/organizations/readModel/committedReadModel.d.ts +66 -0
- package/workflows/organizations/readModel/committedReadModel.js +150 -0
- package/workflows/organizations/readModel/committedReadModel.js.map +1 -0
- package/workflows/organizations/readModel/readModelProjection.d.ts +15 -2
- package/workflows/organizations/readModel/readModelProjection.js +26 -4
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
|
@@ -17,6 +17,7 @@ export type { PrincipalMutationResponse } from "./principalMutations/principalOp
|
|
|
17
17
|
export { type AcknowledgedPrincipalCurrentInput, type AcknowledgedPrincipalCurrentRetirement, retainAcknowledgedPrincipalCurrents, } from "./principalMutations/retainAcknowledgedPrincipalCurrents.js";
|
|
18
18
|
export { addOrganizationGroupUser, buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, createOrganizationGroup, removeOrganizationGroupUser, rotateOrganizationGroupForAccessSetShrink, } from "./principalPolicy/index.js";
|
|
19
19
|
export { buildOrganizationGroupPolicyHistory, type OrganizationContainerGrant, type OrganizationContainerGrants, type OrganizationDirectory, type OrganizationDirectoryAndGroups, type OrganizationDirectoryUser, type OrganizationGroupContainer, type OrganizationGroupContainers, type OrganizationGroupDetails, type OrganizationGroupMember, type OrganizationGroupMembers, type OrganizationGroupPolicyHistory, type OrganizationGroupPolicyHistoryEntry, type OrganizationGroupSummary, type OrganizationPolicyGrantChange, type OrganizationPolicyGroupChange, type OrganizationPolicyHistory, type OrganizationPolicyHistoryEntry, type OrganizationPrincipalMemberChange, type OrganizationPrincipalMemberChangeType, type OrganizationPrincipalPolicyHistory, type OrganizationPrincipalPolicyHistoryEntry, type OrganizationProfile, type OrganizationUserDetail, updateOrganizationProfile, updateOrganizationRosterEntry, } from "./readModel/index.js";
|
|
20
|
+
export { applyCommittedOrganizationReadModel, awaitCommittedReadModelOffers, beginCommittedReadModel, type CommittedReadModelLease, type CommittedReadModelOffer, type CommittedReadModelOutcome, claimCommittedReadModelOffer, loadHeldOrganizationReadModelCursor, } from "./readModel/committedReadModel.js";
|
|
20
21
|
export { loadLocalOrganizationDataUsage, type OrganizationDataUsage, type ReconcileOrganizationDataUsageInput, reconcileOrganizationDataUsage, } from "./readModel/dataUsageReadModel.js";
|
|
21
22
|
export { measureOrganizationDeviceDataUsage, ORGANIZATION_DOCUMENT_USAGE_CATEGORIES, type OrganizationDeviceDataUsage, type OrganizationDeviceDocumentUsageCategoryBreakdown, type OrganizationDocumentUsageCategory, } from "./readModel/deviceDataUsage.js";
|
|
22
23
|
export { type LocalOrganizationSummary, listLocalOrganizations, } from "./readModel/listLocalOrganizations.js";
|
|
@@ -15,6 +15,7 @@ export { PrincipalMutationOutcomeUnknownError, recoverJournaledPrincipalMutation
|
|
|
15
15
|
export { retainAcknowledgedPrincipalCurrents, } from "./principalMutations/retainAcknowledgedPrincipalCurrents.js";
|
|
16
16
|
export { addOrganizationGroupUser, buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, createOrganizationGroup, removeOrganizationGroupUser, rotateOrganizationGroupForAccessSetShrink, } from "./principalPolicy/index.js";
|
|
17
17
|
export { buildOrganizationGroupPolicyHistory, updateOrganizationProfile, updateOrganizationRosterEntry, } from "./readModel/index.js";
|
|
18
|
+
export { applyCommittedOrganizationReadModel, awaitCommittedReadModelOffers, beginCommittedReadModel, claimCommittedReadModelOffer, loadHeldOrganizationReadModelCursor, } from "./readModel/committedReadModel.js";
|
|
18
19
|
export { loadLocalOrganizationDataUsage, reconcileOrganizationDataUsage, } from "./readModel/dataUsageReadModel.js";
|
|
19
20
|
export { measureOrganizationDeviceDataUsage, ORGANIZATION_DOCUMENT_USAGE_CATEGORIES, } from "./readModel/deviceDataUsage.js";
|
|
20
21
|
export { listLocalOrganizations, } from "./readModel/listLocalOrganizations.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,0CAA0C,GAC3C,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAK3G,OAAO,EAAE,gCAAgC,EAAE,MAAM,sDAAsD,CAAC;AACxG,OAAO,EACL,wBAAwB,EACxB,gBAAgB,EAChB,8BAA8B,EAC9B,mCAAmC,EACnC,oBAAoB,EACpB,2BAA2B,EAC3B,uBAAuB,EACvB,8BAA8B,EAC9B,oCAAoC,EACpC,yBAAyB,EAOzB,8BAA8B,EA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EACL,oCAAoC,EACpC,oCAAoC,EACpC,uCAAuC,EACvC,kCAAkC,EAClC,oCAAoC,EACpC,+BAA+B,GAChC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EAEjC,uCAAuC,GACxC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,EAC/B,sCAAsC,EACtC,6CAA6C,EAC7C,kDAAkD,EAClD,+BAA+B,EAC/B,oCAAoC,EACpC,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC","sourcesContent":["export {\n type OrganizationReadModelInvalidationListener,\n subscribeOrganizationReadModelInvalidation,\n} from \"../../data/persistence/organizations/organizationReadModelInvalidation\";\nexport { PendingPrincipalMutationError } from \"../../data/persistence/principalMutationJournalPersistence\";\nexport type {\n AuthoredPrincipalMutation,\n PrincipalMutationJournalScope,\n} from \"../../data/principals/principalMutationJournal\";\nexport { UnreadablePrincipalMutationError } from \"../../data/principals/principalMutationJournalRecord\";\nexport {\n cancelStripeSubscription,\n changeStripePlan,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createStripeCheckout,\n createStripeCheckoutSession,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n type OrganizationBilling,\n type OrganizationBillingHistory,\n type OrganizationBillingHistoryEntry,\n type OrganizationBillingManagementUrl,\n type OrganizationBillingView,\n type OrganizationNativePurchaseEligibility,\n resolveOrganizationBillingView,\n type StripeCheckoutIntent,\n type StripeCheckoutOptions,\n startOrganizationTrial,\n} from \"./billing\";\nexport { revokeOrganizationContainerGrant } from \"./containerGrantRevocation\";\nexport { GroupMembershipNameMismatchError } from \"./groupNames/groupMembershipName\";\nexport {\n GroupShareNameMismatchError,\n shareRemoteContainerWithGroup,\n} from \"./groupShare\";\nexport { deleteOrganizationGroup } from \"./groups/deleteOrganizationGroup\";\nexport {\n type OrganizationLeaveRequestResult,\n setOrganizationLeaveRequested,\n} from \"./memberships/leaveRequest\";\nexport {\n withVerifiedDirectoryUser,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"./memberships/leaveRequestVerification\";\nexport {\n type OrganizationContentHost,\n type OrganizationMembership,\n type OrganizationMembershipApi,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationSyncPaused,\n} from \"./memberships/organizationMemberships\";\nexport {\n buildOrganizationProfileDocumentPatch,\n createInitializedOrganizationProfileDocument,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n getOrganizationProfileDocumentLocalId,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n readOrganizationProfileName,\n} from \"./organizationProfile\";\nexport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n readJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalManagement\";\nexport {\n type PrincipalMutationJournalContext,\n PrincipalMutationOutcomeUnknownError,\n recoverJournaledPrincipalMutation,\n submitJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalSession\";\nexport type { PrincipalMutationResponse } from \"./principalMutations/principalOperationReceipt\";\nexport {\n type AcknowledgedPrincipalCurrentInput,\n type AcknowledgedPrincipalCurrentRetirement,\n retainAcknowledgedPrincipalCurrents,\n} from \"./principalMutations/retainAcknowledgedPrincipalCurrents\";\nexport {\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n createOrganizationGroup,\n removeOrganizationGroupUser,\n rotateOrganizationGroupForAccessSetShrink,\n} from \"./principalPolicy\";\nexport {\n buildOrganizationGroupPolicyHistory,\n type OrganizationContainerGrant,\n type OrganizationContainerGrants,\n type OrganizationDirectory,\n type OrganizationDirectoryAndGroups,\n type OrganizationDirectoryUser,\n type OrganizationGroupContainer,\n type OrganizationGroupContainers,\n type OrganizationGroupDetails,\n type OrganizationGroupMember,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationGroupPolicyHistoryEntry,\n type OrganizationGroupSummary,\n type OrganizationPolicyGrantChange,\n type OrganizationPolicyGroupChange,\n type OrganizationPolicyHistory,\n type OrganizationPolicyHistoryEntry,\n type OrganizationPrincipalMemberChange,\n type OrganizationPrincipalMemberChangeType,\n type OrganizationPrincipalPolicyHistory,\n type OrganizationPrincipalPolicyHistoryEntry,\n type OrganizationProfile,\n type OrganizationUserDetail,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./readModel\";\nexport {\n loadLocalOrganizationDataUsage,\n type OrganizationDataUsage,\n type ReconcileOrganizationDataUsageInput,\n reconcileOrganizationDataUsage,\n} from \"./readModel/dataUsageReadModel\";\nexport {\n measureOrganizationDeviceDataUsage,\n ORGANIZATION_DOCUMENT_USAGE_CATEGORIES,\n type OrganizationDeviceDataUsage,\n type OrganizationDeviceDocumentUsageCategoryBreakdown,\n type OrganizationDocumentUsageCategory,\n} from \"./readModel/deviceDataUsage\";\nexport {\n type LocalOrganizationSummary,\n listLocalOrganizations,\n} from \"./readModel/listLocalOrganizations\";\nexport {\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupPolicyHistory,\n loadLocalOrganizationPolicyHistory,\n loadLocalOrganizationPolicyReference,\n loadLocalOrganizationUserDetail,\n} from \"./readModel/localReadModelDetails\";\nexport {\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupMembers,\n type ReconcileOrganizationDirectoryAndGroupsInput,\n reconcileOrganizationDirectoryAndGroups,\n} from \"./readModel/readModelProjection\";\nexport {\n buildRosterProfileDocumentPatch,\n createInitializedRosterProfileDocument,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"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AA0D,CAAC;AAClE,OAAO,EACL,wBAAwB,EACxB,8BAA8B,EAC9B,oCAAoC,EACpC,uBAAuB,EACvB,2BAA2B,EAC3B,yCAAyC,GAC1C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,mCAAmC,EAwBnC,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,mCAAmC,EACnC,6BAA6B,EAC7B,uBAAuB,EAIvB,4BAA4B,EAC5B,mCAAmC,GACpC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,8BAA8B,EAG9B,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,kCAAkC,EAClC,sCAAsC,GAIvC,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAEL,sBAAsB,GACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,oCAAoC,EACpC,oCAAoC,EACpC,uCAAuC,EACvC,kCAAkC,EAClC,oCAAoC,EACpC,+BAA+B,GAChC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EAEjC,uCAAuC,GACxC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,EAC/B,sCAAsC,EACtC,6CAA6C,EAC7C,kDAAkD,EAClD,+BAA+B,EAC/B,oCAAoC,EACpC,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC","sourcesContent":["export {\n type OrganizationReadModelInvalidationListener,\n subscribeOrganizationReadModelInvalidation,\n} from \"../../data/persistence/organizations/organizationReadModelInvalidation\";\nexport { PendingPrincipalMutationError } from \"../../data/persistence/principalMutationJournalPersistence\";\nexport type {\n AuthoredPrincipalMutation,\n PrincipalMutationJournalScope,\n} from \"../../data/principals/principalMutationJournal\";\nexport { UnreadablePrincipalMutationError } from \"../../data/principals/principalMutationJournalRecord\";\nexport {\n cancelStripeSubscription,\n changeStripePlan,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createStripeCheckout,\n createStripeCheckoutSession,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n type OrganizationBilling,\n type OrganizationBillingHistory,\n type OrganizationBillingHistoryEntry,\n type OrganizationBillingManagementUrl,\n type OrganizationBillingView,\n type OrganizationNativePurchaseEligibility,\n resolveOrganizationBillingView,\n type StripeCheckoutIntent,\n type StripeCheckoutOptions,\n startOrganizationTrial,\n} from \"./billing\";\nexport { revokeOrganizationContainerGrant } from \"./containerGrantRevocation\";\nexport { GroupMembershipNameMismatchError } from \"./groupNames/groupMembershipName\";\nexport {\n GroupShareNameMismatchError,\n shareRemoteContainerWithGroup,\n} from \"./groupShare\";\nexport { deleteOrganizationGroup } from \"./groups/deleteOrganizationGroup\";\nexport {\n type OrganizationLeaveRequestResult,\n setOrganizationLeaveRequested,\n} from \"./memberships/leaveRequest\";\nexport {\n withVerifiedDirectoryUser,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"./memberships/leaveRequestVerification\";\nexport {\n type OrganizationContentHost,\n type OrganizationMembership,\n type OrganizationMembershipApi,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationSyncPaused,\n} from \"./memberships/organizationMemberships\";\nexport {\n buildOrganizationProfileDocumentPatch,\n createInitializedOrganizationProfileDocument,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n getOrganizationProfileDocumentLocalId,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n readOrganizationProfileName,\n} from \"./organizationProfile\";\nexport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n readJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalManagement\";\nexport {\n type PrincipalMutationJournalContext,\n PrincipalMutationOutcomeUnknownError,\n recoverJournaledPrincipalMutation,\n submitJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalSession\";\nexport type { PrincipalMutationResponse } from \"./principalMutations/principalOperationReceipt\";\nexport {\n type AcknowledgedPrincipalCurrentInput,\n type AcknowledgedPrincipalCurrentRetirement,\n retainAcknowledgedPrincipalCurrents,\n} from \"./principalMutations/retainAcknowledgedPrincipalCurrents\";\nexport {\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n createOrganizationGroup,\n removeOrganizationGroupUser,\n rotateOrganizationGroupForAccessSetShrink,\n} from \"./principalPolicy\";\nexport {\n buildOrganizationGroupPolicyHistory,\n type OrganizationContainerGrant,\n type OrganizationContainerGrants,\n type OrganizationDirectory,\n type OrganizationDirectoryAndGroups,\n type OrganizationDirectoryUser,\n type OrganizationGroupContainer,\n type OrganizationGroupContainers,\n type OrganizationGroupDetails,\n type OrganizationGroupMember,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationGroupPolicyHistoryEntry,\n type OrganizationGroupSummary,\n type OrganizationPolicyGrantChange,\n type OrganizationPolicyGroupChange,\n type OrganizationPolicyHistory,\n type OrganizationPolicyHistoryEntry,\n type OrganizationPrincipalMemberChange,\n type OrganizationPrincipalMemberChangeType,\n type OrganizationPrincipalPolicyHistory,\n type OrganizationPrincipalPolicyHistoryEntry,\n type OrganizationProfile,\n type OrganizationUserDetail,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./readModel\";\nexport {\n applyCommittedOrganizationReadModel,\n awaitCommittedReadModelOffers,\n beginCommittedReadModel,\n type CommittedReadModelLease,\n type CommittedReadModelOffer,\n type CommittedReadModelOutcome,\n claimCommittedReadModelOffer,\n loadHeldOrganizationReadModelCursor,\n} from \"./readModel/committedReadModel\";\nexport {\n loadLocalOrganizationDataUsage,\n type OrganizationDataUsage,\n type ReconcileOrganizationDataUsageInput,\n reconcileOrganizationDataUsage,\n} from \"./readModel/dataUsageReadModel\";\nexport {\n measureOrganizationDeviceDataUsage,\n ORGANIZATION_DOCUMENT_USAGE_CATEGORIES,\n type OrganizationDeviceDataUsage,\n type OrganizationDeviceDocumentUsageCategoryBreakdown,\n type OrganizationDocumentUsageCategory,\n} from \"./readModel/deviceDataUsage\";\nexport {\n type LocalOrganizationSummary,\n listLocalOrganizations,\n} from \"./readModel/listLocalOrganizations\";\nexport {\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupPolicyHistory,\n loadLocalOrganizationPolicyHistory,\n loadLocalOrganizationPolicyReference,\n loadLocalOrganizationUserDetail,\n} from \"./readModel/localReadModelDetails\";\nexport {\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupMembers,\n type ReconcileOrganizationDirectoryAndGroupsInput,\n reconcileOrganizationDirectoryAndGroups,\n} from \"./readModel/readModelProjection\";\nexport {\n buildRosterProfileDocumentPatch,\n createInitializedRosterProfileDocument,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"./rosterProfileContainer\";\n"]}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { OrganizationReadModelDeltaResponse } from "../../../internal/validators/response/index.js";
|
|
2
|
+
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
3
|
+
import type { OrganizationDirectoryAndGroups } from "./index.js";
|
|
4
|
+
import { applyOrganizationReadModelPageAt } from "./readModelProjection.js";
|
|
5
|
+
/**
|
|
6
|
+
* The read-model delta one of this device's mutations carried back, and the
|
|
7
|
+
* cursor it held when it sent the mutation: the page a feed read from that
|
|
8
|
+
* cursor returns once the mutation committed.
|
|
9
|
+
*/
|
|
10
|
+
export interface CommittedReadModelOffer {
|
|
11
|
+
readonly delta: OrganizationReadModelDeltaResponse;
|
|
12
|
+
readonly heldCursor: string;
|
|
13
|
+
}
|
|
14
|
+
/** What applying an offer presented; `undefined` when it applied nothing. */
|
|
15
|
+
export type CommittedReadModelOutcome = OrganizationDirectoryAndGroups | null | undefined;
|
|
16
|
+
interface CommittedReadModelScope {
|
|
17
|
+
/** The runtime's domain scope; an identity switch replaces it. */
|
|
18
|
+
readonly domainScope: object;
|
|
19
|
+
readonly execSql: ExecSql;
|
|
20
|
+
readonly organizationId: string;
|
|
21
|
+
/** The runtime's session generation; a logout or new login advances it. */
|
|
22
|
+
readonly sessionGeneration: number;
|
|
23
|
+
readonly userId: string;
|
|
24
|
+
}
|
|
25
|
+
/** A mutation that sent a held cursor; settle it once, when it ends. */
|
|
26
|
+
export interface CommittedReadModelLease {
|
|
27
|
+
readonly heldCursor: string | undefined;
|
|
28
|
+
settle(delta: OrganizationReadModelDeltaResponse | undefined): void;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Begin a mutation that sends the read-model cursor this requester's next
|
|
32
|
+
* reconcile would request from, so its response can carry the delta from it.
|
|
33
|
+
* Until it settles, a realtime hint's cursor check waits for it. No cursor is
|
|
34
|
+
* held while the requester's presentation is denied, since that reconcile
|
|
35
|
+
* requests a snapshot, or when the projection cannot be read.
|
|
36
|
+
*/
|
|
37
|
+
export declare function beginCommittedReadModel(scope: CommittedReadModelScope,
|
|
38
|
+
/** How many cursors the mutation can stamp; a share stamps one. */
|
|
39
|
+
maxStamps?: number): Promise<CommittedReadModelLease>;
|
|
40
|
+
/**
|
|
41
|
+
* Wait, for a bounded time, for this scope's mutations in flight that could
|
|
42
|
+
* be the commit a realtime hint names, then list every unclaimed delta, oldest
|
|
43
|
+
* first: a hint names a commit, and an offer at or past it reflects that
|
|
44
|
+
* commit. A mutation still in flight after the wait leaves the check to read.
|
|
45
|
+
*/
|
|
46
|
+
export declare function awaitCommittedReadModelOffers(scope: CommittedReadModelScope,
|
|
47
|
+
/** Without a hint position, every mutation in flight is waited for. */
|
|
48
|
+
hintPosition: bigint | undefined, maxWaitMs?: number): Promise<readonly CommittedReadModelOffer[]>;
|
|
49
|
+
/**
|
|
50
|
+
* Apply one offer once, by its delta. The first claimant (a hint's cursor
|
|
51
|
+
* check or the mutation's own reconcile) runs `apply`; a later claimant of the
|
|
52
|
+
* same delta shares that outcome instead of reading. `undefined` when the
|
|
53
|
+
* scope holds no such offer.
|
|
54
|
+
*/
|
|
55
|
+
export declare function claimCommittedReadModelOffer(scope: CommittedReadModelScope, delta: OrganizationReadModelDeltaResponse, apply: (offer: CommittedReadModelOffer) => Promise<CommittedReadModelOutcome>): Promise<CommittedReadModelOutcome> | undefined;
|
|
56
|
+
/** The projection cursor a reconcile of this requester would request from. */
|
|
57
|
+
export declare function loadHeldOrganizationReadModelCursor(scope: CommittedReadModelScope): Promise<string | undefined>;
|
|
58
|
+
/**
|
|
59
|
+
* Apply the read-model delta a mutation's response carried as the page a feed
|
|
60
|
+
* read from `requestedCursor` returns, with no request. Resolves `undefined`
|
|
61
|
+
* when it is not applied: its cursor does not advance past the one sent, the
|
|
62
|
+
* projection no longer holds that cursor, or the page applied stale. The
|
|
63
|
+
* caller then reads the feed as before.
|
|
64
|
+
*/
|
|
65
|
+
export declare function applyCommittedOrganizationReadModel(input: Parameters<typeof applyOrganizationReadModelPageAt>[0]): Promise<OrganizationDirectoryAndGroups | null | undefined>;
|
|
66
|
+
export {};
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { organizationReadModelCursorPosition } from "../../../internal/validators/organizationReadModelCursor.js";
|
|
2
|
+
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
3
|
+
import { isOrganizationPresentationAccessReadable, organizationAccessScopeKey, } from "./organizationPresentationAccessState.js";
|
|
4
|
+
import { applyOrganizationReadModelPageAt } from "./readModelProjection.js";
|
|
5
|
+
/** A settled offer older than this many is dropped unread. */
|
|
6
|
+
const MAX_SETTLED_OFFERS = 4;
|
|
7
|
+
/** A hint's cursor check waits no longer than this for mutations in flight. */
|
|
8
|
+
const MAX_PENDING_WAIT_MS = 10_000;
|
|
9
|
+
// Keyed by domain scope and session generation, so a mutation and a hint
|
|
10
|
+
// check of one session never meet those of a session that replaced it.
|
|
11
|
+
const offersByDomainScope = new WeakMap();
|
|
12
|
+
function scopeOffers(scope) {
|
|
13
|
+
let byScope = offersByDomainScope.get(scope.domainScope);
|
|
14
|
+
if (!byScope) {
|
|
15
|
+
byScope = new Map();
|
|
16
|
+
offersByDomainScope.set(scope.domainScope, byScope);
|
|
17
|
+
}
|
|
18
|
+
const requester = organizationAccessScopeKey(scope.organizationId, scope.userId);
|
|
19
|
+
const key = `${scope.sessionGeneration}:${requester}`;
|
|
20
|
+
let offers = byScope.get(key);
|
|
21
|
+
if (!offers) {
|
|
22
|
+
// A newer session retires the requester's older buckets and their offers.
|
|
23
|
+
for (const [existing] of byScope) {
|
|
24
|
+
const [generation, ...rest] = existing.split(":");
|
|
25
|
+
if (rest.join(":") === requester &&
|
|
26
|
+
Number(generation) < scope.sessionGeneration)
|
|
27
|
+
byScope.delete(existing);
|
|
28
|
+
}
|
|
29
|
+
offers = { applying: new WeakMap(), pending: new Map(), settled: [] };
|
|
30
|
+
byScope.set(key, offers);
|
|
31
|
+
}
|
|
32
|
+
return offers;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Begin a mutation that sends the read-model cursor this requester's next
|
|
36
|
+
* reconcile would request from, so its response can carry the delta from it.
|
|
37
|
+
* Until it settles, a realtime hint's cursor check waits for it. No cursor is
|
|
38
|
+
* held while the requester's presentation is denied, since that reconcile
|
|
39
|
+
* requests a snapshot, or when the projection cannot be read.
|
|
40
|
+
*/
|
|
41
|
+
export async function beginCommittedReadModel(scope,
|
|
42
|
+
/** How many cursors the mutation can stamp; a share stamps one. */
|
|
43
|
+
maxStamps = Number.POSITIVE_INFINITY) {
|
|
44
|
+
// An unreadable cursor only forgoes the delta; the mutation still goes out.
|
|
45
|
+
const heldCursor = await loadHeldOrganizationReadModelCursor(scope).catch(() => undefined);
|
|
46
|
+
if (heldCursor === undefined) {
|
|
47
|
+
return { heldCursor, settle: () => { } };
|
|
48
|
+
}
|
|
49
|
+
const offers = scopeOffers(scope);
|
|
50
|
+
let resolve = () => { };
|
|
51
|
+
const promise = new Promise((settled) => {
|
|
52
|
+
resolve = settled;
|
|
53
|
+
});
|
|
54
|
+
offers.pending.set(promise, {
|
|
55
|
+
heldPosition: organizationReadModelCursorPosition(heldCursor, scope.organizationId),
|
|
56
|
+
maxStamps,
|
|
57
|
+
});
|
|
58
|
+
return {
|
|
59
|
+
heldCursor,
|
|
60
|
+
settle: (delta) => {
|
|
61
|
+
if (!offers.pending.delete(promise))
|
|
62
|
+
return;
|
|
63
|
+
if (delta) {
|
|
64
|
+
offers.settled = [...offers.settled, { delta, heldCursor }].slice(-MAX_SETTLED_OFFERS);
|
|
65
|
+
}
|
|
66
|
+
resolve();
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** Whether a mutation in flight could be the commit a hint names. */
|
|
71
|
+
function couldCommit(lease, hintPosition) {
|
|
72
|
+
return (lease.heldPosition !== null &&
|
|
73
|
+
hintPosition > lease.heldPosition &&
|
|
74
|
+
(lease.maxStamps === Number.POSITIVE_INFINITY ||
|
|
75
|
+
hintPosition <= lease.heldPosition + BigInt(lease.maxStamps)));
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Wait, for a bounded time, for this scope's mutations in flight that could
|
|
79
|
+
* be the commit a realtime hint names, then list every unclaimed delta, oldest
|
|
80
|
+
* first: a hint names a commit, and an offer at or past it reflects that
|
|
81
|
+
* commit. A mutation still in flight after the wait leaves the check to read.
|
|
82
|
+
*/
|
|
83
|
+
export async function awaitCommittedReadModelOffers(scope,
|
|
84
|
+
/** Without a hint position, every mutation in flight is waited for. */
|
|
85
|
+
hintPosition, maxWaitMs = MAX_PENDING_WAIT_MS) {
|
|
86
|
+
const offers = scopeOffers(scope);
|
|
87
|
+
let awaited = [...offers.pending]
|
|
88
|
+
.filter(([, lease]) => hintPosition === undefined || couldCommit(lease, hintPosition))
|
|
89
|
+
.map(([promise]) => promise);
|
|
90
|
+
let timer;
|
|
91
|
+
const expired = new Promise((resolve) => {
|
|
92
|
+
timer = setTimeout(resolve, maxWaitMs, "expired");
|
|
93
|
+
});
|
|
94
|
+
// Stop as soon as a settled offer covers the hint, or the wait runs out.
|
|
95
|
+
while (awaited.length > 0 &&
|
|
96
|
+
!offersCover(offers.settled, scope.organizationId, hintPosition)) {
|
|
97
|
+
if ((await Promise.race([...awaited, expired])) === "expired")
|
|
98
|
+
break;
|
|
99
|
+
awaited = awaited.filter((promise) => offers.pending.has(promise));
|
|
100
|
+
}
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
// The bucket read before the wait: a newer session may have retired it.
|
|
103
|
+
return offers.settled;
|
|
104
|
+
}
|
|
105
|
+
/** Whether a settled offer reaches the hint's committed cursor. */
|
|
106
|
+
function offersCover(settled, organizationId, hintPosition) {
|
|
107
|
+
return (hintPosition !== undefined &&
|
|
108
|
+
settled.some((offer) => (organizationReadModelCursorPosition(offer.delta.nextCursor, organizationId) ?? -1n) >= hintPosition));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Apply one offer once, by its delta. The first claimant (a hint's cursor
|
|
112
|
+
* check or the mutation's own reconcile) runs `apply`; a later claimant of the
|
|
113
|
+
* same delta shares that outcome instead of reading. `undefined` when the
|
|
114
|
+
* scope holds no such offer.
|
|
115
|
+
*/
|
|
116
|
+
export function claimCommittedReadModelOffer(scope, delta, apply) {
|
|
117
|
+
const offers = scopeOffers(scope);
|
|
118
|
+
const claimed = offers.applying.get(delta);
|
|
119
|
+
if (claimed)
|
|
120
|
+
return claimed;
|
|
121
|
+
const offer = offers.settled.find((settled) => settled.delta === delta);
|
|
122
|
+
if (!offer)
|
|
123
|
+
return undefined;
|
|
124
|
+
offers.settled = offers.settled.filter((settled) => settled !== offer);
|
|
125
|
+
const outcome = apply(offer);
|
|
126
|
+
offers.applying.set(delta, outcome);
|
|
127
|
+
return outcome;
|
|
128
|
+
}
|
|
129
|
+
/** The projection cursor a reconcile of this requester would request from. */
|
|
130
|
+
export async function loadHeldOrganizationReadModelCursor(scope) {
|
|
131
|
+
if (!isOrganizationPresentationAccessReadable({ ...scope, requesterUserId: scope.userId }, "readModel")) {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
return ((await new OrganizationReadModelRepository(scope.execSql).loadOrganizationReadModelCursor(scope.organizationId)) ?? undefined);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Apply the read-model delta a mutation's response carried as the page a feed
|
|
138
|
+
* read from `requestedCursor` returns, with no request. Resolves `undefined`
|
|
139
|
+
* when it is not applied: its cursor does not advance past the one sent, the
|
|
140
|
+
* projection no longer holds that cursor, or the page applied stale. The
|
|
141
|
+
* caller then reads the feed as before.
|
|
142
|
+
*/
|
|
143
|
+
export async function applyCommittedOrganizationReadModel(input) {
|
|
144
|
+
const sent = organizationReadModelCursorPosition(input.requestedCursor, input.organizationId);
|
|
145
|
+
const next = organizationReadModelCursorPosition(input.response.nextCursor, input.organizationId);
|
|
146
|
+
if (sent === null || next === null || next <= sent)
|
|
147
|
+
return undefined;
|
|
148
|
+
return applyOrganizationReadModelPageAt(input);
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=committedReadModel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"committedReadModel.js","sourceRoot":"","sources":["committedReadModel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mDAAmD,CAAC;AAExG,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAG1H,OAAO,EACL,wCAAwC,EACxC,0BAA0B,GAC3B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,gCAAgC,EAAE,MAAM,uBAAuB,CAAC;AA4CzE,8DAA8D;AAC9D,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,+E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9E,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAA8B;IAE9B,IACE,CAAC,wCAAwC,CACvC,EAAE,GAAG,KAAK,EAAE,eAAe,EAAE,KAAK,CAAC,MAAM,EAAE,EAC3C,WAAW,CACZ,EACD,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,CACL,CAAC,MAAM,IAAI,+BAA+B,CACxC,KAAK,CAAC,OAAO,CACd,CAAC,+BAA+B,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,IAAI,SAAS,CACtE,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAA6D;IAE7D,MAAM,IAAI,GAAG,mCAAmC,CAC9C,KAAK,CAAC,eAAe,EACrB,KAAK,CAAC,cAAc,CACrB,CAAC;IACF,MAAM,IAAI,GAAG,mCAAmC,CAC9C,KAAK,CAAC,QAAQ,CAAC,UAAU,EACzB,KAAK,CAAC,cAAc,CACrB,CAAC;IACF,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,IAAI,IAAI;QAAE,OAAO,SAAS,CAAC;IACrE,OAAO,gCAAgC,CAAC,KAAK,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import { organizationReadModelCursorPosition } from \"@tearleads/validators/organizationReadModelCursor\";\nimport type { OrganizationReadModelDeltaResponse } from \"@tearleads/validators/response\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n isOrganizationPresentationAccessReadable,\n organizationAccessScopeKey,\n} from \"./organizationPresentationAccessState\";\nimport { applyOrganizationReadModelPageAt } from \"./readModelProjection\";\n\n/**\n * The read-model delta one of this device's mutations carried back, and the\n * cursor it held when it sent the mutation: the page a feed read from that\n * cursor returns once the mutation committed.\n */\nexport interface CommittedReadModelOffer {\n readonly delta: OrganizationReadModelDeltaResponse;\n readonly heldCursor: string;\n}\n\n/** A mutation in flight: the cursors it can commit lie in (held, held + stamps]. */\ninterface PendingLease {\n readonly heldPosition: bigint | null;\n readonly maxStamps: number;\n}\n\n/** What applying an offer presented; `undefined` when it applied nothing. */\nexport type CommittedReadModelOutcome =\n | OrganizationDirectoryAndGroups\n | null\n | undefined;\n\ninterface ScopeOffers {\n /** Each claimed offer's one apply, shared by every caller that claims it. */\n readonly applying: WeakMap<\n OrganizationReadModelDeltaResponse,\n Promise<CommittedReadModelOutcome>\n >;\n readonly pending: Map<Promise<void>, PendingLease>;\n settled: readonly CommittedReadModelOffer[];\n}\n\ninterface CommittedReadModelScope {\n /** The runtime's domain scope; an identity switch replaces it. */\n readonly domainScope: object;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n /** The runtime's session generation; a logout or new login advances it. */\n readonly sessionGeneration: number;\n readonly userId: string;\n}\n\n/** A settled offer older than this many is dropped unread. */\nconst MAX_SETTLED_OFFERS = 4;\n/** A hint's cursor check waits no longer than this for mutations in flight. */\nconst MAX_PENDING_WAIT_MS = 10_000;\n\n// Keyed by domain scope and session generation, so a mutation and a hint\n// check of one session never meet those of a session that replaced it.\nconst offersByDomainScope = new WeakMap<object, Map<string, ScopeOffers>>();\n\nfunction scopeOffers(scope: CommittedReadModelScope): ScopeOffers {\n let byScope = offersByDomainScope.get(scope.domainScope);\n if (!byScope) {\n byScope = new Map();\n offersByDomainScope.set(scope.domainScope, byScope);\n }\n const requester = organizationAccessScopeKey(\n scope.organizationId,\n scope.userId,\n );\n const key = `${scope.sessionGeneration}:${requester}`;\n let offers = byScope.get(key);\n if (!offers) {\n // A newer session retires the requester's older buckets and their offers.\n for (const [existing] of byScope) {\n const [generation, ...rest] = existing.split(\":\");\n if (\n rest.join(\":\") === requester &&\n Number(generation) < scope.sessionGeneration\n )\n byScope.delete(existing);\n }\n offers = { applying: new WeakMap(), pending: new Map(), settled: [] };\n byScope.set(key, offers);\n }\n return offers;\n}\n\n/** A mutation that sent a held cursor; settle it once, when it ends. */\nexport interface CommittedReadModelLease {\n readonly heldCursor: string | undefined;\n settle(delta: OrganizationReadModelDeltaResponse | undefined): void;\n}\n\n/**\n * Begin a mutation that sends the read-model cursor this requester's next\n * reconcile would request from, so its response can carry the delta from it.\n * Until it settles, a realtime hint's cursor check waits for it. No cursor is\n * held while the requester's presentation is denied, since that reconcile\n * requests a snapshot, or when the projection cannot be read.\n */\nexport async function beginCommittedReadModel(\n scope: CommittedReadModelScope,\n /** How many cursors the mutation can stamp; a share stamps one. */\n maxStamps = Number.POSITIVE_INFINITY,\n): Promise<CommittedReadModelLease> {\n // An unreadable cursor only forgoes the delta; the mutation still goes out.\n const heldCursor = await loadHeldOrganizationReadModelCursor(scope).catch(\n () => undefined,\n );\n if (heldCursor === undefined) {\n return { heldCursor, settle: () => {} };\n }\n const offers = scopeOffers(scope);\n let resolve = () => {};\n const promise = new Promise<void>((settled) => {\n resolve = settled;\n });\n offers.pending.set(promise, {\n heldPosition: organizationReadModelCursorPosition(\n heldCursor,\n scope.organizationId,\n ),\n maxStamps,\n });\n return {\n heldCursor,\n settle: (delta) => {\n if (!offers.pending.delete(promise)) return;\n if (delta) {\n offers.settled = [...offers.settled, { delta, heldCursor }].slice(\n -MAX_SETTLED_OFFERS,\n );\n }\n resolve();\n },\n };\n}\n\n/** Whether a mutation in flight could be the commit a hint names. */\nfunction couldCommit(lease: PendingLease, hintPosition: bigint): boolean {\n return (\n lease.heldPosition !== null &&\n hintPosition > lease.heldPosition &&\n (lease.maxStamps === Number.POSITIVE_INFINITY ||\n hintPosition <= lease.heldPosition + BigInt(lease.maxStamps))\n );\n}\n\n/**\n * Wait, for a bounded time, for this scope's mutations in flight that could\n * be the commit a realtime hint names, then list every unclaimed delta, oldest\n * first: a hint names a commit, and an offer at or past it reflects that\n * commit. A mutation still in flight after the wait leaves the check to read.\n */\nexport async function awaitCommittedReadModelOffers(\n scope: CommittedReadModelScope,\n /** Without a hint position, every mutation in flight is waited for. */\n hintPosition: bigint | undefined,\n maxWaitMs = MAX_PENDING_WAIT_MS,\n): Promise<readonly CommittedReadModelOffer[]> {\n const offers = scopeOffers(scope);\n let awaited = [...offers.pending]\n .filter(\n ([, lease]) =>\n hintPosition === undefined || couldCommit(lease, hintPosition),\n )\n .map(([promise]) => promise);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<\"expired\">((resolve) => {\n timer = setTimeout(resolve, maxWaitMs, \"expired\");\n });\n // Stop as soon as a settled offer covers the hint, or the wait runs out.\n while (\n awaited.length > 0 &&\n !offersCover(offers.settled, scope.organizationId, hintPosition)\n ) {\n if ((await Promise.race([...awaited, expired])) === \"expired\") break;\n awaited = awaited.filter((promise) => offers.pending.has(promise));\n }\n clearTimeout(timer);\n // The bucket read before the wait: a newer session may have retired it.\n return offers.settled;\n}\n\n/** Whether a settled offer reaches the hint's committed cursor. */\nfunction offersCover(\n settled: readonly CommittedReadModelOffer[],\n organizationId: string,\n hintPosition: bigint | undefined,\n): boolean {\n return (\n hintPosition !== undefined &&\n settled.some(\n (offer) =>\n (organizationReadModelCursorPosition(\n offer.delta.nextCursor,\n organizationId,\n ) ?? -1n) >= hintPosition,\n )\n );\n}\n\n/**\n * Apply one offer once, by its delta. The first claimant (a hint's cursor\n * check or the mutation's own reconcile) runs `apply`; a later claimant of the\n * same delta shares that outcome instead of reading. `undefined` when the\n * scope holds no such offer.\n */\nexport function claimCommittedReadModelOffer(\n scope: CommittedReadModelScope,\n delta: OrganizationReadModelDeltaResponse,\n apply: (offer: CommittedReadModelOffer) => Promise<CommittedReadModelOutcome>,\n): Promise<CommittedReadModelOutcome> | undefined {\n const offers = scopeOffers(scope);\n const claimed = offers.applying.get(delta);\n if (claimed) return claimed;\n const offer = offers.settled.find((settled) => settled.delta === delta);\n if (!offer) return undefined;\n offers.settled = offers.settled.filter((settled) => settled !== offer);\n const outcome = apply(offer);\n offers.applying.set(delta, outcome);\n return outcome;\n}\n\n/** The projection cursor a reconcile of this requester would request from. */\nexport async function loadHeldOrganizationReadModelCursor(\n scope: CommittedReadModelScope,\n): Promise<string | undefined> {\n if (\n !isOrganizationPresentationAccessReadable(\n { ...scope, requesterUserId: scope.userId },\n \"readModel\",\n )\n ) {\n return undefined;\n }\n return (\n (await new OrganizationReadModelRepository(\n scope.execSql,\n ).loadOrganizationReadModelCursor(scope.organizationId)) ?? undefined\n );\n}\n\n/**\n * Apply the read-model delta a mutation's response carried as the page a feed\n * read from `requestedCursor` returns, with no request. Resolves `undefined`\n * when it is not applied: its cursor does not advance past the one sent, the\n * projection no longer holds that cursor, or the page applied stale. The\n * caller then reads the feed as before.\n */\nexport async function applyCommittedOrganizationReadModel(\n input: Parameters<typeof applyOrganizationReadModelPageAt>[0],\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const sent = organizationReadModelCursorPosition(\n input.requestedCursor,\n input.organizationId,\n );\n const next = organizationReadModelCursorPosition(\n input.response.nextCursor,\n input.organizationId,\n );\n if (sent === null || next === null || next <= sent) return undefined;\n return applyOrganizationReadModelPageAt(input);\n}\n"]}
|
|
@@ -11,14 +11,27 @@ interface OrganizationReadModelProjectionInput {
|
|
|
11
11
|
readonly execSql: ExecSql;
|
|
12
12
|
readonly organizationId: string;
|
|
13
13
|
}
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
/** Applying a page needs no API; `stillCurrent` is rechecked in the write. */
|
|
15
|
+
interface ApplyReadModelPageInput extends OrganizationReadModelProjectionInput {
|
|
16
16
|
readonly logError?: ((message: string | Error, cause?: unknown) => void) | undefined;
|
|
17
|
+
readonly stillCurrent?: (() => boolean) | undefined;
|
|
18
|
+
}
|
|
19
|
+
export interface ReconcileOrganizationDirectoryAndGroupsInput extends ApplyReadModelPageInput {
|
|
20
|
+
readonly apiClient: OrganizationReadModelApi;
|
|
17
21
|
}
|
|
18
22
|
export declare function loadLocalOrganizationDirectoryAndGroups(input: OrganizationReadModelProjectionInput): Promise<OrganizationDirectoryAndGroups | null>;
|
|
19
23
|
export declare function loadLocalOrganizationGroupMembers(input: OrganizationReadModelProjectionInput & {
|
|
20
24
|
readonly groupId: string;
|
|
21
25
|
}): Promise<OrganizationReadModelGroupMembers | null>;
|
|
26
|
+
/**
|
|
27
|
+
* Apply one page as a feed read from `requestedCursor` returns it, with no
|
|
28
|
+
* request, while the projection still holds that cursor. Resolves `undefined`
|
|
29
|
+
* when it is not applied; it is never retried.
|
|
30
|
+
*/
|
|
31
|
+
export declare function applyOrganizationReadModelPageAt(input: ApplyReadModelPageInput & {
|
|
32
|
+
readonly requestedCursor: string;
|
|
33
|
+
readonly response: OrganizationReadModelResponse;
|
|
34
|
+
}): Promise<OrganizationDirectoryAndGroups | null | undefined>;
|
|
22
35
|
/**
|
|
23
36
|
* Resolves the reconciled projection, `null` when the pass completed
|
|
24
37
|
* authoritatively with nothing presentable (including a denial that purged
|
|
@@ -131,6 +131,7 @@ async function applyResponse(input, state, response) {
|
|
|
131
131
|
return {
|
|
132
132
|
kind: "applied",
|
|
133
133
|
result: await repository.applyOrganizationReadModelResponse({
|
|
134
|
+
canCommit: input.stillCurrent,
|
|
134
135
|
currentUserId: input.currentUserId,
|
|
135
136
|
requestedCursor: state.expectedLocalCursor,
|
|
136
137
|
response,
|
|
@@ -189,13 +190,12 @@ async function applyReadModelPage(input, state, response) {
|
|
|
189
190
|
}
|
|
190
191
|
const accessInput = organizationPresentationAccessInput(input);
|
|
191
192
|
return runOrganizationPresentationMutation(input.execSql, async () => {
|
|
192
|
-
if (!reconciliationIsCurrent(input, state)
|
|
193
|
+
if (!reconciliationIsCurrent(input, state) ||
|
|
194
|
+
input.stillCurrent?.() === false)
|
|
193
195
|
return { kind: "done", value: null };
|
|
194
|
-
}
|
|
195
196
|
const preparation = await prepareDeniedProjectionForApply(input, state);
|
|
196
|
-
if (preparation)
|
|
197
|
+
if (preparation)
|
|
197
198
|
return preparation;
|
|
198
|
-
}
|
|
199
199
|
const applied = await applyResponse(input, state, response);
|
|
200
200
|
if (applied.kind !== "applied") {
|
|
201
201
|
return applied;
|
|
@@ -221,6 +221,28 @@ export async function loadLocalOrganizationDirectoryAndGroups(input) {
|
|
|
221
221
|
export async function loadLocalOrganizationGroupMembers(input) {
|
|
222
222
|
return runOrganizationPresentationRead(organizationPresentationAccessInput(input), "readModel", () => new OrganizationReadModelRepository(input.execSql).loadOrganizationReadModelGroupMembers(input.organizationId, input.groupId, input.currentUserId));
|
|
223
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Apply one page as a feed read from `requestedCursor` returns it, with no
|
|
226
|
+
* request, while the projection still holds that cursor. Resolves `undefined`
|
|
227
|
+
* when it is not applied; it is never retried.
|
|
228
|
+
*/
|
|
229
|
+
export async function applyOrganizationReadModelPageAt(input) {
|
|
230
|
+
const accessAttempt = captureOrganizationPresentationAccessAttempt(organizationPresentationAccessInput(input), "readModel");
|
|
231
|
+
const projection = await loadProjection(input);
|
|
232
|
+
if (projection?.cursor !== input.requestedCursor)
|
|
233
|
+
return undefined;
|
|
234
|
+
const applied = await applyReadModelPage(input, {
|
|
235
|
+
accessAttempt,
|
|
236
|
+
expectedLocalCursor: projection.cursor,
|
|
237
|
+
preparedDeniedProjection: true,
|
|
238
|
+
projection,
|
|
239
|
+
requestCursor: projection.cursor,
|
|
240
|
+
retriedBindingFailure: true,
|
|
241
|
+
retriedInvalidCursor: true,
|
|
242
|
+
staleRetries: MAX_STALE_RETRIES,
|
|
243
|
+
}, input.response);
|
|
244
|
+
return applied.kind === "done" ? applied.value : undefined;
|
|
245
|
+
}
|
|
224
246
|
/**
|
|
225
247
|
* Resolves the reconciled projection, `null` when the pass completed
|
|
226
248
|
* authoritatively with nothing presentable (including a denial that purged
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readModelProjection.js","sourceRoot":"","sources":["readModelProjection.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,mCAAmC,GAEpC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,iCA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AAE,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 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"]}
|
|
1
|
+
{"version":3,"file":"readModelProjection.js","sourceRoot":"","sources":["readModelProjection.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,mCAAmC,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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 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\n/** Applying a page needs no API; `stillCurrent` is rechecked in the write. */\ninterface ApplyReadModelPageInput extends OrganizationReadModelProjectionInput {\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ReconcileOrganizationDirectoryAndGroupsInput\n extends ApplyReadModelPageInput {\n readonly apiClient: OrganizationReadModelApi;\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: ApplyReadModelPageInput,\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: ApplyReadModelPageInput,\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: ApplyReadModelPageInput,\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: ApplyReadModelPageInput,\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: ApplyReadModelPageInput,\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 canCommit: input.stillCurrent,\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: ApplyReadModelPageInput,\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: ApplyReadModelPageInput,\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: ApplyReadModelPageInput,\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 (\n !reconciliationIsCurrent(input, state) ||\n input.stillCurrent?.() === false\n )\n return { kind: \"done\", value: null };\n const preparation = await prepareDeniedProjectionForApply(input, state);\n if (preparation) return preparation;\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 * Apply one page as a feed read from `requestedCursor` returns it, with no\n * request, while the projection still holds that cursor. Resolves `undefined`\n * when it is not applied; it is never retried.\n */\nexport async function applyOrganizationReadModelPageAt(\n input: ApplyReadModelPageInput & {\n readonly requestedCursor: string;\n readonly response: OrganizationReadModelResponse;\n },\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n organizationPresentationAccessInput(input),\n \"readModel\",\n );\n const projection = await loadProjection(input);\n if (projection?.cursor !== input.requestedCursor) return undefined;\n const applied = await applyReadModelPage(\n input,\n {\n accessAttempt,\n expectedLocalCursor: projection.cursor,\n preparedDeniedProjection: true,\n projection,\n requestCursor: projection.cursor,\n retriedBindingFailure: true,\n retriedInvalidCursor: true,\n staleRetries: MAX_STALE_RETRIES,\n },\n input.response,\n );\n return applied.kind === \"done\" ? applied.value : undefined;\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"]}
|