Open History to see the last commit
1/**
2 * Connects Effect SQL to SQLite storage inside Cloudflare Durable Objects.
3 *
4 * Provides `SqliteClient` and the generic `SqlClient` service. Pass `db` for
5 * queries only, or `storage` for transactions and migrations. SQLite blobs are
6 * returned as `Uint8Array`; `updateValues` is unsupported.
7 *
8 * Transactions use `storage.transaction()` instead of transaction SQL, and
9 * hold the connection until storage completes. A failed or interrupted nested
10 * transaction rolls back only itself, unless the failure reaches the parent.
11 *
12 * Fibers that inherit the transaction context must finish their transaction
13 * work before the transaction exits; later use can bypass the connection
14 * semaphore.
15 *
16 * @stability unstable
17 * @since 4.0.0
18 */
19import type { DurableObjectStorage, DurableObjectTransaction, SqlStorage } from "@cloudflare/workers-types"
20import * as Cause from "effect/Cause"
21import * as Config from "effect/Config"
22import * as Context from "effect/Context"
23import * as Effect from "effect/Effect"
24import * as Exit from "effect/Exit"
25import { identity } from "effect/Function"
26import * as Layer from "effect/Layer"
27import * as Reactivity from "effect/reactivity/Reactivity"
28import * as Rec from "effect/Record"
29import * as Scheduler from "effect/Scheduler"
30import type * as Scope from "effect/Scope"
31import * as Semaphore from "effect/Semaphore"
32import * as Client from "effect/sql/SqlClient"
33import type { Connection } from "effect/sql/SqlConnection"
34import { classifySqliteError, SqlError, UnknownError } from "effect/sql/SqlError"
35import * as Statement from "effect/sql/Statement"
36import * as Stream from "effect/Stream"
37
38const ATTR_DB_SYSTEM_NAME = "db.system.name"
39
40const classifyError = (cause: unknown, message: string, operation: string) =>
41 classifySqliteError(cause, { message, operation })
42
43/**
44 * Runtime type identifier used to mark Cloudflare Durable Object `SqliteClient` values.
45 *
46 * @stability unstable
47 * @category type IDs
48 * @since 4.0.0
49 */
50export const TypeId: TypeId = "~@effect/sql-sqlite-do/SqliteClient"
51
52/**
53 * Type-level identifier used to mark Cloudflare Durable Object `SqliteClient` values.
54 *
55 * @stability unstable
56 * @category type IDs
57 * @since 4.0.0
58 */
59export type TypeId = "~@effect/sql-sqlite-do/SqliteClient"
60
61/**
62 * Cloudflare Durable Object SQLite client service, extending `SqlClient` with its configuration. `updateValues` is not supported.
63 *
64 * @stability unstable
65 * @category services
66 * @since 4.0.0
67 */
68export interface SqliteClient extends Client.Base {
69 readonly [TypeId]: TypeId
70 readonly config: SqliteClientConfig
71
72 /** Not supported in sqlite */
73 readonly updateValues: never
74}
75
76/**
77 * Service tag for the Cloudflare Durable Object SQLite client service.
78 *
79 * **When to use**
80 *
81 * Use to access or provide a Durable Object SQLite client through the Effect
82 * context.
83 *
84 * @stability unstable
85 * @category services
86 * @since 4.0.0
87 */
88export const SqliteClient = Context.Service<SqliteClient, SqliteClient & Client.SqlClient>(
89 "@effect/sql-sqlite-do/SqliteClient"
90)
91
92const SqliteTransaction = Context.Service<Client.TransactionConnection, Client.TransactionConnection.Service>(
93 "@effect/sql-sqlite-do/SqliteClient/SqliteTransaction"
94)
95
96/**
97 * Configuration for a Cloudflare Durable Object SQLite client, including either a `SqlStorage` handle or the full `DurableObjectStorage` for transaction support, span attributes, and query/result name transforms.
98 *
99 * @stability unstable
100 * @category models
101 * @since 4.0.0
102 */
103export interface SqliteClientConfig {
104 readonly db?: SqlStorage | undefined
105 readonly storage?: DurableObjectStorage | undefined
106 readonly spanAttributes?: Record<string, unknown> | undefined
107
108 readonly transformResultNames?: ((str: string) => string) | undefined
109 readonly transformQueryNames?: ((str: string) => string) | undefined
110}
111
112const unsupportedTransaction = (message: string, operation: string) =>
113 new SqlError({
114 reason: new UnknownError({
115 cause: new Error(message),
116 message,
117 operation
118 })
119 })
120
121const makeUnsupportedWithTransaction =
122 (message: string): Client.SqlClient["withTransaction"] =>
123 <R, E, A>(_effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | SqlError, R> =>
124 Effect.fail(unsupportedTransaction(message, "transaction"))
125
126interface StorageLevel {
127 readonly txn: DurableObjectTransaction
128 readonly resolve: () => void
129 readonly done: Promise<Exit.Exit<void, SqlError>>
130}
131
132const makeStorageBackedWithTransaction = (
133 storage: DurableObjectStorage,
134 connection: Connection,
135 acquirer: Effect.Effect<Connection, never, Scope.Scope>,
136 spanAttributes: ReadonlyArray<readonly [string, unknown]>
137): Client.SqlClient["withTransaction"] => {
138 // The open storage transaction at each depth. Transactions at the same depth
139 // never overlap.
140 const levels: Array<StorageLevel> = []
141
142 // Parks the storage callback so the body runs on the fiber.
143 const open = (id: number) =>
144 Effect.callback<void, SqlError>((resume) => {
145 const done: Promise<Exit.Exit<void, SqlError>> = storage.transaction((txn) =>
146 new Promise<void>((resolve) => {
147 resume(Effect.sync(() => {
148 levels[id] = { txn, resolve, done }
149 }))
150 })
151 ).then(
152 () => Exit.void,
153 (cause) => {
154 const exit = Exit.fail(new SqlError({ reason: classifyError(cause, "Failed transaction", "transaction") }))
155 // Only takes effect if storage rejects before the callback starts.
156 resume(exit)
157 return exit
158 }
159 )
160 })
161
162 const close = (id: number) =>
163 Effect.suspend(() => {
164 const level = levels[id]
165 levels.length = id
166 level.resolve()
167 return Effect.flatten(Effect.promise(() => level.done))
168 })
169
170 // Uses `txn.rollback()` because rejecting a nested callback can abort its parent.
171 const rollback = (id: number) => Effect.sync(() => levels[id].txn.rollback())
172
173 const withTransaction = Client.makeWithTransaction({
174 transactionService: SqliteTransaction,
175 spanAttributes,
176 acquireConnection: (restore) => restore(acquirer),
177 begin: () => open(0),
178 savepoint: (_, id) => open(id),
179 releaseSavepoint: (_, id) => close(id),
180 commit: () => close(0),
181 rollback: () => Effect.andThen(rollback(0), close(0)),
182 // `releaseSavepoint` runs next and closes the level.
183 rollbackSavepoint: (_, id) => rollback(id)
184 })
185
186 return <R, E, A>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | SqlError, R> =>
187 Effect.withFiber((fiber) => {
188 const conn = Context.getOrUndefined(fiber.context, SqliteTransaction)
189 if (conn !== undefined && conn[0] !== connection) {
190 return Effect.fail(
191 unsupportedTransaction(
192 "Transactions cannot use a connection from a different SQLite client",
193 "transaction"
194 )
195 )
196 }
197 return withTransaction(effect)
198 }).pipe(
199 // The storage transaction closes the input gate, blocking dispatcher tasks until it completes.
200 Effect.provideService(Scheduler.PreventSchedulerYield, true)
201 )
202}
203
204/**
205 * Creates a scoped Cloudflare Durable Object SQLite client around Durable Object SQLite storage, serializing access and converting returned `ArrayBuffer` values to `Uint8Array`.
206 *
207 * @stability unstable
208 * @category constructors
209 * @since 4.0.0
210 */
211export const make = (
212 options: SqliteClientConfig
213): Effect.Effect<SqliteClient & Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
214 Effect.gen(function*() {
215 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
216 const transformRows = options.transformResultNames
217 ? Statement.defaultTransforms(options.transformResultNames).array
218 : undefined
219 const db = options.storage?.sql ?? options.db
220
221 if (db === undefined) {
222 return yield* Effect.die("SqliteClient.make requires either a Durable Object storage or sql storage")
223 }
224 const sqlStorage = db
225
226 const makeConnection = Effect.gen(function*() {
227 function* runIterator(
228 sql: string,
229 params: ReadonlyArray<unknown> = []
230 ) {
231 const cursor = sqlStorage.exec(sql, ...params)
232 const columns = cursor.columnNames
233 for (const result of cursor.raw()) {
234 const obj: any = {}
235 for (let i = 0; i < columns.length; i++) {
236 const value = result[i]
237 Rec.assignProperty(obj, columns[i], value instanceof ArrayBuffer ? new Uint8Array(value) : value)
238 }
239 yield obj
240 }
241 }
242
243 const runStatement = (
244 sql: string,
245 params: ReadonlyArray<unknown> = []
246 ): Effect.Effect<ReadonlyArray<any>, SqlError, never> =>
247 Effect.try({
248 try: () => Array.from(runIterator(sql, params)),
249 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
250 })
251
252 const runValues = (
253 sql: string,
254 params: ReadonlyArray<unknown> = []
255 ): Effect.Effect<ReadonlyArray<any>, SqlError, never> =>
256 Effect.try({
257 try: () =>
258 Array.from(sqlStorage.exec(sql, ...params).raw(), (row) => {
259 for (let i = 0; i < row.length; i++) {
260 const value = row[i]
261 if (value instanceof ArrayBuffer) {
262 row[i] = new Uint8Array(value) as any
263 }
264 }
265 return row
266 }),
267 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
268 })
269
270 return identity<Connection>({
271 execute(sql, params, transformRows) {
272 return transformRows
273 ? Effect.map(runStatement(sql, params), transformRows)
274 : runStatement(sql, params)
275 },
276 executeRaw(sql, params) {
277 return runStatement(sql, params)
278 },
279 executeValues(sql, params) {
280 return runValues(sql, params)
281 },
282 executeValuesUnprepared(sql, params) {
283 return runValues(sql, params)
284 },
285 executeUnprepared(sql, params, transformRows) {
286 return transformRows
287 ? Effect.map(runStatement(sql, params), transformRows)
288 : runStatement(sql, params)
289 },
290 executeStream(sql, params, transformRows) {
291 return Stream.suspend(() => {
292 const iterator = runIterator(sql, params)
293 return Stream.fromIteratorSucceed(iterator, 128)
294 }).pipe(
295 Stream.catchCauseFilter(Cause.findDefect, (defect) =>
296 Stream.fail(
297 new SqlError({
298 reason: classifyError(defect, "Failed to execute statement", "execute")
299 })
300 )),
301 transformRows
302 ? Stream.mapArray((chunk) => transformRows(chunk) as any)
303 : identity
304 )
305 }
306 })
307 })
308
309 const semaphore = yield* Semaphore.make(1)
310 const connection = yield* makeConnection
311
312 // Streams and reservations hold the permit until their scope closes.
313 const acquirer = Effect.as(
314 Effect.acquireRelease(semaphore.take(1), () => semaphore.release(1), { interruptible: true }),
315 connection
316 )
317
318 const spanAttributes: ReadonlyArray<readonly [string, unknown]> = [
319 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
320 [ATTR_DB_SYSTEM_NAME, "sqlite"]
321 ]
322
323 const client = (yield* Client.make({
324 driver: "sqlite-do",
325 acquirer,
326 borrower: (f) => semaphore.withPermit(f(connection)),
327 compiler,
328 transactionService: SqliteTransaction,
329 spanAttributes,
330 transformRows
331 })) as SqliteClient & Client.SqlClient
332
333 return Object.assign(client, {
334 [TypeId]: TypeId as TypeId,
335 config: options,
336 withTransaction: options.storage
337 ? makeStorageBackedWithTransaction(options.storage, connection, acquirer, spanAttributes)
338 : makeUnsupportedWithTransaction(
339 "Transactions require Durable Object storage; pass ctx.storage as the storage option"
340 )
341 })
342 })
343
344/**
345 * Creates a layer from a `Config`-wrapped Durable Object SQLite client configuration, providing both `SqliteClient` and `SqlClient`.
346 *
347 * @stability unstable
348 * @category layers
349 * @since 4.0.0
350 */
351export const layerConfig = (
352 config: Config.Wrap<SqliteClientConfig>
353): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError> =>
354 Layer.effectContext(
355 Config.unwrap(config).pipe(
356 Effect.flatMap(make),
357 Effect.map((client) =>
358 Context.make(SqliteClient, client).pipe(
359 Context.add(Client.SqlClient, client)
360 )
361 )
362 )
363 ).pipe(Layer.provide(Reactivity.layer))
364
365/**
366 * Creates a layer from a concrete Durable Object SQLite client configuration, providing both `SqliteClient` and `SqlClient`.
367 *
368 * @stability unstable
369 * @category layers
370 * @since 4.0.0
371 */
372export const layer = (
373 config: SqliteClientConfig
374): Layer.Layer<SqliteClient | Client.SqlClient> =>
375 Layer.effectContext(
376 Effect.map(make(config), (client) =>
377 Context.make(SqliteClient, client).pipe(
378 Context.add(Client.SqlClient, client)
379 ))
380 ).pipe(Layer.provide(Reactivity.layer))