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

main
ts 417 lines 14.6 KB
Raw
1 import { MssqlClient, Procedure } from "@effect/sql-mssql"
2 import { assert, describe, expect, it } from "@effect/vitest"
3 import { Deferred, Effect, Fiber } from "effect"
4 import * as Reactivity from "effect/reactivity/Reactivity"
5 import * as Statement from "effect/sql/Statement"
6 import type { EventEmitter } from "node:events"
7 import type * as Tedious from "tedious"
8 import { vi } from "vitest"
9
10 interface MockConnection extends EventEmitter {
11 closed: boolean
12 closedSignal: Deferred.Deferred<void>
13 cancellations: number
14 queries: Array<string>
15 close(): void
16 }
17
18 const state = vi.hoisted(() => ({
19 cancelCalls: 0,
20 acknowledgeCancel: true,
21 completeRequests: true,
22 type: {},
23 connections: [] as Array<MockConnection>,
24 pendingStarted: undefined as Deferred.Deferred<void> | undefined,
25 errorAfterConnect: false,
26 emissionError: undefined as unknown
27 }))
28
29 vi.mock("tedious", async (importOriginal) => {
30 const original = await importOriginal<typeof Tedious>()
31 const { EventEmitter } = await import("node:events")
32
33 class MockRequest {
34 readonly listeners: Record<string, (...args: Array<any>) => void> = {}
35
36 constructor(
37 readonly sql: string,
38 readonly callback: (cause: unknown, rowCount: number, rows: ReadonlyArray<any>) => void
39 ) {}
40
41 addParameter() {}
42 addOutputParameter() {}
43 on(event: string, listener: (...args: Array<any>) => void) {
44 this.listeners[event] = listener
45 }
46 }
47
48 class MockConnection extends EventEmitter {
49 closed = false
50 readonly closedSignal = Deferred.makeUnsafe<void>()
51 pending: MockRequest | undefined
52 cancellations = 0
53 readonly queries: Array<string> = []
54
55 constructor() {
56 super()
57 state.connections.push(this)
58 }
59
60 connect(callback: (cause: unknown) => void) {
61 // Resume acquisition, then emit in the same driver turn, before a forked
62 // pool listener can run. Do not install a test-only error listener.
63 Fiber.getCurrent()!.currentDispatcher.scheduleTask(() => {
64 callback(null)
65 if (state.errorAfterConnect) {
66 state.errorAfterConnect = false
67 this.closed = true
68 try {
69 this.emit("error", new Error("Connection lost - read ETIMEDOUT"))
70 } catch (error) {
71 state.emissionError = error
72 }
73 }
74 }, 0)
75 }
76
77 close() {
78 if (!this.closed) {
79 this.closed = true
80 // Like tedious, emit end on the next tick, after the request callback.
81 process.nextTick(() => this.emit("end"))
82 }
83 const pending = this.pending
84 this.pending = undefined
85 pending?.callback(new Error("Connection closed before request completed."), 0, [])
86 Effect.runSync(Deferred.succeed(this.closedSignal, undefined))
87 }
88
89 cancel() {
90 state.cancelCalls++
91 if (this.pending) {
92 this.cancellations++
93 if (state.acknowledgeCancel) {
94 // Like tedious, call the request back once the server acknowledges.
95 const pending = this.pending
96 this.pending = undefined
97 Fiber.getCurrent()!.currentDispatcher.scheduleTask(() => {
98 pending.callback(new Error("Canceled."), 0, [])
99 }, 0)
100 }
101 }
102 }
103
104 execSql(request: MockRequest) {
105 this.queries.push(request.sql)
106 if (this.closed) {
107 request.callback(new Error("Requests can only be made in the LoggedIn state, not the Final state"), 0, [])
108 } else if (request.sql === "SELECT pending" || !state.completeRequests) {
109 this.pending = request
110 if (state.pendingStarted) {
111 Effect.runSync(Deferred.succeed(state.pendingStarted, undefined))
112 }
113 } else {
114 request.callback(null, 1, [[{ metadata: { colName: "value" }, value: 42 }]])
115 }
116 }
117 callProcedure(request: MockRequest) {
118 request.listeners.returnValue("answer", 42)
119 request.callback(null, 0, [])
120 }
121
122 beginTransaction(callback: (cause: unknown) => void) {
123 callback(null)
124 }
125
126 commitTransaction(callback: (cause: unknown) => void) {
127 callback(null)
128 }
129
130 saveTransaction(callback: (cause: unknown) => void) {
131 callback(null)
132 }
133
134 rollbackTransaction(callback: (cause: unknown) => void) {
135 callback(null)
136 }
137 }
138
139 return {
140 ...original,
141 Connection: MockConnection,
142 Request: MockRequest
143 }
144 })
145
146 const sql = Statement.make(Effect.void as any, MssqlClient.makeCompiler(), [], undefined)
147
148 describe("mssql", () => {
149 it("preserves fractional JavaScript numbers with the default parameter mapping", () => {
150 const value = MssqlClient.defaultParameterTypes.number.validate(1.5, undefined)
151
152 expect(value).toBe(1.5)
153 })
154
155 it("preserves Unicode JavaScript strings with the default parameter mapping", () => {
156 const value = MssqlClient.defaultParameterTypes.string.validate("lambda: \u03bb", undefined)
157
158 expect(value).toBe("lambda: \u03bb")
159 })
160
161 it("insert helper", () => {
162 const [query, params] = sql`INSERT INTO ${sql("people")} ${sql.insert({ name: "Tim", age: 10 })}`.compile()
163 expect(query).toEqual(
164 `INSERT INTO [people] ([name],[age]) VALUES (@1,@2)`
165 )
166 expect(params).toEqual(["Tim", 10])
167 })
168
169 it("insert helper returning", () => {
170 const [query, params] = sql`INSERT INTO ${sql("people")} ${sql.insert({ name: "Tim", age: 10 }).returning("*")}`
171 .compile()
172 expect(query).toEqual(
173 `INSERT INTO [people] ([name],[age]) OUTPUT INSERTED.* VALUES (@1,@2)`
174 )
175 expect(params).toEqual(["Tim", 10])
176 })
177
178 it("update helper", () => {
179 const [query, params] = sql`UPDATE people SET name = data.name ${
180 sql.updateValues(
181 [{ name: "Tim" }, { name: "John" }],
182 "data"
183 )
184 }`.compile()
185 expect(query).toEqual(
186 `UPDATE people SET name = data.name FROM (values (@1),(@2)) AS [data]([name])`
187 )
188 expect(params).toEqual(["Tim", "John"])
189 })
190
191 it("update helper returning", () => {
192 const [query, params] = sql`UPDATE people SET name = data.name ${
193 sql.updateValues(
194 [{ name: "Tim" }, { name: "John" }],
195 "data"
196 ).returning("*")
197 }`.compile()
198 expect(query).toEqual(
199 `UPDATE people SET name = data.name OUTPUT INSERTED.* FROM (values (@1),(@2)) AS [data]([name])`
200 )
201 expect(params).toEqual(["Tim", "John"])
202 })
203
204 it("update single helper returning", () => {
205 const [query, params] = sql`UPDATE people SET ${sql.update({ name: "Tim" }).returning("*")}`
206 .compile()
207 expect(query).toEqual(
208 `UPDATE people SET [name] = @1 OUTPUT INSERTED.*`
209 )
210 expect(params).toEqual(["Tim"])
211 })
212
213 for (
214 const [name, returning] of [
215 ["Identifier", sql("INSERTED.name")],
216 ["wrapped Identifier", sql`${sql("INSERTED.name")}`]
217 ] as const
218 ) {
219 it(`insert helper returning ${name}`, () => {
220 const result = sql`INSERT INTO ${sql("people")} ${sql.insert({ name: "Rowan", age: 10 }).returning(returning)}`
221 .compile()
222
223 assert.deepStrictEqual(result, [
224 `INSERT INTO [people] ([name],[age]) OUTPUT [INSERTED].[name] VALUES (@1,@2)`,
225 ["Rowan", 10]
226 ])
227 })
228
229 it(`update helper returning ${name}`, () => {
230 const result = sql`UPDATE people SET ${sql.update({ name: "Rowan" }).returning(returning)}`.compile()
231
232 assert.deepStrictEqual(result, [
233 `UPDATE people SET [name] = @1 OUTPUT [INSERTED].[name]`,
234 ["Rowan"]
235 ])
236 })
237
238 it(`updateValues helper returning ${name}`, () => {
239 const result = sql`UPDATE people SET name = data.name ${
240 sql.updateValues([{ name: "Rowan" }, { name: "Mira" }], "data").returning(returning)
241 }`.compile()
242
243 assert.deepStrictEqual(result, [
244 `UPDATE people SET name = data.name OUTPUT [INSERTED].[name] FROM (values (@1),(@2)) AS [data]([name])`,
245 ["Rowan", "Mira"]
246 ])
247 })
248 }
249
250 it("array helper", () => {
251 const [query, params] = sql`SELECT * FROM ${sql("people")} WHERE id IN ${sql.in([1, 2, "string"])}`.compile()
252 expect(query).toEqual(`SELECT * FROM [people] WHERE id IN (@1,@2,@3)`)
253 expect(params).toEqual([1, 2, "string"])
254 })
255
256 // it("param types", () => {
257 // const [query, params] = sql`SELECT * FROM ${sql("people")} WHERE id = ${
258 // sql.param(
259 // MssqlTypes.BigInt,
260 // 1
261 // )
262 // }`.compile()
263 // expect(query).toEqual(`SELECT * FROM [people] WHERE id = @1`)
264 // expect(isCustom("MssqlParam")(params[0])).toEqual(true)
265 // const param = params[0] as unknown as Custom<
266 // "MsSqlParam",
267 // any,
268 // any,
269 // any
270 // >
271 // expect(param.i0).toEqual(MssqlTypes.BigInt)
272 // expect(param.i1).toEqual(1)
273 // expect(param.i2).toEqual({})
274 // })
275
276 it("escape [", () => {
277 const [query] = sql`SELECT * FROM ${sql("peo[]ple.te[st]ing")}`.compile()
278 expect(query).toEqual(`SELECT * FROM [peo[]]ple].[te[st]]ing]`)
279 })
280
281 it.effect("returns stored procedure output parameters under output", () =>
282 Effect.gen(function*() {
283 const client = yield* MssqlClient.make({ server: "localhost" })
284 const definition = Procedure.outputParam<number>()("answer", state.type as any)(Procedure.make("get_answer"))
285 const result = yield* client.call(Procedure.compile(definition)({}))
286
287 assert.deepStrictEqual(result, { output: { answer: 42 }, rows: [] })
288 }).pipe(
289 Effect.scoped,
290 Effect.provide(Reactivity.layer)
291 ))
292
293 it.effect("cancels an in-flight Tedious request when interrupted", () =>
294 Effect.gen(function*() {
295 state.cancelCalls = 0
296 state.completeRequests = true
297 const client = yield* MssqlClient.make({ server: "localhost" })
298 state.completeRequests = false
299 const fiber = yield* Effect.forkChild(client`WAITFOR DELAY '00:01:00'`)
300 yield* Effect.yieldNow
301 const callsBeforeInterrupt = state.cancelCalls
302 yield* Fiber.interrupt(fiber)
303
304 assert.strictEqual(state.cancelCalls, callsBeforeInterrupt + 1)
305 }).pipe(
306 Effect.scoped,
307 Effect.provide(Reactivity.layer)
308 ))
309 })
310
311 const reset = () => {
312 state.cancelCalls = 0
313 state.acknowledgeCancel = true
314 state.completeRequests = true
315 state.connections = []
316 state.pendingStarted = Deferred.makeUnsafe<void>()
317 state.errorAfterConnect = false
318 state.emissionError = undefined
319 }
320
321 const makeClient = MssqlClient.make({
322 server: "localhost",
323 minConnections: 0,
324 maxConnections: 1,
325 connectionTTL: "1 hour"
326 })
327
328 const bounded = <A, E, R>(effect: Effect.Effect<A, E, R>) => effect.pipe(Effect.timeout("2 seconds"))
329
330 describe("MssqlClient connection lifecycle", { concurrent: false }, () => {
331 for (const operation of ["withoutTransforms", "call"] as const) {
332 it.live(`${operation} reuses the transaction connection with a single-connection pool`, () =>
333 Effect.gen(function*() {
334 reset()
335 const client = yield* bounded(MssqlClient.make({
336 server: "localhost",
337 minConnections: 0,
338 maxConnections: 1,
339 transformResultNames: (name) => name.toUpperCase()
340 }))
341 const definition = Procedure.outputParam<number>()("answer", state.type as any)(Procedure.make("get_answer"))
342 yield* bounded(client.withTransaction(Effect.gen(function*() {
343 if (operation === "withoutTransforms") {
344 const rows = yield* client.withoutTransforms()`SELECT value`
345 assert.deepStrictEqual(rows, [{ value: 42 }])
346 } else {
347 const result = yield* client.call(Procedure.compile(definition)({}))
348 assert.deepStrictEqual(result, { output: { answer: 42 }, rows: [] })
349 }
350 })))
351 }).pipe(Effect.provide(Reactivity.layer)))
352 }
353 it.live("handles a late error after an ended connection is discarded and recovers", () =>
354 Effect.gen(function*() {
355 reset()
356 const client = yield* bounded(makeClient)
357 const connection = state.connections[0]
358
359 // Model a dropped socket: tedious enters its Final state and emits end
360 // before delivering the queued socket error. Wait for pool cleanup, not time.
361 connection.closed = true
362 connection.emit("end")
363 yield* bounded(Deferred.await(connection.closedSignal))
364 assert.doesNotThrow(() =>
365 connection.emit("error", Object.assign(new Error("Connection lost - read ECONNRESET"), { code: "ESOCKET" }))
366 )
367
368 const rows = yield* bounded(client.unsafe("SELECT recovered"))
369 assert.deepStrictEqual(rows, [{ value: 42 }])
370 }).pipe(Effect.scoped, Effect.provide(Reactivity.layer)))
371
372 it.live("replaces a connection that ends without error after query cancellation", () =>
373 Effect.gen(function*() {
374 reset()
375 const client = yield* bounded(makeClient)
376 const connection = state.connections[0]
377 const query = yield* Effect.forkScoped(client.unsafe("SELECT pending"))
378 yield* bounded(Deferred.await(state.pendingStarted!))
379 state.acknowledgeCancel = false
380 const interrupted = yield* Effect.forkScoped(Fiber.interrupt(query))
381 yield* Effect.yieldNow
382 assert.strictEqual(connection.cancellations, 1)
383 assert.isUndefined(interrupted.pollUnsafe())
384
385 // Model tedious' cancel timeout: Final state and end, with no error event.
386 connection.close()
387 yield* bounded(Fiber.join(interrupted))
388 const rows = yield* bounded(client.unsafe("SELECT recovered"))
389 assert.deepStrictEqual(rows, [{ value: 42 }])
390 assert.strictEqual(state.connections.length, 2)
391 assert.isFalse(connection.queries.includes("SELECT recovered"))
392 assert.isTrue(state.connections[1].queries.includes("SELECT recovered"))
393 }).pipe(Effect.scoped, Effect.provide(Reactivity.layer)))
394
395 it.live("handles an error immediately after the connect callback and does not reuse the failed connection", () =>
396 Effect.gen(function*() {
397 reset()
398 const client = yield* bounded(makeClient)
399 const original = state.connections[0]
400 yield* Effect.yieldNow
401
402 // Retire the healthy connection through a normal driver error, then
403 // inject the callback race on the next acquisition of this same pool.
404 state.errorAfterConnect = true
405 original.emit("error", new Error("Connection lost"))
406 yield* bounded(Deferred.await(original.closedSignal))
407 yield* bounded(Effect.result(client.unsafe("SELECT during_race")))
408 assert.isUndefined(state.emissionError, "the driver's error emission must not throw")
409
410 const failed = state.connections[1]
411 assert.isTrue(failed.closed)
412 const rows = yield* bounded(client.unsafe("SELECT recovered"))
413 assert.deepStrictEqual(rows, [{ value: 42 }])
414 assert.isFalse(failed.queries.includes("SELECT recovered"))
415 assert.isTrue(state.connections.slice(2).some((connection) => connection.queries.includes("SELECT recovered")))
416 }).pipe(Effect.scoped, Effect.provide(Reactivity.layer)))
417 })