@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 402 lines 13.6 KB
Raw
1 /**
2 * libSQL adapter for Effect SQL, backed by `@libsql/client`.
3 *
4 * This module provides a {@link LibsqlClient} and the generic SQL client
5 * service for `@libsql/client`. It uses Effect SQL's SQLite compiler, supports
6 * managed SDK clients or caller-owned live clients, classifies libSQL and
7 * SQLite failures as `SqlError`s, and provides transaction support with
8 * savepoints. Streaming queries are not implemented by this driver.
9 *
10 * @stability unstable
11 * @since 4.0.0
12 */
13 import * as Libsql from "@libsql/client"
14 import * as Config from "effect/Config"
15 import * as Context from "effect/Context"
16 import * as Effect from "effect/Effect"
17 import * as Layer from "effect/Layer"
18 import * as Option from "effect/Option"
19 import * as Reactivity from "effect/reactivity/Reactivity"
20 import * as Redacted from "effect/Redacted"
21 import type * as Scope from "effect/Scope"
22 import * as Semaphore from "effect/Semaphore"
23 import * as Client from "effect/sql/SqlClient"
24 import type { Connection } from "effect/sql/SqlConnection"
25 import { classifySqliteError, SqlError } from "effect/sql/SqlError"
26 import * as Statement from "effect/sql/Statement"
27 import * as Stream from "effect/Stream"
28
29 const ATTR_DB_SYSTEM_NAME = "db.system.name"
30
31 const classifyError = (cause: unknown, message: string, operation: string) =>
32 classifySqliteError(cause, { message, operation })
33
34 /**
35 * Runtime type identifier used to mark `LibsqlClient` values.
36 *
37 * @stability unstable
38 * @category type IDs
39 * @since 4.0.0
40 */
41 export const TypeId: TypeId = "~@effect/sql-libsql/LibsqlClient"
42
43 /**
44 * Type-level identifier used to mark `LibsqlClient` values.
45 *
46 * @stability unstable
47 * @category type IDs
48 * @since 4.0.0
49 */
50 export type TypeId = "~@effect/sql-libsql/LibsqlClient"
51
52 /**
53 * libSQL-backed SQL client service, extending `SqlClient` with its runtime type marker and client configuration.
54 *
55 * @stability unstable
56 * @category services
57 * @since 4.0.0
58 */
59 export interface LibsqlClient extends Client.SqlClient {
60 readonly [TypeId]: TypeId
61 readonly config: LibsqlClientConfig
62 }
63
64 /**
65 * Service tag for the libSQL client service.
66 *
67 * **When to use**
68 *
69 * Use to access or provide a libSQL client through the Effect context.
70 *
71 * @stability unstable
72 * @category services
73 * @since 4.0.0
74 */
75 export const LibsqlClient = Context.Service<LibsqlClient>("@effect/sql-libsql/LibsqlClient")
76
77 let clientIdCounter = 0
78
79 /**
80 * Configuration for a libSQL client, either by supplying connection options or an existing live libSQL client.
81 *
82 * @stability unstable
83 * @category models
84 * @since 4.0.0
85 */
86 export type LibsqlClientConfig = LibsqlClientConfig.Full | LibsqlClientConfig.Live
87
88 /**
89 * Namespace containing the configuration variants for `LibsqlClient`.
90 *
91 * @stability unstable
92 * @since 4.0.0
93 */
94 export declare namespace LibsqlClientConfig {
95 /**
96 * Shared libSQL client options for span attributes and query/result name transformations.
97 *
98 * @category models
99 * @since 4.0.0
100 */
101 export interface Base {
102 readonly spanAttributes?: Record<string, unknown> | undefined
103 readonly transformResultNames?: ((str: string) => string) | undefined
104 readonly transformQueryNames?: ((str: string) => string) | undefined
105 }
106
107 /**
108 * Connection-based libSQL configuration used to create a managed client, including URL, credentials, sync, integer mode, TLS, and concurrency options.
109 *
110 * @category models
111 * @since 4.0.0
112 */
113 export interface Full extends Base {
114 /**
115 * The database URL.
116 *
117 * **Details**
118 *
119 * The client supports `libsql:`, `http:`/`https:`, `ws:`/`wss:` and `file:` URL. For more infomation,
120 * please refer to the project README:
121 *
122 * https://github.com/libsql/libsql-client-ts#supported-urls
123 */
124 readonly url: string | URL
125 /** Authentication token for the database. */
126 readonly authToken?: Redacted.Redacted | undefined
127 /** Encryption key for the database. */
128 readonly encryptionKey?: Redacted.Redacted | undefined
129 /** URL of a remote server to synchronize database with. */
130 readonly syncUrl?: string | URL | undefined
131 /** Sync interval in seconds. */
132 readonly syncInterval?: number | undefined
133 /**
134 * Enables or disables TLS for `libsql:` URLs.
135 *
136 * **Details**
137 *
138 * By default, `libsql:` URLs use TLS. You can set this option to `false` to disable TLS.
139 */
140 readonly tls?: boolean | undefined
141 /**
142 * How to convert SQLite integers to JavaScript values.
143 *
144 * **Details**
145 *
146 * - `"number"` (default): returns SQLite integers as JavaScript `number`-s (double precision floats).
147 * `number` cannot precisely represent integers larger than 2^53-1 in absolute value, so attempting to read
148 * larger integers will throw a `RangeError`.
149 * - `"bigint"`: returns SQLite integers as JavaScript `bigint`-s (arbitrary precision integers). Bigints can
150 * precisely represent all SQLite integers.
151 * - `"string"`: returns SQLite integers as strings.
152 */
153 readonly intMode?: "number" | "bigint" | "string" | undefined
154 /**
155 * Concurrency limit.
156 *
157 * **Details**
158 *
159 * By default, the client performs up to 20 concurrent requests. You can set this option to a higher
160 * number to increase the concurrency limit or set it to 0 to disable concurrency limits completely.
161 */
162 readonly concurrency?: number | undefined
163 }
164
165 /**
166 * Configuration that uses an existing libSQL client. The supplied `liveClient` is caller-owned and is not closed by the Effect client.
167 *
168 * @stability unstable
169 * @category models
170 * @since 4.0.0
171 */
172 export interface Live extends Base {
173 readonly liveClient: Libsql.Client
174 }
175 }
176
177 interface LibsqlConnection extends Connection {
178 readonly beginTransaction: Effect.Effect<LibsqlConnection, SqlError>
179 readonly commit: Effect.Effect<void, SqlError>
180 readonly rollback: Effect.Effect<void, SqlError>
181 }
182
183 /**
184 * Creates a scoped libSQL SQL client with transaction support. When given connection options it creates and closes the SDK client; when given `liveClient`, the caller retains ownership.
185 *
186 * @stability unstable
187 * @category constructors
188 * @since 4.0.0
189 */
190 export const make = (
191 options: LibsqlClientConfig
192 ): Effect.Effect<LibsqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
193 Effect.gen(function*() {
194 const LibsqlTransaction = Context.Service<readonly [LibsqlConnection, counter: number]>(
195 `@effect/sql-libsql/LibsqlClient/LibsqlTransaction/${clientIdCounter++}`
196 )
197 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
198 const transformRows = options.transformResultNames ?
199 Statement.defaultTransforms(
200 options.transformResultNames
201 ).array :
202 undefined
203
204 const spanAttributes: Array<[string, unknown]> = [
205 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
206 [ATTR_DB_SYSTEM_NAME, "sqlite"]
207 ]
208
209 class LibsqlConnectionImpl implements LibsqlConnection {
210 readonly sdk: Libsql.Client | Libsql.Transaction
211 constructor(sdk: Libsql.Client | Libsql.Transaction) {
212 this.sdk = sdk
213 }
214
215 run(
216 sql: string,
217 params: ReadonlyArray<unknown> = []
218 ) {
219 return Effect.map(
220 Effect.tryPromise({
221 try: () => this.sdk.execute({ sql, args: params as Array<any> }),
222 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
223 }),
224 (results) => results.rows
225 )
226 }
227
228 runRaw(
229 sql: string,
230 params: ReadonlyArray<unknown> = []
231 ) {
232 return Effect.tryPromise({
233 try: () => this.sdk.execute({ sql, args: params as Array<any> }),
234 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
235 })
236 }
237
238 execute(
239 sql: string,
240 params: ReadonlyArray<unknown>,
241 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
242 ) {
243 return transformRows
244 ? Effect.map(this.run(sql, params), transformRows)
245 : this.run(sql, params)
246 }
247 executeRaw(sql: string, params: ReadonlyArray<unknown>) {
248 return this.runRaw(sql, params)
249 }
250 executeValues(sql: string, params: ReadonlyArray<unknown>) {
251 return Effect.map(this.run(sql, params), (rows) => rows.map((row) => Array.from(row) as Array<any>))
252 }
253 executeValuesUnprepared(sql: string, params: ReadonlyArray<unknown>) {
254 return this.executeValues(sql, params)
255 }
256 executeUnprepared(
257 sql: string,
258 params: ReadonlyArray<unknown>,
259 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
260 ) {
261 return this.execute(sql, params, transformRows)
262 }
263 executeStream() {
264 return Stream.die("executeStream not implemented")
265 }
266 get beginTransaction() {
267 return Effect.map(
268 Effect.tryPromise({
269 try: () => (this.sdk as Libsql.Client).transaction("write"),
270 catch: (cause) =>
271 new SqlError({ reason: classifyError(cause, "Failed to begin transaction", "beginTransaction") })
272 }),
273 (tx) => new LibsqlConnectionImpl(tx)
274 )
275 }
276 get commit() {
277 return Effect.tryPromise({
278 try: () => (this.sdk as Libsql.Transaction).commit(),
279 catch: (cause) =>
280 new SqlError({ reason: classifyError(cause, "Failed to commit transaction", "commitTransaction") })
281 })
282 }
283 get rollback() {
284 return Effect.tryPromise({
285 try: () => (this.sdk as Libsql.Transaction).rollback(),
286 catch: (cause) =>
287 new SqlError({ reason: classifyError(cause, "Failed to rollback transaction", "rollbackTransaction") })
288 })
289 }
290 }
291
292 const connection = "liveClient" in options
293 ? new LibsqlConnectionImpl(options.liveClient)
294 : yield* Effect.map(
295 Effect.acquireRelease(
296 Effect.sync(() =>
297 Libsql.createClient(
298 {
299 ...options,
300 authToken: Redacted.isRedacted(options.authToken)
301 ? Redacted.value(options.authToken)
302 : options.authToken,
303 encryptionKey: Redacted.isRedacted(options.encryptionKey)
304 ? Redacted.value(options.encryptionKey)
305 : options.encryptionKey,
306 url: options.url.toString(),
307 syncUrl: options.syncUrl?.toString()
308 } as Libsql.Config
309 )
310 ),
311 (sdk) => Effect.sync(() => sdk.close())
312 ),
313 (sdk) => new LibsqlConnectionImpl(sdk)
314 )
315 // Remote transports run each statement and transaction on its own stream.
316 // Local clients may own a single connection that the SDK refuses to lend
317 // while a transaction holds it, so take turns on it instead.
318 const protocol = (connection.sdk as Libsql.Client).protocol
319 const permit: Effect.Effect<void, never, Scope.Scope> = protocol === "http" || protocol === "ws"
320 ? Effect.void
321 : (yield* Semaphore.make(1)).takeScoped(1)
322
323 const withTransaction = Client.makeWithTransaction({
324 transactionService: LibsqlTransaction,
325 spanAttributes,
326 acquireConnection: (restore) => Effect.andThen(restore(permit), connection.beginTransaction),
327 begin: () => Effect.void, // already begun in acquireConnection
328 savepoint: (conn, id) => conn.executeRaw(`SAVEPOINT effect_sql_${id};`, []),
329 releaseSavepoint: (conn, id) => conn.executeRaw(`RELEASE SAVEPOINT effect_sql_${id};`, []),
330 commit: (conn) => conn.commit,
331 rollback: (conn) => conn.rollback,
332 rollbackSavepoint: (conn, id) => conn.executeRaw(`ROLLBACK TO SAVEPOINT effect_sql_${id};`, [])
333 })
334
335 // Outside a transaction, hold the permit until the statement's scope
336 // closes, so no other fiber can begin a transaction while it runs.
337 const lease = Effect.as(permit, connection as LibsqlConnection)
338 const acquirer = Effect.flatMap(
339 Effect.serviceOption(LibsqlTransaction),
340 Option.match({
341 onNone: () => lease,
342 onSome: ([conn]) => Effect.succeed(conn)
343 })
344 )
345
346 return Object.assign(
347 yield* Client.make({
348 driver: "libsql",
349 acquirer,
350 transactionService: LibsqlTransaction as any,
351 compiler,
352 spanAttributes,
353 transformRows
354 }),
355 {
356 [TypeId]: TypeId as TypeId,
357 config: options,
358 withTransaction,
359 sdk: connection.sdk
360 }
361 )
362 })
363
364 /**
365 * Creates a layer from a `Config`-wrapped libSQL client configuration, providing both `LibsqlClient` and `SqlClient`.
366 *
367 * @stability unstable
368 * @category layers
369 * @since 4.0.0
370 */
371 export const layerConfig: (
372 config: Config.Wrap<LibsqlClientConfig>
373 ) => Layer.Layer<LibsqlClient | Client.SqlClient, Config.ConfigError> = (
374 config: Config.Wrap<LibsqlClientConfig>
375 ): Layer.Layer<LibsqlClient | Client.SqlClient, Config.ConfigError> =>
376 Layer.effectContext(
377 Config.unwrap(config).pipe(
378 Effect.flatMap(make),
379 Effect.map((client) =>
380 Context.make(LibsqlClient, client).pipe(
381 Context.add(Client.SqlClient, client)
382 )
383 )
384 )
385 ).pipe(Layer.provide(Reactivity.layer))
386
387 /**
388 * Creates a layer from a concrete libSQL client configuration, providing both `LibsqlClient` and `SqlClient`.
389 *
390 * @stability unstable
391 * @category layers
392 * @since 4.0.0
393 */
394 export const layer = (
395 config: LibsqlClientConfig
396 ): Layer.Layer<LibsqlClient | Client.SqlClient> =>
397 Layer.effectContext(
398 Effect.map(make(config), (client) =>
399 Context.make(LibsqlClient, client).pipe(
400 Context.add(Client.SqlClient, client)
401 ))
402 ).pipe(Layer.provide(Reactivity.layer))