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

OutboxManager.ts

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