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