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

SqliteClient.ts

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