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 { Event, RecordApi } from "trailbase"
10
11import type {
12 CollectionConfig,
13 DeleteMutationFnParams,
14 InsertMutationFnParams,
15 SyncConfig,
16 UpdateMutationFnParams,
17 UtilsRecord,
18} from "@tanstack/db"
19
20type ShapeOf<T> = Record<keyof T, unknown>
21type Conversion<I, O> = (value: I) => O
22
23type OptionalConversions<
24 InputType extends ShapeOf<OutputType>,
25 OutputType extends ShapeOf<InputType>,
26> = {
27 // Excludes all keys that require a conversation.
28 [K in keyof InputType as InputType[K] extends OutputType[K]
29 ? K
30 : never]?: Conversion<InputType[K], OutputType[K]>
31}
32
33type RequiredConversions<
34 InputType extends ShapeOf<OutputType>,
35 OutputType extends ShapeOf<InputType>,
36> = {
37 // Excludes all keys that do not strictly require a conversation.
38 [K in keyof InputType as InputType[K] extends OutputType[K]
39 ? never
40 : K]: Conversion<InputType[K], OutputType[K]>
41}
42
43type Conversions<
44 InputType extends ShapeOf<OutputType>,
45 OutputType extends ShapeOf<InputType>,
46> = OptionalConversions<InputType, OutputType> &
47 RequiredConversions<InputType, OutputType>
48
49function convert<
50 InputType extends ShapeOf<OutputType> & Record<string, unknown>,
51 OutputType extends ShapeOf<InputType>,
52>(
53 conversions: Conversions<InputType, OutputType>,
54 input: InputType
55): OutputType {
56 const c = conversions as Record<string, Conversion<InputType, OutputType>>
57
58 return Object.fromEntries(
59 Object.keys(input).map((k: string) => {
60 const value = input[k]
61 return [k, c[k]?.(value as any) ?? value]
62 })
63 ) as OutputType
64}
65
66function convertPartial<
67 InputType extends ShapeOf<OutputType> & Record<string, unknown>,
68 OutputType extends ShapeOf<InputType>,
69>(
70 conversions: Conversions<InputType, OutputType>,
71 input: Partial<InputType>
72): Partial<OutputType> {
73 const c = conversions as Record<string, Conversion<InputType, OutputType>>
74
75 return Object.fromEntries(
76 Object.keys(input).map((k: string) => {
77 const value = input[k]
78 return [k, c[k]?.(value as any) ?? value]
79 })
80 ) as OutputType
81}
82
83/**
84 * Configuration interface for Trailbase Collection
85 */
86export interface TrailBaseCollectionConfig<
87 TItem extends ShapeOf<TRecord>,
88 TRecord extends ShapeOf<TItem> = TItem,
89 TKey extends string | number = string | number,
90> extends Omit<
91 CollectionConfig<TItem, TKey>,
92 `sync` | `onInsert` | `onUpdate` | `onDelete`
93 > {
94 /**
95 * Record API name
96 */
97 recordApi: RecordApi<TRecord>
98
99 parse: Conversions<TRecord, TItem>
100 serialize: Conversions<TItem, TRecord>
101}
102
103export type AwaitTxIdFn = (txId: string, timeout?: number) => Promise<boolean>
104
105export interface TrailBaseCollectionUtils extends UtilsRecord {
106 cancel: () => void
107}
108
109export function trailBaseCollectionOptions<
110 TItem extends ShapeOf<TRecord>,
111 TRecord extends ShapeOf<TItem> = TItem,
112 TKey extends string | number = string | number,
113>(
114 config: TrailBaseCollectionConfig<TItem, TRecord, TKey>
115): CollectionConfig<TItem, TKey> & { utils: TrailBaseCollectionUtils } {
116 const getKey = config.getKey
117
118 const parse = (record: TRecord) =>
119 convert<TRecord, TItem>(config.parse, record)
120 const serialUpd = (item: Partial<TItem>) =>
121 convertPartial<TItem, TRecord>(config.serialize, item)
122 const serialIns = (item: TItem) =>
123 convert<TItem, TRecord>(config.serialize, item)
124
125 const seenIds = new Store(new Map<string, number>())
126
127 const awaitIds = (
128 ids: Array<string>,
129 timeout: number = 120 * 1000
130 ): Promise<void> => {
131 const completed = (value: Map<string, number>) =>
132 ids.every((id) => value.has(id))
133 if (completed(seenIds.state)) {
134 return Promise.resolve()
135 }
136
137 return new Promise<void>((resolve, reject) => {
138 const timeoutId = setTimeout(() => {
139 unsubscribe()
140 reject(new TimeoutWaitingForIdsError(ids.toString()))
141 }, timeout)
142
143 const unsubscribe = seenIds.subscribe((value) => {
144 if (completed(value.currentVal)) {
145 clearTimeout(timeoutId)
146 unsubscribe()
147 resolve()
148 }
149 })
150 })
151 }
152
153 let eventReader: ReadableStreamDefaultReader<Event> | undefined
154 const cancelEventReader = () => {
155 if (eventReader) {
156 eventReader.cancel()
157 eventReader.releaseLock()
158 eventReader = undefined
159 }
160 }
161
162 type SyncParams = Parameters<SyncConfig<TItem, TKey>[`sync`]>[0]
163 const sync = {
164 sync: (params: SyncParams) => {
165 const { begin, write, commit, markReady } = params
166
167 // Initial fetch.
168 async function initialFetch() {
169 const limit = 256
170 let response = await config.recordApi.list({
171 pagination: {
172 limit,
173 },
174 })
175 let cursor = response.cursor
176 let got = 0
177
178 begin()
179
180 while (true) {
181 const length = response.records.length
182 if (length === 0) break
183
184 got = got + length
185 for (const item of response.records) {
186 write({
187 type: `insert`,
188 value: parse(item),
189 })
190 }
191
192 if (length < limit) break
193
194 response = await config.recordApi.list({
195 pagination: {
196 limit,
197 cursor,
198 offset: cursor === undefined ? got : undefined,
199 },
200 })
201 cursor = response.cursor
202 }
203
204 commit()
205 }
206
207 // Afterwards subscribe.
208 async function listen(reader: ReadableStreamDefaultReader<Event>) {
209 while (true) {
210 const { done, value: event } = await reader.read()
211
212 if (done || !event) {
213 reader.releaseLock()
214 eventReader = undefined
215 return
216 }
217
218 begin()
219 let value: TItem | undefined
220 if (`Insert` in event) {
221 value = parse(event.Insert as TRecord)
222 write({ type: `insert`, value })
223 } else if (`Delete` in event) {
224 value = parse(event.Delete as TRecord)
225 write({ type: `delete`, value })
226 } else if (`Update` in event) {
227 value = parse(event.Update as TRecord)
228 write({ type: `update`, value })
229 } else {
230 console.error(`Error: ${event.Error}`)
231 }
232 commit()
233
234 if (value) {
235 seenIds.setState((curr: Map<string, number>) => {
236 const newIds = new Map(curr)
237 newIds.set(String(getKey(value)), Date.now())
238 return newIds
239 })
240 }
241 }
242 }
243
244 async function start() {
245 const eventStream = await config.recordApi.subscribe(`*`)
246 const reader = (eventReader = eventStream.getReader())
247
248 // Start listening for subscriptions first. Otherwise, we'd risk a gap
249 // between the initial fetch and starting to listen.
250 listen(reader)
251
252 try {
253 await initialFetch()
254 } catch (e) {
255 cancelEventReader()
256 throw e
257 } finally {
258 // Mark ready both if everything went well or if there's an error to
259 // avoid blocking apps waiting for `.preload()` to finish.
260 markReady()
261 }
262
263 // Lastly, start a periodic cleanup task that will be removed when the
264 // reader closes.
265 const periodicCleanupTask = setInterval(() => {
266 seenIds.setState((curr) => {
267 const now = Date.now()
268 let anyExpired = false
269
270 const notExpired = Array.from(curr.entries()).filter(([_, v]) => {
271 const expired = now - v > 300 * 1000
272 anyExpired = anyExpired || expired
273 return !expired
274 })
275
276 if (anyExpired) {
277 return new Map(notExpired)
278 }
279 return curr
280 })
281 }, 120 * 1000)
282
283 reader.closed.finally(() => clearInterval(periodicCleanupTask))
284 }
285
286 start()
287 },
288 // Expose the getSyncMetadata function
289 getSyncMetadata: undefined,
290 }
291
292 return {
293 ...config,
294 sync,
295 getKey,
296 onInsert: async (
297 params: InsertMutationFnParams<TItem, TKey>
298 ): Promise<Array<number | string>> => {
299 const ids = await config.recordApi.createBulk(
300 params.transaction.mutations.map((tx) => {
301 const { type, modified } = tx
302 if (type !== `insert`) {
303 throw new ExpectedInsertTypeError(type)
304 }
305 return serialIns(modified)
306 })
307 )
308
309 // The optimistic mutation overlay is removed on return, so at this point
310 // we have to ensure that the new record was properly added to the local
311 // DB by the subscription.
312 await awaitIds(ids.map((id) => String(id)))
313
314 return ids
315 },
316 onUpdate: async (params: UpdateMutationFnParams<TItem, TKey>) => {
317 const ids: Array<string> = await Promise.all(
318 params.transaction.mutations.map(async (tx) => {
319 const { type, changes, key } = tx
320 if (type !== `update`) {
321 throw new ExpectedUpdateTypeError(type)
322 }
323
324 await config.recordApi.update(key, serialUpd(changes))
325
326 return String(key)
327 })
328 )
329
330 // The optimistic mutation overlay is removed on return, so at this point
331 // we have to ensure that the new record was properly updated in the local
332 // DB by the subscription.
333 await awaitIds(ids)
334 },
335 onDelete: async (params: DeleteMutationFnParams<TItem, TKey>) => {
336 const ids: Array<string> = await Promise.all(
337 params.transaction.mutations.map(async (tx) => {
338 const { type, key } = tx
339 if (type !== `delete`) {
340 throw new ExpectedDeleteTypeError(type)
341 }
342
343 await config.recordApi.delete(key)
344 return String(key)
345 })
346 )
347
348 // The optimistic mutation overlay is removed on return, so at this point
349 // we have to ensure that the new record was properly updated in the local
350 // DB by the subscription.
351 await awaitIds(ids)
352 },
353 utils: {
354 cancel: cancelEventReader,
355 },
356 }
357}