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

OutboxManager.ts

166 lines5.0 KB

1import {
2 MissingTemporalConstructorError,
3 TransactionSerializer,
4} from './TransactionSerializer'
5import type { OfflineTransaction, StorageAdapter } from '../types'
6import type { Collection } from '@tanstack/db'
7​
8export class OutboxTransactionNotFoundError extends Error {}
9​
10export class OutboxManager {
11 private storage: StorageAdapter
12 private serializer: TransactionSerializer
13 private keyPrefix = `tx:`
14 private removalRevision = 0
15 private activeReads = new Set<{ revision: number }>()
16 private removedAtRevision = new Map<string, number>()
17​
18 constructor(
19 storage: StorageAdapter,
20​
21 collections: Record<string, Collection<any, any, any, any, any>>,
22 ) {
23 this.storage = storage
24 this.serializer = new TransactionSerializer(collections)
25 }
26​
27 private getStorageKey(id: string): string {
28 return `${this.keyPrefix}${id}`
29 }
30​
31 private recordRemovals(ids: Iterable<string>): void {
32 this.removalRevision++
33 if (this.activeReads.size === 0) return
34 for (const id of ids) this.removedAtRevision.set(id, this.removalRevision)
35 this.pruneRemovalHistory()
36 }
37​
38 private pruneRemovalHistory(): void {
39 if (this.activeReads.size === 0) {
40 this.removedAtRevision.clear()
41 return
42 }
43 let oldestRead = Number.POSITIVE_INFINITY
44 for (const read of this.activeReads)
45 oldestRead = Math.min(oldestRead, read.revision)
46 for (const [id, revision] of this.removedAtRevision)
47 if (revision <= oldestRead) this.removedAtRevision.delete(id)
48 }
49​
50 async add(transaction: OfflineTransaction): Promise<void> {
51 const key = this.getStorageKey(transaction.id)
52 const serialized = this.serializer.serialize(transaction)
53 await this.storage.set(key, serialized)
54 }
55​
56 async get(id: string): Promise<OfflineTransaction | null> {
57 const key = this.getStorageKey(id)
58 const data = await this.storage.get(key)
59 if (!data) return null
60​
61 try {
62 return this.serializer.deserialize(data)
63 } catch (error) {
64 if (error instanceof MissingTemporalConstructorError) {
65 error.message = `transaction ${id}: ${error.message}`
66 throw error
67 }
68 console.warn(`Failed to deserialize transaction ${id}:`, error)
69 return null
70 }
71 }
72​
73 async getAll(): Promise<Array<OfflineTransaction>> {
74 return this.withAll((transactions) => transactions)
75 }
76​
77 async withAll<T>(
78 consume: (transactions: Array<OfflineTransaction>) => T,
79 ): Promise<T> {
80 const read = { revision: this.removalRevision }
81 this.activeReads.add(read)
82 try {
83 const keys = await this.storage.keys()
84 const transactionKeys = keys.filter((key) =>
85 key.startsWith(this.keyPrefix),
86 )
87​
88 const transactions: Array<OfflineTransaction> = []
89​
90 for (const key of transactionKeys) {
91 const data = await this.storage.get(key)
92 if (data) {
93 try {
94 const transaction = this.serializer.deserialize(data)
95 transactions.push(transaction)
96 } catch (error) {
97 if (error instanceof MissingTemporalConstructorError) {
98 error.message = `transaction ${key.slice(this.keyPrefix.length)}: ${error.message}`
99 throw error
100 }
101 console.warn(
102 `Failed to deserialize transaction from key ${key}:`,
103 error,
104 )
105 }
106 }
107 }
108​
109 const currentTransactions = transactions
110 .filter(
111 ({ id }) => (this.removedAtRevision.get(id) ?? 0) <= read.revision,
112 )
113 .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
114 // Keep the read registered until replay admission completes. A durable
115 // removal cannot land between filtering and this synchronous consumer.
116 return await consume(currentTransactions)
117 } finally {
118 this.activeReads.delete(read)
119 this.pruneRemovalHistory()
120 }
121 }
122​
123 async getByKeys(keys: Array<string>): Promise<Array<OfflineTransaction>> {
124 const allTransactions = await this.getAll()
125 const keySet = new Set(keys)
126​
127 return allTransactions.filter((transaction) =>
128 transaction.keys.some((key) => keySet.has(key)),
129 )
130 }
131​
132 async update(
133 id: string,
134 updates: Partial<OfflineTransaction>,
135 ): Promise<void> {
136 const existing = await this.get(id)
137 if (!existing) {
138 throw new OutboxTransactionNotFoundError(`Transaction ${id} not found`)
139 }
140 await this.add({ ...existing, ...updates })
141 }
142​
143 async remove(id: string): Promise<void> {
144 const key = this.getStorageKey(id)
145 await this.storage.delete(key)
146 this.recordRemovals([id])
147 }
148​
149 async removeMany(ids: Array<string>): Promise<void> {
150 await Promise.all(ids.map((id) => this.remove(id)))
151 }
152​
153 async clear(): Promise<void> {
154 const keys = await this.storage.keys()
155 const transactionKeys = keys.filter((key) => key.startsWith(this.keyPrefix))
156​
157 await this.removeMany(
158 transactionKeys.map((key) => key.slice(this.keyPrefix.length)),
159 )
160 }
161​
162 async count(): Promise<number> {
163 const keys = await this.storage.keys()
164 return keys.filter((key) => key.startsWith(this.keyPrefix)).length
165 }