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

do-driver.ts

266 lines7.6 KB

1import { InvalidPersistedCollectionConfigError } from '@tanstack/db-sqlite-persistence-core'
2import type { SQLiteDriver } from '@tanstack/db-sqlite-persistence-core'
3​
4type DurableObjectSqlRow = Record<string, unknown>
5​
6type DurableObjectSqlCursorLike = Iterable<DurableObjectSqlRow> & {
7 toArray?: () => Array<DurableObjectSqlRow>
8}
9​
10export type DurableObjectSqlStorageLike = {
11 exec: (
12 sql: string,
13 ...params: ReadonlyArray<unknown>
14 ) => DurableObjectSqlCursorLike | ReadonlyArray<DurableObjectSqlRow> | null
16​
17export type DurableObjectTransactionExecutor = <T>(
18 fn: () => Promise<T>,
19) => Promise<T>
20​
21export type DurableObjectStorageLike = {
22 sql: DurableObjectSqlStorageLike
23 transaction?: DurableObjectTransactionExecutor
25​
26type CloudflareDOProvidedSqlOptions = {
27 sql: DurableObjectSqlStorageLike
28 transaction?: DurableObjectTransactionExecutor
30​
31type CloudflareDOProvidedStorageOptions = {
32 storage: DurableObjectStorageLike
34​
35export type CloudflareDOSQLiteDriverOptions =
36 | CloudflareDOProvidedSqlOptions
37 | CloudflareDOProvidedStorageOptions
38​
39function assertTransactionCallbackHasDriverArg(
40 fn: (transactionDriver: SQLiteDriver) => Promise<unknown>,
41): void {
42 if (fn.length > 0) {
43 return
44 }
45​
46 throw new InvalidPersistedCollectionConfigError(
47 `SQLiteDriver.transaction callback must accept the transaction driver argument`,
48 )
50​
51function isIterableRecord(
52 value: unknown,
53): value is Iterable<DurableObjectSqlRow> {
54 if (!value || typeof value !== `object`) {
55 return false
56 }
57​
58 const iterator = (value as { [Symbol.iterator]?: unknown })[Symbol.iterator]
59 return typeof iterator === `function`
61​
62function toRowArray<T>(
63 result: ReturnType<DurableObjectSqlStorageLike[`exec`]>,
64 sql: string,
65): ReadonlyArray<T> {
66 if (result == null) {
67 return []
68 }
69​
70 if (Array.isArray(result)) {
71 return result as ReadonlyArray<T>
72 }
73​
74 const cursorResult = result as DurableObjectSqlCursorLike
75 if (typeof cursorResult.toArray === `function`) {
76 return cursorResult.toArray() as ReadonlyArray<T>
77 }
78​
79 if (isIterableRecord(cursorResult)) {
80 return Array.from(cursorResult as Iterable<T>)
81 }
82​
83 throw new InvalidPersistedCollectionConfigError(
84 `Unsupported Durable Object SQL result shape for query "${sql}"`,
85 )
87​
88export class CloudflareDOSQLiteDriver implements SQLiteDriver {
89 // https://developers.cloudflare.com/durable-objects/platform/limits/
90 // Durable Object SQL storage permits at most 100 bound parameters per query.
91 readonly maxBoundParameters = 100
92 private readonly sqlStorage: DurableObjectSqlStorageLike
93 private readonly storage: DurableObjectStorageLike
94 private readonly transactionExecutor: DurableObjectTransactionExecutor | null
95 private queue: Promise<void> = Promise.resolve()
96 private nextSavepointId = 1
97​
98 constructor(options: CloudflareDOSQLiteDriverOptions) {
99 const resolvedStorage: DurableObjectStorageLike =
100 `storage` in options
101 ? options.storage
102 : {
103 sql: options.sql,
104 ...(typeof options.transaction === `function`
105 ? { transaction: options.transaction }
106 : {}),
107 }
108 const resolvedSqlStorage = resolvedStorage.sql
109 if (typeof resolvedSqlStorage.exec !== `function`) {
110 throw new InvalidPersistedCollectionConfigError(
111 `Cloudflare DO SQL driver requires a sql.exec function`,
112 )
113 }
114 this.storage = resolvedStorage
115 this.sqlStorage = resolvedSqlStorage
116 if (typeof resolvedStorage.transaction === `function`) {
117 const transactionMethod = resolvedStorage.transaction
118 this.transactionExecutor = <T>(fn: () => Promise<T>) =>
119 Promise.resolve(
120 transactionMethod.call(resolvedStorage, fn) as Promise<T> | T,
121 )
122 } else {
123 this.transactionExecutor = null
124 }
125 }
126​
127 async exec(sql: string): Promise<void> {
128 await this.enqueue(() => {
129 this.execute(sql)
130 })
131 }
132​
133 async query<T>(
134 sql: string,
135 params: ReadonlyArray<unknown> = [],
136 ): Promise<ReadonlyArray<T>> {
137 return this.enqueue(() => this.executeQuery<T>(sql, params))
138 }
139​
140 async run(sql: string, params: ReadonlyArray<unknown> = []): Promise<void> {
141 await this.enqueue(() => {
142 this.execute(sql, params)
143 })
144 }
145​
146 async transaction<T>(
147 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
148 ): Promise<T> {
149 assertTransactionCallbackHasDriverArg(fn)
150​
151 return this.enqueue(async () => {
152 const transactionDriver = this.createTransactionDriver()
153 if (this.transactionExecutor) {
154 return this.transactionExecutor(() => fn(transactionDriver))
155 }
156​
157 this.execute(`BEGIN IMMEDIATE`)
158 try {
159 const result = await fn(transactionDriver)
160 this.execute(`COMMIT`)
161 return result
162 } catch (error) {
163 try {
164 this.execute(`ROLLBACK`)
165 } catch {
166 // Keep the original transaction error as the primary failure.
167 }
168 throw error
169 }
170 })
171 }
172​
173 async transactionWithDriver<T>(
174 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
175 ): Promise<T> {
176 return this.transaction(fn)
177 }
178​
179 getStorage(): DurableObjectStorageLike {
180 return this.storage
181 }
182​
183 private execute(sql: string, params: ReadonlyArray<unknown> = []): unknown {
184 return this.sqlStorage.exec(sql, ...params)
185 }
186​
187 private executeQuery<T>(
188 sql: string,
189 params: ReadonlyArray<unknown>,
190 ): ReadonlyArray<T> {
191 const result = this.execute(sql, params)
192 return toRowArray<T>(
193 result as ReturnType<DurableObjectSqlStorageLike[`exec`]>,
194 sql,
195 )
196 }
197​
198 private enqueue<T>(operation: () => Promise<T> | T): Promise<T> {
199 const queuedOperation = this.queue.then(operation, operation)
200 this.queue = queuedOperation.then(
201 () => undefined,
202 () => undefined,
203 )
204 return queuedOperation
205 }
206​
207 private createTransactionDriver(): SQLiteDriver {
208 const transactionDriver: SQLiteDriver = {
209 exec: (sql) => {
210 this.execute(sql)
211 return Promise.resolve()
212 },
213 query: <T>(
214 sql: string,
215 params: ReadonlyArray<unknown> = [],
216 ): Promise<ReadonlyArray<T>> =>
217 Promise.resolve(this.executeQuery<T>(sql, params)),
218 run: (sql, params = []) => {
219 this.execute(sql, params)
220 return Promise.resolve()
221 },
222 transaction: <T>(
223 fn: (nestedDriver: SQLiteDriver) => Promise<T>,
224 ): Promise<T> => {
225 assertTransactionCallbackHasDriverArg(fn)
226 return this.runNestedTransaction(transactionDriver, fn)
227 },
228 transactionWithDriver: <T>(
229 fn: (nestedDriver: SQLiteDriver) => Promise<T>,
230 ): Promise<T> => this.runNestedTransaction(transactionDriver, fn),
231 }
232​
233 return transactionDriver
234 }
235​
236 private async runNestedTransaction<T>(
237 transactionDriver: SQLiteDriver,
238 fn: (nestedDriver: SQLiteDriver) => Promise<T>,
239 ): Promise<T> {
240 if (this.transactionExecutor) {
241 throw new InvalidPersistedCollectionConfigError(
242 `Nested SQL savepoints are not supported when using Durable Object transaction API`,
243 )
244 }
245​
246 const savepointName = `tsdb_sp_${this.nextSavepointId}`
247 this.nextSavepointId++
248 this.execute(`SAVEPOINT ${savepointName}`)
249​
250 try {
251 const result = await fn(transactionDriver)
252 this.execute(`RELEASE SAVEPOINT ${savepointName}`)
253 return result
254 } catch (error) {
255 this.execute(`ROLLBACK TO SAVEPOINT ${savepointName}`)
256 this.execute(`RELEASE SAVEPOINT ${savepointName}`)
257 throw error
258 }
259 }
261​
262export function createCloudflareDOSQLiteDriver(
263 options: CloudflareDOSQLiteDriverOptions,
264): CloudflareDOSQLiteDriver {
265 return new CloudflareDOSQLiteDriver(options)