Open History to see the last commit
1import { withSpan } from '../telemetry/tracer'
2import { TransactionSerializer } from './TransactionSerializer'
3import type { OfflineTransaction, StorageAdapter } from '../types'
4import type { Collection } from '@tanstack/db'
5
6export class OutboxManager {
7 private storage: StorageAdapter
8 private serializer: TransactionSerializer
9 private keyPrefix = `tx:`
10
11 constructor(
12 storage: StorageAdapter,
13
14 collections: Record<string, Collection<any, any, any, any, any>>,
15 ) {
16 this.storage = storage
17 this.serializer = new TransactionSerializer(collections)
18 }
19
20 private getStorageKey(id: string): string {
21 return `${this.keyPrefix}${id}`
22 }
23
24 async add(transaction: OfflineTransaction): Promise<void> {
25 return withSpan(
26 `outbox.add`,
27 {
28 'transaction.id': transaction.id,
29 'transaction.mutationFnName': transaction.mutationFnName,
30 'transaction.keyCount': transaction.keys.length,
31 },
32 async () => {
33 const key = this.getStorageKey(transaction.id)
34 const serialized = this.serializer.serialize(transaction)
35 await this.storage.set(key, serialized)
36 },
37 )
38 }
39
40 async get(id: string): Promise<OfflineTransaction | null> {
41 return withSpan(`outbox.get`, { 'transaction.id': id }, async (span) => {
42 const key = this.getStorageKey(id)
43 const data = await this.storage.get(key)
44
45 if (!data) {
46 span.setAttribute(`result`, `not_found`)
47 return null
48 }
49
50 try {
51 const transaction = this.serializer.deserialize(data)
52 span.setAttribute(`result`, `found`)
53 return transaction
54 } catch (error) {
55 console.warn(`Failed to deserialize transaction ${id}:`, error)
56 span.setAttribute(`result`, `deserialize_error`)
57 return null
58 }
59 })
60 }
61
62 async getAll(): Promise<Array<OfflineTransaction>> {
63 return withSpan(`outbox.getAll`, {}, async (span) => {
64 const keys = await this.storage.keys()
65 const transactionKeys = keys.filter((key) =>
66 key.startsWith(this.keyPrefix),
67 )
68
69 span.setAttribute(`transactionCount`, transactionKeys.length)
70
71 const transactions: Array<OfflineTransaction> = []
72
73 for (const key of transactionKeys) {
74 const data = await this.storage.get(key)
75 if (data) {
76 try {
77 const transaction = this.serializer.deserialize(data)
78 transactions.push(transaction)
79 } catch (error) {
80 console.warn(
81 `Failed to deserialize transaction from key ${key}:`,
82 error,
83 )
84 }
85 }
86 }
87
88 return transactions.sort(
89 (a, b) => a.createdAt.getTime() - b.createdAt.getTime(),
90 )
91 })
92 }
93
94 async getByKeys(keys: Array<string>): Promise<Array<OfflineTransaction>> {
95 const allTransactions = await this.getAll()
96 const keySet = new Set(keys)
97
98 return allTransactions.filter((transaction) =>
99 transaction.keys.some((key) => keySet.has(key)),
100 )
101 }
102
103 async update(
104 id: string,
105 updates: Partial<OfflineTransaction>,
106 ): Promise<void> {
107 return withSpan(`outbox.update`, { 'transaction.id': id }, async () => {
108 const existing = await this.get(id)
109 if (!existing) {
110 throw new Error(`Transaction ${id} not found`)
111 }
112
113 const updated = { ...existing, ...updates }
114 await this.add(updated)
115 })
116 }
117
118 async remove(id: string): Promise<void> {
119 return withSpan(`outbox.remove`, { 'transaction.id': id }, async () => {
120 const key = this.getStorageKey(id)
121 await this.storage.delete(key)
122 })
123 }
124
125 async removeMany(ids: Array<string>): Promise<void> {
126 return withSpan(`outbox.removeMany`, { count: ids.length }, async () => {
127 await Promise.all(ids.map((id) => this.remove(id)))
128 })
129 }
130
131 async clear(): Promise<void> {
132 const keys = await this.storage.keys()
133 const transactionKeys = keys.filter((key) => key.startsWith(this.keyPrefix))
134
135 await Promise.all(transactionKeys.map((key) => this.storage.delete(key)))
136 }
137
138 async count(): Promise<number> {
139 const keys = await this.storage.keys()
140 return keys.filter((key) => key.startsWith(this.keyPrefix)).length
141 }
142}