The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { createServer, type Server, type Socket } from "node:net"; |
| 2 | import { parseDeploymentLogRecord, tailDeploymentLogs } from "@alchemy.run/prisma/PrismaLogs"; |
| 3 | import { describe, expect, it } from "@alchemy.run/test"; |
| 4 | import * as Deferred from "effect/Deferred"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Fiber from "effect/Fiber"; |
| 7 | import * as Redacted from "effect/Redacted"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { TestClock } from "effect/testing"; |
| 10 | import { WebSocketServer } from "ws"; |
| 11 | import { Credentials } from "../../../prisma/src/internal/Credentials.ts"; |
| 12 | |
| 13 | describe("Prisma deployment logs", { tags: ["unit", "provider:prisma", "local"] }, () => { |
| 14 | it.effect("decodes compute log records into Alchemy log lines", () => |
| 15 | Effect.gen(function* () { |
| 16 | const timestamp = new Date("2026-01-01T00:00:00.000Z"); |
| 17 | const record = yield* parseDeploymentLogRecord( |
| 18 | JSON.stringify({ type: "log", text: "server started", byteStart: 0, byteEnd: 15 }), |
| 19 | timestamp, |
| 20 | ); |
| 21 | |
| 22 | expect(record).toMatchObject({ |
| 23 | _tag: "log", |
| 24 | line: { timestamp, message: "server started" }, |
| 25 | raw: { byteStart: 0, byteEnd: 15 }, |
| 26 | }); |
| 27 | }), |
| 28 | ); |
| 29 | |
| 30 | it.effect("decodes terminal records", () => |
| 31 | Effect.gen(function* () { |
| 32 | const record = yield* parseDeploymentLogRecord( |
| 33 | JSON.stringify({ |
| 34 | type: "terminal", |
| 35 | kind: "end", |
| 36 | code: "segment_time_limit", |
| 37 | message: "segment ended", |
| 38 | retryable: true, |
| 39 | cursor: "42", |
| 40 | }), |
| 41 | new Date("2026-01-01T00:00:00.000Z"), |
| 42 | ); |
| 43 | |
| 44 | expect(record).toEqual({ |
| 45 | _tag: "terminal", |
| 46 | raw: { |
| 47 | type: "terminal", |
| 48 | kind: "end", |
| 49 | code: "segment_time_limit", |
| 50 | message: "segment ended", |
| 51 | retryable: true, |
| 52 | cursor: "42", |
| 53 | }, |
| 54 | }); |
| 55 | }), |
| 56 | ); |
| 57 | |
| 58 | it.effect("fails malformed records", () => |
| 59 | Effect.gen(function* () { |
| 60 | const secret = "postgres://admin:do-not-retain@db.example.test/main"; |
| 61 | const error = yield* parseDeploymentLogRecord( |
| 62 | JSON.stringify({ type: "wat", payload: secret }), |
| 63 | new Date("2026-01-01T00:00:00.000Z"), |
| 64 | ).pipe(Effect.flip); |
| 65 | |
| 66 | expect(error).toBeInstanceOf(Error); |
| 67 | expect(error.message).toContain("type: unknown"); |
| 68 | expect(String(error)).not.toContain(secret); |
| 69 | expect(String(error.cause)).not.toContain(secret); |
| 70 | expect(JSON.stringify(error)).not.toContain(secret); |
| 71 | }), |
| 72 | ); |
| 73 | |
| 74 | it.effect("rejects non-integer deployment log byte offsets", () => |
| 75 | parseDeploymentLogRecord( |
| 76 | JSON.stringify({ type: "log", text: "partial", byteStart: 0.5, byteEnd: 7 }), |
| 77 | new Date("2026-01-01T00:00:00.000Z"), |
| 78 | ).pipe( |
| 79 | Effect.flip, |
| 80 | Effect.map((error) => { |
| 81 | expect(error.message).toContain("type: log"); |
| 82 | }), |
| 83 | ), |
| 84 | ); |
| 85 | |
| 86 | it.effect("streams log lines from Prisma's WebSocket endpoint", () => |
| 87 | withWebSocketServer((server) => |
| 88 | Effect.gen(function* () { |
| 89 | const url = yield* listenUrl(server); |
| 90 | let authorization: string | undefined; |
| 91 | |
| 92 | server.on("connection", (socket, request) => { |
| 93 | authorization = request.headers.authorization; |
| 94 | socket.send(JSON.stringify({ type: "log", text: "first", byteStart: 0, byteEnd: 5 })); |
| 95 | socket.send(JSON.stringify({ type: "log", text: "second", byteStart: 6, byteEnd: 12 })); |
| 96 | socket.send( |
| 97 | JSON.stringify({ |
| 98 | type: "terminal", |
| 99 | kind: "end", |
| 100 | code: "vm_stopped", |
| 101 | message: "done", |
| 102 | retryable: false, |
| 103 | cursor: null, |
| 104 | }), |
| 105 | ); |
| 106 | }); |
| 107 | |
| 108 | const lines = yield* tailWith(url, "deployment-1", { tail: 2 }).pipe(Stream.runCollect); |
| 109 | |
| 110 | expect(lines.map((line) => line.message)).toEqual(["first", "second"]); |
| 111 | expect(authorization).toBe("Bearer test-token"); |
| 112 | }), |
| 113 | ), |
| 114 | ); |
| 115 | |
| 116 | it.effect("rejects deployment log frames larger than 1 MiB", () => |
| 117 | withWebSocketServer((server) => |
| 118 | Effect.gen(function* () { |
| 119 | const url = yield* listenUrl(server); |
| 120 | const marker = "oversized-secret-marker"; |
| 121 | server.on("connection", (socket) => { |
| 122 | socket.send(marker.repeat(60_000)); |
| 123 | }); |
| 124 | |
| 125 | const error = yield* tailWith(url, "deployment-1").pipe(Stream.runCollect, Effect.flip); |
| 126 | |
| 127 | expect(String(error)).toContain("exceeds the 1048576-byte frame limit"); |
| 128 | expect(String(error)).not.toContain(marker); |
| 129 | expect(JSON.stringify(error)).not.toContain(marker); |
| 130 | }), |
| 131 | ), |
| 132 | ); |
| 133 | |
| 134 | it.effect("fails instead of buffering unbounded logs for a slow consumer", () => |
| 135 | withWebSocketServer((server) => |
| 136 | Effect.gen(function* () { |
| 137 | const url = yield* listenUrl(server); |
| 138 | server.on("connection", (socket) => { |
| 139 | let byteOffset = 0; |
| 140 | for (let index = 0; index < 1_000; index++) { |
| 141 | const text = `line-${index}`; |
| 142 | socket.send(logRecord(text, byteOffset)); |
| 143 | byteOffset += text.length; |
| 144 | } |
| 145 | socket.send( |
| 146 | terminalRecord({ kind: "end", code: "vm_stopped", retryable: false, cursor: null }), |
| 147 | ); |
| 148 | }); |
| 149 | |
| 150 | const error = yield* tailWith(url, "deployment-1").pipe( |
| 151 | Stream.runForEach(() => Effect.yieldNow), |
| 152 | Effect.flip, |
| 153 | ); |
| 154 | |
| 155 | expect(String(error)).toContain("consumer fell behind"); |
| 156 | expect(String(error)).toContain("64-record safety buffer"); |
| 157 | }), |
| 158 | ), |
| 159 | ); |
| 160 | |
| 161 | it.effect("reconnects from retryable terminal cursors exactly once", () => |
| 162 | withWebSocketServer((server) => |
| 163 | Effect.gen(function* () { |
| 164 | const url = yield* listenUrl(server); |
| 165 | const queries: Array<{ cursor?: string }> = []; |
| 166 | let connections = 0; |
| 167 | |
| 168 | server.on("connection", (socket, request) => { |
| 169 | connections += 1; |
| 170 | const cursor = new URL(request.url ?? "/", url).searchParams.get("cursor"); |
| 171 | queries.push(cursor === null ? {} : { cursor }); |
| 172 | if (connections === 1) { |
| 173 | socket.send(logRecord("first")); |
| 174 | const terminal = terminalRecord({ |
| 175 | kind: "end", |
| 176 | code: "segment_time_limit", |
| 177 | retryable: true, |
| 178 | cursor: "cursor-1", |
| 179 | }); |
| 180 | socket.send(terminal); |
| 181 | // A duplicate frame from the old segment must not open another |
| 182 | // reconnect in parallel. |
| 183 | socket.send(terminal); |
| 184 | return; |
| 185 | } |
| 186 | socket.send(logRecord("second", 5)); |
| 187 | socket.send( |
| 188 | terminalRecord({ kind: "end", code: "vm_stopped", retryable: false, cursor: null }), |
| 189 | ); |
| 190 | }); |
| 191 | |
| 192 | const lines = yield* tailWith(url, "deployment-1").pipe(Stream.runCollect); |
| 193 | |
| 194 | expect(lines.map((line) => line.message)).toEqual(["first", "second"]); |
| 195 | expect(connections).toBe(2); |
| 196 | expect(queries).toEqual([{}, { cursor: "cursor-1" }]); |
| 197 | }), |
| 198 | ), |
| 199 | ); |
| 200 | |
| 201 | it.effect("fails non-retryable terminal errors", () => |
| 202 | withWebSocketServer((server) => |
| 203 | Effect.gen(function* () { |
| 204 | const url = yield* listenUrl(server); |
| 205 | server.on("connection", (socket) => { |
| 206 | socket.send( |
| 207 | terminalRecord({ |
| 208 | kind: "error", |
| 209 | code: "permission_denied", |
| 210 | message: "logs are unavailable", |
| 211 | retryable: false, |
| 212 | cursor: null, |
| 213 | }), |
| 214 | ); |
| 215 | }); |
| 216 | |
| 217 | const error = yield* tailWith(url, "deployment-1").pipe(Stream.runCollect, Effect.flip); |
| 218 | |
| 219 | expect(error).toBeInstanceOf(Error); |
| 220 | expect(String(error)).toContain("permission_denied"); |
| 221 | expect(String(error)).toContain("logs are unavailable"); |
| 222 | }), |
| 223 | ), |
| 224 | ); |
| 225 | |
| 226 | it.effect("reconnects a transient close from the latest confirmed byte", () => |
| 227 | withWebSocketServer((server) => |
| 228 | Effect.gen(function* () { |
| 229 | const url = yield* listenUrl(server); |
| 230 | let connections = 0; |
| 231 | server.on("connection", (socket) => { |
| 232 | connections += 1; |
| 233 | if (connections === 1) { |
| 234 | socket.send(logRecord("partial")); |
| 235 | socket.close(1000, "unexpected end"); |
| 236 | return; |
| 237 | } |
| 238 | socket.send( |
| 239 | terminalRecord({ kind: "end", code: "vm_stopped", retryable: false, cursor: null }), |
| 240 | ); |
| 241 | }); |
| 242 | |
| 243 | const lines = yield* tailWith(url, "deployment-1").pipe(Stream.runCollect); |
| 244 | |
| 245 | expect(lines.map((line) => line.message)).toEqual(["partial"]); |
| 246 | expect(connections).toBe(2); |
| 247 | }), |
| 248 | ), |
| 249 | ); |
| 250 | |
| 251 | it.effect("reconnects a retryable null-cursor terminal from the last byte", () => |
| 252 | withWebSocketServer((server) => |
| 253 | Effect.gen(function* () { |
| 254 | const url = yield* listenUrl(server); |
| 255 | const cursors: Array<string | null> = []; |
| 256 | server.on("connection", (socket, request) => { |
| 257 | cursors.push(new URL(request.url ?? "/", url).searchParams.get("cursor")); |
| 258 | if (cursors.length === 1) { |
| 259 | socket.send(logRecord("first")); |
| 260 | socket.send( |
| 261 | terminalRecord({ |
| 262 | kind: "error", |
| 263 | code: "upstream_error", |
| 264 | retryable: true, |
| 265 | cursor: null, |
| 266 | }), |
| 267 | ); |
| 268 | return; |
| 269 | } |
| 270 | socket.send( |
| 271 | terminalRecord({ kind: "end", code: "vm_stopped", retryable: false, cursor: null }), |
| 272 | ); |
| 273 | }); |
| 274 | |
| 275 | const lines = yield* tailWith(url, "deployment-1").pipe(Stream.runCollect); |
| 276 | |
| 277 | expect(lines.map((line) => line.message)).toEqual(["first"]); |
| 278 | expect(cursors).toEqual([null, "5"]); |
| 279 | }), |
| 280 | ), |
| 281 | ); |
| 282 | |
| 283 | it.effect("fails retry loops that alternate cursors without byte progress", () => |
| 284 | withWebSocketServer((server) => |
| 285 | Effect.gen(function* () { |
| 286 | const url = yield* listenUrl(server); |
| 287 | let connections = 0; |
| 288 | server.on("connection", (socket) => { |
| 289 | connections += 1; |
| 290 | socket.send( |
| 291 | terminalRecord({ |
| 292 | kind: "end", |
| 293 | code: "segment_time_limit", |
| 294 | retryable: true, |
| 295 | cursor: connections % 2 === 0 ? "cursor-2" : "cursor-1", |
| 296 | }), |
| 297 | ); |
| 298 | }); |
| 299 | |
| 300 | const error = yield* tailWith(url, "deployment-1").pipe(Stream.runCollect, Effect.flip); |
| 301 | |
| 302 | expect(connections).toBe(4); |
| 303 | expect(String(error)).toContain("made no progress after 3 reconnect"); |
| 304 | }), |
| 305 | ), |
| 306 | ); |
| 307 | |
| 308 | it.effect("times out a WebSocket that never completes its handshake", () => |
| 309 | withSilentTcpServer((url, connected) => |
| 310 | Effect.gen(function* () { |
| 311 | const fiber = yield* tailWith(url, "deployment-1").pipe( |
| 312 | Stream.runCollect, |
| 313 | Effect.flip, |
| 314 | Effect.forkChild({ startImmediately: true }), |
| 315 | ); |
| 316 | |
| 317 | yield* connected; |
| 318 | yield* Effect.yieldNow; |
| 319 | yield* TestClock.adjust("11 seconds"); |
| 320 | const error = yield* Fiber.join(fiber); |
| 321 | |
| 322 | expect(error).toBeInstanceOf(Error); |
| 323 | expect(String(error)).toContain("WebSocket handshake timed out after 10 seconds"); |
| 324 | }).pipe(Effect.provide(TestClock.layer())), |
| 325 | ), |
| 326 | ); |
| 327 | |
| 328 | it.effect("interrupts cleanly while a WebSocket is still connecting", () => |
| 329 | withSilentTcpServer((url, connected) => |
| 330 | Effect.gen(function* () { |
| 331 | const fiber = yield* tailWith(url, "deployment-1").pipe( |
| 332 | Stream.runDrain, |
| 333 | Effect.forkChild({ startImmediately: true }), |
| 334 | ); |
| 335 | |
| 336 | yield* connected; |
| 337 | yield* Fiber.interrupt(fiber); |
| 338 | const exit = fiber.pollUnsafe(); |
| 339 | |
| 340 | expect(exit?._tag).toBe("Failure"); |
| 341 | }), |
| 342 | ), |
| 343 | ); |
| 344 | }); |
| 345 | |
| 346 | /** |
| 347 | * The credentials the carved-out logs client resolves its request from: the |
| 348 | * test WebSocket server as the API base, and a fixed service token. |
| 349 | */ |
| 350 | const tailWith = ( |
| 351 | baseUrl: string, |
| 352 | deploymentId: string, |
| 353 | query?: Parameters<typeof tailDeploymentLogs>[1], |
| 354 | ) => |
| 355 | tailDeploymentLogs(deploymentId, query).pipe( |
| 356 | Stream.provideService( |
| 357 | Credentials, |
| 358 | Effect.succeed({ apiToken: Redacted.make("test-token"), apiBaseUrl: baseUrl }), |
| 359 | ), |
| 360 | ); |
| 361 | |
| 362 | const logRecord = (text: string, byteStart = 0) => |
| 363 | JSON.stringify({ type: "log", text, byteStart, byteEnd: byteStart + text.length }); |
| 364 | |
| 365 | const terminalRecord = (input: { |
| 366 | kind: "end" | "error"; |
| 367 | code: string; |
| 368 | message?: string; |
| 369 | retryable: boolean; |
| 370 | cursor: string | null; |
| 371 | }) => JSON.stringify({ type: "terminal", message: "segment ended", ...input }); |
| 372 | |
| 373 | const withWebSocketServer = <A, E, R>(f: (server: WebSocketServer) => Effect.Effect<A, E, R>) => |
| 374 | Effect.acquireUseRelease( |
| 375 | Effect.sync(() => new WebSocketServer({ host: "127.0.0.1", port: 0 })), |
| 376 | f, |
| 377 | (server) => |
| 378 | Effect.callback<void>((resume) => { |
| 379 | // This release runs as an uninterruptible finalizer, and bun's ws |
| 380 | // shim does not reliably fire the `server.close` callback once a |
| 381 | // connection was closed server-side — terminate stragglers and |
| 382 | // bound the wait so a shim quirk can't hang the test process. |
| 383 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 384 | const done = () => { |
| 385 | if (timer !== undefined) clearTimeout(timer); |
| 386 | resume(Effect.void); |
| 387 | }; |
| 388 | for (const client of server.clients) client.terminate(); |
| 389 | timer = setTimeout(done, 1_000); |
| 390 | server.close(done); |
| 391 | }).pipe(Effect.ignore), |
| 392 | ); |
| 393 | |
| 394 | const listenUrl = (server: WebSocketServer) => |
| 395 | Effect.callback<string, Error>((resume) => { |
| 396 | const complete = () => { |
| 397 | cleanup(); |
| 398 | const address = server.address(); |
| 399 | if (address && typeof address === "object") { |
| 400 | resume(Effect.succeed(`http://127.0.0.1:${address.port}`)); |
| 401 | } else { |
| 402 | resume(Effect.fail(new Error("WebSocket server has no TCP address"))); |
| 403 | } |
| 404 | }; |
| 405 | const fail = (cause: unknown) => { |
| 406 | cleanup(); |
| 407 | resume(Effect.fail(cause instanceof Error ? cause : new Error(String(cause)))); |
| 408 | }; |
| 409 | const cleanup = () => { |
| 410 | server.off("listening", complete); |
| 411 | server.off("error", fail); |
| 412 | }; |
| 413 | |
| 414 | if (server.address()) { |
| 415 | complete(); |
| 416 | return; |
| 417 | } |
| 418 | |
| 419 | server.once("listening", complete); |
| 420 | server.once("error", fail); |
| 421 | return Effect.sync(cleanup); |
| 422 | }); |
| 423 | |
| 424 | interface SilentTcpServer { |
| 425 | server: Server; |
| 426 | sockets: Set<Socket>; |
| 427 | url: string; |
| 428 | } |
| 429 | |
| 430 | const withSilentTcpServer = <A, E, R>( |
| 431 | f: (url: string, connected: Effect.Effect<void>) => Effect.Effect<A, E, R>, |
| 432 | ) => |
| 433 | Effect.gen(function* () { |
| 434 | const connected = yield* Deferred.make<void>(); |
| 435 | return yield* Effect.acquireUseRelease( |
| 436 | Effect.callback<SilentTcpServer, Error>((resume) => { |
| 437 | const sockets = new Set<Socket>(); |
| 438 | const server = createServer((socket) => { |
| 439 | sockets.add(socket); |
| 440 | Deferred.doneUnsafe(connected, Effect.void); |
| 441 | socket.on("data", () => { |
| 442 | // Intentionally never complete the HTTP upgrade handshake. |
| 443 | }); |
| 444 | socket.on("error", () => {}); |
| 445 | socket.on("close", () => sockets.delete(socket)); |
| 446 | }); |
| 447 | const onError = (cause: Error) => { |
| 448 | cleanup(); |
| 449 | resume(Effect.fail(cause)); |
| 450 | }; |
| 451 | const onListening = () => { |
| 452 | cleanup(); |
| 453 | const address = server.address(); |
| 454 | if (!address || typeof address === "string") { |
| 455 | resume(Effect.fail(new Error("TCP server has no address"))); |
| 456 | return; |
| 457 | } |
| 458 | resume(Effect.succeed({ server, sockets, url: `http://127.0.0.1:${address.port}` })); |
| 459 | }; |
| 460 | const cleanup = () => { |
| 461 | server.off("error", onError); |
| 462 | server.off("listening", onListening); |
| 463 | }; |
| 464 | server.once("error", onError); |
| 465 | server.once("listening", onListening); |
| 466 | server.listen(0, "127.0.0.1"); |
| 467 | return Effect.sync(() => { |
| 468 | cleanup(); |
| 469 | for (const socket of sockets) socket.destroy(); |
| 470 | server.close(); |
| 471 | }); |
| 472 | }), |
| 473 | ({ url }) => f(url, Deferred.await(connected)), |
| 474 | ({ server, sockets }) => |
| 475 | Effect.callback<void>((resume) => { |
| 476 | for (const socket of sockets) socket.destroy(); |
| 477 | server.close(() => resume(Effect.void)); |
| 478 | }).pipe(Effect.ignore), |
| 479 | ); |
| 480 | }); |