Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

live-query-observer-client.ts

352 lines11.5 KB

1import { getLiveQueryRowOptions } from './live-query-options.js'
2import { codedMessage, devBuild } from './error-message.js'
3import { getBuilderFromConfig } from './query/live/collection-registry.js'
4import { getPooledLiveQuerySource } from './query/pooled-source.js'
5import { isFailedStatus } from './live-query-primitives.js'
6import type { Collection } from './collection/index.js'
7import type { DbClient, DehydratedLiveQueryResult } from './client.js'
8import type {
9 LiveQueryObserver,
10 LiveQuerySnapshot,
11} from './live-query-observer.js'
12import type { ChangeMessage } from './types.js'
13​
14/**
15 * DbClient supplies transport behavior to the shared observer. Keeping this
16 * implementation behind the client means ordinary framework queries do not
17 * import server admission, hydration reconciliation, or streaming machinery.
18 */
19export interface LiveQueryObserverClientHost<
20 T extends object,
21 TKey extends string | number,
22> {
23 observer: LiveQueryObserver<T, TKey>
24 read: (forServerSnapshot: boolean) => LiveQuerySnapshot<T, TKey>
25 entries: () => Array<[TKey, T]>
26 isAttached: () => boolean
27 isDisposed: () => boolean
28 dirty: () => void
29 publish: (
30 changes: Array<ChangeMessage<T, TKey>>,
31 entries?: Array<[TKey, T]>,
32 ) => void
33 preload: () => Promise<void>
35​
36export class LiveQueryObserverClient<
37 T extends object,
38 TKey extends string | number,
39> {
40 private hydrationSeed:
41 | {
42 dehydratedAt: number
43 entries: Array<[TKey, T]>
44 snapshot: DehydratedLiveQueryResult
45 }
46 | undefined
47 error: unknown
48 failed = false
49 private authoritative = false
50 private handoffScheduled = false
51 private unregisterResource: (() => void) | undefined
52 private preloadPromise: Promise<void> | undefined
53​
54 constructor(
55 private readonly client: DbClient,
56 private readonly collection: Collection<T, TKey, any> | null,
57 private readonly queryHash: string | undefined,
58 private readonly usesSettledHydration: boolean,
59 private readonly host: LiveQueryObserverClientHost<T, TKey>,
60 ) {}
61​
62 get seed() {
63 return this.authoritative ? undefined : this.hydrationSeed
64 }
65​
66 get query() {
67 return this.queryHash
68 ? this.client._getLiveQuery(this.queryHash)
69 : undefined
70 }
71​
72 sync(forServerSnapshot = false): boolean {
73 if (!this.queryHash || this.authoritative) return false
74 this.client._waitForSsrLiveQuery(this.queryHash)
75 const query = this.client._getLiveQuery(this.queryHash, forServerSnapshot)
76 if (!query) return false
77 if (
78 this.host.isAttached() &&
79 !this.hydrationSeed &&
80 this.collection?.status === `ready` &&
81 !this.collection.isLoadingSubset
82 ) {
83 return this.markAuthoritative(query.dehydratedAt)
84 }
85 if (
86 query.status === `error` &&
87 (this.usesSettledHydration ||
88 !forServerSnapshot ||
89 !query.initialSnapshot)
90 ) {
91 const changed = !this.failed || this.error !== query.error
92 this.error = query.error
93 this.failed = true
94 if (changed) this.host.dirty()
95 return changed
96 }
97 const snapshot =
98 (!this.usesSettledHydration && query.initialSnapshot) || query.snapshot
99 if (!snapshot || this.hydrationSeed?.snapshot === snapshot) return false
100 this.hydrationSeed = {
101 dehydratedAt: query.dehydratedAt,
102 snapshot,
103 entries: snapshot.rows.map((row) => [row.key as TKey, row.value as T]),
104 }
105 this.error = undefined
106 this.failed = false
107 this.host.dirty()
108 return true
109 }
110​
111 getServerSnapshot(preloadRequested: boolean): LiveQuerySnapshot<T, TKey> {
112 preloadRequested &&= this.client._isSsrStreamingEnabled()
113 if (
114 typeof window !== `undefined` &&
115 !this.authoritative &&
116 this.queryHash
117 ) {
118 const waiting = this.client._waitForSsrLiveQuery(this.queryHash, true)
119 if (waiting) throw waiting
120 const query = this.client._getLiveQuery(this.queryHash, true)
121 const snapshot = this.usesSettledHydration
122 ? query?.snapshot
123 : (query?.initialSnapshot ?? query?.snapshot)
124 // A later boundary may hydrate before its result promise arrives.
125 // Local rows cannot substitute for the missing server-rendered view.
126 if (query?.status === `pending` && !snapshot) {
127 if (this.usesSettledHydration)
128 void this.host.observer.preload().catch(() => {})
129 throw query.promise
130 }
131 }
132 if (preloadRequested) {
133 void this.host.observer.preload().catch(() => {})
134 }
135 if (typeof window === `undefined`) this.assertSources()
136 const snapshot = this.host.read(true)
137 const collection = this.collection
138 if (!collection || this.seed) return snapshot
139 // React also calls this getter in the browser during hydration. Only
140 // server reads perform admission; transported seeds win over local activity.
141 if (typeof window !== `undefined`) return snapshot
142 // A suspended component has not rendered this loading view. Its settled
143 // stream will supply the first rendered result.
144 if (preloadRequested && !snapshot.isReady) return snapshot
145​
146 const { sources } = this.getSourceInfo()
147 const entries = this.host.entries()
148 if (
149 !this.queryHash ||
150 (!preloadRequested &&
151 (entries.length > 0 || snapshot.isReady) &&
152 !(sources ?? [collection]).every((source) =>
153 this.client._hasSsrCollectionSnapshot(source),
154 ))
155 ) {
156 throw new Error(
157 devBuild() && process.env.NODE_ENV !== `production`
158 ? `SSR cannot render server-only live-query rows or readiness. Await DbClient.preloadLiveQuery() for this query, or explicitly preload its source Collections for hydration. Opaque queries require an explicit serializable queryKey.`
159 : codedMessage(252),
160 )
161 }
162 // Capture at render, rather than sampling mutable source rows at dehydrate.
163 // Loading views transfer rows without answering a later data preload.
164 this.client._captureServerQuery(
165 this.queryHash,
166 {
167 rows: entries.map(([key, value]) => ({ key, value })),
168 ...(snapshot.isReady
169 ? {}
170 : {
171 status:
172 snapshot.isLoadingError || snapshot.isCrashed
173 ? (`error` as const)
174 : (`loading` as const),
175 }),
176 },
177 sources,
178 getLiveQueryRowOptions(collection),
179 )
180 return this.host.read(true)
181 }
182​
183 private diffEntries(
184 previous: Array<[TKey, T]>,
185 next: Array<[TKey, T]>,
186 ): Array<ChangeMessage<T, TKey>> {
187 const previousByKey = new Map(previous)
188 const nextByKey = new Map(next)
189 const changes: Array<ChangeMessage<T, TKey>> = []
190 for (const [key, value] of previous) {
191 if (!nextByKey.has(key)) changes.push({ type: `delete`, key, value })
192 }
193 for (const [key, value] of next) {
194 const previousValue = previousByKey.get(key)
195 if (previousValue === undefined)
196 changes.push({ type: `insert`, key, value })
197 else if (previousValue !== value)
198 changes.push({ type: `update`, key, value, previousValue })
199 }
200 return changes
201 }
202​
203 markAuthoritative(dehydratedAt?: number): boolean {
204 if (this.authoritative) return false
205 dehydratedAt ??= this.query?.dehydratedAt
206 const changed = this.failed
207 this.error = undefined
208 this.failed = false
209 this.authoritative = true
210 if (dehydratedAt !== undefined && this.queryHash)
211 this.client._consumeLiveQueryResult(this.queryHash, dehydratedAt)
212 if (changed) this.host.dirty()
213 return changed
214 }
215​
216 scheduleHandoff(): void {
217 if (this.handoffScheduled) return
218 this.handoffScheduled = true
219 queueMicrotask(() => {
220 this.handoffScheduled = false
221 this.handoff()
222 })
223 }
224​
225 handoff(): void {
226 const collection = this.collection
227 if (
228 this.host.isDisposed() ||
229 !this.host.isAttached() ||
230 !collection ||
231 !this.seed ||
232 // A failure ends the sync run whose result the seed stood in for.
233 (!isFailedStatus(collection.status) &&
234 (collection.status !== `ready` || collection.isLoadingSubset))
235 )
236 return
237 const previous = this.seed.entries
238 const dehydratedAt = this.seed.dehydratedAt
239 const entries = Array.from(collection.entries()) as Array<[TKey, T]>
240 this.hydrationSeed = undefined
241 this.markAuthoritative(dehydratedAt)
242 this.host.publish(this.diffEntries(previous, entries), entries)
243 }
244​
245 assertSources(): void {
246 const { sources } = this.getSourceInfo()
247 if (this.queryHash && sources)
248 this.client._assertLiveQuerySources(
249 this.queryHash,
250 sources,
251 getLiveQueryRowOptions(this.collection),
252 )
253 }
254​
255 subscribe(): () => void {
256 if (!this.queryHash) return () => {}
257 return this.client.subscribe((event) => {
258 if (
259 event.type === `liveQueryStreamError` ||
260 event.query.queryHash !== this.queryHash
261 )
262 return
263 const previous = this.host.entries()
264 if (this.sync())
265 this.host.publish(this.diffEntries(previous, this.host.entries()))
266 })
267 }
268​
269 registerResource(): void {
270 const config: object | undefined = this.collection?.config
271 if (
272 this.unregisterResource ||
273 !this.client._isSsrServerCleanupEnabled() ||
274 !config ||
275 !getBuilderFromConfig(config)
276 )
277 return
278 this.unregisterResource = this.client._registerLiveQueryResource(
279 this.host.observer,
280 async () => {
281 this.host.observer.dispose()
282 await this.collection?.cleanup({ dependents: true })
283 },
284 )
285 }
286​
287 takeResourceRelease(): (() => void) | undefined {
288 const release = this.unregisterResource
289 this.unregisterResource = undefined
290 return release
291 }
292​
293 private getSourceInfo() {
294 const collection = this.collection
295 const config = collection?.config
296 const pooledSource = collection && getPooledLiveQuerySource(collection)
297 const sources = config
298 ? getBuilderFromConfig(config)?.getSourceCollections()
299 : pooledSource
300 ? [pooledSource]
301 : undefined
302 return { sources, pooledSource: pooledSource || undefined }
303 }
304​
305 preload(): Promise<void> {
306 if (this.preloadPromise) return this.preloadPromise
307 const { sources, pooledSource } = this.getSourceInfo()
308 if (this.queryHash) {
309 const query = this.query
310 try {
311 this.client._waitForSsrLiveQuery(this.queryHash)
312 if (sources)
313 this.client._assertLiveQuerySources(
314 this.queryHash,
315 sources,
316 getLiveQueryRowOptions(this.collection),
317 )
318 if (
319 query?.status === `pending` ||
320 (query?.status === `success` && query.snapshot?.status === undefined)
321 ) {
322 if (pooledSource && this.collection)
323 return Promise.all([query.promise, this.collection.preload()]).then(
324 () => {},
325 )
326 // Stream reuse remains explicit demand for the local Collection.
327 this.collection?._markPreload()
328 return query.status === `pending` ? query.promise : Promise.resolve()
329 }
330 } catch (error) {
331 return Promise.reject(error)
332 }
333 }
334 this.registerResource()
335 const collectionPromise = this.host.preload()
336 const promise =
337 this.client._isSsrStreamingEnabled() && this.queryHash
338 ? this.client._registerLiveQuery(
339 this.queryHash,
340 collectionPromise.then(() => this.host.observer.dehydrate()),
341 sources,
342 getLiveQueryRowOptions(this.collection),
343 )
344 : collectionPromise
345 this.preloadPromise = promise
346 const clear = () => {
347 if (this.preloadPromise === promise) this.preloadPromise = undefined
348 }
349 void promise.then(clear, clear)
350 return promise
351 }