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

persisted.test-d.ts

379 lines12.6 KB

1import { describe, expectTypeOf, it } from 'vitest'
2import { createCollection } from '@tanstack/db'
3import {
4 IndeterminateCommitError,
5 PersistedCollectionDurabilityError,
6 persistedCollectionOptions,
7} from '../src'
8import type {
9 ApplyCommittedTxResponse,
10 ApplyLocalMutationsResponse,
11 EnsureRemoteSubsetRequest,
12 EnsureRemoteSubsetResponse,
13 IndeterminateCommitRequestType,
14 PersistedCollectionCoordinator,
15 PersistedCollectionUtils,
16 PersistedKeySetEvidence,
17 PersistenceAdapter,
18 RemoteSubsetWireValue,
19 TransportedLoadSubsetOptions,
20} from '../src'
21import type { SyncConfig, UtilsRecord } from '@tanstack/db'
22​
23/**
24 * # Which persistence contracts are visible to TypeScript callers?
25 *
26 * The exported types require complete committed-transaction routing, preserve
27 * named reconciliation and durability errors, and admit exactly the declared
28 * remote-subset wire domain. Positive assignments are the reference type
29 * shapes. `@ts-expect-error` cases are the fault controls for omitted
30 * acquisition identity, live signals/subscriptions, unsupported values, and
31 * incomplete coordinators.
32 *
33 * The TypeScript compile is the production checkpoint. These checks establish
34 * assignability and inference only. Runtime validation, structured cloning,
35 * routing, settlement, and publication belong to the executable owners.
36 */
37​
38type Todo = {
39 id: string
40 title: string
42​
43interface LocalExtraUtils extends UtilsRecord {
44 existingUtil: () => number
46​
47interface SyncExtraUtils extends UtilsRecord {
48 refetch: () => Promise<void>
50​
51const adapter: PersistenceAdapter = {
52 loadSubset: () => Promise.resolve([]),
53 loadResumeSnapshot: () =>
54 Promise.resolve({
55 rows: [],
56 keySet: { status: `consistent` },
57 collectionMetadata: [],
58 latestTerm: 0,
59 latestSeq: 0,
60 latestRowVersion: 0,
61 resetEpoch: 0,
62 }),
63 applyCommittedTx: () => Promise.resolve(),
64 ensureIndex: () => Promise.resolve(),
66​
67describe(`persisted collection types`, () => {
68 it(`exports the indeterminate commit reconciliation contract`, () => {
69 const requestType: IndeterminateCommitRequestType = `rpc:applyLocalMutations:req`
70 const error = new IndeterminateCommitError({
71 collectionId: `todos`,
72 requestType,
73 previousLeaderId: `leader-a`,
74 previousTerm: 1,
75 currentLeaderId: null,
76 currentTerm: null,
77 cause: new Error(`channel closed`),
78 })
79​
80 expectTypeOf(error.code).toEqualTypeOf<`INDETERMINATE_COMMIT`>()
81 expectTypeOf(
82 error.requestType,
83 ).toEqualTypeOf<IndeterminateCommitRequestType>()
84 expectTypeOf(error.previousLeaderId).toEqualTypeOf<string | null>()
85 expectTypeOf(error.previousTerm).toEqualTypeOf<number | null>()
86 expectTypeOf(error.currentLeaderId).toEqualTypeOf<string | null>()
87 expectTypeOf(error.currentTerm).toEqualTypeOf<number | null>()
88 expectTypeOf(error.cause).toEqualTypeOf<unknown>()
89 })
90​
91 it(`exports the durability error and persistence response details`, () => {
92 const cause = Object.assign(new Error(`disk failed`), {
93 code: `SQLITE_FULL`,
94 path: `todos.sqlite`,
95 })
96 const error = new PersistedCollectionDurabilityError(`durability failed`, {
97 cause,
98 code: cause.code,
99 path: cause.path,
100 })
101 const response: Extract<
102 ApplyCommittedTxResponse,
103 { ok: false; code: `PERSISTENCE_ERROR` }
104 > = {
105 type: `rpc:applyCommittedTx:res`,
106 rpcId: `durability`,
107 ok: false,
108 code: `PERSISTENCE_ERROR`,
109 error: `disk failed`,
110 sourceCode: `SQLITE_FULL`,
111 path: [`database`, `todos.sqlite`],
112 }
113 const localMutationResponse: Extract<
114 ApplyLocalMutationsResponse,
115 { ok: false; code: `PERSISTENCE_ERROR` }
116 > = {
117 type: `rpc:applyLocalMutations:res`,
118 rpcId: `local-durability`,
119 ok: false,
120 code: `PERSISTENCE_ERROR`,
121 error: `disk failed`,
122 sourceCode: `SQLITE_FULL`,
123 path: [`database`, `todos.sqlite`],
124 }
125​
126 expectTypeOf(error.cause).toEqualTypeOf<unknown>()
127 expectTypeOf(error.code).toEqualTypeOf<unknown>()
128 expectTypeOf(error.path).toEqualTypeOf<unknown>()
129 expectTypeOf(response.sourceCode).toEqualTypeOf<
130 string | number | undefined
131 >()
132 expectTypeOf(response.path).toEqualTypeOf<
133 string | ReadonlyArray<string | number> | undefined
134 >()
135 expectTypeOf(localMutationResponse.sourceCode).toEqualTypeOf<
136 string | number | undefined
137 >()
138 expectTypeOf(localMutationResponse.path).toEqualTypeOf<
139 string | ReadonlyArray<string | number> | undefined
140 >()
141 })
142​
143 it(`exports the exact remote-subset transport domain`, () => {
144 type WireRecord = { [key: string]: RemoteSubsetWireValue }
145 const cyclic: WireRecord = {}
146 cyclic.self = cyclic
147 const supported: TransportedLoadSubsetOptions = {
148 where: {
149 type: `func`,
150 name: `eq`,
151 args: [
152 { type: `ref`, path: [`todos`, `payload`] },
153 {
154 type: `val`,
155 value: {
156 missing: undefined,
157 precise: 9_007_199_254_740_993n,
158 date: new Date(Number.NaN),
159 regexp: /wire/giu,
160 buffer: new ArrayBuffer(4),
161 view: new DataView(new ArrayBuffer(4)),
162 typed: new Uint8Array([1, 2]),
163 map: new Map<RemoteSubsetWireValue, RemoteSubsetWireValue>([
164 [{ key: `object` }, cyclic],
165 ]),
166 set: new Set<RemoteSubsetWireValue>([cyclic]),
167 },
168 },
169 ],
170 },
171 orderBy: [
172 {
173 expression: { type: `ref`, path: [`todos`, `title`] },
174 compareOptions: {
175 direction: `asc`,
176 nulls: `last`,
177 stringSort: `locale`,
178 locale: `en`,
179 localeOptions: { sensitivity: `base` },
180 },
181 },
182 ],
183 cursor: {
184 whereFrom: { type: `val`, value: `from` },
185 whereCurrent: { type: `val`, value: `current` },
186 lastKey: `key`,
187 },
188 limit: 10,
189 offset: 2,
190 }
191 const request: EnsureRemoteSubsetRequest = {
192 type: `rpc:ensureRemoteSubset:req`,
193 rpcId: `wire`,
194 acquisitionId: `wire-acquisition`,
195 options: supported,
196 }
197​
198 // @ts-expect-error every transported acquisition has a stable identity
199 const requestWithoutAcquisition: EnsureRemoteSubsetRequest = {
200 type: `rpc:ensureRemoteSubset:req`,
201 rpcId: `wire-without-acquisition`,
202 options: supported,
203 }
204​
205 expectTypeOf(request.options).toEqualTypeOf<TransportedLoadSubsetOptions>()
206 expectTypeOf(request.acquisitionId).toEqualTypeOf<string>()
207 expectTypeOf<
208 Extract<EnsureRemoteSubsetResponse, { ok: true }>
209 >().toHaveProperty(`leaderId`)
210 expectTypeOf(
211 requestWithoutAcquisition,
212 ).toEqualTypeOf<EnsureRemoteSubsetRequest>()
213 type RegisteredOwner = Parameters<
214 NonNullable<PersistedCollectionCoordinator[`registerRemoteSubsetOwner`]>
215 >[1]
216 expectTypeOf<RegisteredOwner>()
217 .parameter(0)
218 .toEqualTypeOf<TransportedLoadSubsetOptions>()
219​
220 // @ts-expect-error functions are not remote-subset wire values
221 const functionValue: RemoteSubsetWireValue = () => {}
222 // @ts-expect-error symbols are not remote-subset wire values
223 const symbolValue: RemoteSubsetWireValue = Symbol(`unsupported`)
224 // @ts-expect-error promises are not remote-subset wire values
225 const promiseValue: RemoteSubsetWireValue = Promise.resolve()
226 // @ts-expect-error weak collections are not remote-subset wire values
227 const weakValue: RemoteSubsetWireValue = new WeakMap()
228 // @ts-expect-error custom prototypes are not remote-subset wire values
229 const customValue: RemoteSubsetWireValue = new (class Custom {
230 value = `custom`
231 })()
232 // @ts-expect-error shared buffers are not remote-subset wire values
233 const sharedValue: RemoteSubsetWireValue = new SharedArrayBuffer(4)
234 const signalOptions: TransportedLoadSubsetOptions = {
235 // @ts-expect-error live signals never cross the coordinator wire
236 signal: new AbortController().signal,
237 }
238 const subscriptionOptions: TransportedLoadSubsetOptions = {
239 // @ts-expect-error live subscriptions never cross the coordinator wire
240 subscription: {},
241 }
242​
243 expectTypeOf(functionValue).toEqualTypeOf<RemoteSubsetWireValue>()
244 expectTypeOf(symbolValue).toEqualTypeOf<RemoteSubsetWireValue>()
245 expectTypeOf(promiseValue).toEqualTypeOf<RemoteSubsetWireValue>()
246 expectTypeOf(weakValue).toEqualTypeOf<RemoteSubsetWireValue>()
247 expectTypeOf(customValue).toEqualTypeOf<RemoteSubsetWireValue>()
248 expectTypeOf(sharedValue).toEqualTypeOf<RemoteSubsetWireValue>()
249 expectTypeOf(signalOptions).toEqualTypeOf<TransportedLoadSubsetOptions>()
250 expectTypeOf(
251 subscriptionOptions,
252 ).toEqualTypeOf<TransportedLoadSubsetOptions>()
253 })
254​
255 it(`requires complete committed-transaction routing from coordinators`, () => {
256 // @ts-expect-error requestApplyCommittedTx is required for every coordinator
257 const incompleteCoordinator: PersistedCollectionCoordinator = {
258 getNodeId: () => `incomplete`,
259 subscribe: () => () => {},
260 publish: () => {},
261 isLeader: () => true,
262 ensureLeadership: () => Promise.resolve(),
263 requestEnsureRemoteSubset: () => Promise.resolve(),
264 requestReleaseRemoteSubset: () => Promise.resolve(),
265 registerRemoteSubsetOwner: () => () => {},
266 requestEnsurePersistedIndex: () => Promise.resolve(),
267 }
268​
269 expectTypeOf(
270 incompleteCoordinator,
271 ).toMatchTypeOf<PersistedCollectionCoordinator>()
272 })
273​
274 it(`requires an exact atomic resume snapshot contract`, () => {
275 type LoadResumeSnapshot = PersistenceAdapter[`loadResumeSnapshot`]
276 type ResumeSnapshot = Awaited<ReturnType<LoadResumeSnapshot>>
277​
278 expectTypeOf(adapter).toMatchTypeOf<PersistenceAdapter>()
279 expectTypeOf(adapter.loadResumeSnapshot).toMatchTypeOf<LoadResumeSnapshot>()
280 expectTypeOf<Parameters<LoadResumeSnapshot>[1]>().toEqualTypeOf<
281 | {
282 requiredIndexSignatures?: ReadonlyArray<string>
283 includeRows?: boolean
284 }
285 | undefined
286 >()
287 expectTypeOf<ResumeSnapshot[`keySet`]>().toEqualTypeOf<
288 PersistedKeySetEvidence | undefined
289 >()
290​
291 // @ts-expect-error key-set evidence has exactly three supported states
292 const invalidEvidence: PersistedKeySetEvidence = { status: `verified` }
293 expectTypeOf(invalidEvidence).toEqualTypeOf<PersistedKeySetEvidence>()
294 })
295 it(`adds persisted utils in sync-absent mode`, () => {
296 const options = persistedCollectionOptions<
297 Todo,
298 string,
299 never,
300 LocalExtraUtils
301 >({
302 id: `persisted-local-only`,
303 schemaVersion: 1,
304 getKey: (item) => item.id,
305 utils: {
306 existingUtil: () => 42,
307 },
308 persistence: {
309 adapter,
310 },
311 })
312​
313 expectTypeOf(options.utils.existingUtil).toBeFunction()
314 expectTypeOf(options.utils.existingUtil).returns.toEqualTypeOf<number>()
315 expectTypeOf(options.utils.acceptMutations).toBeFunction()
316 expectTypeOf(options.utils.getLeadershipState).toEqualTypeOf<
317 (() => { nodeId: string; isLeader: boolean }) | undefined
318 >()
319​
320 const collection = createCollection(options)
321 expectTypeOf(collection.utils.acceptMutations).toBeFunction()
322 expectTypeOf(collection.utils).toMatchTypeOf<PersistedCollectionUtils>()
323 })
324​
325 it(`preserves sync-present utility typing`, () => {
326 const sync: SyncConfig<Todo, string> = {
327 sync: ({ markReady }) => {
328 markReady()
329 },
330 }
331​
332 const options = persistedCollectionOptions<
333 Todo,
334 string,
335 never,
336 SyncExtraUtils
337 >({
338 id: `persisted-sync-present`,
339 schemaVersion: 2,
340 getKey: (item) => item.id,
341 sync,
342 utils: {
343 refetch: async () => {},
344 },
345 persistence: {
346 adapter,
347 },
348 })
349​
350 expectTypeOf(options.sync).toEqualTypeOf<SyncConfig<Todo, string>>()
351 expectTypeOf(options.utils).toEqualTypeOf<SyncExtraUtils | undefined>()
352​
353 const collection = createCollection(options)
354 expectTypeOf(collection.utils.refetch).toBeFunction()
355 })
356​
357 it(`requires persistence config`, () => {
358 persistedCollectionOptions({
359 getKey: (item: Todo) => item.id,
360 // @ts-expect-error persistedCollectionOptions requires persistence when sync is provided
361 sync: {
362 sync: ({ markReady }: { markReady: () => void }) => {
363 markReady()
364 },
365 },
366 })
367 })
368​
369 it(`requires a valid sync config when sync key is present`, () => {
370 persistedCollectionOptions({
371 getKey: (item: Todo) => item.id,
372 // @ts-expect-error sync must be a valid SyncConfig object when provided
373 sync: null,
374 persistence: {
375 adapter,
376 },
377 })
378 })
379})