@tearleads/client-sdk 0.1.224 → 0.1.225
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/organizationMemberships.d.ts +1 -1
- package/client/organizations/organizationMemberships.js +1 -1
- package/client/organizations/organizationMemberships.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/operations/forgetOrganizationContentOperation.js +1 -1
- package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +1 -1
- package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js +1 -1
- package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js.map +1 -1
- package/stores/documents/documentStore/initialization/index.js +1 -1
- package/stores/documents/documentStore/initialization/index.js.map +1 -1
- package/stores/documents/documentStore/storedDocument.js +1 -1
- package/stores/documents/documentStore/storedDocument.js.map +1 -1
- package/stores/documents/documentStore/sync/syncAttachments.js +1 -1
- package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
- package/workflows/container-contents/syncPause/documentRemoval.js +1 -1
- package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
- package/workflows/organizations/memberships/organizationMemberships.d.ts +1 -1
- package/workflows/organizations/memberships/organizationMemberships.js +1 -1
- package/workflows/organizations/memberships/organizationMemberships.js.map +1 -1
- package/workflows/sync/coordination.d.ts +6 -0
- package/workflows/sync/coordination.js +6 -0
- package/workflows/sync/coordination.js.map +1 -0
- package/workflows/sync/index.d.ts +1 -6
- package/workflows/sync/index.js +1 -5
- package/workflows/sync/index.js.map +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type OrganizationLeaveRequestResult, type OrganizationMembership, type OrganizationSyncPauseResult } from "../../workflows/organizations/index.js";
|
|
2
|
-
import { type DomainScope } from "../../workflows/sync/
|
|
2
|
+
import { type DomainScope } from "../../workflows/sync/coordination.js";
|
|
3
3
|
import { type ContainerContents } from "../containerContents/index.js";
|
|
4
4
|
import type { InternalRuntime } from "../runtime/workflowRuntime.js";
|
|
5
5
|
/** The user's own conduit to the organizations they belong to. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { refreshOrganizationMemberships, setOrganizationLeaveRequested, setOrganizationSyncPaused, } from "../../workflows/organizations/index.js";
|
|
2
2
|
import { loadCurrentMembersHead } from "../../workflows/organizations/memberships/leaveRequestMembersEvidence.js";
|
|
3
|
-
import { getOrCreateOrganizationSyncPauses, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../workflows/sync/
|
|
3
|
+
import { getOrCreateOrganizationSyncPauses, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../workflows/sync/coordination.js";
|
|
4
4
|
import { carriesLocalWrites, } from "../containerContents/index.js";
|
|
5
5
|
// Long enough for a typical upload burst, short enough to answer a tap.
|
|
6
6
|
const PAUSE_FLUSH_TIMEOUT_MS = 10_000;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,8BAA8B,EAC9B,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,uEAAuE,CAAC;AAC/G,OAAO,EAEL,iCAAiC,EACjC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAEL,kBAAkB,GACnB,MAAM,sBAAsB,CAAC;AAM9B,wEAAwE;AACxE,MAAM,sBAAsB,GAAG,MAAM,CAAC;AAwCtC,MAAM,0BAA0B,GAAG,IAAI,OAAO,EAG3C,CAAC;AAiBJ,MAAM,oBAAoB,GAAG,IAAI,OAAO,EAA4B,CAAC;AAErE,2EAA2E;AAC3E,uC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AAE,EAAE,CAC/C,oBAAoB,CAAC,cAAc,EAAE,cAAc,EAAE,SAAS,CAAC;QACjE,KAAK,CAAC,yBAAyB;YAC7B,MAAM,OAAO,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;YAC/C,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,KAAK,OAAO;gBAAE,OAAO,IAAI,GAAG,EAAU,CAAC;YACjE,MAAM,MAAM,GAAG,iCAAiC,CAC9C,OAAO,CAAC,KAAK,CAAC,WAAW,CAC1B,CAAC;YACF,MAAM,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACzC,OAAO,MAAM,CAAC,qBAAqB,EAAE,CAAC;QACxC,CAAC;QACD,qBAAqB,CAAC,QAAQ;YAC5B,OAAO,iCAAiC,CACtC,cAAc,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,WAAW,CACjD,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QACxB,CAAC;QACD,sBAAsB,CAAC,QAAQ;YAC7B,MAAM,EAAE,WAAW,EAAE,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC;YAC7D,MAAM,SAAS,GACb,0BAA0B,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC;YAC3D,0BAA0B,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;YACvD,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,OAAO,GAAG,EAAE;gBACV,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC7B,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type OrganizationContentHost,\n type OrganizationLeaveRequestResult,\n type OrganizationMembership,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationLeaveRequested,\n setOrganizationSyncPaused,\n} from \"../../workflows/organizations\";\nimport { loadCurrentMembersHead } from \"../../workflows/organizations/memberships/leaveRequestMembersEvidence\";\nimport {\n type DomainScope,\n getOrCreateOrganizationSyncPauses,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../workflows/sync\";\nimport {\n type ContainerContents,\n carriesLocalWrites,\n} from \"../containerContents\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\n\n// Long enough for a typical upload burst, short enough to answer a tap.\nconst PAUSE_FLUSH_TIMEOUT_MS = 10_000;\n\n/** The user's own conduit to the organizations they belong to. */\nexport interface OrganizationMemberships {\n /**\n * Reads the user's memberships and applies their pause choices on this\n * device. Null when offline or the list could not be read.\n */\n refresh(): Promise<OrganizationMembership[] | null>;\n /** Pauses or resumes one organization for all of the user's devices. */\n setSyncPaused(\n organizationId: string,\n paused: boolean,\n ): Promise<OrganizationSyncPauseResult>;\n /**\n * Asks the organization's administrators to remove the user, or withdraws\n * that request. Signed with the user's identity key; an administrator still\n * has to approve it.\n */\n setLeaveRequested(\n organizationId: string,\n requested: boolean,\n ): Promise<OrganizationLeaveRequestResult>;\n /** The organizations paused on this device, read from local storage. */\n loadPausedOrganizationIds(): Promise<ReadonlySet<string>>;\n /** Notifies when the paused set for the current scope changes. */\n subscribeToSyncPauses(listener: () => void): () => void;\n /**\n * Hands each membership list a refresh reads for the current scope, so a\n * choice made on another device reaches every view of it.\n */\n subscribeToMemberships(\n listener: (memberships: readonly OrganizationMembership[]) => void,\n ): () => void;\n}\n\ntype MembershipsListener = (\n memberships: readonly OrganizationMembership[],\n) => void;\n\nconst membershipListenersByScope = new WeakMap<\n DomainScope,\n Set<MembershipsListener>\n>();\n\n/**\n * The scope's document reconciler. Containers it reconciled before a pause\n * stay marked as listed, so a resume has to forget that before reconciling.\n */\nexport interface OrganizationContentReconciler {\n resetDiscovered(): void;\n reconcileNow(options: { readonly freshListing: true }): Promise<void>;\n}\n\ninterface SettleRetry {\n retry: () => Promise<boolean>;\n running: boolean;\n unsubscribe: () => void;\n}\n\nconst settleRetriesByScope = new WeakMap<DomainScope, SettleRetry>();\n\n// One retry per scope: it runs whenever the scope's sync lanes go idle and\n// stops once it reports the work done.\nexport function retryWhenWritesSettle(\n domainScope: DomainScope,\n retry: () => Promise<boolean>,\n): void {\n const existing = settleRetriesByScope.get(domainScope);\n if (existing) {\n existing.retry = retry;\n return;\n }\n const entry: SettleRetry = { retry, running: false, unsubscribe: () => {} };\n settleRetriesByScope.set(domainScope, entry);\n const attempt = () => {\n if (entry.running || hasDomainSyncCoordinatorPendingWork(domainScope)) {\n return;\n }\n entry.running = true;\n void entry\n .retry()\n .then(\n (done) => {\n if (!done) return;\n entry.unsubscribe();\n settleRetriesByScope.delete(domainScope);\n },\n () => undefined,\n )\n .finally(() => {\n entry.running = false;\n });\n };\n entry.unsubscribe = subscribeToDomainSyncCoordinator(domainScope, attempt);\n // The lanes may already have gone idle before the subscription existed.\n attempt();\n}\n\n// Bound to the scope the operation started in: the tree is opened once, and\n// every action re-checks the scope so stale work never reaches another\n// identity's device state.\nfunction createOrganizationContentHost(\n runtime: InternalWorkflowRuntimeInput,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n isCurrent: () => boolean,\n): OrganizationContentHost {\n const { domainScope } = runtime.state;\n const tree = containerContents.openTree();\n return {\n async forgetOrganizationContent(organizationId) {\n // A scope that ended has nothing left to retry.\n if (!isCurrent()) return true;\n return tree.forgetOrganizationContent(organizationId);\n },\n async hasUnsyncedOrganizationWrites(organizationId) {\n if (!isCurrent()) return true;\n const pending = await containerContents\n .documentQueries()\n .listPendingWrites();\n return pending.some(\n (item) =>\n item.organizationId === organizationId && carriesLocalWrites(item),\n );\n },\n async flushWrites() {\n requestAllDomainSyncLanes(domainScope);\n await waitForDomainSyncCoordinatorToSettle(domainScope, {\n timeoutMs: PAUSE_FLUSH_TIMEOUT_MS,\n });\n },\n async refetchContent() {\n if (!isCurrent()) return;\n // Re-lists the whole tree and every container's documents. The resumed\n // organization's folders were listed before the pause, and a hydration\n // may already have restored them, so they must be forgotten explicitly.\n // A sweep that started listing while paused would miss them, so this\n // one queues behind it rather than joining it.\n const reconciler = openReconciler();\n reconciler.resetDiscovered();\n await reconciler.reconcileNow({ freshListing: true });\n },\n retryWhenWritesSettle: (retry) => retryWhenWritesSettle(domainScope, retry),\n };\n}\n\nfunction canReachServer(runtime: InternalWorkflowRuntimeInput): boolean {\n return (\n runtime.infra.dbStatus === \"ready\" &&\n runtime.auth.isAuthenticated &&\n runtime.state.online\n );\n}\n\nfunction setLeaveRequestedFor(\n runtimeService: InternalRuntime,\n organizationId: string,\n requested: boolean,\n): Promise<OrganizationLeaveRequestResult> {\n const runtime = runtimeService.workflowInput();\n const { userId } = runtime.auth;\n const { signingKeyPair } = runtime.crypto;\n if (!canReachServer(runtime) || !userId || !signingKeyPair) {\n return Promise.resolve({\n httpStatus: null,\n message: \"Connect to ask to leave an organization.\",\n status: \"failed\",\n });\n }\n const { domainScope } = runtime.state;\n return setOrganizationLeaveRequested({\n apiClient: runtime.apiClient,\n loadMembersHead: () =>\n loadCurrentMembersHead({\n organizationId,\n runtime,\n stillCurrent: () =>\n runtimeService.workflowInput().state.domainScope === domainScope,\n }),\n organizationId,\n requested,\n signer: { signingKeyPair, userId },\n });\n}\n\nexport function createOrganizationMemberships(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n): OrganizationMemberships {\n const membershipInput = (runtime: InternalWorkflowRuntimeInput) => {\n const { domainScope } = runtime.state;\n const isCurrent = () =>\n runtimeService.workflowInput().state.domainScope === domainScope;\n return {\n apiClient: runtime.apiClient,\n domainScope,\n execSql: runtime.infra.execSql,\n host: createOrganizationContentHost(\n runtime,\n containerContents,\n openReconciler,\n isCurrent,\n ),\n isCurrent,\n };\n };\n return {\n async refresh() {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) return null;\n const memberships = await refreshOrganizationMemberships(\n membershipInput(runtime),\n );\n const listeners = membershipListenersByScope.get(\n runtime.state.domainScope,\n );\n if (memberships && listeners) {\n for (const listener of [...listeners]) listener(memberships);\n }\n return memberships;\n },\n async setSyncPaused(organizationId, paused) {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) {\n return {\n httpStatus: null,\n message: \"Connect to change sync for an organization.\",\n status: \"failed\",\n };\n }\n return setOrganizationSyncPaused({\n ...membershipInput(runtime),\n organizationId,\n paused,\n });\n },\n setLeaveRequested: (organizationId, requested) =>\n setLeaveRequestedFor(runtimeService, organizationId, requested),\n async loadPausedOrganizationIds() {\n const runtime = runtimeService.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") return new Set<string>();\n const pauses = getOrCreateOrganizationSyncPauses(\n runtime.state.domainScope,\n );\n await pauses.load(runtime.infra.execSql);\n return pauses.pausedOrganizationIds();\n },\n subscribeToSyncPauses(listener) {\n return getOrCreateOrganizationSyncPauses(\n runtimeService.workflowInput().state.domainScope,\n ).subscribe(listener);\n },\n subscribeToMemberships(listener) {\n const { domainScope } = runtimeService.workflowInput().state;\n const listeners =\n membershipListenersByScope.get(domainScope) ?? new Set();\n membershipListenersByScope.set(domainScope, listeners);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,8BAA8B,EAC9B,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,uEAAuE,CAAC;AAC/G,OAAO,EAEL,iCAAiC,EACjC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAEL,kBAAkB,GACnB,MAAM,sBAAsB,CAAC;AAM9B,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AAC","sourcesContent":["import {\n type OrganizationContentHost,\n type OrganizationLeaveRequestResult,\n type OrganizationMembership,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationLeaveRequested,\n setOrganizationSyncPaused,\n} from \"../../workflows/organizations\";\nimport { loadCurrentMembersHead } from \"../../workflows/organizations/memberships/leaveRequestMembersEvidence\";\nimport {\n type DomainScope,\n getOrCreateOrganizationSyncPauses,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../workflows/sync/coordination\";\nimport {\n type ContainerContents,\n carriesLocalWrites,\n} from \"../containerContents\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\n\n// Long enough for a typical upload burst, short enough to answer a tap.\nconst PAUSE_FLUSH_TIMEOUT_MS = 10_000;\n\n/** The user's own conduit to the organizations they belong to. */\nexport interface OrganizationMemberships {\n /**\n * Reads the user's memberships and applies their pause choices on this\n * device. Null when offline or the list could not be read.\n */\n refresh(): Promise<OrganizationMembership[] | null>;\n /** Pauses or resumes one organization for all of the user's devices. */\n setSyncPaused(\n organizationId: string,\n paused: boolean,\n ): Promise<OrganizationSyncPauseResult>;\n /**\n * Asks the organization's administrators to remove the user, or withdraws\n * that request. Signed with the user's identity key; an administrator still\n * has to approve it.\n */\n setLeaveRequested(\n organizationId: string,\n requested: boolean,\n ): Promise<OrganizationLeaveRequestResult>;\n /** The organizations paused on this device, read from local storage. */\n loadPausedOrganizationIds(): Promise<ReadonlySet<string>>;\n /** Notifies when the paused set for the current scope changes. */\n subscribeToSyncPauses(listener: () => void): () => void;\n /**\n * Hands each membership list a refresh reads for the current scope, so a\n * choice made on another device reaches every view of it.\n */\n subscribeToMemberships(\n listener: (memberships: readonly OrganizationMembership[]) => void,\n ): () => void;\n}\n\ntype MembershipsListener = (\n memberships: readonly OrganizationMembership[],\n) => void;\n\nconst membershipListenersByScope = new WeakMap<\n DomainScope,\n Set<MembershipsListener>\n>();\n\n/**\n * The scope's document reconciler. Containers it reconciled before a pause\n * stay marked as listed, so a resume has to forget that before reconciling.\n */\nexport interface OrganizationContentReconciler {\n resetDiscovered(): void;\n reconcileNow(options: { readonly freshListing: true }): Promise<void>;\n}\n\ninterface SettleRetry {\n retry: () => Promise<boolean>;\n running: boolean;\n unsubscribe: () => void;\n}\n\nconst settleRetriesByScope = new WeakMap<DomainScope, SettleRetry>();\n\n// One retry per scope: it runs whenever the scope's sync lanes go idle and\n// stops once it reports the work done.\nexport function retryWhenWritesSettle(\n domainScope: DomainScope,\n retry: () => Promise<boolean>,\n): void {\n const existing = settleRetriesByScope.get(domainScope);\n if (existing) {\n existing.retry = retry;\n return;\n }\n const entry: SettleRetry = { retry, running: false, unsubscribe: () => {} };\n settleRetriesByScope.set(domainScope, entry);\n const attempt = () => {\n if (entry.running || hasDomainSyncCoordinatorPendingWork(domainScope)) {\n return;\n }\n entry.running = true;\n void entry\n .retry()\n .then(\n (done) => {\n if (!done) return;\n entry.unsubscribe();\n settleRetriesByScope.delete(domainScope);\n },\n () => undefined,\n )\n .finally(() => {\n entry.running = false;\n });\n };\n entry.unsubscribe = subscribeToDomainSyncCoordinator(domainScope, attempt);\n // The lanes may already have gone idle before the subscription existed.\n attempt();\n}\n\n// Bound to the scope the operation started in: the tree is opened once, and\n// every action re-checks the scope so stale work never reaches another\n// identity's device state.\nfunction createOrganizationContentHost(\n runtime: InternalWorkflowRuntimeInput,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n isCurrent: () => boolean,\n): OrganizationContentHost {\n const { domainScope } = runtime.state;\n const tree = containerContents.openTree();\n return {\n async forgetOrganizationContent(organizationId) {\n // A scope that ended has nothing left to retry.\n if (!isCurrent()) return true;\n return tree.forgetOrganizationContent(organizationId);\n },\n async hasUnsyncedOrganizationWrites(organizationId) {\n if (!isCurrent()) return true;\n const pending = await containerContents\n .documentQueries()\n .listPendingWrites();\n return pending.some(\n (item) =>\n item.organizationId === organizationId && carriesLocalWrites(item),\n );\n },\n async flushWrites() {\n requestAllDomainSyncLanes(domainScope);\n await waitForDomainSyncCoordinatorToSettle(domainScope, {\n timeoutMs: PAUSE_FLUSH_TIMEOUT_MS,\n });\n },\n async refetchContent() {\n if (!isCurrent()) return;\n // Re-lists the whole tree and every container's documents. The resumed\n // organization's folders were listed before the pause, and a hydration\n // may already have restored them, so they must be forgotten explicitly.\n // A sweep that started listing while paused would miss them, so this\n // one queues behind it rather than joining it.\n const reconciler = openReconciler();\n reconciler.resetDiscovered();\n await reconciler.reconcileNow({ freshListing: true });\n },\n retryWhenWritesSettle: (retry) => retryWhenWritesSettle(domainScope, retry),\n };\n}\n\nfunction canReachServer(runtime: InternalWorkflowRuntimeInput): boolean {\n return (\n runtime.infra.dbStatus === \"ready\" &&\n runtime.auth.isAuthenticated &&\n runtime.state.online\n );\n}\n\nfunction setLeaveRequestedFor(\n runtimeService: InternalRuntime,\n organizationId: string,\n requested: boolean,\n): Promise<OrganizationLeaveRequestResult> {\n const runtime = runtimeService.workflowInput();\n const { userId } = runtime.auth;\n const { signingKeyPair } = runtime.crypto;\n if (!canReachServer(runtime) || !userId || !signingKeyPair) {\n return Promise.resolve({\n httpStatus: null,\n message: \"Connect to ask to leave an organization.\",\n status: \"failed\",\n });\n }\n const { domainScope } = runtime.state;\n return setOrganizationLeaveRequested({\n apiClient: runtime.apiClient,\n loadMembersHead: () =>\n loadCurrentMembersHead({\n organizationId,\n runtime,\n stillCurrent: () =>\n runtimeService.workflowInput().state.domainScope === domainScope,\n }),\n organizationId,\n requested,\n signer: { signingKeyPair, userId },\n });\n}\n\nexport function createOrganizationMemberships(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n): OrganizationMemberships {\n const membershipInput = (runtime: InternalWorkflowRuntimeInput) => {\n const { domainScope } = runtime.state;\n const isCurrent = () =>\n runtimeService.workflowInput().state.domainScope === domainScope;\n return {\n apiClient: runtime.apiClient,\n domainScope,\n execSql: runtime.infra.execSql,\n host: createOrganizationContentHost(\n runtime,\n containerContents,\n openReconciler,\n isCurrent,\n ),\n isCurrent,\n };\n };\n return {\n async refresh() {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) return null;\n const memberships = await refreshOrganizationMemberships(\n membershipInput(runtime),\n );\n const listeners = membershipListenersByScope.get(\n runtime.state.domainScope,\n );\n if (memberships && listeners) {\n for (const listener of [...listeners]) listener(memberships);\n }\n return memberships;\n },\n async setSyncPaused(organizationId, paused) {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) {\n return {\n httpStatus: null,\n message: \"Connect to change sync for an organization.\",\n status: \"failed\",\n };\n }\n return setOrganizationSyncPaused({\n ...membershipInput(runtime),\n organizationId,\n paused,\n });\n },\n setLeaveRequested: (organizationId, requested) =>\n setLeaveRequestedFor(runtimeService, organizationId, requested),\n async loadPausedOrganizationIds() {\n const runtime = runtimeService.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") return new Set<string>();\n const pauses = getOrCreateOrganizationSyncPauses(\n runtime.state.domainScope,\n );\n await pauses.load(runtime.infra.execSql);\n return pauses.pausedOrganizationIds();\n },\n subscribeToSyncPauses(listener) {\n return getOrCreateOrganizationSyncPauses(\n runtimeService.workflowInput().state.domainScope,\n ).subscribe(listener);\n },\n subscribeToMemberships(listener) {\n const { domainScope } = runtimeService.workflowInput().state;\n const listeners =\n membershipListenersByScope.get(domainScope) ?? new Set();\n membershipListenersByScope.set(domainScope, listeners);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { removeOrganizationContentUnlessPending } from "../../../workflows/container-contents/syncPause/documentRemoval.js";
|
|
2
2
|
import { reclaimDocumentOrphanBlobs } from "../../../workflows/documents/index.js";
|
|
3
|
-
import { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, } from "../../../workflows/sync/
|
|
3
|
+
import { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, } from "../../../workflows/sync/coordination.js";
|
|
4
4
|
import { emitPersistedDocumentDeletion, hasQueuedDocumentStoreWrites, restoreDocumentStore, retireDocumentStore, } from "../../documents/registry.js";
|
|
5
5
|
import { updateContainerContentsSnapshot } from "../state.js";
|
|
6
6
|
/** The local containers forgetting an organization's content removes. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forgetOrganizationContentOperation.js","sourceRoot":"","sources":["forgetOrganizationContentOperation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sCAAsC,EAAE,MAAM,iEAAiE,CAAC;AACzH,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EACL,iCAAiC,EACjC,yBAAyB,GAC1B,MAAM,
|
|
1
|
+
{"version":3,"file":"forgetOrganizationContentOperation.js","sourceRoot":"","sources":["forgetOrganizationContentOperation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sCAAsC,EAAE,MAAM,iEAAiE,CAAC;AACzH,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EACL,iCAAiC,EACjC,yBAAyB,GAC1B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,EAC5B,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,+BAA+B,EAAE,MAAM,UAAU,CAAC;AAG3D,yEAAyE;AACzE,SAAS,uCAAuC,CAC9C,KAA0D,EAC1D,cAAsB;IAEtB,OAAO,CAAC,GAAG,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,CAClE,SAAS,CAAC,cAAc,KAAK,cAAc;QAC3C,CAAC,yBAAyB,CAAC,SAAS,CAAC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K,EAAE,cAAc,CAAC,CAC/D,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { removeOrganizationContentUnlessPending } from \"../../../workflows/container-contents/syncPause/documentRemoval\";\nimport { reclaimDocumentOrphanBlobs } from \"../../../workflows/documents\";\nimport {\n getOrCreateOrganizationSyncPauses,\n isRetainedWhileSyncPaused,\n} from \"../../../workflows/sync/coordination\";\nimport {\n emitPersistedDocumentDeletion,\n hasQueuedDocumentStoreWrites,\n restoreDocumentStore,\n retireDocumentStore,\n} from \"../../documents/registry\";\nimport type { ContainerWriteGuard } from \"../remoteWrites/writeGeneration\";\nimport { updateContainerContentsSnapshot } from \"../state\";\nimport type { ContainerContentsStoreState } from \"../types\";\n\n/** The local containers forgetting an organization's content removes. */\nfunction listForgettableOrganizationContainerIds(\n state: Pick<ContainerContentsStoreState, \"containersById\">,\n organizationId: string,\n): string[] {\n return [...state.containersById.values()].flatMap(({ container }) =>\n container.organizationId === organizationId &&\n !isRetainedWhileSyncPaused(container)\n ? [container.id]\n : [],\n );\n}\n\n/**\n * Removes one organization's content from this device after its sync was\n * paused: every container except its retained metadata root, and every\n * document placed only in those containers. Nothing changes on the server, so\n * resuming downloads it again.\n *\n * Unsynced work is never removed: the removal refuses while any pending write\n * touches the organization, checked under the same lock as the deletions, and\n * while an open store holds edits for any of its documents that have not\n * reached SQLite. It also refuses the session's active organization, whose\n * root the session still writes to. Returns whether nothing is left to retry.\n */\nasync function forgetOrganizationContent(\n state: ContainerContentsStoreState,\n organizationId: string,\n isCurrent: ContainerWriteGuard,\n): Promise<boolean> {\n if (state.runtime.infra.dbStatus !== \"ready\" || !state.snapshot.ready) {\n return false;\n }\n if (state.runtime.auth.organizationId === organizationId) return false;\n const containerIds = listForgettableOrganizationContainerIds(\n state,\n organizationId,\n );\n const { documentProjectors, execSql } = state.runtime.infra;\n const { domainScope } = state.runtime.state;\n // Switching into the organization mid-removal stops it before any deletion.\n const stillCurrent = () =>\n isCurrent() && state.runtime.auth.organizationId !== organizationId;\n await state.persistence.ensureSchema(execSql);\n const pauses = getOrCreateOrganizationSyncPauses(domainScope);\n const removal = await removeOrganizationContentUnlessPending({\n containerIds,\n deleteContainers: (lockedExecSql, removals) =>\n state.persistence.deleteContainers(lockedExecSql, removals, {\n stillCurrent,\n }),\n documentProjectors,\n execSql,\n hasQueuedWrites: (localId) =>\n hasQueuedDocumentStoreWrites(domainScope, localId),\n organizationId,\n restoreDocument: (localId) => restoreDocumentStore(domainScope, localId),\n retireDocument: (localId) =>\n retireDocumentStore(domainScope, localId, () =>\n pauses.isOrganizationPaused(organizationId),\n ),\n stillCurrent,\n });\n for (const localId of removal.deletedLocalIds) {\n emitPersistedDocumentDeletion(domainScope, localId);\n }\n if (removal.deletedLocalIds.length > 0) {\n void reclaimDocumentOrphanBlobs(state.runtime);\n }\n for (const containerId of removal.deletedContainerIds) {\n state.containersById.delete(containerId);\n }\n if (removal.deletedContainerIds.length > 0 && state.initialized) {\n updateContainerContentsSnapshot(state);\n }\n return removal.status === \"removed\";\n}\n\ntype ContainerWriteChain = (\n state: ContainerContentsStoreState,\n work: (isCurrent: () => boolean) => ContainerContentsStoreState[\"writeChain\"],\n changedIds: readonly string[],\n) => ContainerContentsStoreState[\"writeChain\"];\n\n/** Runs `forgetOrganizationContent` in the store's container write chain. */\nexport function createForgetOrganizationContentMethod(\n state: ContainerContentsStoreState,\n chainContainerWrite: ContainerWriteChain,\n): (organizationId: string) => Promise<boolean> {\n return async (organizationId) => {\n let forgotten = false;\n await chainContainerWrite(\n state,\n async (isCurrent) => {\n forgotten = await forgetOrganizationContent(\n state,\n organizationId,\n isCurrent,\n );\n return null;\n },\n listForgettableOrganizationContainerIds(state, organizationId),\n );\n return forgotten;\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { beginDomainSyncUploadLane, } from "../../../../workflows/sync/
|
|
1
|
+
import { beginDomainSyncUploadLane, } from "../../../../workflows/sync/coordination.js";
|
|
2
2
|
function getAttachmentUploadLaneLabel(name) {
|
|
3
3
|
return name ? `Upload ${name}` : "Attachment upload";
|
|
4
4
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentUploadLane.js","sourceRoot":"","sources":["attachmentUploadLane.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,yBAAyB,GAE1B,MAAM,
|
|
1
|
+
{"version":3,"file":"attachmentUploadLane.js","sourceRoot":"","sources":["attachmentUploadLane.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,yBAAyB,GAE1B,MAAM,yCAAyC,CAAC;AASjD,SAAS,4BAA4B,CAAC,IAA+B;IACnE,OAAO,IAAI,CAAC,CAAC,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,CAAC,mBAAmB,CAAC;AACvD,CAAC;AAED,SAAS,gCAAgC,CACvC,iBAA0C;IAE1C,OAAO,iBAAiB,CAAC,IAAI;QAC3B,CAAC,CAAC,GAAG,iBAAiB,CAAC,IAAI,UAAU,iBAAiB,CAAC,MAAM,GAAG;QAChE,CAAC,CAAC,QAAQ,iBAAiB,CAAC,MAAM,EAAE,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,iBAA0C,EAC1C,KAAc;IAEd,MAAM,KAAK,GAAG,IAAI,KAAK,CACrB,gCAAgC,gCAAgC,CAAC,iBAAiB,CAAC,GAAG,CACvF,CAAC;IACF,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IAE5D,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kCAAkC,CAAC,KAIlD;IACC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACzD,MAAM,OAAO,GAAuC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAEtE,MAAM,UAAU,GAAG,GAAmB,EAAE;QACtC,OAAO,CAAC,OAAO,KAAK,yBAAyB,CAC3C,WAAW,EACX,eAAe,MAAM,EAAE,EACvB;YACE,cAAc,EAAE,iBAAiB,CAAC,UAAU;YAC5C,KAAK,EAAE,4BAA4B,CAAC,iBAAiB,CAAC,IAAI,CAAC;SAC5D,CACF,CAAC;QACF,OAAO,OAAO,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC;IAEF,OAAO;QACL,QAAQ;YACN,oEAAoE;YACpE,8DAA8D;YAC9D,UAAU,EAAE,CAAC,QAAQ,EAAE,CAAC;QAC1B,CAAC;QACD,IAAI,CAAC,KAAc;YACjB,UAAU,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC3B,CAAC;QACD,aAAa,CAAC,KAAc;YAC1B,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QACD,mBAAmB,CAAC,QAAQ;YAC1B,UAAU,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;QACxC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../../../data/shared/domainScope\";\nimport type { MultipartUploadProgressListener } from \"../../../../workflows/blobs\";\nimport type { PendingAttachmentRecord } from \"../../../../workflows/documents\";\nimport {\n beginDomainSyncUploadLane,\n type UploadSyncLane,\n} from \"../../../../workflows/sync/coordination\";\n\nexport interface AttachmentUploadLaneReporter {\n complete: () => void;\n fail: (error: unknown) => void;\n failIfStarted: (error: unknown) => void;\n onMultipartProgress: MultipartUploadProgressListener;\n}\n\nfunction getAttachmentUploadLaneLabel(name: string | null | undefined): string {\n return name ? `Upload ${name}` : \"Attachment upload\";\n}\n\nfunction getAttachmentUploadFailureTarget(\n pendingAttachment: PendingAttachmentRecord,\n): string {\n return pendingAttachment.name\n ? `${pendingAttachment.name} (slot ${pendingAttachment.slotId})`\n : `slot ${pendingAttachment.slotId}`;\n}\n\nexport function createAttachmentUploadFailedError(\n pendingAttachment: PendingAttachmentRecord,\n cause: unknown,\n): Error {\n const error = new Error(\n `Attachment upload failed for ${getAttachmentUploadFailureTarget(pendingAttachment)}.`,\n );\n if (cause !== undefined) Reflect.set(error, \"cause\", cause);\n\n return error;\n}\n\n/**\n * Surfaces attachment uploads as observational lanes. The persisted blob id is\n * the lane identity: slot ids repeat across documents, while a retry must keep\n * updating the same row. Lane creation stays lazy until progress, failure, or\n * completion so a billing block before any upload work does not add noise.\n */\nexport function createAttachmentUploadLaneReporter(input: {\n blobId: string;\n domainScope: DomainScope;\n pendingAttachment: PendingAttachmentRecord;\n}): AttachmentUploadLaneReporter {\n const { blobId, domainScope, pendingAttachment } = input;\n const laneRef: { current: UploadSyncLane | null } = { current: null };\n\n const ensureLane = (): UploadSyncLane => {\n laneRef.current ??= beginDomainSyncUploadLane(\n domainScope,\n `blob-upload:${blobId}`,\n {\n blobStorageKey: pendingAttachment.storageKey,\n label: getAttachmentUploadLaneLabel(pendingAttachment.name),\n },\n );\n return laneRef.current;\n };\n\n return {\n complete() {\n // Completion must create/re-begin the lane too: a resumed stage can\n // already be complete before it emits any per-part callbacks.\n ensureLane().complete();\n },\n fail(error: unknown) {\n ensureLane().fail(error);\n },\n failIfStarted(error: unknown) {\n laneRef.current?.fail(error);\n },\n onMultipartProgress(progress) {\n ensureLane().reportProgress(progress);\n },\n };\n}\n"]}
|
|
@@ -4,7 +4,7 @@ import { DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, } from "../../../
|
|
|
4
4
|
import { initializeStoredDocumentKind, readStoredDocumentState, } from "../../../../data/documents/documentKinds.js";
|
|
5
5
|
import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
|
|
6
6
|
import { isDatabaseUnavailableError, loadPersistedDocumentStoreState, } from "../../../../workflows/documents/index.js";
|
|
7
|
-
import { OrganizationSyncPauseRepository } from "../../../../workflows/sync/
|
|
7
|
+
import { OrganizationSyncPauseRepository } from "../../../../workflows/sync/coordination.js";
|
|
8
8
|
import { chainIdentityWrite } from "../identityWriteChain.js";
|
|
9
9
|
import { runDocumentOrphanMaintenance } from "../orphanMaintenance.js";
|
|
10
10
|
import { advancePendingBaseVersion, documentSummaryFromRecord, persistDocument, saveDocumentRecord, } from "../persistence.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,GACxB,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAEL,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,+BAA+B,EAAE,MAAM,4BAA4B,CAAC;AAE7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,eAAe,EACf,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAGL,gBAAgB,GACjB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EAAE,iCAAiC,EAAE,MAAM,8BAA8B,CAAC;AACjF,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,EAClC,iCAAiC,EACjC,oCAAoC,EACpC,kCAAkC,GACnC,MAAM,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,KAAK,GAAG,iBAAiB,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAErD,2EAA2E;QAC3E,oEAAoE;QACpE,oEAAoE;QACpE,2EAA2E;QAC3E,2CAA2C;QAC3C,qEAAqE;QACrE,oEAAoE;QACpE,qEAAqE;QACrE,gDAAgD;QAChD,IAAI,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC;YAC7D,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,eAAe,CAClC,KAAK,EACL,UAAU,EACV,KAAK,EACL;YACE,gCAAgC,EAAE,IAAI;YACtC,oBAAoB,EAAE,IAAI;YAC1B,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,EACD,UAAU,EACV,gBAAgB,CACjB,CAAC;QACF,IAAI,MAAM,IAAI,iBAAiB,KAAK,KAAK,CAAC,UAAU,EAAE,CAAC;YACrD,KAAK,CAAC,gBAAgB,GAAG,IAAI,CAAC;YAC9B,iCAAiC,CAAC,KAAK,CAAC,CAAC;QAC3C,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,yEAAyE;IACzE,yCAAyC;IACzC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,SAAS,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,yBAAyB,CAC9B,SAAS,CAAC,MAAM,EAChB,SAAS,CAAC,SAAS,EACnB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CACvC,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n emptyVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistorySnapshot,\n mergeVersionVectors,\n} from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../../../data/documents/documentConstants\";\nimport {\n initializeStoredDocumentKind,\n readStoredDocumentState,\n} from \"../../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport {\n type DocumentRecord,\n isDatabaseUnavailableError,\n loadPersistedDocumentStoreState,\n} from \"../../../../workflows/documents\";\nimport { OrganizationSyncPauseRepository } from \"../../../../workflows/sync\";\nimport type { DocumentStoreRelinkInput } from \"../../types\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport type { DocumentRelinkCommitSideEffect } from \"../internalRelink\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n advancePendingBaseVersion,\n documentSummaryFromRecord,\n persistDocument,\n saveDocumentRecord,\n} from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { logRevalidationScheduled } from \"../sync/remoteRevalidationTelemetry\";\nimport { deferStartupProbeToPendingConnect } from \"../sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreSyncGeneration,\n invalidateDocumentStoreRemoteSync,\n isDocumentStoreSyncGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n} from \"../sync/syncGeneration\";\nimport { writeInitialDocumentContent } from \"./initialContent\";\nimport {\n installPersistedAttachments,\n type LoadedDocumentStoreState,\n} from \"./initializationAttachments\";\nimport {\n type RestoredHistoryState,\n restoredRemoteTailCoverage,\n restorePersistedDocumentContent,\n} from \"./initializationHistory\";\nimport {\n healLocalAttachmentDetachState,\n recoverDroppedAttachmentSlots,\n} from \"./initializationRecovery\";\nimport { relinkRecordPatch } from \"./relinkRecordPatch\";\n\nasync function createInitialDocumentRecord(\n state: DocumentStoreState,\n nextDoc: DocumentState,\n): ReturnType<typeof saveDocumentRecord> {\n initializeStoredDocumentKind(\n nextDoc,\n state.initialDocumentKind,\n state.runtime.infra.documentProjectors,\n );\n if (state.initialText.length > 0) {\n nextDoc.getText(\"text\").update(state.initialText);\n }\n const wroteInitialContent = writeInitialDocumentContent(state, nextDoc);\n const initialDocumentState = readStoredDocumentState(\n nextDoc,\n state.runtime.infra.documentProjectors,\n );\n const hasInitialContent =\n wroteInitialContent ||\n state.initialText.length > 0 ||\n state.initialDocumentKind !== DEFAULT_DOCUMENT_KIND;\n const initialUpdate = hasInitialContent\n ? createPendingUpdateFields(exportAllUpdates(nextDoc))\n : null;\n // A deferred birth still commits its checkpoint, but leaves the marker at the\n // empty version with nothing queued: the promised attach exports every op\n // since that marker, so one update carries the birth and the attachment.\n const birthDurability = !initialUpdate\n ? {}\n : state.deferInitialUpdate\n ? { pendingBaseVersionOverride: emptyVersionVector() }\n : { pendingUpdate: initialUpdate };\n\n const created: DocumentRecord = {\n id: state.localId,\n containerId: state.runtime.state.containerId ?? null,\n documentId: state.initialDocumentId,\n documentKind: initialDocumentState.documentKind,\n text: initialDocumentState.text,\n title: initialDocumentState.title,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n accessEpoch: DEFAULT_DOCUMENT_ACCESS_EPOCH,\n accessStateHash: null,\n effectiveAccessLevel: \"admin\",\n lastCommitLsn: null,\n contentKeyBundle: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n };\n // The create-only persistence primitive commits the canonical row and birth\n // checkpoint together. A concurrent initializer either wins both or adopts\n // both, so it cannot replace another pane's history or keying state.\n const persisted = await saveDocumentRecord(\n state,\n nextDoc,\n {\n ...created,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n },\n {\n historyCheckpoint: {\n coveredTailIds: [],\n endVersionVector: encodeVersionVector(nextDoc),\n pruneCoveredLocalState: false,\n snapshot: bytesToBase64(exportFullHistorySnapshot(nextDoc)),\n },\n ...birthDurability,\n },\n );\n return persisted;\n}\n\nfunction installPersistedDocumentRecord(\n state: DocumentStoreState,\n record: NonNullable<DocumentStoreState[\"record\"]>,\n): void {\n state.record = record;\n state.pullContinuation = record.pullContinuation ?? null;\n}\n\ninterface RestoredInitialDocumentState {\n activePersistedState: LoadedDocumentStoreState;\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n}\n\nasync function restoreLoadedInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n const record = persistedState.document;\n if (!record) return null;\n const history = await restorePersistedDocumentContent(\n input.nextDoc,\n persistedState.historyRestoreState,\n );\n if (state.localWriteGeneration !== initializeGeneration) return null;\n installPersistedDocumentRecord(state, record);\n return {\n activePersistedState: persistedState,\n activeRecord: record,\n doc: input.nextDoc,\n history,\n };\n}\n\nasync function restoreOrCreateInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n if (persistedState.document) {\n return restoreLoadedInitialDocument(input);\n }\n const created = await createInitialDocumentRecord(state, input.nextDoc);\n if (!created || state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n const activePersistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n if (!activePersistedState.document) {\n throw new Error(\"Document creation completed without a durable record\");\n }\n const replacementDoc = await createStoredDocument(state);\n return restoreLoadedInitialDocument({\n initializeGeneration,\n nextDoc: replacementDoc,\n persistedState: activePersistedState,\n state,\n });\n}\n\nfunction restorePendingBaseVersion(input: {\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n state: DocumentStoreState;\n}): void {\n const { activeRecord, doc, history, state } = input;\n const markerBase =\n activeRecord.pendingBaseVersion ??\n (activeRecord.snapshotEndVersion.length > 0\n ? activeRecord.snapshotEndVersion\n : null);\n if (markerBase === null) {\n advancePendingBaseVersion(state, doc);\n return;\n }\n\n const remoteCoverage = restoredRemoteTailCoverage(history);\n state.pendingBaseVersion =\n remoteCoverage.length > 0\n ? mergeVersionVectors([markerBase, ...remoteCoverage])\n : markerBase;\n}\n\nasync function initializeDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n // A store reset while this fire-and-forget initialization is loading (a\n // runtime swap, or a local-edits discard that re-seeds the persisted rows)\n // must win: assigning the state loaded BEFORE the reset would bring the\n // replaced record and doc back to life. Every reset bumps the local write\n // generation, so a stale capture here aborts before each assignment batch.\n const initializeGeneration = state.localWriteGeneration;\n\n const nextDoc = await createStoredDocument(state);\n const persistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n // A paused organization's cleanup removed it; creating it again would\n // download the organization's content while the pause lasts. A later open\n // retries, so it loads once the organization resumes.\n if (\n !persistedState.document &&\n (await new OrganizationSyncPauseRepository(\n state.runtime.infra.execSql,\n ).isPauseRemovedDocument(state.localId))\n ) {\n state.initializePromise = null;\n return;\n }\n const restored = await restoreOrCreateInitialDocument({\n initializeGeneration,\n nextDoc,\n persistedState,\n state,\n });\n if (!restored) {\n if (state.localWriteGeneration === initializeGeneration) {\n state.initializePromise = null;\n }\n return;\n }\n const activePersistedState = restored.activePersistedState;\n installPersistedAttachments(state, activePersistedState);\n\n state.doc = restored.doc;\n // Restore the durable outgoing-delta marker. Re-seeding it to the restored\n // document's version would move it PAST any device-first `deferRemoteSync`\n // op (persisted into the durable history but deliberately left un-enqueued\n // and behind the marker), permanently dropping that op from sync across a\n // restart. When a marker was persisted, restore it so the next edit still\n // re-derives the deferred delta. Only seed for rows that never persisted\n // one, from the RECORD's persisted frontier rather than the restored\n // document: a crash between the tail append and the queue/marker writes can\n // resurrect ops the outgoing queue never durably received, and seeding from\n // the restored document would classify those as covered and orphan them\n // from sync forever.\n restorePendingBaseVersion({\n activeRecord: restored.activeRecord,\n doc: restored.doc,\n history: restored.history,\n state,\n });\n // Heal attachment slots lost to an interrupted attach write before marking\n // ready, so the recovered slots are in the snapshot the editor first renders\n // and are queued for sync. recoverDroppedAttachmentSlots advances the marker\n // again for whatever it re-derives. Both helpers gate every durable write\n // on this generation (validated inside the writes' serialized mutations),\n // so a reset mid-helper cannot repopulate discarded state.\n const writeGeneration = captureDocumentStoreSyncGeneration(\n state,\n restored.doc,\n );\n if (!writeGeneration) {\n return;\n }\n await recoverDroppedAttachmentSlots(state, restored.doc, writeGeneration);\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n await healLocalAttachmentDetachState(\n state,\n restored.doc,\n activePersistedState,\n writeGeneration,\n );\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n state.initialized = true;\n state.initializePromise = null;\n setReadySnapshot(state, restored.doc, false);\n\n // Websocket invalidations are intentionally session-local. A process can\n // stop before receiving a peer device's update event, and no event survives\n // the restart to distinguish a clean local snapshot from a stale one. Probe\n // each opened remote document once after loading it; unopened documents stay\n // lazy, while body and attachment state for a restored window converges.\n // A connect attempt in flight arms a later probe on its acknowledgement,\n // which covers this one, so the startup probe waits on that attempt.\n if (\n restored.activeRecord.documentId &&\n state.scheduleStartupRemoteSync &&\n !deferStartupProbeToPendingConnect(state)\n ) {\n allowDocumentStoreRemoteSync(state);\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n logRevalidationScheduled(state.runtime, \"startup\");\n }\n scheduleSync();\n void runDocumentOrphanMaintenance(state);\n}\n\nexport function ensureDocumentStoreInitialized(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (\n state.initialized ||\n state.initializePromise ||\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return;\n }\n\n const initializePromise = initializeDocumentStore(state, scheduleSync).catch(\n (error: unknown) => {\n state.initializePromise = null;\n // A caller that deferred the birth for its attach may give up once\n // opening fails; never leave its durable birth holding sync. No attach\n // has reached a live doc yet, so lifting the hold ships nothing unsafe.\n state.deferInitialUpdate = false;\n\n if (isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n },\n );\n state.initializePromise = initializePromise;\n void initializePromise.catch(() => undefined);\n}\n\nexport async function awaitInitializationForSync(state: DocumentStoreState) {\n if (!state.initializePromise) {\n return state.initialized;\n }\n\n try {\n await state.initializePromise;\n return state.initialized;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function ensureDocumentStoreReady(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): Promise<boolean> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (state.initialized) {\n return true;\n }\n\n if (!state.initializePromise) {\n return false;\n }\n\n return awaitInitializationForSync(state);\n}\n\nexport async function relinkDocumentStore(\n state: DocumentStoreState,\n input: DocumentStoreRelinkInput,\n scheduleSync: () => void,\n commitSideEffect?: DocumentRelinkCommitSideEffect,\n): Promise<DocumentSummary | null> {\n if (\n input.stillCurrent?.() === false ||\n !(await ensureDocumentStoreReady(state, scheduleSync)) ||\n input.stillCurrent?.() === false ||\n !state.doc\n ) {\n return null;\n }\n const currentDoc = state.doc;\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) return null;\n // Read the record and persist on the identity-write chain so an in-flight\n // eager create cannot interleave: a create that captured a null identity\n // before its network round trip would otherwise write the derived documentId\n // over the one this relink assigns.\n const persisted = await chainIdentityWrite(state, async () => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n const currentDocumentId = state.record?.documentId ?? null;\n const patch = relinkRecordPatch(state.record, input);\n\n // Relink rewrites access/identity metadata, not content. If it lands while\n // the user is mid-edit, re-deriving text/structured fields from the\n // (possibly lagging) doc would republish a stale read over the live\n // optimistic snapshot and drop in-flight keystrokes; preserve the snapshot\n // like the keystroke and sync persists do.\n // A prior chained write may have cleared this store (resurrect-guard\n // refusal): persisting the captured doc against a null record would\n // resurrect the document as a create. The identity check runs inside\n // the chain, after every earlier write settled.\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n return null;\n }\n const result = await persistDocument(\n state,\n currentDoc,\n patch,\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n stillCurrent: input.stillCurrent,\n },\n generation,\n commitSideEffect,\n );\n if (result && currentDocumentId !== input.documentId) {\n state.writerProjection = null;\n invalidateDocumentStoreRemoteSync(state);\n }\n return result;\n });\n // A refused persist means the durable row vanished mid-relink (resurrect\n // guard); there is no summary to report.\n if (!persisted) {\n return null;\n }\n if (persisted.updatedAt === undefined) {\n return null;\n }\n return documentSummaryFromRecord(\n persisted.record,\n persisted.updatedAt,\n state.runtime.infra.documentProjectors,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,GACxB,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAEL,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAE1F,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,4BAA4B,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AC;IACd,CAAC;IACD,IAAI,SAAS,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,yBAAyB,CAC9B,SAAS,CAAC,MAAM,EAChB,SAAS,CAAC,SAAS,EACnB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CACvC,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n emptyVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistorySnapshot,\n mergeVersionVectors,\n} from \"@tearleads/loro\";\nimport {\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n} from \"../../../../data/documents/documentConstants\";\nimport {\n initializeStoredDocumentKind,\n readStoredDocumentState,\n} from \"../../../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport {\n type DocumentRecord,\n isDatabaseUnavailableError,\n loadPersistedDocumentStoreState,\n} from \"../../../../workflows/documents\";\nimport { OrganizationSyncPauseRepository } from \"../../../../workflows/sync/coordination\";\nimport type { DocumentStoreRelinkInput } from \"../../types\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport type { DocumentRelinkCommitSideEffect } from \"../internalRelink\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport {\n advancePendingBaseVersion,\n documentSummaryFromRecord,\n persistDocument,\n saveDocumentRecord,\n} from \"../persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { logRevalidationScheduled } from \"../sync/remoteRevalidationTelemetry\";\nimport { deferStartupProbeToPendingConnect } from \"../sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreSyncGeneration,\n invalidateDocumentStoreRemoteSync,\n isDocumentStoreSyncGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n} from \"../sync/syncGeneration\";\nimport { writeInitialDocumentContent } from \"./initialContent\";\nimport {\n installPersistedAttachments,\n type LoadedDocumentStoreState,\n} from \"./initializationAttachments\";\nimport {\n type RestoredHistoryState,\n restoredRemoteTailCoverage,\n restorePersistedDocumentContent,\n} from \"./initializationHistory\";\nimport {\n healLocalAttachmentDetachState,\n recoverDroppedAttachmentSlots,\n} from \"./initializationRecovery\";\nimport { relinkRecordPatch } from \"./relinkRecordPatch\";\n\nasync function createInitialDocumentRecord(\n state: DocumentStoreState,\n nextDoc: DocumentState,\n): ReturnType<typeof saveDocumentRecord> {\n initializeStoredDocumentKind(\n nextDoc,\n state.initialDocumentKind,\n state.runtime.infra.documentProjectors,\n );\n if (state.initialText.length > 0) {\n nextDoc.getText(\"text\").update(state.initialText);\n }\n const wroteInitialContent = writeInitialDocumentContent(state, nextDoc);\n const initialDocumentState = readStoredDocumentState(\n nextDoc,\n state.runtime.infra.documentProjectors,\n );\n const hasInitialContent =\n wroteInitialContent ||\n state.initialText.length > 0 ||\n state.initialDocumentKind !== DEFAULT_DOCUMENT_KIND;\n const initialUpdate = hasInitialContent\n ? createPendingUpdateFields(exportAllUpdates(nextDoc))\n : null;\n // A deferred birth still commits its checkpoint, but leaves the marker at the\n // empty version with nothing queued: the promised attach exports every op\n // since that marker, so one update carries the birth and the attachment.\n const birthDurability = !initialUpdate\n ? {}\n : state.deferInitialUpdate\n ? { pendingBaseVersionOverride: emptyVersionVector() }\n : { pendingUpdate: initialUpdate };\n\n const created: DocumentRecord = {\n id: state.localId,\n containerId: state.runtime.state.containerId ?? null,\n documentId: state.initialDocumentId,\n documentKind: initialDocumentState.documentKind,\n text: initialDocumentState.text,\n title: initialDocumentState.title,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n accessEpoch: DEFAULT_DOCUMENT_ACCESS_EPOCH,\n accessStateHash: null,\n effectiveAccessLevel: \"admin\",\n lastCommitLsn: null,\n contentKeyBundle: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n };\n // The create-only persistence primitive commits the canonical row and birth\n // checkpoint together. A concurrent initializer either wins both or adopts\n // both, so it cannot replace another pane's history or keying state.\n const persisted = await saveDocumentRecord(\n state,\n nextDoc,\n {\n ...created,\n snapshotEndVersion: encodeVersionVector(nextDoc),\n },\n {\n historyCheckpoint: {\n coveredTailIds: [],\n endVersionVector: encodeVersionVector(nextDoc),\n pruneCoveredLocalState: false,\n snapshot: bytesToBase64(exportFullHistorySnapshot(nextDoc)),\n },\n ...birthDurability,\n },\n );\n return persisted;\n}\n\nfunction installPersistedDocumentRecord(\n state: DocumentStoreState,\n record: NonNullable<DocumentStoreState[\"record\"]>,\n): void {\n state.record = record;\n state.pullContinuation = record.pullContinuation ?? null;\n}\n\ninterface RestoredInitialDocumentState {\n activePersistedState: LoadedDocumentStoreState;\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n}\n\nasync function restoreLoadedInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n const record = persistedState.document;\n if (!record) return null;\n const history = await restorePersistedDocumentContent(\n input.nextDoc,\n persistedState.historyRestoreState,\n );\n if (state.localWriteGeneration !== initializeGeneration) return null;\n installPersistedDocumentRecord(state, record);\n return {\n activePersistedState: persistedState,\n activeRecord: record,\n doc: input.nextDoc,\n history,\n };\n}\n\nasync function restoreOrCreateInitialDocument(input: {\n initializeGeneration: number;\n nextDoc: DocumentState;\n persistedState: LoadedDocumentStoreState;\n state: DocumentStoreState;\n}): Promise<RestoredInitialDocumentState | null> {\n const { initializeGeneration, persistedState, state } = input;\n if (persistedState.document) {\n return restoreLoadedInitialDocument(input);\n }\n const created = await createInitialDocumentRecord(state, input.nextDoc);\n if (!created || state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n const activePersistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return null;\n }\n if (!activePersistedState.document) {\n throw new Error(\"Document creation completed without a durable record\");\n }\n const replacementDoc = await createStoredDocument(state);\n return restoreLoadedInitialDocument({\n initializeGeneration,\n nextDoc: replacementDoc,\n persistedState: activePersistedState,\n state,\n });\n}\n\nfunction restorePendingBaseVersion(input: {\n activeRecord: NonNullable<DocumentStoreState[\"record\"]>;\n doc: DocumentState;\n history: RestoredHistoryState | null;\n state: DocumentStoreState;\n}): void {\n const { activeRecord, doc, history, state } = input;\n const markerBase =\n activeRecord.pendingBaseVersion ??\n (activeRecord.snapshotEndVersion.length > 0\n ? activeRecord.snapshotEndVersion\n : null);\n if (markerBase === null) {\n advancePendingBaseVersion(state, doc);\n return;\n }\n\n const remoteCoverage = restoredRemoteTailCoverage(history);\n state.pendingBaseVersion =\n remoteCoverage.length > 0\n ? mergeVersionVectors([markerBase, ...remoteCoverage])\n : markerBase;\n}\n\nasync function initializeDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n // A store reset while this fire-and-forget initialization is loading (a\n // runtime swap, or a local-edits discard that re-seeds the persisted rows)\n // must win: assigning the state loaded BEFORE the reset would bring the\n // replaced record and doc back to life. Every reset bumps the local write\n // generation, so a stale capture here aborts before each assignment batch.\n const initializeGeneration = state.localWriteGeneration;\n\n const nextDoc = await createStoredDocument(state);\n const persistedState = await loadPersistedDocumentStoreState({\n execSql: state.runtime.infra.execSql,\n localId: state.localId,\n persistence: state.persistence,\n });\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n // A paused organization's cleanup removed it; creating it again would\n // download the organization's content while the pause lasts. A later open\n // retries, so it loads once the organization resumes.\n if (\n !persistedState.document &&\n (await new OrganizationSyncPauseRepository(\n state.runtime.infra.execSql,\n ).isPauseRemovedDocument(state.localId))\n ) {\n state.initializePromise = null;\n return;\n }\n const restored = await restoreOrCreateInitialDocument({\n initializeGeneration,\n nextDoc,\n persistedState,\n state,\n });\n if (!restored) {\n if (state.localWriteGeneration === initializeGeneration) {\n state.initializePromise = null;\n }\n return;\n }\n const activePersistedState = restored.activePersistedState;\n installPersistedAttachments(state, activePersistedState);\n\n state.doc = restored.doc;\n // Restore the durable outgoing-delta marker. Re-seeding it to the restored\n // document's version would move it PAST any device-first `deferRemoteSync`\n // op (persisted into the durable history but deliberately left un-enqueued\n // and behind the marker), permanently dropping that op from sync across a\n // restart. When a marker was persisted, restore it so the next edit still\n // re-derives the deferred delta. Only seed for rows that never persisted\n // one, from the RECORD's persisted frontier rather than the restored\n // document: a crash between the tail append and the queue/marker writes can\n // resurrect ops the outgoing queue never durably received, and seeding from\n // the restored document would classify those as covered and orphan them\n // from sync forever.\n restorePendingBaseVersion({\n activeRecord: restored.activeRecord,\n doc: restored.doc,\n history: restored.history,\n state,\n });\n // Heal attachment slots lost to an interrupted attach write before marking\n // ready, so the recovered slots are in the snapshot the editor first renders\n // and are queued for sync. recoverDroppedAttachmentSlots advances the marker\n // again for whatever it re-derives. Both helpers gate every durable write\n // on this generation (validated inside the writes' serialized mutations),\n // so a reset mid-helper cannot repopulate discarded state.\n const writeGeneration = captureDocumentStoreSyncGeneration(\n state,\n restored.doc,\n );\n if (!writeGeneration) {\n return;\n }\n await recoverDroppedAttachmentSlots(state, restored.doc, writeGeneration);\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n await healLocalAttachmentDetachState(\n state,\n restored.doc,\n activePersistedState,\n writeGeneration,\n );\n if (state.localWriteGeneration !== initializeGeneration) {\n return;\n }\n state.initialized = true;\n state.initializePromise = null;\n setReadySnapshot(state, restored.doc, false);\n\n // Websocket invalidations are intentionally session-local. A process can\n // stop before receiving a peer device's update event, and no event survives\n // the restart to distinguish a clean local snapshot from a stale one. Probe\n // each opened remote document once after loading it; unopened documents stay\n // lazy, while body and attachment state for a restored window converges.\n // A connect attempt in flight arms a later probe on its acknowledgement,\n // which covers this one, so the startup probe waits on that attempt.\n if (\n restored.activeRecord.documentId &&\n state.scheduleStartupRemoteSync &&\n !deferStartupProbeToPendingConnect(state)\n ) {\n allowDocumentStoreRemoteSync(state);\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n logRevalidationScheduled(state.runtime, \"startup\");\n }\n scheduleSync();\n void runDocumentOrphanMaintenance(state);\n}\n\nexport function ensureDocumentStoreInitialized(\n state: DocumentStoreState,\n scheduleSync: () => void,\n) {\n if (\n state.initialized ||\n state.initializePromise ||\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return;\n }\n\n const initializePromise = initializeDocumentStore(state, scheduleSync).catch(\n (error: unknown) => {\n state.initializePromise = null;\n // A caller that deferred the birth for its attach may give up once\n // opening fails; never leave its durable birth holding sync. No attach\n // has reached a live doc yet, so lifting the hold ships nothing unsafe.\n state.deferInitialUpdate = false;\n\n if (isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n },\n );\n state.initializePromise = initializePromise;\n void initializePromise.catch(() => undefined);\n}\n\nexport async function awaitInitializationForSync(state: DocumentStoreState) {\n if (!state.initializePromise) {\n return state.initialized;\n }\n\n try {\n await state.initializePromise;\n return state.initialized;\n } catch (error) {\n if (isDatabaseUnavailableError(error)) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function ensureDocumentStoreReady(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): Promise<boolean> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (state.initialized) {\n return true;\n }\n\n if (!state.initializePromise) {\n return false;\n }\n\n return awaitInitializationForSync(state);\n}\n\nexport async function relinkDocumentStore(\n state: DocumentStoreState,\n input: DocumentStoreRelinkInput,\n scheduleSync: () => void,\n commitSideEffect?: DocumentRelinkCommitSideEffect,\n): Promise<DocumentSummary | null> {\n if (\n input.stillCurrent?.() === false ||\n !(await ensureDocumentStoreReady(state, scheduleSync)) ||\n input.stillCurrent?.() === false ||\n !state.doc\n ) {\n return null;\n }\n const currentDoc = state.doc;\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) return null;\n // Read the record and persist on the identity-write chain so an in-flight\n // eager create cannot interleave: a create that captured a null identity\n // before its network round trip would otherwise write the derived documentId\n // over the one this relink assigns.\n const persisted = await chainIdentityWrite(state, async () => {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) return null;\n const currentDocumentId = state.record?.documentId ?? null;\n const patch = relinkRecordPatch(state.record, input);\n\n // Relink rewrites access/identity metadata, not content. If it lands while\n // the user is mid-edit, re-deriving text/structured fields from the\n // (possibly lagging) doc would republish a stale read over the live\n // optimistic snapshot and drop in-flight keystrokes; preserve the snapshot\n // like the keystroke and sync persists do.\n // A prior chained write may have cleared this store (resurrect-guard\n // refusal): persisting the captured doc against a null record would\n // resurrect the document as a create. The identity check runs inside\n // the chain, after every earlier write settled.\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n return null;\n }\n const result = await persistDocument(\n state,\n currentDoc,\n patch,\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n stillCurrent: input.stillCurrent,\n },\n generation,\n commitSideEffect,\n );\n if (result && currentDocumentId !== input.documentId) {\n state.writerProjection = null;\n invalidateDocumentStoreRemoteSync(state);\n }\n return result;\n });\n // A refused persist means the durable row vanished mid-relink (resurrect\n // guard); there is no summary to report.\n if (!persisted) {\n return null;\n }\n if (persisted.updatedAt === undefined) {\n return null;\n }\n return documentSummaryFromRecord(\n persisted.record,\n persisted.updatedAt,\n state.runtime.infra.documentProjectors,\n );\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { createDocument } from "../../../internal/loro/index.js";
|
|
|
2
2
|
import { ensureDocumentAttachmentStructure } from "../../../data/documents/documentContent.js";
|
|
3
3
|
import { ensureDocumentRowsStructure } from "../../../data/documents/documentRowList.js";
|
|
4
4
|
import { DOCUMENTS_APP_KIND } from "../../../workflows/documents/index.js";
|
|
5
|
-
import { getRuntimePeerSeed } from "../../../workflows/sync/
|
|
5
|
+
import { getRuntimePeerSeed } from "../../../workflows/sync/coordination.js";
|
|
6
6
|
async function createStoredDocumentWithSeed(peerSeed) {
|
|
7
7
|
const createdDoc = await createDocument(peerSeed);
|
|
8
8
|
ensureDocumentAttachmentStructure(createdDoc);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storedDocument.js","sourceRoot":"","sources":["storedDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,iCAAiC,EAAE,MAAM,yCAAyC,CAAC;AAC5F,OAAO,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"storedDocument.js","sourceRoot":"","sources":["storedDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,iCAAiC,EAAE,MAAM,yCAAyC,CAAC;AAC5F,OAAO,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAG1E,KAAK,UAAU,4BAA4B,CACzC,QAAgB;IAEhB,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,QAAQ,CAAC,CAAC;IAClD,iCAAiC,CAAC,UAAU,CAAC,CAAC;IAC9C,2BAA2B,CAAC,UAAU,CAAC,CAAC;IACxC,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAyB;IAEzB,6EAA6E;IAC7E,4EAA4E;IAC5E,0EAA0E;IAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;IAChD,MAAM,KAAK,GAAG,SAAS;QACrB,CAAC,CAAC,GAAG,kBAAkB,IAAI,SAAS,EAAE;QACtC,CAAC,CAAC,kBAAkB,CAAC;IACvB,OAAO,4BAA4B,CACjC,MAAM,kBAAkB,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CACjE,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,6BAA6B;IAC3C,OAAO,4BAA4B,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { createDocument } from \"@tearleads/loro\";\nimport { ensureDocumentAttachmentStructure } from \"../../../data/documents/documentContent\";\nimport { ensureDocumentRowsStructure } from \"../../../data/documents/documentRowList\";\nimport { DOCUMENTS_APP_KIND } from \"../../../workflows/documents\";\nimport { getRuntimePeerSeed } from \"../../../workflows/sync/coordination\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\n\nasync function createStoredDocumentWithSeed(\n peerSeed: string,\n): Promise<DocumentState> {\n const createdDoc = await createDocument(peerSeed);\n ensureDocumentAttachmentStructure(createdDoc);\n ensureDocumentRowsStructure(createdDoc);\n return createdDoc;\n}\n\nexport async function createStoredDocument(\n state: DocumentStoreState,\n): Promise<DocumentState> {\n // Persistent pane namespaces retain stable seeds. Concurrent runtimes in one\n // namespace receive distinct memory-only seeds after the first owner, while\n // the usual single runtime can reuse its device seed after a page reload.\n const peerScope = state.runtime.state.peerScope;\n const scope = peerScope\n ? `${DOCUMENTS_APP_KIND}:${peerScope}`\n : DOCUMENTS_APP_KIND;\n return createStoredDocumentWithSeed(\n await getRuntimePeerSeed(scope, state.runtime.state.domainScope),\n );\n}\n\n/**\n * Rebuild after discarding non-durable local ops under a new peer. Reusing the\n * normal peer would reuse the discarded counters and corrupt the next edit.\n */\nexport function createFreshPeerStoredDocument(): Promise<DocumentState> {\n return createStoredDocumentWithSeed(crypto.randomUUID());\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DOCUMENTS_APP_KIND, DocumentRecordRepository, resolveDocumentCreateAuthor, } from "../../../../workflows/documents/index.js";
|
|
2
|
-
import { markOriginatedDocuments } from "../../../../workflows/sync/
|
|
2
|
+
import { markOriginatedDocuments } from "../../../../workflows/sync/coordination.js";
|
|
3
3
|
import { requestDocumentStoreSync } from "../../registry.js";
|
|
4
4
|
import { dropUnavailablePendingAttachment, pendingAttachmentMatchesIntent, resolveAttachmentSourceUpload, } from "../attachmentUpload/attachmentSourceUpload.js";
|
|
5
5
|
import { uploadAttachmentWithWriterProjectionRetry } from "../attachmentUpload/attachmentUploadAttempt.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EACL,gCAAgC,EAChC,8BAA8B,EAC9B,6BAA6B,GAC9B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yCAAyC,EAAE,MAAM,6CAA6C,CAAC;AACxG,OAAO,EAEL,kCAAkC,GACnC,MAAM,0CAA0C,CAAC;AAQlD,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC1E,OAAO,EAEL,uCAAuC,EACvC,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,oCAAoC,GACrC,M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AM,CAAC,MAAM;QACrB,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,iBAAiB;KAClB,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,+BAA+B,CAAC;QACtD,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,MAAM;QACN,MAAM;QACN,cAAc,EAAE,QAAQ;QACxB,UAAU;KACX,CAAC,CAAC;IACH,OAAO,4BAA4B,CAAC;QAClC,eAAe;QACf,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,eAAe;QAC9C,aAAa,EAAE,KAAK;QACpB,UAAU;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n BlobAttachmentService,\n BlobByteSource,\n BlobSourceSnapshot,\n} from \"../../../../workflows/blobs\";\nimport type { PreparedUploadDocumentAttachmentRequest } from \"../../../../workflows/blobs/upload\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { markOriginatedDocuments } from \"../../../../workflows/sync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"../attachmentUpload/attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"../attachmentUpload/attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadLaneReporter,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"../attachmentUpload/attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"../state\";\nimport { reportAttachmentUploadFailure } from \"./attachmentUploadFailure\";\nimport {\n type CarriedFirstUpdate,\n ensureRemoteDocumentCarryingFirstUpdate,\n uploadCarryingFirstUpdate,\n} from \"./carriedFirstUpdate\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n let carriedFirstUpdate: CarriedFirstUpdate | undefined;\n const currentRecord = nextRecord.documentId\n ? nextRecord\n : await ensureRemoteDocumentCarryingFirstUpdate({\n currentDoc,\n encapsulationKeyPair,\n generation: attachmentGeneration,\n nextRecord,\n onCarried: (carried) => {\n carriedFirstUpdate = carried;\n },\n policyOperation,\n state,\n });\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n const step = await syncNextPendingAttachment(\n {\n attachmentGeneration,\n carriedFirstUpdate,\n encapsulationKeyPair,\n pendingAttachment,\n policyOperation,\n remoteDocumentId,\n state,\n },\n progress,\n currentDoc,\n );\n // Only the first bind may carry it; a failed one leaves the row queued.\n carriedFirstUpdate = undefined;\n if (step === \"stop\") {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await new DocumentRecordRepository(\n state.runtime.infra.execSql,\n ).clearDocumentSyncFailure({\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\n/** Settles one queued attachment; \"stop\" ends this pass early. */\nasync function syncNextPendingAttachment(\n upload: Omit<PendingAttachmentUploadInput, \"activeBindingBySlotId\">,\n progress: AttachmentSyncProgress,\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>,\n): Promise<\"continue\" | \"stop\"> {\n const { attachmentGeneration, pendingAttachment, state } = upload;\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n if (!(await loadRemoteAttachmentBindings({ ...upload, progress }))) {\n return \"stop\";\n }\n const outcome = await syncPendingAttachmentUpload({\n ...upload,\n activeBindingBySlotId: progress.activeBindingBySlotId,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return \"stop\";\n }\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") progress.uploadedAttachment = true;\n return \"continue\";\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n carriedFirstUpdate?: CarriedFirstUpdate | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: PreparedUploadDocumentAttachmentRequest[\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): PreparedUploadDocumentAttachmentRequest {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n documentSync: input.pendingUpload.carriedFirstUpdate?.request,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n warmReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer({\n operation: input.pendingUpload.policyOperation,\n }),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: PreparedUploadDocumentAttachmentRequest;\n /** Read from the runtime the base input was built from. */\n blobAttachments: BlobAttachmentService;\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId === input.pendingUpload.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadCarryingFirstUpdate({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n carried: input.pendingUpload.carriedFirstUpdate,\n committed: (attempt) => attempt.uploaded?.response.documentSync,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n upload: () =>\n uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n blobAttachments: input.blobAttachments,\n state,\n writerProjection,\n }),\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n blobAttachments: state.runtime.blobAttachments,\n pendingUpload: input,\n uploadLane,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,2BAA2B,GAC5B,MAAM,iCAAiC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,GAAG,CACpB,iFAAiF,CAClF,CAAC;QACF,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,6BAA6B,CAAC;QACnD,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,iBAAiB;QACjB,MAAM;QACN,KAAK;KACN,CAAC,CAAC;IACH,4EAA4E;IAC5E,wEAAwE;IACxE,0CAA0C;IAC1C,IACE,CAAC,oCAAoC,CAAC,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,EACxE,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,IAAI,CAAC,QAAQ;QAAE,OAAO,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAC9D,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC;IACtC,MAAM,UAAU,GAAG,kCAAkC,CAAC;QACpD,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,iBAAiB;KAClB,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,+BAA+B,CAAC;QACtD,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,MAAM;QACN,MAAM;QACN,cAAc,EAAE,QAAQ;QACxB,UAAU;KACX,CAAC,CAAC;IACH,OAAO,4BAA4B,CAAC;QAClC,eAAe;QACf,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,eAAe;QAC9C,aAAa,EAAE,KAAK;QACpB,UAAU;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n BlobAttachmentService,\n BlobByteSource,\n BlobSourceSnapshot,\n} from \"../../../../workflows/blobs\";\nimport type { PreparedUploadDocumentAttachmentRequest } from \"../../../../workflows/blobs/upload\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { markOriginatedDocuments } from \"../../../../workflows/sync/coordination\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"../attachmentUpload/attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"../attachmentUpload/attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadLaneReporter,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"../attachmentUpload/attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"../state\";\nimport { reportAttachmentUploadFailure } from \"./attachmentUploadFailure\";\nimport {\n type CarriedFirstUpdate,\n ensureRemoteDocumentCarryingFirstUpdate,\n uploadCarryingFirstUpdate,\n} from \"./carriedFirstUpdate\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n let carriedFirstUpdate: CarriedFirstUpdate | undefined;\n const currentRecord = nextRecord.documentId\n ? nextRecord\n : await ensureRemoteDocumentCarryingFirstUpdate({\n currentDoc,\n encapsulationKeyPair,\n generation: attachmentGeneration,\n nextRecord,\n onCarried: (carried) => {\n carriedFirstUpdate = carried;\n },\n policyOperation,\n state,\n });\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n const step = await syncNextPendingAttachment(\n {\n attachmentGeneration,\n carriedFirstUpdate,\n encapsulationKeyPair,\n pendingAttachment,\n policyOperation,\n remoteDocumentId,\n state,\n },\n progress,\n currentDoc,\n );\n // Only the first bind may carry it; a failed one leaves the row queued.\n carriedFirstUpdate = undefined;\n if (step === \"stop\") {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await new DocumentRecordRepository(\n state.runtime.infra.execSql,\n ).clearDocumentSyncFailure({\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\n/** Settles one queued attachment; \"stop\" ends this pass early. */\nasync function syncNextPendingAttachment(\n upload: Omit<PendingAttachmentUploadInput, \"activeBindingBySlotId\">,\n progress: AttachmentSyncProgress,\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>,\n): Promise<\"continue\" | \"stop\"> {\n const { attachmentGeneration, pendingAttachment, state } = upload;\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n if (!(await loadRemoteAttachmentBindings({ ...upload, progress }))) {\n return \"stop\";\n }\n const outcome = await syncPendingAttachmentUpload({\n ...upload,\n activeBindingBySlotId: progress.activeBindingBySlotId,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return \"stop\";\n }\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") progress.uploadedAttachment = true;\n return \"continue\";\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n carriedFirstUpdate?: CarriedFirstUpdate | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: PreparedUploadDocumentAttachmentRequest[\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): PreparedUploadDocumentAttachmentRequest {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n documentSync: input.pendingUpload.carriedFirstUpdate?.request,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n warmReferencedPrincipalPolicies:\n state.runtime.principalPolicies.createWarmer({\n operation: input.pendingUpload.policyOperation,\n }),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: PreparedUploadDocumentAttachmentRequest;\n /** Read from the runtime the base input was built from. */\n blobAttachments: BlobAttachmentService;\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId === input.pendingUpload.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadCarryingFirstUpdate({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n carried: input.pendingUpload.carriedFirstUpdate,\n committed: (attempt) => attempt.uploaded?.response.documentSync,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n upload: () =>\n uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n blobAttachments: input.blobAttachments,\n state,\n writerProjection,\n }),\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n blobAttachments: state.runtime.blobAttachments,\n pendingUpload: input,\n uploadLane,\n });\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { listDocumentLocalIdsPlacedOnlyIn } from "../../../data/persistence/cont
|
|
|
2
2
|
import { runSerializedSqlMutation } from "../../../data/sqlite/sqlExec.js";
|
|
3
3
|
import { registerClientSQLiteCommitGuard } from "../../../data/sqlite/sqliteCommitGuards.js";
|
|
4
4
|
import { defaultDocumentsPersistence, deletePersistedDocument, } from "../../documents/index.js";
|
|
5
|
-
import { OrganizationSyncPauseRepository } from "../../sync/
|
|
5
|
+
import { OrganizationSyncPauseRepository } from "../../sync/coordination.js";
|
|
6
6
|
import { carriesLocalWrites, listPendingWrites } from "../pendingWrites/index.js";
|
|
7
7
|
// The deletion cascade binds several values per container across its
|
|
8
8
|
// statements (its tombstone row alone binds a value per column), so a large
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentRemoval.js","sourceRoot":"","sources":["documentRemoval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,0EAA0E,CAAC;AAC5H,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAE1F,OAAO,EACL,2BAA2B,EAC3B,uBAAuB,GACxB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,+BAA+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,aAAa;SACzE,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { listDocumentLocalIdsPlacedOnlyIn } from \"../../../data/persistence/container-contents/exclusiveDocumentPlacements\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport { registerClientSQLiteCommitGuard } from \"../../../data/sqlite/sqliteCommitGuards\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n defaultDocumentsPersistence,\n deletePersistedDocument,\n} from \"../../documents\";\nimport { OrganizationSyncPauseRepository } from \"../../sync\";\nimport { carriesLocalWrites, listPendingWrites } from \"../pendingWrites\";\nimport type { ContainerContentsWorkflowRuntimeInfra } from \"../runtime\";\n\nexport interface OrganizationContentRemoval {\n /**\n * `removed` when every targeted container and document is gone.\n * `pending-writes` and `queued-edits` refused before deleting anything.\n * `interrupted` stopped part way: the removal stopped being current, or a\n * document was edited while it ran and stayed.\n */\n readonly status:\n | \"removed\"\n | \"pending-writes\"\n | \"queued-edits\"\n | \"interrupted\";\n readonly deletedContainerIds: readonly string[];\n readonly deletedLocalIds: readonly string[];\n}\n\n// The deletion cascade binds several values per container across its\n// statements (its tombstone row alone binds a value per column), so a large\n// organization is removed in batches that stay within SQLite's bind budget.\nconst CONTAINER_REMOVAL_BATCH_SIZE = 50;\n\nconst refused = (\n status: \"pending-writes\" | \"queued-edits\",\n): OrganizationContentRemoval => ({\n deletedContainerIds: [],\n deletedLocalIds: [],\n status,\n});\n\ninterface ContainerRemoval {\n readonly containerId: string;\n readonly reason: \"access_revoked\";\n readonly updatedAt: string;\n}\n\n/** Stops at the first batch that is no longer current. */\nasync function deleteContainersInBatches(\n lockedExecSql: ExecSql,\n containerIds: readonly string[],\n deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>,\n): Promise<string[]> {\n const removedAt = new Date().toISOString();\n const deleted: string[] = [];\n for (\n let index = 0;\n index < containerIds.length;\n index += CONTAINER_REMOVAL_BATCH_SIZE\n ) {\n const batch = containerIds.slice(\n index,\n index + CONTAINER_REMOVAL_BATCH_SIZE,\n );\n const removed = await deleteContainers(\n lockedExecSql,\n batch.map((containerId) => ({\n containerId,\n reason: \"access_revoked\",\n updatedAt: removedAt,\n })),\n );\n deleted.push(...removed);\n if (removed.length !== batch.length) break;\n }\n return deleted;\n}\n\nclass DocumentRemovalNotCurrent extends Error {}\n\n/**\n * Deletes one document unless the removal stopped being current or a store\n * queued a write for it. The check runs as a commit guard, in the same\n * synchronous slice as the COMMIT, so an edit queued while the rows were being\n * deleted rolls the deletion back. When the COMMIT-time check passes, the\n * document's store is retired in that same slice, so an open editor turns\n * read-only before the deletion commits and no later edit can be accepted and\n * lost; a COMMIT that then fails restores it.\n */\nasync function deleteDocumentUnlessEdited(input: {\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly localId: string;\n readonly organizationId: string;\n readonly restoreDocument: (localId: string) => void;\n readonly retireDocument: (localId: string) => void;\n readonly stillCurrent: () => boolean;\n}): Promise<boolean> {\n const expectedRecord = await defaultDocumentsPersistence.loadDocument(\n input.execSql,\n input.localId,\n );\n if (!expectedRecord) return false;\n // The guard runs once when registered and again right before the COMMIT;\n // only that last run retires the store.\n let guardRuns = 0;\n let retired = false;\n try {\n const deleted = await deletePersistedDocument({\n beforeDeleteInTransaction: async (transactionExecSql) => {\n await new OrganizationSyncPauseRepository(\n transactionExecSql,\n ).recordPauseRemovedDocument({\n localId: input.localId,\n organizationId: input.organizationId,\n });\n registerClientSQLiteCommitGuard(transactionExecSql, () => {\n if (!input.stillCurrent() || input.hasQueuedWrites(input.localId)) {\n throw new DocumentRemovalNotCurrent();\n }\n guardRuns += 1;\n if (guardRuns > 1) {\n retired = true;\n input.retireDocument(input.localId);\n }\n });\n },\n documentProjectors: input.documentProjectors,\n execSql: input.execSql,\n expectedRecord,\n localId: input.localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted && retired) input.restoreDocument(input.localId);\n return deleted;\n } catch (error) {\n if (retired) input.restoreDocument(input.localId);\n if (error instanceof DocumentRemovalNotCurrent) return false;\n throw error;\n }\n}\n\n/**\n * Removes a paused organization's containers and the documents placed only in\n * them, unless a persisted pending write (a queued update, a deferred tail, an\n * intent, or an attachment upload) touches the organization, those\n * containers, or those documents. The scan and every deletion hold one SQLite\n * mutation lock, so no persisted write can land between them.\n *\n * An open store may also hold edits that have not reached SQLite yet, so\n * the removal refuses while any targeted document has queued writes; they\n * persist as pending writes and upload, and a later pass removes the rest.\n * The containers go first, under `stillCurrent`; documents are deleted only\n * after every container was, each under a commit guard against an edit\n * queued meanwhile or the removal no longer applying. A document edited mid-removal stays as a detached local\n * copy, like any document whose container this device lost. Documents that\n * were already detached are never touched: they may be the only copy of work\n * a recovery still needs.\n */\n/** Deletes documents in order until the removal stops being current. */\nasync function deleteUneditedDocuments(\n input: Parameters<typeof removeOrganizationContentUnlessPending>[0],\n lockedExecSql: ExecSql,\n localIds: readonly string[],\n): Promise<string[]> {\n const deletedLocalIds: string[] = [];\n for (const localId of localIds) {\n if (!input.stillCurrent()) break;\n if (\n await deleteDocumentUnlessEdited({\n documentProjectors: input.documentProjectors,\n execSql: lockedExecSql,\n hasQueuedWrites: input.hasQueuedWrites,\n localId,\n organizationId: input.organizationId,\n restoreDocument: input.restoreDocument,\n retireDocument: input.retireDocument,\n stillCurrent: input.stillCurrent,\n })\n ) {\n deletedLocalIds.push(localId);\n }\n }\n return deletedLocalIds;\n}\n\nexport async function removeOrganizationContentUnlessPending(input: {\n readonly containerIds: readonly string[];\n readonly deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>;\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n /** Whether an open store holds writes for the document not yet in SQLite. */\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly organizationId: string;\n /** Undoes retireDocument when the deletion did not commit. */\n readonly restoreDocument: (localId: string) => void;\n /** Retires a deleted document's store; see deleteDocumentUnlessEdited. */\n readonly retireDocument: (localId: string) => void;\n /** Whether the removal still applies, e.g. the session did not switch in. */\n readonly stillCurrent: () => boolean;\n}): Promise<OrganizationContentRemoval> {\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n const containerIds = new Set(input.containerIds);\n const localIds = await listDocumentLocalIdsPlacedOnlyIn(\n lockedExecSql,\n input.containerIds,\n );\n if (containerIds.size === 0 && localIds.length === 0) {\n return {\n deletedContainerIds: [],\n deletedLocalIds: [],\n status: \"removed\",\n };\n }\n const documentIds = new Set(localIds);\n const pending = await listPendingWrites(lockedExecSql);\n if (\n pending.some(\n (item) =>\n carriesLocalWrites(item) &&\n (item.organizationId === input.organizationId ||\n (item.containerId !== null && containerIds.has(item.containerId)) ||\n documentIds.has(item.localId)),\n )\n ) {\n return refused(\"pending-writes\");\n }\n if (localIds.some(input.hasQueuedWrites)) return refused(\"queued-edits\");\n\n const deletedContainerIds = await deleteContainersInBatches(\n lockedExecSql,\n [...containerIds],\n input.deleteContainers,\n );\n if (deletedContainerIds.length !== containerIds.size) {\n return {\n deletedContainerIds,\n deletedLocalIds: [],\n status: \"interrupted\",\n };\n }\n const deletedLocalIds = await deleteUneditedDocuments(\n input,\n lockedExecSql,\n localIds,\n );\n return {\n deletedContainerIds,\n deletedLocalIds,\n status:\n deletedLocalIds.length === localIds.length ? \"removed\" : \"interrupted\",\n };\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentRemoval.js","sourceRoot":"","sources":["documentRemoval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,0EAA0E,CAAC;AAC5H,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAE1F,OAAO,EAC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,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa;SACzE,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { listDocumentLocalIdsPlacedOnlyIn } from \"../../../data/persistence/container-contents/exclusiveDocumentPlacements\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport { registerClientSQLiteCommitGuard } from \"../../../data/sqlite/sqliteCommitGuards\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n defaultDocumentsPersistence,\n deletePersistedDocument,\n} from \"../../documents\";\nimport { OrganizationSyncPauseRepository } from \"../../sync/coordination\";\nimport { carriesLocalWrites, listPendingWrites } from \"../pendingWrites\";\nimport type { ContainerContentsWorkflowRuntimeInfra } from \"../runtime\";\n\nexport interface OrganizationContentRemoval {\n /**\n * `removed` when every targeted container and document is gone.\n * `pending-writes` and `queued-edits` refused before deleting anything.\n * `interrupted` stopped part way: the removal stopped being current, or a\n * document was edited while it ran and stayed.\n */\n readonly status:\n | \"removed\"\n | \"pending-writes\"\n | \"queued-edits\"\n | \"interrupted\";\n readonly deletedContainerIds: readonly string[];\n readonly deletedLocalIds: readonly string[];\n}\n\n// The deletion cascade binds several values per container across its\n// statements (its tombstone row alone binds a value per column), so a large\n// organization is removed in batches that stay within SQLite's bind budget.\nconst CONTAINER_REMOVAL_BATCH_SIZE = 50;\n\nconst refused = (\n status: \"pending-writes\" | \"queued-edits\",\n): OrganizationContentRemoval => ({\n deletedContainerIds: [],\n deletedLocalIds: [],\n status,\n});\n\ninterface ContainerRemoval {\n readonly containerId: string;\n readonly reason: \"access_revoked\";\n readonly updatedAt: string;\n}\n\n/** Stops at the first batch that is no longer current. */\nasync function deleteContainersInBatches(\n lockedExecSql: ExecSql,\n containerIds: readonly string[],\n deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>,\n): Promise<string[]> {\n const removedAt = new Date().toISOString();\n const deleted: string[] = [];\n for (\n let index = 0;\n index < containerIds.length;\n index += CONTAINER_REMOVAL_BATCH_SIZE\n ) {\n const batch = containerIds.slice(\n index,\n index + CONTAINER_REMOVAL_BATCH_SIZE,\n );\n const removed = await deleteContainers(\n lockedExecSql,\n batch.map((containerId) => ({\n containerId,\n reason: \"access_revoked\",\n updatedAt: removedAt,\n })),\n );\n deleted.push(...removed);\n if (removed.length !== batch.length) break;\n }\n return deleted;\n}\n\nclass DocumentRemovalNotCurrent extends Error {}\n\n/**\n * Deletes one document unless the removal stopped being current or a store\n * queued a write for it. The check runs as a commit guard, in the same\n * synchronous slice as the COMMIT, so an edit queued while the rows were being\n * deleted rolls the deletion back. When the COMMIT-time check passes, the\n * document's store is retired in that same slice, so an open editor turns\n * read-only before the deletion commits and no later edit can be accepted and\n * lost; a COMMIT that then fails restores it.\n */\nasync function deleteDocumentUnlessEdited(input: {\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly localId: string;\n readonly organizationId: string;\n readonly restoreDocument: (localId: string) => void;\n readonly retireDocument: (localId: string) => void;\n readonly stillCurrent: () => boolean;\n}): Promise<boolean> {\n const expectedRecord = await defaultDocumentsPersistence.loadDocument(\n input.execSql,\n input.localId,\n );\n if (!expectedRecord) return false;\n // The guard runs once when registered and again right before the COMMIT;\n // only that last run retires the store.\n let guardRuns = 0;\n let retired = false;\n try {\n const deleted = await deletePersistedDocument({\n beforeDeleteInTransaction: async (transactionExecSql) => {\n await new OrganizationSyncPauseRepository(\n transactionExecSql,\n ).recordPauseRemovedDocument({\n localId: input.localId,\n organizationId: input.organizationId,\n });\n registerClientSQLiteCommitGuard(transactionExecSql, () => {\n if (!input.stillCurrent() || input.hasQueuedWrites(input.localId)) {\n throw new DocumentRemovalNotCurrent();\n }\n guardRuns += 1;\n if (guardRuns > 1) {\n retired = true;\n input.retireDocument(input.localId);\n }\n });\n },\n documentProjectors: input.documentProjectors,\n execSql: input.execSql,\n expectedRecord,\n localId: input.localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted && retired) input.restoreDocument(input.localId);\n return deleted;\n } catch (error) {\n if (retired) input.restoreDocument(input.localId);\n if (error instanceof DocumentRemovalNotCurrent) return false;\n throw error;\n }\n}\n\n/**\n * Removes a paused organization's containers and the documents placed only in\n * them, unless a persisted pending write (a queued update, a deferred tail, an\n * intent, or an attachment upload) touches the organization, those\n * containers, or those documents. The scan and every deletion hold one SQLite\n * mutation lock, so no persisted write can land between them.\n *\n * An open store may also hold edits that have not reached SQLite yet, so\n * the removal refuses while any targeted document has queued writes; they\n * persist as pending writes and upload, and a later pass removes the rest.\n * The containers go first, under `stillCurrent`; documents are deleted only\n * after every container was, each under a commit guard against an edit\n * queued meanwhile or the removal no longer applying. A document edited mid-removal stays as a detached local\n * copy, like any document whose container this device lost. Documents that\n * were already detached are never touched: they may be the only copy of work\n * a recovery still needs.\n */\n/** Deletes documents in order until the removal stops being current. */\nasync function deleteUneditedDocuments(\n input: Parameters<typeof removeOrganizationContentUnlessPending>[0],\n lockedExecSql: ExecSql,\n localIds: readonly string[],\n): Promise<string[]> {\n const deletedLocalIds: string[] = [];\n for (const localId of localIds) {\n if (!input.stillCurrent()) break;\n if (\n await deleteDocumentUnlessEdited({\n documentProjectors: input.documentProjectors,\n execSql: lockedExecSql,\n hasQueuedWrites: input.hasQueuedWrites,\n localId,\n organizationId: input.organizationId,\n restoreDocument: input.restoreDocument,\n retireDocument: input.retireDocument,\n stillCurrent: input.stillCurrent,\n })\n ) {\n deletedLocalIds.push(localId);\n }\n }\n return deletedLocalIds;\n}\n\nexport async function removeOrganizationContentUnlessPending(input: {\n readonly containerIds: readonly string[];\n readonly deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>;\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n /** Whether an open store holds writes for the document not yet in SQLite. */\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly organizationId: string;\n /** Undoes retireDocument when the deletion did not commit. */\n readonly restoreDocument: (localId: string) => void;\n /** Retires a deleted document's store; see deleteDocumentUnlessEdited. */\n readonly retireDocument: (localId: string) => void;\n /** Whether the removal still applies, e.g. the session did not switch in. */\n readonly stillCurrent: () => boolean;\n}): Promise<OrganizationContentRemoval> {\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n const containerIds = new Set(input.containerIds);\n const localIds = await listDocumentLocalIdsPlacedOnlyIn(\n lockedExecSql,\n input.containerIds,\n );\n if (containerIds.size === 0 && localIds.length === 0) {\n return {\n deletedContainerIds: [],\n deletedLocalIds: [],\n status: \"removed\",\n };\n }\n const documentIds = new Set(localIds);\n const pending = await listPendingWrites(lockedExecSql);\n if (\n pending.some(\n (item) =>\n carriesLocalWrites(item) &&\n (item.organizationId === input.organizationId ||\n (item.containerId !== null && containerIds.has(item.containerId)) ||\n documentIds.has(item.localId)),\n )\n ) {\n return refused(\"pending-writes\");\n }\n if (localIds.some(input.hasQueuedWrites)) return refused(\"queued-edits\");\n\n const deletedContainerIds = await deleteContainersInBatches(\n lockedExecSql,\n [...containerIds],\n input.deleteContainers,\n );\n if (deletedContainerIds.length !== containerIds.size) {\n return {\n deletedContainerIds,\n deletedLocalIds: [],\n status: \"interrupted\",\n };\n }\n const deletedLocalIds = await deleteUneditedDocuments(\n input,\n lockedExecSql,\n localIds,\n );\n return {\n deletedContainerIds,\n deletedLocalIds,\n status:\n deletedLocalIds.length === localIds.length ? \"removed\" : \"interrupted\",\n };\n });\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import type { UpdateOrganizationMembershipRequest } from "../../../internal/vali
|
|
|
3
3
|
import type { OrganizationMembershipResponse, OrganizationMembershipsResponse } from "../../../internal/validators/response/index.js";
|
|
4
4
|
import type { DomainScope } from "../../../data/shared/domainScope.js";
|
|
5
5
|
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
6
|
-
import { type OrganizationSyncPauses } from "../../sync/
|
|
6
|
+
import { type OrganizationSyncPauses } from "../../sync/coordination.js";
|
|
7
7
|
/** One organization the user belongs to, with their own choices for it. */
|
|
8
8
|
export type OrganizationMembership = OrganizationMembershipResponse;
|
|
9
9
|
export interface OrganizationMembershipApi {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getOrCreateOrganizationSyncPauses, } from "../../sync/
|
|
1
|
+
import { getOrCreateOrganizationSyncPauses, } from "../../sync/coordination.js";
|
|
2
2
|
async function forgetEveryPausedOrganization(input) {
|
|
3
3
|
let complete = true;
|
|
4
4
|
for (const organizationId of [...input.pauses.pausedOrganizationIds()]) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,iCAAiC,GAElC,MAAM,YAAY,CAAC;AA2DpB,KAAK,UAAU,6BAA6B,CAAC,KAG5C;IACC,IAAI,QAAQ,GAAG,IAAI,CAAC;IACpB,KAAK,MAAM,cAAc,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,qBAAqB,EAAE,CAAC,EAAE,CAAC;QACvE,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,yBAAyB,CAAC,cAAc,CAAC,CAAC,EAAE,CAAC;YAClE,QAAQ,GAAG,KAAK,CAAC;QACnB,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAGrD;IACC,IAAI,MAAM,6BAA6B,CAAC,KAAK,CAAC;QAAE,OAAO;IACvD,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,GAAG,EAAE,CACpC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG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AI,GAAG,CAAC,MAAM,CAAC,qBAAqB,EAAE,CAAC,CAAC;IACrD,IAAI,MAAM;QAAE,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;;QAChC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;IACjC,MAAM,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC1C,IAAI,MAAM;QAAE,MAAM,+BAA+B,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;;QAC/D,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;IACjC,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AACxD,CAAC","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { UpdateOrganizationMembershipRequest } from \"@tearleads/validators/request\";\nimport type {\n OrganizationMembershipResponse,\n OrganizationMembershipsResponse,\n} from \"@tearleads/validators/response\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n getOrCreateOrganizationSyncPauses,\n type OrganizationSyncPauses,\n} from \"../../sync\";\n\n/** One organization the user belongs to, with their own choices for it. */\nexport type OrganizationMembership = OrganizationMembershipResponse;\n\nexport interface OrganizationMembershipApi {\n listOrganizationMemberships(): Promise<OrganizationMembershipsResponse | null>;\n updateOrganizationMembership(\n organizationId: string,\n input: UpdateOrganizationMembershipRequest,\n ): Promise<RequestResult<OrganizationMembershipResponse>>;\n}\n\n/**\n * What applying a pause needs from the device's content. Wired by the\n * composition root to the container tree and the document sync lanes.\n */\nexport interface OrganizationContentHost {\n /**\n * Removes an organization's content, keeping its metadata root. Refuses,\n * returning false, while any of its writes is unsynced or still queued in\n * an open store.\n */\n forgetOrganizationContent(organizationId: string): Promise<boolean>;\n /** Whether any local write for the organization has not uploaded yet. */\n hasUnsyncedOrganizationWrites(organizationId: string): Promise<boolean>;\n /** Asks every sync lane to upload now and waits briefly for them to idle. */\n flushWrites(): Promise<void>;\n /** Re-lists the whole tree so resumed organizations download again. */\n refetchContent(): Promise<void>;\n /**\n * Runs `retry` each time the scope's sync lanes go idle until it resolves\n * true. A later call replaces the pending retry.\n */\n retryWhenWritesSettle(retry: () => Promise<boolean>): void;\n}\n\ninterface OrganizationMembershipInput {\n readonly apiClient: OrganizationMembershipApi;\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly host: OrganizationContentHost;\n /**\n * Whether the session still uses `domainScope`. A membership list or pause\n * that completes after an identity switch must not touch the new identity's\n * device state.\n */\n readonly isCurrent: () => boolean;\n}\n\nexport type OrganizationSyncPauseResult =\n | { readonly status: \"updated\"; readonly membership: OrganizationMembership }\n | { readonly status: \"unsynced-writes\" }\n | {\n readonly status: \"failed\";\n readonly httpStatus: number | null;\n readonly message: string;\n };\n\nasync function forgetEveryPausedOrganization(input: {\n readonly host: OrganizationContentHost;\n readonly pauses: OrganizationSyncPauses;\n}): Promise<boolean> {\n let complete = true;\n for (const organizationId of [...input.pauses.pausedOrganizationIds()]) {\n if (!(await input.host.forgetOrganizationContent(organizationId))) {\n complete = false;\n }\n }\n return complete;\n}\n\n/**\n * Removes the content of every paused organization that has nothing left to\n * upload. An organization with pending or queued writes keeps syncing those\n * out and is retried once the sync lanes go idle, so pausing never discards\n * unsynced work and a removal does not wait for the next membership read.\n */\nexport async function forgetPausedOrganizationContent(input: {\n readonly host: OrganizationContentHost;\n readonly pauses: OrganizationSyncPauses;\n}): Promise<void> {\n if (await forgetEveryPausedOrganization(input)) return;\n input.host.retryWhenWritesSettle(() =>\n input.pauses.runExclusive(() => forgetEveryPausedOrganization(input)),\n );\n}\n\n/**\n * Reads the user's memberships and applies their pause choices, including\n * ones made on another device: paused organizations leave this device, and\n * resumed ones download again. Returns null when the list is unavailable, in\n * which case the persisted pauses stay in force.\n */\nexport async function refreshOrganizationMemberships(\n input: OrganizationMembershipInput,\n): Promise<OrganizationMembership[] | null> {\n const pauses = getOrCreateOrganizationSyncPauses(input.domainScope);\n return pauses.runExclusive(() => applyMembershipList(input, pauses));\n}\n\nasync function applyMembershipList(\n input: OrganizationMembershipInput,\n pauses: OrganizationSyncPauses,\n): Promise<OrganizationMembership[] | null> {\n const response = await input.apiClient.listOrganizationMemberships();\n if (!response || !input.isCurrent()) return null;\n const change = await pauses.replace(\n input.execSql,\n response.memberships.flatMap((membership) =>\n membership.syncPaused ? [membership.organizationId] : [],\n ),\n );\n await forgetPausedOrganizationContent({ host: input.host, pauses });\n if (change.resumed.length > 0) await input.host.refetchContent();\n return [...response.memberships];\n}\n\n/**\n * Pauses or resumes one organization for every device of this user. Pausing\n * first uploads this device's pending writes and is refused while any remain,\n * so the local copy it removes holds nothing the server lacks.\n */\nexport async function setOrganizationSyncPaused(\n input: OrganizationMembershipInput & {\n readonly organizationId: string;\n readonly paused: boolean;\n },\n): Promise<OrganizationSyncPauseResult> {\n const pauses = getOrCreateOrganizationSyncPauses(input.domainScope);\n return pauses.runExclusive(() => applySyncPauseChoice(input, pauses));\n}\n\nasync function applySyncPauseChoice(\n input: OrganizationMembershipInput & {\n readonly organizationId: string;\n readonly paused: boolean;\n },\n pauses: OrganizationSyncPauses,\n): Promise<OrganizationSyncPauseResult> {\n const { host, organizationId, paused } = input;\n const scopeEnded = {\n httpStatus: null,\n message: \"The session changed before sync could be changed.\",\n status: \"failed\",\n } as const;\n // Queued behind other membership work, the session may have switched\n // identity; the shared API client would then act for the new identity.\n if (!input.isCurrent()) return scopeEnded;\n if (paused) {\n await host.flushWrites();\n if (await host.hasUnsyncedOrganizationWrites(organizationId)) {\n return { status: \"unsynced-writes\" };\n }\n }\n if (!input.isCurrent()) return scopeEnded;\n const result = await input.apiClient.updateOrganizationMembership(\n organizationId,\n { syncPaused: paused },\n );\n if (!result.ok) {\n return {\n httpStatus: result.status,\n message: result.message,\n status: \"failed\",\n };\n }\n // The choice is recorded; a scope that ended meanwhile applies it on its\n // next membership read instead.\n if (!input.isCurrent()) return { membership: result.data, status: \"updated\" };\n await pauses.load(input.execSql);\n const next = new Set(pauses.pausedOrganizationIds());\n if (paused) next.add(organizationId);\n else next.delete(organizationId);\n await pauses.replace(input.execSql, next);\n if (paused) await forgetPausedOrganizationContent({ host, pauses });\n else await host.refetchContent();\n return { membership: result.data, status: \"updated\" };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,iCAAiC,GAElC,MAAM,yBAAyB,CAAC;AA2DjC,KAAK,UAAU,6BAA6B,CAAC,KAG5C;IACC,IAAI,QAAQ,GAAG,IAAI,CAAC;IACpB,KAAK,MAAM,cAAc,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,qBAAqB,EAAE,CAAC,EAAE,CAAC;QACvE,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,yBAAyB,CAAC,cAAc,CAAC,CAAC,EAAE,CAAC;YAClE,QAAQ,GAAG,KAAK,CAAC;QACnB,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAGrD;IACC,IAAI,MAAM,6BAA6B,CAAC,KAAK,CAAC;QAAE,OAAO;IACvD,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,GAAG,EAAE,CACpC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC,6BAA6B,CAAC,KAAK,CAAC,CAAC,CACtE,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,KAAkC;IAElC,MAAM,MAAM,GAAG,iCAAiC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACpE,OAAO,MAAM,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC,mBAAmB,CAAC,K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AAM,+BAA+B,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;;QAC/D,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;IACjC,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AACxD,CAAC","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { UpdateOrganizationMembershipRequest } from \"@tearleads/validators/request\";\nimport type {\n OrganizationMembershipResponse,\n OrganizationMembershipsResponse,\n} from \"@tearleads/validators/response\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n getOrCreateOrganizationSyncPauses,\n type OrganizationSyncPauses,\n} from \"../../sync/coordination\";\n\n/** One organization the user belongs to, with their own choices for it. */\nexport type OrganizationMembership = OrganizationMembershipResponse;\n\nexport interface OrganizationMembershipApi {\n listOrganizationMemberships(): Promise<OrganizationMembershipsResponse | null>;\n updateOrganizationMembership(\n organizationId: string,\n input: UpdateOrganizationMembershipRequest,\n ): Promise<RequestResult<OrganizationMembershipResponse>>;\n}\n\n/**\n * What applying a pause needs from the device's content. Wired by the\n * composition root to the container tree and the document sync lanes.\n */\nexport interface OrganizationContentHost {\n /**\n * Removes an organization's content, keeping its metadata root. Refuses,\n * returning false, while any of its writes is unsynced or still queued in\n * an open store.\n */\n forgetOrganizationContent(organizationId: string): Promise<boolean>;\n /** Whether any local write for the organization has not uploaded yet. */\n hasUnsyncedOrganizationWrites(organizationId: string): Promise<boolean>;\n /** Asks every sync lane to upload now and waits briefly for them to idle. */\n flushWrites(): Promise<void>;\n /** Re-lists the whole tree so resumed organizations download again. */\n refetchContent(): Promise<void>;\n /**\n * Runs `retry` each time the scope's sync lanes go idle until it resolves\n * true. A later call replaces the pending retry.\n */\n retryWhenWritesSettle(retry: () => Promise<boolean>): void;\n}\n\ninterface OrganizationMembershipInput {\n readonly apiClient: OrganizationMembershipApi;\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly host: OrganizationContentHost;\n /**\n * Whether the session still uses `domainScope`. A membership list or pause\n * that completes after an identity switch must not touch the new identity's\n * device state.\n */\n readonly isCurrent: () => boolean;\n}\n\nexport type OrganizationSyncPauseResult =\n | { readonly status: \"updated\"; readonly membership: OrganizationMembership }\n | { readonly status: \"unsynced-writes\" }\n | {\n readonly status: \"failed\";\n readonly httpStatus: number | null;\n readonly message: string;\n };\n\nasync function forgetEveryPausedOrganization(input: {\n readonly host: OrganizationContentHost;\n readonly pauses: OrganizationSyncPauses;\n}): Promise<boolean> {\n let complete = true;\n for (const organizationId of [...input.pauses.pausedOrganizationIds()]) {\n if (!(await input.host.forgetOrganizationContent(organizationId))) {\n complete = false;\n }\n }\n return complete;\n}\n\n/**\n * Removes the content of every paused organization that has nothing left to\n * upload. An organization with pending or queued writes keeps syncing those\n * out and is retried once the sync lanes go idle, so pausing never discards\n * unsynced work and a removal does not wait for the next membership read.\n */\nexport async function forgetPausedOrganizationContent(input: {\n readonly host: OrganizationContentHost;\n readonly pauses: OrganizationSyncPauses;\n}): Promise<void> {\n if (await forgetEveryPausedOrganization(input)) return;\n input.host.retryWhenWritesSettle(() =>\n input.pauses.runExclusive(() => forgetEveryPausedOrganization(input)),\n );\n}\n\n/**\n * Reads the user's memberships and applies their pause choices, including\n * ones made on another device: paused organizations leave this device, and\n * resumed ones download again. Returns null when the list is unavailable, in\n * which case the persisted pauses stay in force.\n */\nexport async function refreshOrganizationMemberships(\n input: OrganizationMembershipInput,\n): Promise<OrganizationMembership[] | null> {\n const pauses = getOrCreateOrganizationSyncPauses(input.domainScope);\n return pauses.runExclusive(() => applyMembershipList(input, pauses));\n}\n\nasync function applyMembershipList(\n input: OrganizationMembershipInput,\n pauses: OrganizationSyncPauses,\n): Promise<OrganizationMembership[] | null> {\n const response = await input.apiClient.listOrganizationMemberships();\n if (!response || !input.isCurrent()) return null;\n const change = await pauses.replace(\n input.execSql,\n response.memberships.flatMap((membership) =>\n membership.syncPaused ? [membership.organizationId] : [],\n ),\n );\n await forgetPausedOrganizationContent({ host: input.host, pauses });\n if (change.resumed.length > 0) await input.host.refetchContent();\n return [...response.memberships];\n}\n\n/**\n * Pauses or resumes one organization for every device of this user. Pausing\n * first uploads this device's pending writes and is refused while any remain,\n * so the local copy it removes holds nothing the server lacks.\n */\nexport async function setOrganizationSyncPaused(\n input: OrganizationMembershipInput & {\n readonly organizationId: string;\n readonly paused: boolean;\n },\n): Promise<OrganizationSyncPauseResult> {\n const pauses = getOrCreateOrganizationSyncPauses(input.domainScope);\n return pauses.runExclusive(() => applySyncPauseChoice(input, pauses));\n}\n\nasync function applySyncPauseChoice(\n input: OrganizationMembershipInput & {\n readonly organizationId: string;\n readonly paused: boolean;\n },\n pauses: OrganizationSyncPauses,\n): Promise<OrganizationSyncPauseResult> {\n const { host, organizationId, paused } = input;\n const scopeEnded = {\n httpStatus: null,\n message: \"The session changed before sync could be changed.\",\n status: \"failed\",\n } as const;\n // Queued behind other membership work, the session may have switched\n // identity; the shared API client would then act for the new identity.\n if (!input.isCurrent()) return scopeEnded;\n if (paused) {\n await host.flushWrites();\n if (await host.hasUnsyncedOrganizationWrites(organizationId)) {\n return { status: \"unsynced-writes\" };\n }\n }\n if (!input.isCurrent()) return scopeEnded;\n const result = await input.apiClient.updateOrganizationMembership(\n organizationId,\n { syncPaused: paused },\n );\n if (!result.ok) {\n return {\n httpStatus: result.status,\n message: result.message,\n status: \"failed\",\n };\n }\n // The choice is recorded; a scope that ended meanwhile applies it on its\n // next membership read instead.\n if (!input.isCurrent()) return { membership: result.data, status: \"updated\" };\n await pauses.load(input.execSql);\n const next = new Set(pauses.pausedOrganizationIds());\n if (paused) next.add(organizationId);\n else next.delete(organizationId);\n await pauses.replace(input.execSql, next);\n if (paused) await forgetPausedOrganizationContent({ host, pauses });\n else await host.refetchContent();\n return { membership: result.data, status: \"updated\" };\n}\n"]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { createDomainScope, type DomainScope, } from "../../data/shared/domainScope.js";
|
|
2
|
+
export { getRuntimePeerSeed } from "../../data/sync/crdtPeerSeed.js";
|
|
3
|
+
export { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, type OrganizationSyncPauseChange, OrganizationSyncPauseRepository, type OrganizationSyncPauseSubject, type OrganizationSyncPauses, } from "../../data/sync/organizationSyncPauses.js";
|
|
4
|
+
export { markOriginatedDocuments } from "../../data/sync/originatedDocuments.js";
|
|
5
|
+
export type { DomainSyncCoordinator, DomainSyncSnapshot, SyncIdleOptions, SyncLane, SyncLaneConfig, SyncLaneLastAction, SyncLanePhase, SyncLaneProgress, SyncLaneSnapshot, SyncLaneStatus, UploadSyncLane, UploadSyncLaneOptions, } from "../../data/sync/syncCoordinator.js";
|
|
6
|
+
export { beginDomainSyncUploadLane, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../data/sync/syncCoordinator.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { createDomainScope, } from "../../data/shared/domainScope.js";
|
|
2
|
+
export { getRuntimePeerSeed } from "../../data/sync/crdtPeerSeed.js";
|
|
3
|
+
export { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, OrganizationSyncPauseRepository, } from "../../data/sync/organizationSyncPauses.js";
|
|
4
|
+
export { markOriginatedDocuments } from "../../data/sync/originatedDocuments.js";
|
|
5
|
+
export { beginDomainSyncUploadLane, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../data/sync/syncCoordinator.js";
|
|
6
|
+
//# sourceMappingURL=coordination.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coordination.js","sourceRoot":"","sources":["coordination.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,GAElB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EACL,iCAAiC,EACjC,yBAAyB,EAEzB,+BAA+B,GAGhC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAe9E,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,iCAAiC,CAAC","sourcesContent":["export {\n createDomainScope,\n type DomainScope,\n} from \"../../data/shared/domainScope\";\nexport { getRuntimePeerSeed } from \"../../data/sync/crdtPeerSeed\";\nexport {\n getOrCreateOrganizationSyncPauses,\n isRetainedWhileSyncPaused,\n type OrganizationSyncPauseChange,\n OrganizationSyncPauseRepository,\n type OrganizationSyncPauseSubject,\n type OrganizationSyncPauses,\n} from \"../../data/sync/organizationSyncPauses\";\nexport { markOriginatedDocuments } from \"../../data/sync/originatedDocuments\";\nexport type {\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n UploadSyncLane,\n UploadSyncLaneOptions,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n beginDomainSyncUploadLane,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../data/sync/syncCoordinator\";\n"]}
|
|
@@ -1,7 +1,2 @@
|
|
|
1
|
-
export { createDomainScope, type DomainScope, } from "
|
|
2
|
-
export { getRuntimePeerSeed } from "../../data/sync/crdtPeerSeed.js";
|
|
3
|
-
export { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, type OrganizationSyncPauseChange, OrganizationSyncPauseRepository, type OrganizationSyncPauseSubject, type OrganizationSyncPauses, } from "../../data/sync/organizationSyncPauses.js";
|
|
4
|
-
export { markOriginatedDocuments } from "../../data/sync/originatedDocuments.js";
|
|
5
|
-
export type { DomainSyncCoordinator, DomainSyncSnapshot, SyncIdleOptions, SyncLane, SyncLaneConfig, SyncLaneLastAction, SyncLanePhase, SyncLaneProgress, SyncLaneSnapshot, SyncLaneStatus, UploadSyncLane, UploadSyncLaneOptions, } from "../../data/sync/syncCoordinator.js";
|
|
6
|
-
export { beginDomainSyncUploadLane, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../data/sync/syncCoordinator.js";
|
|
1
|
+
export { beginDomainSyncUploadLane, createDomainScope, type DomainScope, type DomainSyncCoordinator, type DomainSyncSnapshot, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, getOrCreateOrganizationSyncPauses, getRuntimePeerSeed, hasDomainSyncCoordinatorPendingWork, isRetainedWhileSyncPaused, markOriginatedDocuments, type OrganizationSyncPauseChange, OrganizationSyncPauseRepository, type OrganizationSyncPauseSubject, type OrganizationSyncPauses, requestAllDomainSyncLanes, type SyncIdleOptions, type SyncLane, type SyncLaneConfig, type SyncLaneLastAction, type SyncLanePhase, type SyncLaneProgress, type SyncLaneSnapshot, type SyncLaneStatus, subscribeToDomainSyncCoordinator, type UploadSyncLane, type UploadSyncLaneOptions, waitForDomainSyncCoordinatorToSettle, } from "./coordination.js";
|
|
7
2
|
export { type ClearRemoteSyncStateResult, clearRemoteSyncState, type RemoteResetInput, type RemoteResetReplacement, } from "./remoteReset.js";
|
package/workflows/sync/index.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
export { createDomainScope, } from "
|
|
2
|
-
export { getRuntimePeerSeed } from "../../data/sync/crdtPeerSeed.js";
|
|
3
|
-
export { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, OrganizationSyncPauseRepository, } from "../../data/sync/organizationSyncPauses.js";
|
|
4
|
-
export { markOriginatedDocuments } from "../../data/sync/originatedDocuments.js";
|
|
5
|
-
export { beginDomainSyncUploadLane, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../data/sync/syncCoordinator.js";
|
|
1
|
+
export { beginDomainSyncUploadLane, createDomainScope, getDomainSyncCoordinatorSnapshot, getOrCreateDomainSyncCoordinator, getOrCreateOrganizationSyncPauses, getRuntimePeerSeed, hasDomainSyncCoordinatorPendingWork, isRetainedWhileSyncPaused, markOriginatedDocuments, OrganizationSyncPauseRepository, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "./coordination.js";
|
|
6
2
|
export { clearRemoteSyncState, } from "./remoteReset.js";
|
|
7
3
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EAIjB,gCAAgC,EAChC,gCAAgC,EAChC,iCAAiC,EACjC,kBAAkB,EAClB,mCAAmC,EACnC,yBAAyB,EACzB,uBAAuB,EAEvB,+BAA+B,EAG/B,yBAAyB,EASzB,gCAAgC,EAGhC,oCAAoC,GACrC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEL,oBAAoB,GAGrB,MAAM,eAAe,CAAC","sourcesContent":["export {\n beginDomainSyncUploadLane,\n createDomainScope,\n type DomainScope,\n type DomainSyncCoordinator,\n type DomainSyncSnapshot,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n getOrCreateOrganizationSyncPauses,\n getRuntimePeerSeed,\n hasDomainSyncCoordinatorPendingWork,\n isRetainedWhileSyncPaused,\n markOriginatedDocuments,\n type OrganizationSyncPauseChange,\n OrganizationSyncPauseRepository,\n type OrganizationSyncPauseSubject,\n type OrganizationSyncPauses,\n requestAllDomainSyncLanes,\n type SyncIdleOptions,\n type SyncLane,\n type SyncLaneConfig,\n type SyncLaneLastAction,\n type SyncLanePhase,\n type SyncLaneProgress,\n type SyncLaneSnapshot,\n type SyncLaneStatus,\n subscribeToDomainSyncCoordinator,\n type UploadSyncLane,\n type UploadSyncLaneOptions,\n waitForDomainSyncCoordinatorToSettle,\n} from \"./coordination\";\nexport {\n type ClearRemoteSyncStateResult,\n clearRemoteSyncState,\n type RemoteResetInput,\n type RemoteResetReplacement,\n} from \"./remoteReset\";\n"]}
|