Open History to see the last commit
1import { BaseQueryBuilder } from './query/builder/index.js'
2import { collectSourceRefs, requireCollectionSource } from './query/ir.js'
3import { isCollection, isFailedStatus } from './live-query-primitives.js'
4import {
5 DEFAULT_GC_TIME_MS,
6 UNSUBSCRIBED_GC_FLOOR_MS,
7} from './collection/lifecycle.js'
8import { createLiveQueryCollection } from './query/live-query-collection.js'
9import { LIVE_QUERY_INTERNAL } from './query/live/internal.js'
10import { getBuilderFromConfig } from './query/live/collection-registry.js'
11import {
12 getStableQueryBuilderHash,
13 getStableValueHash,
14} from './query/ir-stable-identity.js'
15import { getStringCollationIdentity } from './query/runtime-reference-identity.js'
16import { codedMessage, devBuild } from './error-message.js'
17import { InvalidPoolOptionError } from './errors.js'
18import type { Collection, CollectionImpl } from './collection/index.js'
19import type { CollectionOptionsIdentity } from './collection-options.js'
20import type { CollectionOptions, DbClient } from './client.js'
21import type { PooledLiveQueries } from './query/pooled-live-query.js'
22import type {
23 Context,
24 InitialQueryBuilder,
25 LiveQueryCollectionConfig,
26 LiveQueryHookConfig,
27 QueryBuilder,
28} from './query/index.js'
29
30/**
31 * A hook config's pool: `pooledLiveQueries` or nothing. Any other value, such
32 * as the removed boolean form, contradicts the hook contract, so every reader
33 * rejects it the same way, whatever the config's other options. An adapter
34 * that reads the pool from its own options, as Angular does, checks it here.
35 */
36export function configPool(config: object): PooledLiveQueries | undefined {
37 const { pool } = config as { pool?: unknown }
38 if (
39 pool !== undefined &&
40 typeof (pool as Partial<PooledLiveQueries> | null)
41 ?.createPooledLiveQuery !== `function`
42 )
43 throw new InvalidPoolOptionError()
44 return pool as PooledLiveQueries | undefined
45}
46
47export type LiveQueryKey = ReadonlyArray<unknown>
48
49export type LiveQueryOptions = LiveQueryCollectionConfig<any> & {
50 queryKey?: LiveQueryKey
51}
52
53export type DeferredLiveQueryCollections = Set<
54 CollectionImpl<any, string | number, any, any, any>
55>
56
57/**
58 * Release the sync starts a rejected query input deferred, then rethrow its
59 * rejection. A framework hook calls this around its own render work, so a
60 * query the hook rejects leaves no source deferred and a later reader can
61 * start it. A render that throws after the hook returns, such as in a sibling
62 * hook, is not a rejection of this input: like any render that never commits,
63 * it releases its deferral through `releaseDeferredOnReclaim` when garbage
64 * collection reclaims its live query. As for a
65 * `DbClient` preload, the rejection wins over a source whose resumed start
66 * fails; that source records its own failure.
67 */
68export function rejectLiveQueryInput(
69 collections: DeferredLiveQueryCollections | undefined,
70 rejection: unknown,
71): never {
72 try {
73 if (collections) resumeDeferredLiveQueryCollections(collections)
74 } catch {
75 // Report the rejection, not a later start failure.
76 }
77 throw rejection
78}
79
80/**
81 * Release a render's deferred sync starts when the live query it built is
82 * reclaimed. A render that commits releases them first, when it subscribes.
83 * A render that never commits, because a sibling threw or it suspended, leaves
84 * its live query unsubscribed until garbage collection cleans it up; that
85 * cleanup releases the starts, so a direct reader's demand, made before or
86 * after, then starts the sources. A live query that garbage collection never
87 * reclaims, because its config disables GC or does not start its sync,
88 * releases after the unsubscribed GC floor instead. Releases only the starts
89 * deferred so far, not ones a later render of the same hook defers. Pass only
90 * a live query the render built, and call the returned function when the
91 * render commits, so a committed hook keeps no listener, timer, or copied
92 * sources.
93 */
94export function releaseDeferredOnReclaim(
95 liveQuery: Pick<Collection<any, any, any>, `once` | `config` | `status`>,
96 deferredCollections: DeferredLiveQueryCollections,
97): (() => void) | undefined {
98 if (deferredCollections.size === 0) return undefined
99 const pending: DeferredLiveQueryCollections = new Set(deferredCollections)
100 const release = () => {
101 try {
102 resumeDeferredLiveQueryCollections(pending)
103 } catch {
104 // A source whose resumed start fails records its own failure.
105 }
106 }
107 // The lifecycle's own rule: GC reclaims only a started collection with a
108 // finite, positive gcTime.
109 const gcTime = liveQuery.config.gcTime ?? DEFAULT_GC_TIME_MS
110 if (gcTime > 0 && Number.isFinite(gcTime) && liveQuery.status !== `idle`) {
111 return liveQuery.once(`status:cleaned-up`, release)
112 }
113 const timer = setTimeout(release, UNSUBSCRIBED_GC_FLOOR_MS)
114 return () => clearTimeout(timer)
115}
116
117/** Release every deferred source, then report the first startup failure. */
118export function resumeDeferredLiveQueryCollections(
119 collections: DeferredLiveQueryCollections,
120 reportSourceErrors = false,
121): void {
122 const pending = Array.from(collections)
123 collections.clear()
124 let firstFailure: { error: unknown } | undefined
125 for (const collection of pending) {
126 try {
127 collection._resumeSyncStart()
128 // An explicit preload owns source failure reporting even when graph
129 // demand already released the gate. Ordinary hooks read the status.
130 if (reportSourceErrors && isFailedStatus(collection.status)) {
131 throw collection._lifecycle.getSyncError()
132 }
133 } catch (error) {
134 firstFailure ??= { error }
135 }
136 }
137 if (firstFailure) throw firstFailure.error
138}
139
140type PreparedLiveQueryConfigInput = Omit<
141 LiveQueryHookConfig<Context>,
142 `query`
143> & {
144 query:
145 | QueryBuilder<Context>
146 | ((q: InitialQueryBuilder) => QueryBuilder<Context> | undefined | null)
147 queryKey?: LiveQueryKey
148 client?: DbClient
149}
150
151function createInitialQueryBuilder(): InitialQueryBuilder {
152 // Query construction does not materialize descriptor Collections.
153 return new BaseQueryBuilder() as InitialQueryBuilder
154}
155
156function createCollectionResolver(
157 dbClient: DbClient | undefined,
158 deferredCollections?: DeferredLiveQueryCollections,
159) {
160 if (!dbClient) return undefined
161 return (
162 options: CollectionOptionsIdentity<any, string | number, any, any, any>,
163 ): CollectionImpl<any, string | number, any, any, any> => {
164 if (!deferredCollections) {
165 return dbClient.collection(
166 options as CollectionOptions<any, string | number, any, any>,
167 ) as CollectionImpl<any, string | number, any, any, any>
168 }
169 const collection = dbClient._materializeCollectionForRender(
170 options as CollectionOptions<any, string | number, any, any>,
171 ) as CollectionImpl<any, string | number, any, any, any>
172 if (collection._deferSyncStart()) deferredCollections.add(collection)
173 return collection
174 }
175}
176
177export function prepareLiveQueryValue(
178 value: unknown,
179 dbClient: DbClient | undefined,
180 deferredCollections?: DeferredLiveQueryCollections,
181): unknown {
182 if (typeof value === `function`) {
183 return prepareLiveQueryValue(
184 value(createInitialQueryBuilder()),
185 dbClient,
186 deferredCollections,
187 )
188 }
189
190 if (value instanceof BaseQueryBuilder) {
191 return value._bindCollectionSources(
192 createCollectionResolver(dbClient, deferredCollections),
193 )
194 }
195
196 if (
197 value &&
198 typeof value === `object` &&
199 !isCollection(value) &&
200 !(value instanceof BaseQueryBuilder) &&
201 `query` in value
202 ) {
203 const pool = configPool(value)
204 const {
205 query,
206 queryKey: _queryKey,
207 client: _client,
208 pool: _pool,
209 ...config
210 } = value as PreparedLiveQueryConfigInput
211
212 const preparedQuery = prepareLiveQueryValue(
213 query,
214 dbClient,
215 deferredCollections,
216 )
217
218 if (preparedQuery === undefined || preparedQuery === null) {
219 return preparedQuery
220 }
221
222 return {
223 ...config,
224 // A DbClient query never pools, so its identity must not depend on
225 // pool: a server preload and a client hook must hash alike.
226 ...(pool && !dbClient ? { pool } : {}),
227 query: preparedQuery,
228 }
229 }
230
231 return value
232}
233
234/** Concrete source objects in query-position order for a prepared value. */
235export function getPreparedLiveQuerySources(
236 value: unknown,
237 onUnboundDescriptor?: (alias: string) => never,
238): Array<Collection> {
239 if (isCollection(value)) return [value]
240 const query =
241 value instanceof BaseQueryBuilder
242 ? value
243 : value && typeof value === `object` && `query` in value
244 ? value.query
245 : value
246 if (query instanceof BaseQueryBuilder) {
247 return collectSourceRefs(query._getQuery()).map((source) =>
248 source.type === `descriptorRef`
249 ? onUnboundDescriptor
250 ? onUnboundDescriptor(source.alias)
251 : requireCollectionSource(source)
252 : source.collection,
253 )
254 }
255 return isCollection(query) ? [query] : []
256}
257
258/** Local row behavior, kept separate from the portable query identity. */
259export type LiveQueryRowOptions = readonly [getKey: unknown, schema: unknown]
260
261export function getLiveQueryRowOptions(value: unknown): LiveQueryRowOptions {
262 if (isCollection(value)) {
263 const { config } = value
264 const internal = config.utils?.[LIVE_QUERY_INTERNAL] as
265 { hasCustomGetKey?: boolean } | undefined
266 return [
267 internal?.hasCustomGetKey ? config.getKey : undefined,
268 config.schema,
269 ]
270 }
271 const config = value as
272 { getKey?: unknown; schema?: unknown } | null | undefined
273 return [config?.getKey, config?.schema]
274}
275
276export function getPreparedLiveQueryIdentity(
277 value: unknown,
278 pool?: PooledLiveQueries,
279): unknown {
280 if (isCollection(value)) return [`collection`, value.id]
281 if (value instanceof BaseQueryBuilder) {
282 // A pooled query's fields and literals identify its rows without
283 // canonicalizing its whole IR on every render.
284 const pooled = pool?.getPooledQueryIdentity(value)
285 return pooled === undefined
286 ? [`query`, getStableQueryBuilderHash(value)]
287 : [`pooled`, pooled]
288 }
289 if (value && typeof value === `object` && `query` in value) {
290 const config = value as LiveQueryCollectionConfig<any>
291 return [
292 // getKey and schema bind for this query identity. Inline options must
293 // not turn a normal framework render into a new Collection.
294 `config`,
295 getPreparedLiveQueryIdentity(config.query, configPool(config)),
296 [`singleResult`, config.singleResult === true],
297 [
298 `defaultStringCollation`,
299 getStringCollationIdentity(config.defaultStringCollation),
300 ],
301 ]
302 }
303 if (value === undefined || value === null) return [`disabled`]
304 return [`value`, value]
305}
306
307export function getLiveQueryHash(
308 preparedValue: unknown,
309 queryKey?: LiveQueryKey,
310): string {
311 if (queryKey?.length) {
312 const query =
313 preparedValue instanceof BaseQueryBuilder
314 ? preparedValue
315 : preparedValue &&
316 typeof preparedValue === `object` &&
317 `query` in preparedValue
318 ? preparedValue.query
319 : undefined
320 const ir = isCollection(preparedValue)
321 ? getBuilderFromConfig(preparedValue.config)?.getWindow()
322 : query instanceof BaseQueryBuilder
323 ? query._getQuery()
324 : undefined
325 const window =
326 ir && (ir.limit !== undefined || (ir.offset ?? 0) !== 0)
327 ? [{ limit: ir.limit, offset: ir.offset ?? 0 }]
328 : []
329 return getStableValueHash([`queryKey`, queryKey, ...window], `queryKey`)
330 }
331 const identity = isCollection(preparedValue)
332 ? [`collection`, preparedValue.id]
333 : [`derived`, getPreparedLiveQueryIdentity(preparedValue)]
334
335 return getStableValueHash(identity, `queryKey`)
336}
337
338// A config that names only its query and lifetime describes the same live
339// query as its builder. Any other option shapes its Collection, so compiles.
340function poolConfig(
341 config: LiveQueryCollectionConfig<any>,
342 gcTime: number | undefined,
343 pool: PooledLiveQueries,
344): Collection<any, any, any> | undefined {
345 if (
346 !(config.query instanceof BaseQueryBuilder) ||
347 !Object.keys(config).every((key) => key === `query` || key === `gcTime`)
348 ) {
349 return undefined
350 }
351 return pool.createPooledLiveQuery(config.query, {
352 gcTime: config.gcTime ?? gcTime,
353 })
354}
355
356/**
357 * Resolve an adapter's query value to what its observer watches: `null` for a
358 * disabled query, an existing Collection with sync started, or a live query.
359 * A query builder whose shape a shared partition can serve gets a pooled view
360 * instead of its own live-query Collection.
361 */
362export function resolveLiveQueryValue(
363 value: unknown,
364 {
365 gcTime,
366 pool,
367 startSync = true,
368 }: {
369 gcTime?: number
370 // `false` keeps a hook that cannot pool, such as a Suspense or DbClient
371 // query, from pooling even when its config passes `pooledLiveQueries`.
372 // A pool here has passed `configPool`.
373 pool?: PooledLiveQueries | false
374 startSync?: boolean
375 } = {},
376): Collection<any, any, any> | null {
377 if (value === undefined || value === null) return null
378 if (isCollection(value)) {
379 value.startSyncImmediate()
380 return value
381 }
382 if (value instanceof BaseQueryBuilder) {
383 return (
384 (pool ? pool.createPooledLiveQuery(value, { gcTime }) : undefined) ??
385 createLiveQueryCollection({ query: value, startSync, gcTime })
386 )
387 }
388 if (typeof value === `object`) {
389 const requested = configPool(value)
390 const { pool: _pool, ...given } = value as LiveQueryHookConfig<any>
391 const pooling = pool === false ? undefined : (requested ?? pool)
392 // A pooled view needs the built query. Build a query function once and
393 // compile the same builder if the partition cannot serve it.
394 const built =
395 pooling && typeof given.query === `function`
396 ? given.query(createInitialQueryBuilder())
397 : undefined
398 const config =
399 built instanceof BaseQueryBuilder ? { ...given, query: built } : given
400 return (
401 (pooling ? poolConfig(config, gcTime, pooling) : undefined) ??
402 createLiveQueryCollection({
403 ...config,
404 startSync: config.startSync ?? startSync,
405 gcTime: config.gcTime ?? gcTime,
406 })
407 )
408 }
409 throw new Error(
410 devBuild() && process.env.NODE_ENV !== `production`
411 ? `A live query must be a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof value}`
412 : codedMessage(102, { type: typeof value }),
413 )
414}