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

trailbase.ts

358 lines10.1 KB

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