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

main
ts 320 lines 12.6 KB
Raw
1 import { LibsqlClient } from "@effect/sql-libsql"
2 import { assert, describe, it, layer } from "@effect/vitest"
3 import { Cause, Deferred, Effect, Exit, Fiber, Layer, Option } from "effect"
4 import * as Reactivity from "effect/reactivity/Reactivity"
5 import { SqlError } from "effect/sql/SqlError"
6 import { LibsqlContainer } from "./util.ts"
7
8 const Migrations = Layer.effectDiscard(
9 LibsqlClient.LibsqlClient.pipe(
10 Effect.andThen((sql) =>
11 Effect.acquireRelease(
12 sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`,
13 () => sql`DROP TABLE test;`.pipe(Effect.ignore)
14 )
15 )
16 )
17 )
18
19 describe("Client", () => {
20 it.effect("exposes the active transaction service for each client", () =>
21 Effect.gen(function*() {
22 const a = yield* LibsqlClient.make({ url: ":memory:" })
23 const b = yield* LibsqlClient.make({ url: ":memory:" })
24 const active = Effect.all([
25 Effect.map(Effect.serviceOption(a.transactionService), Option.isSome),
26 Effect.map(Effect.serviceOption(b.transactionService), Option.isSome)
27 ])
28
29 assert.deepStrictEqual(yield* active, [false, false])
30 yield* a.withTransaction(Effect.gen(function*() {
31 assert.deepStrictEqual(yield* active, [true, false])
32 assert.deepStrictEqual(yield* b.withTransaction(active), [true, true])
33 assert.deepStrictEqual(yield* active, [true, false])
34 }))
35 assert.deepStrictEqual(yield* active, [false, false])
36 }).pipe(Effect.provide(Reactivity.layer)))
37
38 it.effect("releases completed nested savepoints", () =>
39 Effect.gen(function*() {
40 const sql = yield* LibsqlClient.make({ url: ":memory:" })
41 yield* sql`CREATE TABLE savepoint_release (value INTEGER)`
42 yield* sql.withTransaction(Effect.gen(function*() {
43 for (const rollback of [false, true]) {
44 yield* sql.withTransaction(
45 sql`INSERT INTO savepoint_release VALUES (1)`.pipe(
46 Effect.andThen(rollback ? Effect.fail("rollback") : Effect.void)
47 )
48 ).pipe(Effect.ignore)
49 const error = yield* sql`RELEASE SAVEPOINT effect_sql_1`.unprepared.pipe(Effect.flip)
50 assert.strictEqual(error._tag, "SqlError")
51 }
52 }))
53 assert.deepStrictEqual(yield* sql`SELECT value FROM savepoint_release`, [{ value: 1 }])
54 const error = yield* sql.withTransaction(
55 sql.withTransaction(sql`INSERT INTO savepoint_release VALUES (2)`).pipe(
56 Effect.andThen(Effect.fail("outer rollback"))
57 )
58 ).pipe(Effect.flip)
59 assert.strictEqual(error, "outer rollback")
60 assert.deepStrictEqual(yield* sql`SELECT value FROM savepoint_release`, [{ value: 1 }])
61 }).pipe(Effect.provide(Reactivity.layer)))
62
63 it.effect("keeps transactions isolated between clients", () =>
64 Effect.gen(function*() {
65 const a = yield* LibsqlClient.make({ url: ":memory:" })
66 const b = yield* LibsqlClient.make({ url: ":memory:" })
67
68 yield* a`CREATE TABLE marker (owner TEXT NOT NULL)`
69 yield* b`CREATE TABLE marker (owner TEXT NOT NULL)`
70 yield* a`INSERT INTO marker VALUES ('A')`
71 yield* b`INSERT INTO marker VALUES ('B')`
72
73 const rows = yield* a.withTransaction(b`SELECT owner FROM marker`)
74 assert.deepStrictEqual(rows, [{ owner: "B" }])
75 }).pipe(
76 Effect.scoped,
77 Effect.provide(Reactivity.layer)
78 ))
79
80 it.effect("releases transaction serialization after begin fails", () => {
81 let transactionCalls = 0
82 const transaction = {
83 execute: () => Promise.resolve({ rows: [] }),
84 commit: () => Promise.resolve(),
85 rollback: () => Promise.resolve()
86 }
87 const liveClient = {
88 execute: () => Promise.resolve({ rows: [] }),
89 transaction: () => {
90 transactionCalls++
91 return transactionCalls === 1
92 ? Promise.reject(new Error("transient begin failure"))
93 : Promise.resolve(transaction)
94 }
95 }
96
97 return Effect.gen(function*() {
98 const client = yield* LibsqlClient.make({ liveClient: liveClient as any })
99 const first = yield* Effect.exit(client.withTransaction(Effect.void))
100 assert.isTrue(Exit.isFailure(first))
101
102 yield* Effect.forkChild(client.withTransaction(Effect.void))
103 yield* Effect.yieldNow
104
105 assert.strictEqual(transactionCalls, 2)
106 }).pipe(
107 Effect.scoped,
108 Effect.provide(Reactivity.layer)
109 )
110 })
111
112 for (const rollbackFails of [false, true]) {
113 it.effect(`rolls back an interrupted pending begin (rollback ${rollbackFails ? "rejects" : "succeeds"})`, () =>
114 Effect.gen(function*() {
115 const calls: Array<string> = []
116 const rollbackError = new Error("rollback failed")
117 const transaction = {
118 execute: () => Promise.resolve({ rows: [] }),
119 commit: () => {
120 calls.push("commit")
121 return Promise.resolve()
122 },
123 rollback: () => {
124 calls.push("rollback")
125 return rollbackFails ? Promise.reject(rollbackError) : Promise.resolve()
126 }
127 }
128 const started = Promise.withResolvers<void>()
129 const begin = Promise.withResolvers<typeof transaction>()
130 let transactionCalls = 0
131 const liveClient = {
132 transaction: () => {
133 if (++transactionCalls === 1) {
134 started.resolve()
135 return begin.promise
136 }
137 return Promise.resolve(transaction)
138 }
139 }
140 const client = yield* LibsqlClient.make({ liveClient: liveClient as any })
141 const fiber = yield* Effect.forkChild(client.withTransaction(Effect.sync(() => {
142 calls.push("cancelled body")
143 })))
144 yield* Effect.promise(() => started.promise)
145 // Request interruption while the SDK still owns the pending BEGIN.
146 fiber.interruptUnsafe()
147 begin.resolve(transaction)
148 const exit = yield* Fiber.await(fiber)
149
150 assert.isTrue(Exit.isFailure(exit))
151 if (Exit.isFailure(exit)) {
152 assert.isTrue(Cause.hasInterrupts(exit.cause))
153 const defects = exit.cause.reasons.filter(Cause.isDieReason).map((reason) => reason.defect)
154 assert.strictEqual(defects.length, rollbackFails ? 1 : 0)
155 if (rollbackFails) {
156 assert.instanceOf(defects[0], SqlError)
157 assert.strictEqual((defects[0] as SqlError).reason.cause, rollbackError)
158 }
159 }
160 assert.deepStrictEqual(calls, ["rollback"])
161
162 yield* client.withTransaction(Effect.sync(() => {
163 calls.push("next body")
164 }))
165 assert.deepStrictEqual(calls, ["rollback", "next body", "commit"])
166 }).pipe(Effect.provide(Reactivity.layer)))
167 }
168
169 it.effect("overlaps remote statements with each other and open transactions", () =>
170 Effect.gen(function*() {
171 const calls: Array<string> = []
172 const statement = Promise.withResolvers<{ rows: Array<unknown> }>()
173 const transaction = {
174 execute: () => {
175 calls.push("transaction execute")
176 return Promise.resolve({ rows: [] })
177 },
178 commit: () => Promise.resolve(),
179 rollback: () => Promise.resolve()
180 }
181 const liveClient = {
182 protocol: "http",
183 execute: () => {
184 calls.push("execute")
185 return statement.promise
186 },
187 transaction: () => Promise.resolve(transaction)
188 }
189 const client = yield* LibsqlClient.make({ liveClient: liveClient as any })
190 const open = yield* Deferred.make<void>()
191 const release = yield* Deferred.make<void>()
192 const tx = yield* Effect.forkChild(client.withTransaction(
193 Deferred.succeed(open, undefined).pipe(Effect.andThen(Deferred.await(release)))
194 ))
195 yield* Deferred.await(open)
196
197 const statements = yield* Effect.forkChild(
198 Effect.all([client`SELECT 1`, client`SELECT 2`], { concurrency: "unbounded" })
199 )
200 yield* Effect.yieldNow
201 assert.deepStrictEqual(calls, ["execute", "execute"])
202
203 statement.resolve({ rows: [] })
204 yield* Fiber.join(statements)
205 yield* Deferred.succeed(release, undefined)
206 yield* Fiber.join(tx)
207 }).pipe(Effect.provide(Reactivity.layer)))
208
209 it.effect("serializes local statements behind open transactions", () =>
210 Effect.gen(function*() {
211 const sql = yield* LibsqlClient.make({ url: ":memory:" })
212 yield* sql`CREATE TABLE serialized (value INTEGER)`
213 const open = yield* Deferred.make<void>()
214 const release = yield* Deferred.make<void>()
215 const tx = yield* Effect.forkChild(sql.withTransaction(
216 sql`INSERT INTO serialized VALUES (1)`.pipe(
217 Effect.andThen(Deferred.succeed(open, undefined)),
218 Effect.andThen(Deferred.await(release))
219 )
220 ))
221 yield* Deferred.await(open)
222
223 const read = yield* Effect.forkChild(sql`SELECT value FROM serialized`)
224 yield* Effect.yieldNow
225 yield* Deferred.succeed(release, undefined)
226 yield* Fiber.join(tx)
227
228 assert.deepStrictEqual(yield* Fiber.join(read), [{ value: 1 }])
229 }).pipe(Effect.provide(Reactivity.layer)))
230
231 // Each test recreates the same tables.
232 layer(LibsqlContainer.layerClient, { timeout: "30 seconds", concurrent: false })("shared tables", (it) => {
233 it.effect("should work", () =>
234 Effect.gen(function*() {
235 const sql = yield* LibsqlClient.LibsqlClient
236 let response = yield* sql`INSERT INTO test (name) VALUES ('hello')`
237 assert.deepStrictEqual(response, [])
238 response = yield* sql`SELECT * FROM test`
239 assert.deepStrictEqual(response, [{ id: 1, name: "hello" }])
240 response = yield* sql`SELECT * FROM test`
241 assert.deepStrictEqual(yield* sql`select * from test`.values, [
242 [1, "hello"]
243 ])
244 }).pipe(Effect.provide(Migrations)))
245
246 it.effect("should work with raw", () =>
247 Effect.gen(function*() {
248 const sql = yield* LibsqlClient.LibsqlClient
249 let response: any
250 response = yield* sql`CREATE TABLE test2 (id INTEGER PRIMARY KEY, name TEXT)`.raw
251 yield* Effect.addFinalizer(() => sql`DROP TABLE test2;`.pipe(Effect.ignore))
252 assert.deepStrictEqual(response.toJSON(), {
253 columnTypes: [],
254 columns: [],
255 lastInsertRowid: null,
256 rows: [],
257 rowsAffected: 0
258 })
259 response = yield* sql`INSERT INTO test (name) VALUES ('hello')`.raw
260 assert.deepStrictEqual(response.toJSON(), {
261 columnTypes: [],
262 columns: [],
263 lastInsertRowid: "1",
264 rows: [],
265 rowsAffected: 1
266 })
267 response = yield* sql`SELECT * FROM test`.raw
268 assert.deepStrictEqual(response.toJSON(), {
269 columnTypes: ["INTEGER", "TEXT"],
270 columns: ["id", "name"],
271 lastInsertRowid: null,
272 rows: [[1, "hello"]],
273 rowsAffected: 0
274 })
275 }).pipe(Effect.provide(Migrations)))
276
277 it.effect("withTransaction", () =>
278 Effect.gen(function*() {
279 const sql = yield* LibsqlClient.LibsqlClient
280 yield* sql.withTransaction(sql`INSERT INTO test (name) VALUES ('hello')`)
281 const rows = yield* sql`SELECT * FROM test`
282 assert.deepStrictEqual(rows, [{ id: 1, name: "hello" }])
283 }).pipe(Effect.provide(Migrations)))
284
285 it.effect("withTransaction rollback", () =>
286 Effect.gen(function*() {
287 const sql = yield* LibsqlClient.LibsqlClient
288 yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe(
289 Effect.andThen(Effect.fail("boom")),
290 sql.withTransaction,
291 Effect.ignore
292 )
293 const rows = yield* sql`SELECT * FROM test`
294 assert.deepStrictEqual(rows, [])
295 }).pipe(Effect.provide(Migrations)))
296
297 it.effect("withTransaction nested", () =>
298 Effect.gen(function*() {
299 const sql = yield* LibsqlClient.LibsqlClient
300 const stmt = sql`INSERT INTO test (name) VALUES ('hello')`
301
302 yield* stmt.pipe(Effect.andThen(() => stmt.pipe(sql.withTransaction)), sql.withTransaction)
303 const rows = yield* sql<{ total_rows: number }>`select count(*) as total_rows FROM test`
304 assert.deepStrictEqual(rows.at(0)?.total_rows, 2)
305 }).pipe(Effect.provide(Migrations)))
306
307 it.effect("withTransaction nested rollback", () =>
308 Effect.gen(function*() {
309 const sql = yield* LibsqlClient.LibsqlClient
310 const stmt = sql`INSERT INTO test (name) VALUES ('hello')`
311
312 yield* stmt.pipe(
313 Effect.andThen(() => stmt.pipe(Effect.andThen(Effect.fail("boom")), sql.withTransaction, Effect.ignore)),
314 sql.withTransaction
315 )
316 const rows = yield* sql<{ total_rows: number }>`select count(*) as total_rows FROM test`
317 assert.deepStrictEqual(rows.at(0)?.total_rows, 1)
318 }).pipe(Effect.provide(Migrations)))
319 })
320 })