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

OutboxManager.ts

198 lines6.2 KB

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