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

node-persisted-collection.e2e.test.ts

279 lines7.5 KB

1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterAll, afterEach, beforeAll } from 'vitest'
5import { BTreeIndex, createCollection } from '@tanstack/db'
6import BetterSqlite3 from 'better-sqlite3'
7import { createNodeSQLitePersistence, persistedCollectionOptions } from '../src'
8import {
9 captureSeedData,
10 generateSeedData,
11} from '../../db-collection-e2e/src/fixtures/seed-data'
12import { runPersistedCollectionConformanceSuite } from '../../db-sqlite-persistence-core/tests/contracts/persisted-collection-conformance-contract'
13import type { Collection } from '@tanstack/db'
14import type {
15 Comment,
16 E2ETestConfig,
17 Post,
18 User,
19} from '../../db-collection-e2e/src/types'
20​
21type PersistableRow = {
22 id: string
24​
25type NodePersistedCollectionTestConfig = E2ETestConfig
26type PersistedCollectionHarness<T extends PersistableRow> = {
27 collection: Collection<T, string | number>
28 seedPersisted: (rows: Array<T>) => Promise<void>
30​
31let config: NodePersistedCollectionTestConfig
32​
33function createPersistedCollection<T extends PersistableRow>(
34 database: InstanceType<typeof BetterSqlite3>,
35 id: string,
36 syncMode: `eager` | `on-demand`,
37): PersistedCollectionHarness<T> {
38 const persistence = createNodeSQLitePersistence({
39 database,
40 })
41 let seedTxSequence = 0
42 const seedPersisted = async (rows: Array<T>): Promise<void> => {
43 if (rows.length === 0) {
44 return
45 }
46 seedTxSequence++
47 await persistence.adapter.applyCommittedTx(id, {
48 txId: `seed-${id}-${seedTxSequence}`,
49 term: 1,
50 seq: seedTxSequence,
51 rowVersion: seedTxSequence,
52 mutations: rows.map((row) => ({
53 type: `insert` as const,
54 key: row.id,
55 value: row,
56 })),
57 })
58 }
59​
60 const collection = createCollection(
61 persistedCollectionOptions<T, string | number>({
62 id,
63 syncMode,
64 getKey: (item) => item.id,
65 persistence,
66 autoIndex: `eager`,
67 defaultIndexType: BTreeIndex,
68 }),
69 )
70​
71 return {
72 collection,
73 seedPersisted,
74 }
76​
77type PersistedTransactionHandle = {
78 isPersisted: {
79 promise: Promise<unknown>
80 }
82​
83async function waitForPersisted(
84 transaction: PersistedTransactionHandle,
85): Promise<void> {
86 await transaction.isPersisted.promise
88​
89async function seedCollection<T extends PersistableRow>(
90 collection: Collection<T, string | number>,
91 rows: Array<T>,
92): Promise<void> {
93 const tx = collection.insert(rows)
94 await waitForPersisted(tx)
96​
97async function insertRowIntoCollections<T extends PersistableRow>(
98 collections: ReadonlyArray<Collection<T, string | number>>,
99 row: T,
100): Promise<void> {
101 for (const collection of collections) {
102 const tx = collection.insert(row)
103 await waitForPersisted(tx)
104 }
106​
107async function updateRowAcrossCollections<T extends PersistableRow>(
108 collections: ReadonlyArray<Collection<T, string | number>>,
109 id: string,
110 updates: Partial<T>,
111): Promise<void> {
112 for (const collection of collections) {
113 if (!collection.has(id)) {
114 continue
115 }
116 const tx = collection.update(id, (draft) => {
117 Object.assign(draft, updates)
118 })
119 await waitForPersisted(tx)
120 }
122​
123async function deleteRowAcrossCollections<T extends PersistableRow>(
124 collections: ReadonlyArray<Collection<T, string | number>>,
125 id: string,
126): Promise<void> {
127 for (const collection of collections) {
128 if (!collection.has(id)) {
129 continue
130 }
131 const tx = collection.delete(id)
132 await waitForPersisted(tx)
133 }
135​
136beforeAll(async () => {
137 const tempDirectory = mkdtempSync(join(tmpdir(), `db-node-persisted-e2e-`))
138 const dbPath = join(tempDirectory, `state.sqlite`)
139 const suiteId = Date.now().toString(36)
140 const database = new BetterSqlite3(dbPath)
141 const seedData = generateSeedData()
142 const fixture = captureSeedData(seedData, {
143 registration:
144 'packages/node-db-sqlite-persistence/e2e/node-persisted-collection.e2e.test.ts',
145 provider: 'BetterSqlite3',
146 })
147​
148 const eagerUsers = createPersistedCollection<User>(
149 database,
150 `node-persisted-users-eager-${suiteId}`,
151 `eager`,
152 )
153 const eagerPosts = createPersistedCollection<Post>(
154 database,
155 `node-persisted-posts-eager-${suiteId}`,
156 `eager`,
157 )
158 const eagerComments = createPersistedCollection<Comment>(
159 database,
160 `node-persisted-comments-eager-${suiteId}`,
161 `eager`,
162 )
163​
164 const onDemandUsers = createPersistedCollection<User>(
165 database,
166 `node-persisted-users-ondemand-${suiteId}`,
167 `on-demand`,
168 )
169 const onDemandPosts = createPersistedCollection<Post>(
170 database,
171 `node-persisted-posts-ondemand-${suiteId}`,
172 `on-demand`,
173 )
174 const onDemandComments = createPersistedCollection<Comment>(
175 database,
176 `node-persisted-comments-ondemand-${suiteId}`,
177 `on-demand`,
178 )
179​
180 await Promise.all([
181 eagerUsers.collection.preload(),
182 eagerPosts.collection.preload(),
183 eagerComments.collection.preload(),
184 ])
185​
186 await seedCollection(eagerUsers.collection, seedData.users)
187 await seedCollection(eagerPosts.collection, seedData.posts)
188 await seedCollection(eagerComments.collection, seedData.comments)
189 await onDemandUsers.seedPersisted(seedData.users)
190 await onDemandPosts.seedPersisted(seedData.posts)
191 await onDemandComments.seedPersisted(seedData.comments)
192​
193 config = {
194 fixture,
195 collections: {
196 eager: {
197 users: eagerUsers.collection,
198 posts: eagerPosts.collection,
199 comments: eagerComments.collection,
200 },
201 onDemand: {
202 users: onDemandUsers.collection,
203 posts: onDemandPosts.collection,
204 comments: onDemandComments.collection,
205 },
206 },
207 mutations: {
208 insertUser: async (user) =>
209 insertRowIntoCollections(
210 [eagerUsers.collection, onDemandUsers.collection],
211 user,
212 ),
213 updateUser: async (id, updates) =>
214 updateRowAcrossCollections(
215 [eagerUsers.collection, onDemandUsers.collection],
216 id,
217 updates,
218 ),
219 deleteUser: async (id) =>
220 deleteRowAcrossCollections(
221 [eagerUsers.collection, onDemandUsers.collection],
222 id,
223 ),
224 insertPost: async (post) =>
225 insertRowIntoCollections(
226 [eagerPosts.collection, onDemandPosts.collection],
227 post,
228 ),
229 deletePost: async (id) =>
230 deleteRowAcrossCollections(
231 [eagerPosts.collection, onDemandPosts.collection],
232 id,
233 ),
234 },
235 setup: async () => {},
236 afterEach: async () => {
237 await Promise.all([
238 onDemandUsers.collection.cleanup(),
239 onDemandPosts.collection.cleanup(),
240 onDemandComments.collection.cleanup(),
241 ])
242​
243 onDemandUsers.collection.startSyncImmediate()
244 onDemandPosts.collection.startSyncImmediate()
245 onDemandComments.collection.startSyncImmediate()
246 },
247 teardown: async () => {
248 await Promise.all([
249 eagerUsers.collection.cleanup(),
250 eagerPosts.collection.cleanup(),
251 eagerComments.collection.cleanup(),
252 onDemandUsers.collection.cleanup(),
253 onDemandPosts.collection.cleanup(),
254 onDemandComments.collection.cleanup(),
255 ])
256 database.close()
257 rmSync(tempDirectory, { recursive: true, force: true })
258 },
259 }
260})
261​
262afterEach(async () => {
263 if (config.afterEach) {
264 await config.afterEach()
265 }
266})
267​
268afterAll(async () => {
269 await config.teardown()
270})
271​
272function getConfig(): Promise<NodePersistedCollectionTestConfig> {
273 return Promise.resolve(config)
275​
276runPersistedCollectionConformanceSuite(
277 `node persisted collection conformance`,
278 getConfig,