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