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

rxdb.ts

306 lines9.1 KB

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