@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 171 lines 6.74 KB
Raw
1 import { PgClient } from "@effect/sql-pg"
2 import { PostgreSqlContainer, type StartedPostgreSqlContainer } from "@testcontainers/postgresql"
3 import { type Cause, Clock, Console, Context, Data, Effect, Exit, Fiber, Layer, Redacted, String } from "effect"
4 import { SqlClient } from "effect/sql"
5 import { getContainerRuntimeClient } from "testcontainers"
6
7 export class ContainerError extends Data.TaggedError("ContainerError")<{
8 cause: unknown
9 }> {}
10
11 class ReleaseError extends Data.TaggedError("ReleaseError")<{
12 message: string
13 cause: Cause.Cause<unknown>
14 }> {}
15
16 // it.effect and it.layer provide a TestClock that only moves when a test
17 // adjusts it, and a TestConsole that keeps output in memory. Container
18 // deadlines must read the real clock, and lifecycle logs must reach the host
19 // console.
20 const withLiveServices = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
21 effect.pipe(
22 Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),
23 Effect.provideService(Console.Console, Console.Console.defaultValue())
24 )
25
26 // testcontainers waits up to 120 seconds for a healthy container. Give up
27 // sooner so a stuck start fails with a ContainerError inside the hook budget.
28 const startupTimeout = "90 seconds"
29
30 // Leaves headroom under Vitest's ten-second cancellation-hook deadline.
31 const releaseTimeout = "8 seconds"
32
33 // A failure names the container, so whoever observes it can report it.
34 const stopAndRemove = Effect.fnUntraced(
35 function*(container: StartedPostgreSqlContainer) {
36 yield* Effect.promise(() => container.stop({ remove: false }))
37 const client = yield* Effect.promise(() => getContainerRuntimeClient())
38 const handle = client.container.getById(container.getId())
39 // Stop can return before the daemon processes the exit event; wait before removing.
40 // docker-modem can leave an aborted response pending forever. Abort each
41 // timed-out request and retry only this read-only wait, not stop or remove.
42 yield* Effect.tryPromise((signal) => handle.wait({ condition: "not-running", abortSignal: signal })).pipe(
43 Effect.timeout("2 seconds"),
44 Effect.retry({ times: 2 })
45 )
46 yield* Effect.promise(() => client.container.remove(handle, { removeVolumes: true }))
47 },
48 (effect, container) =>
49 Effect.catchCause(
50 effect,
51 (cause) => new ReleaseError({ message: `Failed to release PostgreSQL container ${container.getId()}`, cause })
52 )
53 )
54
55 // Releases the container once it has started. A start that failed leaves
56 // nothing to release, and the acquisition already reported it.
57 const release = (starting: Promise<StartedPostgreSqlContainer>) =>
58 Effect.tryPromise(() => starting).pipe(
59 Effect.flatMap(stopAndRemove),
60 Effect.catchTag("UnknownError", () => Effect.void)
61 )
62
63 const reportReleaseFailure = (error: ReleaseError) => Effect.logError(error.message, error.cause)
64
65 // Waits up to `releaseTimeout` for the release, so a slow one does not fail
66 // whichever test closes the layer. Past the wait, the release continues in the
67 // background and only then gets a reporter, so a failure is reported exactly
68 // once. Inside the wait, a failure is the caller's defect, unless the scope is
69 // closing because its fiber was interrupted: Vitest cancelling a test drops that
70 // fiber's exit, so the failure is logged instead.
71 const releaseContainer = Effect.fnUntraced(
72 function*(starting: Promise<StartedPostgreSqlContainer>, exit: Exit.Exit<unknown, unknown>) {
73 const fiber = yield* Effect.forkDetach(release(starting))
74 const waited = Exit.hasInterrupts(exit)
75 ? Effect.catch(Fiber.join(fiber), reportReleaseFailure)
76 : Effect.orDie(Fiber.join(fiber))
77 yield* Effect.timeoutOrElse(waited, {
78 duration: releaseTimeout,
79 orElse: () =>
80 Effect.andThen(
81 Effect.logWarning(
82 `PostgreSQL container release is taking longer than ${releaseTimeout}, continuing in the background`
83 ),
84 Effect.forkDetach(Effect.catch(Fiber.join(fiber), reportReleaseFailure))
85 )
86 })
87 },
88 withLiveServices
89 )
90
91 let databases = 0
92
93 const runAdmin = (container: StartedPostgreSqlContainer, statement: string) =>
94 SqlClient.SqlClient.use((sql) => sql.unsafe(statement)).pipe(
95 Effect.provide(PgClient.layer({ url: Redacted.make(container.getConnectionUri()) })),
96 Effect.timeout("10 seconds"),
97 Effect.orDie,
98 withLiveServices
99 )
100
101 export class PgContainer extends Context.Service<PgContainer>()("test/PgContainer", {
102 // The start runs outside the acquisition, so waiting for it stays
103 // interruptible. The release owns the container from the moment the start
104 // begins, so one that finishes starting after its waiter gave up is still
105 // released.
106 make: Effect.gen(function*() {
107 const starting = yield* Effect.acquireRelease(
108 // @effect-diagnostics-next-line lazyPromiseInEffectSync:off
109 Effect.sync(() => new PostgreSqlContainer("postgres:alpine").start()),
110 releaseContainer
111 )
112 return yield* Effect.tryPromise({
113 try: () => starting,
114 catch: (cause) => new ContainerError({ cause })
115 }).pipe(
116 Effect.timeoutOrElse({
117 duration: startupTimeout,
118 orElse: () =>
119 Effect.fail(
120 new ContainerError({ cause: new Error(`PostgreSQL container did not start within ${startupTimeout}`) })
121 )
122 })
123 )
124 }).pipe(withLiveServices)
125 }) {
126 static readonly layer = Layer.effect(this)(this.make)
127
128 static layerClient = Layer.unwrap(
129 Effect.gen(function*() {
130 const container = yield* PgContainer
131 return PgClient.layer({
132 url: Redacted.make(container.getConnectionUri())
133 })
134 })
135 ).pipe(Layer.provide(this.layer))
136
137 /**
138 * A client for a database of its own on a shared container. Tests that each
139 * need an empty database share one container this way, so container startup
140 * stays out of their time budget. The database is dropped after the client
141 * closes.
142 */
143 static layerClientDatabase = Layer.unwrap(
144 Effect.gen(function*() {
145 const container = yield* PgContainer
146 const database = `test_${++databases}`
147 yield* Effect.acquireRelease(
148 runAdmin(container, `CREATE DATABASE ${database}`),
149 () => runAdmin(container, `DROP DATABASE ${database} WITH (FORCE)`)
150 )
151 return PgClient.layer({
152 host: container.getHost(),
153 port: container.getPort(),
154 database,
155 username: container.getUsername(),
156 password: Redacted.make(container.getPassword())
157 })
158 })
159 )
160
161 static layerClientWithTransforms = Layer.unwrap(
162 Effect.gen(function*() {
163 const container = yield* PgContainer
164 return PgClient.layer({
165 url: Redacted.make(container.getConnectionUri()),
166 transformResultNames: String.snakeToCamel,
167 transformQueryNames: String.camelToSnake
168 })
169 })
170 ).pipe(Layer.provide(this.layer))
171 }