Open History to see the last commit
1import {
2 CollectionInErrorStateError,
3 CollectionStateError,
4 InvalidCollectionStatusTransitionError,
5} from '../errors'
6import {
7 safeCancelIdleCallback,
8 safeRequestIdleCallback,
9} from '../utils/browser-polyfills'
10import { runAllCallbacks } from '../utils/callbacks'
11import { createDeferred } from '../deferred'
12import { CleanupQueue } from './cleanup-queue'
13import type { IdleCallbackDeadline } from '../utils/browser-polyfills'
14import type { StandardSchemaV1 } from '@standard-schema/spec'
15import type { CollectionConfig, CollectionStatus } from '../types'
16import type { CollectionEventsManager } from './events'
17import type { CollectionIndexesManager } from './indexes'
18import type { CollectionChangesManager } from './changes'
19import type { CollectionSyncManager } from './sync'
20import type { CollectionStateManager } from './state'
21
22/**
23 * Floor applied to the GC delay of a collection that started syncing before
24 * anything subscribed. Adapters build their live query while rendering and
25 * subscribe when that render commits. This grace period reduces cleanup
26 * during that gap; a later subscriber can still restart sync. Adapters pass
27 * a near-zero `gcTime` to make teardown on unmount immediate. Does not apply
28 * to the timer armed when the last subscriber leaves, which still honours
29 * `gcTime` exactly.
30 */
31const UNSUBSCRIBED_GC_FLOOR_MS = 50
32
33export class CollectionLifecycleManager<
34 TOutput extends object = Record<string, unknown>,
35 TKey extends string | number = string | number,
36 TSchema extends StandardSchemaV1 = StandardSchemaV1,
37 TInput extends object = TOutput,
38> {
39 private config: CollectionConfig<TOutput, TKey, TSchema, any>
40 private id: string
41 private indexes!: CollectionIndexesManager<TOutput, TKey, TSchema, TInput>
42 private events!: CollectionEventsManager
43 private changes!: CollectionChangesManager<TOutput, TKey, TSchema, TInput>
44 private sync!: CollectionSyncManager<TOutput, TKey, TSchema, TInput>
45 private state!: CollectionStateManager<TOutput, TKey, TSchema, TInput>
46
47 public status: CollectionStatus = `idle`
48 public hasBeenReady = false
49 public hasReceivedFirstCommit = false
50 public onFirstReadyCallbacks: Array<() => void> = []
51 private idleCallbackId: number | null = null
52 private syncError: unknown
53 private cleanupConfig: () => void
54 private statusRevision = 0
55 private cleaningUp = false
56 private cleanupPromise: Promise<void> | null = null
57
58 /**
59 * Creates a new CollectionLifecycleManager instance
60 */
61 constructor(
62 config: CollectionConfig<TOutput, TKey, TSchema, any>,
63 id: string,
64 cleanupConfig: () => void = () => {},
65 ) {
66 this.config = config
67 this.id = id
68 this.cleanupConfig = cleanupConfig
69 }
70
71 setDeps(deps: {
72 indexes: CollectionIndexesManager<TOutput, TKey, TSchema, TInput>
73 events: CollectionEventsManager
74 changes: CollectionChangesManager<TOutput, TKey, TSchema, TInput>
75 sync: CollectionSyncManager<TOutput, TKey, TSchema, TInput>
76 state: CollectionStateManager<TOutput, TKey, TSchema, TInput>
77 }) {
78 this.indexes = deps.indexes
79 this.events = deps.events
80 this.changes = deps.changes
81 this.sync = deps.sync
82 this.state = deps.state
83 }
84
85 /**
86 * Validates state transitions to prevent invalid status changes
87 */
88 public validateStatusTransition(
89 from: CollectionStatus,
90 to: CollectionStatus,
91 ): void {
92 if (from === to) {
93 // Allow same state transitions
94 return
95 }
96 const validTransitions: Record<
97 CollectionStatus,
98 Array<CollectionStatus>
99 > = {
100 idle: [`loading`, `error`, `cleaned-up`],
101 loading: [`ready`, `error`, `cleaned-up`],
102 ready: [`cleaned-up`, `error`],
103 error: [`ready`, `cleaned-up`, `idle`],
104 'cleaned-up': [`loading`, `error`],
105 }
106
107 if (!validTransitions[from].includes(to)) {
108 throw new InvalidCollectionStatusTransitionError(from, to, this.id)
109 }
110 }
111
112 /**
113 * Safely update the collection status with validation
114 * @private
115 */
116 public setStatus(
117 newStatus: CollectionStatus,
118 allowReady: boolean = false,
119 ): void {
120 if (newStatus === `ready` && !allowReady) {
121 // setStatus('ready') is an internal method that should not be called directly
122 // Instead, use markReady to transition to ready triggering the necessary events
123 // and side effects.
124 throw new CollectionStateError(
125 `You can't directly call "setStatus('ready'). You must use markReady instead.`,
126 )
127 }
128 this.validateStatusTransition(this.status, newStatus)
129 const revision = ++this.statusRevision
130 const previousStatus = this.status
131 this.status = newStatus
132
133 // Emit event
134 this.events.emitStatusChange(
135 newStatus,
136 previousStatus,
137 () => this.statusRevision === revision,
138 )
139 }
140
141 /**
142 * Validates that the collection is in a usable state for data operations
143 * @private
144 */
145 public validateCollectionUsable(operation: string): void {
146 switch (this.status) {
147 case `error`:
148 throw new CollectionInErrorStateError(operation, this.id)
149 case `cleaned-up`:
150 // Automatically restart the collection when operations are called on cleaned-up collections
151 this.sync.startSync()
152 break
153 }
154 }
155
156 /**
157 * Mark the collection as ready for use
158 * This is called by sync implementations to explicitly signal that the collection is ready,
159 * providing a more intuitive alternative to using commits for readiness signaling
160 * @private - Should only be called by sync implementations
161 */
162 public markReady(): void {
163 const failure = this.applyReadyTransition()
164 if (failure) throw failure.error
165 }
166
167 /** @internal Capture ready-effect failures while the sync entry completes. */
168 public markReadyDuringSyncStart(): { error: unknown } | undefined {
169 return this.applyReadyTransition()
170 }
171
172 private applyReadyTransition(): { error: unknown } | undefined {
173 this.validateStatusTransition(this.status, `ready`)
174 // A successful initial sync or recovery establishes a ready snapshot.
175 if (this.status === `loading` || this.status === `error`) {
176 this.syncError = undefined
177 const readyRevision = this.statusRevision + 1
178 this.setStatus(`ready`, true)
179
180 // A status listener can synchronously supersede this transition, even
181 // when it restarts the Collection back to ready before returning.
182 if (
183 (this.status as CollectionStatus) !== `ready` ||
184 this.statusRevision !== readyRevision
185 ) {
186 return undefined
187 }
188
189 const readyEffects: Array<() => void> = []
190
191 // Call any registered first ready callbacks (only on first time becoming ready)
192 if (!this.hasBeenReady) {
193 this.hasBeenReady = true
194
195 // Also mark as having received first commit for backwards compatibility
196 if (!this.hasReceivedFirstCommit) {
197 this.hasReceivedFirstCommit = true
198 }
199
200 readyEffects.push(...this.onFirstReadyCallbacks)
201 this.onFirstReadyCallbacks = []
202 }
203 // Notify dependents when markReady is called, after status is set
204 // This ensures live queries get notified when their dependencies become ready
205 readyEffects.push(() => this.changes.emitEmptyReadyEvent())
206 try {
207 runAllCallbacks(readyEffects)
208 } catch (error) {
209 return { error }
210 }
211 }
212 return undefined
213 }
214
215 /** Mark an asynchronous sync failure after sync has started. */
216 public markError(error?: unknown): void {
217 this.validateStatusTransition(this.status, `error`)
218 this.syncError = error
219 this.setStatus(`error`)
220 }
221
222 /** Return the cause supplied by the current sync run, if any. */
223 public getSyncError(): unknown {
224 return this.syncError
225 }
226
227 public assertCanStartSync(): void {
228 if (this.cleaningUp) {
229 throw new CollectionStateError(
230 `Cannot start collection "${this.id}" during cleanup. Restart after cleanup() completes.`,
231 )
232 }
233 // A synchronously finished retirement retains its public promise until
234 // settlement. Starting a new sync run assigns later cleanup to that run.
235 this.cleanupPromise = null
236 }
237
238 /**
239 * Start the garbage collection timer for a collection with no subscribers
240 * Called when sync starts outside a subscription
241 */
242 public startGCTimerIfUnsubscribed(): void {
243 this.startGCTimer(UNSUBSCRIBED_GC_FLOOR_MS)
244 }
245
246 private canGarbageCollect(): boolean {
247 return (
248 !this.cleaningUp &&
249 this.changes.activeSubscribersCount === 0 &&
250 !this.sync.hasPendingPreload
251 )
252 }
253
254 /**
255 * Start the garbage collection timer
256 * Called when the collection becomes inactive (no subscribers)
257 */
258 public startGCTimer(minDelay = 0): void {
259 if (!this.canGarbageCollect()) return
260
261 const gcTime = this.config.gcTime ?? 300000 // 5 minutes default
262
263 // If gcTime is 0, negative, or non-finite (Infinity, -Infinity, NaN), GC is disabled.
264 // Note: setTimeout with Infinity coerces to 0 via ToInt32, causing immediate GC,
265 // so we must explicitly check for non-finite values here.
266 if (gcTime <= 0 || !Number.isFinite(gcTime)) {
267 return
268 }
269
270 CleanupQueue.getInstance().schedule(
271 this,
272 Math.max(gcTime, minDelay),
273 () => {
274 if (this.canGarbageCollect()) {
275 // Schedule cleanup during idle time to avoid blocking the UI thread
276 this.scheduleIdleCleanup()
277 }
278 },
279 )
280 }
281
282 /**
283 * Cancel the garbage collection timer
284 * Called when the collection becomes active again
285 */
286 public cancelGCTimer(): void {
287 CleanupQueue.getInstance().cancel(this)
288 // Also cancel any pending idle cleanup
289 if (this.idleCallbackId !== null) {
290 safeCancelIdleCallback(this.idleCallbackId)
291 this.idleCallbackId = null
292 }
293 }
294
295 /**
296 * Schedule cleanup to run during browser idle time
297 * This prevents blocking the UI thread during cleanup operations
298 */
299 private scheduleIdleCleanup(): void {
300 // Cancel any existing idle callback
301 if (this.idleCallbackId !== null) {
302 safeCancelIdleCallback(this.idleCallbackId)
303 }
304
305 // Schedule cleanup with a timeout of 1 second
306 // This ensures cleanup happens even if the browser is busy
307 this.idleCallbackId = safeRequestIdleCallback(
308 (deadline) => {
309 // Perform cleanup if we still have no subscribers
310 if (this.canGarbageCollect()) {
311 const cleanupCompleted = this.performCleanup(deadline)
312 // Only clear the callback ID if cleanup actually completed
313 if (cleanupCompleted) {
314 this.idleCallbackId = null
315 }
316 } else {
317 // No need to cleanup, clear the callback ID
318 this.idleCallbackId = null
319 }
320 },
321 { timeout: 1000 },
322 )
323 }
324
325 /**
326 * Perform cleanup operations, optionally in chunks during idle time
327 * @returns true if cleanup was completed, false if it was rescheduled
328 */
329 private performCleanup(deadline?: IdleCallbackDeadline): boolean {
330 // Nested cleanup belongs to this retirement, not a new lifecycle turn.
331 if (this.cleaningUp) return true
332 // If we have a deadline, we can potentially split cleanup into chunks
333 // For now, we'll do all cleanup at once but check if we have time
334 const hasTime =
335 !deadline || deadline.timeRemaining() > 0 || deadline.didTimeout
336
337 if (hasTime) {
338 const cleanup = this.beginCleanup()
339 // Automatic GC has no caller to receive cleanup rejection. Core still
340 // finalizes the lifecycle; adapter diagnostics remain observable through
341 // the returned promise for explicit cleanup.
342 void cleanup.catch(() => undefined)
343
344 return true
345 } else {
346 // If we don't have time, reschedule for the next idle period
347 this.scheduleIdleCleanup()
348 return false
349 }
350 }
351
352 private beginCleanup(): Promise<void> {
353 if (this.cleanupPromise) return this.cleanupPromise
354
355 const completion = createDeferred<void>()
356 this.cleanupPromise = completion.promise
357 this.cleaningUp = true
358 let localFailure: { error: unknown } | undefined
359 let synchronousSyncFailure: { error: unknown } | undefined
360 let syncCleanupComplete = true
361 let finished = false
362
363 const attempt = (callback: () => void): void => {
364 try {
365 callback()
366 } catch (error) {
367 localFailure ??= { error }
368 }
369 }
370
371 const finish = (syncFailure?: { error: unknown }) => {
372 if (finished) return
373 finished = true
374 this.cleaningUp = false
375 attempt(() => this.setStatus(`cleaned-up`))
376
377 // Active collection subscriptions still depend on lifecycle events.
378 // Once the last subscriber leaves, its GC cleanup clears the handlers.
379 if (this.changes.activeSubscribersCount === 0) {
380 attempt(() => this.events.cleanup())
381 }
382
383 // Keep cleanup observably asynchronous even when every release is
384 // synchronous. Existing callers may use this turn to let optimistic
385 // settlement finish before starting the next operation.
386 const failure =
387 syncFailure && localFailure
388 ? {
389 error: new AggregateError(
390 [syncFailure.error, localFailure.error],
391 `Adapter cleanup and local teardown both failed`,
392 { cause: syncFailure.error },
393 ),
394 }
395 : (syncFailure ?? localFailure)
396 void Promise.resolve()
397 .then(() => Promise.resolve())
398 .then(() => {
399 if (this.cleanupPromise === completion.promise) {
400 this.cleanupPromise = null
401 }
402 if (failure) completion.reject(failure.error)
403 else completion.resolve()
404 })
405 }
406
407 // Sync cleanup invalidates the sync run before invoking the adapter. The
408 // remaining managers retire their local state synchronously while the
409 // adapter's resource-release promise is pending.
410 attempt(() => this.cleanupConfig())
411 try {
412 syncCleanupComplete = this.sync.cleanup(finish)
413 } catch (error) {
414 synchronousSyncFailure = { error }
415 }
416
417 attempt(() => this.state.cleanup())
418 attempt(() => this.changes.cleanup())
419 attempt(() => this.indexes.cleanup())
420 CleanupQueue.getInstance().cancel(this)
421
422 this.hasBeenReady = false
423 this.syncError = undefined
424 // Cleanup is not readiness. Sync cleanup rejects pending preload callers;
425 // first-ready listeners belong to the discarded run.
426 this.onFirstReadyCallbacks = []
427
428 if (syncCleanupComplete) finish(synchronousSyncFailure)
429 return completion.promise
430 }
431
432 /**
433 * Register a callback to be executed when the collection first becomes ready
434 * Useful for preloading collections
435 * @param callback Function to call when the collection first becomes ready
436 */
437 public onFirstReady(callback: () => void): () => void {
438 // If already ready, call immediately
439 if (this.hasBeenReady) {
440 callback()
441 return () => {}
442 }
443
444 this.onFirstReadyCallbacks.push(callback)
445 return () => {
446 const index = this.onFirstReadyCallbacks.indexOf(callback)
447 if (index !== -1) {
448 this.onFirstReadyCallbacks.splice(index, 1)
449 }
450 }
451 }
452
453 public cleanup(): Promise<void> {
454 // Cancel any pending idle cleanup
455 if (this.idleCallbackId !== null) {
456 safeCancelIdleCallback(this.idleCallbackId)
457 this.idleCallbackId = null
458 }
459
460 // Return this exact retirement operation even if an event listener starts
461 // a replacement run and cleanup while the first promise is still pending.
462 return this.beginCleanup()
463 }
464}