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

offline.test.ts

219 lines6.4 KB

1import { createCollection, withAcceptedReceipt } from '@tanstack/db'
2import { NonRetriableError } from '@tanstack/offline-transactions'
3import { makeFunctionReference } from 'convex/server'
4import { expect, it, vi } from 'vitest'
5import { convexCollectionOptions } from '../src/index'
6import { convexOfflineMutation } from '../src/offline'
7import { controlledClient, query } from './helpers'
8import type { ConvexClient } from 'convex/browser'
9import type { OfflineConfig } from '@tanstack/offline-transactions'
10​
11const mutation = makeFunctionReference<
12 `mutation`,
13 { idempotencyKey: string; text: string },
14 null
15>(`tasks:save`)
16const params = {
17 transaction: { mutations: [] },
18 idempotencyKey: `durable-id`,
19} as unknown as Parameters<OfflineConfig[`mutationFns`][string]>[0]
20​
21it(`sends the durable idempotency key and waits for sync acceptance`, async () => {
22 const send = vi.fn(() => Promise.resolve(null))
23 let accepted!: () => void
24 const gate = new Promise<void>((resolve) => {
25 accepted = resolve
26 })
27 const synced = vi.fn(() => gate)
28 const persist = convexOfflineMutation({
29 client: { mutation: send } as unknown as Pick<ConvexClient, `mutation`>,
30 mutation,
31 getArgs: () => ({ text: `hello` }),
32 collections: [{ utils: { awaitSync: synced } }],
33 })
34 let settled = false
35 const pending = persist(params).then(() => {
36 settled = true
37 })
38 await vi.waitFor(() => expect(synced).toHaveBeenCalledOnce())
39 expect(settled).toBe(false)
40 expect(send).toHaveBeenCalledWith(mutation, {
41 text: `hello`,
42 idempotencyKey: `durable-id`,
43 })
44 accepted()
45 await pending
46 expect(settled).toBe(true)
47})
48​
49it(`rolls back rejected server functions without durable retry`, async () => {
50 const persist = convexOfflineMutation({
51 client: {
52 mutation: () => Promise.reject(new Error(`permission denied`)),
53 } as unknown as Pick<ConvexClient, `mutation`>,
54 mutation,
55 getArgs: () => ({ text: `hello` }),
56 collections: [],
57 })
58 await expect(persist(params)).rejects.toBeInstanceOf(NonRetriableError)
59})
60​
61it.each([`idle`, `pending`, `failed`] as const)(
62 `requires a real source snapshot during %s replay`,
63 async (state) => {
64 const transport = controlledClient()
65 const startupError = new Error(`startup failed`)
66 const collection = createCollection(
67 convexCollectionOptions({
68 client:
69 state === `failed`
70 ? {
71 onUpdate: () => {
72 throw startupError
73 },
74 }
75 : transport.client,
76 query,
77 queryArgs: { owner: `alice` },
78 getKey: (row) => row._id,
79 gcTime: 0,
80 }),
81 )
82 if (state !== `idle`) collection.startSyncImmediate()
83 const persist = convexOfflineMutation({
84 client: { mutation: () => Promise.resolve(null) } as unknown as Pick<
85 ConvexClient,
86 `mutation`
87 >,
88 mutation,
89 getArgs: () => ({ text: `hello` }),
90 collections: [collection],
91 })
92 let outcome: unknown = `pending`
93 const pending = persist(params).then(
94 () => {
95 outcome = `fulfilled`
96 },
97 (error) => {
98 outcome = error
99 },
100 )
101 await new Promise((resolve) => setTimeout(resolve, 0))
102 try {
103 if (state === `failed`) {
104 expect(outcome).toBe(startupError)
105 } else {
106 expect(outcome).toBe(`pending`)
107 expect(transport.counts().subscriptions).toBe(1)
108 transport.emit([])
109 await pending
110 expect(outcome).toBe(`fulfilled`)
111 }
112 } finally {
113 await collection.cleanup()
114 }
115 },
117​
118it(`rejects replay when a wrapping sync rejects source acceptance`, async () => {
119 const transport = controlledClient()
120 const cause = new Error(`durable sync failed`)
121 let rejectAcceptance!: (error: unknown) => void
122 const accepted = new Promise<void>((_resolve, reject) => {
123 rejectAcceptance = reject
124 })
125 const options = convexCollectionOptions({
126 client: transport.client,
127 query,
128 queryArgs: { owner: `alice` },
129 getKey: (row) => row._id,
130 gcTime: 0,
131 })
132 const collection = createCollection({
133 ...options,
134 sync: {
135 ...options.sync,
136 sync: (syncParams) =>
137 options.sync.sync({
138 ...syncParams,
139 commit: () => {
140 const visible = syncParams.commit()
141 return withAcceptedReceipt(
142 Promise.resolve(visible).then(() => undefined),
143 accepted,
144 )
145 },
146 }),
147 },
148 })
149 const persist = convexOfflineMutation({
150 client: { mutation: () => Promise.resolve(null) } as unknown as Pick<
151 ConvexClient,
152 `mutation`
153 >,
154 mutation,
155 getArgs: () => ({ text: `hello` }),
156 collections: [collection],
157 })
158 const pending = persist(params)
159 const rejected = expect(pending).rejects.toBe(cause)
160 await new Promise((resolve) => setTimeout(resolve, 0))
161 transport.emit([])
162 rejectAcceptance(cause)
163 try {
164 await rejected
165 } finally {
166 await collection.cleanup()
167 }
168})
169​
170it(`requires a new sync run after durable acceptance fails`, async () => {
171 const transport = controlledClient()
172 const cause = new Error(`durable source failure`)
173 let rejectAcceptance!: (error: unknown) => void
174 let durable = new Promise<void>((_resolve, reject) => {
175 rejectAcceptance = reject
176 })
177 const options = convexCollectionOptions({
178 client: transport.client,
179 query,
180 queryArgs: { owner: `alice` },
181 getKey: (row) => row._id,
182 gcTime: 0,
183 })
184 const collection = createCollection({
185 ...options,
186 sync: {
187 ...options.sync,
188 sync: (syncParams) =>
189 options.sync.sync({
190 ...syncParams,
191 commit: () => {
192 const visible = durable
193 .then(async () => {
194 await syncParams.commit()
195 })
196 .then(() => undefined)
197 return withAcceptedReceipt(visible, durable)
198 },
199 }),
200 },
201 })
202 const waiting = collection.utils.awaitSync()
203 const rejected = expect(waiting).rejects.toBe(cause)
204 transport.emit([])
205 rejectAcceptance(cause)
206 await rejected
207 try {
208 await expect(collection.utils.awaitSync()).rejects.toBe(cause)
209 transport.emit([{ _id: `a`, text: `later callback` }])
210 await expect(collection.utils.awaitSync()).rejects.toBe(cause)
211 await collection.cleanup()
212 durable = Promise.resolve()
213 collection.startSyncImmediate()
214 await collection.utils.awaitSync()
215 expect(collection.get(`a`)?.text).toBe(`later callback`)
216 } finally {
217 await collection.cleanup()
218 }
219})