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

cache-claim-notice.opfs.ts

453 lines14.0 KB

1/**
2 * Browser receiver for cache-claim-notice.opfs.spec.ts. Two real Chromium
3 * contexts share OPFS, Web Locks, and BroadcastChannel. The test controls one
4 * subscriber callback after native delivery; it never constructs or publishes
5 * a notice. One history uses a small deterministic provider. The paired
6 * history uses the installed Electric SDK with controlled HTTP responses in
7 * the expired tab while the warm tab commits through the deterministic source.
8 * Both use real OPFS storage and native BroadcastChannel delivery.
9 */
10import { createCollection } from '@tanstack/db'
11import { electricCollectionOptions } from '../../electric-db-collection/src/electric'
12import {
13 BrowserCollectionCoordinator,
14 createBrowserWASQLitePersistence,
15 openBrowserWASQLiteOPFSDatabase,
16 persistedCollectionOptions,
17} from '../src'
18import type { Collection, SyncConfig } from '@tanstack/db'
19import type { ProtocolEnvelope } from '@tanstack/db-sqlite-persistence-core'
20​
21type Row = { id: string; title: string }
22export type Observation = {
23 phase: `starting` | `ready` | `failed`
24 failure?: string
25 storageId?: string
26 isLeader: boolean
27 publicIds: Array<string>
28 sourceLoads: Array<boolean | undefined>
29 pendingDemand: `not-started` | `pending` | `fulfilled` | `rejected`
30 pendingDemandError?: string
31 refetchEntered: boolean
32 heldNotices: number
33 receivedPeerNotices: Array<string>
34 postedPeerNotices: Array<string>
36type DurableObservation = {
37 head: string
38 claims: Array<{
39 physicalId: string
40 ids: Array<string>
41 metadata: Array<string>
42 }>
44type Probe = {
45 observe: () => Observation
46 demand: () => Promise<void>
47 beginPendingDemand: () => void
48 holdPeerNotices: () => void
49 releasePeerNotices: () => void
50 advanceClock: (now: number) => void
51 commitPeer: () => Promise<void>
52 releaseRefetch: () => void
53 durable: () => Promise<DurableObservation>
54 cleanup: () => Promise<Array<string>>
56declare global {
57 interface Window {
58 __cacheClaimNoticeProbe?: Probe
59 }
61​
62const parameters = new URL(location.href).searchParams
63const databaseId = parameters.get(`databaseId`)
64const role = parameters.get(`role`)
65const provider = parameters.get(`provider`) ?? `controlled`
66const initialNow = Number(parameters.get(`now`))
67if (
68 !databaseId ||
69 (role !== `expired` && role !== `warm`) ||
70 (provider !== `controlled` && provider !== `electric`) ||
71 (provider === `electric` && role !== `expired`) ||
72 !Number.isSafeInteger(initialNow)
73) {
74 throw new Error(`Invalid cache-claim notice parameters`)
76​
77const logicalId = `cache-claim-notice`
78let hostNow = initialNow
79let phase: Observation[`phase`] = `starting`
80let failure: string | undefined
81let storageId: string | undefined
82let collection: Collection<Row, string | number> | undefined
83let coordinator: BrowserCollectionCoordinator | undefined
84let database:
85 Awaited<ReturnType<typeof openBrowserWASQLiteOPFSDatabase>> | undefined
86let persistence: ReturnType<typeof createBrowserWASQLitePersistence> | undefined
87let source: Parameters<SyncConfig<Row, string | number>[`sync`]>[0] | undefined
88let seeded = false
89let refetchEntered = false
90let refreshStarted = false
91let pendingDemand: Observation[`pendingDemand`] = `not-started`
92let pendingDemandError: string | undefined
93let pendingDemandPromise: Promise<void> | undefined
94let holdNotices = false
95let releaseRefetch = () => {}
96const refetchRelease = new Promise<void>((resolve) => {
97 releaseRefetch = resolve
98})
99let releaseFreshApplied = () => {}
100const freshApplied = new Promise<void>((resolve) => {
101 releaseFreshApplied = resolve
102})
103const heldNotices: Array<() => void> = []
104const receivedPeerNotices: Array<string> = []
105const postedPeerNotices: Array<string> = []
106const sourceLoads: Array<boolean | undefined> = []
107let firstElectricStorageId: string | undefined
108let electricSnapshotNumber = 0
109let initialElectricLiveDelivered = false
110const pendingElectricRequests = new Set<() => void>()
111​
112function electricSnapshotResponse(row: Row): Response {
113 const offset = ++electricSnapshotNumber
114 return new Response(
115 JSON.stringify({
116 metadata: {
117 xmin: `10`,
118 xmax: `20`,
119 xip_list: [],
120 database_lsn: `10`,
121 snapshot_mark: offset,
122 },
123 data: [
124 {
125 key: row.id,
126 value: row,
127 headers: { operation: `insert` },
128 },
129 ],
130 }),
131 {
132 headers: {
133 'electric-handle': `shape`,
134 'electric-offset': `${offset}_0`,
135 'electric-cursor': String(offset),
136 'electric-up-to-date': `true`,
137 'electric-schema': JSON.stringify({
138 id: { type: `text` },
139 title: { type: `text` },
140 }),
141 },
142 },
143 )
145​
146function holdElectricRequest(signal?: AbortSignal): Promise<Response> {
147 return new Promise<Response>((_resolve, reject) => {
148 const abort = () => {
149 signal?.removeEventListener(`abort`, abort)
150 pendingElectricRequests.delete(abort)
151 reject(
152 signal?.reason ?? new DOMException(`Request aborted`, `AbortError`),
153 )
154 }
155 if (signal?.aborted) {
156 abort()
157 return
158 }
159 pendingElectricRequests.add(abort)
160 signal?.addEventListener(`abort`, abort, { once: true })
161 })
163​
164const electricFetch: typeof fetch = (input, init) => {
165 const url = new URL(String(input), location.href)
166 const isSubset = [...url.searchParams.keys()].some((key) =>
167 key.startsWith(`subset__`),
168 )
169 if (!isSubset) {
170 if (!initialElectricLiveDelivered) {
171 initialElectricLiveDelivered = true
172 return Promise.resolve(
173 new Response(
174 JSON.stringify([
175 { headers: { control: `up-to-date`, global_last_seen_lsn: `1` } },
176 ]),
177 {
178 headers: {
179 'electric-handle': `shape`,
180 'electric-offset': `0_0`,
181 'electric-cursor': `0`,
182 'electric-up-to-date': `true`,
183 'electric-schema': JSON.stringify({
184 id: { type: `text` },
185 title: { type: `text` },
186 }),
187 },
188 },
189 ),
190 )
191 }
192 return holdElectricRequest(init?.signal ?? undefined)
193 }
194 sourceLoads.push(undefined)
195 firstElectricStorageId ??= storageId
196 if (!seeded) {
197 seeded = true
198 return Promise.resolve(
199 electricSnapshotResponse({ id: `old`, title: `Warm source row` }),
200 )
201 }
202 if (storageId === firstElectricStorageId) {
203 return holdElectricRequest(init?.signal ?? undefined)
204 }
205 refetchEntered = true
206 return refetchRelease.then(() =>
207 electricSnapshotResponse({ id: `fresh`, title: `Fresh source row` }),
208 )
210​
211let originalPostMessage:
212 typeof BroadcastChannel.prototype.postMessage | undefined
213​
214const peerNoticeId = (message: unknown): string | undefined => {
215 if (typeof message !== `object` || message === null) return undefined
216 const envelope = message as {
217 collectionId?: string
218 payload?: {
219 type?: string
220 changedRows?: Array<{ key?: string | number }>
221 }
222 }
223 return envelope.payload?.type === `tx:committed` &&
224 envelope.payload.changedRows?.some(({ key }) => key === `peer`)
225 ? envelope.collectionId
226 : undefined
228​
229async function commit(row: Row): Promise<void> {
230 if (!source) throw new Error(`Source is unavailable`)
231 source.begin()
232 source.write({ type: `insert`, value: row })
233 const receipt = source.commit()
234 if (receipt === true) throw new Error(`Source receipt was untracked`)
235 await receipt
237​
238window.__cacheClaimNoticeProbe = {
239 observe: () => ({
240 phase,
241 ...(failure ? { failure } : {}),
242 storageId,
243 isLeader: storageId ? (coordinator?.isLeader(storageId) ?? false) : false,
244 publicIds: collection ? [...collection.keys()].map(String).sort() : [],
245 sourceLoads: [...sourceLoads],
246 pendingDemand,
247 ...(pendingDemandError ? { pendingDemandError } : {}),
248 refetchEntered,
249 heldNotices: heldNotices.length,
250 receivedPeerNotices: [...receivedPeerNotices],
251 postedPeerNotices: [...postedPeerNotices],
252 }),
253 demand: async () => {
254 if (!collection) throw new Error(`Collection is unavailable`)
255 await collection._sync.loadSubset({ limit: 2 })
256 },
257 beginPendingDemand: () => {
258 if (!collection) throw new Error(`Collection is unavailable`)
259 if (pendingDemand !== `not-started`) {
260 throw new Error(`Pending demand already started`)
261 }
262 pendingDemand = `pending`
263 pendingDemandPromise = Promise.resolve(
264 collection._sync.loadSubset({ limit: 1 }),
265 ).then(
266 () => {
267 pendingDemand = `fulfilled`
268 },
269 (error: unknown) => {
270 pendingDemand = `rejected`
271 pendingDemandError = String(error)
272 },
273 )
274 },
275 holdPeerNotices: () => {
276 holdNotices = true
277 },
278 releasePeerNotices: () => {
279 holdNotices = false
280 for (const deliver of heldNotices.splice(0)) deliver()
281 },
282 advanceClock: (now) => {
283 hostNow = now
284 },
285 commitPeer: () => commit({ id: `peer`, title: `Peer source row` }),
286 releaseRefetch: () => releaseRefetch(),
287 durable: async () => {
288 if (!database || !persistence) throw new Error(`Persistence unavailable`)
289 const headRows = await database.execute<{ physical_id: string }>(
290 `SELECT physical_id FROM cache_generation
291 WHERE logical_id = ? AND retired = 0`,
292 [logicalId],
293 )
294 const head = headRows[0]?.physical_id
295 if (!head) throw new Error(`No current cache generation`)
296 const claims = await database.execute<{
297 physical_id: string
298 claim_id: string
299 }>(
300 `SELECT physical_id, claim_id FROM cache_generation_claim
301 WHERE logical_id = ? AND expires_at_ms > ? ORDER BY physical_id`,
302 [logicalId, hostNow],
303 )
304 const adapter = persistence.resolvePersistenceForCollection!({
305 collectionId: logicalId,
306 mode: `sync-present`,
307 }).adapter
308 const snapshots = await Promise.all(
309 claims.map(async ({ physical_id, claim_id }) => {
310 const snapshot = await adapter.loadResumeSnapshot(
311 {
312 kind: `managed`,
313 storageCollectionId: physical_id,
314 claimId: claim_id,
315 },
316 {
317 cacheGenerationClaimId: claim_id,
318 },
319 )
320 return {
321 physicalId: physical_id,
322 ids: snapshot.rows.map(({ key }) => String(key)).sort(),
323 metadata: snapshot.collectionMetadata.map(({ key }) => key).sort(),
324 }
325 }),
326 )
327 return { head, claims: snapshots }
328 },
329 cleanup: async () => {
330 for (const abort of [...pendingElectricRequests]) {
331 abort()
332 }
333 releaseRefetch()
334 releaseFreshApplied()
335 holdNotices = false
336 for (const deliver of heldNotices.splice(0)) deliver()
337 const failures: Array<string> = []
338 try {
339 await collection?.cleanup()
340 } catch (error) {
341 failures.push(`Collection: ${String(error)}`)
342 }
343 await pendingDemandPromise
344 try {
345 coordinator?.dispose()
346 } catch (error) {
347 failures.push(`Coordinator: ${String(error)}`)
348 }
349 try {
350 await database?.close?.()
351 } catch (error) {
352 failures.push(`OPFS: ${String(error)}`)
353 }
354 if (originalPostMessage) {
355 BroadcastChannel.prototype.postMessage = originalPostMessage
356 }
357 return failures
358 },
360​
361try {
362 originalPostMessage = BroadcastChannel.prototype.postMessage
363 BroadcastChannel.prototype.postMessage = function (message: unknown) {
364 const id = peerNoticeId(message)
365 if (id) postedPeerNotices.push(id)
366 return originalPostMessage!.call(this, message)
367 }
368 database = await openBrowserWASQLiteOPFSDatabase({
369 databaseName: `${databaseId}.sqlite`,
370 })
371 coordinator = new BrowserCollectionCoordinator({ dbName: databaseId })
372 const subscribe = coordinator.subscribe.bind(coordinator)
373 coordinator.subscribe = (id, callback) =>
374 subscribe(id, (message: ProtocolEnvelope<unknown>) => {
375 const peerId = peerNoticeId(message)
376 if (peerId) {
377 receivedPeerNotices.push(peerId)
378 if (holdNotices) {
379 heldNotices.push(() => callback(message))
380 return
381 }
382 }
383 callback(message)
384 })
385 const setAdapter = coordinator.setAdapterForCollection.bind(coordinator)
386 coordinator.setAdapterForCollection = (id, adapter, claimId) => {
387 if (claimId) storageId = id
388 setAdapter(id, adapter, claimId)
389 }
390 persistence = createBrowserWASQLitePersistence({
391 database,
392 coordinator,
393 cacheGenerationClaimTtlMs: 300_000,
394 now: () => hostNow,
395 })
396 const electricSync =
397 provider === `electric`
398 ? electricCollectionOptions<Row>({
399 id: logicalId,
400 shapeOptions: {
401 url: `${location.origin}/electric/v1/shape`,
402 params: { table: `public.cache_claim_notice` },
403 fetchClient: electricFetch,
404 },
405 syncMode: `on-demand`,
406 getKey: (row) => row.id,
407 }).sync
408 : undefined
409 collection = createCollection(
410 persistedCollectionOptions<Row, string | number>({
411 id: logicalId,
412 syncMode: `on-demand`,
413 getKey: (row) => row.id,
414 persistence,
415 sync: electricSync ?? {
416 sync: (params) => {
417 source = params
418 params.markReady()
419 return {
420 restartAfterScopedRecovery: () => {},
421 loadSubset: async (options) => {
422 sourceLoads.push(options.refetch)
423 if (role !== `expired`) return
424 if (options.refetch) {
425 if (!refreshStarted) {
426 refreshStarted = true
427 refetchEntered = true
428 await refetchRelease
429 await commit({ id: `fresh`, title: `Fresh source row` })
430 releaseFreshApplied()
431 } else {
432 await freshApplied
433 }
434 } else if (options.limit === 1) {
435 await freshApplied
436 } else if (!seeded) {
437 seeded = true
438 await commit({ id: `old`, title: `Warm source row` })
439 }
440 },
441 }
442 },
443 },
444 }),
445 )
446 collection.startSyncImmediate()
447 await collection.stateWhenReady()
448 phase = `ready`
449} catch (error) {
450 failure =
451 error instanceof Error ? `${error.name}: ${error.message}` : String(error)
452 phase = `failed`