@tearleads/client-sdk 0.1.252 → 0.1.254

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.
Files changed (155) hide show
  1. package/Tearleads.js +3 -3
  2. package/Tearleads.js.map +1 -1
  3. package/client/containerContents/documentDiscovery.js +0 -2
  4. package/client/containerContents/documentDiscovery.js.map +1 -1
  5. package/client/containerContents/index.d.ts +2 -0
  6. package/client/containerContents/index.js +4 -9
  7. package/client/containerContents/index.js.map +1 -1
  8. package/client/containerContents/storeRuntime.d.ts +17 -0
  9. package/client/containerContents/storeRuntime.js +31 -0
  10. package/client/containerContents/storeRuntime.js.map +1 -0
  11. package/client/deviceFirst/index.d.ts +2 -3
  12. package/client/deviceFirst/index.js +44 -22
  13. package/client/deviceFirst/index.js.map +1 -1
  14. package/client/runtime/workflowRuntime.d.ts +2 -0
  15. package/client/runtime/workflowRuntime.js +13 -6
  16. package/client/runtime/workflowRuntime.js.map +1 -1
  17. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +7 -10
  18. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  19. package/data/persistence/container-contents/containerDeletionPersistence.js +5 -1
  20. package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
  21. package/data/persistence/container-contents/containerHydrationPersistence.js +1 -1
  22. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  23. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +11 -4
  24. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  25. package/data/persistence/container-contents/containerRemovalMetadata.js +47 -0
  26. package/data/persistence/container-contents/containerRemovalMetadata.js.map +1 -0
  27. package/data/persistence/container-contents/containerRemovalPlacements.js +22 -0
  28. package/data/persistence/container-contents/containerRemovalPlacements.js.map +1 -0
  29. package/data/persistence/container-contents/containerSyncWatermarkPersistence.d.ts +2 -1
  30. package/data/persistence/container-contents/containerSyncWatermarkPersistence.js +10 -2
  31. package/data/persistence/container-contents/containerSyncWatermarkPersistence.js.map +1 -1
  32. package/data/persistence/documents/documentDiscoveryCandidate.d.ts +1 -0
  33. package/data/persistence/documents/documentDiscoveryCandidate.js +3 -1
  34. package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
  35. package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +1 -1
  36. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +16 -4
  37. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  38. package/data/sqlite/migrations/localSchemaMigrations.js +11 -0
  39. package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
  40. package/data/sqlite/schema/containerSyncWatermarkSchema.js +6 -3
  41. package/data/sqlite/schema/containerSyncWatermarkSchema.js.map +1 -1
  42. package/data/sqlite/schema/index.d.ts +17 -0
  43. package/data/sync/syncCoordinator.js +17 -10
  44. package/data/sync/syncCoordinator.js.map +1 -1
  45. package/internal/api-client/ApiClient.d.ts +1 -0
  46. package/internal/api-client/client/apiClientContext.d.ts +1 -0
  47. package/internal/api-client/client/containerReads.d.ts +1 -0
  48. package/internal/api-client/requestInternals.js +14 -6
  49. package/internal/api-client/requestInternals.js.map +1 -1
  50. package/internal/validators/operation/containerReads.d.ts +29 -2
  51. package/internal/validators/operation/containerReads.js +2 -1
  52. package/internal/validators/operation/containerReads.js.map +1 -1
  53. package/internal/validators/request/containerDocumentLanes.d.ts +7 -0
  54. package/internal/validators/request/containerDocumentLanes.js +6 -0
  55. package/internal/validators/request/containerDocumentLanes.js.map +1 -1
  56. package/internal/validators/response/container.d.ts +8 -0
  57. package/internal/validators/response/container.js +1 -0
  58. package/internal/validators/response/container.js.map +1 -1
  59. package/internal/validators/response/containerParentLanes.d.ts +2 -0
  60. package/package.json +1 -1
  61. package/stores/container-contents/containerContentsStore.d.ts +3 -9
  62. package/stores/container-contents/containerContentsStore.js +24 -21
  63. package/stores/container-contents/containerContentsStore.js.map +1 -1
  64. package/stores/container-contents/containerState/storeScope.js +6 -0
  65. package/stores/container-contents/containerState/storeScope.js.map +1 -0
  66. package/stores/container-contents/hydration/backgroundHydration.js +2 -1
  67. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
  68. package/stores/container-contents/hydration/reconnectRefresh.d.ts +10 -0
  69. package/stores/container-contents/hydration/reconnectRefresh.js +68 -0
  70. package/stores/container-contents/hydration/reconnectRefresh.js.map +1 -0
  71. package/stores/container-contents/hydration/reconnectRefreshMachine.js +49 -0
  72. package/stores/container-contents/hydration/reconnectRefreshMachine.js.map +1 -0
  73. package/stores/container-contents/hydration/remoteHydrationRefresh.js +4 -1
  74. package/stores/container-contents/hydration/remoteHydrationRefresh.js.map +1 -1
  75. package/stores/container-contents/hydration/remoteHydrationRequest.js +79 -10
  76. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
  77. package/stores/container-contents/hydration/startupHydration.js +2 -9
  78. package/stores/container-contents/hydration/startupHydration.js.map +1 -1
  79. package/stores/container-contents/hydration/treeResetMachine.js +61 -0
  80. package/stores/container-contents/hydration/treeResetMachine.js.map +1 -0
  81. package/stores/container-contents/localRefresh.js +28 -12
  82. package/stores/container-contents/localRefresh.js.map +1 -1
  83. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +4 -1
  84. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -1
  85. package/stores/container-contents/remoteWrites/writeGeneration.js +5 -2
  86. package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -1
  87. package/stores/container-contents/state.d.ts +3 -7
  88. package/stores/container-contents/state.js +27 -16
  89. package/stores/container-contents/state.js.map +1 -1
  90. package/stores/container-contents/syncAgent/index.d.ts +7 -2
  91. package/stores/container-contents/syncAgent/index.js +77 -49
  92. package/stores/container-contents/syncAgent/index.js.map +1 -1
  93. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -2
  94. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  95. package/stores/container-contents/syncAgent/syncLaneIteration.js +6 -3
  96. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  97. package/stores/local-projection/localProjectionStore.js +24 -15
  98. package/stores/local-projection/localProjectionStore.js.map +1 -1
  99. package/stores/local-projection/registry.js +2 -2
  100. package/stores/local-projection/registry.js.map +1 -1
  101. package/workflows/container-contents/container-state/create/createChild.js +3 -15
  102. package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
  103. package/workflows/container-contents/containerPersistence.d.ts +4 -8
  104. package/workflows/container-contents/containerPersistence.js +22 -12
  105. package/workflows/container-contents/containerPersistence.js.map +1 -1
  106. package/workflows/container-contents/documentDiscovery/containerDocumentListing.js +52 -4
  107. package/workflows/container-contents/documentDiscovery/containerDocumentListing.js.map +1 -1
  108. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js +4 -2
  109. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js.map +1 -1
  110. package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js +17 -12
  111. package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
  112. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.js.map +1 -1
  113. package/workflows/container-contents/documentDiscovery/publicationWatermark.js +15 -0
  114. package/workflows/container-contents/documentDiscovery/publicationWatermark.js.map +1 -0
  115. package/workflows/container-contents/localState.js +3 -0
  116. package/workflows/container-contents/localState.js.map +1 -1
  117. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.d.ts +12 -0
  118. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +93 -0
  119. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -0
  120. package/workflows/container-contents/remoteHydration/index.d.ts +3 -11
  121. package/workflows/container-contents/remoteHydration/index.js +17 -66
  122. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  123. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
  124. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
  125. package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js +25 -0
  126. package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js.map +1 -0
  127. package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js +107 -0
  128. package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js.map +1 -0
  129. package/workflows/container-contents/remoteHydration/principalPolicyCache.js +57 -5
  130. package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
  131. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +129 -84
  132. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  133. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +32 -10
  134. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  135. package/workflows/container-contents/remoteHydration/tombstoneApplication.js +67 -24
  136. package/workflows/container-contents/remoteHydration/tombstoneApplication.js.map +1 -1
  137. package/workflows/container-contents/remoteHydration/types.d.ts +16 -1
  138. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  139. package/workflows/container-contents/remoteReset/remoteResetCursorScope.js +3 -3
  140. package/workflows/container-contents/remoteReset/remoteResetCursorScope.js.map +1 -1
  141. package/workflows/container-contents/runtime.d.ts +3 -0
  142. package/workflows/container-contents/runtime.js.map +1 -1
  143. package/workflows/container-contents/storedContainerState.js +17 -7
  144. package/workflows/container-contents/storedContainerState.js.map +1 -1
  145. package/workflows/container-contents/syncLane.d.ts +1 -0
  146. package/workflows/container-contents/syncLane.js +9 -1
  147. package/workflows/container-contents/syncLane.js.map +1 -1
  148. package/workflows/container-contents/syncPause/discoveryGuard.js +6 -2
  149. package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
  150. package/workflows/container-contents/tombstones/documentTombstoneGate.js +6 -3
  151. package/workflows/container-contents/tombstones/documentTombstoneGate.js.map +1 -1
  152. package/workflows/shared/runtimeInput.d.ts +2 -0
  153. package/workflows/shared/runtimeInput.js.map +1 -1
  154. package/workflows/container-contents/remoteHydration/completeHydration.js +0 -25
  155. package/workflows/container-contents/remoteHydration/completeHydration.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAE5F,OAAO,EACL,0BAA0B,EAC1B,iCAAiC,GAClC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,oCAAoC,EAAE,MAAM,sCAAsC,CAAC;AAC5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,EAEL,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,uCAAuC,EAAE,MAAM,qCAAqC,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,GACpC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,iCAAiC,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EAAE,wCAAwC,EAAE,MAAM,0CAA0C,CAAC;AACpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EAAE,+CAA+C,EAAE,MAAM,UAAU,CAAC;AAK3E,OAAO,EAAE,sCAAsC,EAAE,MAAM,qBAAqB,CAAC;AAU7E,SAAS,iCAAiC,CACxC,KAAsC;IAEtC,KAAK,CAAC,QAAQ,EAAE,WAAW,EAAE,CAAC;AAChC,CAAC;AAED,KAAK,UAAU,gCAAgC,CAAC,KAO/C;IACC,MAAM,EACJ,kBAAkB,EAClB,IAAI,EACJ,SAAS,EACT,kBAAkB,EAClB,YAAY,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AAE,KAAK,EAAE,CAAC;QAC1E,OAAO;QACP,eAAe,EAAE,CAAC,OAAO,EAAE,EAAE,CAC3B,0BAA0B,CAAC;YACzB,0BAA0B,EAAE,OAAO,EAAE,0BAA0B;YAC/D,SAAS,EAAE,OAAO,EAAE,SAAS;YAC7B,gBAAgB,EAAE,uBAAuB;YACzC,KAAK;SACN,CAAC;QACJ,sBAAsB,EAAE,gBAAgB;QACxC,uBAAuB,EAAE,iBAAiB;QAC1C,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["import { loadLocalContainerStates } from \"../../../workflows/container-contents/localState\";\nimport type { RemoteContainerHydrationHost } from \"../../../workflows/container-contents/remoteHydration\";\nimport {\n isDatabaseUnavailableError,\n registerContainerContentsSyncLane,\n} from \"../../../workflows/container-contents/syncLane\";\nimport { loadOrganizationSyncPausesBeforeSync } from \"../../../workflows/sync/coordination\";\nimport { createRestoredAccessReconciler } from \"../accessRestorationSweep\";\nimport { primeStoreDocumentSubtree } from \"../documentWork/documentRecovery\";\nimport { observeContainerBackgroundHydration } from \"../hydration/backgroundHydration\";\nimport {\n type RemoteHydrationRefreshOptions,\n refreshAllRemoteHydration,\n refreshRootRemoteHydration,\n} from \"../hydration/remoteHydrationRefresh\";\nimport { requestContainerContentsRemoteHydration } from \"../hydration/remoteHydrationRequest\";\nimport {\n hasStartupContainerSyncWork,\n scheduleStaleStartupRemoteHydration,\n} from \"../hydration/startupHydration\";\nimport { refreshLocalContainerStates } from \"../localRefresh\";\nimport { getContainerContentsStoreLogLabel } from \"../logLabel\";\nimport { createRemoteContainerIngestionController } from \"../remoteEvents/remoteContainerIngestion\";\nimport { handleContainerContentsRemoteEvents } from \"../remoteEvents/remoteEventSync\";\nimport { consumePendingContainerContentsReconnectRefresh } from \"../state\";\nimport type {\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n} from \"./syncAgentTypes\";\nimport { runContainerContentsStoreSyncIteration } from \"./syncLaneIteration\";\n\nexport type { ContainerState } from \"../../../workflows/container-contents/remoteHydration\";\nexport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n RefreshRootLaneOptions,\n} from \"./syncAgentTypes\";\n\nfunction requestContainerContentsStoreSync(\n state: ContainerContentsStoreSyncState,\n) {\n state.syncLane?.requestSync();\n}\n\nasync function initializeContainerContentsStore(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}) {\n const {\n handleRemoteEvents,\n host,\n isCurrent,\n resumeRecoveryWork,\n scheduleSync,\n state,\n } = input;\n const persistence = state.persistence;\n const loadRuntime = state.runtime;\n if (loadRuntime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n await loadOrganizationSyncPausesBeforeSync({\n domainScope: loadRuntime.state.domainScope,\n execSql: loadRuntime.infra.execSql,\n log: loadRuntime.util.log,\n });\n const localContainerStates = await loadLocalContainerStates({\n persistence,\n runtime: loadRuntime,\n });\n if (!isCurrent()) {\n return;\n }\n\n for (const containerState of localContainerStates) {\n state.containersById.set(containerState.container.id, containerState);\n }\n\n state.initialized = true;\n\n const shouldScheduleStaleRootRecovery =\n await scheduleStaleStartupRemoteHydration({\n isCurrent,\n requestHydration: () =>\n requestContainerContentsRemoteHydration({\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n }),\n state,\n });\n if (!isCurrent()) {\n return;\n }\n const runtime = state.runtime;\n const hasPendingRestorationSweep =\n typeof runtime.auth.userId === \"string\" &&\n (\n await persistence.listDormantMetadataSweepRequests(\n loadRuntime.infra.execSql,\n runtime.auth.userId,\n )\n ).length > 0;\n if (!isCurrent()) {\n return;\n }\n\n host.updateSnapshot();\n handleRemoteEvents();\n\n runtime.util.log(\n `${getContainerContentsStoreLogLabel(state)}: loaded ${state.containersById.size} container(s)`,\n );\n\n const currentRuntime = state.runtime;\n if (currentRuntime.auth.isAuthenticated && currentRuntime.state.online) {\n const hasStartupWork =\n shouldScheduleStaleRootRecovery ||\n hasPendingRestorationSweep ||\n (await hasStartupContainerSyncWork(state));\n if (!isCurrent() || !hasStartupWork) {\n return;\n }\n currentRuntime.util.log(\n shouldScheduleStaleRootRecovery\n ? `${getContainerContentsStoreLogLabel(state)}: startup detected stale root recovery; scheduling lane pass`\n : `${getContainerContentsStoreLogLabel(state)}: startup detected durable sync work; scheduling lane pass`,\n );\n scheduleSync();\n }\n}\n\nfunction waitForStaleLocalRefreshBeforeInitialization(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n refreshAfterReconnect: () => Promise<boolean>;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}): boolean {\n const { state } = input;\n const activeRefresh = state.localContainerRefreshPromise;\n if (\n !activeRefresh ||\n (state.localContainerRefreshGeneration === state.lifecycleGeneration &&\n state.localContainerRefreshStructuralGeneration ===\n state.structuralGeneration)\n ) {\n return false;\n }\n\n const lifecycleGeneration = state.lifecycleGeneration;\n state.initializeGeneration = lifecycleGeneration;\n const releaseInitializationBarrier = () => {\n if (state.initializePromise !== initializationBarrier) {\n return;\n }\n state.initializePromise = null;\n state.initializeGeneration = null;\n if (state.runtime.infra.dbStatus === \"ready\") {\n ensureContainerContentsStoreInitialized(input);\n }\n };\n const initializationBarrier = activeRefresh.then(\n releaseInitializationBarrier,\n releaseInitializationBarrier,\n );\n state.initializePromise = initializationBarrier;\n return true;\n}\n\nfunction ensureContainerContentsStoreInitialized(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n refreshAfterReconnect: () => Promise<boolean>;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}) {\n const { handleRemoteEvents, host, resumeRecoveryWork, scheduleSync, state } =\n input;\n if (state.initialized || state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n if (state.initializePromise) {\n return;\n }\n if (waitForStaleLocalRefreshBeforeInitialization(input)) {\n return;\n }\n\n const lifecycleGeneration = state.lifecycleGeneration;\n const persistence = state.persistence;\n const execSql = state.runtime.infra.execSql;\n const isCurrent = () =>\n state.lifecycleGeneration === lifecycleGeneration &&\n state.persistence === persistence &&\n state.runtime.infra.execSql === execSql;\n state.initializeGeneration = lifecycleGeneration;\n const initializePromise = initializeContainerContentsStore({\n handleRemoteEvents,\n host,\n isCurrent,\n resumeRecoveryWork,\n scheduleSync,\n state,\n })\n .catch((error: unknown) => {\n if (!isCurrent() || isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n })\n .finally(() => {\n if (state.initializePromise !== initializePromise) {\n return;\n }\n state.initializePromise = null;\n state.initializeGeneration = null;\n if (isCurrent()) {\n consumePendingContainerContentsReconnectRefresh(\n state,\n input.refreshAfterReconnect,\n );\n } else if (state.runtime.infra.dbStatus === \"ready\") {\n ensureContainerContentsStoreInitialized(input);\n }\n });\n state.initializePromise = initializePromise;\n}\n\n// Read the runtime lazily: updateRuntime replaces state.runtime, so a\n// reference captured at lane registration would report into a dead identity's\n// host. Returns the host's result: both callbacks are declared `=> void` but\n// may be async, and the lane reporter only catches a rejection it is handed.\nfunction logSyncLaneFailure(\n state: ContainerContentsStoreSyncState,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = state.runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nfunction createHydrationRequester(input: {\n host: RemoteContainerHydrationHost;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}): ContainerContentsStoreSyncAgent[\"requestRemoteHydration\"] {\n return (options = {}) =>\n requestContainerContentsRemoteHydration({\n ...input,\n followDiscoveredParentLanes: options.followDiscoveredParentLanes,\n parentIds: options.parentIds,\n resetAllLaneWatermarks: options.resetAllLaneWatermarks,\n });\n}\n\nexport function createContainerContentsStoreSyncAgent(input: {\n host: RemoteContainerHydrationHost;\n state: ContainerContentsStoreSyncState;\n}): ContainerContentsStoreSyncAgent {\n const { host, state } = input;\n const scheduleSync = () => requestContainerContentsStoreSync(state);\n const remoteContainerIngestion = createRemoteContainerIngestionController({\n host,\n scheduleSync,\n state,\n });\n const resumeRecoveryWork = remoteContainerIngestion.resumeInterruptedWork;\n\n const requestHydration = createHydrationRequester({\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n const requestRefreshHydration = (options: RemoteHydrationRefreshOptions) =>\n requestContainerContentsRemoteHydration({\n ...options,\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n const scheduleHydration = (\n options?: Parameters<typeof requestHydration>[0],\n ) => observeContainerBackgroundHydration(state, requestHydration(options));\n const refresh: ContainerContentsStoreSyncAgent[\"refresh\"] = (options) =>\n refreshAllRemoteHydration({\n // Explicit user refresh must rediscover children hidden by unsigned hints.\n resetAllLaneWatermarks: options?.resetAllLaneWatermarks,\n requestHydration: requestRefreshHydration,\n state,\n });\n const handleRemoteEvents = () =>\n handleContainerContentsRemoteEvents({\n requestHydration,\n scheduleSync,\n state,\n });\n const reconcileRestoredAccess = createRestoredAccessReconciler({\n requestHydration: requestRefreshHydration,\n state,\n });\n\n state.syncLane = registerContainerContentsSyncLane({\n domainScope: state.runtime.state.domainScope,\n logError: (message, error) => logSyncLaneFailure(state, message, error),\n run: (policyOperation) =>\n runContainerContentsStoreSyncIteration({\n host,\n policyOperation,\n reconcileRestoredAccess,\n requestRemoteReconciliation: (parentContainerId) => {\n scheduleHydration({\n followDiscoveredParentLanes: false,\n parentIds: [parentContainerId],\n });\n },\n state,\n }),\n });\n\n return {\n ensureInitialized: () => {\n ensureContainerContentsStoreInitialized({\n handleRemoteEvents,\n host,\n refreshAfterReconnect: refresh,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n void resumeRecoveryWork();\n },\n handleRemoteEvents,\n ingestRemoteContainer: remoteContainerIngestion.ingest,\n primeDocumentsForSharedSubtree: (rootContainerId, isCurrent) =>\n primeStoreDocumentSubtree(state, rootContainerId, isCurrent),\n refreshLocalContainers: () => refreshLocalContainerStates({ host, state }),\n refresh,\n refreshRootLane: (options) =>\n refreshRootRemoteHydration({\n includeActiveRootChildLane: options?.includeActiveRootChildLane,\n parentIds: options?.parentIds,\n requestHydration: requestRefreshHydration,\n state,\n }),\n requestRemoteHydration: requestHydration,\n scheduleRemoteHydration: scheduleHydration,\n scheduleSync,\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAK5F,OAAO,EACL,0BAA0B,EAC1B,iCAAiC,GAClC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,oCAAoC,EAAE,MAAM,sCAAsC,CAAC;AAC5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,EAEL,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,uCAAuC,EAAE,MAAM,qCAAqC,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,uBAAuB,GACxB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,iCAAiC,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EAAE,wCAAwC,EAAE,MAAM,0CAA0C,CAAC;AACpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EACL,+CAA+C,EAC/C,oBAAoB,GACrB,MAAM,UAAU,CAAC;AAKlB,OAAO,EAAE,sCAAsC,EAAE,MAAM,qBAAqB,CAAC;AAU7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C,kBAAkB;gBAClB,IAAI;gBACJ,qBAAqB,EAAE,OAAO;gBAC9B,kBAAkB;gBAClB,YAAY;gBACZ,KAAK;aACN,CAAC,CAAC;YACH,KAAK,kBAAkB,EAAE,CAAC;QAC5B,CAAC;QACD,kBAAkB;QAClB,qBAAqB,EAAE,wBAAwB,CAAC,MAAM;QACtD,8BAA8B,EAAE,CAAC,eAAe,EAAE,SAAS,EAAE,EAAE,CAC7D,yBAAyB,CAAC,KAAK,EAAE,eAAe,EAAE,SAAS,CAAC;QAC9D,sBAAsB,EAAE,GAAG,EAAE,CAAC,2BAA2B,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;QAC1E,OAAO;QACP,eAAe,EAAE,CAAC,OAAO,EAAE,EAAE,CAC3B,0BAA0B,CAAC;YACzB,0BAA0B,EAAE,OAAO,EAAE,0BAA0B;YAC/D,SAAS,EAAE,OAAO,EAAE,SAAS;YAC7B,gBAAgB,EAAE,uBAAuB;YACzC,KAAK;SACN,CAAC;QACJ,sBAAsB,EAAE,gBAAgB;QACxC,uBAAuB,EAAE,iBAAiB;QAC1C,YAAY;KACb,CAAC;IACF,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,qCAAqC,CACnD,KAAiB;IAEjB,MAAM,QAAQ,GAAG,sCAAsC,CAAC,KAAK,CAAC,CAAC;IAC/D,QAAQ,CAAC,YAAY,EAAE,CAAC;IACxB,OAAO,QAAQ,CAAC,KAAK,CAAC;AACxB,CAAC","sourcesContent":["import { loadLocalContainerStates } from \"../../../workflows/container-contents/localState\";\nimport type {\n ContainerState,\n RemoteContainerHydrationHost,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport {\n isDatabaseUnavailableError,\n registerContainerContentsSyncLane,\n} from \"../../../workflows/container-contents/syncLane\";\nimport { loadOrganizationSyncPausesBeforeSync } from \"../../../workflows/sync/coordination\";\nimport { createRestoredAccessReconciler } from \"../accessRestorationSweep\";\nimport { ownsContainerStore } from \"../containerState/storeScope\";\nimport { primeStoreDocumentSubtree } from \"../documentWork/documentRecovery\";\nimport { observeContainerBackgroundHydration } from \"../hydration/backgroundHydration\";\nimport {\n type RemoteHydrationRefreshOptions,\n refreshAllRemoteHydration,\n refreshRootRemoteHydration,\n} from \"../hydration/remoteHydrationRefresh\";\nimport { requestContainerContentsRemoteHydration } from \"../hydration/remoteHydrationRequest\";\nimport {\n hasStartupContainerSyncWork,\n inspectStartupHydration,\n} from \"../hydration/startupHydration\";\nimport { refreshLocalContainerStates } from \"../localRefresh\";\nimport { getContainerContentsStoreLogLabel } from \"../logLabel\";\nimport { createRemoteContainerIngestionController } from \"../remoteEvents/remoteContainerIngestion\";\nimport { handleContainerContentsRemoteEvents } from \"../remoteEvents/remoteEventSync\";\nimport {\n consumePendingContainerContentsReconnectRefresh,\n retireContainerStore,\n} from \"../state\";\nimport type {\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n} from \"./syncAgentTypes\";\nimport { runContainerContentsStoreSyncIteration } from \"./syncLaneIteration\";\n\nexport type { ContainerState } from \"../../../workflows/container-contents/remoteHydration\";\nexport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n RefreshRootLaneOptions,\n} from \"./syncAgentTypes\";\n\nfunction requestContainerContentsStoreSync(\n state: ContainerContentsStoreSyncState,\n) {\n state.syncLane?.requestSync();\n}\n\nfunction publishInitialContainers(\n state: ContainerContentsStoreSyncState,\n startup: {\n containersById: ReadonlyMap<string, ContainerState>;\n rootLaneHydrated: boolean;\n containerParentIdsNeedingHydration: ReadonlySet<string | null>;\n },\n): boolean {\n for (const [id, row] of startup.containersById) {\n state.containersById.set(id, row);\n }\n state.initialized = true;\n state.rootLaneHydrated = startup.rootLaneHydrated;\n for (const id of startup.containerParentIdsNeedingHydration) {\n state.containerParentIdsNeedingHydration.add(id);\n }\n return startup.containerParentIdsNeedingHydration.size > 0;\n}\n\nasync function initializeContainerContentsStore(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}) {\n const {\n handleRemoteEvents,\n host,\n isCurrent,\n resumeRecoveryWork,\n scheduleSync,\n state,\n } = input;\n const persistence = state.persistence;\n const loadRuntime = state.runtime;\n if (loadRuntime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n await loadOrganizationSyncPausesBeforeSync({\n domainScope: loadRuntime.state.domainScope,\n execSql: loadRuntime.infra.execSql,\n log: loadRuntime.util.log,\n });\n const localContainerStates = await loadLocalContainerStates({\n isCurrent,\n persistence,\n runtime: loadRuntime,\n });\n if (!isCurrent()) {\n return;\n }\n\n // Keep the local tree and marker reads private until this initialization\n // can publish them together. Another organization can take over between reads.\n const startup = {\n runtime: state.runtime,\n containersById: new Map(\n localContainerStates.map((row) => [row.container.id, row]),\n ),\n containerParentIdsNeedingHydration: new Set<string | null>(),\n rootLaneHydrated: state.rootLaneHydrated,\n };\n const shouldScheduleStaleRootRecovery = await inspectStartupHydration({\n isCurrent,\n state: startup,\n });\n if (!isCurrent()) return;\n const runtime = state.runtime;\n const hasPendingRestorationSweep =\n typeof runtime.auth.userId === \"string\" &&\n (\n await persistence.listDormantMetadataSweepRequests(\n loadRuntime.infra.execSql,\n runtime.auth.userId,\n )\n ).length > 0;\n if (!isCurrent()) {\n return;\n }\n\n if (publishInitialContainers(state, startup)) {\n observeContainerBackgroundHydration(\n state,\n requestContainerContentsRemoteHydration({\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n }),\n );\n }\n\n host.updateSnapshot();\n handleRemoteEvents();\n\n runtime.util.log(\n `${getContainerContentsStoreLogLabel(state)}: loaded ${state.containersById.size} container(s)`,\n );\n\n const currentRuntime = state.runtime;\n if (currentRuntime.auth.isAuthenticated && currentRuntime.state.online) {\n const hasStartupWork =\n shouldScheduleStaleRootRecovery ||\n hasPendingRestorationSweep ||\n (await hasStartupContainerSyncWork(state));\n if (!isCurrent() || !hasStartupWork) {\n return;\n }\n currentRuntime.util.log(\n shouldScheduleStaleRootRecovery\n ? `${getContainerContentsStoreLogLabel(state)}: startup detected stale root recovery; scheduling lane pass`\n : `${getContainerContentsStoreLogLabel(state)}: startup detected durable sync work; scheduling lane pass`,\n );\n scheduleSync();\n }\n}\n\nfunction waitForStaleLocalRefreshBeforeInitialization(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n refreshAfterReconnect: ContainerContentsStoreSyncAgent[\"refresh\"];\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}): boolean {\n const { state } = input;\n const activeRefresh = state.localContainerRefreshPromise;\n if (\n !activeRefresh ||\n (state.localContainerRefreshGeneration === state.lifecycleGeneration &&\n state.localContainerRefreshStructuralGeneration ===\n state.structuralGeneration)\n ) {\n return false;\n }\n\n const lifecycleGeneration = state.lifecycleGeneration;\n state.initializeGeneration = lifecycleGeneration;\n const releaseInitializationBarrier = () => {\n if (state.initializePromise !== initializationBarrier) {\n return;\n }\n state.initializePromise = null;\n state.initializeGeneration = null;\n if (state.runtime.infra.dbStatus === \"ready\") {\n ensureContainerContentsStoreInitialized(input);\n }\n };\n const initializationBarrier = activeRefresh.then(\n releaseInitializationBarrier,\n releaseInitializationBarrier,\n );\n state.initializePromise = initializationBarrier;\n return true;\n}\n\nfunction ensureContainerContentsStoreInitialized(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n refreshAfterReconnect: ContainerContentsStoreSyncAgent[\"refresh\"];\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}) {\n const { handleRemoteEvents, host, resumeRecoveryWork, scheduleSync, state } =\n input;\n if (state.initialized || state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n if (!ownsContainerStore(state) || state.initializePromise) {\n return;\n }\n if (waitForStaleLocalRefreshBeforeInitialization(input)) {\n return;\n }\n\n const lifecycleGeneration = state.lifecycleGeneration;\n // A first login adopts device-local rows on this executor. A later owner must reload them.\n const startedAnonymous = !state.runtime.auth.isAuthenticated;\n const writeGeneration = state.writeGeneration;\n const persistence = state.persistence;\n const execSql = state.runtime.infra.execSql;\n const isCurrent = () =>\n ownsContainerStore(state) &&\n (state.writeGeneration === writeGeneration ||\n (startedAnonymous &&\n state.runtime.auth.isAuthenticated &&\n state.writeGeneration === writeGeneration + 1)) &&\n state.lifecycleGeneration === lifecycleGeneration &&\n state.persistence === persistence &&\n state.runtime.infra.execSql === execSql;\n state.initializeGeneration = lifecycleGeneration;\n const initializePromise = initializeContainerContentsStore({\n handleRemoteEvents,\n host,\n isCurrent,\n resumeRecoveryWork,\n scheduleSync,\n state,\n })\n .catch((error: unknown) => {\n if (!isCurrent() || isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n })\n .finally(() => {\n if (state.initializePromise !== initializePromise) {\n return;\n }\n state.initializePromise = null;\n state.initializeGeneration = null;\n if (isCurrent()) {\n consumePendingContainerContentsReconnectRefresh(\n state,\n input.refreshAfterReconnect,\n );\n } else if (state.runtime.infra.dbStatus === \"ready\") {\n if (!state.snapshot.ready) state.initialized = false;\n ensureContainerContentsStoreInitialized(input);\n }\n });\n state.initializePromise = initializePromise;\n}\n\n// Read the runtime lazily: updateRuntime replaces state.runtime, so a\n// reference captured at lane registration would report into a dead identity's\n// host. Returns the host's result: both callbacks are declared `=> void` but\n// may be async, and the lane reporter only catches a rejection it is handed.\nfunction logSyncLaneFailure(\n state: ContainerContentsStoreSyncState,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = state.runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nfunction createHydrationRequester(input: {\n host: RemoteContainerHydrationHost;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}): ContainerContentsStoreSyncAgent[\"requestRemoteHydration\"] {\n return (options = {}) =>\n requestContainerContentsRemoteHydration({\n ...input,\n followDiscoveredParentLanes: options.followDiscoveredParentLanes,\n parentIds: options.parentIds,\n resetAllLaneWatermarks: options.resetAllLaneWatermarks,\n });\n}\n\ninterface AgentInput {\n host: RemoteContainerHydrationHost;\n state: ContainerContentsStoreSyncState;\n}\n\nexport function prepareContainerContentsStoreSyncAgent(input: AgentInput): {\n agent: ContainerContentsStoreSyncAgent;\n registerLane: () => void;\n} {\n const { host, state } = input;\n const scheduleSync = () => requestContainerContentsStoreSync(state);\n const remoteContainerIngestion = createRemoteContainerIngestionController({\n host,\n scheduleSync,\n state,\n });\n const resumeRecoveryWork = remoteContainerIngestion.resumeInterruptedWork;\n\n const hydrationInput = { host, resumeRecoveryWork, scheduleSync, state };\n const requestHydration = createHydrationRequester(hydrationInput);\n const requestRefreshHydration = (options: RemoteHydrationRefreshOptions) =>\n requestContainerContentsRemoteHydration({ ...hydrationInput, ...options });\n const scheduleHydration = (\n options?: Parameters<typeof requestHydration>[0],\n ) => observeContainerBackgroundHydration(state, requestHydration(options));\n const refresh: ContainerContentsStoreSyncAgent[\"refresh\"] = (options) =>\n refreshAllRemoteHydration({\n // Explicit user refresh must rediscover children hidden by unsigned hints.\n resetAllLaneWatermarks: options?.resetAllLaneWatermarks,\n reconnect: options?.reconnect,\n requestHydration: requestRefreshHydration,\n state,\n });\n const handleRemoteEvents = () =>\n handleContainerContentsRemoteEvents({\n requestHydration,\n scheduleSync,\n state,\n });\n const reconcileRestoredAccess = createRestoredAccessReconciler({\n requestHydration: requestRefreshHydration,\n state,\n });\n\n const registerLane = () => {\n state.syncLane = registerContainerContentsSyncLane({\n onDispose: () => retireContainerStore(state),\n domainScope: state.runtime.state.domainScope,\n logError: (message, error) => logSyncLaneFailure(state, message, error),\n run: (policyOperation) =>\n runContainerContentsStoreSyncIteration({\n host,\n policyOperation,\n reconcileRestoredAccess,\n requestRemoteReconciliation: (parentContainerId) => {\n scheduleHydration({\n followDiscoveredParentLanes: false,\n parentIds: [parentContainerId],\n });\n },\n state,\n }),\n });\n };\n\n const agent: ContainerContentsStoreSyncAgent = {\n ensureInitialized: () => {\n ensureContainerContentsStoreInitialized({\n handleRemoteEvents,\n host,\n refreshAfterReconnect: refresh,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n void resumeRecoveryWork();\n },\n handleRemoteEvents,\n ingestRemoteContainer: remoteContainerIngestion.ingest,\n primeDocumentsForSharedSubtree: (rootContainerId, isCurrent) =>\n primeStoreDocumentSubtree(state, rootContainerId, isCurrent),\n refreshLocalContainers: () => refreshLocalContainerStates({ host, state }),\n refresh,\n refreshRootLane: (options) =>\n refreshRootRemoteHydration({\n includeActiveRootChildLane: options?.includeActiveRootChildLane,\n parentIds: options?.parentIds,\n requestHydration: requestRefreshHydration,\n state,\n }),\n requestRemoteHydration: requestHydration,\n scheduleRemoteHydration: scheduleHydration,\n scheduleSync,\n };\n return { agent, registerLane };\n}\n\nexport function createContainerContentsStoreSyncAgent(\n input: AgentInput,\n): ContainerContentsStoreSyncAgent {\n const prepared = prepareContainerContentsStoreSyncAgent(input);\n prepared.registerLane();\n return prepared.agent;\n}\n"]}
@@ -1,8 +1,9 @@
1
1
  import type { ContainerContentsPersistence } from "../../../workflows/container-contents/containerPersistence.js";
2
2
  import type { ContainerContentsProjectionUserKeyResolver } from "../../../workflows/container-contents/projectionKeys.js";
3
- import type { ContainerState, RemoteContainer } from "../../../workflows/container-contents/remoteHydration/index.js";
3
+ import type { ContainerState, ReconnectCrawl, RemoteContainer } from "../../../workflows/container-contents/remoteHydration/index.js";
4
4
  import type { ContainerContentsStoreWorkflowRuntime } from "../../../workflows/container-contents/runtime.js";
5
5
  import type { ContainerContentsSyncLane } from "../../../workflows/container-contents/syncLane.js";
6
+ import type { ReconnectRefresh } from "../hydration/reconnectRefresh.js";
6
7
  export type ContainerContentsStoreRuntime = ContainerContentsStoreWorkflowRuntime;
7
8
  export interface RefreshRootLaneOptions {
8
9
  readonly includeActiveRootChildLane?: boolean | undefined;
@@ -15,6 +16,7 @@ export interface ContainerContentsStoreSyncAgent {
15
16
  primeDocumentsForSharedSubtree: (rootContainerId: string, isCurrent?: (() => boolean) | undefined) => Promise<void>;
16
17
  refreshLocalContainers: () => Promise<void>;
17
18
  refresh: (options?: {
19
+ reconnect?: ReconnectCrawl | undefined;
18
20
  resetAllLaneWatermarks?: boolean;
19
21
  }) => Promise<boolean>;
20
22
  refreshRootLane: (options?: RefreshRootLaneOptions) => Promise<boolean>;
@@ -27,6 +29,7 @@ export interface ContainerContentsStoreSyncAgent {
27
29
  scheduleSync: () => void;
28
30
  }
29
31
  export interface ContainerContentsStoreSyncState {
32
+ readonly parentLaneRequestPrefix?: string;
30
33
  /** Container listing requests that failed or timed out in a current crawl. */
31
34
  containerListingFailures: number;
32
35
  containersById: Map<string, ContainerState>;
@@ -82,7 +85,7 @@ export interface ContainerContentsStoreSyncState {
82
85
  remoteHydrationPromise: Promise<void> | null;
83
86
  remoteHydrationGeneration: number | null;
84
87
  remoteHydrationStructuralGeneration: number | null;
85
- remoteReconnectRefreshPending: boolean;
88
+ reconnectRefresh: ReconnectRefresh;
86
89
  resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;
87
90
  /** True after this store has fully applied an authoritative root lane. */
88
91
  rootLaneHydrated: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"syncAgentTypes.js","sourceRoot":"","sources":["syncAgentTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerContentsPersistence } from \"../../../workflows/container-contents/containerPersistence\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../../../workflows/container-contents/projectionKeys\";\nimport type {\n ContainerState,\n RemoteContainer,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport type { ContainerContentsStoreWorkflowRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { ContainerContentsSyncLane } from \"../../../workflows/container-contents/syncLane\";\n\nexport type ContainerContentsStoreRuntime =\n ContainerContentsStoreWorkflowRuntime;\n\nexport interface RefreshRootLaneOptions {\n readonly includeActiveRootChildLane?: boolean | undefined;\n // Extra parent lanes to re-list alongside the root lane. Used by the\n // resync_required handler to re-list affected containers' parent lanes so a\n // tombstone only visible there is still applied without the full crawl.\n readonly parentIds?: ReadonlyArray<string | null> | undefined;\n}\n\nexport interface ContainerContentsStoreSyncAgent {\n ensureInitialized: () => void;\n handleRemoteEvents: () => void;\n ingestRemoteContainer: (remoteContainer: RemoteContainer) => Promise<void>;\n primeDocumentsForSharedSubtree: (\n rootContainerId: string,\n isCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n refreshLocalContainers: () => Promise<void>;\n refresh: (options?: { resetAllLaneWatermarks?: boolean }) => Promise<boolean>;\n refreshRootLane: (options?: RefreshRootLaneOptions) => Promise<boolean>;\n requestRemoteHydration: (options?: {\n followDiscoveredParentLanes?: boolean | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n }) => Promise<void>;\n scheduleRemoteHydration: () => void;\n scheduleSync: () => void;\n}\n\nexport interface ContainerContentsStoreSyncState {\n /** Container listing requests that failed or timed out in a current crawl. */\n containerListingFailures: number;\n containersById: Map<string, ContainerState>;\n documentStoresNeedPriming: boolean;\n initializeGeneration: number | null;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n localContainerRefreshPromise: Promise<void> | null;\n localContainerRefreshGeneration: number | null;\n localContainerRefreshStructuralGeneration: number | null;\n localContainersNeedRefresh: boolean;\n /** Invalidates asynchronous hydration work when this store is reset. */\n lifecycleGeneration: number;\n /** Invalidates structural work when its runtime or persistence is replaced. */\n structuralGeneration: number;\n /** Invalidates writes across write-relevant runtime ABA transitions. */\n writeGeneration: number;\n lastEventCount: number;\n /**\n * Update ids this client sent for container metadata documents, registered\n * before the network await of each metadata sync pass. The author's own\n * `document_update_created` echo consumes its ids here instead of arming a\n * redundant forced read-sync; a genuine peer update always carries unknown\n * ids and still forces one. Shared across all metadata docs in the store —\n * update ids are globally unique.\n */\n locallyAcceptedMetadataUpdateIds: Set<string>;\n logLabel?: string | undefined;\n metadataDocumentIdsNeedingSync: Set<string>;\n /**\n * Per-metadata-document enqueue sequence. Bumped for a specific id whenever a\n * remote event re-queues it in {@link metadataDocumentIdsNeedingSync}. A sync\n * pass snapshots the id's sequence before its GET and only clears the id if it\n * is unchanged at pass end, so a mid-pass re-queue of THIS container is not\n * erased. Keyed per id (not a single global counter) so a remote event for an\n * unrelated container does not force a redundant re-sync of this one. See\n * `clearMetadataSyncQueueIfUnchanged`.\n */\n metadataSyncSignalSeqById: Map<string, number>;\n /**\n * Whether this store's first sync pass has requeued the metadata reads a\n * previous run still owed (`container_metadata_revalidations`). Reset with\n * the store, so a replacement database is restored on its own first pass.\n */\n owedMetadataReadsRestored: boolean;\n /**\n * Metadata document ids of folder creates in flight. A remote hint for one\n * queues the folder's first read before the create response installs the id.\n */\n plannedMetadataDocumentIds: Set<string>;\n containerParentIdsNeedingHydration: Set<string | null>;\n persistence: ContainerContentsPersistence;\n remoteHydrationPromise: Promise<void> | null;\n remoteHydrationGeneration: number | null;\n remoteHydrationStructuralGeneration: number | null;\n remoteReconnectRefreshPending: boolean;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n /** True after this store has fully applied an authoritative root lane. */\n rootLaneHydrated: boolean;\n runtime: ContainerContentsStoreRuntime;\n snapshot: { ready: boolean };\n syncLane: ContainerContentsSyncLane | null;\n}\n"]}
1
+ {"version":3,"file":"syncAgentTypes.js","sourceRoot":"","sources":["syncAgentTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerContentsPersistence } from \"../../../workflows/container-contents/containerPersistence\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../../../workflows/container-contents/projectionKeys\";\nimport type {\n ContainerState,\n ReconnectCrawl,\n RemoteContainer,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport type { ContainerContentsStoreWorkflowRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { ContainerContentsSyncLane } from \"../../../workflows/container-contents/syncLane\";\n\nimport type { ReconnectRefresh } from \"../hydration/reconnectRefresh\";\n\nexport type ContainerContentsStoreRuntime =\n ContainerContentsStoreWorkflowRuntime;\n\nexport interface RefreshRootLaneOptions {\n readonly includeActiveRootChildLane?: boolean | undefined;\n // Extra parent lanes to re-list alongside the root lane. Used by the\n // resync_required handler to re-list affected containers' parent lanes so a\n // tombstone only visible there is still applied without the full crawl.\n readonly parentIds?: ReadonlyArray<string | null> | undefined;\n}\n\nexport interface ContainerContentsStoreSyncAgent {\n ensureInitialized: () => void;\n handleRemoteEvents: () => void;\n ingestRemoteContainer: (remoteContainer: RemoteContainer) => Promise<void>;\n primeDocumentsForSharedSubtree: (\n rootContainerId: string,\n isCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n refreshLocalContainers: () => Promise<void>;\n refresh: (options?: {\n reconnect?: ReconnectCrawl | undefined;\n resetAllLaneWatermarks?: boolean;\n }) => Promise<boolean>;\n refreshRootLane: (options?: RefreshRootLaneOptions) => Promise<boolean>;\n requestRemoteHydration: (options?: {\n followDiscoveredParentLanes?: boolean | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n }) => Promise<void>;\n scheduleRemoteHydration: () => void;\n scheduleSync: () => void;\n}\n\nexport interface ContainerContentsStoreSyncState {\n readonly parentLaneRequestPrefix?: string;\n /** Container listing requests that failed or timed out in a current crawl. */\n containerListingFailures: number;\n containersById: Map<string, ContainerState>;\n documentStoresNeedPriming: boolean;\n initializeGeneration: number | null;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n localContainerRefreshPromise: Promise<void> | null;\n localContainerRefreshGeneration: number | null;\n localContainerRefreshStructuralGeneration: number | null;\n localContainersNeedRefresh: boolean;\n /** Invalidates asynchronous hydration work when this store is reset. */\n lifecycleGeneration: number;\n /** Invalidates structural work when its runtime or persistence is replaced. */\n structuralGeneration: number;\n /** Invalidates writes across write-relevant runtime ABA transitions. */\n writeGeneration: number;\n lastEventCount: number;\n /**\n * Update ids this client sent for container metadata documents, registered\n * before the network await of each metadata sync pass. The author's own\n * `document_update_created` echo consumes its ids here instead of arming a\n * redundant forced read-sync; a genuine peer update always carries unknown\n * ids and still forces one. Shared across all metadata docs in the store —\n * update ids are globally unique.\n */\n locallyAcceptedMetadataUpdateIds: Set<string>;\n logLabel?: string | undefined;\n metadataDocumentIdsNeedingSync: Set<string>;\n /**\n * Per-metadata-document enqueue sequence. Bumped for a specific id whenever a\n * remote event re-queues it in {@link metadataDocumentIdsNeedingSync}. A sync\n * pass snapshots the id's sequence before its GET and only clears the id if it\n * is unchanged at pass end, so a mid-pass re-queue of THIS container is not\n * erased. Keyed per id (not a single global counter) so a remote event for an\n * unrelated container does not force a redundant re-sync of this one. See\n * `clearMetadataSyncQueueIfUnchanged`.\n */\n metadataSyncSignalSeqById: Map<string, number>;\n /**\n * Whether this store's first sync pass has requeued the metadata reads a\n * previous run still owed (`container_metadata_revalidations`). Reset with\n * the store, so a replacement database is restored on its own first pass.\n */\n owedMetadataReadsRestored: boolean;\n /**\n * Metadata document ids of folder creates in flight. A remote hint for one\n * queues the folder's first read before the create response installs the id.\n */\n plannedMetadataDocumentIds: Set<string>;\n containerParentIdsNeedingHydration: Set<string | null>;\n persistence: ContainerContentsPersistence;\n remoteHydrationPromise: Promise<void> | null;\n remoteHydrationGeneration: number | null;\n remoteHydrationStructuralGeneration: number | null;\n reconnectRefresh: ReconnectRefresh;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n /** True after this store has fully applied an authoritative root lane. */\n rootLaneHydrated: boolean;\n runtime: ContainerContentsStoreRuntime;\n snapshot: { ready: boolean };\n syncLane: ContainerContentsSyncLane | null;\n}\n"]}
@@ -7,6 +7,7 @@ import { openDocumentStore, requestDomainDocumentSync } from "../../documents/in
7
7
  import { relinkDocumentStoreWithCommitSideEffect } from "../../documents/documentStore/internalRelink.js";
8
8
  import { DocumentRemoteWorkBusyError } from "../../documents/documentStore/sync/remoteWork.js";
9
9
  import { removeMissingSyncedContainerState } from "../containerState/missingSyncedContainerState.js";
10
+ import { ownsContainerStore } from "../containerState/storeScope.js";
10
11
  import { runContainerDocumentWork } from "../documentWork/index.js";
11
12
  import { primeStoreDocuments, recoverStoreStaleRoot, } from "../documentWork/documentRecovery.js";
12
13
  import { createAcceptedMoveRetry } from "./acceptedMoveRetry.js";
@@ -27,15 +28,15 @@ function captureStructuralSyncGeneration(state, runtime) {
27
28
  const execSql = runtime.infra.execSql;
28
29
  const resolveProjectionUserKey = state.resolveProjectionUserKey;
29
30
  const syncLane = state.syncLane;
30
- return () => state.lifecycleGeneration === lifecycleGeneration &&
31
+ return () => ownsContainerStore(state) &&
32
+ state.lifecycleGeneration === lifecycleGeneration &&
31
33
  state.structuralGeneration === structuralGeneration &&
32
34
  state.runtime.auth.organizationId === activeOrganizationId &&
33
35
  state.runtime.state.containerId === activeContainerId &&
34
36
  state.runtime.state.domainScope === domainScope &&
35
37
  state.runtime.infra.execSql === execSql &&
36
38
  state.resolveProjectionUserKey === resolveProjectionUserKey &&
37
- state.syncLane === syncLane &&
38
- !syncLane?.isDisposed?.();
39
+ state.syncLane === syncLane;
39
40
  }
40
41
  function createContainerContentsStoreDocumentMoveHost(state, isCurrent) {
41
42
  const runtime = state.runtime;
@@ -247,6 +248,8 @@ export async function runContainerContentsStoreSyncIteration(input) {
247
248
  }
248
249
  const domainScope = runtime.state.domainScope;
249
250
  const isCurrent = captureStructuralSyncGeneration(state, runtime);
251
+ if (!isCurrent())
252
+ return;
250
253
  await reconcileRestoredAccess(isCurrent);
251
254
  if (!isCurrent()) {
252
255
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"syncLaneIteration.js","sourceRoot":"","sources":["syncLaneIteration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,+EAA+E,CAAC;AAClI,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAK5H,OAAO,EAEL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AC,KAAK,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QACD,gBAAgB,EAAE,GAAG,EAAE;YACrB,IAAI,SAAS,EAAE,EAAE,CAAC;gBAChB,yBAAyB,CAAC,WAAW,CAAC,CAAC;gBACvC,iCAAiC,CAAC,KAAK,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QACD,cAAc,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC;QAC3D,gBAAgB,EAAE,GAAG,EAAE,CAAC,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC;QAC/D,oBAAoB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,yBAAyB;QAC3D,sEAAsE;QACtE,wEAAwE;QACxE,sEAAsE;QACtE,yDAAyD;QACzD,wBAAwB,EAAE,GAAG,EAAE,CAC7B,6BAA6B,CAAC;YAC5B,eAAe;YACf,SAAS;YACT,mBAAmB,EAAE,qBAAqB;YAC1C,KAAK;SACN,CAAC;KACL,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { syncPendingContainerCreateIntents } from \"../../../workflows/container-contents/container-state/create/createIntentSync\";\nimport { syncPendingContainerMoveIntents } from \"../../../workflows/container-contents/container-state/move/moveIntentSync\";\nimport type {\n ContainerMetadataRevalidation,\n ExecSql,\n} from \"../../../workflows/container-contents/containerPersistence\";\nimport {\n type DocumentMoveIntentSyncHost,\n syncPendingDocumentMoveIntents,\n} from \"../../../workflows/container-contents/documentMove/documentMoveIntentSync\";\nimport { syncContainerMetadataState } from \"../../../workflows/container-contents/metadata\";\nimport type { SyncedContainerMetadataState } from \"../../../workflows/container-contents/metadata/metadataTypes\";\nimport type {\n ContainerState,\n RemoteContainerHydrationHost,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport { createContainerContentsDocumentsRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { PrincipalPolicyOperation } from \"../../../workflows/principals/principalPolicyService\";\nimport { openDocumentStore, requestDomainDocumentSync } from \"../../documents\";\nimport { relinkDocumentStoreWithCommitSideEffect } from \"../../documents/documentStore/internalRelink\";\nimport { DocumentRemoteWorkBusyError } from \"../../documents/documentStore/sync/remoteWork\";\nimport { removeMissingSyncedContainerState } from \"../containerState/missingSyncedContainerState\";\nimport { runContainerDocumentWork } from \"../documentWork\";\nimport {\n primeStoreDocuments,\n recoverStoreStaleRoot,\n} from \"../documentWork/documentRecovery\";\nimport { createAcceptedMoveRetry } from \"./acceptedMoveRetry\";\nimport {\n coversAdvertisedMetadataVersion,\n findOwedContainerMetadataRead,\n restoreOwedContainerMetadataReads,\n settleOwedContainerMetadataRead,\n} from \"./metadataRevalidation\";\nimport {\n bumpMetadataSyncSeq,\n clearMetadataSyncQueueIfUnchanged,\n readMetadataSyncSeq,\n} from \"./metadataSyncSignal\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncState,\n} from \"./syncAgentTypes\";\n\ntype ContainerContentsStorePrimeDocumentRuntime = ReturnType<\n typeof createContainerContentsDocumentsRuntime\n>;\ntype SyncContainerMetadata = typeof syncContainerMetadataState;\n\nfunction requestContainerContentsStoreSync(\n state: ContainerContentsStoreSyncState,\n) {\n state.syncLane?.requestSync();\n}\n\nfunction createRemoteSyncBlocker(runtime: ContainerContentsStoreRuntime) {\n return (organizationId: string) =>\n runtime.util.isRemoteSyncBlocked?.(organizationId) ?? false;\n}\n\nfunction captureStructuralSyncGeneration(\n state: ContainerContentsStoreSyncState,\n runtime: ContainerContentsStoreRuntime,\n) {\n const activeContainerId = runtime.state.containerId;\n const activeOrganizationId = runtime.auth.organizationId;\n const lifecycleGeneration = state.lifecycleGeneration;\n const structuralGeneration = state.structuralGeneration;\n const domainScope = runtime.state.domainScope;\n const execSql = runtime.infra.execSql;\n const resolveProjectionUserKey = state.resolveProjectionUserKey;\n const syncLane = state.syncLane;\n return () =>\n state.lifecycleGeneration === lifecycleGeneration &&\n state.structuralGeneration === structuralGeneration &&\n state.runtime.auth.organizationId === activeOrganizationId &&\n state.runtime.state.containerId === activeContainerId &&\n state.runtime.state.domainScope === domainScope &&\n state.runtime.infra.execSql === execSql &&\n state.resolveProjectionUserKey === resolveProjectionUserKey &&\n state.syncLane === syncLane &&\n !syncLane?.isDisposed?.();\n}\n\nfunction createContainerContentsStoreDocumentMoveHost(\n state: ContainerContentsStoreSyncState,\n isCurrent: () => boolean,\n): DocumentMoveIntentSyncHost<ContainerContentsStorePrimeDocumentRuntime> {\n const runtime = state.runtime;\n const domainScope = runtime.state.domainScope;\n return {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: ({ containerId, documentId, localId }) => {\n const store = openDocumentStore(\n domainScope,\n localId,\n createContainerContentsDocumentsRuntime(runtime, containerId),\n documentId,\n );\n return {\n assertCanRotateContentKey: (proof) =>\n store.assertCanRotateContentKey(proof).catch((error: unknown) => {\n if (error instanceof DocumentRemoteWorkBusyError) {\n void error.whenIdle.then(() => {\n if (isCurrent()) requestContainerContentsStoreSync(state);\n });\n }\n throw error;\n }),\n ensureInitialized: () => store.ensureInitialized(),\n relink: ({ commitSideEffect, ...input }) =>\n commitSideEffect\n ? relinkDocumentStoreWithCommitSideEffect(\n store,\n input,\n commitSideEffect,\n )\n : store.relink(input),\n requestSync: () => store.requestSync(),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n },\n };\n}\n\nfunction syncPendingStoreDocumentMoves(input: {\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n state: ContainerContentsStoreSyncState;\n}) {\n return syncPendingDocumentMoveIntents({\n host: createContainerContentsStoreDocumentMoveHost(\n input.state,\n input.isCurrent,\n ),\n isCreatePending: input.isCreatePending,\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n state: input.state,\n });\n}\n\nfunction syncPendingStoreContainerMoves(\n input: Omit<\n Parameters<typeof syncPendingContainerMoveIntents>[0],\n \"acceptedMoveRetry\" | \"state\"\n > & { state: ContainerContentsStoreSyncState },\n) {\n return syncPendingContainerMoveIntents({\n ...input,\n acceptedMoveRetry: createAcceptedMoveRetry(input.state),\n });\n}\n\nasync function syncSingleContainerMetadata(input: {\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n state: ContainerContentsStoreSyncState;\n containerState: ContainerState;\n encapsulationKeyPair: NonNullable<\n ContainerContentsStoreRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n >;\n policyOperation: PrincipalPolicyOperation;\n syncContainerMetadata?: SyncContainerMetadata | undefined;\n}) {\n const { containerState, encapsulationKeyPair, host, isCurrent, state } =\n input;\n const metadataDocumentId = containerState.record.documentId;\n const readExecSql = state.runtime.infra.execSql;\n // The durable request this read answers, read before the read begins.\n const owedRead =\n typeof metadataDocumentId === \"string\" &&\n state.metadataDocumentIdsNeedingSync.has(metadataDocumentId)\n ? await findOwedContainerMetadataRead(state, {\n documentId: metadataDocumentId,\n execSql: readExecSql,\n })\n : null;\n if (!isCurrent()) return;\n // Snapshot this signal before the GET so a mid-pass event survives clearing.\n const consumedSeqById = new Map<string, number>();\n if (typeof metadataDocumentId === \"string\") {\n consumedSeqById.set(\n metadataDocumentId,\n readMetadataSyncSeq(state.metadataSyncSignalSeqById, metadataDocumentId),\n );\n }\n const synced = await (\n input.syncContainerMetadata ?? syncContainerMetadataState\n )({\n forceReadSync:\n typeof metadataDocumentId === \"string\" &&\n state.metadataDocumentIdsNeedingSync.has(metadataDocumentId),\n locallyAcceptedUpdateIds: state.locallyAcceptedMetadataUpdateIds,\n isCurrent,\n metadataState: containerState,\n onDurableStateNeedsReload: () => {\n const currentDocumentId = state.containersById.get(\n containerState.container.id,\n )?.record.documentId;\n if (typeof currentDocumentId === \"string\") {\n state.metadataDocumentIdsNeedingSync.add(currentDocumentId);\n bumpMetadataSyncSeq(state.metadataSyncSignalSeqById, currentDocumentId);\n }\n requestContainerContentsStoreSync(state);\n },\n persistence: state.persistence,\n policyOperation: input.policyOperation,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n runtime: state.runtime,\n targetSecretKey: encapsulationKeyPair.secretKey,\n });\n if (!isCurrent() || !synced) {\n return;\n }\n if (\"missing\" in synced) {\n removeMissingSyncedContainerState(\n state,\n containerState,\n host.updateSnapshot,\n );\n return;\n }\n\n const kept = keptMetadataSignals({ containerState, owedRead, synced });\n const stillCurrent = await settleConsumedMetadataSignals({\n consumedSeqById,\n documentIds: [metadataDocumentId, synced.record.documentId],\n isCurrent,\n keepsSignals: kept.keep,\n owedRead,\n readExecSql,\n state,\n });\n // A reset can land after the settlement's last check and before this resumes.\n if (!stillCurrent || !isCurrent()) return;\n // syncContainerMetadataState settles its detached candidate into this live\n // object while preserving any metadata edit that completed or queued during\n // the remote pass. Do not install its returned detached record again here:\n // doing so would overwrite that preserved live edit.\n host.updateSnapshot();\n\n // A pass that kept an owed read hands it to a fresh read next pass.\n if (\n synced.shouldRequestFollowupSync ||\n (kept.followUp && isQueuedForRead(state, metadataDocumentId))\n ) {\n requestContainerContentsStoreSync(state);\n }\n}\n\n/**\n * Whether a completed read keeps its signals for another read, and whether to\n * ask for that read now. A resumed pull reads only to its earlier bound, and a\n * superseded result discarded what it pulled: both hand the read to a fresh\n * pass. A replica lagging the listing can answer without the advertised edit;\n * that debt waits for a later pass rather than a follow-up loop.\n */\nfunction keptMetadataSignals(input: {\n containerState: ContainerState;\n owedRead: ContainerMetadataRevalidation | null;\n synced: SyncedContainerMetadataState;\n}): { followUp: boolean; keep: boolean } {\n const followUp =\n input.synced.resumedEarlierPull === true ||\n isSupersededMetadataSync(input.synced);\n const behindListing =\n input.owedRead !== null &&\n !coversAdvertisedMetadataVersion(input.containerState.doc, input.owedRead);\n return { followUp, keep: followUp || behindListing };\n}\n\nfunction isSupersededMetadataSync(\n synced: Pick<\n SyncedContainerMetadataState,\n | \"mutationSuperseded\"\n | \"pullContinuationSuperseded\"\n | \"syncIdentitySuperseded\"\n >,\n): boolean {\n return (\n synced.mutationSuperseded === true ||\n synced.pullContinuationSuperseded === true ||\n synced.syncIdentitySuperseded === true\n );\n}\n\nfunction isQueuedForRead(\n state: ContainerContentsStoreSyncState,\n documentId: string | null | undefined,\n): boolean {\n return (\n typeof documentId === \"string\" &&\n state.metadataDocumentIdsNeedingSync.has(documentId)\n );\n}\n\n/**\n * Clears the signals a completed metadata sync consumed and settles the read a\n * listing owed: the sync pulled every update this client lacked, unless a\n * newer signal queued the document again. A pass that keeps its signals\n * settles nothing. Returns false once the pass is no longer current, before\n * touching a replacement store's queue.\n */\nasync function settleConsumedMetadataSignals(input: {\n consumedSeqById: ReadonlyMap<string, number>;\n documentIds: ReadonlyArray<string | null | undefined>;\n isCurrent: () => boolean;\n keepsSignals: boolean;\n owedRead: ContainerMetadataRevalidation | null;\n readExecSql: ExecSql;\n state: ContainerContentsStoreSyncState;\n}): Promise<boolean> {\n if (input.keepsSignals) return true;\n for (const id of new Set(input.documentIds)) {\n if (typeof id !== \"string\") continue;\n if (!input.isCurrent()) return false;\n clearMetadataSyncQueueIfUnchanged({\n consumedSeqById: input.consumedSeqById,\n id,\n needingSync: input.state.metadataDocumentIdsNeedingSync,\n seqById: input.state.metadataSyncSignalSeqById,\n });\n }\n if (input.owedRead) {\n await settleOwedContainerMetadataRead(input.state, {\n execSql: input.readExecSql,\n revalidation: input.owedRead,\n });\n }\n return input.isCurrent();\n}\n\n/**\n * Syncs each held container's metadata, after requeueing reads a previous run\n * still owed. Returns false once the pass is no longer current.\n */\nasync function syncEveryContainerMetadata(\n input: Omit<\n Parameters<typeof syncSingleContainerMetadata>[0],\n \"containerState\"\n > & {\n isCreatePending: (containerId: string) => boolean;\n },\n): Promise<boolean> {\n const { isCurrent, state } = input;\n if (!state.owedMetadataReadsRestored) {\n await restoreOwedContainerMetadataReads(state, isCurrent);\n if (!isCurrent()) return false;\n state.owedMetadataReadsRestored = true;\n }\n for (const containerState of Array.from(state.containersById.values())) {\n if (input.isCreatePending(containerState.container.id)) continue;\n await syncSingleContainerMetadata({ ...input, containerState });\n if (!isCurrent()) return false;\n }\n return true;\n}\n\n/**\n * A folder whose create has not settled can carry a listed identity that\n * adoption has not verified, or has refused. Folder moves, document moves and\n * metadata edits wait for it; child and document creates wait in their own\n * create paths.\n */\nasync function loadPendingCreatePredicate(\n state: ContainerContentsStoreSyncState,\n): Promise<(containerId: string) => boolean> {\n const pending = await state.persistence.listPendingCreateIntents(\n state.runtime.infra.execSql,\n );\n const pendingIds = new Set(pending.map((intent) => intent.containerId));\n return (containerId) => pendingIds.has(containerId);\n}\n\ninterface ContainerContentsStoreSyncIterationInput {\n host: RemoteContainerHydrationHost;\n /** The drain's operation: every metadata sync of this pass shares it. */\n policyOperation: PrincipalPolicyOperation;\n reconcileRestoredAccess: (isCurrent: () => boolean) => Promise<void>;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerContentsStoreSyncState;\n syncContainerMetadata?: SyncContainerMetadata | undefined;\n}\n\nexport async function runContainerContentsStoreSyncIteration(\n input: ContainerContentsStoreSyncIterationInput,\n) {\n const { host, reconcileRestoredAccess, requestRemoteReconciliation, state } =\n input;\n const runtime = state.runtime;\n const encapsulationKeyPair = runtime.crypto.encapsulationKeyPair;\n if (\n runtime.infra.dbStatus !== \"ready\" ||\n !state.snapshot.ready ||\n !runtime.state.online ||\n !runtime.auth.isAuthenticated ||\n !encapsulationKeyPair\n ) {\n return;\n }\n const domainScope = runtime.state.domainScope;\n const isCurrent = captureStructuralSyncGeneration(state, runtime);\n\n await reconcileRestoredAccess(isCurrent);\n if (!isCurrent()) {\n return;\n }\n const isOrganizationBlocked = createRemoteSyncBlocker(runtime);\n\n const createdContainerCount = await syncPendingContainerCreateIntents({\n host,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n requestRemoteReconciliation,\n state,\n });\n if (!isCurrent()) {\n return;\n }\n if (createdContainerCount > 0) {\n state.documentStoresNeedPriming = true;\n host.updateSnapshot();\n }\n const isCreatePending = await loadPendingCreatePredicate(state);\n if (!isCurrent()) {\n return;\n }\n\n const movedContainerCount = await syncPendingStoreContainerMoves({\n host,\n isCreatePending,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n requestRemoteReconciliation,\n state,\n });\n if (!isCurrent()) {\n return;\n }\n if (movedContainerCount > 0) {\n state.documentStoresNeedPriming = true;\n host.updateSnapshot();\n requestDomainDocumentSync(domainScope);\n requestContainerContentsStoreSync(state);\n }\n\n const metadataSynced = await syncEveryContainerMetadata({\n ...input,\n encapsulationKeyPair,\n isCreatePending,\n isCurrent,\n });\n if (!metadataSynced) {\n return;\n }\n\n // Root adoption notifies session consumers synchronously. Let container\n // metadata converge first so a recovered system container is never exposed\n // under its placeholder name when the active root changes.\n await runContainerDocumentWork({\n isCurrent,\n onContextChanged: () => {\n if (isCurrent()) {\n requestContainerContentsStoreSync(state);\n }\n },\n onDocumentsMoved: () => {\n if (isCurrent()) {\n requestDomainDocumentSync(domainScope);\n requestContainerContentsStoreSync(state);\n }\n },\n primeDocuments: () => primeStoreDocuments(state, isCurrent),\n recoverStaleRoot: () => recoverStoreStaleRoot(state, isCurrent),\n shouldPrimeDocuments: () => state.documentStoresNeedPriming,\n // Document move intents live in the structural phase because they may\n // target containers created locally in the same session, such as Trash.\n // Root recovery rewrites stale endpoints and returns their intents to\n // pending, so replay follows recovery in this same pass.\n syncPendingDocumentMoves: () =>\n syncPendingStoreDocumentMoves({\n isCreatePending,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n state,\n }),\n });\n}\n"]}
1
+ {"version":3,"file":"syncLaneIteration.js","sourceRoot":"","sources":["syncLaneIteration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,+EAA+E,CAAC;AAClI,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAK5H,OAAO,EAEL,8BAA8B,GAC/B,MAAM,2EAA2E,CAAC;AACnF,OAAO,EAAE,0BAA0B,EAAE,MAAM,gD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,CAAC,KAAK,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QACD,gBAAgB,EAAE,GAAG,EAAE;YACrB,IAAI,SAAS,EAAE,EAAE,CAAC;gBAChB,yBAAyB,CAAC,WAAW,CAAC,CAAC;gBACvC,iCAAiC,CAAC,KAAK,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QACD,cAAc,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC;QAC3D,gBAAgB,EAAE,GAAG,EAAE,CAAC,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC;QAC/D,oBAAoB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,yBAAyB;QAC3D,sEAAsE;QACtE,wEAAwE;QACxE,sEAAsE;QACtE,yDAAyD;QACzD,wBAAwB,EAAE,GAAG,EAAE,CAC7B,6BAA6B,CAAC;YAC5B,eAAe;YACf,SAAS;YACT,mBAAmB,EAAE,qBAAqB;YAC1C,KAAK;SACN,CAAC;KACL,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { syncPendingContainerCreateIntents } from \"../../../workflows/container-contents/container-state/create/createIntentSync\";\nimport { syncPendingContainerMoveIntents } from \"../../../workflows/container-contents/container-state/move/moveIntentSync\";\nimport type {\n ContainerMetadataRevalidation,\n ExecSql,\n} from \"../../../workflows/container-contents/containerPersistence\";\nimport {\n type DocumentMoveIntentSyncHost,\n syncPendingDocumentMoveIntents,\n} from \"../../../workflows/container-contents/documentMove/documentMoveIntentSync\";\nimport { syncContainerMetadataState } from \"../../../workflows/container-contents/metadata\";\nimport type { SyncedContainerMetadataState } from \"../../../workflows/container-contents/metadata/metadataTypes\";\nimport type {\n ContainerState,\n RemoteContainerHydrationHost,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport { createContainerContentsDocumentsRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { PrincipalPolicyOperation } from \"../../../workflows/principals/principalPolicyService\";\nimport { openDocumentStore, requestDomainDocumentSync } from \"../../documents\";\nimport { relinkDocumentStoreWithCommitSideEffect } from \"../../documents/documentStore/internalRelink\";\nimport { DocumentRemoteWorkBusyError } from \"../../documents/documentStore/sync/remoteWork\";\nimport { removeMissingSyncedContainerState } from \"../containerState/missingSyncedContainerState\";\nimport { ownsContainerStore } from \"../containerState/storeScope\";\nimport { runContainerDocumentWork } from \"../documentWork\";\nimport {\n primeStoreDocuments,\n recoverStoreStaleRoot,\n} from \"../documentWork/documentRecovery\";\nimport { createAcceptedMoveRetry } from \"./acceptedMoveRetry\";\nimport {\n coversAdvertisedMetadataVersion,\n findOwedContainerMetadataRead,\n restoreOwedContainerMetadataReads,\n settleOwedContainerMetadataRead,\n} from \"./metadataRevalidation\";\nimport {\n bumpMetadataSyncSeq,\n clearMetadataSyncQueueIfUnchanged,\n readMetadataSyncSeq,\n} from \"./metadataSyncSignal\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncState,\n} from \"./syncAgentTypes\";\n\ntype ContainerContentsStorePrimeDocumentRuntime = ReturnType<\n typeof createContainerContentsDocumentsRuntime\n>;\ntype SyncContainerMetadata = typeof syncContainerMetadataState;\n\nfunction requestContainerContentsStoreSync(\n state: ContainerContentsStoreSyncState,\n) {\n state.syncLane?.requestSync();\n}\n\nfunction createRemoteSyncBlocker(runtime: ContainerContentsStoreRuntime) {\n return (organizationId: string) =>\n runtime.util.isRemoteSyncBlocked?.(organizationId) ?? false;\n}\n\nfunction captureStructuralSyncGeneration(\n state: ContainerContentsStoreSyncState,\n runtime: ContainerContentsStoreRuntime,\n) {\n const activeContainerId = runtime.state.containerId;\n const activeOrganizationId = runtime.auth.organizationId;\n const lifecycleGeneration = state.lifecycleGeneration;\n const structuralGeneration = state.structuralGeneration;\n const domainScope = runtime.state.domainScope;\n const execSql = runtime.infra.execSql;\n const resolveProjectionUserKey = state.resolveProjectionUserKey;\n const syncLane = state.syncLane;\n return () =>\n ownsContainerStore(state) &&\n state.lifecycleGeneration === lifecycleGeneration &&\n state.structuralGeneration === structuralGeneration &&\n state.runtime.auth.organizationId === activeOrganizationId &&\n state.runtime.state.containerId === activeContainerId &&\n state.runtime.state.domainScope === domainScope &&\n state.runtime.infra.execSql === execSql &&\n state.resolveProjectionUserKey === resolveProjectionUserKey &&\n state.syncLane === syncLane;\n}\n\nfunction createContainerContentsStoreDocumentMoveHost(\n state: ContainerContentsStoreSyncState,\n isCurrent: () => boolean,\n): DocumentMoveIntentSyncHost<ContainerContentsStorePrimeDocumentRuntime> {\n const runtime = state.runtime;\n const domainScope = runtime.state.domainScope;\n return {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: ({ containerId, documentId, localId }) => {\n const store = openDocumentStore(\n domainScope,\n localId,\n createContainerContentsDocumentsRuntime(runtime, containerId),\n documentId,\n );\n return {\n assertCanRotateContentKey: (proof) =>\n store.assertCanRotateContentKey(proof).catch((error: unknown) => {\n if (error instanceof DocumentRemoteWorkBusyError) {\n void error.whenIdle.then(() => {\n if (isCurrent()) requestContainerContentsStoreSync(state);\n });\n }\n throw error;\n }),\n ensureInitialized: () => store.ensureInitialized(),\n relink: ({ commitSideEffect, ...input }) =>\n commitSideEffect\n ? relinkDocumentStoreWithCommitSideEffect(\n store,\n input,\n commitSideEffect,\n )\n : store.relink(input),\n requestSync: () => store.requestSync(),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n },\n };\n}\n\nfunction syncPendingStoreDocumentMoves(input: {\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n state: ContainerContentsStoreSyncState;\n}) {\n return syncPendingDocumentMoveIntents({\n host: createContainerContentsStoreDocumentMoveHost(\n input.state,\n input.isCurrent,\n ),\n isCreatePending: input.isCreatePending,\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n state: input.state,\n });\n}\n\nfunction syncPendingStoreContainerMoves(\n input: Omit<\n Parameters<typeof syncPendingContainerMoveIntents>[0],\n \"acceptedMoveRetry\" | \"state\"\n > & { state: ContainerContentsStoreSyncState },\n) {\n return syncPendingContainerMoveIntents({\n ...input,\n acceptedMoveRetry: createAcceptedMoveRetry(input.state),\n });\n}\n\nasync function syncSingleContainerMetadata(input: {\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n state: ContainerContentsStoreSyncState;\n containerState: ContainerState;\n encapsulationKeyPair: NonNullable<\n ContainerContentsStoreRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n >;\n policyOperation: PrincipalPolicyOperation;\n syncContainerMetadata?: SyncContainerMetadata | undefined;\n}) {\n const { containerState, encapsulationKeyPair, host, isCurrent, state } =\n input;\n const metadataDocumentId = containerState.record.documentId;\n const readExecSql = state.runtime.infra.execSql;\n // The durable request this read answers, read before the read begins.\n const owedRead =\n typeof metadataDocumentId === \"string\" &&\n state.metadataDocumentIdsNeedingSync.has(metadataDocumentId)\n ? await findOwedContainerMetadataRead(state, {\n documentId: metadataDocumentId,\n execSql: readExecSql,\n })\n : null;\n if (!isCurrent()) return;\n // Snapshot this signal before the GET so a mid-pass event survives clearing.\n const consumedSeqById = new Map<string, number>();\n if (typeof metadataDocumentId === \"string\") {\n consumedSeqById.set(\n metadataDocumentId,\n readMetadataSyncSeq(state.metadataSyncSignalSeqById, metadataDocumentId),\n );\n }\n const synced = await (\n input.syncContainerMetadata ?? syncContainerMetadataState\n )({\n forceReadSync:\n typeof metadataDocumentId === \"string\" &&\n state.metadataDocumentIdsNeedingSync.has(metadataDocumentId),\n locallyAcceptedUpdateIds: state.locallyAcceptedMetadataUpdateIds,\n isCurrent,\n metadataState: containerState,\n onDurableStateNeedsReload: () => {\n const currentDocumentId = state.containersById.get(\n containerState.container.id,\n )?.record.documentId;\n if (typeof currentDocumentId === \"string\") {\n state.metadataDocumentIdsNeedingSync.add(currentDocumentId);\n bumpMetadataSyncSeq(state.metadataSyncSignalSeqById, currentDocumentId);\n }\n requestContainerContentsStoreSync(state);\n },\n persistence: state.persistence,\n policyOperation: input.policyOperation,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n runtime: state.runtime,\n targetSecretKey: encapsulationKeyPair.secretKey,\n });\n if (!isCurrent() || !synced) {\n return;\n }\n if (\"missing\" in synced) {\n removeMissingSyncedContainerState(\n state,\n containerState,\n host.updateSnapshot,\n );\n return;\n }\n\n const kept = keptMetadataSignals({ containerState, owedRead, synced });\n const stillCurrent = await settleConsumedMetadataSignals({\n consumedSeqById,\n documentIds: [metadataDocumentId, synced.record.documentId],\n isCurrent,\n keepsSignals: kept.keep,\n owedRead,\n readExecSql,\n state,\n });\n // A reset can land after the settlement's last check and before this resumes.\n if (!stillCurrent || !isCurrent()) return;\n // syncContainerMetadataState settles its detached candidate into this live\n // object while preserving any metadata edit that completed or queued during\n // the remote pass. Do not install its returned detached record again here:\n // doing so would overwrite that preserved live edit.\n host.updateSnapshot();\n\n // A pass that kept an owed read hands it to a fresh read next pass.\n if (\n synced.shouldRequestFollowupSync ||\n (kept.followUp && isQueuedForRead(state, metadataDocumentId))\n ) {\n requestContainerContentsStoreSync(state);\n }\n}\n\n/**\n * Whether a completed read keeps its signals for another read, and whether to\n * ask for that read now. A resumed pull reads only to its earlier bound, and a\n * superseded result discarded what it pulled: both hand the read to a fresh\n * pass. A replica lagging the listing can answer without the advertised edit;\n * that debt waits for a later pass rather than a follow-up loop.\n */\nfunction keptMetadataSignals(input: {\n containerState: ContainerState;\n owedRead: ContainerMetadataRevalidation | null;\n synced: SyncedContainerMetadataState;\n}): { followUp: boolean; keep: boolean } {\n const followUp =\n input.synced.resumedEarlierPull === true ||\n isSupersededMetadataSync(input.synced);\n const behindListing =\n input.owedRead !== null &&\n !coversAdvertisedMetadataVersion(input.containerState.doc, input.owedRead);\n return { followUp, keep: followUp || behindListing };\n}\n\nfunction isSupersededMetadataSync(\n synced: Pick<\n SyncedContainerMetadataState,\n | \"mutationSuperseded\"\n | \"pullContinuationSuperseded\"\n | \"syncIdentitySuperseded\"\n >,\n): boolean {\n return (\n synced.mutationSuperseded === true ||\n synced.pullContinuationSuperseded === true ||\n synced.syncIdentitySuperseded === true\n );\n}\n\nfunction isQueuedForRead(\n state: ContainerContentsStoreSyncState,\n documentId: string | null | undefined,\n): boolean {\n return (\n typeof documentId === \"string\" &&\n state.metadataDocumentIdsNeedingSync.has(documentId)\n );\n}\n\n/**\n * Clears the signals a completed metadata sync consumed and settles the read a\n * listing owed: the sync pulled every update this client lacked, unless a\n * newer signal queued the document again. A pass that keeps its signals\n * settles nothing. Returns false once the pass is no longer current, before\n * touching a replacement store's queue.\n */\nasync function settleConsumedMetadataSignals(input: {\n consumedSeqById: ReadonlyMap<string, number>;\n documentIds: ReadonlyArray<string | null | undefined>;\n isCurrent: () => boolean;\n keepsSignals: boolean;\n owedRead: ContainerMetadataRevalidation | null;\n readExecSql: ExecSql;\n state: ContainerContentsStoreSyncState;\n}): Promise<boolean> {\n if (input.keepsSignals) return true;\n for (const id of new Set(input.documentIds)) {\n if (typeof id !== \"string\") continue;\n if (!input.isCurrent()) return false;\n clearMetadataSyncQueueIfUnchanged({\n consumedSeqById: input.consumedSeqById,\n id,\n needingSync: input.state.metadataDocumentIdsNeedingSync,\n seqById: input.state.metadataSyncSignalSeqById,\n });\n }\n if (input.owedRead) {\n await settleOwedContainerMetadataRead(input.state, {\n execSql: input.readExecSql,\n revalidation: input.owedRead,\n });\n }\n return input.isCurrent();\n}\n\n/**\n * Syncs each held container's metadata, after requeueing reads a previous run\n * still owed. Returns false once the pass is no longer current.\n */\nasync function syncEveryContainerMetadata(\n input: Omit<\n Parameters<typeof syncSingleContainerMetadata>[0],\n \"containerState\"\n > & {\n isCreatePending: (containerId: string) => boolean;\n },\n): Promise<boolean> {\n const { isCurrent, state } = input;\n if (!state.owedMetadataReadsRestored) {\n await restoreOwedContainerMetadataReads(state, isCurrent);\n if (!isCurrent()) return false;\n state.owedMetadataReadsRestored = true;\n }\n for (const containerState of Array.from(state.containersById.values())) {\n if (input.isCreatePending(containerState.container.id)) continue;\n await syncSingleContainerMetadata({ ...input, containerState });\n if (!isCurrent()) return false;\n }\n return true;\n}\n\n/**\n * A folder whose create has not settled can carry a listed identity that\n * adoption has not verified, or has refused. Folder moves, document moves and\n * metadata edits wait for it; child and document creates wait in their own\n * create paths.\n */\nasync function loadPendingCreatePredicate(\n state: ContainerContentsStoreSyncState,\n): Promise<(containerId: string) => boolean> {\n const pending = await state.persistence.listPendingCreateIntents(\n state.runtime.infra.execSql,\n );\n const pendingIds = new Set(pending.map((intent) => intent.containerId));\n return (containerId) => pendingIds.has(containerId);\n}\n\ninterface ContainerContentsStoreSyncIterationInput {\n host: RemoteContainerHydrationHost;\n /** The drain's operation: every metadata sync of this pass shares it. */\n policyOperation: PrincipalPolicyOperation;\n reconcileRestoredAccess: (isCurrent: () => boolean) => Promise<void>;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerContentsStoreSyncState;\n syncContainerMetadata?: SyncContainerMetadata | undefined;\n}\n\nexport async function runContainerContentsStoreSyncIteration(\n input: ContainerContentsStoreSyncIterationInput,\n) {\n const { host, reconcileRestoredAccess, requestRemoteReconciliation, state } =\n input;\n const runtime = state.runtime;\n const encapsulationKeyPair = runtime.crypto.encapsulationKeyPair;\n if (\n runtime.infra.dbStatus !== \"ready\" ||\n !state.snapshot.ready ||\n !runtime.state.online ||\n !runtime.auth.isAuthenticated ||\n !encapsulationKeyPair\n ) {\n return;\n }\n const domainScope = runtime.state.domainScope;\n const isCurrent = captureStructuralSyncGeneration(state, runtime);\n\n if (!isCurrent()) return;\n await reconcileRestoredAccess(isCurrent);\n if (!isCurrent()) {\n return;\n }\n const isOrganizationBlocked = createRemoteSyncBlocker(runtime);\n\n const createdContainerCount = await syncPendingContainerCreateIntents({\n host,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n requestRemoteReconciliation,\n state,\n });\n if (!isCurrent()) {\n return;\n }\n if (createdContainerCount > 0) {\n state.documentStoresNeedPriming = true;\n host.updateSnapshot();\n }\n const isCreatePending = await loadPendingCreatePredicate(state);\n if (!isCurrent()) {\n return;\n }\n\n const movedContainerCount = await syncPendingStoreContainerMoves({\n host,\n isCreatePending,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n requestRemoteReconciliation,\n state,\n });\n if (!isCurrent()) {\n return;\n }\n if (movedContainerCount > 0) {\n state.documentStoresNeedPriming = true;\n host.updateSnapshot();\n requestDomainDocumentSync(domainScope);\n requestContainerContentsStoreSync(state);\n }\n\n const metadataSynced = await syncEveryContainerMetadata({\n ...input,\n encapsulationKeyPair,\n isCreatePending,\n isCurrent,\n });\n if (!metadataSynced) {\n return;\n }\n\n // Root adoption notifies session consumers synchronously. Let container\n // metadata converge first so a recovered system container is never exposed\n // under its placeholder name when the active root changes.\n await runContainerDocumentWork({\n isCurrent,\n onContextChanged: () => {\n if (isCurrent()) {\n requestContainerContentsStoreSync(state);\n }\n },\n onDocumentsMoved: () => {\n if (isCurrent()) {\n requestDomainDocumentSync(domainScope);\n requestContainerContentsStoreSync(state);\n }\n },\n primeDocuments: () => primeStoreDocuments(state, isCurrent),\n recoverStaleRoot: () => recoverStoreStaleRoot(state, isCurrent),\n shouldPrimeDocuments: () => state.documentStoresNeedPriming,\n // Document move intents live in the structural phase because they may\n // target containers created locally in the same session, such as Trash.\n // Root recovery rewrites stale endpoints and returns their intents to\n // pending, so replay follows recovery in this same pass.\n syncPendingDocumentMoves: () =>\n syncPendingStoreDocumentMoves({\n isCreatePending,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n state,\n }),\n });\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { loadLocalContainerProjectionDocumentsFromRuntime } from "../../workflows/container-contents/projectionView.js";
2
2
  import { didRegainSyncPrerequisites } from "../../workflows/container-contents/syncLane.js";
3
+ import { getOrCreateDomainSyncCoordinator } from "../../workflows/sync/coordination.js";
3
4
  import { isReconcilableContainerNode, isRemoteBackedContainerNode, } from "../container-contents/index.js";
4
5
  import { applyContainerSummaries, createSummaryCache, removeDocumentSummary, resetSummaryCache, snapshotLinkedContainerIdsByDocumentId, snapshotSummariesByContainerId, } from "./summaryCache.js";
5
6
  const EMPTY_SNAPSHOT = {
@@ -18,6 +19,8 @@ function computeSnapshot(state) {
18
19
  };
19
20
  }
20
21
  function emit(state) {
22
+ if (state.isDisposed())
23
+ return;
21
24
  state.snapshot = computeSnapshot(state);
22
25
  for (const listener of state.listeners) {
23
26
  try {
@@ -39,7 +42,8 @@ function notifyReconcile(state, signal) {
39
42
  }
40
43
  }
41
44
  function loadContainerSummaries(state, containerId) {
42
- if (state.cache.hydratedContainerIds.has(containerId) ||
45
+ if (state.isDisposed() ||
46
+ state.cache.hydratedContainerIds.has(containerId) ||
43
47
  state.pendingSummaryReads.has(containerId) ||
44
48
  state.runtime.infra.dbStatus !== "ready") {
45
49
  return;
@@ -55,7 +59,8 @@ function loadContainerSummaries(state, containerId) {
55
59
  .then((documents) => {
56
60
  // A runtime reset (e.g. dbStatus loss) clears this entry and the cache
57
61
  // mid-flight; do not apply a stale read to a freshly reset cache.
58
- if (state.pendingSummaryReads.get(containerId) !== pendingRead ||
62
+ if (state.isDisposed() ||
63
+ state.pendingSummaryReads.get(containerId) !== pendingRead ||
59
64
  pendingRead.discardResult) {
60
65
  return;
61
66
  }
@@ -205,8 +210,24 @@ function updateLocalProjectionRuntime(state, runtime) {
205
210
  // ready (e.g. first DB attach) so first paint reflects cached contents.
206
211
  publishHydration(state);
207
212
  }
213
+ function applyReconciledDelta(state, delta) {
214
+ if (state.isDisposed())
215
+ return;
216
+ const revision = state.deltaRevisions.get(delta);
217
+ if (revision !== undefined && revision !== state.documentRevision) {
218
+ refreshContainerSummaries(state, delta.containerId, true);
219
+ return;
220
+ }
221
+ if (state.pendingSummaryReads.has(delta.containerId)) {
222
+ refreshContainerSummaries(state, delta.containerId, true);
223
+ }
224
+ if (applyContainerSummaries(state.cache, delta)) {
225
+ emit(state);
226
+ }
227
+ }
208
228
  export function createLocalProjectionStore(input) {
209
229
  const state = {
230
+ isDisposed: getOrCreateDomainSyncCoordinator(input.runtime.state.domainScope).isDisposed,
210
231
  activeContainerId: null,
211
232
  documentRevision: 0,
212
233
  deltaRevisions: new WeakMap(),
@@ -271,19 +292,7 @@ export function createLocalProjectionStore(input) {
271
292
  state.deltaRevisions.set(delta, revision);
272
293
  return delta;
273
294
  },
274
- applyReconciled: (delta) => {
275
- const revision = state.deltaRevisions.get(delta);
276
- if (revision !== undefined && revision !== state.documentRevision) {
277
- refreshContainerSummaries(state, delta.containerId, true);
278
- return;
279
- }
280
- if (state.pendingSummaryReads.has(delta.containerId)) {
281
- refreshContainerSummaries(state, delta.containerId, true);
282
- }
283
- if (applyContainerSummaries(state.cache, delta)) {
284
- emit(state);
285
- }
286
- },
295
+ applyReconciled: (delta) => applyReconciledDelta(state, delta),
287
296
  removePersistedDocument: (localId) => removePersistedDocumentFromCache(state, localId),
288
297
  refreshPersistedDocument: (document, placementChanged) => refreshPersistedDocument(state, document, placementChanged),
289
298
  updateRuntime: (runtime) => updateLocalProjectionRuntime(state, runtime),
@@ -1 +1 @@
1
- {"version":3,"file":"localProjectionStore.js","sourceRoot":"","sources":["localProjectionStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gDAAgD,EAAE,MAAM,mDAAmD,CAAC;AACrH,OAAO,EAAE,0BAA0B,EAAE,MAAM,6CAA6C,CAAC;AAEzF,OAAO,EACL,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,qBAAqB,EACrB,iBAAiB,EAEjB,sCAAsC,EACtC,8BAA8B,GAC/B,MAAM,gBAAgB,CAAC;AAqExB,MAAM,cAAc,GAA4B;IAC9C,KAAK,EAAE,KAAK;IACZ,UAAU,EAAE,EAAE;IACd,8BAA8B,EAAE,IAAI,GAAG,EAAE;IACzC,8BAA8B,EAAE,IAAI,GAAG,EAA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AAI,CAAC,CAAC;gBAC1D,OAAO;YACT,CAAC;YACD,IAAI,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,CAAC;gBACrD,yBAAyB,CAAC,KAAK,EAAE,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;YAC5D,CAAC;YACD,IAAI,uBAAuB,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC;gBAChD,IAAI,CAAC,KAAK,CAAC,CAAC;YACd,CAAC;QACH,CAAC;QACD,uBAAuB,EAAE,CAAC,OAAO,EAAE,EAAE,CACnC,gCAAgC,CAAC,KAAK,EAAE,OAAO,CAAC;QAClD,wBAAwB,EAAE,CAAC,QAAQ,EAAE,gBAAgB,EAAE,EAAE,CACvD,wBAAwB,CAAC,KAAK,EAAE,QAAQ,EAAE,gBAAgB,CAAC;QAC7D,aAAa,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,4BAA4B,CAAC,KAAK,EAAE,OAAO,CAAC;QACxE,iBAAiB,EAAE,CAAC,QAAQ,EAAE,EAAE;YAC9B,KAAK,CAAC,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACvC,OAAO,GAAG,EAAE;gBACV,KAAK,CAAC,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC5C,CAAC,CAAC;QACJ,CAAC;QACD,iBAAiB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,cAAc;KAC9C,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport { loadLocalContainerProjectionDocumentsFromRuntime } from \"../../workflows/container-contents/projectionView\";\nimport { didRegainSyncPrerequisites } from \"../../workflows/container-contents/syncLane\";\nimport type { ContainerContentsStoreRuntime } from \"../container-contents\";\nimport {\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../container-contents\";\nimport type { ContainerContentsStore } from \"../container-contents/types\";\nimport {\n applyContainerSummaries,\n createSummaryCache,\n removeDocumentSummary,\n resetSummaryCache,\n type SummaryCache,\n snapshotLinkedContainerIdsByDocumentId,\n snapshotSummariesByContainerId,\n} from \"./summaryCache\";\nimport type {\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n} from \"./types\";\n\n/**\n * Signals the local projection store raises so the background reconciler\n * (Layer B) knows what to sync. The store never performs remote I/O itself.\n */\nexport interface LocalProjectionReconcileSignal {\n reason:\n | \"hydrated\"\n | \"active-changed\"\n | \"prerequisites-regained\"\n | \"remote-containers-added\";\n activeContainerId: string | null;\n}\n\nexport type LocalProjectionReconcileListener = (\n signal: LocalProjectionReconcileSignal,\n) => void;\n\nexport interface LocalProjectionStore {\n getSnapshot: () => LocalProjectionSnapshot;\n subscribe: (listener: () => void) => () => void;\n setActiveContainer: (containerId: string | null) => void;\n getActiveContainerId: () => string | null;\n applyReconciled: (delta: LocalProjectionReconciledDelta) => void;\n loadContainerDelta: (\n containerId: string,\n ) => Promise<LocalProjectionReconciledDelta>;\n removePersistedDocument: (localId: string) => void;\n refreshPersistedDocument: (\n document: DocumentSummary,\n placementChanged?: boolean,\n ) => void;\n updateRuntime: (runtime: ContainerContentsStoreRuntime) => void;\n /** Registered by the reconciler; returns an unsubscribe handle. */\n onReconcileSignal: (listener: LocalProjectionReconcileListener) => () => void;\n getContainerStore: () => ContainerContentsStore;\n}\n\ninterface LocalProjectionStoreState {\n activeContainerId: string | null;\n documentRevision: number;\n deltaRevisions: WeakMap<LocalProjectionReconciledDelta, number>;\n cache: SummaryCache;\n containerStore: ContainerContentsStore;\n hydratedContainerSummaries: boolean;\n listeners: Set<() => void>;\n /**\n * A sync-prerequisite regain (auth, connectivity, or key pair) that arrived\n * before the container tree was ready. The signal's reset-and-backfill must\n * not be lost to startup ordering, so it is latched here and flushed once\n * hydration completes.\n */\n pendingPrerequisitesRegained: boolean;\n reconcileListeners: Set<LocalProjectionReconcileListener>;\n runtime: ContainerContentsStoreRuntime;\n snapshot: LocalProjectionSnapshot;\n pendingSummaryReads: Map<string, PendingSummaryRead>;\n}\n\ninterface PendingSummaryRead {\n discardResult: boolean;\n reloadAfter: boolean;\n}\n\nconst EMPTY_SNAPSHOT: LocalProjectionSnapshot = {\n ready: false,\n containers: [],\n documentSummariesByContainerId: new Map(),\n linkedContainerIdsByDocumentId: new Map(),\n};\n\nfunction computeSnapshot(\n state: LocalProjectionStoreState,\n): LocalProjectionSnapshot {\n const containerSnapshot = state.containerStore.getSnapshot();\n return {\n ready: containerSnapshot.ready,\n containers: containerSnapshot.nodes,\n documentSummariesByContainerId: snapshotSummariesByContainerId(state.cache),\n linkedContainerIdsByDocumentId: snapshotLinkedContainerIdsByDocumentId(\n state.cache,\n ),\n };\n}\n\nfunction emit(state: LocalProjectionStoreState): void {\n state.snapshot = computeSnapshot(state);\n for (const listener of state.listeners) {\n try {\n listener();\n } catch {\n // Keep one subscriber failure from blocking later subscribers.\n }\n }\n}\n\nfunction notifyReconcile(\n state: LocalProjectionStoreState,\n signal: LocalProjectionReconcileSignal,\n): void {\n for (const listener of state.reconcileListeners) {\n try {\n listener(signal);\n } catch {\n // Reconciler failures must not break the read path.\n }\n }\n}\n\nfunction loadContainerSummaries(\n state: LocalProjectionStoreState,\n containerId: string,\n): void {\n if (\n state.cache.hydratedContainerIds.has(containerId) ||\n state.pendingSummaryReads.has(containerId) ||\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return;\n }\n\n const pendingRead: PendingSummaryRead = {\n discardResult: false,\n reloadAfter: false,\n };\n void loadLocalContainerProjectionDocumentsFromRuntime({\n containerIds: [containerId],\n runtime: state.runtime,\n })\n .then((documents) => {\n // A runtime reset (e.g. dbStatus loss) clears this entry and the cache\n // mid-flight; do not apply a stale read to a freshly reset cache.\n if (\n state.pendingSummaryReads.get(containerId) !== pendingRead ||\n pendingRead.discardResult\n ) {\n return;\n }\n const changed = applyContainerSummaries(state.cache, {\n containerId,\n documentSummaries: documents.documentSummaries,\n linkedContainerIdsByDocumentId:\n documents.linkedContainerIdsByDocumentId,\n });\n if (changed) {\n emit(state);\n }\n })\n .catch(() => {\n // Local read failures fall back to an empty list; the reconciler retries.\n })\n .finally(() => {\n if (state.pendingSummaryReads.get(containerId) !== pendingRead) {\n return;\n }\n state.pendingSummaryReads.delete(containerId);\n if (pendingRead.reloadAfter) {\n state.cache.hydratedContainerIds.delete(containerId);\n loadContainerSummaries(state, containerId);\n }\n });\n\n state.pendingSummaryReads.set(containerId, pendingRead);\n}\n\nfunction refreshContainerSummaries(\n state: LocalProjectionStoreState,\n containerId: string,\n discardPendingRead = false,\n): void {\n state.cache.hydratedContainerIds.delete(containerId);\n const pendingRead = state.pendingSummaryReads.get(containerId);\n if (pendingRead) {\n // Publish ordinary reads before the trailing refresh so autosaves cannot\n // starve first paint. Deletion and reconciliation must reject older rows.\n pendingRead.reloadAfter = true;\n pendingRead.discardResult ||= discardPendingRead;\n } else {\n loadContainerSummaries(state, containerId);\n }\n}\n\nfunction refreshPersistedDocument(\n state: LocalProjectionStoreState,\n document: DocumentSummary,\n placementChanged = false,\n): void {\n state.documentRevision += 1;\n const containerIds = new Set(state.pendingSummaryReads.keys());\n if (\n state.activeContainerId &&\n state.activeContainerId === document.containerId\n ) {\n containerIds.add(state.activeContainerId);\n }\n for (const [containerId, summaries] of state.cache.summariesByContainerId) {\n if (\n containerId === document.containerId ||\n summaries.some((summary) => summary.id === document.id)\n ) {\n containerIds.add(containerId);\n }\n }\n for (const containerId of containerIds) {\n refreshContainerSummaries(state, containerId, placementChanged);\n }\n}\n\nfunction markHydratedIfReady(state: LocalProjectionStoreState): boolean {\n if (\n state.hydratedContainerSummaries ||\n state.runtime.infra.dbStatus !== \"ready\" ||\n !state.containerStore.getSnapshot().ready\n ) {\n return false;\n }\n\n state.hydratedContainerSummaries = true;\n if (state.activeContainerId) {\n loadContainerSummaries(state, state.activeContainerId);\n }\n return true;\n}\n\nfunction flushPendingPrerequisitesRegained(\n state: LocalProjectionStoreState,\n): void {\n if (\n !state.pendingPrerequisitesRegained ||\n !state.hydratedContainerSummaries ||\n !state.containerStore.getSnapshot().ready\n ) {\n return;\n }\n state.pendingPrerequisitesRegained = false;\n notifyReconcile(state, {\n reason: \"prerequisites-regained\",\n activeContainerId: state.activeContainerId,\n });\n}\n\nfunction publishHydration(state: LocalProjectionStoreState): boolean {\n const didMarkHydrated = markHydratedIfReady(state);\n emit(state);\n if (didMarkHydrated) {\n notifyReconcile(state, {\n reason: \"hydrated\",\n activeContainerId: state.activeContainerId,\n });\n }\n // Backfills read getSnapshot(), so publish the tree before requesting them.\n flushPendingPrerequisitesRegained(state);\n return didMarkHydrated;\n}\n\nfunction resetProjection(state: LocalProjectionStoreState): void {\n state.documentRevision += 1;\n resetSummaryCache(state.cache);\n state.pendingSummaryReads.clear();\n state.hydratedContainerSummaries = false;\n}\n\nfunction hasRemoteBackedContainerMembershipGrowth(\n previous: LocalProjectionSnapshot[\"containers\"],\n next: LocalProjectionSnapshot[\"containers\"],\n homeOrganizationId: string | null,\n activeContainerId: string | null,\n): boolean {\n const isRemoteReconcilable = (\n container: LocalProjectionSnapshot[\"containers\"][number],\n ) => isReconcilableContainerNode(container, homeOrganizationId);\n const previousIds = new Set(\n previous.flatMap((container) =>\n isRemoteReconcilable(container) ? [container.id] : [],\n ),\n );\n if (\n next.some(\n (container) =>\n isRemoteReconcilable(container) && !previousIds.has(container.id),\n )\n ) {\n return true;\n }\n if (!activeContainerId) {\n return false;\n }\n const wasActiveRemoteBacked = previous.some(\n (container) =>\n container.id === activeContainerId &&\n isRemoteBackedContainerNode(container),\n );\n return (\n !wasActiveRemoteBacked &&\n next.some(\n (container) =>\n container.id === activeContainerId &&\n isRemoteBackedContainerNode(container),\n )\n );\n}\n\nfunction removePersistedDocumentFromCache(\n state: LocalProjectionStoreState,\n localId: string,\n): void {\n state.documentRevision += 1;\n // The deleted row may exist only in an in-flight first read, so invalidating\n // just containers that already cached it would allow it to reappear offline.\n for (const containerId of state.pendingSummaryReads.keys()) {\n refreshContainerSummaries(state, containerId, true);\n }\n if (removeDocumentSummary(state.cache, localId)) {\n emit(state);\n }\n}\n\nfunction updateLocalProjectionRuntime(\n state: LocalProjectionStoreState,\n runtime: ContainerContentsStoreRuntime,\n): void {\n const previousRuntime = state.runtime;\n state.runtime = runtime;\n if (\n runtime.infra.execSql !== previousRuntime.infra.execSql ||\n runtime.state.domainScope !== previousRuntime.state.domainScope\n ) {\n resetProjection(state);\n }\n state.containerStore.updateRuntime(runtime);\n\n // Latch before the readiness checks so a regain that arrives while the\n // database or container tree is still warming up is flushed after\n // hydration instead of being lost to startup ordering.\n if (didRegainSyncPrerequisites(previousRuntime, runtime)) {\n state.pendingPrerequisitesRegained = true;\n }\n\n if (runtime.infra.dbStatus !== \"ready\") {\n resetProjection(state);\n emit(state);\n return;\n }\n\n // Reload the active container's summaries when the local store becomes\n // ready (e.g. first DB attach) so first paint reflects cached contents.\n publishHydration(state);\n}\n\nexport function createLocalProjectionStore(input: {\n containerStore: ContainerContentsStore;\n runtime: ContainerContentsStoreRuntime;\n}): LocalProjectionStore {\n const state: LocalProjectionStoreState = {\n activeContainerId: null,\n documentRevision: 0,\n deltaRevisions: new WeakMap(),\n cache: createSummaryCache(),\n containerStore: input.containerStore,\n hydratedContainerSummaries: false,\n listeners: new Set(),\n pendingPrerequisitesRegained: false,\n reconcileListeners: new Set(),\n runtime: input.runtime,\n snapshot: EMPTY_SNAPSHOT,\n pendingSummaryReads: new Map(),\n };\n state.snapshot = computeSnapshot(state);\n\n // Re-emit whenever the underlying container tree changes (mutations, remote\n // hydration). This keeps the merged snapshot in step with the tree store.\n input.containerStore.subscribe(() => {\n const previousContainers = state.snapshot.containers;\n const didMarkHydrated = publishHydration(state);\n // Authentication can schedule the initial idle backfill before the\n // asynchronous remote tree crawl discovers this identity's real root and\n // system children. Re-arm backfill after those remotely-listable ids become\n // visible. Compare membership, not node objects, so metadata/sync-state\n // churn cannot create a reconciliation loop.\n if (\n !didMarkHydrated &&\n hasRemoteBackedContainerMembershipGrowth(\n previousContainers,\n state.snapshot.containers,\n state.runtime.auth.organizationId,\n state.activeContainerId,\n )\n ) {\n notifyReconcile(state, {\n reason: \"remote-containers-added\",\n activeContainerId: state.activeContainerId,\n });\n }\n });\n\n return {\n getSnapshot: () => state.snapshot,\n subscribe: (listener) => {\n state.listeners.add(listener);\n return () => {\n state.listeners.delete(listener);\n };\n },\n setActiveContainer: (containerId) => {\n if (state.activeContainerId === containerId) {\n return;\n }\n state.activeContainerId = containerId;\n if (containerId) {\n refreshContainerSummaries(state, containerId);\n }\n notifyReconcile(state, {\n reason: \"active-changed\",\n activeContainerId: containerId,\n });\n },\n getActiveContainerId: () => state.activeContainerId,\n loadContainerDelta: async (containerId) => {\n const revision = state.documentRevision;\n const documents = await loadLocalContainerProjectionDocumentsFromRuntime({\n containerIds: [containerId],\n runtime: state.runtime,\n });\n const delta = { containerId, ...documents };\n state.deltaRevisions.set(delta, revision);\n return delta;\n },\n applyReconciled: (delta) => {\n const revision = state.deltaRevisions.get(delta);\n if (revision !== undefined && revision !== state.documentRevision) {\n refreshContainerSummaries(state, delta.containerId, true);\n return;\n }\n if (state.pendingSummaryReads.has(delta.containerId)) {\n refreshContainerSummaries(state, delta.containerId, true);\n }\n if (applyContainerSummaries(state.cache, delta)) {\n emit(state);\n }\n },\n removePersistedDocument: (localId) =>\n removePersistedDocumentFromCache(state, localId),\n refreshPersistedDocument: (document, placementChanged) =>\n refreshPersistedDocument(state, document, placementChanged),\n updateRuntime: (runtime) => updateLocalProjectionRuntime(state, runtime),\n onReconcileSignal: (listener) => {\n state.reconcileListeners.add(listener);\n return () => {\n state.reconcileListeners.delete(listener);\n };\n },\n getContainerStore: () => state.containerStore,\n };\n}\n"]}
1
+ {"version":3,"file":"localProjectionStore.js","sourceRoot":"","sources":["localProjectionStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gDAAgD,EAAE,MAAM,mDAAmD,CAAC;AACrH,OAAO,EAAE,0BAA0B,EAAE,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AAE,gBAAgB,EAAE,EAAE,CACvD,wBAAwB,CAAC,KAAK,EAAE,QAAQ,EAAE,gBAAgB,CAAC;QAC7D,aAAa,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,4BAA4B,CAAC,KAAK,EAAE,OAAO,CAAC;QACxE,iBAAiB,EAAE,CAAC,QAAQ,EAAE,EAAE;YAC9B,KAAK,CAAC,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACvC,OAAO,GAAG,EAAE;gBACV,KAAK,CAAC,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC5C,CAAC,CAAC;QACJ,CAAC;QACD,iBAAiB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,cAAc;KAC9C,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport { loadLocalContainerProjectionDocumentsFromRuntime } from \"../../workflows/container-contents/projectionView\";\nimport { didRegainSyncPrerequisites } from \"../../workflows/container-contents/syncLane\";\nimport { getOrCreateDomainSyncCoordinator } from \"../../workflows/sync/coordination\";\nimport type { ContainerContentsStoreRuntime } from \"../container-contents\";\nimport {\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../container-contents\";\nimport type { ContainerContentsStore } from \"../container-contents/types\";\nimport {\n applyContainerSummaries,\n createSummaryCache,\n removeDocumentSummary,\n resetSummaryCache,\n type SummaryCache,\n snapshotLinkedContainerIdsByDocumentId,\n snapshotSummariesByContainerId,\n} from \"./summaryCache\";\nimport type {\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n} from \"./types\";\n\n/**\n * Signals the local projection store raises so the background reconciler\n * (Layer B) knows what to sync. The store never performs remote I/O itself.\n */\nexport interface LocalProjectionReconcileSignal {\n reason:\n | \"hydrated\"\n | \"active-changed\"\n | \"prerequisites-regained\"\n | \"remote-containers-added\";\n activeContainerId: string | null;\n}\n\nexport type LocalProjectionReconcileListener = (\n signal: LocalProjectionReconcileSignal,\n) => void;\n\nexport interface LocalProjectionStore {\n getSnapshot: () => LocalProjectionSnapshot;\n subscribe: (listener: () => void) => () => void;\n setActiveContainer: (containerId: string | null) => void;\n getActiveContainerId: () => string | null;\n applyReconciled: (delta: LocalProjectionReconciledDelta) => void;\n loadContainerDelta: (\n containerId: string,\n ) => Promise<LocalProjectionReconciledDelta>;\n removePersistedDocument: (localId: string) => void;\n refreshPersistedDocument: (\n document: DocumentSummary,\n placementChanged?: boolean,\n ) => void;\n updateRuntime: (runtime: ContainerContentsStoreRuntime) => void;\n /** Registered by the reconciler; returns an unsubscribe handle. */\n onReconcileSignal: (listener: LocalProjectionReconcileListener) => () => void;\n getContainerStore: () => ContainerContentsStore;\n}\n\ninterface LocalProjectionStoreState {\n isDisposed: () => boolean;\n activeContainerId: string | null;\n documentRevision: number;\n deltaRevisions: WeakMap<LocalProjectionReconciledDelta, number>;\n cache: SummaryCache;\n containerStore: ContainerContentsStore;\n hydratedContainerSummaries: boolean;\n listeners: Set<() => void>;\n /**\n * A sync-prerequisite regain (auth, connectivity, or key pair) that arrived\n * before the container tree was ready. The signal's reset-and-backfill must\n * not be lost to startup ordering, so it is latched here and flushed once\n * hydration completes.\n */\n pendingPrerequisitesRegained: boolean;\n reconcileListeners: Set<LocalProjectionReconcileListener>;\n runtime: ContainerContentsStoreRuntime;\n snapshot: LocalProjectionSnapshot;\n pendingSummaryReads: Map<string, PendingSummaryRead>;\n}\n\ninterface PendingSummaryRead {\n discardResult: boolean;\n reloadAfter: boolean;\n}\n\nconst EMPTY_SNAPSHOT: LocalProjectionSnapshot = {\n ready: false,\n containers: [],\n documentSummariesByContainerId: new Map(),\n linkedContainerIdsByDocumentId: new Map(),\n};\n\nfunction computeSnapshot(\n state: LocalProjectionStoreState,\n): LocalProjectionSnapshot {\n const containerSnapshot = state.containerStore.getSnapshot();\n return {\n ready: containerSnapshot.ready,\n containers: containerSnapshot.nodes,\n documentSummariesByContainerId: snapshotSummariesByContainerId(state.cache),\n linkedContainerIdsByDocumentId: snapshotLinkedContainerIdsByDocumentId(\n state.cache,\n ),\n };\n}\n\nfunction emit(state: LocalProjectionStoreState): void {\n if (state.isDisposed()) return;\n state.snapshot = computeSnapshot(state);\n for (const listener of state.listeners) {\n try {\n listener();\n } catch {\n // Keep one subscriber failure from blocking later subscribers.\n }\n }\n}\n\nfunction notifyReconcile(\n state: LocalProjectionStoreState,\n signal: LocalProjectionReconcileSignal,\n): void {\n for (const listener of state.reconcileListeners) {\n try {\n listener(signal);\n } catch {\n // Reconciler failures must not break the read path.\n }\n }\n}\n\nfunction loadContainerSummaries(\n state: LocalProjectionStoreState,\n containerId: string,\n): void {\n if (\n state.isDisposed() ||\n state.cache.hydratedContainerIds.has(containerId) ||\n state.pendingSummaryReads.has(containerId) ||\n state.runtime.infra.dbStatus !== \"ready\"\n ) {\n return;\n }\n\n const pendingRead: PendingSummaryRead = {\n discardResult: false,\n reloadAfter: false,\n };\n void loadLocalContainerProjectionDocumentsFromRuntime({\n containerIds: [containerId],\n runtime: state.runtime,\n })\n .then((documents) => {\n // A runtime reset (e.g. dbStatus loss) clears this entry and the cache\n // mid-flight; do not apply a stale read to a freshly reset cache.\n if (\n state.isDisposed() ||\n state.pendingSummaryReads.get(containerId) !== pendingRead ||\n pendingRead.discardResult\n ) {\n return;\n }\n const changed = applyContainerSummaries(state.cache, {\n containerId,\n documentSummaries: documents.documentSummaries,\n linkedContainerIdsByDocumentId:\n documents.linkedContainerIdsByDocumentId,\n });\n if (changed) {\n emit(state);\n }\n })\n .catch(() => {\n // Local read failures fall back to an empty list; the reconciler retries.\n })\n .finally(() => {\n if (state.pendingSummaryReads.get(containerId) !== pendingRead) {\n return;\n }\n state.pendingSummaryReads.delete(containerId);\n if (pendingRead.reloadAfter) {\n state.cache.hydratedContainerIds.delete(containerId);\n loadContainerSummaries(state, containerId);\n }\n });\n\n state.pendingSummaryReads.set(containerId, pendingRead);\n}\n\nfunction refreshContainerSummaries(\n state: LocalProjectionStoreState,\n containerId: string,\n discardPendingRead = false,\n): void {\n state.cache.hydratedContainerIds.delete(containerId);\n const pendingRead = state.pendingSummaryReads.get(containerId);\n if (pendingRead) {\n // Publish ordinary reads before the trailing refresh so autosaves cannot\n // starve first paint. Deletion and reconciliation must reject older rows.\n pendingRead.reloadAfter = true;\n pendingRead.discardResult ||= discardPendingRead;\n } else {\n loadContainerSummaries(state, containerId);\n }\n}\n\nfunction refreshPersistedDocument(\n state: LocalProjectionStoreState,\n document: DocumentSummary,\n placementChanged = false,\n): void {\n state.documentRevision += 1;\n const containerIds = new Set(state.pendingSummaryReads.keys());\n if (\n state.activeContainerId &&\n state.activeContainerId === document.containerId\n ) {\n containerIds.add(state.activeContainerId);\n }\n for (const [containerId, summaries] of state.cache.summariesByContainerId) {\n if (\n containerId === document.containerId ||\n summaries.some((summary) => summary.id === document.id)\n ) {\n containerIds.add(containerId);\n }\n }\n for (const containerId of containerIds) {\n refreshContainerSummaries(state, containerId, placementChanged);\n }\n}\n\nfunction markHydratedIfReady(state: LocalProjectionStoreState): boolean {\n if (\n state.hydratedContainerSummaries ||\n state.runtime.infra.dbStatus !== \"ready\" ||\n !state.containerStore.getSnapshot().ready\n ) {\n return false;\n }\n\n state.hydratedContainerSummaries = true;\n if (state.activeContainerId) {\n loadContainerSummaries(state, state.activeContainerId);\n }\n return true;\n}\n\nfunction flushPendingPrerequisitesRegained(\n state: LocalProjectionStoreState,\n): void {\n if (\n !state.pendingPrerequisitesRegained ||\n !state.hydratedContainerSummaries ||\n !state.containerStore.getSnapshot().ready\n ) {\n return;\n }\n state.pendingPrerequisitesRegained = false;\n notifyReconcile(state, {\n reason: \"prerequisites-regained\",\n activeContainerId: state.activeContainerId,\n });\n}\n\nfunction publishHydration(state: LocalProjectionStoreState): boolean {\n const didMarkHydrated = markHydratedIfReady(state);\n emit(state);\n if (didMarkHydrated) {\n notifyReconcile(state, {\n reason: \"hydrated\",\n activeContainerId: state.activeContainerId,\n });\n }\n // Backfills read getSnapshot(), so publish the tree before requesting them.\n flushPendingPrerequisitesRegained(state);\n return didMarkHydrated;\n}\n\nfunction resetProjection(state: LocalProjectionStoreState): void {\n state.documentRevision += 1;\n resetSummaryCache(state.cache);\n state.pendingSummaryReads.clear();\n state.hydratedContainerSummaries = false;\n}\n\nfunction hasRemoteBackedContainerMembershipGrowth(\n previous: LocalProjectionSnapshot[\"containers\"],\n next: LocalProjectionSnapshot[\"containers\"],\n homeOrganizationId: string | null,\n activeContainerId: string | null,\n): boolean {\n const isRemoteReconcilable = (\n container: LocalProjectionSnapshot[\"containers\"][number],\n ) => isReconcilableContainerNode(container, homeOrganizationId);\n const previousIds = new Set(\n previous.flatMap((container) =>\n isRemoteReconcilable(container) ? [container.id] : [],\n ),\n );\n if (\n next.some(\n (container) =>\n isRemoteReconcilable(container) && !previousIds.has(container.id),\n )\n ) {\n return true;\n }\n if (!activeContainerId) {\n return false;\n }\n const wasActiveRemoteBacked = previous.some(\n (container) =>\n container.id === activeContainerId &&\n isRemoteBackedContainerNode(container),\n );\n return (\n !wasActiveRemoteBacked &&\n next.some(\n (container) =>\n container.id === activeContainerId &&\n isRemoteBackedContainerNode(container),\n )\n );\n}\n\nfunction removePersistedDocumentFromCache(\n state: LocalProjectionStoreState,\n localId: string,\n): void {\n state.documentRevision += 1;\n // The deleted row may exist only in an in-flight first read, so invalidating\n // just containers that already cached it would allow it to reappear offline.\n for (const containerId of state.pendingSummaryReads.keys()) {\n refreshContainerSummaries(state, containerId, true);\n }\n if (removeDocumentSummary(state.cache, localId)) {\n emit(state);\n }\n}\n\nfunction updateLocalProjectionRuntime(\n state: LocalProjectionStoreState,\n runtime: ContainerContentsStoreRuntime,\n): void {\n const previousRuntime = state.runtime;\n state.runtime = runtime;\n if (\n runtime.infra.execSql !== previousRuntime.infra.execSql ||\n runtime.state.domainScope !== previousRuntime.state.domainScope\n ) {\n resetProjection(state);\n }\n state.containerStore.updateRuntime(runtime);\n\n // Latch before the readiness checks so a regain that arrives while the\n // database or container tree is still warming up is flushed after\n // hydration instead of being lost to startup ordering.\n if (didRegainSyncPrerequisites(previousRuntime, runtime)) {\n state.pendingPrerequisitesRegained = true;\n }\n\n if (runtime.infra.dbStatus !== \"ready\") {\n resetProjection(state);\n emit(state);\n return;\n }\n\n // Reload the active container's summaries when the local store becomes\n // ready (e.g. first DB attach) so first paint reflects cached contents.\n publishHydration(state);\n}\n\nfunction applyReconciledDelta(\n state: LocalProjectionStoreState,\n delta: LocalProjectionReconciledDelta,\n): void {\n if (state.isDisposed()) return;\n const revision = state.deltaRevisions.get(delta);\n if (revision !== undefined && revision !== state.documentRevision) {\n refreshContainerSummaries(state, delta.containerId, true);\n return;\n }\n if (state.pendingSummaryReads.has(delta.containerId)) {\n refreshContainerSummaries(state, delta.containerId, true);\n }\n if (applyContainerSummaries(state.cache, delta)) {\n emit(state);\n }\n}\n\nexport function createLocalProjectionStore(input: {\n containerStore: ContainerContentsStore;\n runtime: ContainerContentsStoreRuntime;\n}): LocalProjectionStore {\n const state: LocalProjectionStoreState = {\n isDisposed: getOrCreateDomainSyncCoordinator(\n input.runtime.state.domainScope,\n ).isDisposed,\n activeContainerId: null,\n documentRevision: 0,\n deltaRevisions: new WeakMap(),\n cache: createSummaryCache(),\n containerStore: input.containerStore,\n hydratedContainerSummaries: false,\n listeners: new Set(),\n pendingPrerequisitesRegained: false,\n reconcileListeners: new Set(),\n runtime: input.runtime,\n snapshot: EMPTY_SNAPSHOT,\n pendingSummaryReads: new Map(),\n };\n state.snapshot = computeSnapshot(state);\n\n // Re-emit whenever the underlying container tree changes (mutations, remote\n // hydration). This keeps the merged snapshot in step with the tree store.\n input.containerStore.subscribe(() => {\n const previousContainers = state.snapshot.containers;\n const didMarkHydrated = publishHydration(state);\n // Authentication can schedule the initial idle backfill before the\n // asynchronous remote tree crawl discovers this identity's real root and\n // system children. Re-arm backfill after those remotely-listable ids become\n // visible. Compare membership, not node objects, so metadata/sync-state\n // churn cannot create a reconciliation loop.\n if (\n !didMarkHydrated &&\n hasRemoteBackedContainerMembershipGrowth(\n previousContainers,\n state.snapshot.containers,\n state.runtime.auth.organizationId,\n state.activeContainerId,\n )\n ) {\n notifyReconcile(state, {\n reason: \"remote-containers-added\",\n activeContainerId: state.activeContainerId,\n });\n }\n });\n\n return {\n getSnapshot: () => state.snapshot,\n subscribe: (listener) => {\n state.listeners.add(listener);\n return () => {\n state.listeners.delete(listener);\n };\n },\n setActiveContainer: (containerId) => {\n if (state.activeContainerId === containerId) {\n return;\n }\n state.activeContainerId = containerId;\n if (containerId) {\n refreshContainerSummaries(state, containerId);\n }\n notifyReconcile(state, {\n reason: \"active-changed\",\n activeContainerId: containerId,\n });\n },\n getActiveContainerId: () => state.activeContainerId,\n loadContainerDelta: async (containerId) => {\n const revision = state.documentRevision;\n const documents = await loadLocalContainerProjectionDocumentsFromRuntime({\n containerIds: [containerId],\n runtime: state.runtime,\n });\n const delta = { containerId, ...documents };\n state.deltaRevisions.set(delta, revision);\n return delta;\n },\n applyReconciled: (delta) => applyReconciledDelta(state, delta),\n removePersistedDocument: (localId) =>\n removePersistedDocumentFromCache(state, localId),\n refreshPersistedDocument: (document, placementChanged) =>\n refreshPersistedDocument(state, document, placementChanged),\n updateRuntime: (runtime) => updateLocalProjectionRuntime(state, runtime),\n onReconcileSignal: (listener) => {\n state.reconcileListeners.add(listener);\n return () => {\n state.reconcileListeners.delete(listener);\n };\n },\n getContainerStore: () => state.containerStore,\n };\n}\n"]}
@@ -8,12 +8,12 @@ const localProjectionStoresByScope = new WeakMap();
8
8
  * contents store is cached.
9
9
  */
10
10
  export function getOrCreateLocalProjectionStore(input) {
11
+ const containerStore = getOrCreateContainerContentsStore(input.domainScope, input.runtime, input.options ?? {});
11
12
  const existing = localProjectionStoresByScope.get(input.domainScope);
12
- if (existing) {
13
+ if (existing?.getContainerStore() === containerStore) {
13
14
  existing.updateRuntime(input.runtime);
14
15
  return existing;
15
16
  }
16
- const containerStore = getOrCreateContainerContentsStore(input.domainScope, input.runtime, input.options ?? {});
17
17
  const store = createLocalProjectionStore({
18
18
  containerStore,
19
19
  runtime: input.runtime,
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","sourceRoot":"","sources":["registry.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,iCAAiC,GAClC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,0BAA0B,GAE3B,MAAM,wBAAwB,CAAC;AAEhC,MAAM,4BAA4B,GAAG,IAAI,OAAO,EAG7C,CAAC;AAEJ;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAAC,KAI/C;IACC,MAAM,QAAQ,GAAG,4BAA4B,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACrE,IAAI,QAAQ,EAAE,CAAC;QACb,QAAQ,CAAC,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACtC,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,cAAc,GAAG,iCAAiC,CACtD,KAAK,CAAC,WAAW,EACjB,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,OAAO,IAAI,EAAE,CACpB,CAAC;IACF,MAAM,KAAK,GAAG,0BAA0B,CAAC;QACvC,cAAc;QACd,OAAO,EAAE,KAAK,CAAC,OAAO;KACvB,CAAC,CAAC;IACH,4BAA4B,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC;IAC3D,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { ContainerContentsStoreRuntime } from \"../container-contents\";\nimport {\n type ContainerContentsStoreOptions,\n getOrCreateContainerContentsStore,\n} from \"../container-contents\";\nimport {\n createLocalProjectionStore,\n type LocalProjectionStore,\n} from \"./localProjectionStore\";\n\nconst localProjectionStoresByScope = new WeakMap<\n DomainScope,\n LocalProjectionStore\n>();\n\n/**\n * Get (or lazily create) the device-first local projection store for a domain\n * scope. The store is cached per scope so every consumer in the same\n * storage/identity context shares one view — mirroring how the container\n * contents store is cached.\n */\nexport function getOrCreateLocalProjectionStore(input: {\n domainScope: DomainScope;\n runtime: ContainerContentsStoreRuntime;\n options?: ContainerContentsStoreOptions | undefined;\n}): LocalProjectionStore {\n const existing = localProjectionStoresByScope.get(input.domainScope);\n if (existing) {\n existing.updateRuntime(input.runtime);\n return existing;\n }\n\n const containerStore = getOrCreateContainerContentsStore(\n input.domainScope,\n input.runtime,\n input.options ?? {},\n );\n const store = createLocalProjectionStore({\n containerStore,\n runtime: input.runtime,\n });\n localProjectionStoresByScope.set(input.domainScope, store);\n return store;\n}\n"]}
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["registry.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,iCAAiC,GAClC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,0BAA0B,GAE3B,MAAM,wBAAwB,CAAC;AAEhC,MAAM,4BAA4B,GAAG,IAAI,OAAO,EAG7C,CAAC;AAEJ;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAAC,KAI/C;IACC,MAAM,cAAc,GAAG,iCAAiC,CACtD,KAAK,CAAC,WAAW,EACjB,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,OAAO,IAAI,EAAE,CACpB,CAAC;IACF,MAAM,QAAQ,GAAG,4BAA4B,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACrE,IAAI,QAAQ,EAAE,iBAAiB,EAAE,KAAK,cAAc,EAAE,CAAC;QACrD,QAAQ,CAAC,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACtC,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,KAAK,GAAG,0BAA0B,CAAC;QACvC,cAAc;QACd,OAAO,EAAE,KAAK,CAAC,OAAO;KACvB,CAAC,CAAC;IACH,4BAA4B,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC;IAC3D,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { ContainerContentsStoreRuntime } from \"../container-contents\";\nimport {\n type ContainerContentsStoreOptions,\n getOrCreateContainerContentsStore,\n} from \"../container-contents\";\nimport {\n createLocalProjectionStore,\n type LocalProjectionStore,\n} from \"./localProjectionStore\";\n\nconst localProjectionStoresByScope = new WeakMap<\n DomainScope,\n LocalProjectionStore\n>();\n\n/**\n * Get (or lazily create) the device-first local projection store for a domain\n * scope. The store is cached per scope so every consumer in the same\n * storage/identity context shares one view — mirroring how the container\n * contents store is cached.\n */\nexport function getOrCreateLocalProjectionStore(input: {\n domainScope: DomainScope;\n runtime: ContainerContentsStoreRuntime;\n options?: ContainerContentsStoreOptions | undefined;\n}): LocalProjectionStore {\n const containerStore = getOrCreateContainerContentsStore(\n input.domainScope,\n input.runtime,\n input.options ?? {},\n );\n const existing = localProjectionStoresByScope.get(input.domainScope);\n if (existing?.getContainerStore() === containerStore) {\n existing.updateRuntime(input.runtime);\n return existing;\n }\n\n const store = createLocalProjectionStore({\n containerStore,\n runtime: input.runtime,\n });\n localProjectionStoresByScope.set(input.domainScope, store);\n return store;\n}\n"]}