Open History to see the last commit
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
78}
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
94}
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
103}
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, markError, 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 begin()
141
142 while (!initialFetchComplete) {
143 let query: FilledMangoQuery<Row>
144 if (cursor) {
145 query = {
146 selector: {
147 $or: [
148 { '_meta.lwt': { $gt: cursor._meta.lwt } },
149 {
150 '_meta.lwt': cursor._meta.lwt,
151 [primaryPath]: {
152 $gt: getKey(cursor),
153 },
154 },
155 ],
156 _deleted: false,
157 },
158 sort: [{ '_meta.lwt': `asc` }, { [primaryPath]: `asc` }],
159 limit: syncBatchSize,
160 skip: 0,
161 }
162 } else {
163 query = {
164 selector: { _deleted: false },
165 sort: [{ '_meta.lwt': `asc` }, { [primaryPath]: `asc` }],
166 limit: syncBatchSize,
167 skip: 0,
168 }
169 }
170
171 /**
172 * Instead of doing a RxCollection.query(),
173 * we directly query the storage engine of the RxCollection so we do not use the
174 * RxCollection document cache because it likely wont be used anyway
175 * since most queries will run directly on the tanstack-db side.
176 */
177 const preparedQuery = prepareQuery<Row>(
178 rxCollection.storageInstance.schema,
179 query,
180 )
181 const result = await rxCollection.storageInstance.query(preparedQuery)
182 const docs = result.documents
183
184 cursor = lastOfArray(docs)
185 if (docs.length === 0) {
186 initialFetchComplete = true
187 break
188 }
189
190 docs.forEach((d) => {
191 write({
192 type: `insert`,
193 value: stripRxdbFields(clone(d)),
194 })
195 })
196 }
197 await commit()
198 }
199
200 type WriteMessage = Parameters<typeof write>[0]
201 const buffer: Array<WriteMessage> = []
202 let buffering = true
203 const queue = (msg: WriteMessage) => {
204 if (buffering) {
205 buffer.push(msg)
206 return
207 }
208 begin()
209 write(msg)
210 commit()
211 }
212
213 let sub: Subscription | undefined
214 function stopOngoingFetch() {
215 buffer.length = 0
216 if (!sub) return
217 getFromMapOrCreate(
218 OPEN_RXDB_SUBSCRIPTIONS,
219 rxCollection,
220 () => new Set(),
221 ).delete(sub)
222 sub.unsubscribe()
223 sub = undefined
224 }
225
226 function startOngoingFetch() {
227 // Subscribe early and buffer live changes during initial load and ongoing
228 sub = rxCollection.$.subscribe((ev) => {
229 const cur: Row = stripRxdbFields(clone(ev.documentData as Row))
230 switch (ev.operation) {
231 case `INSERT`:
232 queue({ type: `insert`, value: cur })
233 break
234 case `UPDATE`:
235 queue({ type: `update`, value: cur })
236 break
237 case `DELETE`:
238 queue({ type: `delete`, value: cur })
239 break
240 }
241 })
242
243 const subs = getFromMapOrCreate(
244 OPEN_RXDB_SUBSCRIPTIONS,
245 rxCollection,
246 () => new Set(),
247 )
248 subs.add(sub)
249 }
250
251 async function start() {
252 const isCleanedUp = () => collection.status === `cleaned-up`
253
254 startOngoingFetch()
255 await initialFetch()
256 if (isCleanedUp()) {
257 return
258 }
259
260 // Take one finite snapshot of changes observed during the initial
261 // fetch, then route newer events through the normal live path. The
262 // core transaction queue preserves their order without letting a
263 // continuous event stream postpone readiness forever.
264 const pending = buffer.splice(0)
265 buffering = false
266 if (pending.length > 0) {
267 begin()
268 for (const msg of pending) write(msg)
269 await commit()
270 if (isCleanedUp()) {
271 return
272 }
273 }
274
275 if (!isCleanedUp()) {
276 markReady()
277 }
278 }
279
280 void start().catch((error: unknown) => {
281 stopOngoingFetch()
282 if (collection.status === `loading`) {
283 markError(error)
284 }
285 })
286
287 return stopOngoingFetch
288 },
289 // Expose the getSyncMetadata function
290 getSyncMetadata: undefined,
291 }
292
293 const collectionConfig: CollectionConfig<Row, string> = {
294 ...restConfig,
295 getKey,
296 sync,
297 onInsert: async (params) => {
298 debug(`insert`, params)
299 const newItems = params.transaction.mutations.map((m) => m.modified)
300 return rxCollection.bulkUpsert(newItems).then((result) => {
301 if (result.error.length > 0) {
302 throw rxStorageWriteErrorToRxError(ensureNotFalsy(result.error[0]))
303 }
304 return result.success
305 })
306 },
307 onUpdate: async (params) => {
308 debug(`update`, params)
309 const mutations = params.transaction.mutations.filter(
310 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
311 (m) => m.type === `update`,
312 )
313
314 for (const mutation of mutations) {
315 const newValue = stripRxdbFields(mutation.modified)
316 const id = getKey(newValue)
317 const doc = await rxCollection.findOne(id).exec()
318 if (!doc) {
319 continue
320 }
321 await doc.incrementalPatch(newValue)
322 }
323 },
324 onDelete: async (params) => {
325 debug(`delete`, params)
326 const mutations = params.transaction.mutations.filter(
327 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
328 (m) => m.type === `delete`,
329 )
330 const ids = mutations.map((mutation) => getKey(mutation.original))
331 return rxCollection.bulkRemove(ids).then((result) => {
332 if (result.error.length > 0) {
333 throw result.error
334 }
335 return result.success
336 })
337 },
338 }
339 return withCollectionConfigFactory(collectionConfig, () =>
340 rxdbCollectionOptions(config),
341 )
342}