The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { Config as CredentialsConfig } from "@distilled.cloud/prisma"; |
| 2 | import type { LogLine } from "alchemy/Provider"; |
| 3 | import * as Cause from "effect/Cause"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import * as Deferred from "effect/Deferred"; |
| 6 | import * as Duration from "effect/Duration"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Exit from "effect/Exit"; |
| 9 | import * as Queue from "effect/Queue"; |
| 10 | import * as Redacted from "effect/Redacted"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import type WebSocket from "ws"; |
| 13 | import type { RawData } from "ws"; |
| 14 | import { Credentials } from "./internal/Credentials.ts"; |
| 15 | import { getDeploymentLogsRequest } from "./internal/LogsClient.ts"; |
| 16 | import type { DeploymentLogsQuery } from "./Types.ts"; |
| 17 | |
| 18 | export class PrismaLogStreamError extends Data.TaggedError("PrismaLogStreamError")<{ |
| 19 | message: string; |
| 20 | cause?: unknown; |
| 21 | }> {} |
| 22 | |
| 23 | interface PrismaDeploymentLogLine { |
| 24 | type: "log"; |
| 25 | text: string; |
| 26 | byteStart: number; |
| 27 | byteEnd: number; |
| 28 | } |
| 29 | |
| 30 | interface PrismaDeploymentTerminalLine { |
| 31 | type: "terminal"; |
| 32 | kind: "end" | "error"; |
| 33 | code: string; |
| 34 | message: string; |
| 35 | retryable: boolean; |
| 36 | cursor: string | null; |
| 37 | details?: Record<string, unknown>; |
| 38 | } |
| 39 | |
| 40 | export type PrismaDeploymentLogRecord = PrismaDeploymentLogLine | PrismaDeploymentTerminalLine; |
| 41 | |
| 42 | export type ParsedDeploymentLogRecord = |
| 43 | | { _tag: "log"; line: LogLine; raw: PrismaDeploymentLogLine } |
| 44 | | { _tag: "terminal"; raw: PrismaDeploymentTerminalLine }; |
| 45 | |
| 46 | const WEBSOCKET_HANDSHAKE_TIMEOUT = "10 seconds" as const; |
| 47 | const RECONNECT_BACKOFF_MS = 100; |
| 48 | const MAX_NO_PROGRESS_RECONNECTS = 3; |
| 49 | const LOG_QUEUE_CAPACITY = 64; |
| 50 | const MAX_WEBSOCKET_PAYLOAD_BYTES = 1024 * 1024; |
| 51 | |
| 52 | export const parseDeploymentLogRecord = ( |
| 53 | message: string, |
| 54 | timestamp: Date, |
| 55 | ): Effect.Effect<ParsedDeploymentLogRecord, PrismaLogStreamError> => { |
| 56 | const byteLength = new TextEncoder().encode(message).byteLength; |
| 57 | // The socket is opened with `maxPayload`, but not every runtime's `ws` |
| 58 | // implementation enforces it (bun's ws shim delivers oversized frames), so |
| 59 | // bound the frame here too — without retaining any of its contents. |
| 60 | if (byteLength > MAX_WEBSOCKET_PAYLOAD_BYTES) { |
| 61 | return Effect.fail( |
| 62 | new PrismaLogStreamError({ |
| 63 | message: `Prisma deployment log record exceeds the ${MAX_WEBSOCKET_PAYLOAD_BYTES}-byte frame limit (${byteLength} bytes)`, |
| 64 | }), |
| 65 | ); |
| 66 | } |
| 67 | let recordType: "log" | "terminal" | "unknown" | "invalid-json" = "invalid-json"; |
| 68 | return Effect.try({ |
| 69 | try: () => { |
| 70 | const parsed = JSON.parse(message) as unknown; |
| 71 | if (parsed === null || typeof parsed !== "object") { |
| 72 | recordType = "unknown"; |
| 73 | throw new Error("Invalid Prisma deployment log record shape"); |
| 74 | } |
| 75 | const raw = parsed as Partial<PrismaDeploymentLogRecord>; |
| 76 | recordType = raw.type === "log" || raw.type === "terminal" ? raw.type : "unknown"; |
| 77 | if ( |
| 78 | raw.type === "log" && |
| 79 | typeof raw.text === "string" && |
| 80 | typeof raw.byteStart === "number" && |
| 81 | Number.isSafeInteger(raw.byteStart) && |
| 82 | raw.byteStart >= 0 && |
| 83 | typeof raw.byteEnd === "number" && |
| 84 | Number.isSafeInteger(raw.byteEnd) && |
| 85 | raw.byteEnd >= raw.byteStart |
| 86 | ) { |
| 87 | return { |
| 88 | _tag: "log" as const, |
| 89 | line: { timestamp, message: raw.text }, |
| 90 | raw: raw as PrismaDeploymentLogLine, |
| 91 | }; |
| 92 | } |
| 93 | if ( |
| 94 | raw.type === "terminal" && |
| 95 | (raw.kind === "end" || raw.kind === "error") && |
| 96 | typeof raw.code === "string" && |
| 97 | typeof raw.message === "string" && |
| 98 | typeof raw.retryable === "boolean" && |
| 99 | (raw.cursor === null || typeof raw.cursor === "string") && |
| 100 | (raw.details === undefined || |
| 101 | (raw.details !== null && typeof raw.details === "object" && !Array.isArray(raw.details))) |
| 102 | ) { |
| 103 | return { |
| 104 | _tag: "terminal" as const, |
| 105 | raw: raw as PrismaDeploymentTerminalLine, |
| 106 | }; |
| 107 | } |
| 108 | throw new Error("Invalid Prisma deployment log record shape"); |
| 109 | }, |
| 110 | catch: () => |
| 111 | new PrismaLogStreamError({ |
| 112 | message: `Failed to decode Prisma deployment log record (${byteLength} bytes; type: ${recordType})`, |
| 113 | }), |
| 114 | }); |
| 115 | }; |
| 116 | |
| 117 | export const tailDeploymentLogs = (deploymentId: string, query?: DeploymentLogsQuery) => |
| 118 | Stream.unwrap( |
| 119 | Effect.gen(function* () { |
| 120 | // Resolve the credentials on the caller's fiber once; the reconnect |
| 121 | // loop below forks with `Effect.runFork`, which cannot carry context. |
| 122 | const credentials = yield* Credentials; |
| 123 | return tailDeploymentLogsWith(yield* credentials, deploymentId, query); |
| 124 | }).pipe( |
| 125 | Effect.mapError( |
| 126 | (cause) => |
| 127 | new PrismaLogStreamError({ |
| 128 | message: "Failed to resolve Prisma credentials for log tailing", |
| 129 | cause, |
| 130 | }), |
| 131 | ), |
| 132 | ), |
| 133 | ); |
| 134 | |
| 135 | const tailDeploymentLogsWith = ( |
| 136 | credentials: CredentialsConfig, |
| 137 | deploymentId: string, |
| 138 | query?: DeploymentLogsQuery, |
| 139 | ) => |
| 140 | Stream.callback<LogLine, PrismaLogStreamError>( |
| 141 | (queue) => |
| 142 | Effect.gen(function* () { |
| 143 | const WebSocket = yield* loadWebSocketConstructor; |
| 144 | const sockets = new Set<WebSocket>(); |
| 145 | let latestCursor = query?.cursor; |
| 146 | let latestByteEnd = |
| 147 | query?.cursor !== undefined && |
| 148 | Number.isSafeInteger(Number(query.cursor)) && |
| 149 | Number(query.cursor) >= 0 |
| 150 | ? Number(query.cursor) |
| 151 | : undefined; |
| 152 | let noProgressReconnects = 0; |
| 153 | let connectionCount = 0; |
| 154 | let stopped = false; |
| 155 | |
| 156 | const end = () => { |
| 157 | if (stopped) return; |
| 158 | stopped = true; |
| 159 | Queue.endUnsafe(queue); |
| 160 | }; |
| 161 | const fail = (error: PrismaLogStreamError) => { |
| 162 | if (stopped) return; |
| 163 | stopped = true; |
| 164 | Queue.failCauseUnsafe(queue, Cause.fail(error)); |
| 165 | }; |
| 166 | |
| 167 | const connect = (cursor: string | undefined): Effect.Effect<void, PrismaLogStreamError> => |
| 168 | Effect.gen(function* () { |
| 169 | if (stopped) return; |
| 170 | const request = yield* getDeploymentLogsRequest( |
| 171 | deploymentId, |
| 172 | cursor === undefined ? query : { ...query, cursor }, |
| 173 | ).pipe( |
| 174 | Effect.provideService(Credentials, Effect.succeed(credentials)), |
| 175 | Effect.mapError( |
| 176 | () => |
| 177 | new PrismaLogStreamError({ |
| 178 | message: "Failed to prepare the Prisma deployment log stream request", |
| 179 | }), |
| 180 | ), |
| 181 | ); |
| 182 | const auth = Redacted.value(request.headers.Authorization); |
| 183 | const socket = yield* Effect.try({ |
| 184 | try: () => |
| 185 | new WebSocket(request.url, { |
| 186 | headers: { Authorization: auth }, |
| 187 | maxPayload: MAX_WEBSOCKET_PAYLOAD_BYTES, |
| 188 | }), |
| 189 | catch: () => |
| 190 | new PrismaLogStreamError({ |
| 191 | message: "Failed to open Prisma deployment log WebSocket", |
| 192 | }), |
| 193 | }); |
| 194 | if (stopped) { |
| 195 | socket.close(1000, "tail stopped"); |
| 196 | return; |
| 197 | } |
| 198 | sockets.add(socket); |
| 199 | const isReconnect = connectionCount > 0; |
| 200 | connectionCount += 1; |
| 201 | let terminalHandled = false; |
| 202 | let madeProgress = false; |
| 203 | let socketOpened = false; |
| 204 | const connectionStartByteEnd = latestByteEnd; |
| 205 | const opened = yield* Deferred.make<void, PrismaLogStreamError>(); |
| 206 | const context = yield* Effect.context<never>(); |
| 207 | |
| 208 | const scheduleReconnect = ( |
| 209 | reconnectCursor: string | undefined, |
| 210 | code: string, |
| 211 | closeMode: "close" | "terminate" | "already-closed", |
| 212 | ) => { |
| 213 | if (terminalHandled || stopped) return; |
| 214 | terminalHandled = true; |
| 215 | if (madeProgress) { |
| 216 | noProgressReconnects = 0; |
| 217 | } else if (isReconnect) { |
| 218 | noProgressReconnects += 1; |
| 219 | } |
| 220 | if (noProgressReconnects >= MAX_NO_PROGRESS_RECONNECTS) { |
| 221 | fail( |
| 222 | new PrismaLogStreamError({ |
| 223 | message: `${code}: Prisma deployment log stream made no progress after ${MAX_NO_PROGRESS_RECONNECTS} reconnect attempts`, |
| 224 | }), |
| 225 | ); |
| 226 | if (closeMode === "close") { |
| 227 | socket.close(1000, "reconnect progress limit reached"); |
| 228 | } else if (closeMode === "terminate") { |
| 229 | socket.terminate(); |
| 230 | } |
| 231 | return; |
| 232 | } |
| 233 | if (closeMode === "close") { |
| 234 | socket.close(1000, "reconnecting from latest log cursor"); |
| 235 | } else if (closeMode === "terminate") { |
| 236 | socket.terminate(); |
| 237 | } |
| 238 | Effect.sleep( |
| 239 | Duration.millis(Math.min(RECONNECT_BACKOFF_MS * 2 ** noProgressReconnects, 1_000)), |
| 240 | ).pipe( |
| 241 | Effect.andThen(connect(reconnectCursor)), |
| 242 | Effect.catch((error) => |
| 243 | Effect.sync(() => { |
| 244 | fail(error); |
| 245 | }), |
| 246 | ), |
| 247 | Effect.runFork, |
| 248 | ); |
| 249 | }; |
| 250 | |
| 251 | socket.once("open", () => { |
| 252 | if (terminalHandled || stopped) return; |
| 253 | socketOpened = true; |
| 254 | Deferred.doneUnsafe(opened, Effect.void); |
| 255 | }); |
| 256 | |
| 257 | socket.on("message", (raw) => { |
| 258 | if (terminalHandled || stopped) return; |
| 259 | const decoded = Effect.runSyncExitWith(context)( |
| 260 | parseDeploymentLogRecord(rawDataToString(raw), new Date()), |
| 261 | ); |
| 262 | if (!Exit.isSuccess(decoded)) { |
| 263 | terminalHandled = true; |
| 264 | Queue.failCauseUnsafe(queue, decoded.cause); |
| 265 | stopped = true; |
| 266 | socket.close(1000, "decode failed"); |
| 267 | return; |
| 268 | } |
| 269 | const record = decoded.value; |
| 270 | if (record._tag === "log") { |
| 271 | if (latestByteEnd !== undefined && record.raw.byteEnd <= latestByteEnd) { |
| 272 | // Exact/older replay after reconnect: drop it and keep the |
| 273 | // no-progress budget intact. |
| 274 | return; |
| 275 | } |
| 276 | if (latestByteEnd !== undefined && record.raw.byteStart < latestByteEnd) { |
| 277 | terminalHandled = true; |
| 278 | fail( |
| 279 | new PrismaLogStreamError({ |
| 280 | message: "Prisma deployment log stream returned an overlapping byte range", |
| 281 | }), |
| 282 | ); |
| 283 | socket.close(1000, "overlapping log range"); |
| 284 | return; |
| 285 | } |
| 286 | madeProgress = |
| 287 | madeProgress || |
| 288 | (connectionStartByteEnd === undefined |
| 289 | ? record.raw.byteEnd > record.raw.byteStart |
| 290 | : record.raw.byteEnd > connectionStartByteEnd); |
| 291 | latestByteEnd = record.raw.byteEnd; |
| 292 | latestCursor = String(record.raw.byteEnd); |
| 293 | if (madeProgress) noProgressReconnects = 0; |
| 294 | if (!Queue.offerUnsafe(queue, record.line)) { |
| 295 | terminalHandled = true; |
| 296 | fail( |
| 297 | new PrismaLogStreamError({ |
| 298 | message: `Prisma deployment log consumer fell behind the ${LOG_QUEUE_CAPACITY}-record safety buffer`, |
| 299 | }), |
| 300 | ); |
| 301 | socket.terminate(); |
| 302 | } |
| 303 | return; |
| 304 | } |
| 305 | |
| 306 | if (record.raw.retryable) { |
| 307 | const reconnectCursor = |
| 308 | record.raw.cursor && record.raw.cursor.length > 0 |
| 309 | ? record.raw.cursor |
| 310 | : latestCursor; |
| 311 | scheduleReconnect(reconnectCursor, record.raw.code, "close"); |
| 312 | return; |
| 313 | } |
| 314 | |
| 315 | terminalHandled = true; |
| 316 | if (record.raw.kind === "error") { |
| 317 | fail( |
| 318 | new PrismaLogStreamError({ |
| 319 | message: `${record.raw.code}: ${record.raw.message}`, |
| 320 | cause: record.raw.details, |
| 321 | }), |
| 322 | ); |
| 323 | socket.close(1000, "non-retryable terminal error"); |
| 324 | return; |
| 325 | } |
| 326 | |
| 327 | end(); |
| 328 | socket.close(1000, "terminal record received"); |
| 329 | }); |
| 330 | socket.on("error", (cause) => { |
| 331 | if (terminalHandled || stopped) return; |
| 332 | const oversized = |
| 333 | cause instanceof Error && cause.message.includes("Max payload size exceeded"); |
| 334 | const error = new PrismaLogStreamError({ |
| 335 | message: "Prisma deployment log WebSocket failed", |
| 336 | }); |
| 337 | if (!socketOpened || oversized) { |
| 338 | terminalHandled = true; |
| 339 | Deferred.doneUnsafe(opened, Effect.fail(error)); |
| 340 | fail(error); |
| 341 | return; |
| 342 | } |
| 343 | scheduleReconnect(latestCursor, "transport_error", "terminate"); |
| 344 | }); |
| 345 | socket.on("close", () => { |
| 346 | sockets.delete(socket); |
| 347 | if (!terminalHandled && !stopped) { |
| 348 | if (!socketOpened) { |
| 349 | terminalHandled = true; |
| 350 | const error = new PrismaLogStreamError({ |
| 351 | message: "Prisma deployment log WebSocket closed before opening", |
| 352 | }); |
| 353 | Deferred.doneUnsafe(opened, Effect.fail(error)); |
| 354 | fail(error); |
| 355 | return; |
| 356 | } |
| 357 | scheduleReconnect(latestCursor, "transport_closed", "already-closed"); |
| 358 | } |
| 359 | }); |
| 360 | |
| 361 | yield* Deferred.await(opened).pipe( |
| 362 | Effect.timeoutOrElse({ |
| 363 | duration: WEBSOCKET_HANDSHAKE_TIMEOUT, |
| 364 | orElse: () => { |
| 365 | const error = new PrismaLogStreamError({ |
| 366 | message: `Prisma deployment log WebSocket handshake timed out after ${WEBSOCKET_HANDSHAKE_TIMEOUT}`, |
| 367 | }); |
| 368 | return Effect.sync(() => { |
| 369 | terminalHandled = true; |
| 370 | sockets.delete(socket); |
| 371 | try { |
| 372 | socket.terminate(); |
| 373 | } catch { |
| 374 | // The socket may have closed concurrently with the timeout. |
| 375 | } |
| 376 | fail(error); |
| 377 | }).pipe(Effect.andThen(Effect.fail(error))); |
| 378 | }, |
| 379 | }), |
| 380 | ); |
| 381 | }); |
| 382 | |
| 383 | yield* Effect.addFinalizer(() => |
| 384 | Effect.sync(() => { |
| 385 | stopped = true; |
| 386 | for (const socket of sockets) { |
| 387 | try { |
| 388 | if ( |
| 389 | socket.readyState === WebSocket.CONNECTING || |
| 390 | socket.readyState === WebSocket.CLOSING |
| 391 | ) { |
| 392 | socket.terminate(); |
| 393 | } else if (socket.readyState === WebSocket.OPEN) { |
| 394 | socket.close(1000, "tail stopped"); |
| 395 | } |
| 396 | } catch { |
| 397 | // Cleanup must never turn cancellation into a finalizer defect. |
| 398 | } |
| 399 | } |
| 400 | sockets.clear(); |
| 401 | }), |
| 402 | ); |
| 403 | |
| 404 | yield* connect(query?.cursor); |
| 405 | }), |
| 406 | { bufferSize: LOG_QUEUE_CAPACITY, strategy: "dropping" }, |
| 407 | ); |
| 408 | |
| 409 | const loadWebSocketConstructor = Effect.tryPromise({ |
| 410 | try: () => import("ws").then((module) => module.default), |
| 411 | catch: (cause) => |
| 412 | new PrismaLogStreamError({ |
| 413 | message: "Prisma deployment log tailing requires the optional `ws` package.", |
| 414 | cause, |
| 415 | }), |
| 416 | }); |
| 417 | |
| 418 | const rawDataToString = (raw: RawData): string => { |
| 419 | if (typeof raw === "string") return raw; |
| 420 | if (raw instanceof ArrayBuffer) return new TextDecoder().decode(raw); |
| 421 | if (Array.isArray(raw)) return raw.map(rawDataToString).join(""); |
| 422 | return raw.toString(); |
| 423 | }; |