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