@tearleads/client-sdk 0.1.252 → 0.1.253
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Tearleads.js +3 -3
- package/Tearleads.js.map +1 -1
- package/client/containerContents/index.d.ts +2 -0
- package/client/containerContents/index.js +4 -9
- package/client/containerContents/index.js.map +1 -1
- package/client/containerContents/storeRuntime.d.ts +17 -0
- package/client/containerContents/storeRuntime.js +31 -0
- package/client/containerContents/storeRuntime.js.map +1 -0
- package/client/deviceFirst/index.d.ts +2 -3
- package/client/deviceFirst/index.js +44 -22
- package/client/deviceFirst/index.js.map +1 -1
- package/client/runtime/workflowRuntime.d.ts +2 -0
- package/client/runtime/workflowRuntime.js +13 -6
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/data/sync/syncCoordinator.js +17 -10
- package/data/sync/syncCoordinator.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/containerContentsStore.d.ts +3 -9
- package/stores/container-contents/containerContentsStore.js +24 -21
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/containerState/storeScope.js +6 -0
- package/stores/container-contents/containerState/storeScope.js.map +1 -0
- package/stores/container-contents/hydration/backgroundHydration.js +2 -1
- package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
- package/stores/container-contents/hydration/reconnectRefresh.d.ts +10 -0
- package/stores/container-contents/hydration/reconnectRefresh.js +68 -0
- package/stores/container-contents/hydration/reconnectRefresh.js.map +1 -0
- package/stores/container-contents/hydration/reconnectRefreshMachine.js +49 -0
- package/stores/container-contents/hydration/reconnectRefreshMachine.js.map +1 -0
- package/stores/container-contents/hydration/remoteHydrationRefresh.js +4 -1
- package/stores/container-contents/hydration/remoteHydrationRefresh.js.map +1 -1
- package/stores/container-contents/hydration/remoteHydrationRequest.js +79 -10
- package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
- package/stores/container-contents/hydration/startupHydration.js +2 -9
- package/stores/container-contents/hydration/startupHydration.js.map +1 -1
- package/stores/container-contents/hydration/treeResetMachine.js +61 -0
- package/stores/container-contents/hydration/treeResetMachine.js.map +1 -0
- package/stores/container-contents/localRefresh.js +28 -12
- package/stores/container-contents/localRefresh.js.map +1 -1
- package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +4 -1
- package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -1
- package/stores/container-contents/remoteWrites/writeGeneration.js +5 -2
- package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -1
- package/stores/container-contents/state.d.ts +3 -7
- package/stores/container-contents/state.js +27 -16
- package/stores/container-contents/state.js.map +1 -1
- package/stores/container-contents/syncAgent/index.d.ts +7 -2
- package/stores/container-contents/syncAgent/index.js +77 -49
- package/stores/container-contents/syncAgent/index.js.map +1 -1
- package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -2
- package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
- package/stores/container-contents/syncAgent/syncLaneIteration.js +6 -3
- package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
- package/stores/local-projection/localProjectionStore.js +24 -15
- package/stores/local-projection/localProjectionStore.js.map +1 -1
- package/stores/local-projection/registry.js +2 -2
- package/stores/local-projection/registry.js.map +1 -1
- package/workflows/container-contents/container-state/create/createChild.js +3 -15
- package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +4 -8
- package/workflows/container-contents/containerPersistence.js +22 -12
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/localState.js +3 -0
- package/workflows/container-contents/localState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.d.ts +12 -0
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +93 -0
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -0
- package/workflows/container-contents/remoteHydration/index.d.ts +3 -11
- package/workflows/container-contents/remoteHydration/index.js +17 -66
- package/workflows/container-contents/remoteHydration/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
- package/workflows/container-contents/remoteHydration/principalPolicyCache.js +57 -5
- package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +105 -62
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +15 -5
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +13 -0
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/runtime.d.ts +3 -0
- package/workflows/container-contents/runtime.js.map +1 -1
- package/workflows/container-contents/storedContainerState.js +17 -7
- package/workflows/container-contents/storedContainerState.js.map +1 -1
- package/workflows/container-contents/syncLane.d.ts +1 -0
- package/workflows/container-contents/syncLane.js +9 -1
- package/workflows/container-contents/syncLane.js.map +1 -1
- package/workflows/shared/runtimeInput.d.ts +2 -0
- package/workflows/shared/runtimeInput.js.map +1 -1
- package/workflows/container-contents/remoteHydration/completeHydration.js +0 -25
- package/workflows/container-contents/remoteHydration/completeHydration.js.map +0 -1
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { createContainerContentsProjectionUserKeyResolver, didContainerContentsProjectionKeyRuntimeChange, } from "../../workflows/container-contents/projectionKeys.js";
|
|
2
2
|
import { didRegainSyncPrerequisites } from "../../workflows/container-contents/syncLane.js";
|
|
3
3
|
import { ContainerStateMap } from "./containerState/containerStateMap.js";
|
|
4
|
+
import { observeContainerBackgroundHydration } from "./hydration/backgroundHydration.js";
|
|
5
|
+
import { ReconnectRefresh } from "./hydration/reconnectRefresh.js";
|
|
4
6
|
import { didContainerWriteRuntimeChange } from "./remoteWrites/writeGeneration.js";
|
|
5
7
|
import { getSnapshotNodes } from "./utils.js";
|
|
6
8
|
function areSyncStatesEqual(left, right) {
|
|
@@ -44,8 +46,12 @@ function didStructuralRuntimeChange(previousRuntime, nextRuntime) {
|
|
|
44
46
|
previousRuntime.util.isRemoteSyncBlocked !==
|
|
45
47
|
nextRuntime.util.isRemoteSyncBlocked);
|
|
46
48
|
}
|
|
49
|
+
// Request correlation is scoped to the store instance. A reopened tree can
|
|
50
|
+
// issue an identical listing while the retired tree is waiting on the API.
|
|
51
|
+
let storeSequence = 0;
|
|
47
52
|
export function createContainerContentsStoreState(initialRuntime, persistence, logLabel) {
|
|
48
53
|
return {
|
|
54
|
+
parentLaneRequestPrefix: `s${++storeSequence}`,
|
|
49
55
|
containerListingFailures: 0,
|
|
50
56
|
containersById: new ContainerStateMap(),
|
|
51
57
|
containerParentIdsNeedingHydration: new Set(),
|
|
@@ -72,7 +78,7 @@ export function createContainerContentsStoreState(initialRuntime, persistence, l
|
|
|
72
78
|
remoteHydrationStructuralGeneration: null,
|
|
73
79
|
// A store opened after the socket's interest was acknowledged missed that
|
|
74
80
|
// acknowledgement's re-list, which is how hints lost earlier are recovered.
|
|
75
|
-
|
|
81
|
+
reconnectRefresh: new ReconnectRefresh((initialRuntime.state.serverEventsConnectionGeneration ?? 0) > 0),
|
|
76
82
|
resolveProjectionUserKey: createContainerContentsProjectionUserKeyResolver(initialRuntime),
|
|
77
83
|
rootLaneHydrated: false,
|
|
78
84
|
runtime: initialRuntime,
|
|
@@ -150,6 +156,7 @@ export function updateContainerContentsStoreRuntime(state, nextRuntime, syncAgen
|
|
|
150
156
|
const serverEventsConnectionChanged = previousRuntime.state.serverEventsConnectionGeneration !==
|
|
151
157
|
nextRuntime.state.serverEventsConnectionGeneration;
|
|
152
158
|
if (runtimeReplaced) {
|
|
159
|
+
state.reconnectRefresh.reset("runtimeChanged");
|
|
153
160
|
state.structuralGeneration += 1;
|
|
154
161
|
state.localContainersNeedRefresh = true;
|
|
155
162
|
}
|
|
@@ -161,7 +168,7 @@ export function updateContainerContentsStoreRuntime(state, nextRuntime, syncAgen
|
|
|
161
168
|
}
|
|
162
169
|
state.runtime = nextRuntime;
|
|
163
170
|
if (serverEventsConnectionChanged) {
|
|
164
|
-
state.
|
|
171
|
+
state.reconnectRefresh.reset("acknowledged");
|
|
165
172
|
}
|
|
166
173
|
if (nextRuntime.infra.dbStatus !== "ready") {
|
|
167
174
|
if (hasContainerContentsLoadState(state)) {
|
|
@@ -178,12 +185,8 @@ export function updateContainerContentsStoreRuntime(state, nextRuntime, syncAgen
|
|
|
178
185
|
syncAgent.handleRemoteEvents();
|
|
179
186
|
return;
|
|
180
187
|
}
|
|
181
|
-
//
|
|
182
|
-
//
|
|
183
|
-
// tree stays valid. Reconcile it in place instead of resetting — resetting
|
|
184
|
-
// here is what blanked Explorer and forced a re-read on first open after
|
|
185
|
-
// register. Identity/storage changes are handled by scope rotation and the
|
|
186
|
-
// dbStatus-loss branch above.
|
|
188
|
+
// The signing fingerprint owns the locally loaded tree. When this scope
|
|
189
|
+
// gains authentication, keep the tree available while reconciling it.
|
|
187
190
|
if (state.snapshot.ready &&
|
|
188
191
|
(contextChanged || didRegainSyncPrerequisites(previousRuntime, nextRuntime))) {
|
|
189
192
|
state.localContainersNeedRefresh = true;
|
|
@@ -209,21 +212,29 @@ export function updateContainerContentsStoreRuntime(state, nextRuntime, syncAgen
|
|
|
209
212
|
syncAgent.scheduleRemoteHydration();
|
|
210
213
|
}
|
|
211
214
|
}
|
|
215
|
+
export function retireContainerStore(state) {
|
|
216
|
+
state.lifecycleGeneration++;
|
|
217
|
+
state.reconnectRefresh.reset("disposed");
|
|
218
|
+
}
|
|
212
219
|
export function consumePendingContainerContentsReconnectRefresh(state, refresh) {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
state.
|
|
220
|
+
state.reconnectRefresh.runWhenReady(() => state.snapshot.ready &&
|
|
221
|
+
state.initialized &&
|
|
222
|
+
state.runtime.infra.dbStatus === "ready" &&
|
|
223
|
+
state.runtime.auth.isAuthenticated &&
|
|
224
|
+
state.runtime.state.online &&
|
|
225
|
+
(state.runtime.liveHydrationStatus?.() ?? "ready") === "ready" &&
|
|
226
|
+
state.runtime.isAcknowledgementCurrent?.() !== false &&
|
|
227
|
+
!state.syncLane?.isDisposed?.(), (options) => {
|
|
228
|
+
const hydration = refresh(options);
|
|
229
|
+
observeContainerBackgroundHydration(state, hydration);
|
|
230
|
+
return hydration;
|
|
221
231
|
});
|
|
222
232
|
}
|
|
223
233
|
export function updateContainerContentsStorePersistence(state, nextPersistence, syncAgent) {
|
|
224
234
|
if (state.persistence === nextPersistence) {
|
|
225
235
|
return;
|
|
226
236
|
}
|
|
237
|
+
state.reconnectRefresh.reset("runtimeChanged");
|
|
227
238
|
state.persistence = nextPersistence;
|
|
228
239
|
state.structuralGeneration += 1;
|
|
229
240
|
state.writeGeneration += 1;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,6CAA6C,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;AAUhF,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE3C,SAAS,kBAAkB,CACzB,IAAgC,EAChC,KAAiC;IAEjC,OAAO,CACL,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS;QAClC,IAAI,CAAC,sBAAsB,KAAK,KAAK,CAAC,sBAAsB;QAC5D,IAAI,CAAC,sBAAsB,KAAK,KAAK,CAAC,sBAAsB;QAC5D,IAAI,CAAC,kBAAkB,KAAK,KAA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AAC,6BAA6B;QAAE,OAAO;IAC1E,KAAK,CAAC,6BAA6B,GAAG,KAAK,CAAC;IAC5C,KAAK,OAAO,EAAE,CAAC,IAAI,CACjB,CAAC,SAAS,EAAE,EAAE;QACZ,IAAI,CAAC,SAAS;YAAE,KAAK,CAAC,6BAA6B,GAAG,IAAI,CAAC;IAC7D,CAAC,EACD,GAAG,EAAE;QACH,KAAK,CAAC,6BAA6B,GAAG,IAAI,CAAC;IAC7C,CAAC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,uCAAuC,CACrD,KAAkC,EAClC,eAA6C,EAC7C,SAA0C;IAE1C,IAAI,KAAK,CAAC,WAAW,KAAK,eAAe,EAAE,CAAC;QAC1C,OAAO;IACT,CAAC;IACD,KAAK,CAAC,WAAW,GAAG,eAAe,CAAC;IACpC,KAAK,CAAC,oBAAoB,IAAI,CAAC,CAAC;IAChC,KAAK,CAAC,eAAe,IAAI,CAAC,CAAC;IAC3B,2EAA2E;IAC3E,4EAA4E;IAC5E,yEAAyE;IACzE,2BAA2B,CAAC,KAAK,CAAC,CAAC;IACnC,SAAS,CAAC,iBAAiB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import type { ContainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport {\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"../../workflows/container-contents/projectionKeys\";\nimport { didRegainSyncPrerequisites } from \"../../workflows/container-contents/syncLane\";\nimport { ContainerStateMap } from \"./containerState/containerStateMap\";\nimport { didContainerWriteRuntimeChange } from \"./remoteWrites/writeGeneration\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n} from \"./syncAgent/syncAgentTypes\";\nimport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreState,\n ContainerNode,\n} from \"./types\";\nimport { getSnapshotNodes } from \"./utils\";\n\nfunction areSyncStatesEqual(\n left: ContainerNode[\"syncState\"],\n right: ContainerNode[\"syncState\"],\n): boolean {\n return (\n left.lastError === right.lastError &&\n left.pendingAttachmentBytes === right.pendingAttachmentBytes &&\n left.pendingAttachmentCount === right.pendingAttachmentCount &&\n left.pendingUpdateCount === right.pendingUpdateCount &&\n left.status === right.status\n );\n}\n\nfunction areSnapshotNodesEqual(\n left: ReadonlyArray<ContainerNode>,\n right: ReadonlyArray<ContainerNode>,\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n return left.every((leftNode, index) => {\n const rightNode = right[index];\n return (\n rightNode !== undefined &&\n leftNode.createdAt === rightNode.createdAt &&\n leftNode.effectiveAccessLevel === rightNode.effectiveAccessLevel &&\n leftNode.id === rightNode.id &&\n leftNode.icon === rightNode.icon &&\n leftNode.kind === rightNode.kind &&\n leftNode.metadataDocumentId === rightNode.metadataDocumentId &&\n leftNode.metadataReady === rightNode.metadataReady &&\n leftNode.name === rightNode.name &&\n leftNode.organizationId === rightNode.organizationId &&\n leftNode.parentId === rightNode.parentId &&\n leftNode.primaryDocumentId === rightNode.primaryDocumentId &&\n areSyncStatesEqual(leftNode.syncState, rightNode.syncState) &&\n leftNode.systemSlot === rightNode.systemSlot &&\n leftNode.updatedAt === rightNode.updatedAt\n );\n });\n}\n\nfunction didStructuralRuntimeChange(\n previousRuntime: ContainerContentsStoreRuntime,\n nextRuntime: ContainerContentsStoreRuntime,\n): boolean {\n // Structural sync also depends on connectivity and event delivery. Local\n // writes use only the identity and storage checks shared below.\n return (\n didContainerWriteRuntimeChange(previousRuntime, nextRuntime) ||\n previousRuntime.state.online !== nextRuntime.state.online ||\n previousRuntime.state.peerScope !== nextRuntime.state.peerScope ||\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration ||\n previousRuntime.util.isRemoteSyncBlocked !==\n nextRuntime.util.isRemoteSyncBlocked\n );\n}\n\nexport function createContainerContentsStoreState(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence,\n logLabel?: string | undefined,\n): ContainerContentsStoreState {\n return {\n containerListingFailures: 0,\n containersById: new ContainerStateMap(),\n containerParentIdsNeedingHydration: new Set(),\n documentStoresNeedPriming: true,\n initializeGeneration: null,\n initializePromise: null,\n initialized: false,\n localContainerRefreshPromise: null,\n localContainerRefreshGeneration: null,\n localContainerRefreshStructuralGeneration: null,\n localContainersNeedRefresh: false,\n lifecycleGeneration: 0,\n lastEventCount: 0,\n listeners: new Set(),\n locallyAcceptedMetadataUpdateIds: new Set(),\n logLabel,\n metadataDocumentIdsNeedingSync: new Set(),\n metadataSyncSignalSeqById: new Map(),\n owedMetadataReadsRestored: false,\n persistence,\n plannedMetadataDocumentIds: new Set(),\n remoteHydrationPromise: null,\n remoteHydrationGeneration: null,\n remoteHydrationStructuralGeneration: null,\n // A store opened after the socket's interest was acknowledged missed that\n // acknowledgement's re-list, which is how hints lost earlier are recovered.\n remoteReconnectRefreshPending:\n (initialRuntime.state.serverEventsConnectionGeneration ?? 0) > 0,\n resolveProjectionUserKey:\n createContainerContentsProjectionUserKeyResolver(initialRuntime),\n rootLaneHydrated: false,\n runtime: initialRuntime,\n snapshot: {\n nodes: [],\n ready: false,\n },\n syncLane: null,\n structuralGeneration: 0,\n writeGeneration: 0,\n writeChain: Promise.resolve<ContainerNode | null>(null),\n };\n}\n\nfunction emitContainerContentsStore(state: ContainerContentsStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nfunction setContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n next: ContainerContentsSnapshot,\n) {\n if (\n next.ready === state.snapshot.ready &&\n areSnapshotNodesEqual(next.nodes, state.snapshot.nodes)\n ) {\n return;\n }\n\n state.snapshot = next;\n emitContainerContentsStore(state);\n}\n\nexport function updateContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n) {\n setContainerContentsSnapshot(state, {\n nodes: getSnapshotNodes(state.containersById),\n ready: true,\n });\n}\n\nfunction resetContainerContentsStore(state: ContainerContentsStoreState) {\n state.lifecycleGeneration += 1;\n state.containersById = new ContainerStateMap();\n state.containerParentIdsNeedingHydration = new Set();\n state.documentStoresNeedPriming = true;\n state.initialized = false;\n state.localContainersNeedRefresh = false;\n // Runtime events are snapshots, not a destructive queue. A replacement\n // executor or persistence adapter has not observed any of them, even when\n // their effects were already applied to the previous database. Replay the\n // snapshot after replacement initialization rebuilds metadata identities.\n state.lastEventCount = 0;\n // Accepted-echo suppression state must not survive a reset: after a\n // database loss the tree rehydrates from remote, and a retained id would\n // suppress the next matching remote update signal. Mirrors\n // clearDocumentStoreState in the document store lane.\n state.locallyAcceptedMetadataUpdateIds = new Set();\n state.metadataDocumentIdsNeedingSync = new Set();\n state.metadataSyncSignalSeqById = new Map();\n state.owedMetadataReadsRestored = false;\n state.plannedMetadataDocumentIds = new Set();\n state.rootLaneHydrated = false;\n state.writeChain = Promise.resolve<ContainerNode | null>(null);\n setContainerContentsSnapshot(state, {\n nodes: [],\n ready: false,\n });\n}\n\nexport function subscribeToContainerContentsStore(\n state: ContainerContentsStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n\nfunction hasContainerContentsLoadState(\n state: ContainerContentsStoreState,\n): boolean {\n return Boolean(\n state.snapshot.ready || state.initialized || state.initializePromise,\n );\n}\n\nexport function updateContainerContentsStoreRuntime(\n state: ContainerContentsStoreState,\n nextRuntime: ContainerContentsStoreRuntime,\n syncAgent: ContainerContentsStoreSyncAgent,\n) {\n const previousRuntime = state.runtime;\n const runtimeReplaced = didStructuralRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (didContainerWriteRuntimeChange(previousRuntime, nextRuntime)) {\n state.writeGeneration += 1;\n }\n const executorReplaced =\n previousRuntime.infra.execSql !== nextRuntime.infra.execSql;\n const serverEventsConnectionChanged =\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration;\n if (runtimeReplaced) {\n state.structuralGeneration += 1;\n state.localContainersNeedRefresh = true;\n }\n const contextChanged =\n previousRuntime.auth.organizationId !== nextRuntime.auth.organizationId ||\n previousRuntime.state.containerId !== nextRuntime.state.containerId;\n if (\n didContainerContentsProjectionKeyRuntimeChange(previousRuntime, nextRuntime)\n ) {\n state.resolveProjectionUserKey =\n createContainerContentsProjectionUserKeyResolver(nextRuntime);\n }\n state.runtime = nextRuntime;\n if (serverEventsConnectionChanged) {\n state.remoteReconnectRefreshPending = true;\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (hasContainerContentsLoadState(state)) {\n resetContainerContentsStore(state);\n }\n return;\n }\n\n if (executorReplaced) {\n // The in-memory tree and lane markers belong to the previous executor.\n // Rebuild them from the replacement database before any remote sync can\n // observe or persist the old database's state.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n syncAgent.handleRemoteEvents();\n return;\n }\n\n // Gaining authentication within a domain scope does not change identity\n // (the scope is keyed on the signing fingerprint), so the locally-loaded\n // tree stays valid. Reconcile it in place instead of resetting — resetting\n // here is what blanked Explorer and forced a re-read on first open after\n // register. Identity/storage changes are handled by scope rotation and the\n // dbStatus-loss branch above.\n if (\n state.snapshot.ready &&\n (contextChanged || didRegainSyncPrerequisites(previousRuntime, nextRuntime))\n ) {\n state.localContainersNeedRefresh = true;\n state.documentStoresNeedPriming = true;\n void syncAgent.refreshLocalContainers();\n // The refresh alone does not run the sync lane; schedule it so newly\n // eligible documents (e.g. this organization's orphans) prime now.\n syncAgent.scheduleSync();\n }\n\n syncAgent.ensureInitialized();\n\n syncAgent.handleRemoteEvents();\n\n if (runtimeReplaced) {\n void syncAgent.refreshLocalContainers();\n syncAgent.scheduleSync();\n }\n\n consumePendingContainerContentsReconnectRefresh(state, syncAgent.refresh);\n\n if (\n state.snapshot.ready &&\n didRegainSyncPrerequisites(previousRuntime, nextRuntime)\n ) {\n // A pass blocked by missing prerequisites consumes its lane request before\n // returning early. Re-arm it directly when they return even if hydration\n // finds no remote delta; this also primes unopened document stores.\n syncAgent.scheduleSync();\n syncAgent.scheduleRemoteHydration();\n }\n}\n\nexport function consumePendingContainerContentsReconnectRefresh(\n state: {\n remoteReconnectRefreshPending: boolean;\n snapshot: { ready: boolean };\n },\n refresh: () => Promise<boolean>,\n): void {\n if (!state.snapshot.ready || !state.remoteReconnectRefreshPending) return;\n state.remoteReconnectRefreshPending = false;\n void refresh().then(\n (refreshed) => {\n if (!refreshed) state.remoteReconnectRefreshPending = true;\n },\n () => {\n state.remoteReconnectRefreshPending = true;\n },\n );\n}\n\nexport function updateContainerContentsStorePersistence(\n state: ContainerContentsStoreState,\n nextPersistence: ContainerContentsPersistence,\n syncAgent: ContainerContentsStoreSyncAgent,\n): void {\n if (state.persistence === nextPersistence) {\n return;\n }\n state.persistence = nextPersistence;\n state.structuralGeneration += 1;\n state.writeGeneration += 1;\n // Persistence replacement changes the authoritative local data source even\n // when the SQLite executor itself is stable. Clear storage-backed state and\n // let initialization load the replacement before scheduling remote work.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,6CAA6C,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;AAWhF,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE3C,SAAS,kBAAkB,CACzB,IAAgC,EAChC,KAAiC;IAEjC,OAAO,CACL,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS;QAClC,IAAI,CAAC,sBAAsB,KAAK,KAAK,CAAC,sBAAsB;QAC5D,IAAI,CAAC,sBAA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eAAe,CAAC;IACpC,KAAK,CAAC,oBAAoB,IAAI,CAAC,CAAC;IAChC,KAAK,CAAC,eAAe,IAAI,CAAC,CAAC;IAC3B,2EAA2E;IAC3E,4EAA4E;IAC5E,yEAAyE;IACzE,2BAA2B,CAAC,KAAK,CAAC,CAAC;IACnC,SAAS,CAAC,iBAAiB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import type { ContainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport {\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"../../workflows/container-contents/projectionKeys\";\nimport { didRegainSyncPrerequisites } from \"../../workflows/container-contents/syncLane\";\nimport { ContainerStateMap } from \"./containerState/containerStateMap\";\nimport { observeContainerBackgroundHydration } from \"./hydration/backgroundHydration\";\nimport { ReconnectRefresh } from \"./hydration/reconnectRefresh\";\nimport { didContainerWriteRuntimeChange } from \"./remoteWrites/writeGeneration\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n} from \"./syncAgent/syncAgentTypes\";\nimport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreState,\n ContainerNode,\n} from \"./types\";\nimport { getSnapshotNodes } from \"./utils\";\n\nfunction areSyncStatesEqual(\n left: ContainerNode[\"syncState\"],\n right: ContainerNode[\"syncState\"],\n): boolean {\n return (\n left.lastError === right.lastError &&\n left.pendingAttachmentBytes === right.pendingAttachmentBytes &&\n left.pendingAttachmentCount === right.pendingAttachmentCount &&\n left.pendingUpdateCount === right.pendingUpdateCount &&\n left.status === right.status\n );\n}\n\nfunction areSnapshotNodesEqual(\n left: ReadonlyArray<ContainerNode>,\n right: ReadonlyArray<ContainerNode>,\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n return left.every((leftNode, index) => {\n const rightNode = right[index];\n return (\n rightNode !== undefined &&\n leftNode.createdAt === rightNode.createdAt &&\n leftNode.effectiveAccessLevel === rightNode.effectiveAccessLevel &&\n leftNode.id === rightNode.id &&\n leftNode.icon === rightNode.icon &&\n leftNode.kind === rightNode.kind &&\n leftNode.metadataDocumentId === rightNode.metadataDocumentId &&\n leftNode.metadataReady === rightNode.metadataReady &&\n leftNode.name === rightNode.name &&\n leftNode.organizationId === rightNode.organizationId &&\n leftNode.parentId === rightNode.parentId &&\n leftNode.primaryDocumentId === rightNode.primaryDocumentId &&\n areSyncStatesEqual(leftNode.syncState, rightNode.syncState) &&\n leftNode.systemSlot === rightNode.systemSlot &&\n leftNode.updatedAt === rightNode.updatedAt\n );\n });\n}\n\nfunction didStructuralRuntimeChange(\n previousRuntime: ContainerContentsStoreRuntime,\n nextRuntime: ContainerContentsStoreRuntime,\n): boolean {\n // Structural sync also depends on connectivity and event delivery. Local\n // writes use only the identity and storage checks shared below.\n return (\n didContainerWriteRuntimeChange(previousRuntime, nextRuntime) ||\n previousRuntime.state.online !== nextRuntime.state.online ||\n previousRuntime.state.peerScope !== nextRuntime.state.peerScope ||\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration ||\n previousRuntime.util.isRemoteSyncBlocked !==\n nextRuntime.util.isRemoteSyncBlocked\n );\n}\n\n// Request correlation is scoped to the store instance. A reopened tree can\n// issue an identical listing while the retired tree is waiting on the API.\nlet storeSequence = 0;\n\nexport function createContainerContentsStoreState(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence,\n logLabel?: string | undefined,\n): ContainerContentsStoreState {\n return {\n parentLaneRequestPrefix: `s${++storeSequence}`,\n containerListingFailures: 0,\n containersById: new ContainerStateMap(),\n containerParentIdsNeedingHydration: new Set(),\n documentStoresNeedPriming: true,\n initializeGeneration: null,\n initializePromise: null,\n initialized: false,\n localContainerRefreshPromise: null,\n localContainerRefreshGeneration: null,\n localContainerRefreshStructuralGeneration: null,\n localContainersNeedRefresh: false,\n lifecycleGeneration: 0,\n lastEventCount: 0,\n listeners: new Set(),\n locallyAcceptedMetadataUpdateIds: new Set(),\n logLabel,\n metadataDocumentIdsNeedingSync: new Set(),\n metadataSyncSignalSeqById: new Map(),\n owedMetadataReadsRestored: false,\n persistence,\n plannedMetadataDocumentIds: new Set(),\n remoteHydrationPromise: null,\n remoteHydrationGeneration: null,\n remoteHydrationStructuralGeneration: null,\n // A store opened after the socket's interest was acknowledged missed that\n // acknowledgement's re-list, which is how hints lost earlier are recovered.\n reconnectRefresh: new ReconnectRefresh(\n (initialRuntime.state.serverEventsConnectionGeneration ?? 0) > 0,\n ),\n resolveProjectionUserKey:\n createContainerContentsProjectionUserKeyResolver(initialRuntime),\n rootLaneHydrated: false,\n runtime: initialRuntime,\n snapshot: {\n nodes: [],\n ready: false,\n },\n syncLane: null,\n structuralGeneration: 0,\n writeGeneration: 0,\n writeChain: Promise.resolve<ContainerNode | null>(null),\n };\n}\n\nfunction emitContainerContentsStore(state: ContainerContentsStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nfunction setContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n next: ContainerContentsSnapshot,\n) {\n if (\n next.ready === state.snapshot.ready &&\n areSnapshotNodesEqual(next.nodes, state.snapshot.nodes)\n ) {\n return;\n }\n\n state.snapshot = next;\n emitContainerContentsStore(state);\n}\n\nexport function updateContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n) {\n setContainerContentsSnapshot(state, {\n nodes: getSnapshotNodes(state.containersById),\n ready: true,\n });\n}\n\nfunction resetContainerContentsStore(state: ContainerContentsStoreState) {\n state.lifecycleGeneration += 1;\n state.containersById = new ContainerStateMap();\n state.containerParentIdsNeedingHydration = new Set();\n state.documentStoresNeedPriming = true;\n state.initialized = false;\n state.localContainersNeedRefresh = false;\n // Runtime events are snapshots, not a destructive queue. A replacement\n // executor or persistence adapter has not observed any of them, even when\n // their effects were already applied to the previous database. Replay the\n // snapshot after replacement initialization rebuilds metadata identities.\n state.lastEventCount = 0;\n // Accepted-echo suppression state must not survive a reset: after a\n // database loss the tree rehydrates from remote, and a retained id would\n // suppress the next matching remote update signal. Mirrors\n // clearDocumentStoreState in the document store lane.\n state.locallyAcceptedMetadataUpdateIds = new Set();\n state.metadataDocumentIdsNeedingSync = new Set();\n state.metadataSyncSignalSeqById = new Map();\n state.owedMetadataReadsRestored = false;\n state.plannedMetadataDocumentIds = new Set();\n state.rootLaneHydrated = false;\n state.writeChain = Promise.resolve<ContainerNode | null>(null);\n setContainerContentsSnapshot(state, {\n nodes: [],\n ready: false,\n });\n}\n\nexport function subscribeToContainerContentsStore(\n state: ContainerContentsStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n\nfunction hasContainerContentsLoadState(\n state: ContainerContentsStoreState,\n): boolean {\n return Boolean(\n state.snapshot.ready || state.initialized || state.initializePromise,\n );\n}\n\nexport function updateContainerContentsStoreRuntime(\n state: ContainerContentsStoreState,\n nextRuntime: ContainerContentsStoreRuntime,\n syncAgent: ContainerContentsStoreSyncAgent,\n) {\n const previousRuntime = state.runtime;\n const runtimeReplaced = didStructuralRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (didContainerWriteRuntimeChange(previousRuntime, nextRuntime)) {\n state.writeGeneration += 1;\n }\n const executorReplaced =\n previousRuntime.infra.execSql !== nextRuntime.infra.execSql;\n const serverEventsConnectionChanged =\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration;\n if (runtimeReplaced) {\n state.reconnectRefresh.reset(\"runtimeChanged\");\n state.structuralGeneration += 1;\n state.localContainersNeedRefresh = true;\n }\n const contextChanged =\n previousRuntime.auth.organizationId !== nextRuntime.auth.organizationId ||\n previousRuntime.state.containerId !== nextRuntime.state.containerId;\n if (\n didContainerContentsProjectionKeyRuntimeChange(previousRuntime, nextRuntime)\n ) {\n state.resolveProjectionUserKey =\n createContainerContentsProjectionUserKeyResolver(nextRuntime);\n }\n state.runtime = nextRuntime;\n if (serverEventsConnectionChanged) {\n state.reconnectRefresh.reset(\"acknowledged\");\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (hasContainerContentsLoadState(state)) {\n resetContainerContentsStore(state);\n }\n return;\n }\n\n if (executorReplaced) {\n // The in-memory tree and lane markers belong to the previous executor.\n // Rebuild them from the replacement database before any remote sync can\n // observe or persist the old database's state.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n syncAgent.handleRemoteEvents();\n return;\n }\n\n // The signing fingerprint owns the locally loaded tree. When this scope\n // gains authentication, keep the tree available while reconciling it.\n if (\n state.snapshot.ready &&\n (contextChanged || didRegainSyncPrerequisites(previousRuntime, nextRuntime))\n ) {\n state.localContainersNeedRefresh = true;\n state.documentStoresNeedPriming = true;\n void syncAgent.refreshLocalContainers();\n // The refresh alone does not run the sync lane; schedule it so newly\n // eligible documents (e.g. this organization's orphans) prime now.\n syncAgent.scheduleSync();\n }\n\n syncAgent.ensureInitialized();\n\n syncAgent.handleRemoteEvents();\n\n if (runtimeReplaced) {\n void syncAgent.refreshLocalContainers();\n syncAgent.scheduleSync();\n }\n\n consumePendingContainerContentsReconnectRefresh(state, syncAgent.refresh);\n\n if (\n state.snapshot.ready &&\n didRegainSyncPrerequisites(previousRuntime, nextRuntime)\n ) {\n // A pass blocked by missing prerequisites consumes its lane request before\n // returning early. Re-arm it directly when they return even if hydration\n // finds no remote delta; this also primes unopened document stores.\n syncAgent.scheduleSync();\n syncAgent.scheduleRemoteHydration();\n }\n}\n\nexport function retireContainerStore(\n state: ContainerContentsStoreSyncState,\n): void {\n state.lifecycleGeneration++;\n state.reconnectRefresh.reset(\"disposed\");\n}\n\nexport function consumePendingContainerContentsReconnectRefresh(\n state: ContainerContentsStoreSyncState,\n refresh: ContainerContentsStoreSyncAgent[\"refresh\"],\n): void {\n state.reconnectRefresh.runWhenReady(\n () =>\n state.snapshot.ready &&\n state.initialized &&\n state.runtime.infra.dbStatus === \"ready\" &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.state.online &&\n (state.runtime.liveHydrationStatus?.() ?? \"ready\") === \"ready\" &&\n state.runtime.isAcknowledgementCurrent?.() !== false &&\n !state.syncLane?.isDisposed?.(),\n (options) => {\n const hydration = refresh(options);\n observeContainerBackgroundHydration(state, hydration);\n return hydration;\n },\n );\n}\n\nexport function updateContainerContentsStorePersistence(\n state: ContainerContentsStoreState,\n nextPersistence: ContainerContentsPersistence,\n syncAgent: ContainerContentsStoreSyncAgent,\n): void {\n if (state.persistence === nextPersistence) {\n return;\n }\n state.reconnectRefresh.reset(\"runtimeChanged\");\n state.persistence = nextPersistence;\n state.structuralGeneration += 1;\n state.writeGeneration += 1;\n // Persistence replacement changes the authoritative local data source even\n // when the SQLite executor itself is stable. Clear storage-backed state and\n // let initialization load the replacement before scheduling remote work.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n}\n"]}
|
|
@@ -2,7 +2,12 @@ import type { RemoteContainerHydrationHost } from "../../../workflows/container-
|
|
|
2
2
|
import type { ContainerContentsStoreSyncAgent, ContainerContentsStoreSyncState } from "./syncAgentTypes.js";
|
|
3
3
|
export type { ContainerState } from "../../../workflows/container-contents/remoteHydration/index.js";
|
|
4
4
|
export type { ContainerContentsStoreRuntime, ContainerContentsStoreSyncAgent, ContainerContentsStoreSyncState, RefreshRootLaneOptions, } from "./syncAgentTypes.js";
|
|
5
|
-
|
|
5
|
+
interface AgentInput {
|
|
6
6
|
host: RemoteContainerHydrationHost;
|
|
7
7
|
state: ContainerContentsStoreSyncState;
|
|
8
|
-
}
|
|
8
|
+
}
|
|
9
|
+
export declare function prepareContainerContentsStoreSyncAgent(input: AgentInput): {
|
|
10
|
+
agent: ContainerContentsStoreSyncAgent;
|
|
11
|
+
registerLane: () => void;
|
|
12
|
+
};
|
|
13
|
+
export declare function createContainerContentsStoreSyncAgent(input: AgentInput): ContainerContentsStoreSyncAgent;
|
|
@@ -2,20 +2,32 @@ import { loadLocalContainerStates } from "../../../workflows/container-contents/
|
|
|
2
2
|
import { isDatabaseUnavailableError, registerContainerContentsSyncLane, } from "../../../workflows/container-contents/syncLane.js";
|
|
3
3
|
import { loadOrganizationSyncPausesBeforeSync } from "../../../workflows/sync/coordination.js";
|
|
4
4
|
import { createRestoredAccessReconciler } from "../accessRestorationSweep.js";
|
|
5
|
+
import { ownsContainerStore } from "../containerState/storeScope.js";
|
|
5
6
|
import { primeStoreDocumentSubtree } from "../documentWork/documentRecovery.js";
|
|
6
7
|
import { observeContainerBackgroundHydration } from "../hydration/backgroundHydration.js";
|
|
7
8
|
import { refreshAllRemoteHydration, refreshRootRemoteHydration, } from "../hydration/remoteHydrationRefresh.js";
|
|
8
9
|
import { requestContainerContentsRemoteHydration } from "../hydration/remoteHydrationRequest.js";
|
|
9
|
-
import { hasStartupContainerSyncWork,
|
|
10
|
+
import { hasStartupContainerSyncWork, inspectStartupHydration, } from "../hydration/startupHydration.js";
|
|
10
11
|
import { refreshLocalContainerStates } from "../localRefresh.js";
|
|
11
12
|
import { getContainerContentsStoreLogLabel } from "../logLabel.js";
|
|
12
13
|
import { createRemoteContainerIngestionController } from "../remoteEvents/remoteContainerIngestion.js";
|
|
13
14
|
import { handleContainerContentsRemoteEvents } from "../remoteEvents/remoteEventSync.js";
|
|
14
|
-
import { consumePendingContainerContentsReconnectRefresh } from "../state.js";
|
|
15
|
+
import { consumePendingContainerContentsReconnectRefresh, retireContainerStore, } from "../state.js";
|
|
15
16
|
import { runContainerContentsStoreSyncIteration } from "./syncLaneIteration.js";
|
|
16
17
|
function requestContainerContentsStoreSync(state) {
|
|
17
18
|
state.syncLane?.requestSync();
|
|
18
19
|
}
|
|
20
|
+
function publishInitialContainers(state, startup) {
|
|
21
|
+
for (const [id, row] of startup.containersById) {
|
|
22
|
+
state.containersById.set(id, row);
|
|
23
|
+
}
|
|
24
|
+
state.initialized = true;
|
|
25
|
+
state.rootLaneHydrated = startup.rootLaneHydrated;
|
|
26
|
+
for (const id of startup.containerParentIdsNeedingHydration) {
|
|
27
|
+
state.containerParentIdsNeedingHydration.add(id);
|
|
28
|
+
}
|
|
29
|
+
return startup.containerParentIdsNeedingHydration.size > 0;
|
|
30
|
+
}
|
|
19
31
|
async function initializeContainerContentsStore(input) {
|
|
20
32
|
const { handleRemoteEvents, host, isCurrent, resumeRecoveryWork, scheduleSync, state, } = input;
|
|
21
33
|
const persistence = state.persistence;
|
|
@@ -29,35 +41,41 @@ async function initializeContainerContentsStore(input) {
|
|
|
29
41
|
log: loadRuntime.util.log,
|
|
30
42
|
});
|
|
31
43
|
const localContainerStates = await loadLocalContainerStates({
|
|
44
|
+
isCurrent,
|
|
32
45
|
persistence,
|
|
33
46
|
runtime: loadRuntime,
|
|
34
47
|
});
|
|
35
48
|
if (!isCurrent()) {
|
|
36
49
|
return;
|
|
37
50
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
51
|
+
// Keep the local tree and marker reads private until this initialization
|
|
52
|
+
// can publish them together. Another organization can take over between reads.
|
|
53
|
+
const startup = {
|
|
54
|
+
runtime: state.runtime,
|
|
55
|
+
containersById: new Map(localContainerStates.map((row) => [row.container.id, row])),
|
|
56
|
+
containerParentIdsNeedingHydration: new Set(),
|
|
57
|
+
rootLaneHydrated: state.rootLaneHydrated,
|
|
58
|
+
};
|
|
59
|
+
const shouldScheduleStaleRootRecovery = await inspectStartupHydration({
|
|
43
60
|
isCurrent,
|
|
44
|
-
|
|
45
|
-
host,
|
|
46
|
-
resumeRecoveryWork,
|
|
47
|
-
scheduleSync,
|
|
48
|
-
state,
|
|
49
|
-
}),
|
|
50
|
-
state,
|
|
61
|
+
state: startup,
|
|
51
62
|
});
|
|
52
|
-
if (!isCurrent())
|
|
63
|
+
if (!isCurrent())
|
|
53
64
|
return;
|
|
54
|
-
}
|
|
55
65
|
const runtime = state.runtime;
|
|
56
66
|
const hasPendingRestorationSweep = typeof runtime.auth.userId === "string" &&
|
|
57
67
|
(await persistence.listDormantMetadataSweepRequests(loadRuntime.infra.execSql, runtime.auth.userId)).length > 0;
|
|
58
68
|
if (!isCurrent()) {
|
|
59
69
|
return;
|
|
60
70
|
}
|
|
71
|
+
if (publishInitialContainers(state, startup)) {
|
|
72
|
+
observeContainerBackgroundHydration(state, requestContainerContentsRemoteHydration({
|
|
73
|
+
host,
|
|
74
|
+
resumeRecoveryWork,
|
|
75
|
+
scheduleSync,
|
|
76
|
+
state,
|
|
77
|
+
}));
|
|
78
|
+
}
|
|
61
79
|
host.updateSnapshot();
|
|
62
80
|
handleRemoteEvents();
|
|
63
81
|
runtime.util.log(`${getContainerContentsStoreLogLabel(state)}: loaded ${state.containersById.size} container(s)`);
|
|
@@ -105,16 +123,24 @@ function ensureContainerContentsStoreInitialized(input) {
|
|
|
105
123
|
if (state.initialized || state.runtime.infra.dbStatus !== "ready") {
|
|
106
124
|
return;
|
|
107
125
|
}
|
|
108
|
-
if (state.initializePromise) {
|
|
126
|
+
if (!ownsContainerStore(state) || state.initializePromise) {
|
|
109
127
|
return;
|
|
110
128
|
}
|
|
111
129
|
if (waitForStaleLocalRefreshBeforeInitialization(input)) {
|
|
112
130
|
return;
|
|
113
131
|
}
|
|
114
132
|
const lifecycleGeneration = state.lifecycleGeneration;
|
|
133
|
+
// A first login adopts device-local rows on this executor. A later owner must reload them.
|
|
134
|
+
const startedAnonymous = !state.runtime.auth.isAuthenticated;
|
|
135
|
+
const writeGeneration = state.writeGeneration;
|
|
115
136
|
const persistence = state.persistence;
|
|
116
137
|
const execSql = state.runtime.infra.execSql;
|
|
117
|
-
const isCurrent = () => state
|
|
138
|
+
const isCurrent = () => ownsContainerStore(state) &&
|
|
139
|
+
(state.writeGeneration === writeGeneration ||
|
|
140
|
+
(startedAnonymous &&
|
|
141
|
+
state.runtime.auth.isAuthenticated &&
|
|
142
|
+
state.writeGeneration === writeGeneration + 1)) &&
|
|
143
|
+
state.lifecycleGeneration === lifecycleGeneration &&
|
|
118
144
|
state.persistence === persistence &&
|
|
119
145
|
state.runtime.infra.execSql === execSql;
|
|
120
146
|
state.initializeGeneration = lifecycleGeneration;
|
|
@@ -142,6 +168,8 @@ function ensureContainerContentsStoreInitialized(input) {
|
|
|
142
168
|
consumePendingContainerContentsReconnectRefresh(state, input.refreshAfterReconnect);
|
|
143
169
|
}
|
|
144
170
|
else if (state.runtime.infra.dbStatus === "ready") {
|
|
171
|
+
if (!state.snapshot.ready)
|
|
172
|
+
state.initialized = false;
|
|
145
173
|
ensureContainerContentsStoreInitialized(input);
|
|
146
174
|
}
|
|
147
175
|
});
|
|
@@ -163,7 +191,7 @@ function createHydrationRequester(input) {
|
|
|
163
191
|
resetAllLaneWatermarks: options.resetAllLaneWatermarks,
|
|
164
192
|
});
|
|
165
193
|
}
|
|
166
|
-
export function
|
|
194
|
+
export function prepareContainerContentsStoreSyncAgent(input) {
|
|
167
195
|
const { host, state } = input;
|
|
168
196
|
const scheduleSync = () => requestContainerContentsStoreSync(state);
|
|
169
197
|
const remoteContainerIngestion = createRemoteContainerIngestionController({
|
|
@@ -172,23 +200,14 @@ export function createContainerContentsStoreSyncAgent(input) {
|
|
|
172
200
|
state,
|
|
173
201
|
});
|
|
174
202
|
const resumeRecoveryWork = remoteContainerIngestion.resumeInterruptedWork;
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
scheduleSync,
|
|
179
|
-
state,
|
|
180
|
-
});
|
|
181
|
-
const requestRefreshHydration = (options) => requestContainerContentsRemoteHydration({
|
|
182
|
-
...options,
|
|
183
|
-
host,
|
|
184
|
-
resumeRecoveryWork,
|
|
185
|
-
scheduleSync,
|
|
186
|
-
state,
|
|
187
|
-
});
|
|
203
|
+
const hydrationInput = { host, resumeRecoveryWork, scheduleSync, state };
|
|
204
|
+
const requestHydration = createHydrationRequester(hydrationInput);
|
|
205
|
+
const requestRefreshHydration = (options) => requestContainerContentsRemoteHydration({ ...hydrationInput, ...options });
|
|
188
206
|
const scheduleHydration = (options) => observeContainerBackgroundHydration(state, requestHydration(options));
|
|
189
207
|
const refresh = (options) => refreshAllRemoteHydration({
|
|
190
208
|
// Explicit user refresh must rediscover children hidden by unsigned hints.
|
|
191
209
|
resetAllLaneWatermarks: options?.resetAllLaneWatermarks,
|
|
210
|
+
reconnect: options?.reconnect,
|
|
192
211
|
requestHydration: requestRefreshHydration,
|
|
193
212
|
state,
|
|
194
213
|
});
|
|
@@ -201,23 +220,26 @@ export function createContainerContentsStoreSyncAgent(input) {
|
|
|
201
220
|
requestHydration: requestRefreshHydration,
|
|
202
221
|
state,
|
|
203
222
|
});
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
policyOperation
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
223
|
+
const registerLane = () => {
|
|
224
|
+
state.syncLane = registerContainerContentsSyncLane({
|
|
225
|
+
onDispose: () => retireContainerStore(state),
|
|
226
|
+
domainScope: state.runtime.state.domainScope,
|
|
227
|
+
logError: (message, error) => logSyncLaneFailure(state, message, error),
|
|
228
|
+
run: (policyOperation) => runContainerContentsStoreSyncIteration({
|
|
229
|
+
host,
|
|
230
|
+
policyOperation,
|
|
231
|
+
reconcileRestoredAccess,
|
|
232
|
+
requestRemoteReconciliation: (parentContainerId) => {
|
|
233
|
+
scheduleHydration({
|
|
234
|
+
followDiscoveredParentLanes: false,
|
|
235
|
+
parentIds: [parentContainerId],
|
|
236
|
+
});
|
|
237
|
+
},
|
|
238
|
+
state,
|
|
239
|
+
}),
|
|
240
|
+
});
|
|
241
|
+
};
|
|
242
|
+
const agent = {
|
|
221
243
|
ensureInitialized: () => {
|
|
222
244
|
ensureContainerContentsStoreInitialized({
|
|
223
245
|
handleRemoteEvents,
|
|
@@ -244,5 +266,11 @@ export function createContainerContentsStoreSyncAgent(input) {
|
|
|
244
266
|
scheduleRemoteHydration: scheduleHydration,
|
|
245
267
|
scheduleSync,
|
|
246
268
|
};
|
|
269
|
+
return { agent, registerLane };
|
|
270
|
+
}
|
|
271
|
+
export function createContainerContentsStoreSyncAgent(input) {
|
|
272
|
+
const prepared = prepareContainerContentsStoreSyncAgent(input);
|
|
273
|
+
prepared.registerLane();
|
|
274
|
+
return prepared.agent;
|
|
247
275
|
}
|
|
248
276
|
//# sourceMappingURL=index.js.map
|
|
@@ -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,C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AAE,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;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,i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D,KAAK;aACN,CAAC;SACL,CAAC,CAAC;IACL,CAAC,CAAC;IAEF,MAAM,KAAK,GAAoC;QAC7C,iBAAiB,EAAE,GAAG,EAAE;YACtB,uCAAuC,CAAC;gBACtC,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
|
-
|
|
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
|
|
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"]}
|