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