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

node-persisted-collection.e2e.test.ts

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