Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { createCollection, createTransaction } from '@tanstack/db'
3import {
4 addRxPlugin,
5 createRxDatabase,
6 getFromMapOrCreate,
7} from 'rxdb/plugins/core'
8import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode'
9import { getRxStorageMemory } from 'rxdb/plugins/storage-memory'
10import { wrappedValidateAjvStorage } from 'rxdb/plugins/validate-ajv'
11import { stripVirtualProps } from '../../db/tests/utils'
12import { OPEN_RXDB_SUBSCRIPTIONS, rxdbCollectionOptions } from '../src/rxdb'
13import type { RxCollection } from 'rxdb/plugins/core'
14import type { RxDBCollectionConfig } from '../src/rxdb'
15
16type TestDocType = {
17 id: string
18 name: string
19}
20type RxCollections = { test: RxCollection<TestDocType> }
21
22// Helper to advance timers and allow microtasks to flush
23const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0))
24
25function createDeferred<T>() {
26 let resolve!: (value: T) => void
27 const promise = new Promise<T>((resolvePromise) => {
28 resolve = resolvePromise
29 })
30 return { promise, resolve }
31}
32
33describe(`RxDB Integration`, () => {
34 addRxPlugin(RxDBDevModePlugin)
35
36 let dbNameId = 0
37 function getTestData(amount: number): Array<TestDocType> {
38 return new Array(amount).fill(0).map((_v, i) => {
39 return {
40 id: i + 1 + ``,
41 name: `Item ` + (i + 1),
42 }
43 })
44 }
45
46 async function getDatababase(
47 initialDocs: Array<TestDocType> = [],
48 dbId = dbNameId++,
49 ) {
50 const db = await createRxDatabase<RxCollections, unknown, unknown, unknown>(
51 {
52 name: `my-rxdb-` + dbId,
53 ignoreDuplicate: true,
54 storage: wrappedValidateAjvStorage({
55 storage: getRxStorageMemory(),
56 }),
57 },
58 )
59 const collections = await db.addCollections<RxCollections>({
60 test: {
61 schema: {
62 version: 0,
63 type: `object`,
64 primaryKey: `id`,
65 properties: {
66 id: {
67 type: `string`,
68 maxLength: 100,
69 },
70 name: {
71 type: `string`,
72 maxLength: 9,
73 },
74 },
75 },
76 },
77 })
78 const rxCollection: RxCollection<TestDocType> = collections.test
79 if (initialDocs.length > 0) {
80 const insertResult = await rxCollection.bulkInsert(initialDocs)
81 expect(insertResult.error.length).toBe(0)
82 }
83 return db
84 }
85
86 async function createTestState(
87 initialDocs: Array<TestDocType> = [],
88 config: Partial<RxDBCollectionConfig<TestDocType, any>> = {},
89 ) {
90 const db = await getDatababase(initialDocs, dbNameId++)
91 const rxCollection: RxCollection<TestDocType> = db.test
92 const options = rxdbCollectionOptions({
93 rxCollection: rxCollection,
94 startSync: true,
95 /**
96 * In tests we use a small batch size
97 * to ensure iteration works.
98 */
99 syncBatchSize: 10,
100 ...config,
101 })
102
103 const collection = createCollection(options)
104 await collection.stateWhenReady()
105
106 return {
107 collection,
108 rxCollection,
109 db,
110 }
111 }
112
113 describe(`sync`, () => {
114 it(`reports an initial storage query failure`, async () => {
115 const db = await getDatababase()
116 const rxCollection: RxCollection<TestDocType> = db.test
117 const initialError = new Error(`initial RxDB query failed`)
118 const query = vi
119 .spyOn(rxCollection.storageInstance, `query`)
120 .mockRejectedValueOnce(initialError)
121 const collection = createCollection(
122 rxdbCollectionOptions({
123 rxCollection,
124 startSync: true,
125 syncBatchSize: 10,
126 }),
127 )
128
129 try {
130 await expect(collection.preload()).rejects.toBe(initialError)
131 expect(collection.status).toBe(`error`)
132 expect(OPEN_RXDB_SUBSCRIPTIONS.get(rxCollection)?.size ?? 0).toBe(0)
133
134 await rxCollection.insert({ id: `after-failure`, name: `failed` })
135 await flushPromises()
136 expect(OPEN_RXDB_SUBSCRIPTIONS.get(rxCollection)?.size ?? 0).toBe(0)
137 expect(collection.has(`after-failure`)).toBe(false)
138 } finally {
139 query.mockRestore()
140 await collection.cleanup()
141 await db.remove()
142 }
143 })
144
145 it(`marks initial sync ready only after its rows are applied`, async () => {
146 const db = await getDatababase([{ id: `server`, name: `Server` }])
147 const rxCollection: RxCollection<TestDocType> = db.test
148 const releaseInitialQuery = createDeferred<void>()
149 const initialQueryStarted = createDeferred<void>()
150 const storageQuery = rxCollection.storageInstance.query.bind(
151 rxCollection.storageInstance,
152 )
153 const query = vi
154 .spyOn(rxCollection.storageInstance, `query`)
155 .mockImplementationOnce(async (preparedQuery) => {
156 const result = await storageQuery(preparedQuery)
157 initialQueryStarted.resolve()
158 await releaseInitialQuery.promise
159 return result
160 })
161 const collection = createCollection(
162 rxdbCollectionOptions({
163 rxCollection,
164 startSync: true,
165 syncBatchSize: 10,
166 }),
167 )
168 const persistence = createDeferred<void>()
169 const transaction = createTransaction({
170 mutationFn: () => persistence.promise,
171 })
172
173 try {
174 await initialQueryStarted.promise
175 transaction.mutate(() =>
176 collection.insert({ id: `local`, name: `Local` }),
177 )
178 const buffered = await rxCollection.insert({
179 id: `buffered`,
180 name: `Buffered`,
181 })
182 releaseInitialQuery.resolve()
183
184 const ready = collection.preload()
185 await flushPromises()
186
187 // The initial receipt is still parked. A later live change for the
188 // same row must not overtake the older buffered insert.
189 await buffered.getLatest().patch({ name: `Newest` })
190 await flushPromises()
191
192 expect(collection.status).toBe(`loading`)
193 expect(collection.get(`server`)).toBeUndefined()
194 expect(collection.get(`buffered`)).toBeUndefined()
195
196 persistence.resolve()
197 await transaction.isPersisted.promise
198 await ready
199
200 expect(collection.get(`server`)).toEqual(
201 expect.objectContaining({ id: `server`, name: `Server` }),
202 )
203 expect(collection.get(`buffered`)).toEqual(
204 expect.objectContaining({ id: `buffered`, name: `Newest` }),
205 )
206 expect(collection.status).toBe(`ready`)
207 } finally {
208 releaseInitialQuery.resolve()
209 persistence.resolve()
210 await transaction.isPersisted.promise.catch(() => undefined)
211 query.mockRestore()
212 await collection.cleanup()
213 await db.remove()
214 }
215 })
216
217 it(`does not let later live traffic extend the startup readiness boundary`, async () => {
218 const db = await getDatababase()
219 const rxCollection: RxCollection<TestDocType> = db.test
220 const initialQueryStarted = createDeferred<void>()
221 const releaseInitialQuery = createDeferred<void>()
222 const bufferedApplied = createDeferred<void>()
223 const laterLiveApplied = createDeferred<void>()
224 const storageQuery = rxCollection.storageInstance.query.bind(
225 rxCollection.storageInstance,
226 )
227 const query = vi
228 .spyOn(rxCollection.storageInstance, `query`)
229 .mockImplementationOnce(async (preparedQuery) => {
230 const result = await storageQuery(preparedQuery)
231 initialQueryStarted.resolve()
232 await releaseInitialQuery.promise
233 return result
234 })
235 const options = rxdbCollectionOptions({ rxCollection })
236 const begin = vi.fn()
237 const write = vi.fn()
238 const commit = vi
239 .fn()
240 .mockReturnValueOnce(true)
241 .mockReturnValueOnce(bufferedApplied.promise)
242 .mockReturnValueOnce(laterLiveApplied.promise)
243 const markReady = vi.fn()
244 const markError = vi.fn()
245 const cleanup = options.sync.sync({
246 begin,
247 write,
248 commit,
249 markReady,
250 markError,
251 collection: { status: `loading` },
252 } as never)
253
254 try {
255 await initialQueryStarted.promise
256 await rxCollection.insert({ id: `buffered`, name: `Buffered` })
257 releaseInitialQuery.resolve()
258 await vi.waitFor(() => expect(commit).toHaveBeenCalledTimes(2))
259
260 await rxCollection.insert({ id: `later`, name: `Later` })
261 await vi.waitFor(() => expect(commit).toHaveBeenCalledTimes(3))
262 expect(markReady).not.toHaveBeenCalled()
263
264 bufferedApplied.resolve()
265 await vi.waitFor(() => expect(markReady).toHaveBeenCalledOnce())
266 } finally {
267 releaseInitialQuery.resolve()
268 bufferedApplied.resolve()
269 laterLiveApplied.resolve()
270 if (typeof cleanup === `function`) cleanup()
271 query.mockRestore()
272 await db.remove()
273 }
274 })
275
276 it(`should initialize and fetch initial data`, async () => {
277 const initialItems = getTestData(2)
278
279 const { collection, db } = await createTestState(initialItems)
280
281 // Verify the collection state contains our items
282 expect(collection.size).toBe(initialItems.length)
283 expect(stripVirtualProps(collection.get(`1`))).toEqual(initialItems[0])
284 expect(stripVirtualProps(collection.get(`2`))).toEqual(initialItems[1])
285
286 // Verify the synced data
287 expect(collection._state.syncedData.size).toBe(initialItems.length)
288 expect(collection._state.syncedData.get(`1`)).toEqual(initialItems[0])
289 expect(collection._state.syncedData.get(`2`)).toEqual(initialItems[1])
290
291 await db.remove()
292 })
293
294 it(`should initialize and fetch initial data with many documents`, async () => {
295 const docsAmount = 25 // > 10 to force multiple batches
296 const initialItems = getTestData(docsAmount)
297 const { collection, db } = await createTestState(initialItems)
298
299 // All docs should be present after initial sync
300 expect(collection.size).toBe(docsAmount)
301 expect(collection._state.syncedData.size).toBe(docsAmount)
302
303 // Spot-check a few positions
304 expect(stripVirtualProps(collection.get(`1`))).toEqual({
305 id: `1`,
306 name: `Item 1`,
307 })
308 expect(stripVirtualProps(collection.get(`10`))).toEqual({
309 id: `10`,
310 name: `Item 10`,
311 })
312 expect(stripVirtualProps(collection.get(`11`))).toEqual({
313 id: `11`,
314 name: `Item 11`,
315 })
316 expect(stripVirtualProps(collection.get(`25`))).toEqual({
317 id: `25`,
318 name: `Item 25`,
319 })
320
321 // Ensure no gaps
322 for (let i = 1; i <= docsAmount; i++) {
323 expect(collection.has(String(i))).toBe(true)
324 }
325
326 await db.remove()
327 })
328
329 it(`should update the collection when RxDB changes data`, async () => {
330 const initialItems = getTestData(2)
331
332 const { collection, rxCollection, db } =
333 await createTestState(initialItems)
334
335 // inserts
336 const doc = await rxCollection.insert({ id: `3`, name: `inserted` })
337 expect(stripVirtualProps(collection.get(`3`))?.name).toEqual(`inserted`)
338
339 // updates
340 await doc.getLatest().patch({ name: `updated` })
341 expect(stripVirtualProps(collection.get(`3`))?.name).toEqual(`updated`)
342
343 // deletes
344 await doc.getLatest().remove()
345 expect(stripVirtualProps(collection.get(`3`))).toEqual(undefined)
346
347 await db.remove()
348 })
349
350 it(`should update RxDB when the collection changes data`, async () => {
351 const initialItems = getTestData(2)
352
353 const { collection, rxCollection, db } =
354 await createTestState(initialItems)
355
356 // inserts
357 const tx = collection.insert({ id: `3`, name: `inserted` })
358 await tx.isPersisted.promise
359 let doc = await rxCollection.findOne(`3`).exec(true)
360 expect(doc.name).toEqual(`inserted`)
361
362 // updates
363 collection.update(`3`, (d) => {
364 d.name = `updated`
365 })
366 expect(stripVirtualProps(collection.get(`3`))?.name).toEqual(`updated`)
367 await collection.stateWhenReady()
368 await rxCollection.database.requestIdlePromise()
369 doc = await rxCollection.findOne(`3`).exec(true)
370 expect(doc.name).toEqual(`updated`)
371
372 // deletes
373 collection.delete(`3`)
374 await rxCollection.database.requestIdlePromise()
375 const mustNotBeFound = await rxCollection.findOne(`3`).exec()
376 expect(mustNotBeFound).toEqual(null)
377
378 await db.remove()
379 })
380 })
381
382 describe(`lifecycle management`, () => {
383 it(`should call unsubscribe when collection is cleaned up`, async () => {
384 const { collection, rxCollection, db } = await createTestState()
385
386 await collection.cleanup()
387
388 const subs = getFromMapOrCreate(
389 OPEN_RXDB_SUBSCRIPTIONS,
390 rxCollection,
391 () => new Set(),
392 )
393 expect(subs.size).toEqual(0)
394
395 await db.remove()
396 })
397
398 it(`should restart sync when collection is accessed after cleanup`, async () => {
399 const initialItems = getTestData(2)
400 const { collection, rxCollection, db } =
401 await createTestState(initialItems)
402
403 await collection.cleanup()
404 await flushPromises()
405 expect(collection.status).toBe(`cleaned-up`)
406
407 // insert into RxDB while cleaned-up
408 await rxCollection.insert({ id: `3`, name: `Item 3` })
409
410 // Access collection data to restart sync
411 const subscription = collection.subscribeChanges(() => {})
412
413 await collection.toArrayWhenReady()
414 expect(stripVirtualProps(collection.get(`3`))?.name).toEqual(`Item 3`)
415
416 subscription.unsubscribe()
417 await db.remove()
418 })
419 })
420
421 /**
422 * Here we simulate having multiple browser tabs
423 * open where the data should still be in sync.
424 */
425 describe(`multi tab`, () => {
426 it(`should update the state accross instances`, async () => {
427 const dbid = dbNameId++
428 const db1 = await getDatababase([], dbid)
429 const db2 = await getDatababase(getTestData(2), dbid)
430
431 const col1 = createCollection(
432 rxdbCollectionOptions({
433 rxCollection: db1.test,
434 startSync: true,
435 }),
436 )
437 const col2 = createCollection(
438 rxdbCollectionOptions({
439 rxCollection: db2.test,
440 startSync: true,
441 }),
442 )
443 await col1.stateWhenReady()
444 await col2.stateWhenReady()
445
446 // tanstack-db writes
447 col1.insert({ id: `t1`, name: `t1` })
448 col2.insert({ id: `t2`, name: `t2` })
449 await db1.test.findOne(`t1`).exec(true)
450 await db1.test.findOne(`t2`).exec(true)
451 await db2.test.findOne(`t1`).exec(true)
452 await db2.test.findOne(`t2`).exec(true)
453 expect(col2.get(`t1`)).toBeTruthy()
454 expect(col1.get(`t2`)).toBeTruthy()
455
456 // RxDB writes
457 await db1.test.insert({ id: `rx1`, name: `rx1` })
458 await db2.test.insert({ id: `rx2`, name: `rx2` })
459 expect(col2.get(`rx1`)).toBeTruthy()
460 expect(col1.get(`rx2`)).toBeTruthy()
461
462 db1.remove()
463 db2.remove()
464 })
465 })
466
467 describe(`error handling`, () => {
468 function expectAdditionalPropertyError(error: unknown, id: string) {
469 expect(error).toBeInstanceOf(Error)
470 expect(error).toHaveProperty(
471 `message`,
472 expect.stringMatching(/schema validation error/),
473 )
474 expect(error).toMatchObject({
475 code: `COL20`,
476 rxdb: true,
477 parameters: {
478 document: id,
479 writeError: {
480 status: 422,
481 documentId: id,
482 validationErrors: expect.arrayContaining([
483 expect.objectContaining({
484 keyword: `additionalProperties`,
485 params: { additionalProperty: `foo` },
486 }),
487 ]),
488 },
489 },
490 })
491 }
492
493 it(`rejects an extra field at the provider and accepts its valid neighbor`, async () => {
494 const db = await getDatababase()
495 try {
496 const invalid = { id: `3`, name: `invalid`, foo: `bar` }
497 const rejected = await db.test.bulkUpsert([invalid])
498 expect(rejected.success).toEqual([])
499 expect(rejected.error).toHaveLength(1)
500 expect(rejected.error[0]).toMatchObject({
501 status: 422,
502 documentId: `3`,
503 validationErrors: expect.arrayContaining([
504 expect.objectContaining({
505 keyword: `additionalProperties`,
506 params: { additionalProperty: `foo` },
507 }),
508 ]),
509 })
510 expect(await db.test.find().exec()).toEqual([])
511
512 const accepted = await db.test.bulkUpsert([
513 { id: `3`, name: `invalid` },
514 ])
515 expect(accepted.error).toEqual([])
516 expect(accepted.success).toHaveLength(1)
517 const rows = await db.test.find().exec()
518 expect(rows.map((row) => ({ id: row.id, name: row.name }))).toEqual([
519 { id: `3`, name: `invalid` },
520 ])
521 expect(rows[0]!.toJSON()).not.toHaveProperty(`foo`)
522 } finally {
523 await db.remove()
524 }
525 })
526
527 it(`should rollback the transaction on invalid data that does not match the RxCollection schema`, async () => {
528 const initialItems = getTestData(2)
529 const { collection, rxCollection, db } =
530 await createTestState(initialItems)
531 const outcomes: Array<Promise<unknown>> = []
532 const observe = (promise: Promise<unknown>) => {
533 const outcome = promise.then(
534 () => ({ status: `fulfilled` as const }),
535 (error: unknown) => ({ status: `rejected` as const, error }),
536 )
537 outcomes.push(outcome)
538 return outcome
539 }
540 const expectRows = async (expected: Array<TestDocType>) => {
541 expect(collection.toArray.map((row) => stripVirtualProps(row))).toEqual(
542 expected,
543 )
544 const stored = await rxCollection.find().exec()
545 expect(stored.map((row) => ({ id: row.id, name: row.name }))).toEqual(
546 expected,
547 )
548 for (const row of stored) {
549 expect(row.toJSON()).not.toHaveProperty(`foo`)
550 }
551 }
552
553 try {
554 // Both old invalid inputs reach the actual provider through persistence.
555 const invalid = { id: `3`, name: `invalid`, foo: `bar` }
556 const insert = collection.insert(invalid)
557 const inserted = observe(insert.isPersisted.promise)
558 expect(collection.has(`3`)).toBe(true)
559 const insertOutcome = await inserted
560 expect(insertOutcome.status).toBe(`rejected`)
561 if (insertOutcome.status !== `rejected`) {
562 throw new Error(`Invalid insert unexpectedly persisted`)
563 }
564 expectAdditionalPropertyError(insertOutcome.error, `3`)
565 expect(collection.has(`3`)).toBe(false)
566 await expectRows(initialItems)
567
568 const update = collection.update(`2`, (draft) => {
569 Object.assign(draft, { name: `invalid`, foo: `bar` })
570 })
571 const updated = observe(update.isPersisted.promise)
572 expect(collection.get(`2`)?.name).toBe(`invalid`)
573 const updateOutcome = await updated
574 expect(updateOutcome.status).toBe(`rejected`)
575 if (updateOutcome.status !== `rejected`) {
576 throw new Error(`Invalid update unexpectedly persisted`)
577 }
578 expectAdditionalPropertyError(updateOutcome.error, `2`)
579 expect(stripVirtualProps(collection.get(`2`))?.name).toBe(`Item 2`)
580 await expectRows(initialItems)
581
582 const next = collection.update(`2`, (draft) => {
583 draft.name = `Valid`
584 })
585 expect(await observe(next.isPersisted.promise)).toEqual({
586 status: `fulfilled`,
587 })
588 await expectRows([
589 { id: `1`, name: `Item 1` },
590 { id: `2`, name: `Valid` },
591 ])
592 } finally {
593 await Promise.all(outcomes)
594 await collection.cleanup()
595 await db.remove()
596 }
597 })
598 })
599})