@tearleads/client-sdk 0.1.87 → 0.1.89
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/Tearleads.js +1 -1
- package/Tearleads.js.map +1 -1
- package/client/containerContents/documentDiscovery.js +16 -2
- package/client/containerContents/documentDiscovery.js.map +1 -1
- package/client/containerContents/index.d.ts +1 -1
- package/client/containerContents/index.js +1 -0
- package/client/containerContents/index.js.map +1 -1
- package/client/index.d.ts +1 -1
- package/client/index.js.map +1 -1
- package/client/organizations/index.d.ts +4 -2
- package/client/organizations/index.js +15 -8
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationMemberships.d.ts +41 -0
- package/client/organizations/organizationMemberships.js +166 -0
- package/client/organizations/organizationMemberships.js.map +1 -0
- package/client/organizations/organizationReadModels.d.ts +7 -1
- package/client/organizations/organizationReadModels.js +15 -6
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationsTypes.d.ts +3 -0
- package/client/organizations/organizationsTypes.js.map +1 -1
- package/data/persistence/container-contents/containerStructuralRepair.js +19 -14
- package/data/persistence/container-contents/containerStructuralRepair.js.map +1 -1
- package/data/persistence/container-contents/exclusiveDocumentPlacements.js +60 -0
- package/data/persistence/container-contents/exclusiveDocumentPlacements.js.map +1 -0
- package/data/persistence/organizations/organizationReadModelPersistence.js +14 -0
- package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelProjection.js +12 -0
- package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
- package/data/sqlite/schema/index.d.ts +90 -0
- package/data/sqlite/schema/index.js +3 -0
- package/data/sqlite/schema/index.js.map +1 -1
- package/data/sqlite/schema/organizationReadModelSchema.js +2 -0
- package/data/sqlite/schema/organizationReadModelSchema.js.map +1 -1
- package/data/sqlite/schema/organizationReadModelTableRegistry.d.ts +19 -0
- package/data/sqlite/schema/organizationSyncPauseSchema.js +32 -0
- package/data/sqlite/schema/organizationSyncPauseSchema.js.map +1 -0
- package/data/sync/organizationSyncPauses.d.ts +59 -0
- package/data/sync/organizationSyncPauses.js +149 -0
- package/data/sync/organizationSyncPauses.js.map +1 -0
- package/index.d.ts +2 -2
- package/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +21 -2
- package/internal/api-client/ApiClient.js +15 -1
- package/internal/api-client/ApiClient.js.map +1 -1
- package/internal/api-client/routes/organizations/memberships.js +36 -0
- package/internal/api-client/routes/organizations/memberships.js.map +1 -0
- package/internal/crypto/index.d.ts +1 -0
- package/internal/crypto/index.js +1 -0
- package/internal/crypto/index.js.map +1 -1
- package/internal/crypto/organizationLeaveRequest.d.ts +13 -0
- package/internal/crypto/organizationLeaveRequest.js +39 -0
- package/internal/crypto/organizationLeaveRequest.js.map +1 -0
- package/internal/validators/operation/index.d.ts +1 -0
- package/internal/validators/operation/index.js +1 -0
- package/internal/validators/operation/index.js.map +1 -1
- package/internal/validators/operation/organizationMemberships.d.ts +503 -0
- package/internal/validators/operation/organizationMemberships.js +93 -0
- package/internal/validators/operation/organizationMemberships.js.map +1 -0
- package/internal/validators/operation/organizations.d.ts +48 -0
- package/internal/validators/operation/registry.d.ts +5 -0
- package/internal/validators/operation/registry.js +5 -0
- package/internal/validators/operation/registry.js.map +1 -1
- package/internal/validators/realtime/index.js +1 -1
- package/internal/validators/realtime/index.js.map +1 -1
- package/internal/validators/realtime/wsInvalidationHints.js +8 -0
- package/internal/validators/realtime/wsInvalidationHints.js.map +1 -1
- package/internal/validators/request/index.d.ts +1 -1
- package/internal/validators/request/index.js +1 -1
- package/internal/validators/request/index.js.map +1 -1
- package/internal/validators/request/organization.d.ts +6 -0
- package/internal/validators/request/organization.js +7 -0
- package/internal/validators/request/organization.js.map +1 -1
- package/internal/validators/response/index.d.ts +1 -0
- package/internal/validators/response/index.js +1 -0
- package/internal/validators/response/index.js.map +1 -1
- package/internal/validators/response/organization.d.ts +82 -0
- package/internal/validators/response/organization.js +6 -0
- package/internal/validators/response/organization.js.map +1 -1
- package/internal/validators/response/organizationMembership.d.ts +66 -0
- package/internal/validators/response/organizationMembership.js +29 -0
- package/internal/validators/response/organizationMembership.js.map +1 -0
- package/internal/validators/response/organizationReadModel.d.ts +60 -0
- package/internal/validators/util/index.d.ts +1 -0
- package/internal/validators/util/index.js +1 -0
- package/internal/validators/util/index.js.map +1 -1
- package/internal/validators/util/organizationLeaveRequest.d.ts +15 -0
- package/internal/validators/util/organizationLeaveRequest.js +22 -0
- package/internal/validators/util/organizationLeaveRequest.js.map +1 -0
- package/package.json +1 -1
- package/stores/container-contents/containerContentsStore.d.ts +1 -1
- package/stores/container-contents/containerContentsStore.js +2 -0
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/operations/forgetOrganizationContentOperation.js +76 -0
- package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +1 -0
- package/stores/container-contents/types.d.ts +6 -0
- package/stores/container-contents/types.js.map +1 -1
- package/stores/documents/documentStore/attachments/attachmentRemoval.js +3 -4
- package/stores/documents/documentStore/attachments/attachmentRemoval.js.map +1 -1
- package/stores/documents/documentStore/attachments/index.js +5 -7
- package/stores/documents/documentStore/attachments/index.js.map +1 -1
- package/stores/documents/documentStore/index.js +16 -12
- package/stores/documents/documentStore/index.js.map +1 -1
- package/stores/documents/documentStore/initialization/index.js +9 -0
- package/stores/documents/documentStore/initialization/index.js.map +1 -1
- package/stores/documents/documentStore/mutations.js +5 -7
- package/stores/documents/documentStore/mutations.js.map +1 -1
- package/stores/documents/documentStore/rotation/index.js +2 -1
- package/stores/documents/documentStore/rotation/index.js.map +1 -1
- package/stores/documents/documentStore/rows/index.js +3 -4
- package/stores/documents/documentStore/rows/index.js.map +1 -1
- package/stores/documents/documentStore/state.js +18 -0
- package/stores/documents/documentStore/state.js.map +1 -1
- package/stores/documents/documentStore/sync/index.js +5 -2
- package/stores/documents/documentStore/sync/index.js.map +1 -1
- package/stores/documents/registry.d.ts +32 -0
- package/stores/documents/registry.js +79 -4
- package/stores/documents/registry.js.map +1 -1
- package/stores/documents/removedDocumentStore.js +38 -0
- package/stores/documents/removedDocumentStore.js.map +1 -0
- package/stores/documents/types.d.ts +2 -0
- package/stores/documents/types.js.map +1 -1
- package/sync/reconciliation/service.js +2 -2
- package/sync/reconciliation/service.js.map +1 -1
- package/sync/reconciliation/serviceTypes.d.ts +8 -1
- package/sync/reconciliation/serviceTypes.js.map +1 -1
- package/workflows/container-contents/pendingWrites/index.d.ts +5 -0
- package/workflows/container-contents/pendingWrites/index.js +7 -0
- package/workflows/container-contents/pendingWrites/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/index.js +7 -1
- package/workflows/container-contents/remoteHydration/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js +13 -0
- package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js.map +1 -0
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +13 -2
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
- package/workflows/container-contents/syncPause/discoveryGuard.js +31 -0
- package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -0
- package/workflows/container-contents/syncPause/documentRemoval.js +154 -0
- package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -0
- package/workflows/organizations/index.d.ts +3 -0
- package/workflows/organizations/index.js +3 -0
- package/workflows/organizations/index.js.map +1 -1
- package/workflows/organizations/memberships/leaveRequest.d.ts +31 -0
- package/workflows/organizations/memberships/leaveRequest.js +20 -0
- package/workflows/organizations/memberships/leaveRequest.js.map +1 -0
- package/workflows/organizations/memberships/leaveRequestVerification.d.ts +15 -0
- package/workflows/organizations/memberships/leaveRequestVerification.js +46 -0
- package/workflows/organizations/memberships/leaveRequestVerification.js.map +1 -0
- package/workflows/organizations/memberships/organizationMemberships.d.ts +84 -0
- package/workflows/organizations/memberships/organizationMemberships.js +95 -0
- package/workflows/organizations/memberships/organizationMemberships.js.map +1 -0
- package/workflows/sync/index.d.ts +1 -0
- package/workflows/sync/index.js +1 -0
- package/workflows/sync/index.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","sourceRoot":"","sources":["registry.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,EAC9B,uCAAuC,GACxC,MAAM,gCAAgC,CAAC;AAexC,MAAM,8BAA8B,GAAG,IAAI,OAAO,EAG/C,CAAC;AAGJ,mEAAmE;AACnE,qEAAqE;AACrE,wEAAwE;AACxE,SAAS,4BAA4B;IAGnC,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAA8B,CAAC;IAEnE,OAAO;QACL,IAAI,EAAE,CAAC,WAAwB,EAAE,GAAG,IAA0B,EAAQ,EAAE;YACtE,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;YACpD,IAAI,CAAC,SAAS,EAAE,CAAC;gBACf,OAAO;YACT,CAAC;YAED,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;gBACjC,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QACD,SAAS,EAAE,CAAC,WAAwB,EAAE,QAAkB,EAAgB,EAAE;YACxE,MAAM,SAAS,GACb,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,IAAI,GAAG,EAAY,CAAC;YAC3D,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,gBAAgB,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;YAE7C,OAAO,GAAG,EAAE;gBACV,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAC3B,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;oBACzB,gBAAgB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;gBACvC,CAAC;YACH,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ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M,EAAE,CAAC,KAAK,EAAE,gBAAgB,EAAE,EAAE,CACjE,uCAAuC,CACrC,WAAW,EACX,KAAK,EACL,gBAAgB,CACjB,CACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,qBAAqB,CACnC,WAAwB,EACxB,iBAA2D,EAC3D,gBAAgB,GAAG,KAAK;IAExB,0BAA0B,CAAC,IAAI,CAAC,WAAW,EAAE,iBAAiB,EAAE;QAC9D,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,WAAwB,EACxB,QAAmC;IAEnC,OAAO,0BAA0B,CAAC,SAAS,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,WAAwB,EACxB,OAAe;IAEf,kCAAkC,CAAC,IAAI,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,qCAAqC,CACnD,WAAwB,EACxB,QAA2C;IAE3C,OAAO,kCAAkC,CAAC,SAAS,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC;AAC7E,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,WAAwB;IAChE,MAAM,QAAQ,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACjE,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO;IACT,CAAC;IAED,KAAK,MAAM,KAAK,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QAC3D,KAAK,CAAC,WAAW,EAAE,CAAC;IACtB,CAAC;AACH,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n registerInternalDocumentRelink,\n relinkDocumentStoreWithCommitSideEffect,\n} from \"./documentStore/internalRelink\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"./types\";\n\ninterface DocumentStoreRegistry {\n storeKeysByDocumentId: Map<string, string>;\n storeKeysByLocalId: Map<string, string>;\n storesByKey: Map<string, DocumentStoreFacade>;\n}\n\nconst documentStoreRegistriesByScope = new WeakMap<\n DomainScope,\n DocumentStoreRegistry\n>();\ntype PersistedDocumentDeletionListener = (localId: string) => void;\n\n// Per-scope listener plumbing shared by the persisted-document and\n// persisted-document-deletion channels: emit fans out to the scope's\n// listeners, and unsubscribing the last listener drops the scope entry.\nfunction createScopedListenerRegistry<\n Listener extends (...args: never[]) => void,\n>() {\n const listenersByScope = new WeakMap<DomainScope, Set<Listener>>();\n\n return {\n emit: (domainScope: DomainScope, ...args: Parameters<Listener>): void => {\n const listeners = listenersByScope.get(domainScope);\n if (!listeners) {\n return;\n }\n\n for (const listener of listeners) {\n listener(...args);\n }\n },\n subscribe: (domainScope: DomainScope, listener: Listener): (() => void) => {\n const listeners =\n listenersByScope.get(domainScope) ?? new Set<Listener>();\n listeners.add(listener);\n listenersByScope.set(domainScope, listeners);\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n listenersByScope.delete(domainScope);\n }\n };\n },\n };\n}\n\nconst persistedDocumentListeners =\n createScopedListenerRegistry<PersistedDocumentListener>();\nconst persistedDocumentDeletionListeners =\n createScopedListenerRegistry<PersistedDocumentDeletionListener>();\n\nexport function getOrCreateDocumentStoreRegistry(\n domainScope: DomainScope,\n): DocumentStoreRegistry {\n const existingRegistry = documentStoreRegistriesByScope.get(domainScope);\n if (existingRegistry) {\n return existingRegistry;\n }\n\n const nextRegistry: DocumentStoreRegistry = {\n storeKeysByDocumentId: new Map(),\n storeKeysByLocalId: new Map(),\n storesByKey: new Map(),\n };\n documentStoreRegistriesByScope.set(domainScope, nextRegistry);\n return nextRegistry;\n}\n\nexport function resolveDocumentStoreKey(\n registry: DocumentStoreRegistry,\n localId: string,\n documentId: string | null,\n): string {\n return (\n (documentId ? registry.storeKeysByDocumentId.get(documentId) : undefined) ??\n registry.storeKeysByLocalId.get(localId) ??\n localId\n );\n}\n\nexport function registerDocumentStore(\n domainScope: DomainScope,\n localId: string,\n store: DocumentStoreFacade,\n documentId: string | null,\n) {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n registry.storeKeysByLocalId.set(localId, storeKey);\n if (documentId) {\n registry.storeKeysByDocumentId.set(documentId, storeKey);\n }\n registry.storesByKey.set(storeKey, store);\n}\n\nexport function registerDocumentStoreIdentity(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n) {\n if (!documentId) {\n return;\n }\n\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const localStoreKey = registry.storeKeysByLocalId.get(localId) ?? localId;\n const documentStoreKey =\n registry.storeKeysByDocumentId.get(documentId) ?? documentId;\n\n registry.storeKeysByLocalId.set(localId, documentStoreKey);\n registry.storeKeysByDocumentId.set(documentId, documentStoreKey);\n\n if (documentStoreKey === localStoreKey) {\n return;\n }\n\n const localStore = registry.storesByKey.get(localStoreKey);\n const documentStore = registry.storesByKey.get(documentStoreKey);\n if (localStore) {\n documentStore?.rebindTo(localStore);\n registry.storesByKey.set(documentStoreKey, localStore);\n }\n registry.storesByKey.delete(localStoreKey);\n}\n\nexport function requestDocumentStoreSync(state: {\n syncLane: {\n requestSync: () => void;\n } | null;\n}) {\n state.syncLane?.requestSync();\n}\n\nexport function requestRegisteredDocumentRemoteSync(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const store = registry.storesByKey.get(\n resolveDocumentStoreKey(registry, localId, documentId),\n );\n if (!store) {\n return false;\n }\n\n // Explicit refresh uses this path to recover missed websocket invalidations\n // without instantiating every unopened document discovered in the container.\n store.requestRemoteSync();\n return true;\n}\n\n/**\n * Discard a registered document's local edits through its store, so the\n * teardown serializes on the store's write machinery instead of racing an\n * in-flight persist that would resurrect the deleted rows. Only registered\n * stores qualify — an unregistered document has no lane submitting its queue,\n * so there is nothing this escape hatch could unstick. No deletion is\n * emitted: the document survives as a re-seeded shell that keeps its listing\n * entry, and the re-pull's own persist announces the restored content.\n *\n * Resolution is strict, unlike the read-side lookups: a destructive action\n * must never run against whichever store won a lookup priority. Both\n * identifiers must map to the SAME registered store — an unknown or stale\n * documentId refuses rather than trusting the localId alone — and the store\n * revalidates the expected documentId against its persisted record inside\n * the teardown's serialized mutation, so even a stale registry mapping\n * cannot discard a different identity's edits.\n */\nexport async function discardRegisteredDocumentLocalState(\n domainScope: DomainScope,\n localId: string,\n documentId: string,\n): Promise<boolean> {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const localStoreKey = registry.storeKeysByLocalId.get(localId);\n const documentStoreKey = registry.storeKeysByDocumentId.get(documentId);\n if (\n !localStoreKey ||\n !documentStoreKey ||\n documentStoreKey !== localStoreKey\n ) {\n return false;\n }\n const store = registry.storesByKey.get(localStoreKey);\n if (!store) {\n return false;\n }\n\n return store.discardLocalState(documentId);\n}\n\nexport function createDocumentStoreFacade(\n initialStore: DocumentStore,\n): DocumentStoreFacade {\n let targetStore = initialStore;\n const listeners = new Set<() => void>();\n\n const emitFacade = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n let unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n\n const connectTarget = (nextStore: DocumentStore) => {\n if (targetStore === nextStore) {\n return;\n }\n\n unsubscribeTarget();\n targetStore = nextStore;\n unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n emitFacade();\n };\n\n const facade: DocumentStoreFacade = {\n addRow: (fields) => targetStore.addRow(fields),\n assertCanRotateContentKey: () => targetStore.assertCanRotateContentKey(),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n targetStore.attachFiles(files),\n discardLocalState: (expectedDocumentId: string) =>\n targetStore.discardLocalState(expectedDocumentId),\n ensureInitialized: () => targetStore.ensureInitialized(),\n getSnapshot: () => targetStore.getSnapshot(),\n removeAttachment: (slotId: string) => targetStore.removeAttachment(slotId),\n removeRow: (id) => targetStore.removeRow(id),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n targetStore.replaceAttachment(slotId, file),\n requestRemoteSync: () => targetStore.requestRemoteSync(),\n requestRemoteSyncAndWait: (signal) =>\n targetStore.requestRemoteSyncAndWait(signal),\n requestSync: () => targetStore.requestSync(),\n relink: (input) => targetStore.relink(input),\n rebindTo: (store) => connectTarget(store),\n setStructuredFields: (kind, patch, options) =>\n targetStore.setStructuredFields(kind, patch, options),\n setText: (value: string) => targetStore.setText(value),\n subscribe: (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n updateRowFields: (id, patch) => targetStore.updateRowFields(id, patch),\n updateRuntime: (runtime: DocumentsRuntime) =>\n targetStore.updateRuntime(runtime),\n };\n registerInternalDocumentRelink(facade, (input, commitSideEffect) =>\n relinkDocumentStoreWithCommitSideEffect(\n targetStore,\n input,\n commitSideEffect,\n ),\n );\n return facade;\n}\n\nexport function emitPersistedDocument(\n domainScope: DomainScope,\n persistedDocument: Parameters<PersistedDocumentListener>[0],\n placementChanged = false,\n): void {\n persistedDocumentListeners.emit(domainScope, persistedDocument, {\n placementChanged,\n });\n}\n\nexport function subscribeToPersistedDocuments(\n domainScope: DomainScope,\n listener: PersistedDocumentListener,\n): () => void {\n return persistedDocumentListeners.subscribe(domainScope, listener);\n}\n\nexport function emitPersistedDocumentDeletion(\n domainScope: DomainScope,\n localId: string,\n): void {\n persistedDocumentDeletionListeners.emit(domainScope, localId);\n}\n\nexport function subscribeToPersistedDocumentDeletions(\n domainScope: DomainScope,\n listener: PersistedDocumentDeletionListener,\n): () => void {\n return persistedDocumentDeletionListeners.subscribe(domainScope, listener);\n}\n\nexport function requestDomainDocumentSync(domainScope: DomainScope): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return;\n }\n\n for (const store of new Set(registry.storesByKey.values())) {\n store.requestSync();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"registry.js","sourceRoot":"","sources":["registry.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,EAC9B,uCAAuC,GACxC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AAwBpE,MAAM,8BAA8B,GAAG,IAAI,OAAO,EAG/C,CAAC;AAGJ,mEAAmE;AACnE,qEAAqE;AACrE,wEAAwE;AACxE,SAAS,4BAA4B;IAGnC,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAA8B,CAAC;IAEnE,OAAO;QACL,IAAI,EAAE,CAAC,WAAwB,EAAE,GAAG,IAA0B,EAAQ,EAAE;YACtE,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;YACpD,IAAI,CAAC,SAAS,EAAE,CAAC;gBACf,OAAO;YACT,CAAC;YAED,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;gBACjC,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QACD,SAAS,EAAE,CAAC,WAAwB,EAAE,QAAkB,EAAgB,EAAE;YACxE,MAAM,SAAS,GACb,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,IAAI,GAAG,EAAY,CAAC;YAC3D,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,gBAAgB,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;YAE7C,OAAO,GAAG,EAAE;gBACV,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAC3B,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;oBACzB,gBAAgB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;gBACvC,CAAC;YACH,CAAC,CAAC;QACJ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G,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;AACzD,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,2BAA2B,CACzC,QAA+B,EAC/B,QAAgB,EAChB,WAAgC;IAEhC,QAAQ,CAAC,mBAAmB,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;IACxD,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACjD,MAAM,YAAY,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC1D,IAAI,KAAK,IAAI,YAAY,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;QAC7C,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACxC,KAAK,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n registerInternalDocumentRelink,\n relinkDocumentStoreWithCommitSideEffect,\n} from \"./documentStore/internalRelink\";\nimport { createRemovedDocumentStore } from \"./removedDocumentStore\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"./types\";\n\ninterface DocumentStoreRegistry {\n /** How the last open built each store's backing store, by store key. */\n freshStoreFactories: Map<string, () => DocumentStore>;\n /** Each backing store's way to stop its sync lane, by local id. */\n retireHandlersByLocalId: Map<string, () => void>;\n /**\n * Stores whose document was removed under them, each with whether its\n * removal still holds; see retireDocumentStore.\n */\n retiredStores: Map<string, () => boolean>;\n storeKeysByDocumentId: Map<string, string>;\n storeKeysByLocalId: Map<string, string>;\n storesByKey: Map<string, DocumentStoreFacade>;\n}\n\nconst documentStoreRegistriesByScope = new WeakMap<\n DomainScope,\n DocumentStoreRegistry\n>();\ntype PersistedDocumentDeletionListener = (localId: string) => void;\n\n// Per-scope listener plumbing shared by the persisted-document and\n// persisted-document-deletion channels: emit fans out to the scope's\n// listeners, and unsubscribing the last listener drops the scope entry.\nfunction createScopedListenerRegistry<\n Listener extends (...args: never[]) => void,\n>() {\n const listenersByScope = new WeakMap<DomainScope, Set<Listener>>();\n\n return {\n emit: (domainScope: DomainScope, ...args: Parameters<Listener>): void => {\n const listeners = listenersByScope.get(domainScope);\n if (!listeners) {\n return;\n }\n\n for (const listener of listeners) {\n listener(...args);\n }\n },\n subscribe: (domainScope: DomainScope, listener: Listener): (() => void) => {\n const listeners =\n listenersByScope.get(domainScope) ?? new Set<Listener>();\n listeners.add(listener);\n listenersByScope.set(domainScope, listeners);\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n listenersByScope.delete(domainScope);\n }\n };\n },\n };\n}\n\nconst persistedDocumentListeners =\n createScopedListenerRegistry<PersistedDocumentListener>();\nconst persistedDocumentDeletionListeners =\n createScopedListenerRegistry<PersistedDocumentDeletionListener>();\n\nexport function getOrCreateDocumentStoreRegistry(\n domainScope: DomainScope,\n): DocumentStoreRegistry {\n const existingRegistry = documentStoreRegistriesByScope.get(domainScope);\n if (existingRegistry) {\n return existingRegistry;\n }\n\n const nextRegistry: DocumentStoreRegistry = {\n freshStoreFactories: new Map(),\n retireHandlersByLocalId: new Map(),\n retiredStores: new Map(),\n storeKeysByDocumentId: new Map(),\n storeKeysByLocalId: new Map(),\n storesByKey: new Map(),\n };\n documentStoreRegistriesByScope.set(domainScope, nextRegistry);\n return nextRegistry;\n}\n\nexport function resolveDocumentStoreKey(\n registry: DocumentStoreRegistry,\n localId: string,\n documentId: string | null,\n): string {\n return (\n (documentId ? registry.storeKeysByDocumentId.get(documentId) : undefined) ??\n registry.storeKeysByLocalId.get(localId) ??\n localId\n );\n}\n\nexport function registerDocumentStore(\n domainScope: DomainScope,\n localId: string,\n store: DocumentStoreFacade,\n documentId: string | null,\n) {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n registry.storeKeysByLocalId.set(localId, storeKey);\n if (documentId) {\n registry.storeKeysByDocumentId.set(documentId, storeKey);\n }\n registry.storesByKey.set(storeKey, store);\n}\n\nexport function registerDocumentStoreIdentity(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n) {\n if (!documentId) {\n return;\n }\n\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const localStoreKey = registry.storeKeysByLocalId.get(localId) ?? localId;\n const documentStoreKey =\n registry.storeKeysByDocumentId.get(documentId) ?? documentId;\n\n registry.storeKeysByLocalId.set(localId, documentStoreKey);\n registry.storeKeysByDocumentId.set(documentId, documentStoreKey);\n\n if (documentStoreKey === localStoreKey) {\n return;\n }\n\n const localStore = registry.storesByKey.get(localStoreKey);\n const documentStore = registry.storesByKey.get(documentStoreKey);\n if (localStore) {\n documentStore?.rebindTo(localStore);\n registry.storesByKey.set(documentStoreKey, localStore);\n // The store's retirement and how to rebuild it move with it.\n moveKeyedEntry(\n registry.freshStoreFactories,\n localStoreKey,\n documentStoreKey,\n );\n moveKeyedEntry(registry.retiredStores, localStoreKey, documentStoreKey);\n }\n registry.storesByKey.delete(localStoreKey);\n}\n\nfunction moveKeyedEntry<Value>(\n entries: Map<string, Value>,\n fromKey: string,\n toKey: string,\n): void {\n const value = entries.get(fromKey);\n entries.delete(fromKey);\n if (value !== undefined) entries.set(toKey, value);\n}\n\n/**\n * Whether an open store holds local writes for the document that have not\n * reached SQLite yet, which no persisted-write scan can see.\n */\nexport function hasQueuedDocumentStoreWrites(\n domainScope: DomainScope,\n localId: string,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n return registry?.storesByKey.get(storeKey)?.hasQueuedWrites() ?? false;\n}\n\nexport function requestDocumentStoreSync(state: {\n syncLane: {\n requestSync: () => void;\n } | null;\n}) {\n state.syncLane?.requestSync();\n}\n\nexport function requestRegisteredDocumentRemoteSync(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n const store = registry.storesByKey.get(storeKey);\n if (!store || registry.retiredStores.has(storeKey)) {\n return false;\n }\n\n // Explicit refresh uses this path to recover missed websocket invalidations\n // without instantiating every unopened document discovered in the container.\n store.requestRemoteSync();\n return true;\n}\n\n/**\n * Discard a registered document's local edits through its store, so the\n * teardown serializes on the store's write machinery instead of racing an\n * in-flight persist that would resurrect the deleted rows. Only registered\n * stores qualify — an unregistered document has no lane submitting its queue,\n * so there is nothing this escape hatch could unstick. No deletion is\n * emitted: the document survives as a re-seeded shell that keeps its listing\n * entry, and the re-pull's own persist announces the restored content.\n *\n * Resolution is strict, unlike the read-side lookups: a destructive action\n * must never run against whichever store won a lookup priority. Both\n * identifiers must map to the SAME registered store — an unknown or stale\n * documentId refuses rather than trusting the localId alone — and the store\n * revalidates the expected documentId against its persisted record inside\n * the teardown's serialized mutation, so even a stale registry mapping\n * cannot discard a different identity's edits.\n */\nexport async function discardRegisteredDocumentLocalState(\n domainScope: DomainScope,\n localId: string,\n documentId: string,\n): Promise<boolean> {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const localStoreKey = registry.storeKeysByLocalId.get(localId);\n const documentStoreKey = registry.storeKeysByDocumentId.get(documentId);\n if (\n !localStoreKey ||\n !documentStoreKey ||\n documentStoreKey !== localStoreKey\n ) {\n return false;\n }\n const store = registry.storesByKey.get(localStoreKey);\n if (!store) {\n return false;\n }\n\n return store.discardLocalState(documentId);\n}\n\nexport function createDocumentStoreFacade(\n initialStore: DocumentStore,\n): DocumentStoreFacade {\n let targetStore = initialStore;\n const listeners = new Set<() => void>();\n\n const emitFacade = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n let unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n\n const connectTarget = (nextStore: DocumentStore) => {\n if (targetStore === nextStore) {\n return;\n }\n\n unsubscribeTarget();\n targetStore = nextStore;\n unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n emitFacade();\n };\n\n const facade: DocumentStoreFacade = {\n addRow: (fields) => targetStore.addRow(fields),\n assertCanRotateContentKey: () => targetStore.assertCanRotateContentKey(),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n targetStore.attachFiles(files),\n discardLocalState: (expectedDocumentId: string) =>\n targetStore.discardLocalState(expectedDocumentId),\n ensureInitialized: () => targetStore.ensureInitialized(),\n getSnapshot: () => targetStore.getSnapshot(),\n hasQueuedWrites: () => targetStore.hasQueuedWrites(),\n removeAttachment: (slotId: string) => targetStore.removeAttachment(slotId),\n removeRow: (id) => targetStore.removeRow(id),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n targetStore.replaceAttachment(slotId, file),\n requestRemoteSync: () => targetStore.requestRemoteSync(),\n requestRemoteSyncAndWait: (signal) =>\n targetStore.requestRemoteSyncAndWait(signal),\n requestSync: () => targetStore.requestSync(),\n relink: (input) => targetStore.relink(input),\n rebindTo: (store) => connectTarget(store),\n setStructuredFields: (kind, patch, options) =>\n targetStore.setStructuredFields(kind, patch, options),\n setText: (value: string) => targetStore.setText(value),\n subscribe: (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n updateRowFields: (id, patch) => targetStore.updateRowFields(id, patch),\n updateRuntime: (runtime: DocumentsRuntime) =>\n targetStore.updateRuntime(runtime),\n };\n registerInternalDocumentRelink(facade, (input, commitSideEffect) =>\n relinkDocumentStoreWithCommitSideEffect(\n targetStore,\n input,\n commitSideEffect,\n ),\n );\n return facade;\n}\n\nexport function emitPersistedDocument(\n domainScope: DomainScope,\n persistedDocument: Parameters<PersistedDocumentListener>[0],\n placementChanged = false,\n): void {\n persistedDocumentListeners.emit(domainScope, persistedDocument, {\n placementChanged,\n });\n}\n\nexport function subscribeToPersistedDocuments(\n domainScope: DomainScope,\n listener: PersistedDocumentListener,\n): () => void {\n return persistedDocumentListeners.subscribe(domainScope, listener);\n}\n\nexport function emitPersistedDocumentDeletion(\n domainScope: DomainScope,\n localId: string,\n): void {\n persistedDocumentDeletionListeners.emit(domainScope, localId);\n}\n\nexport function subscribeToPersistedDocumentDeletions(\n domainScope: DomainScope,\n listener: PersistedDocumentDeletionListener,\n): () => void {\n return persistedDocumentDeletionListeners.subscribe(domainScope, listener);\n}\n\nexport function requestDomainDocumentSync(domainScope: DomainScope): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return;\n }\n\n for (const [storeKey, store] of registry.storesByKey) {\n if (!registry.retiredStores.has(storeKey)) store.requestSync();\n }\n}\n\n/** Lets the backing store for `localId` stop its sync lane when retired. */\nexport function onDocumentStoreRetired(\n domainScope: DomainScope,\n localId: string,\n stopSyncLane: () => void,\n): void {\n getOrCreateDocumentStoreRegistry(domainScope).retireHandlersByLocalId.set(\n localId,\n stopSyncLane,\n );\n}\n\n/**\n * Retires the store of a document a paused organization's cleanup removed.\n * Its backing store's sync lane stops and the facade an editor may hold\n * switches to a read-only stand-in, so nothing recreates or downloads the\n * document. While `stillRemoved()` holds, reopening returns the stand-in;\n * after that, the next open rebinds the facade to a fresh backing store that\n * loads whatever SQLite holds by then, such as a copy rediscovered on resume.\n */\nexport function retireDocumentStore(\n domainScope: DomainScope,\n localId: string,\n stillRemoved: () => boolean,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || registry.retiredStores.has(storeKey)) return;\n registry.retireHandlersByLocalId.get(localId)?.();\n store.rebindTo(createRemovedDocumentStore(store.getSnapshot()));\n registry.retiredStores.set(storeKey, stillRemoved);\n}\n\n/**\n * Undoes a retirement whose deletion did not commit: the document survives,\n * so its facade gets a fresh backing store again.\n */\nexport function restoreDocumentStore(\n domainScope: DomainScope,\n localId: string,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || !registry.retiredStores.delete(storeKey)) return;\n const createFresh = registry.freshStoreFactories.get(storeKey);\n // Without a factory the next open rebinds it instead.\n if (createFresh) store.rebindTo(createFresh());\n else registry.retiredStores.set(storeKey, () => false);\n}\n\n/** The registered store for a key, rebound once its removal has lifted. */\nexport function takeRegisteredDocumentStore(\n registry: DocumentStoreRegistry,\n storeKey: string,\n createFresh: () => DocumentStore,\n): DocumentStoreFacade | undefined {\n registry.freshStoreFactories.set(storeKey, createFresh);\n const store = registry.storesByKey.get(storeKey);\n const stillRemoved = registry.retiredStores.get(storeKey);\n if (store && stillRemoved && !stillRemoved()) {\n registry.retiredStores.delete(storeKey);\n store.rebindTo(createFresh());\n }\n return store;\n}\n"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const REMOVED_DOCUMENT_MESSAGE = "This document was removed while its organization's sync is paused";
|
|
2
|
+
/**
|
|
3
|
+
* Stands in for a store whose document a paused organization's cleanup
|
|
4
|
+
* removed. It keeps showing the last snapshot, read-only, and does nothing
|
|
5
|
+
* else, so an open editor neither recreates the document nor downloads it
|
|
6
|
+
* while the pause lasts.
|
|
7
|
+
*/
|
|
8
|
+
export function createRemovedDocumentStore(lastSnapshot) {
|
|
9
|
+
const snapshot = {
|
|
10
|
+
...lastSnapshot,
|
|
11
|
+
canAttach: false,
|
|
12
|
+
canWrite: false,
|
|
13
|
+
syncing: false,
|
|
14
|
+
};
|
|
15
|
+
const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));
|
|
16
|
+
return {
|
|
17
|
+
addRow: refuse,
|
|
18
|
+
assertCanRotateContentKey: refuse,
|
|
19
|
+
attachFiles: () => undefined,
|
|
20
|
+
discardLocalState: async () => false,
|
|
21
|
+
ensureInitialized: async () => false,
|
|
22
|
+
getSnapshot: () => snapshot,
|
|
23
|
+
hasQueuedWrites: () => false,
|
|
24
|
+
removeAttachment: () => undefined,
|
|
25
|
+
removeRow: refuse,
|
|
26
|
+
replaceAttachment: refuse,
|
|
27
|
+
requestRemoteSync: () => undefined,
|
|
28
|
+
requestRemoteSyncAndWait: async () => false,
|
|
29
|
+
requestSync: () => undefined,
|
|
30
|
+
relink: async () => null,
|
|
31
|
+
setStructuredFields: refuse,
|
|
32
|
+
setText: refuse,
|
|
33
|
+
subscribe: () => () => undefined,
|
|
34
|
+
updateRowFields: refuse,
|
|
35
|
+
updateRuntime: () => undefined,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=removedDocumentStore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"removedDocumentStore.js","sourceRoot":"","sources":["removedDocumentStore.ts"],"names":[],"mappings":"AAEA,MAAM,wBAAwB,GAC5B,mEAAmE,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,YAA8B;IAE9B,MAAM,QAAQ,GAAqB;QACjC,GAAG,YAAY;QACf,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,KAAK;QACf,OAAO,EAAE,KAAK;KACf,CAAC;IACF,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzE,OAAO;QACL,MAAM,EAAE,MAAM;QACd,yBAAyB,EAAE,MAAM;QACjC,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,WAAW,EAAE,GAAG,EAAE,CAAC,QAAQ;QAC3B,eAAe,EAAE,GAAG,EAAE,CAAC,KAAK;QAC5B,gBAAgB,EAAE,GAAG,EAAE,CAAC,SAAS;QACjC,SAAS,EAAE,MAAM;QACjB,iBAAiB,EAAE,MAAM;QACzB,iBAAiB,EAAE,GAAG,EAAE,CAAC,SAAS;QAClC,wBAAwB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QAC3C,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI;QACxB,mBAAmB,EAAE,MAAM;QAC3B,OAAO,EAAE,MAAM;QACf,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,SAAS;QAChC,eAAe,EAAE,MAAM;QACvB,aAAa,EAAE,GAAG,EAAE,CAAC,SAAS;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentSnapshot, DocumentStore } from \"./types\";\n\nconst REMOVED_DOCUMENT_MESSAGE =\n \"This document was removed while its organization's sync is paused\";\n\n/**\n * Stands in for a store whose document a paused organization's cleanup\n * removed. It keeps showing the last snapshot, read-only, and does nothing\n * else, so an open editor neither recreates the document nor downloads it\n * while the pause lasts.\n */\nexport function createRemovedDocumentStore(\n lastSnapshot: DocumentSnapshot,\n): DocumentStore {\n const snapshot: DocumentSnapshot = {\n ...lastSnapshot,\n canAttach: false,\n canWrite: false,\n syncing: false,\n };\n const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));\n return {\n addRow: refuse,\n assertCanRotateContentKey: refuse,\n attachFiles: () => undefined,\n discardLocalState: async () => false,\n ensureInitialized: async () => false,\n getSnapshot: () => snapshot,\n hasQueuedWrites: () => false,\n removeAttachment: () => undefined,\n removeRow: refuse,\n replaceAttachment: refuse,\n requestRemoteSync: () => undefined,\n requestRemoteSyncAndWait: async () => false,\n requestSync: () => undefined,\n relink: async () => null,\n setStructuredFields: refuse,\n setText: refuse,\n subscribe: () => () => undefined,\n updateRowFields: refuse,\n updateRuntime: () => undefined,\n };\n}\n"]}
|
|
@@ -73,6 +73,8 @@ export interface DocumentStore {
|
|
|
73
73
|
discardLocalState: (expectedDocumentId: string) => Promise<boolean>;
|
|
74
74
|
ensureInitialized: () => Promise<boolean>;
|
|
75
75
|
getSnapshot: () => DocumentSnapshot;
|
|
76
|
+
/** Whether local writes are queued that have not reached SQLite yet. */
|
|
77
|
+
hasQueuedWrites: () => boolean;
|
|
76
78
|
removeAttachment: (slotId: string) => void;
|
|
77
79
|
removeRow: RemoveDocumentRow;
|
|
78
80
|
replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) => Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAcA,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\nimport type {\n DocumentFieldValidationIssue,\n StoredDocumentKind,\n} from \"../../data/documents/documentKinds\";\nimport type { DocumentRow } from \"../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { BlobByteSourceInput } from \"../../workflows/blobs\";\nimport type {\n DocumentsWorkflowRuntime,\n RelinkPersistedDocumentInput,\n} from \"../../workflows/documents\";\n\nexport const DEFAULT_DOCUMENT_ID = \"default\";\n\nexport type DocumentsRuntime = DocumentsWorkflowRuntime;\nexport type DocumentStructuredFieldPatch = Readonly<\n Record<string, string | undefined>\n>;\n\nexport interface DocumentMutationOptions {\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface DocumentStoreOpenOptions {\n /**\n * The caller attaches a file immediately after creating the document. The\n * birth commits locally without its own pending update, so the attach's\n * delta carries it; a failed attach enqueues the birth on its own.\n */\n deferInitialUpdate?: boolean | undefined;\n /**\n * Rows and structured fields a newly created record starts with. They are\n * written into its birth update with the initial kind and text, so a\n * document whose content is known up front queues one update. Fields need a\n * non-note `initialDocumentKind`. Both are ignored when the record exists.\n */\n initialRows?: ReadonlyArray<Readonly<Record<string, string>>> | undefined;\n initialStructuredFields?: DocumentStructuredFieldPatch | undefined;\n remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n}\n\nexport interface DocumentAttachmentUpload {\n bytes: BlobByteSourceInput;\n name: string;\n mimeType: string | null;\n}\n\n// `syncing`: the slot's upload is still queued. `intent-mismatch`: the held\n// bytes are a validly signed served binding whose digest differs from the one\n// the document content records (its content update has not arrived).\nexport type DocumentAttachmentStatus = \"syncing\" | \"intent-mismatch\";\n\n// Add a row to the document's repeated-row list, returning the new row id.\nexport type AddDocumentRow = (\n fields: Readonly<Record<string, string>>,\n) => Promise<string>;\n// Patch one or more cells of a single row (merges per-cell).\nexport type UpdateDocumentRowFields = (\n id: string,\n patch: Readonly<Record<string, string>>,\n) => Promise<void>;\nexport type RemoveDocumentRow = (id: string) => Promise<void>;\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation methods, spelled as a Pick so the two can't drift.\nexport type DocumentContextValue = DocumentSnapshot &\n Pick<\n DocumentStore,\n | \"addRow\"\n | \"attachFiles\"\n | \"relink\"\n | \"removeAttachment\"\n | \"removeRow\"\n | \"replaceAttachment\"\n | \"requestSync\"\n | \"setStructuredFields\"\n | \"setText\"\n | \"updateRowFields\"\n >;\n\nexport interface DocumentSnapshot {\n attachments: ReadonlyArray<DocumentAttachment>;\n attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;\n attachmentStorageKeyBySlotId: Readonly<Record<string, string>>;\n canAttach: boolean;\n canWrite: boolean;\n currentAuthorId: string | null;\n documentId: string | null;\n documentKind: StoredDocumentKind;\n effectiveAccessLevel: ContainerAccessLevel;\n fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;\n ready: boolean;\n rows: ReadonlyArray<DocumentRow>;\n structuredFields: Readonly<Record<string, string>>;\n text: string;\n title: string;\n syncing: boolean;\n}\n\nexport interface DocumentStore {\n addRow: AddDocumentRow;\n /** Fail unless this store can produce a mergeable full-history checkpoint. */\n assertCanRotateContentKey: () => Promise<Uint8Array>;\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) => void;\n /**\n * Convert this document's persisted local state to the discovered-share\n * shell so the store re-pulls the server copy — the escape hatch for\n * queued local writes that can no longer sync. `expectedDocumentId` is\n * revalidated against the persisted record inside the teardown's\n * serialized mutation, so a stale caller can never discard a different\n * identity's edits. Refuses (returns false) local-only, unlinked,\n * move-pending, and identity-mismatched documents.\n */\n discardLocalState: (expectedDocumentId: string) => Promise<boolean>;\n ensureInitialized: () => Promise<boolean>;\n getSnapshot: () => DocumentSnapshot;\n removeAttachment: (slotId: string) => void;\n removeRow: RemoveDocumentRow;\n replaceAttachment: (\n slotId: string,\n file: DocumentAttachmentUpload,\n ) => Promise<void>;\n /** Pull remote document updates even when no websocket event marked it dirty. */\n requestRemoteSync: () => void;\n /** Pull remote updates and report whether the requested sync pass completed. */\n requestRemoteSyncAndWait: (\n signal?: AbortSignal | undefined,\n ) => Promise<boolean>;\n requestSync: () => void;\n relink: (input: DocumentStoreRelinkInput) => Promise<DocumentSummary | null>;\n setStructuredFields: (\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options?: DocumentMutationOptions | undefined,\n ) => Promise<void>;\n setText: (value: string) => Promise<void>;\n subscribe: (listener: () => void) => () => void;\n updateRowFields: UpdateDocumentRowFields;\n updateRuntime: (runtime: DocumentsRuntime) => void;\n}\n\nexport interface DocumentStoreFacade extends DocumentStore {\n rebindTo: (store: DocumentStore) => void;\n}\n\nexport type PersistedDocumentListener = (\n document: DocumentSummary,\n change: { readonly placementChanged: boolean },\n) => void;\n\nexport interface DocumentStoreRelinkInput extends RelinkPersistedDocumentInput {\n contentKeyBundle?: string | null | undefined;\n documentKekTargets?: string | null | undefined;\n documentManifestBundle?: string | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAcA,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\nimport type {\n DocumentFieldValidationIssue,\n StoredDocumentKind,\n} from \"../../data/documents/documentKinds\";\nimport type { DocumentRow } from \"../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { BlobByteSourceInput } from \"../../workflows/blobs\";\nimport type {\n DocumentsWorkflowRuntime,\n RelinkPersistedDocumentInput,\n} from \"../../workflows/documents\";\n\nexport const DEFAULT_DOCUMENT_ID = \"default\";\n\nexport type DocumentsRuntime = DocumentsWorkflowRuntime;\nexport type DocumentStructuredFieldPatch = Readonly<\n Record<string, string | undefined>\n>;\n\nexport interface DocumentMutationOptions {\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface DocumentStoreOpenOptions {\n /**\n * The caller attaches a file immediately after creating the document. The\n * birth commits locally without its own pending update, so the attach's\n * delta carries it; a failed attach enqueues the birth on its own.\n */\n deferInitialUpdate?: boolean | undefined;\n /**\n * Rows and structured fields a newly created record starts with. They are\n * written into its birth update with the initial kind and text, so a\n * document whose content is known up front queues one update. Fields need a\n * non-note `initialDocumentKind`. Both are ignored when the record exists.\n */\n initialRows?: ReadonlyArray<Readonly<Record<string, string>>> | undefined;\n initialStructuredFields?: DocumentStructuredFieldPatch | undefined;\n remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n}\n\nexport interface DocumentAttachmentUpload {\n bytes: BlobByteSourceInput;\n name: string;\n mimeType: string | null;\n}\n\n// `syncing`: the slot's upload is still queued. `intent-mismatch`: the held\n// bytes are a validly signed served binding whose digest differs from the one\n// the document content records (its content update has not arrived).\nexport type DocumentAttachmentStatus = \"syncing\" | \"intent-mismatch\";\n\n// Add a row to the document's repeated-row list, returning the new row id.\nexport type AddDocumentRow = (\n fields: Readonly<Record<string, string>>,\n) => Promise<string>;\n// Patch one or more cells of a single row (merges per-cell).\nexport type UpdateDocumentRowFields = (\n id: string,\n patch: Readonly<Record<string, string>>,\n) => Promise<void>;\nexport type RemoveDocumentRow = (id: string) => Promise<void>;\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation methods, spelled as a Pick so the two can't drift.\nexport type DocumentContextValue = DocumentSnapshot &\n Pick<\n DocumentStore,\n | \"addRow\"\n | \"attachFiles\"\n | \"relink\"\n | \"removeAttachment\"\n | \"removeRow\"\n | \"replaceAttachment\"\n | \"requestSync\"\n | \"setStructuredFields\"\n | \"setText\"\n | \"updateRowFields\"\n >;\n\nexport interface DocumentSnapshot {\n attachments: ReadonlyArray<DocumentAttachment>;\n attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;\n attachmentStorageKeyBySlotId: Readonly<Record<string, string>>;\n canAttach: boolean;\n canWrite: boolean;\n currentAuthorId: string | null;\n documentId: string | null;\n documentKind: StoredDocumentKind;\n effectiveAccessLevel: ContainerAccessLevel;\n fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;\n ready: boolean;\n rows: ReadonlyArray<DocumentRow>;\n structuredFields: Readonly<Record<string, string>>;\n text: string;\n title: string;\n syncing: boolean;\n}\n\nexport interface DocumentStore {\n addRow: AddDocumentRow;\n /** Fail unless this store can produce a mergeable full-history checkpoint. */\n assertCanRotateContentKey: () => Promise<Uint8Array>;\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) => void;\n /**\n * Convert this document's persisted local state to the discovered-share\n * shell so the store re-pulls the server copy — the escape hatch for\n * queued local writes that can no longer sync. `expectedDocumentId` is\n * revalidated against the persisted record inside the teardown's\n * serialized mutation, so a stale caller can never discard a different\n * identity's edits. Refuses (returns false) local-only, unlinked,\n * move-pending, and identity-mismatched documents.\n */\n discardLocalState: (expectedDocumentId: string) => Promise<boolean>;\n ensureInitialized: () => Promise<boolean>;\n getSnapshot: () => DocumentSnapshot;\n /** Whether local writes are queued that have not reached SQLite yet. */\n hasQueuedWrites: () => boolean;\n removeAttachment: (slotId: string) => void;\n removeRow: RemoveDocumentRow;\n replaceAttachment: (\n slotId: string,\n file: DocumentAttachmentUpload,\n ) => Promise<void>;\n /** Pull remote document updates even when no websocket event marked it dirty. */\n requestRemoteSync: () => void;\n /** Pull remote updates and report whether the requested sync pass completed. */\n requestRemoteSyncAndWait: (\n signal?: AbortSignal | undefined,\n ) => Promise<boolean>;\n requestSync: () => void;\n relink: (input: DocumentStoreRelinkInput) => Promise<DocumentSummary | null>;\n setStructuredFields: (\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options?: DocumentMutationOptions | undefined,\n ) => Promise<void>;\n setText: (value: string) => Promise<void>;\n subscribe: (listener: () => void) => () => void;\n updateRowFields: UpdateDocumentRowFields;\n updateRuntime: (runtime: DocumentsRuntime) => void;\n}\n\nexport interface DocumentStoreFacade extends DocumentStore {\n rebindTo: (store: DocumentStore) => void;\n}\n\nexport type PersistedDocumentListener = (\n document: DocumentSummary,\n change: { readonly placementChanged: boolean },\n) => void;\n\nexport interface DocumentStoreRelinkInput extends RelinkPersistedDocumentInput {\n contentKeyBundle?: string | null | undefined;\n documentKekTargets?: string | null | undefined;\n documentManifestBundle?: string | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\n"]}
|
|
@@ -309,8 +309,8 @@ export function createReconciliationService(host) {
|
|
|
309
309
|
listContainerIds: host.listAutomaticRootCatchupContainerIds,
|
|
310
310
|
scope: "root",
|
|
311
311
|
}),
|
|
312
|
-
reconcileNow: () => requestContainerRefresh({
|
|
313
|
-
freshListing:
|
|
312
|
+
reconcileNow: (options) => requestContainerRefresh({
|
|
313
|
+
freshListing: options?.freshListing === true,
|
|
314
314
|
host,
|
|
315
315
|
state,
|
|
316
316
|
refreshTree: host.refreshTree,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"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,EAAE,IAAI,CAAC,WAAW;YAC7B,gBAAgB,EAAE,GAAG,EAAE,CAAC,2BAA2B,CAAC,IAAI,EAAE,KAAK,CAAC;YAChE,KAAK,EAAE,MAAM;SACd,CAAC;QACJ,IAAI,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC;KACnD,CAAC;AACJ,CAAC","sourcesContent":["import { clearOriginatedDocuments } from \"../../data/sync/originatedDocuments\";\nimport type { SyncLane } from \"../../data/sync/syncLaneConfig\";\nimport {\n acknowledgeContainerForce,\n activateContainer,\n enqueueKnownContainersForIdleBackfill,\n type IdleBackfillState,\n markContainerForced,\n} from \"./idleBackfill\";\nimport { createInitialDocumentProbe } from \"./initialDocumentProbe\";\nimport {\n clearPendingDiscoveryRetries,\n isCurrentReconciliationLifecycle,\n reconcileMarkedContainers,\n sweepKnownContainers,\n} from \"./knownContainerSweep\";\nimport { rearmFailedContainer } from \"./laneFailure\";\nimport { createReconcileQueue, type ReconcilePriority } from \"./queue\";\nimport type {\n ReconciliationHost,\n ReconciliationRuntimeStatus,\n ReconciliationService,\n} from \"./serviceTypes\";\n\nfunction canReconcile(status: ReconciliationRuntimeStatus): boolean {\n return status.dbStatus === \"ready\" && status.isAuthenticated && status.online;\n}\n\ntype RefreshScope = \"root\" | \"full\";\n\ninterface ReconciliationState extends IdleBackfillState {\n active: boolean;\n lane: SyncLane | null;\n lifecycleGeneration: number;\n probeContinuationCancel: (() => void) | null;\n pendingRefresh: {\n readonly promise: Promise<void>;\n readonly scope: RefreshScope;\n readonly started: { value: boolean };\n } | null;\n}\n\n/**\n * Queued containers one lane run lists together. Each still verifies and\n * applies on its own; the bound keeps one run's head verification well\n * inside the lane watchdog.\n */\nconst RECONCILE_LANE_BATCH_SIZE = 4;\n\nfunction dequeueContainerBatch(state: ReconciliationState): string[] {\n const containerIds: string[] = [];\n while (containerIds.length < RECONCILE_LANE_BATCH_SIZE) {\n const containerId = state.queue.dequeue();\n if (!containerId) break;\n containerIds.push(containerId);\n }\n return containerIds;\n}\n\nasync function runReconcileLane(\n host: ReconciliationHost,\n state: ReconciliationState,\n): Promise<void> {\n if (!state.active || !canReconcile(host.getRuntimeStatus())) {\n return;\n }\n const lifecycleGeneration = state.lifecycleGeneration;\n\n const containerIds = dequeueContainerBatch(state);\n if (containerIds.length === 0) {\n await state.initialDocumentProbe.run();\n scheduleProbeContinuation(host, state);\n return;\n }\n // Double-check at run time: a container may have been discovered (by an\n // explicit refresh or an earlier lane pass) after it was queued. Mark it\n // discovered up front to collapse concurrent re-enqueues into one fetch, but\n // roll the mark back on failure so a transient error can be retried. Force\n // generations are read before the batched listing starts.\n const batch = containerIds.flatMap((containerId) => {\n const forceGeneration = state.forcedContainerGenerations.get(containerId);\n if (\n forceGeneration === undefined &&\n state.discoveredContainerIds.has(containerId)\n ) {\n return [];\n }\n state.discoveredContainerIds.add(containerId);\n return [{ containerId, forceGeneration }];\n });\n const results = await reconcileMarkedContainers(\n host,\n state,\n batch.map(({ containerId, forceGeneration }) => ({\n containerId,\n forceDocumentContentPull: forceGeneration !== undefined,\n })),\n );\n let firstError: unknown;\n results.forEach((result, index) => {\n const forceGeneration = batch[index]?.forceGeneration;\n if (result.status === \"reconciled\") {\n acknowledgeContainerForce(state, result.containerId, forceGeneration);\n } else if (result.status === \"failed\") {\n rearmFailedContainer(\n state,\n result.containerId,\n forceGeneration,\n lifecycleGeneration,\n );\n firstError ??= result.error;\n }\n });\n if (firstError !== undefined) throw firstError;\n\n // Keep draining: schedule another pass while the queue holds work.\n if (state.queue.size > 0) {\n state.lane?.requestSync();\n } else {\n scheduleProbeContinuation(host, state);\n }\n}\n\nfunction scheduleProbeContinuation(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n state.probeContinuationCancel?.();\n const canContinue = () =>\n state.active &&\n state.queue.size === 0 &&\n canReconcile(host.getRuntimeStatus()) &&\n state.initialDocumentProbe.hasPendingWork();\n if (!canContinue()) {\n state.probeContinuationCancel = null;\n return;\n }\n state.probeContinuationCancel = host.clock.schedule(() => {\n if (canContinue()) {\n state.probeContinuationCancel = null;\n state.lane?.requestSync();\n }\n }, state.initialDocumentProbe.continuationDelayMs());\n}\n\nfunction forgetIneligibleDiscoveredContainers(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n for (const containerId of state.discoveredContainerIds) {\n if (!host.canDiscoverContainerDocuments(containerId)) {\n state.discoveredContainerIds.delete(containerId);\n }\n }\n}\n\nasync function refreshAndReconcileContainers(input: {\n forceAllDocumentContentPulls: boolean;\n host: ReconciliationHost;\n listContainerIds: () => ReadonlyArray<string>;\n refreshTree: () => Promise<void>;\n state: ReconciliationState;\n}): Promise<void> {\n const { host, listContainerIds, refreshTree, state } = input;\n if (!canReconcile(host.getRuntimeStatus())) {\n return;\n }\n const lifecycleGeneration = state.lifecycleGeneration;\n\n if (input.forceAllDocumentContentPulls) {\n state.queue.clear();\n }\n try {\n // A resync_required structural refresh runs independently of this service.\n // If it already removed a container after the forced document lane won its\n // race against the old tree, forget the stale discovered bit before this\n // refresh can re-add the same id.\n forgetIneligibleDiscoveredContainers(host, state);\n await refreshTree();\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n // Structural hydration can revoke and remove a container after a targeted\n // force already reconciled it against the old tree. Forget every id that\n // is no longer remotely listable so a later share of the same container id\n // is treated as newly surfaced instead of being suppressed for the rest of\n // the session.\n forgetIneligibleDiscoveredContainers(host, state);\n await sweepKnownContainers({\n forceAllDocumentContentPulls: input.forceAllDocumentContentPulls,\n host,\n knownIds: listContainerIds(),\n lifecycleGeneration,\n state,\n });\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n } catch (error) {\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n if (!host.isIgnorableError(error)) {\n throw error;\n }\n }\n}\n\n// Sweeps share the queue and discovered set, so they must run serially.\n// Root requests join either kind of sweep; a full request after a root sweep\n// must wait for it and then refresh the whole tree. A fresh-listing request\n// joins only a sweep that has not started: one already running may have listed\n// before the event behind the request, so it queues a trailing sweep instead.\nfunction requestContainerRefresh(input: {\n freshListing: boolean;\n host: ReconciliationHost;\n state: ReconciliationState;\n refreshTree: () => Promise<void>;\n listContainerIds: () => ReadonlyArray<string>;\n scope: RefreshScope;\n}): Promise<void> {\n const { state, scope } = input;\n const pending = state.pendingRefresh;\n if (\n pending &&\n (scope === \"root\" || pending.scope === \"full\") &&\n !(input.freshListing && pending.started.value)\n ) {\n return pending.promise;\n }\n\n const started = { value: false };\n const promise = (pending?.promise ?? Promise.resolve())\n // A failed earlier sweep must not prevent the queued refresh.\n .catch(() => undefined)\n .then(() => {\n started.value = true;\n return refreshAndReconcileContainers({\n forceAllDocumentContentPulls: scope === \"full\",\n host: input.host,\n listContainerIds: input.listContainerIds,\n refreshTree: input.refreshTree,\n state,\n });\n })\n .finally(() => {\n if (state.pendingRefresh?.promise === promise) {\n state.pendingRefresh = null;\n }\n });\n state.pendingRefresh = { promise, scope, started };\n return promise;\n}\n\nfunction listFullRefreshContainerIds(\n host: ReconciliationHost,\n state: ReconciliationState,\n): ReadonlyArray<string> {\n const knownIds = host.listKnownContainerIds();\n const activeContainerId = state.activeContainerId;\n if (\n !activeContainerId ||\n knownIds.includes(activeContainerId) ||\n !host.canDiscoverContainerDocuments(activeContainerId)\n ) {\n return knownIds;\n }\n // Explicit refresh also retries an open foreign system container that the\n // background discovery list excludes.\n return [...knownIds, activeContainerId];\n}\n\nfunction startReconciliationLane(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n if (state.active) {\n return;\n }\n state.lifecycleGeneration += 1;\n state.active = true;\n state.lane = host.registerLane(\"reconciliation:documents\", {\n label: \"Device-first document reconciliation\",\n // Document discovery runs in the document phase, after structural\n // container hydration/metadata sync settles for the scope.\n phase: \"document\",\n priority: () => (state.activeContainerId ? -1 : 0),\n onUnexpectedError: (error) => {\n console.error(\"Device-first reconciliation failed:\", error);\n },\n // Fixed literal: no container or document id may reach a report. The\n // mapped stack identifies which lane body threw. Returning the host's\n // result hands a rejection to the lane reporter's wrapper; discarding it\n // would surface as an unhandled rejection instead.\n reportUnexpectedError: (error) =>\n host.logError?.(\"Reconciliation: sync lane failed\", error),\n run: () => runReconcileLane(host, state),\n shouldIgnoreError: host.isIgnorableError,\n });\n}\n\nfunction createReconciliationState(\n host: ReconciliationHost,\n): ReconciliationState {\n return {\n active: false,\n activeContainerId: null,\n automaticRetryGenerations: new Map(),\n discoveredContainerIds: new Set(),\n forcedContainerGenerations: new Map(),\n forcedDocumentIds: new Map(),\n initialDocumentProbe: createInitialDocumentProbe(host),\n lane: null,\n lifecycleGeneration: 0,\n nextForceGeneration: 0,\n probeContinuationCancel: null,\n queue: createReconcileQueue(),\n pendingRefresh: null,\n };\n}\n\nfunction stopReconciliationService(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n clearPendingDiscoveryRetries(state);\n state.active = false;\n state.probeContinuationCancel?.();\n state.probeContinuationCancel = null;\n state.queue.clear();\n state.automaticRetryGenerations.clear();\n state.forcedContainerGenerations.clear();\n state.forcedDocumentIds.clear();\n state.pendingRefresh = null;\n state.initialDocumentProbe.resetPending();\n // Drop the per-session discovered suppression cache too: a stopped\n // reconciler is being torn down (scope/identity change) or paused across\n // a prerequisite loss, after which every container must be re-validated.\n state.discoveredContainerIds.clear();\n // Drop pending self-echo originations too — they are session-scoped and a\n // teardown invalidates them.\n clearOriginatedDocuments(host.domainScope);\n}\n\nexport function createReconciliationService(\n host: ReconciliationHost,\n): ReconciliationService {\n const state = createReconciliationState(host);\n\n const scheduleDrain = () => {\n if (\n !state.active ||\n (state.queue.size === 0 && !state.initialDocumentProbe.canRun())\n ) {\n return;\n }\n if (!canReconcile(host.getRuntimeStatus())) {\n return;\n }\n state.probeContinuationCancel?.();\n state.probeContinuationCancel = null;\n state.lane?.requestSync();\n };\n\n const enqueueContainer = (\n containerId: string,\n priority: ReconcilePriority,\n force = false,\n documentId?: string,\n ) => {\n if (!containerId) {\n return;\n }\n // Skip containers already reconciled this session unless forced. Events\n // force re-discovery; passive active/backfill scheduling does not, so\n // opening Explorer does not re-fetch every container on each navigation.\n if (\n !force &&\n !state.forcedContainerGenerations.has(containerId) &&\n state.discoveredContainerIds.has(containerId)\n ) {\n return;\n }\n if (force) {\n markContainerForced(state, containerId, documentId);\n }\n state.queue.enqueue(containerId, priority);\n scheduleDrain();\n };\n\n const enqueueIdleBackfill = () => {\n enqueueKnownContainersForIdleBackfill({\n host,\n scheduleDrain,\n state,\n });\n };\n\n return {\n start: () => {\n startReconciliationLane(host, state);\n scheduleDrain();\n },\n // Reconcile the active container first; siblings remain lazy until visited.\n setActiveContainer: (containerId) =>\n activateContainer(state, containerId, (activeId) =>\n enqueueContainer(activeId, \"active\"),\n ),\n enqueueContainer,\n enqueueIdleBackfill,\n resetDiscovered: () => {\n state.discoveredContainerIds.clear();\n state.initialDocumentProbe.resetSkippedListings();\n },\n reconcileRootContainersNow: (options) =>\n requestContainerRefresh({\n freshListing: options?.freshListing === true,\n host,\n state,\n refreshTree: host.refreshRootTree,\n listContainerIds: host.listAutomaticRootCatchupContainerIds,\n scope: \"root\",\n }),\n reconcileNow: () =>\n requestContainerRefresh({\n freshListing: false,\n host,\n state,\n refreshTree: host.refreshTree,\n listContainerIds: () => listFullRefreshContainerIds(host, state),\n scope: \"full\",\n }),\n stop: () => stopReconciliationService(host, state),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAE/E,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,qCAAqC,EAErC,mBAAmB,GACpB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,EAChC,yBAAyB,EACzB,oBAAoB,GACrB,MAAM,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ocuments } from \"../../data/sync/originatedDocuments\";\nimport type { SyncLane } from \"../../data/sync/syncLaneConfig\";\nimport {\n acknowledgeContainerForce,\n activateContainer,\n enqueueKnownContainersForIdleBackfill,\n type IdleBackfillState,\n markContainerForced,\n} from \"./idleBackfill\";\nimport { createInitialDocumentProbe } from \"./initialDocumentProbe\";\nimport {\n clearPendingDiscoveryRetries,\n isCurrentReconciliationLifecycle,\n reconcileMarkedContainers,\n sweepKnownContainers,\n} from \"./knownContainerSweep\";\nimport { rearmFailedContainer } from \"./laneFailure\";\nimport { createReconcileQueue, type ReconcilePriority } from \"./queue\";\nimport type {\n ReconciliationHost,\n ReconciliationRuntimeStatus,\n ReconciliationService,\n} from \"./serviceTypes\";\n\nfunction canReconcile(status: ReconciliationRuntimeStatus): boolean {\n return status.dbStatus === \"ready\" && status.isAuthenticated && status.online;\n}\n\ntype RefreshScope = \"root\" | \"full\";\n\ninterface ReconciliationState extends IdleBackfillState {\n active: boolean;\n lane: SyncLane | null;\n lifecycleGeneration: number;\n probeContinuationCancel: (() => void) | null;\n pendingRefresh: {\n readonly promise: Promise<void>;\n readonly scope: RefreshScope;\n readonly started: { value: boolean };\n } | null;\n}\n\n/**\n * Queued containers one lane run lists together. Each still verifies and\n * applies on its own; the bound keeps one run's head verification well\n * inside the lane watchdog.\n */\nconst RECONCILE_LANE_BATCH_SIZE = 4;\n\nfunction dequeueContainerBatch(state: ReconciliationState): string[] {\n const containerIds: string[] = [];\n while (containerIds.length < RECONCILE_LANE_BATCH_SIZE) {\n const containerId = state.queue.dequeue();\n if (!containerId) break;\n containerIds.push(containerId);\n }\n return containerIds;\n}\n\nasync function runReconcileLane(\n host: ReconciliationHost,\n state: ReconciliationState,\n): Promise<void> {\n if (!state.active || !canReconcile(host.getRuntimeStatus())) {\n return;\n }\n const lifecycleGeneration = state.lifecycleGeneration;\n\n const containerIds = dequeueContainerBatch(state);\n if (containerIds.length === 0) {\n await state.initialDocumentProbe.run();\n scheduleProbeContinuation(host, state);\n return;\n }\n // Double-check at run time: a container may have been discovered (by an\n // explicit refresh or an earlier lane pass) after it was queued. Mark it\n // discovered up front to collapse concurrent re-enqueues into one fetch, but\n // roll the mark back on failure so a transient error can be retried. Force\n // generations are read before the batched listing starts.\n const batch = containerIds.flatMap((containerId) => {\n const forceGeneration = state.forcedContainerGenerations.get(containerId);\n if (\n forceGeneration === undefined &&\n state.discoveredContainerIds.has(containerId)\n ) {\n return [];\n }\n state.discoveredContainerIds.add(containerId);\n return [{ containerId, forceGeneration }];\n });\n const results = await reconcileMarkedContainers(\n host,\n state,\n batch.map(({ containerId, forceGeneration }) => ({\n containerId,\n forceDocumentContentPull: forceGeneration !== undefined,\n })),\n );\n let firstError: unknown;\n results.forEach((result, index) => {\n const forceGeneration = batch[index]?.forceGeneration;\n if (result.status === \"reconciled\") {\n acknowledgeContainerForce(state, result.containerId, forceGeneration);\n } else if (result.status === \"failed\") {\n rearmFailedContainer(\n state,\n result.containerId,\n forceGeneration,\n lifecycleGeneration,\n );\n firstError ??= result.error;\n }\n });\n if (firstError !== undefined) throw firstError;\n\n // Keep draining: schedule another pass while the queue holds work.\n if (state.queue.size > 0) {\n state.lane?.requestSync();\n } else {\n scheduleProbeContinuation(host, state);\n }\n}\n\nfunction scheduleProbeContinuation(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n state.probeContinuationCancel?.();\n const canContinue = () =>\n state.active &&\n state.queue.size === 0 &&\n canReconcile(host.getRuntimeStatus()) &&\n state.initialDocumentProbe.hasPendingWork();\n if (!canContinue()) {\n state.probeContinuationCancel = null;\n return;\n }\n state.probeContinuationCancel = host.clock.schedule(() => {\n if (canContinue()) {\n state.probeContinuationCancel = null;\n state.lane?.requestSync();\n }\n }, state.initialDocumentProbe.continuationDelayMs());\n}\n\nfunction forgetIneligibleDiscoveredContainers(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n for (const containerId of state.discoveredContainerIds) {\n if (!host.canDiscoverContainerDocuments(containerId)) {\n state.discoveredContainerIds.delete(containerId);\n }\n }\n}\n\nasync function refreshAndReconcileContainers(input: {\n forceAllDocumentContentPulls: boolean;\n host: ReconciliationHost;\n listContainerIds: () => ReadonlyArray<string>;\n refreshTree: () => Promise<void>;\n state: ReconciliationState;\n}): Promise<void> {\n const { host, listContainerIds, refreshTree, state } = input;\n if (!canReconcile(host.getRuntimeStatus())) {\n return;\n }\n const lifecycleGeneration = state.lifecycleGeneration;\n\n if (input.forceAllDocumentContentPulls) {\n state.queue.clear();\n }\n try {\n // A resync_required structural refresh runs independently of this service.\n // If it already removed a container after the forced document lane won its\n // race against the old tree, forget the stale discovered bit before this\n // refresh can re-add the same id.\n forgetIneligibleDiscoveredContainers(host, state);\n await refreshTree();\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n // Structural hydration can revoke and remove a container after a targeted\n // force already reconciled it against the old tree. Forget every id that\n // is no longer remotely listable so a later share of the same container id\n // is treated as newly surfaced instead of being suppressed for the rest of\n // the session.\n forgetIneligibleDiscoveredContainers(host, state);\n await sweepKnownContainers({\n forceAllDocumentContentPulls: input.forceAllDocumentContentPulls,\n host,\n knownIds: listContainerIds(),\n lifecycleGeneration,\n state,\n });\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n } catch (error) {\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n if (!host.isIgnorableError(error)) {\n throw error;\n }\n }\n}\n\n// Sweeps share the queue and discovered set, so they must run serially.\n// Root requests join either kind of sweep; a full request after a root sweep\n// must wait for it and then refresh the whole tree. A fresh-listing request\n// joins only a sweep that has not started: one already running may have listed\n// before the event behind the request, so it queues a trailing sweep instead.\nfunction requestContainerRefresh(input: {\n freshListing: boolean;\n host: ReconciliationHost;\n state: ReconciliationState;\n refreshTree: () => Promise<void>;\n listContainerIds: () => ReadonlyArray<string>;\n scope: RefreshScope;\n}): Promise<void> {\n const { state, scope } = input;\n const pending = state.pendingRefresh;\n if (\n pending &&\n (scope === \"root\" || pending.scope === \"full\") &&\n !(input.freshListing && pending.started.value)\n ) {\n return pending.promise;\n }\n\n const started = { value: false };\n const promise = (pending?.promise ?? Promise.resolve())\n // A failed earlier sweep must not prevent the queued refresh.\n .catch(() => undefined)\n .then(() => {\n started.value = true;\n return refreshAndReconcileContainers({\n forceAllDocumentContentPulls: scope === \"full\",\n host: input.host,\n listContainerIds: input.listContainerIds,\n refreshTree: input.refreshTree,\n state,\n });\n })\n .finally(() => {\n if (state.pendingRefresh?.promise === promise) {\n state.pendingRefresh = null;\n }\n });\n state.pendingRefresh = { promise, scope, started };\n return promise;\n}\n\nfunction listFullRefreshContainerIds(\n host: ReconciliationHost,\n state: ReconciliationState,\n): ReadonlyArray<string> {\n const knownIds = host.listKnownContainerIds();\n const activeContainerId = state.activeContainerId;\n if (\n !activeContainerId ||\n knownIds.includes(activeContainerId) ||\n !host.canDiscoverContainerDocuments(activeContainerId)\n ) {\n return knownIds;\n }\n // Explicit refresh also retries an open foreign system container that the\n // background discovery list excludes.\n return [...knownIds, activeContainerId];\n}\n\nfunction startReconciliationLane(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n if (state.active) {\n return;\n }\n state.lifecycleGeneration += 1;\n state.active = true;\n state.lane = host.registerLane(\"reconciliation:documents\", {\n label: \"Device-first document reconciliation\",\n // Document discovery runs in the document phase, after structural\n // container hydration/metadata sync settles for the scope.\n phase: \"document\",\n priority: () => (state.activeContainerId ? -1 : 0),\n onUnexpectedError: (error) => {\n console.error(\"Device-first reconciliation failed:\", error);\n },\n // Fixed literal: no container or document id may reach a report. The\n // mapped stack identifies which lane body threw. Returning the host's\n // result hands a rejection to the lane reporter's wrapper; discarding it\n // would surface as an unhandled rejection instead.\n reportUnexpectedError: (error) =>\n host.logError?.(\"Reconciliation: sync lane failed\", error),\n run: () => runReconcileLane(host, state),\n shouldIgnoreError: host.isIgnorableError,\n });\n}\n\nfunction createReconciliationState(\n host: ReconciliationHost,\n): ReconciliationState {\n return {\n active: false,\n activeContainerId: null,\n automaticRetryGenerations: new Map(),\n discoveredContainerIds: new Set(),\n forcedContainerGenerations: new Map(),\n forcedDocumentIds: new Map(),\n initialDocumentProbe: createInitialDocumentProbe(host),\n lane: null,\n lifecycleGeneration: 0,\n nextForceGeneration: 0,\n probeContinuationCancel: null,\n queue: createReconcileQueue(),\n pendingRefresh: null,\n };\n}\n\nfunction stopReconciliationService(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n clearPendingDiscoveryRetries(state);\n state.active = false;\n state.probeContinuationCancel?.();\n state.probeContinuationCancel = null;\n state.queue.clear();\n state.automaticRetryGenerations.clear();\n state.forcedContainerGenerations.clear();\n state.forcedDocumentIds.clear();\n state.pendingRefresh = null;\n state.initialDocumentProbe.resetPending();\n // Drop the per-session discovered suppression cache too: a stopped\n // reconciler is being torn down (scope/identity change) or paused across\n // a prerequisite loss, after which every container must be re-validated.\n state.discoveredContainerIds.clear();\n // Drop pending self-echo originations too — they are session-scoped and a\n // teardown invalidates them.\n clearOriginatedDocuments(host.domainScope);\n}\n\nexport function createReconciliationService(\n host: ReconciliationHost,\n): ReconciliationService {\n const state = createReconciliationState(host);\n\n const scheduleDrain = () => {\n if (\n !state.active ||\n (state.queue.size === 0 && !state.initialDocumentProbe.canRun())\n ) {\n return;\n }\n if (!canReconcile(host.getRuntimeStatus())) {\n return;\n }\n state.probeContinuationCancel?.();\n state.probeContinuationCancel = null;\n state.lane?.requestSync();\n };\n\n const enqueueContainer = (\n containerId: string,\n priority: ReconcilePriority,\n force = false,\n documentId?: string,\n ) => {\n if (!containerId) {\n return;\n }\n // Skip containers already reconciled this session unless forced. Events\n // force re-discovery; passive active/backfill scheduling does not, so\n // opening Explorer does not re-fetch every container on each navigation.\n if (\n !force &&\n !state.forcedContainerGenerations.has(containerId) &&\n state.discoveredContainerIds.has(containerId)\n ) {\n return;\n }\n if (force) {\n markContainerForced(state, containerId, documentId);\n }\n state.queue.enqueue(containerId, priority);\n scheduleDrain();\n };\n\n const enqueueIdleBackfill = () => {\n enqueueKnownContainersForIdleBackfill({\n host,\n scheduleDrain,\n state,\n });\n };\n\n return {\n start: () => {\n startReconciliationLane(host, state);\n scheduleDrain();\n },\n // Reconcile the active container first; siblings remain lazy until visited.\n setActiveContainer: (containerId) =>\n activateContainer(state, containerId, (activeId) =>\n enqueueContainer(activeId, \"active\"),\n ),\n enqueueContainer,\n enqueueIdleBackfill,\n resetDiscovered: () => {\n state.discoveredContainerIds.clear();\n state.initialDocumentProbe.resetSkippedListings();\n },\n reconcileRootContainersNow: (options) =>\n requestContainerRefresh({\n freshListing: options?.freshListing === true,\n host,\n state,\n refreshTree: host.refreshRootTree,\n listContainerIds: host.listAutomaticRootCatchupContainerIds,\n scope: \"root\",\n }),\n reconcileNow: (options) =>\n requestContainerRefresh({\n freshListing: options?.freshListing === true,\n host,\n state,\n refreshTree: host.refreshTree,\n listContainerIds: () => listFullRefreshContainerIds(host, state),\n scope: \"full\",\n }),\n stop: () => stopReconciliationService(host, state),\n };\n}\n"]}
|
|
@@ -102,6 +102,13 @@ export interface ReconciliationService {
|
|
|
102
102
|
reconcileRootContainersNow: (options?: {
|
|
103
103
|
readonly freshListing?: boolean;
|
|
104
104
|
}) => Promise<void>;
|
|
105
|
-
|
|
105
|
+
/**
|
|
106
|
+
* Refresh the whole tree and reconcile every known container. With
|
|
107
|
+
* `freshListing`, never join a sweep that already started listing: one
|
|
108
|
+
* queues behind it instead, so the listing reflects a change made after.
|
|
109
|
+
*/
|
|
110
|
+
reconcileNow: (options?: {
|
|
111
|
+
readonly freshListing?: boolean;
|
|
112
|
+
}) => Promise<void>;
|
|
106
113
|
stop: () => void;
|
|
107
114
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serviceTypes.js","sourceRoot":"","sources":["serviceTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SyncLane, SyncLaneConfig } from \"../../data/sync/syncLaneConfig\";\nimport type { LocalProjectionReconciledDelta } from \"../../stores/local-projection\";\nimport type { InitialDocumentProbeHost } from \"./initialDocumentProbe\";\nimport type { ReconcilePriority } from \"./queue\";\n\n/** One container a reconciliation pass lists, with its per-lane callbacks. */\nexport interface ContainerDiscoveryRequest {\n readonly containerId: string;\n readonly onFullListing?:\n | ((documentIds: ReadonlyArray<string>) => void)\n | undefined;\n readonly onPendingDiscovery?: ((delayMs: number) => void) | undefined;\n}\n\n/** A discovered lane: `null` means it was not fully listed or applied nothing. */\nexport type ContainerDiscoveryOutcome =\n | {\n readonly containerId: string;\n readonly status: \"fulfilled\";\n readonly value: ReadonlyArray<DocumentSummary> | null;\n }\n | {\n readonly containerId: string;\n readonly reason: unknown;\n readonly status: \"rejected\";\n };\n\nexport interface ReconciliationRuntimeStatus {\n dbStatus: string;\n isAuthenticated: boolean;\n online: boolean;\n}\n\n/**\n * Host contract injected by the device-first facade. Keeps the reconciler\n * React-free and decoupled from runtime/persistence construction — it only\n * orchestrates *when* these run and routes their results into Layer A. The\n * host also supplies the coordinator lane and the clock, so the reconciler\n * imports no runtime code from the client, store, workflow, or coordinator\n * layers; `lint:architecture` enforces this.\n */\nexport interface ReconciliationHost extends InitialDocumentProbeHost {\n domainScope: DomainScope;\n /**\n * Register the reconciler's lane on the scope's sync coordinator. The host\n * owns the coordinator; the reconciler only schedules work on its lane.\n */\n registerLane: (key: string, config: SyncLaneConfig) => SyncLane;\n getRuntimeStatus: () => ReconciliationRuntimeStatus;\n /** True when this container has enough remote state to list documents. */\n canDiscoverContainerDocuments: (containerId: string) => boolean;\n /** Known container ids eligible for idle document reconciliation. */\n listKnownContainerIds: () => ReadonlyArray<string>;\n /** Known ids eligible after an automatic root-lane discovery hint. */\n listAutomaticRootCatchupContainerIds: () => ReadonlyArray<string>;\n /**\n * Discover + persist documents for every requested container through one\n * batched listing. Each lane's outcome is handed to `onOutcome` (awaited)\n * as soon as it applies, before later lanes apply; every outcome is also\n * returned.\n */\n discoverContainerDocuments: (\n requests: ReadonlyArray<ContainerDiscoveryRequest>,\n onOutcome: (outcome: ContainerDiscoveryOutcome) => Promise<void>,\n ) => Promise<ReadonlyArray<ContainerDiscoveryOutcome>>;\n /** Read a container's freshly-persisted summaries+links from SQLite. */\n loadContainerDelta: (\n containerId: string,\n ) => Promise<LocalProjectionReconciledDelta>;\n /** Push a reconciled delta into the local projection store. */\n applyReconciled: (delta: LocalProjectionReconciledDelta) => void;\n /**\n * Sync document bodies for a reconciled container. `force` (an explicit\n * refresh) revalidates registered ordinary documents and retries system\n * documents; otherwise only unopened system documents are synced, so a\n * background pass can materialize projection-owned content without eagerly\n * opening every ordinary document. A documentIds set limits forced pulls to\n * hint-named documents while still discovering new system content.\n */\n requestDocumentContentPull: (\n containerId: string,\n documents: ReadonlyArray<DocumentSummary>,\n force: boolean,\n documentIds?: ReadonlySet<string>,\n ) => void;\n /** Refresh the container tree from the server (explicit refresh). */\n refreshTree: () => Promise<void>;\n /** Refresh only the top-level root lane from the server. */\n refreshRootTree: () => Promise<void>;\n /** True if the destroyed-db error should be swallowed rather than surfaced. */\n isIgnorableError: (error: unknown) => boolean;\n /** Host diagnostics sink; bare runtimes do not structure errors. */\n logError?: ((message: string, error: unknown) => void) | undefined;\n}\n\nexport interface ReconciliationService {\n start: () => void;\n setActiveContainer: (containerId: string | null) => void;\n /** Force a listing; documentId limits content revalidation to that hint. */\n enqueueContainer: (\n containerId: string,\n priority: ReconcilePriority,\n force?: boolean,\n documentId?: string,\n ) => void;\n /** Queue known containers at idle priority. */\n enqueueIdleBackfill: () => void;\n /**\n * Forget which containers were reconciled this session so the next enqueue of\n * each re-validates against the server exactly once. Call on the\n * cannot-reconcile → can-reconcile edge (relogin/reconnect): the discovered\n * set is a per-session suppression cache, a previously-visited container may\n * have changed remotely, and initial-probe listings that exhausted their\n * retries need a fresh opportunity once the server is reachable again.\n */\n resetDiscovered: () => void;\n /**\n * Re-list root containers and reconcile the root catch-up set. By default a\n * request joins a sweep already in flight. With `freshListing`, the returned\n * sweep starts after this call: a discovery event (a root shared with or\n * created for this user) must not be satisfied by a sweep that may have\n * listed roots before the event committed.\n */\n reconcileRootContainersNow: (options?: {\n readonly freshListing?: boolean;\n }) => Promise<void>;\n reconcileNow: () => Promise<void>;\n stop: () => void;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"serviceTypes.js","sourceRoot":"","sources":["serviceTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SyncLane, SyncLaneConfig } from \"../../data/sync/syncLaneConfig\";\nimport type { LocalProjectionReconciledDelta } from \"../../stores/local-projection\";\nimport type { InitialDocumentProbeHost } from \"./initialDocumentProbe\";\nimport type { ReconcilePriority } from \"./queue\";\n\n/** One container a reconciliation pass lists, with its per-lane callbacks. */\nexport interface ContainerDiscoveryRequest {\n readonly containerId: string;\n readonly onFullListing?:\n | ((documentIds: ReadonlyArray<string>) => void)\n | undefined;\n readonly onPendingDiscovery?: ((delayMs: number) => void) | undefined;\n}\n\n/** A discovered lane: `null` means it was not fully listed or applied nothing. */\nexport type ContainerDiscoveryOutcome =\n | {\n readonly containerId: string;\n readonly status: \"fulfilled\";\n readonly value: ReadonlyArray<DocumentSummary> | null;\n }\n | {\n readonly containerId: string;\n readonly reason: unknown;\n readonly status: \"rejected\";\n };\n\nexport interface ReconciliationRuntimeStatus {\n dbStatus: string;\n isAuthenticated: boolean;\n online: boolean;\n}\n\n/**\n * Host contract injected by the device-first facade. Keeps the reconciler\n * React-free and decoupled from runtime/persistence construction — it only\n * orchestrates *when* these run and routes their results into Layer A. The\n * host also supplies the coordinator lane and the clock, so the reconciler\n * imports no runtime code from the client, store, workflow, or coordinator\n * layers; `lint:architecture` enforces this.\n */\nexport interface ReconciliationHost extends InitialDocumentProbeHost {\n domainScope: DomainScope;\n /**\n * Register the reconciler's lane on the scope's sync coordinator. The host\n * owns the coordinator; the reconciler only schedules work on its lane.\n */\n registerLane: (key: string, config: SyncLaneConfig) => SyncLane;\n getRuntimeStatus: () => ReconciliationRuntimeStatus;\n /** True when this container has enough remote state to list documents. */\n canDiscoverContainerDocuments: (containerId: string) => boolean;\n /** Known container ids eligible for idle document reconciliation. */\n listKnownContainerIds: () => ReadonlyArray<string>;\n /** Known ids eligible after an automatic root-lane discovery hint. */\n listAutomaticRootCatchupContainerIds: () => ReadonlyArray<string>;\n /**\n * Discover + persist documents for every requested container through one\n * batched listing. Each lane's outcome is handed to `onOutcome` (awaited)\n * as soon as it applies, before later lanes apply; every outcome is also\n * returned.\n */\n discoverContainerDocuments: (\n requests: ReadonlyArray<ContainerDiscoveryRequest>,\n onOutcome: (outcome: ContainerDiscoveryOutcome) => Promise<void>,\n ) => Promise<ReadonlyArray<ContainerDiscoveryOutcome>>;\n /** Read a container's freshly-persisted summaries+links from SQLite. */\n loadContainerDelta: (\n containerId: string,\n ) => Promise<LocalProjectionReconciledDelta>;\n /** Push a reconciled delta into the local projection store. */\n applyReconciled: (delta: LocalProjectionReconciledDelta) => void;\n /**\n * Sync document bodies for a reconciled container. `force` (an explicit\n * refresh) revalidates registered ordinary documents and retries system\n * documents; otherwise only unopened system documents are synced, so a\n * background pass can materialize projection-owned content without eagerly\n * opening every ordinary document. A documentIds set limits forced pulls to\n * hint-named documents while still discovering new system content.\n */\n requestDocumentContentPull: (\n containerId: string,\n documents: ReadonlyArray<DocumentSummary>,\n force: boolean,\n documentIds?: ReadonlySet<string>,\n ) => void;\n /** Refresh the container tree from the server (explicit refresh). */\n refreshTree: () => Promise<void>;\n /** Refresh only the top-level root lane from the server. */\n refreshRootTree: () => Promise<void>;\n /** True if the destroyed-db error should be swallowed rather than surfaced. */\n isIgnorableError: (error: unknown) => boolean;\n /** Host diagnostics sink; bare runtimes do not structure errors. */\n logError?: ((message: string, error: unknown) => void) | undefined;\n}\n\nexport interface ReconciliationService {\n start: () => void;\n setActiveContainer: (containerId: string | null) => void;\n /** Force a listing; documentId limits content revalidation to that hint. */\n enqueueContainer: (\n containerId: string,\n priority: ReconcilePriority,\n force?: boolean,\n documentId?: string,\n ) => void;\n /** Queue known containers at idle priority. */\n enqueueIdleBackfill: () => void;\n /**\n * Forget which containers were reconciled this session so the next enqueue of\n * each re-validates against the server exactly once. Call on the\n * cannot-reconcile → can-reconcile edge (relogin/reconnect): the discovered\n * set is a per-session suppression cache, a previously-visited container may\n * have changed remotely, and initial-probe listings that exhausted their\n * retries need a fresh opportunity once the server is reachable again.\n */\n resetDiscovered: () => void;\n /**\n * Re-list root containers and reconcile the root catch-up set. By default a\n * request joins a sweep already in flight. With `freshListing`, the returned\n * sweep starts after this call: a discovery event (a root shared with or\n * created for this user) must not be satisfied by a sweep that may have\n * listed roots before the event committed.\n */\n reconcileRootContainersNow: (options?: {\n readonly freshListing?: boolean;\n }) => Promise<void>;\n /**\n * Refresh the whole tree and reconcile every known container. With\n * `freshListing`, never join a sweep that already started listing: one\n * queues behind it instead, so the listing reflects a change made after.\n */\n reconcileNow: (options?: {\n readonly freshListing?: boolean;\n }) => Promise<void>;\n stop: () => void;\n}\n"]}
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
2
2
|
import type { PendingWriteQueueItem } from "./pendingWritesTypes.js";
|
|
3
3
|
export type { PendingWriteQueueItem, PendingWriteQueueItemStatus, PendingWriteQueueObjectKind, PendingWriteQueueOperation, PendingWriteQueueOperationKind, PendingWriteQueueOperationStatus, } from "./pendingWritesTypes.js";
|
|
4
|
+
/**
|
|
5
|
+
* Whether an item holds local work that still has to upload. A revalidation
|
|
6
|
+
* item only reports a failed read and carries no local writes.
|
|
7
|
+
*/
|
|
8
|
+
export declare function carriesLocalWrites(item: PendingWriteQueueItem): boolean;
|
|
4
9
|
/**
|
|
5
10
|
* List identity-wide local state that still requires a remote write. The
|
|
6
11
|
* returned diagnostic contains only navigation/display metadata and aggregate
|
|
@@ -9,6 +9,13 @@ import { defaultContainerContentsPersistence } from "../containerPersistence.js"
|
|
|
9
9
|
import { groupPendingWriteCandidates } from "./aggregation.js";
|
|
10
10
|
import { hasDeferredTailScopeWork, listDeferredPendingWriteCandidates, } from "./deferredTails.js";
|
|
11
11
|
import { listPersistedPendingWriteCandidates } from "./sources.js";
|
|
12
|
+
/**
|
|
13
|
+
* Whether an item holds local work that still has to upload. A revalidation
|
|
14
|
+
* item only reports a failed read and carries no local writes.
|
|
15
|
+
*/
|
|
16
|
+
export function carriesLocalWrites(item) {
|
|
17
|
+
return item.operations.some((operation) => operation.kind !== "revalidation");
|
|
18
|
+
}
|
|
12
19
|
/**
|
|
13
20
|
* List identity-wide local state that still requires a remote write. The
|
|
14
21
|
* returned diagnostic contains only navigation/display metadata and aggregate
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EACL,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EACL,6BAA6B,EAC7B,cAAc,EACd,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACL,wBAAwB,EACxB,kCAAkC,GACnC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,mCAAmC,EAAE,MAAM,WAAW,CAAC;AAWhE;;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AAC;IACL,CAAC;IACD,yEAAyE;IACzE,0EAA0E;IAC1E,sEAAsE;IACtE,wEAAwE;IACxE,yEAAyE;IACzE,IAAI,MAAM,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,CAAC;QAC7C,MAAM,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,KAAK,UAAU,kBAAkB,CAC/B,OAAgB,EAChB,KAA2C;IAE3C,MAAM,eAAe,CAAC,OAAO,EAAE;QAC7B,GAAG,cAAc;QACjB,GAAG,6BAA6B;KACjC,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,OAAO,CACxB;;;;;;;;;;;;gCAY4B,kBAAkB,CAAC,iBAAiB;;;;;;;;;aASvD,EACT;QACE,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CACF,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,sEAAsE;IACtE,kEAAkE;IAClE,iCAAiC;IACjC,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n clearDocumentSyncFailure,\n resetDocumentPendingUpdateRekeyBudget,\n} from \"../../../data/persistence/documents/records\";\nimport {\n documentPlacementIntentTables,\n documentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n await resetDocumentPendingUpdateRekeyBudget(execSql, scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await clearDocumentSyncFailure(execSql, scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EACL,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EACL,6BAA6B,EAC7B,cAAc,EACd,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACL,wBAAwB,EACxB,kCAAkC,GACnC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,mCAAmC,EAAE,MAAM,WAAW,CAAC;AAWhE;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,IAA2B;IAC5D,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,cAAc,CAAC,CAAC;AAChF,CA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B,CAAC,CAAC;IACL,CAAC;IACD,yEAAyE;IACzE,0EAA0E;IAC1E,sEAAsE;IACtE,wEAAwE;IACxE,yEAAyE;IACzE,IAAI,MAAM,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,CAAC;QAC7C,MAAM,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,KAAK,UAAU,kBAAkB,CAC/B,OAAgB,EAChB,KAA2C;IAE3C,MAAM,eAAe,CAAC,OAAO,EAAE;QAC7B,GAAG,cAAc;QACjB,GAAG,6BAA6B;KACjC,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,OAAO,CACxB;;;;;;;;;;;;gCAY4B,kBAAkB,CAAC,iBAAiB;;;;;;;;;aASvD,EACT;QACE,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CACF,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,sEAAsE;IACtE,kEAAkE;IAClE,iCAAiC;IACjC,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n clearDocumentSyncFailure,\n resetDocumentPendingUpdateRekeyBudget,\n} from \"../../../data/persistence/documents/records\";\nimport {\n documentPlacementIntentTables,\n documentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * Whether an item holds local work that still has to upload. A revalidation\n * item only reports a failed read and carries no local writes.\n */\nexport function carriesLocalWrites(item: PendingWriteQueueItem): boolean {\n return item.operations.some((operation) => operation.kind !== \"revalidation\");\n}\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n await resetDocumentPendingUpdateRekeyBudget(execSql, scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await clearDocumentSyncFailure(execSql, scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
|
|
@@ -3,6 +3,7 @@ import { finishRemoteHydration } from "./completeHydration.js";
|
|
|
3
3
|
import { createContainerChildIndex } from "./lanes/childIndex.js";
|
|
4
4
|
import { createContainerParentHydrationQueue } from "./lanes/parentLaneQueue.js";
|
|
5
5
|
import { cacheRemoteContainerPrincipalPolicies } from "./principalPolicyCache.js";
|
|
6
|
+
import { loadPausedContainerFilter } from "./remoteContainers/organizationSyncPauseFilter.js";
|
|
6
7
|
import { canHydrateRemoteContainers, hydrateContainerParentLanes, } from "./remoteContainers/remoteContainerPageHydration.js";
|
|
7
8
|
import { listRemoteContainerIdsWithPendingMetadataUpdates, listRemoteContainerIdsWithPendingStructuralIntents, upsertIsolatedRemoteContainerState, } from "./remoteContainers/remoteContainerState.js";
|
|
8
9
|
export class StaleRemoteHydrationError extends Error {
|
|
@@ -61,6 +62,11 @@ async function upsertQueuedRemoteContainer(input) {
|
|
|
61
62
|
!isCurrentQueuedRemoteContainer(generation, generationByContainerId, queue, queuedRemoteContainer)) {
|
|
62
63
|
return false;
|
|
63
64
|
}
|
|
65
|
+
// A paused organization's container is acknowledged without being stored,
|
|
66
|
+
// including when the pause lands while the commit is in flight.
|
|
67
|
+
const isPaused = await loadPausedContainerFilter(state);
|
|
68
|
+
if (isPaused(queuedRemoteContainer))
|
|
69
|
+
return true;
|
|
64
70
|
const tombstones = await state.persistence.loadContainerHydrationTombstones(state.runtime.infra.execSql);
|
|
65
71
|
// A refused folder is reported and acknowledged; the batch continues.
|
|
66
72
|
const upserted = await upsertIsolatedRemoteContainerState({
|
|
@@ -69,7 +75,7 @@ async function upsertQueuedRemoteContainer(input) {
|
|
|
69
75
|
containerIdsWithPendingMetadataUpdates,
|
|
70
76
|
containerIdsWithPendingStructuralIntents,
|
|
71
77
|
host,
|
|
72
|
-
isCurrent: input.isCurrent,
|
|
78
|
+
isCurrent: () => input.isCurrent() && !isPaused(queuedRemoteContainer),
|
|
73
79
|
remoteContainer: queuedRemoteContainer,
|
|
74
80
|
state,
|
|
75
81
|
});
|