Open History to see the last commit
1/* eslint-disable @typescript-eslint/no-unnecessary-condition */
2import { Store } from '@tanstack/store'
3import {
4 ExpectedDeleteTypeError,
5 ExpectedInsertTypeError,
6 ExpectedUpdateTypeError,
7 TimeoutWaitingForIdsError,
8} from './errors'
9import type { OrderByClause } from '../../db/dist/esm/query/ir'
10import type { CompareOp, Event, FilterOrComposite, RecordApi } from 'trailbase'
11
12import type {
13 BaseCollectionConfig,
14 CollectionConfig,
15 DeleteMutationFnParams,
16 InsertMutationFnParams,
17 LoadSubsetOptions,
18 SyncConfig,
19 SyncMode,
20 UpdateMutationFnParams,
21 UtilsRecord,
22} from '@tanstack/db'
23
24type ShapeOf<T> = Record<keyof T, unknown>
25type Conversion<I, O> = (value: I) => O
26
27type OptionalConversions<
28 InputType extends ShapeOf<OutputType>,
29 OutputType extends ShapeOf<InputType>,
30> = {
31 // Excludes all keys that require a conversation.
32 [K in keyof InputType as InputType[K] extends OutputType[K]
33 ? K
34 : never]?: Conversion<InputType[K], OutputType[K]>
35}
36
37type RequiredConversions<
38 InputType extends ShapeOf<OutputType>,
39 OutputType extends ShapeOf<InputType>,
40> = {
41 // Excludes all keys that do not strictly require a conversation.
42 [K in keyof InputType as InputType[K] extends OutputType[K]
43 ? never
44 : K]: Conversion<InputType[K], OutputType[K]>
45}
46
47type Conversions<
48 InputType extends ShapeOf<OutputType>,
49 OutputType extends ShapeOf<InputType>,
50> = OptionalConversions<InputType, OutputType> &
51 RequiredConversions<InputType, OutputType>
52
53function convert<
54 InputType extends ShapeOf<OutputType> & Record<string, unknown>,
55 OutputType extends ShapeOf<InputType>,
56>(
57 conversions: Conversions<InputType, OutputType>,
58 input: InputType,
59): OutputType {
60 const c = conversions as Record<string, Conversion<InputType, OutputType>>
61
62 return Object.fromEntries(
63 Object.keys(input).map((k: string) => {
64 const value = input[k]
65 return [k, c[k]?.(value as any) ?? value]
66 }),
67 ) as OutputType
68}
69
70function convertPartial<
71 InputType extends ShapeOf<OutputType> & Record<string, unknown>,
72 OutputType extends ShapeOf<InputType>,
73>(
74 conversions: Conversions<InputType, OutputType>,
75 input: Partial<InputType>,
76): Partial<OutputType> {
77 const c = conversions as Record<string, Conversion<InputType, OutputType>>
78
79 return Object.fromEntries(
80 Object.keys(input).map((k: string) => {
81 const value = input[k]
82 return [k, c[k]?.(value as any) ?? value]
83 }),
84 ) as OutputType
85}
86
87export type TrailBaseSyncMode = SyncMode
88
89/**
90 * Configuration interface for Trailbase Collection
91 */
92export interface TrailBaseCollectionConfig<
93 TItem extends ShapeOf<TRecord>,
94 TRecord extends ShapeOf<TItem> = TItem,
95 TKey extends string | number = string | number,
96> extends Omit<
97 BaseCollectionConfig<TItem, TKey>,
98 `onInsert` | `onUpdate` | `onDelete` | `syncMode`
99> {
100 /**
101 * Record API name
102 */
103 recordApi: RecordApi<TRecord>
104
105 /**
106 * The mode of sync to use for the collection.
107 * @default `eager`
108 */
109 syncMode?: TrailBaseSyncMode
110
111 parse: Conversions<TRecord, TItem>
112 serialize: Conversions<TItem, TRecord>
113}
114
115export type AwaitTxIdFn = (txId: string, timeout?: number) => Promise<boolean>
116
117export interface TrailBaseCollectionUtils extends UtilsRecord {
118 cancel: () => void
119}
120
121export function trailBaseCollectionOptions<
122 TItem extends ShapeOf<TRecord>,
123 TRecord extends ShapeOf<TItem> = TItem,
124 TKey extends string | number = string | number,
125>(
126 config: TrailBaseCollectionConfig<TItem, TRecord, TKey>,
127): CollectionConfig<TItem, TKey, never, TrailBaseCollectionUtils> & {
128 utils: TrailBaseCollectionUtils
129} {
130 const getKey = config.getKey
131
132 const parse = (record: TRecord) =>
133 convert<TRecord, TItem>(config.parse, record)
134 const serialUpd = (item: Partial<TItem>) =>
135 convertPartial<TItem, TRecord>(config.serialize, item)
136 const serialIns = (item: TItem) =>
137 convert<TItem, TRecord>(config.serialize, item)
138
139 const seenIds = new Store(new Map<string, number>())
140
141 const internalSyncMode = config.syncMode ?? `eager`
142 let fullSyncCompleted = false
143
144 const awaitIds = (
145 ids: Array<string>,
146 timeout: number = 120 * 1000,
147 ): Promise<void> => {
148 const completed = (value: Map<string, number>) =>
149 ids.every((id) => value.has(id))
150 if (completed(seenIds.state)) {
151 return Promise.resolve()
152 }
153
154 return new Promise<void>((resolve, reject) => {
155 const timeoutId = setTimeout(() => {
156 sub.unsubscribe()
157 reject(new TimeoutWaitingForIdsError(ids.toString()))
158 }, timeout)
159
160 const sub = seenIds.subscribe((value) => {
161 if (completed(value)) {
162 clearTimeout(timeoutId)
163 sub.unsubscribe()
164 resolve()
165 }
166 })
167 })
168 }
169
170 let eventReader: ReadableStreamDefaultReader<Event> | undefined
171 const cancelEventReader = () => {
172 if (eventReader) {
173 eventReader.cancel()
174 eventReader.releaseLock()
175 eventReader = undefined
176 }
177 }
178
179 type SyncParams = Parameters<SyncConfig<TItem, TKey>[`sync`]>[0]
180 const sync = {
181 sync: (params: SyncParams) => {
182 const { begin, write, commit, markReady } = params
183
184 // NOTE: We cache cursors from prior fetches. TanStack/db expects that
185 // cursors can be derived from a key, which is not true for TB, since
186 // cursors are encrypted. This is leaky and therefore not ideal.
187 const cursors = new Map<string | number, string>()
188
189 // Load (more) data.
190 async function load(opts: LoadSubsetOptions) {
191 const lastKey = opts.cursor?.lastKey
192 let cursor: string | undefined =
193 lastKey !== undefined ? cursors.get(lastKey) : undefined
194 let offset: number | undefined =
195 (opts.offset ?? 0) > 0 ? opts.offset : undefined
196
197 const order: Array<string> | undefined = buildOrder(opts)
198 const filters: Array<FilterOrComposite> | undefined = buildFilters(
199 opts,
200 config,
201 )
202
203 let remaining: number = opts.limit ?? Number.MAX_VALUE
204 if (remaining <= 0) {
205 return
206 }
207
208 while (true) {
209 const limit = Math.min(remaining, 256)
210 const response = await config.recordApi.list({
211 pagination: {
212 limit,
213 offset,
214 cursor,
215 },
216 order,
217 filters,
218 })
219
220 const length = response.records.length
221 if (length === 0) {
222 // Drained - read everything.
223 break
224 }
225
226 begin()
227
228 for (let i = 0; i < Math.min(length, remaining); ++i) {
229 write({
230 type: `insert`,
231 value: parse(response.records[i]!),
232 })
233 }
234
235 commit()
236
237 remaining -= length
238
239 // Drained or read enough.
240 if (length < limit || remaining <= 0) {
241 if (response.cursor) {
242 cursors.set(
243 getKey(parse(response.records.at(-1)!)),
244 response.cursor,
245 )
246 }
247 break
248 }
249
250 // Update params for next iteration.
251 if (offset !== undefined) {
252 offset += length
253 } else {
254 cursor = response.cursor
255 }
256 }
257 }
258
259 // Afterwards subscribe.
260 async function listen(reader: ReadableStreamDefaultReader<Event>) {
261 while (true) {
262 const { done, value: event } = await reader.read()
263
264 if (done || !event) {
265 reader.releaseLock()
266 eventReader = undefined
267 return
268 }
269
270 begin()
271 let value: TItem | undefined
272 if (`Insert` in event) {
273 value = parse(event.Insert as TRecord)
274 write({ type: `insert`, value })
275 } else if (`Delete` in event) {
276 value = parse(event.Delete as TRecord)
277 write({ type: `delete`, value })
278 } else if (`Update` in event) {
279 value = parse(event.Update as TRecord)
280 write({ type: `update`, value })
281 } else {
282 console.error(`Error: ${event.Error}`)
283 }
284 commit()
285
286 if (value) {
287 seenIds.setState((curr: Map<string, number>) => {
288 const newIds = new Map(curr)
289 newIds.set(String(getKey(value)), Date.now())
290 return newIds
291 })
292 }
293 }
294 }
295
296 async function start() {
297 const eventStream = await config.recordApi.subscribe(`*`)
298 const reader = (eventReader = eventStream.getReader())
299
300 // Start listening for subscriptions first. Otherwise, we'd risk a gap
301 // between the initial fetch and starting to listen.
302 listen(reader)
303
304 try {
305 // Eager mode: perform initial fetch to populate everything
306 if (internalSyncMode === `eager`) {
307 // Load everything on initial load.
308 await load({})
309 fullSyncCompleted = true
310 }
311 } catch (e) {
312 cancelEventReader()
313 throw e
314 } finally {
315 // Mark ready both if everything went well or if there's an error to
316 // avoid blocking apps waiting for `.preload()` to finish.
317 markReady()
318 }
319
320 // Lastly, start a periodic cleanup task that will be removed when the
321 // reader closes.
322 const periodicCleanupTask = setInterval(() => {
323 seenIds.setState((curr) => {
324 const now = Date.now()
325 let anyExpired = false
326
327 const notExpired = Array.from(curr.entries()).filter(([_, v]) => {
328 const expired = now - v > 300 * 1000
329 anyExpired = anyExpired || expired
330 return !expired
331 })
332
333 if (anyExpired) {
334 return new Map(notExpired)
335 }
336 return curr
337 })
338 }, 120 * 1000)
339
340 reader.closed.finally(() => clearInterval(periodicCleanupTask))
341 }
342
343 start()
344
345 // Eager mode doesn't need subset loading
346 if (internalSyncMode === `eager`) {
347 return
348 }
349
350 return {
351 loadSubset: load,
352 getSyncMetadata: () =>
353 ({
354 syncMode: internalSyncMode,
355 }) as const,
356 }
357 },
358 // Expose the getSyncMetadata function
359 getSyncMetadata: () =>
360 ({
361 syncMode: internalSyncMode,
362 fullSyncComplete: fullSyncCompleted,
363 }) as const,
364 }
365
366 return {
367 ...config,
368 sync,
369 getKey,
370 onInsert: async (
371 params: InsertMutationFnParams<TItem, TKey>,
372 ): Promise<Array<number | string>> => {
373 const ids = await config.recordApi.createBulk(
374 params.transaction.mutations.map((tx) => {
375 const { type, modified } = tx
376 if (type !== `insert`) {
377 throw new ExpectedInsertTypeError(type)
378 }
379 return serialIns(modified)
380 }),
381 )
382
383 // The optimistic mutation overlay is removed on return, so at this point
384 // we have to ensure that the new record was properly added to the local
385 // DB by the subscription.
386 await awaitIds(ids.map((id) => String(id)))
387
388 return ids
389 },
390 onUpdate: async (params: UpdateMutationFnParams<TItem, TKey>) => {
391 const ids: Array<string> = await Promise.all(
392 params.transaction.mutations.map(async (tx) => {
393 const { type, changes, key } = tx
394 if (type !== `update`) {
395 throw new ExpectedUpdateTypeError(type)
396 }
397
398 await config.recordApi.update(key, serialUpd(changes))
399
400 return String(key)
401 }),
402 )
403
404 // The optimistic mutation overlay is removed on return, so at this point
405 // we have to ensure that the new record was properly updated in the local
406 // DB by the subscription.
407 await awaitIds(ids)
408 },
409 onDelete: async (params: DeleteMutationFnParams<TItem, TKey>) => {
410 const ids: Array<string> = await Promise.all(
411 params.transaction.mutations.map(async (tx) => {
412 const { type, key } = tx
413 if (type !== `delete`) {
414 throw new ExpectedDeleteTypeError(type)
415 }
416
417 await config.recordApi.delete(key)
418 return String(key)
419 }),
420 )
421
422 // The optimistic mutation overlay is removed on return, so at this point
423 // we have to ensure that the new record was properly updated in the local
424 // DB by the subscription.
425 await awaitIds(ids)
426 },
427 utils: {
428 cancel: cancelEventReader,
429 },
430 }
431}
432
433function buildOrder(opts: LoadSubsetOptions): undefined | Array<string> {
434 return opts.orderBy
435 ?.map((o: OrderByClause) => {
436 switch (o.expression.type) {
437 case 'ref': {
438 const field = o.expression.path[0]
439 if (o.compareOptions.direction == 'asc') {
440 return `+${field}`
441 }
442 return `-${field}`
443 }
444 default: {
445 console.warn(
446 'Skipping unsupported order clause:',
447 JSON.stringify(o.expression),
448 )
449 return undefined
450 }
451 }
452 })
453 .filter((f: string | undefined) => f !== undefined)
454}
455
456function buildCompareOp(name: string): CompareOp | undefined {
457 switch (name) {
458 case 'eq':
459 return 'equal'
460 case 'ne':
461 return 'notEqual'
462 case 'gt':
463 return 'greaterThan'
464 case 'gte':
465 return 'greaterThanEqual'
466 case 'lt':
467 return 'lessThan'
468 case 'lte':
469 return 'lessThanEqual'
470 default:
471 return undefined
472 }
473}
474
475function buildFilters<
476 TItem extends ShapeOf<TRecord>,
477 TRecord extends ShapeOf<TItem> = TItem,
478 TKey extends string | number = string | number,
479>(
480 opts: LoadSubsetOptions,
481 config: TrailBaseCollectionConfig<TItem, TRecord, TKey>,
482): undefined | Array<FilterOrComposite> {
483 const where = opts.where
484 if (where === undefined) {
485 return undefined
486 }
487
488 function serializeValue<T = any>(column: string, value: T): string {
489 const conv = (config.serialize as any)[column]
490 if (conv) {
491 return `${conv(value)}`
492 }
493
494 if (typeof value === 'boolean') {
495 return value ? '1' : '0'
496 }
497
498 return `${value}`
499 }
500
501 switch (where.type) {
502 case 'func': {
503 const field = where.args[0]
504 const val = where.args[1]
505
506 const op = buildCompareOp(where.name)
507 if (op === undefined) {
508 break
509 }
510
511 if (field?.type === 'ref' && val?.type === 'val') {
512 const column = field.path.at(0)
513 if (column) {
514 const f = [
515 {
516 column: field.path.at(0) ?? '',
517 op,
518 value: serializeValue(column, val.value),
519 },
520 ]
521
522 return f
523 }
524 }
525 break
526 }
527 case 'ref':
528 case 'val':
529 break
530 }
531
532 console.warn('where clause which is not (yet) supported', opts.where)
533
534 return undefined
535}