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

lifecycle-support.ts

76 lines2.1 KB

1import { vi } from 'vitest'
2import type { Event, ListResponse } from 'trailbase'
3​
4/**
5 * Shared controls for the TrailBase lifecycle tests. The gated source, the
6 * settle helpers, and the row type serve both lifecycle-oracle.property.test.ts,
7 * which owns the lifecycle laws, and lifecycle.test.ts, which holds the
8 * hand-written startup control.
9 */
10​
11export type Row = { id: number; value: number }
12​
13export function deferred<T>() {
14 let resolve!: (value: T) => void
15 let reject!: (error: unknown) => void
16 const promise = new Promise<T>((yes, no) => {
17 resolve = yes
18 reject = no
19 })
20 // Every adapter promise is observed even when its sync run is abandoned.
21 void promise.catch(() => undefined)
22 return { promise, resolve, reject }
24​
25export function observe(promise: Promise<unknown>) {
26 let result: `pending` | `fulfilled` | `rejected` = `pending`
27 let error: unknown
28 void promise.then(
29 () => {
30 result = `fulfilled`
31 },
32 (failure: unknown) => {
33 result = `rejected`
34 error = failure
35 },
36 )
37 return {
38 get result() {
39 return result
40 },
41 get error() {
42 return error
43 },
44 }
46​
47// All adapter I/O is gated. One host turn drains native stream microtasks and
48// exposes detached rejections; it does not stand in for a network completion.
49export const turn = () => new Promise<void>((resolve) => setTimeout(resolve, 0))
50export const failure = new Error(`oracle stream failure`)
51export const invalidValue = -10_000
52​
53export function source() {
54 let controller!: ReadableStreamDefaultController<Event>
55 const cancel = vi.fn((): void | Promise<void> => {})
56 const stream = new ReadableStream<Event>({
57 start(value) {
58 controller = value
59 },
60 cancel,
61 })
62 return {
63 stream,
64 cancel,
65 controller,
66 subscription: deferred<ReadableStream<Event>>(),
67 list: deferred<ListResponse<Row>>(),
68 listCalls: 0,
69 }
71​
72export type RaceRow = { id: number; data: string }
73​
74// Compare only the row fields; the Collection adds virtual properties.
75export const sortedRows = (rows: Iterable<RaceRow>) =>
76 [...rows].map(({ id, data }) => ({ id, data })).sort((a, b) => a.id - b.id)