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

trailbase.e2e.test.ts

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