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

rxdb.ts

350 lines10.9 KB

1import {
2 clone,
3 ensureNotFalsy,
4 getFromMapOrCreate,
5 lastOfArray,
6 prepareQuery,
7 rxStorageWriteErrorToRxError,
8} from 'rxdb/plugins/core'
9import DebugModule from 'debug'
10import { withCollectionConfigFactory } from '@tanstack/db'
11import { stripRxdbFields } from './helper'
12import type {
13 FilledMangoQuery,
14 RxCollection,
15 RxDocumentData,
16} from 'rxdb/plugins/core'
17import type { Subscription } from 'rxjs'
18​
19import type {
20 BaseCollectionConfig,
21 CollectionConfig,
22 InferSchemaOutput,
23 SyncConfig,
24} from '@tanstack/db'
25import type { StandardSchemaV1 } from '@standard-schema/spec'
26​
27const debug = DebugModule.debug(`ts/db:rxdb`)
28​
29/**
30 * Used in tests to ensure proper cleanup
31 */
32export const OPEN_RXDB_SUBSCRIPTIONS = new WeakMap<
33 RxCollection,
34 Set<Subscription>
35>()
36​
37/**
38 * Configuration interface for RxDB collection options
39 * @template T - The explicit type of items in the collection (highest priority). Use the document type of your RxCollection here.
40 * @template TSchema - The schema type for validation and type inference (second priority)
41 *
42 * @remarks
43 * Type resolution follows a priority order:
44 * 1. If you provide an explicit type via generic parameter, it will be used
45 * 2. If no explicit type is provided but a schema is, the schema's output type will be inferred
46 *
47 * You should provide EITHER an explicit type OR a schema, but not both, as they would conflict.
48 * Notice that primary keys in RxDB must always be a string.
49 */
50export type RxDBCollectionConfig<
51 T extends object = Record<string, unknown>,
52 TSchema extends StandardSchemaV1 = never,
53> = Omit<
54 BaseCollectionConfig<T, string, TSchema>,
55 `onInsert` | `onUpdate` | `onDelete` | `getKey`
56> & {
57 /**
58 * The RxCollection from a RxDB Database instance.
59 */
60 rxCollection: RxCollection<T, unknown, unknown, unknown>
61​
62 /**
63 * The maximum number of documents to read from the RxDB collection
64 * in a single batch during the initial sync between RxDB and the
65 * in-memory TanStack DB collection.
66 *
67 * @remarks
68 * - Defaults to `1000` if not specified.
69 * - Larger values reduce the number of round trips to the storage
70 * engine but increase memory usage per batch.
71 * - Smaller values may lower memory usage and allow earlier
72 * streaming of initial results, at the cost of more query calls.
73 *
74 * Adjust this depending on your expected collection size and
75 * performance characteristics of the chosen RxDB storage adapter.
76 */
77 syncBatchSize?: number
79​
80/**
81 * Creates RxDB collection options for use with a standard Collection
82 *
83 * @template TExplicit - The explicit type of items in the collection (highest priority)
84 * @template TSchema - The schema type for validation and type inference (second priority)
85 * @param config - Configuration options for the RxDB collection
86 * @returns Collection options with utilities
87 */
88​
89// Overload for when schema is provided
90export function rxdbCollectionOptions<T extends StandardSchemaV1>(
91 config: RxDBCollectionConfig<InferSchemaOutput<T>, T>,
92): CollectionConfig<InferSchemaOutput<T>, string, T> & {
93 schema: T
95​
96// Overload for when no schema is provided
97export function rxdbCollectionOptions<T extends object>(
98 config: RxDBCollectionConfig<T> & {
99 schema?: never // prohibit schema
100 },
101): CollectionConfig<T, string> & {
102 schema?: never // no schema in the result
104​
105export function rxdbCollectionOptions(
106 config: RxDBCollectionConfig<any, any>,
107): CollectionConfig<any, string, any> {
108 type Row = Record<string, unknown>
109 type Key = string // because RxDB primary keys must be strings
110​
111 const { rxCollection, syncBatchSize: _syncBatchSize, ...restConfig } = config
112​
113 // "getKey"
114 const primaryPath = rxCollection.schema.primaryPath
115 function getKey(item: Record<string, unknown>): string {
116 const key: string = item[primaryPath] as string
117 return key
118 }
119​
120 /**
121 * "sync"
122 * Notice that this describes the Sync between the local RxDB collection
123 * and the in-memory tanstack-db collection.
124 * It is not about sync between a client and a server!
125 */
126 type SyncParams = Parameters<SyncConfig<Row, string>[`sync`]>[0]
127 const sync: SyncConfig<Row, Key> = {
128 sync: (params: SyncParams) => {
129 const { begin, write, commit, markReady, fail, collection } = params
130​
131 let initialFetchComplete = false
132 async function initialFetch() {
133 /**
134 * RxDB stores a last-write-time
135 * which can be used to "sort" document writes,
136 * so for initial sync we iterate over that.
137 */
138 let cursor: RxDocumentData<Row> | undefined = undefined
139 const syncBatchSize = config.syncBatchSize ? config.syncBatchSize : 1000
140 // The initial fetch reads every document. When the Collection holds
141 // rows, such as a reload's kept rows, it is a snapshot that replaces
142 // them, so a row RxDB no longer has goes.
143 begin({
144 snapshot: !collection._state.acceptedSyncedEntries().next().done,
145 })
146​
147 while (!initialFetchComplete) {
148 let query: FilledMangoQuery<Row>
149 if (cursor) {
150 query = {
151 selector: {
152 $or: [
153 { '_meta.lwt': { $gt: cursor._meta.lwt } },
154 {
155 '_meta.lwt': cursor._meta.lwt,
156 [primaryPath]: {
157 $gt: getKey(cursor),
158 },
159 },
160 ],
161 _deleted: false,
162 },
163 sort: [{ '_meta.lwt': `asc` }, { [primaryPath]: `asc` }],
164 limit: syncBatchSize,
165 skip: 0,
166 }
167 } else {
168 query = {
169 selector: { _deleted: false },
170 sort: [{ '_meta.lwt': `asc` }, { [primaryPath]: `asc` }],
171 limit: syncBatchSize,
172 skip: 0,
173 }
174 }
175​
176 /**
177 * Instead of doing a RxCollection.query(),
178 * we directly query the storage engine of the RxCollection so we do not use the
179 * RxCollection document cache because it likely wont be used anyway
180 * since most queries will run directly on the tanstack-db side.
181 */
182 const preparedQuery = prepareQuery<Row>(
183 rxCollection.storageInstance.schema,
184 query,
185 )
186 const result = await rxCollection.storageInstance.query(preparedQuery)
187 const docs = result.documents
188​
189 cursor = lastOfArray(docs)
190 if (docs.length === 0) {
191 initialFetchComplete = true
192 break
193 }
194​
195 docs.forEach((d) => {
196 write({
197 type: `insert`,
198 value: stripRxdbFields(clone(d)),
199 })
200 })
201 }
202 await commit()
203 }
204​
205 type WriteMessage = Parameters<typeof write>[0]
206 const buffer: Array<WriteMessage> = []
207 let buffering = true
208 const queue = (msg: WriteMessage) => {
209 if (buffering) {
210 buffer.push(msg)
211 return
212 }
213 begin()
214 write(msg)
215 commit()
216 }
217​
218 let sub: Subscription | undefined
219 function stopOngoingFetch() {
220 buffer.length = 0
221 if (!sub) return
222 getFromMapOrCreate(
223 OPEN_RXDB_SUBSCRIPTIONS,
224 rxCollection,
225 () => new Set(),
226 ).delete(sub)
227 sub.unsubscribe()
228 sub = undefined
229 }
230​
231 function startOngoingFetch() {
232 // Subscribe early and buffer live changes during initial load and ongoing
233 sub = rxCollection.$.subscribe({
234 next: (ev) => {
235 const cur: Row = stripRxdbFields(clone(ev.documentData as Row))
236 switch (ev.operation) {
237 case `INSERT`:
238 queue({ type: `insert`, value: cur })
239 break
240 case `UPDATE`:
241 queue({ type: `update`, value: cur })
242 break
243 case `DELETE`:
244 queue({ type: `delete`, value: cur })
245 break
246 }
247 },
248 // An errored stream ends, so later writes would never arrive.
249 error: stop,
250 })
251​
252 const subs = getFromMapOrCreate(
253 OPEN_RXDB_SUBSCRIPTIONS,
254 rxCollection,
255 () => new Set(),
256 )
257 subs.add(sub)
258 }
259​
260 async function start() {
261 const isCleanedUp = () => collection.status === `cleaned-up`
262​
263 startOngoingFetch()
264 await initialFetch()
265 if (isCleanedUp()) {
266 return
267 }
268​
269 // Take one finite snapshot of changes observed during the initial
270 // fetch, then route newer events through the normal live path. The
271 // core transaction queue preserves their order without letting a
272 // continuous event stream postpone readiness forever.
273 const pending = buffer.splice(0)
274 buffering = false
275 if (pending.length > 0) {
276 begin()
277 for (const msg of pending) write(msg)
278 await commit()
279 if (isCleanedUp()) {
280 return
281 }
282 }
283​
284 // After this run's fail(), markReady() does nothing.
285 markReady()
286 }
287​
288 // Core ignores a later fail() in the same run.
289 function stop(error: unknown) {
290 stopOngoingFetch()
291 fail(error)
292 }
293 void start().catch(stop)
294​
295 return stopOngoingFetch
296 },
297 // Expose the getSyncMetadata function
298 getSyncMetadata: undefined,
299 }
300​
301 const collectionConfig: CollectionConfig<Row, string> = {
302 ...restConfig,
303 getKey,
304 sync,
305 onInsert: async (params) => {
306 debug(`insert`, params)
307 const newItems = params.transaction.mutations.map((m) => m.modified)
308 return rxCollection.bulkUpsert(newItems).then((result) => {
309 if (result.error.length > 0) {
310 throw rxStorageWriteErrorToRxError(ensureNotFalsy(result.error[0]))
311 }
312 return result.success
313 })
314 },
315 onUpdate: async (params) => {
316 debug(`update`, params)
317 const mutations = params.transaction.mutations.filter(
318 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
319 (m) => m.type === `update`,
320 )
321​
322 for (const mutation of mutations) {
323 const newValue = stripRxdbFields(mutation.modified)
324 const id = getKey(newValue)
325 const doc = await rxCollection.findOne(id).exec()
326 if (!doc) {
327 continue
328 }
329 await doc.incrementalPatch(newValue)
330 }
331 },
332 onDelete: async (params) => {
333 debug(`delete`, params)
334 const mutations = params.transaction.mutations.filter(
335 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
336 (m) => m.type === `delete`,
337 )
338 const ids = mutations.map((mutation) => getKey(mutation.original))
339 return rxCollection.bulkRemove(ids).then((result) => {
340 if (result.error.length > 0) {
341 throw result.error
342 }
343 return result.success
344 })
345 },
346 }
347 return withCollectionConfigFactory(collectionConfig, () =>
348 rxdbCollectionOptions(config),
349 )