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

trailbase.e2e.test.ts

489 lines14.6 KB

1/**
2 * TrailBase Collection E2E Tests
3 *
4 * End-to-end tests using actual TrailBase server with sync.
5 * Uses shared test suites from @tanstack/db-collection-e2e.
6 */
7​
8import { afterEach, describe, expect, inject } from 'vitest'
9import { BTreeIndex, createCollection } from '@tanstack/db'
10import { initClient } from 'trailbase'
11import { trailBaseCollectionOptions } from '../src/trailbase'
12import {
13 captureSeedData,
14 createCollationTestSuite,
15 createDeduplicationTestSuite,
16 createJoinsTestSuite,
17 createLiveUpdatesTestSuite,
18 createMutationsTestSuite,
19 createPaginationTestSuite,
20 createPredicatesTestSuite,
21 createProgressiveTestSuite,
22 generateSeedData,
23} from '../../db-collection-e2e/src/index'
24import type { Client } from 'trailbase'
25import type { SeedDataResult } from '../../db-collection-e2e/src/index'
26import type { TrailBaseSyncMode } from '../src/trailbase'
27import type {
28 Comment,
29 E2ETestConfig,
30 Post,
31 User,
32} from '../../db-collection-e2e/src/types'
33import type { Collection } from '@tanstack/db'
34​
35declare module 'vitest' {
36 export interface ProvidedContext {
37 baseUrl: string
38 }
40​
41function parseUuid(uuid: string): Uint8Array {
42 const hex = uuid.replace(/-/g, '')
43​
44 if (!/^[0-9a-fA-F]{32}$/.test(hex)) {
45 throw new Error(`Invalid UUID: ${uuid}`)
46 }
47​
48 return Uint8Array.from(
49 Array.from({ length: 16 }, (_, index) =>
50 Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16),
51 ),
52 )
54​
55function stringifyUuid(bytes: Uint8Array): string {
56 if (bytes.length !== 16) {
57 throw new Error(`UUID bytes must be 16 bytes, got ${bytes.length}`)
58 }
59​
60 const hex = Array.from(bytes, (byte) =>
61 byte.toString(16).padStart(2, '0'),
62 ).join('')
63​
64 return [
65 hex.slice(0, 8),
66 hex.slice(8, 12),
67 hex.slice(12, 16),
68 hex.slice(16, 20),
69 hex.slice(20),
70 ].join('-')
72// / Decode a "url-safe" base64 string to bytes.
73function urlSafeBase64Decode(base64: string): Uint8Array {
74 return Uint8Array.from(
75 atob(base64.replace(/_/g, '/').replace(/-/g, '+')),
76 (c) => c.charCodeAt(0),
77 )
79​
80// / Encode an arbitrary string input as a "url-safe" base64 string.
81function urlSafeBase64Encode(bytes: Uint8Array): string {
82 return btoa(String.fromCharCode(...bytes))
83 .replace(/\//g, '_')
84 .replace(/\+/g, '-')
86​
87function parseTrailBaseId(id: string): string {
88 return stringifyUuid(urlSafeBase64Decode(id))
90​
91function toTrailBaseId(id: string): string {
92 return urlSafeBase64Encode(parseUuid(id))
94​
95/**
96 * TrailBase record types matching the camelCase schema
97 * Column names match the app types, only types differ for storage
98 */
99interface UserRecord {
100 id: string // base64 encoded UUID
101 name: string
102 email: string | null
103 age: number
104 isActive: number // SQLite INTEGER (0/1) for boolean
105 createdAt: string // ISO date string
106 metadata: string | null // JSON stored as string
107 deletedAt: string | null // ISO date string
109​
110interface PostRecord {
111 id: string
112 userId: string
113 title: string
114 content: string | null
115 viewCount: number
116 largeViewCount: string // BigInt as string
117 publishedAt: string | null
118 deletedAt: string | null
120​
121interface CommentRecord {
122 id: string
123 postId: string
124 userId: string
125 text: string
126 createdAt: string
127 deletedAt: string | null
129​
130/**
131 * Serialize functions - transform app types to DB storage types
132 * ID is base64 encoded for TrailBase BLOB storage
133 */
134const serializeUser = (user: User): UserRecord => ({
135 ...user,
136 isActive: user.isActive ? 1 : 0,
137 createdAt: user.createdAt.toISOString(),
138 metadata: user.metadata ? JSON.stringify(user.metadata) : null,
139 deletedAt: user.deletedAt ? user.deletedAt.toISOString() : null,
140})
141​
142const serializePost = (post: Post): PostRecord => ({
143 ...post,
144 largeViewCount: post.largeViewCount.toString(),
145 publishedAt: post.publishedAt ? post.publishedAt.toISOString() : null,
146 deletedAt: post.deletedAt ? post.deletedAt.toISOString() : null,
147})
148​
149const serializeComment = (comment: Comment): CommentRecord => ({
150 ...comment,
151 createdAt: comment.createdAt.toISOString(),
152 deletedAt: comment.deletedAt ? comment.deletedAt.toISOString() : null,
153})
154​
155/**
156 * Helper to create a set of collections for a given sync mode
157 */
158function createCollectionsForSyncMode(
159 client: Client,
160 testId: string,
161 syncMode: TrailBaseSyncMode,
162 suffix: string,
163 own: (collection: { cleanup: () => Promise<void> }) => void,
164) {
165 const usersRecordApi = client.records<UserRecord>(`users_e2e`)
166 const postsRecordApi = client.records<PostRecord>(`posts_e2e`)
167 const commentsRecordApi = client.records<CommentRecord>(`comments_e2e`)
168​
169 const usersCollection = createCollection(
170 trailBaseCollectionOptions({
171 id: `trailbase-e2e-users-${suffix}-${testId}`,
172 recordApi: usersRecordApi,
173 getKey: (item: User) => item.id,
174 startSync: true,
175 syncMode,
176 autoIndex: `eager`,
177 defaultIndexType: BTreeIndex,
178 parse: {
179 id: parseTrailBaseId,
180 isActive: (isActive) => Boolean(isActive),
181 createdAt: (createdAt) => new Date(createdAt),
182 metadata: (m) => (m ? JSON.parse(m) : null),
183 deletedAt: (d) => (d ? new Date(d) : null),
184 },
185 serialize: {
186 id: toTrailBaseId,
187 isActive: (a) => (a ? 1 : 0),
188 createdAt: (c) => c.toISOString(),
189 metadata: (m) => (m ? JSON.stringify(m) : null),
190 deletedAt: (d) => (d ? d.toISOString() : null),
191 },
192 }),
193 )
194 own(usersCollection)
195​
196 const postsCollection = createCollection(
197 trailBaseCollectionOptions({
198 id: `trailbase-e2e-posts-${suffix}-${testId}`,
199 recordApi: postsRecordApi,
200 getKey: (item: Post) => item.id,
201 startSync: true,
202 syncMode,
203 autoIndex: `eager`,
204 defaultIndexType: BTreeIndex,
205 parse: {
206 id: parseTrailBaseId,
207 largeViewCount: (l) => BigInt(l),
208 publishedAt: (v) => (v ? new Date(v) : null),
209 deletedAt: (d) => (d ? new Date(d) : null),
210 },
211 serialize: {
212 id: toTrailBaseId,
213 largeViewCount: (v) => v.toString(),
214 publishedAt: (v) => (v ? v.toISOString() : null),
215 deletedAt: (d) => (d ? d.toISOString() : null),
216 },
217 }),
218 )
219 own(postsCollection)
220​
221 const commentsCollection = createCollection(
222 trailBaseCollectionOptions({
223 id: `trailbase-e2e-comments-${suffix}-${testId}`,
224 recordApi: commentsRecordApi,
225 getKey: (item: Comment) => item.id,
226 startSync: true,
227 syncMode,
228 autoIndex: `eager`,
229 defaultIndexType: BTreeIndex,
230 parse: {
231 id: parseTrailBaseId,
232 createdAt: (v) => new Date(v),
233 deletedAt: (d) => (d ? new Date(d) : null),
234 },
235 serialize: {
236 id: toTrailBaseId,
237 createdAt: (v) => v.toISOString(),
238 deletedAt: (d) => (d ? d.toISOString() : null),
239 },
240 }),
241 )
242 own(commentsCollection)
243​
244 return {
245 users: usersCollection as Collection<User>,
246 posts: postsCollection as Collection<Post>,
247 comments: commentsCollection as Collection<Comment>,
248 }
250​
251async function initialCleanup(client: Client) {
252 console.log(`Cleaning up existing records...`)
253​
254 const commentsRecordApi = client.records<CommentRecord>(`comments_e2e`)
255 const existingComments = await commentsRecordApi.list({})
256 for (const comment of existingComments.records) {
257 try {
258 await commentsRecordApi.delete(comment.id)
259 } catch {
260 /* ignore */
261 }
262 }
263​
264 const postsRecordApi = client.records<PostRecord>(`posts_e2e`)
265 const existingPosts = await postsRecordApi.list({})
266 for (const post of existingPosts.records) {
267 try {
268 await postsRecordApi.delete(post.id)
269 } catch {
270 /* ignore */
271 }
272 }
273​
274 const usersRecordApi = client.records<UserRecord>(`users_e2e`)
275 const existingUsers = await usersRecordApi.list({})
276 for (const user of existingUsers.records) {
277 try {
278 await usersRecordApi.delete(user.id)
279 } catch {
280 /* ignore */
281 }
282 }
283​
284 console.log(`Cleanup complete`)
286​
287async function setupInitialData(client: Client, seedData: SeedDataResult) {
288 const errors: Array<unknown> = []
289 const usersRecordApi = client.records<UserRecord>(`users_e2e`)
290 const postsRecordApi = client.records<PostRecord>(`posts_e2e`)
291 const commentsRecordApi = client.records<CommentRecord>(`comments_e2e`)
292​
293 // Insert seed data - we provide the ID so the original UUIDs are preserved
294 console.log(`Inserting ${seedData.users.length} users...`)
295 let userErrors = 0
296 for (const user of seedData.users) {
297 try {
298 const serialized = serializeUser(user)
299 if (userErrors === 0)
300 console.log('First user data:', JSON.stringify(serialized))
301 await usersRecordApi.create(serialized)
302 } catch (e) {
303 errors.push(e)
304 userErrors++
305 if (userErrors <= 3) console.error('User insert error:', e)
306 }
307 }
308 console.log(
309 `Inserted users: ${seedData.users.length - userErrors} success, ${userErrors} errors`,
310 )
311 console.log(`First user ID: ${seedData.users.at(0)?.id}`)
312​
313 console.log(`Inserting ${seedData.posts.length} posts...`)
314 let postErrors = 0
315 for (const post of seedData.posts) {
316 try {
317 await postsRecordApi.create(serializePost(post))
318 } catch (e) {
319 errors.push(e)
320 postErrors++
321 if (postErrors <= 3) console.error('Post insert error:', e)
322 }
323 }
324 console.log(
325 `Inserted posts: ${seedData.posts.length - postErrors} success, ${postErrors} errors`,
326 )
327​
328 console.log(`Inserting ${seedData.comments.length} comments...`)
329 let commentErrors = 0
330 for (const comment of seedData.comments) {
331 try {
332 await commentsRecordApi.create(serializeComment(comment))
333 } catch (e) {
334 errors.push(e)
335 commentErrors++
336 if (commentErrors <= 3) console.error('Comment insert error:', e)
337 }
338 }
339 console.log(
340 `Inserted comments: ${seedData.comments.length - commentErrors} success, ${commentErrors} errors`,
341 )
342 if (errors.length > 0)
343 throw new AggregateError(errors, 'TrailBase fixture insertions failed')
345​
346describe(`TrailBase Collection E2E Tests`, async () => {
347 const baseUrl = inject(`baseUrl`)
348 const client = initClient(baseUrl)
349 const cleanups: Array<() => Promise<void>> = []
350 const own = (collection: { cleanup: () => Promise<void> }) => {
351 cleanups.push(() => collection.cleanup())
352 }
353 afterEach(async () => {
354 const errors: Array<unknown> = []
355 for (const cleanup of cleanups.splice(0).reverse()) {
356 try {
357 await cleanup()
358 } catch (error) {
359 errors.push(error)
360 }
361 }
362 if (errors.length === 1) throw errors[0]
363 if (errors.length > 1)
364 throw new AggregateError(errors, 'TrailBase collection cleanup failed')
365 })
366​
367 // Wipe all pre-existing data, e.g. when using a persistent TB instance.
368 await initialCleanup(client)
369​
370 const seedData = generateSeedData()
371 const fixture = captureSeedData(seedData, {
372 registration: 'packages/trailbase-db-collection/e2e/trailbase.e2e.test.ts',
373 provider: 'TrailBase SDK with test service',
374 })
375 await setupInitialData(client, seedData)
376​
377 async function getConfig(): Promise<E2ETestConfig> {
378 // Create collections with different sync modes
379 const testId = Date.now().toString(16)
380​
381 const onDemandCollections = createCollectionsForSyncMode(
382 client,
383 testId,
384 `on-demand`,
385 `ondemand`,
386 own,
387 )
388​
389 // On-demand collections are marked ready immediately
390 await Promise.all([
391 onDemandCollections.users.preload(),
392 onDemandCollections.posts.preload(),
393 onDemandCollections.comments.preload(),
394 ])
395​
396 const eagerCollections = createCollectionsForSyncMode(
397 client,
398 testId,
399 `eager`,
400 `eager`,
401 own,
402 )
403​
404 // Wait for eager collections to sync (they need to fetch all data before marking ready)
405 // console.log('Calling preload on eager collections...')
406 await Promise.all([
407 eagerCollections.users.preload(),
408 eagerCollections.posts.preload(),
409 eagerCollections.comments.preload(),
410 ])
411 expect(eagerCollections.posts.size).toEqual(seedData.posts.length)
412 expect(eagerCollections.comments.size).toEqual(seedData.comments.length)
413​
414 // NOTE: One of the tests deletes a user :/
415 expect(eagerCollections.users.size).toBeGreaterThanOrEqual(
416 seedData.users.length - 1,
417 )
418​
419 const usersRecordApi = client.records<UserRecord>(`users_e2e`)
420 const postsRecordApi = client.records<PostRecord>(`posts_e2e`)
421​
422 return {
423 fixture,
424 collections: {
425 eager: {
426 users: eagerCollections.users,
427 posts: eagerCollections.posts,
428 comments: eagerCollections.comments,
429 },
430 onDemand: {
431 users: onDemandCollections.users,
432 posts: onDemandCollections.posts,
433 comments: onDemandCollections.comments,
434 },
435 },
436 hasReplicationLag: true, // TrailBase has async subscription-based sync
437 // Note: progressiveTestControl is not provided because the explicit snapshot/swap
438 // transition tests require Electric-specific sync behavior that TrailBase doesn't support.
439 // Tests that require this will be skipped.
440 mutations: {
441 insertUser: async (user) => {
442 // Insert with the provided ID (base64-encoded UUID)
443 await usersRecordApi.create(serializeUser(user))
444 // ID is preserved from the user object
445 },
446 updateUser: async (id, updates) => {
447 const partialRecord: Partial<UserRecord> = {}
448 if (updates.age !== undefined) partialRecord.age = updates.age
449 if (updates.name !== undefined) partialRecord.name = updates.name
450 if (updates.email !== undefined) partialRecord.email = updates.email
451 if (updates.isActive !== undefined)
452 partialRecord.isActive = updates.isActive ? 1 : 0
453 await usersRecordApi.update(id, partialRecord)
454 },
455 deleteUser: async (id) => {
456 await usersRecordApi.delete(id)
457 },
458 insertPost: async (post) => {
459 // Insert with the provided ID
460 await postsRecordApi.create(serializePost(post))
461 },
462 deletePost: async (id) => {
463 await postsRecordApi.delete(id)
464 },
465 },
466 setup: async () => {},
467 teardown: async () => {
468 await Promise.all([
469 eagerCollections.users.cleanup(),
470 eagerCollections.posts.cleanup(),
471 eagerCollections.comments.cleanup(),
472 onDemandCollections.users.cleanup(),
473 onDemandCollections.posts.cleanup(),
474 onDemandCollections.comments.cleanup(),
475 ])
476 },
477 }
478 }
479​
480 // Run all shared test suites
481 createPredicatesTestSuite(getConfig)
482 createPaginationTestSuite(getConfig)
483 createJoinsTestSuite(getConfig)
484 createDeduplicationTestSuite(getConfig)
485 createCollationTestSuite(getConfig)
486 createMutationsTestSuite(getConfig)
487 createLiveUpdatesTestSuite(getConfig)
488 createProgressiveTestSuite(getConfig)
489})