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

main
ts 177 lines 8.29 KB
Raw
1 import { assert, describe, it } from "@effect/vitest"
2 import { Cause, Effect, Exit, Fiber, Option } from "effect"
3 import { TestClock } from "effect/testing"
4 import * as Http from "node:http"
5 import { BoundPorts, getContainerRuntimeClient } from "testcontainers"
6 import { afterAll, beforeAll, vi } from "vitest"
7 import { pgWaitStrategy, releasePgContainer } from "./utils.ts"
8
9 // Less than the existing 30s integration hook limit, including all retry attempts.
10 const cleanupBudget = "25 seconds"
11 const testTimeout = 28_000
12 // Bounds each wait attempt; the fake daemon answers a healthy wait well within it.
13 const releaseOptions = { waitTimeout: "1 second" } as const
14
15 describe("PostgreSQL container lifecycle", () => {
16 const requests = new Map<string, Array<string>>()
17 const interruptedResponses = new Map<string, number>()
18 const unexpected: Array<string> = []
19 let infoRequests = 0
20 const server = Http.createServer((request, response) => {
21 const url = new URL(request.url!, "http://localhost")
22 response.setHeader("Content-Type", "application/json")
23 // Bun re-sends a request that fails on a reused keep-alive socket. Fresh
24 // connections keep one HTTP request per release attempt on every runtime.
25 response.setHeader("Connection", "close")
26 if (url.pathname === "/info") {
27 infoRequests++
28 response.end(JSON.stringify({ ServerVersion: "27.0.0", OperatingSystem: "Docker", OSType: "linux" }))
29 return
30 }
31 const match = /^\/containers\/([^/]+)(\/wait|\/json|\/exec)?$/.exec(url.pathname)
32 if (match === null || !requests.has(match[1])) {
33 unexpected.push(request.method + " " + request.url)
34 response.writeHead(404).end(JSON.stringify({ message: "Unexpected request" }))
35 return
36 }
37 const id = match[1]
38 const steps = requests.get(id)!
39 if (request.method === "GET" && match[2] === "/json") {
40 steps.push("inspect")
41 response.end(
42 JSON.stringify({ Id: id, State: { Status: "running", Running: true, Health: { Status: "healthy" } } })
43 )
44 } else if (request.method === "POST" && match[2] === "/exec") {
45 // An exec that never completes, as observed under Deno in CI.
46 steps.push("exec")
47 } else if (request.method === "POST" && match[2] === "/wait") {
48 steps.push("wait")
49 assert.strictEqual(url.searchParams.get("condition"), "not-running")
50 const attempt = steps.filter((step) => step === "wait").length
51 // A wait response that never arrives, as observed under Bun in CI.
52 if (id === "wait-hangs") return void response.flushHeaders()
53 if (id === "always-interrupted" || attempt === 1) {
54 // Docker flushes the wait headers before writing its JSON body. Close
55 // after a partial body, deterministically exercising docker-modem's
56 // aborted-response path, not a probabilistic keep-alive reuse race.
57 response.flushHeaders()
58 response.write("{\"StatusCode\":", () => {
59 interruptedResponses.set(id, (interruptedResponses.get(id) ?? 0) + 1)
60 response.socket!.end()
61 })
62 } else {
63 response.end(JSON.stringify({ StatusCode: 137 }))
64 }
65 } else if (request.method === "DELETE" && match[2] === undefined) {
66 steps.push("remove")
67 assert.strictEqual(url.searchParams.get("v"), "true")
68 response.writeHead(204).end()
69 } else {
70 unexpected.push(request.method + " " + request.url)
71 response.writeHead(404).end(JSON.stringify({ message: "Unexpected request" }))
72 }
73 })
74
75 beforeAll(async () => {
76 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))
77 const address = server.address()
78 if (address === null || typeof address === "string") throw new Error("Expected a TCP listener")
79 vi.stubEnv("DOCKER_HOST", "tcp://127.0.0.1:" + address.port)
80 vi.stubEnv("DOCKER_TLS_VERIFY", "0")
81 // Initialize the real testcontainers/dockerode client against our daemon.
82 // It is cached for this isolated test file; no real Docker is required.
83 try {
84 await getContainerRuntimeClient()
85 assert.strictEqual(infoRequests, 1, "runtime client must use the mock daemon")
86 } finally {
87 vi.unstubAllEnvs()
88 }
89 })
90
91 afterAll(async () => {
92 await new Promise<void>((resolve, reject) => {
93 // Register closure before destroying connections: Bun also stops the
94 // listener in closeAllConnections, so closing it afterwards fails.
95 server.close((error) => error ? reject(error) : resolve())
96 server.closeAllConnections()
97 })
98 })
99
100 it.live("startup readiness does not depend on docker exec completing", () =>
101 Effect.gen(function*() {
102 requests.set("exec-hangs", [])
103 const client = yield* Effect.promise(() => getContainerRuntimeClient())
104 const ports = new BoundPorts()
105 ports.setBinding(5432, (server.address() as { port: number }).port)
106 const result = yield* Effect.promise(() =>
107 pgWaitStrategy().waitUntilReady(client.container.getById("exec-hangs"), ports)
108 ).pipe(Effect.timeoutOption("5 seconds"))
109 assert.isTrue(Option.isSome(result), "readiness waited on a docker exec that never completed")
110 assert.deepStrictEqual(requests.get("exec-hangs"), ["inspect"])
111 assert.deepStrictEqual(unexpected, [])
112 }), testTimeout)
113
114 const container = (id: string) => {
115 const steps: Array<string> = []
116 requests.set(id, steps)
117 return {
118 getId: () => id,
119 stop: async (options: { remove: boolean }) => {
120 assert.deepStrictEqual(options, { remove: false })
121 steps.push("stop")
122 }
123 }
124 }
125
126 it.live("retries an interrupted wait response before removing the container", () =>
127 Effect.gen(function*() {
128 const result = yield* releasePgContainer(container("retry-succeeds"), releaseOptions).pipe(
129 Effect.exit,
130 Effect.timeoutOption(cleanupBudget)
131 )
132 assert.strictEqual(interruptedResponses.get("retry-succeeds"), 1, "daemon did not interrupt the first wait")
133 assert.isTrue(Option.isSome(result), "teardown exceeded the cleanup budget")
134 if (Option.isNone(result)) return
135 assert.isTrue(Exit.isSuccess(result.value), "teardown failed instead of retrying")
136 assert.deepStrictEqual(requests.get("retry-succeeds"), ["stop", "wait", "wait", "remove"])
137 assert.deepStrictEqual(unexpected, [])
138 }), testTimeout)
139
140 it.live(
141 "surfaces repeated interrupted waits within the cleanup budget without removing",
142 () =>
143 Effect.gen(function*() {
144 const result = yield* releasePgContainer(container("always-interrupted"), releaseOptions).pipe(
145 Effect.exit,
146 Effect.timeoutOption(cleanupBudget)
147 )
148 assert.isAtLeast(interruptedResponses.get("always-interrupted")!, 1, "daemon did not interrupt a wait")
149 assert.isTrue(Option.isSome(result), "teardown hung instead of reporting exhausted retries")
150 if (Option.isNone(result)) return
151 assert.isTrue(Exit.isFailure(result.value), "cleanup failure was suppressed")
152 if (Exit.isSuccess(result.value)) return
153 assert.isFalse(Cause.hasInterruptsOnly(result.value.cause), "failure must be visible, not just interruption")
154 const steps = requests.get("always-interrupted")!
155 assert.strictEqual(steps[0], "stop")
156 assert.isAtLeast(interruptedResponses.get("always-interrupted")!, 2)
157 assert.isAtMost(interruptedResponses.get("always-interrupted")!, 3)
158 assert.isFalse(steps.includes("remove"), "remove ran without a successful wait")
159 assert.deepStrictEqual(unexpected, [])
160 }),
161 testTimeout
162 )
163
164 // `it.layer` provides TestClock to fixture layers, so their finalizers
165 // run with it during afterAll.
166 it.effect("bounds a hung wait under the test services used by it.layer", () =>
167 Effect.gen(function*() {
168 const fiber = yield* Effect.forkChild(
169 releasePgContainer(container("wait-hangs"), releaseOptions).pipe(Effect.exit)
170 )
171 const result = yield* Fiber.join(fiber).pipe(Effect.timeoutOption(cleanupBudget), TestClock.withLive)
172 assert.isTrue(Option.isSome(result), "teardown hung instead of reporting exhausted retries")
173 if (Option.isNone(result)) return yield* Fiber.interrupt(fiber)
174 assert.isTrue(Exit.isFailure(result.value), "cleanup failure was suppressed")
175 assert.isFalse(requests.get("wait-hangs")!.includes("remove"), "remove ran without a successful wait")
176 }), testTimeout)
177 })