Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SqliteClient.ts

349 lines12.1 KB

1/**
2 * Connects Effect SQL to SQLite storage inside Cloudflare Durable Objects.
3 *
4 * This module adapts a Durable Object `SqlStorage` handle into both the
5 * Durable Object-specific `SqliteClient` service and the generic Effect
6 * `SqlClient` service. Use it from inside a Durable Object to run local
7 * per-object queries, repositories, migrations, transactional read/write
8 * workflows, and tests that exercise Cloudflare's SQLite-backed storage API.
9 *
10 * Durable Object SQLite storage is scoped to one object id, so each object
11 * instance has its own database. Callers can pass the `SqlStorage` handle for
12 * normal queries, or the full `DurableObjectStorage` when `withTransaction` or
13 * migrations need Cloudflare-managed transactions. This adapter serializes
14 * Effect SQL access through one connection; a transaction holds that permit for
15 * the lifetime of its scope, so keep transactions short, avoid suspending them
16 * across unrelated work, and use them when multi-statement writes must commit
17 * atomically. `SqlStorage.exec` returns `ArrayBuffer` values
18 * for SQLite blobs, which this client normalizes to `Uint8Array`, and SQLite
19 * does not support `updateValues`.
20 *
21 * @since 4.0.0
22 */
23import type { DurableObjectStorage, SqlStorage } from "@cloudflare/workers-types"
24import * as Cause from "effect/Cause"
25import * as Config from "effect/Config"
26import * as Context from "effect/Context"
27import * as Effect from "effect/Effect"
28import * as Exit from "effect/Exit"
29import * as Fiber from "effect/Fiber"
30import { identity } from "effect/Function"
31import * as Layer from "effect/Layer"
32import * as Rec from "effect/Record"
33import * as Scope from "effect/Scope"
34import * as Semaphore from "effect/Semaphore"
35import * as Stream from "effect/Stream"
36import * as Reactivity from "effect/unstable/reactivity/Reactivity"
37import * as Client from "effect/unstable/sql/SqlClient"
38import type { Connection } from "effect/unstable/sql/SqlConnection"
39import { classifySqliteError, SqlError, UnknownError } from "effect/unstable/sql/SqlError"
40import * as Statement from "effect/unstable/sql/Statement"
41​
42const ATTR_DB_SYSTEM_NAME = "db.system.name"
43​
44const classifyError = (cause: unknown, message: string, operation: string) =>
45 classifySqliteError(cause, { message, operation })
46​
47/**
48 * Runtime type identifier used to mark Cloudflare Durable Object `SqliteClient` values.
49 *
50 * @category type IDs
51 * @since 4.0.0
52 */
53export const TypeId: TypeId = "~@effect/sql-sqlite-do/SqliteClient"
54​
55/**
56 * Type-level identifier used to mark Cloudflare Durable Object `SqliteClient` values.
57 *
58 * @category type IDs
59 * @since 4.0.0
60 */
61export type TypeId = "~@effect/sql-sqlite-do/SqliteClient"
62​
63/**
64 * Cloudflare Durable Object SQLite client service, extending `SqlClient` with its configuration. `updateValues` is not supported.
65 *
66 * @category services
67 * @since 4.0.0
68 */
69export interface SqliteClient extends Client.SqlClient {
70 readonly [TypeId]: TypeId
71 readonly config: SqliteClientConfig
72​
73 /** Not supported in sqlite */
74 readonly updateValues: never
76​
77/**
78 * Service tag for the Cloudflare Durable Object SQLite client service.
79 *
80 * **When to use**
81 *
82 * Use to access or provide a Durable Object SQLite client through the Effect
83 * context.
84 *
85 * @category services
86 * @since 4.0.0
87 */
88export const SqliteClient = Context.Service<SqliteClient>("@effect/sql-sqlite-do/SqliteClient")
89​
90const SqliteTransaction = Context.Service<Client.TransactionConnection, Client.TransactionConnection.Service>(
91 "@effect/sql-sqlite-do/SqliteClient/SqliteTransaction"
93​
94/**
95 * 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.
96 *
97 * @category models
98 * @since 4.0.0
99 */
100export interface SqliteClientConfig {
101 readonly db?: SqlStorage | undefined
102 readonly storage?: DurableObjectStorage | undefined
103 readonly spanAttributes?: Record<string, unknown> | undefined
104​
105 readonly transformResultNames?: ((str: string) => string) | undefined
106 readonly transformQueryNames?: ((str: string) => string) | undefined
108​
109const unsupportedTransaction = (message: string, operation: string) =>
110 new SqlError({
111 reason: new UnknownError({
112 cause: new Error(message),
113 message,
114 operation
115 })
116 })
117​
118const makeUnsupportedWithTransaction =
119 (message: string): Client.SqlClient["withTransaction"] =>
120 <R, E, A>(_effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | SqlError, R> =>
121 Effect.fail(unsupportedTransaction(message, "transaction"))
122​
123const makeStorageBackedWithTransaction = (
124 storage: DurableObjectStorage,
125 connection: Connection,
126 semaphore: Semaphore.Semaphore
127): Client.SqlClient["withTransaction"] =>
128<R, E, A>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | SqlError, R> =>
129 Effect.withFiber((fiber) => {
130 const services = fiber.context
131 const connOption = Context.getOption(services, SqliteTransaction)
132 if (connOption._tag === "Some") {
133 return Effect.fail(
134 unsupportedTransaction(
135 "Nested transactions are not supported by Cloudflare Durable Object SQLite storage",
136 "transaction"
137 )
138 )
139 }
140​
141 const effectWithTxn = Effect.provideContext(
142 effect,
143 Context.add(services, SqliteTransaction, [connection, 0] as const)
144 )
145​
146 return semaphore.withPermits(1)(
147 Effect.callback((resume) => {
148 let interrupted = false
149 const promise = storage.transaction((txn) =>
150 new Promise<void>((resolve) => {
151 if (interrupted) return resolve()
152 resume(Effect.onExit(effectWithTxn, (exit) => {
153 if (Exit.isFailure(exit)) {
154 txn.rollback()
155 }
156 resolve()
157 // wait for the transaction to complete
158 return Effect.promise(() => promise)
159 }))
160 })
161 ).catch((cause) =>
162 resume(Effect.fail(new SqlError({ reason: classifyError(cause, "Failed transaction", "transaction") })))
163 )
164 return Effect.suspend(() => {
165 interrupted = true
166 return Effect.promise(() => promise)
167 })
168 })
169 )
170 })
171​
172/**
173 * Creates a scoped Cloudflare Durable Object SQLite client around Durable Object SQLite storage, serializing access and converting returned `ArrayBuffer` values to `Uint8Array`.
174 *
175 * @category constructors
176 * @since 4.0.0
177 */
178export const make = (
179 options: SqliteClientConfig
180): Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity> =>
181 Effect.gen(function*() {
182 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
183 const transformRows = options.transformResultNames
184 ? Statement.defaultTransforms(options.transformResultNames).array
185 : undefined
186 const db = options.storage?.sql ?? options.db
187​
188 if (db === undefined) {
189 return yield* Effect.die("SqliteClient.make requires either a Durable Object storage or sql storage")
190 }
191 const sqlStorage = db
192​
193 const makeConnection = Effect.gen(function*() {
194 function* runIterator(
195 sql: string,
196 params: ReadonlyArray<unknown> = []
197 ) {
198 const cursor = sqlStorage.exec(sql, ...params)
199 const columns = cursor.columnNames
200 for (const result of cursor.raw()) {
201 const obj: any = {}
202 for (let i = 0; i < columns.length; i++) {
203 const value = result[i]
204 Rec.assignProperty(obj, columns[i], value instanceof ArrayBuffer ? new Uint8Array(value) : value)
205 }
206 yield obj
207 }
208 }
209​
210 const runStatement = (
211 sql: string,
212 params: ReadonlyArray<unknown> = []
213 ): Effect.Effect<ReadonlyArray<any>, SqlError, never> =>
214 Effect.try({
215 try: () => Array.from(runIterator(sql, params)),
216 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
217 })
218​
219 const runValues = (
220 sql: string,
221 params: ReadonlyArray<unknown> = []
222 ): Effect.Effect<ReadonlyArray<any>, SqlError, never> =>
223 Effect.try({
224 try: () =>
225 Array.from(sqlStorage.exec(sql, ...params).raw(), (row) => {
226 for (let i = 0; i < row.length; i++) {
227 const value = row[i]
228 if (value instanceof ArrayBuffer) {
229 row[i] = new Uint8Array(value) as any
230 }
231 }
232 return row
233 }),
234 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
235 })
236​
237 return identity<Connection>({
238 execute(sql, params, transformRows) {
239 return transformRows
240 ? Effect.map(runStatement(sql, params), transformRows)
241 : runStatement(sql, params)
242 },
243 executeRaw(sql, params) {
244 return runStatement(sql, params)
245 },
246 executeValues(sql, params) {
247 return runValues(sql, params)
248 },
249 executeValuesUnprepared(sql, params) {
250 return runValues(sql, params)
251 },
252 executeUnprepared(sql, params, transformRows) {
253 return transformRows
254 ? Effect.map(runStatement(sql, params), transformRows)
255 : runStatement(sql, params)
256 },
257 executeStream(sql, params, transformRows) {
258 return Stream.suspend(() => {
259 const iterator = runIterator(sql, params)
260 return Stream.fromIteratorSucceed(iterator, 128)
261 }).pipe(
262 Stream.catchCauseFilter(Cause.findDefect, (defect) =>
263 Stream.fail(
264 new SqlError({
265 reason: classifyError(defect, "Failed to execute statement", "execute")
266 })
267 )),
268 transformRows
269 ? Stream.mapArray((chunk) => transformRows(chunk) as any)
270 : identity
271 )
272 }
273 })
274 })
275​
276 const semaphore = yield* Semaphore.make(1)
277 const connection = yield* makeConnection
278​
279 const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
280 const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
281 const fiber = Fiber.getCurrent()!
282 const scope = Context.getUnsafe(fiber.context, Scope.Scope)
283 return Effect.as(
284 Effect.tap(
285 restore(semaphore.take(1)),
286 () => Scope.addFinalizer(scope, semaphore.release(1))
287 ),
288 connection
289 )
290 })
291​
292 const client = (yield* Client.make({
293 acquirer,
294 compiler,
295 transactionAcquirer,
296 transactionService: SqliteTransaction,
297 spanAttributes: [
298 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
299 [ATTR_DB_SYSTEM_NAME, "sqlite"]
300 ],
301 transformRows
302 })) as SqliteClient
303​
304 return Object.assign(client, {
305 [TypeId]: TypeId as TypeId,
306 config: options,
307 withTransaction: options.storage
308 ? makeStorageBackedWithTransaction(options.storage, connection, semaphore)
309 : makeUnsupportedWithTransaction(
310 "Transactions require Durable Object storage; pass ctx.storage as the storage option"
311 )
312 })
313 })
314​
315/**
316 * Creates a layer from a `Config`-wrapped Durable Object SQLite client configuration, providing both `SqliteClient` and `SqlClient`.
317 *
318 * @category layers
319 * @since 4.0.0
320 */
321export const layerConfig = (
322 config: Config.Wrap<SqliteClientConfig>
323): Layer.Layer<SqliteClient | Client.SqlClient, Config.ConfigError> =>
324 Layer.effectContext(
325 Config.unwrap(config).pipe(
326 Effect.flatMap(make),
327 Effect.map((client) =>
328 Context.make(SqliteClient, client).pipe(
329 Context.add(Client.SqlClient, client)
330 )
331 )
332 )
333 ).pipe(Layer.provide(Reactivity.layer))
334​
335/**
336 * Creates a layer from a concrete Durable Object SQLite client configuration, providing both `SqliteClient` and `SqlClient`.
337 *
338 * @category layers
339 * @since 4.0.0
340 */
341export const layer = (
342 config: SqliteClientConfig
343): Layer.Layer<SqliteClient | Client.SqlClient> =>
344 Layer.effectContext(
345 Effect.map(make(config), (client) =>
346 Context.make(SqliteClient, client).pipe(
347 Context.add(Client.SqlClient, client)
348 ))
349 ).pipe(Layer.provide(Reactivity.layer))