From 0c6b6764f01b76dc00de0acc54c8e4273c3003a9 Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:36:35 -0800 Subject: [PATCH 1/2] An emulator WebSocket endpoint: echo and paced messages, hosted and local GET /_emulate/openai/websocket accepts a WebSocket upgrade and echoes each message, text or binary, as it was received. With ?chunks=N&interval_ms=M, the paced-answer controls, it also sends N messages of its own, M ms apart, then stays open, for a busy connection or an idle one. It closes when the client closes, answering with the client's code. An emulator control, not OpenAI's Realtime or WebSocket-mode protocol, which stay unsupported. Core gains upgradeWebSocket(request, session) for routes, on both hosts: a WebSocketPair on the Workers runtime (binary messages may arrive as a Blob, read in order), and on Node a server side of RFC 6455 in serve's upgrade handler (masked client frames, fragments, ping/pong, the closing handshake, a 1 MiB message limit). The response finaliser passes a 101 through, and the ledger records an upgrade without reading a body. --- README.md | 2 +- apps/web/app/docs/openai/page.mdx | 2 + .../core/src/__tests__/websocket.test.ts | 86 ++++++++++ packages/@emulators/core/src/http.ts | 22 +++ packages/@emulators/core/src/index.ts | 1 + packages/@emulators/core/src/ledger.ts | 14 +- .../@emulators/core/src/websocket-node.ts | 161 ++++++++++++++++++ packages/@emulators/core/src/websocket.ts | 118 +++++++++++++ .../openai/src/__tests__/websocket.test.ts | 87 ++++++++++ packages/@emulators/openai/src/index.ts | 2 + packages/@emulators/openai/src/manifest.ts | 10 ++ .../@emulators/openai/src/routes/websocket.ts | 49 ++++++ skills/openai/SKILL.md | 9 + 13 files changed, 557 insertions(+), 6 deletions(-) create mode 100644 packages/@emulators/core/src/__tests__/websocket.test.ts create mode 100644 packages/@emulators/core/src/websocket-node.ts create mode 100644 packages/@emulators/core/src/websocket.ts create mode 100644 packages/@emulators/openai/src/__tests__/websocket.test.ts create mode 100644 packages/@emulators/openai/src/routes/websocket.ts diff --git a/README.md b/README.md index 8a575fad2..bc3942726 100644 --- a/README.md +++ b/README.md @@ -1116,7 +1116,7 @@ openai: answer: { text: "...600 or more characters...", stream: { chunks: 600, interval_ms: 500 } } ``` -A key's `rate_limit` (or `POST /_emulate/openai/keys/:name/rate-limit`) answers `429 rate_limit_exceeded` with `Retry-After` and `x-ratelimit-*-requests` for that key only. Token counts are approximate (one token per four characters) and identical in responses and in `GET /_emulate/openai/usage`, which lists every call with its key, model, tokens, whether it streamed and the request size. Request bodies over 64 KiB are recorded in the ledger by size only. Request bodies are limited to 32 MiB (33,554,432 bytes), the emulator's own limit since OpenAI documents no overall one for these endpoints (only 50 MB across the files in one request); a larger body is refused before it is read with `413` and `{"error":{"type":"invalid_request_error","code":"request_too_large"}}`. Tools, images, audio, embeddings, stored responses and the Realtime and WebSocket transports are not emulated. +A key's `rate_limit` (or `POST /_emulate/openai/keys/:name/rate-limit`) answers `429 rate_limit_exceeded` with `Retry-After` and `x-ratelimit-*-requests` for that key only. Token counts are approximate (one token per four characters) and identical in responses and in `GET /_emulate/openai/usage`, which lists every call with its key, model, tokens, whether it streamed and the request size. Request bodies over 64 KiB are recorded in the ledger by size only. Request bodies are limited to 32 MiB (33,554,432 bytes), the emulator's own limit since OpenAI documents no overall one for these endpoints (only 50 MB across the files in one request); a larger body is refused before it is read with `413` and `{"error":{"type":"invalid_request_error","code":"request_too_large"}}`. Tools, images, audio, embeddings, stored responses and OpenAI's Realtime and WebSocket transports are not emulated. A WebSocket endpoint, an emulator control and not OpenAI's Realtime or WebSocket-mode protocol: `GET /_emulate/openai/websocket` (`ws://` locally, `wss://` hosted) accepts the upgrade and echoes each message, text or binary, as it was received. With `?chunks=N&interval_ms=M`, the same controls as the paced answers, it also sends N messages of its own (`{"type":"emulate.message","n":1,"of":N,"at":...}`) M ms apart, then stays open, so a client can hold a busy connection or an idle one for as long as it likes. It closes when the client closes, answering with the client's close code (1000 for a normal close). ## Zapier MCP diff --git a/apps/web/app/docs/openai/page.mdx b/apps/web/app/docs/openai/page.mdx index 35a91c41f..984f07bc0 100644 --- a/apps/web/app/docs/openai/page.mdx +++ b/apps/web/app/docs/openai/page.mdx @@ -38,6 +38,8 @@ openai: Rules match on `model`, `contains` (any text in the request), `last_user_equals` and `instructions_contains`; `times` limits how often a rule applies. `stream` paces a streamed answer as exactly `chunks` deltas `interval_ms` apart. Control calls: `POST /_emulate/openai/answers/queue`, `POST /_emulate/openai/answers/rules`, `GET /_emulate/openai/answers`. +A WebSocket endpoint, an emulator control and not OpenAI's Realtime or WebSocket-mode protocol: `GET /_emulate/openai/websocket` (`ws://` locally, `wss://` hosted) accepts the upgrade and echoes each message, text or binary, as it was received. With `?chunks=N&interval_ms=M`, the same controls as the paced answers, it also sends N messages of its own (`{"type":"emulate.message","n":1,"of":N,"at":...}`) M ms apart, then stays open, so a client can hold a busy connection or an idle one for as long as it likes. It closes when the client closes, answering with the client's close code (1000 for a normal close). + ## Per-key limits ```bash diff --git a/packages/@emulators/core/src/__tests__/websocket.test.ts b/packages/@emulators/core/src/__tests__/websocket.test.ts new file mode 100644 index 000000000..910a77982 --- /dev/null +++ b/packages/@emulators/core/src/__tests__/websocket.test.ts @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { upgradeWebSocket } from "../websocket.js"; + +type Listener = (event: Record) => void; + +/** A stand-in for the Workers runtime's WebSocketPair: records what the server end does. */ +class FakeSocket { + sent: Array = []; + closedWith: [number, string] | null = null; + accepted = false; + private listeners = new Map(); + accept() { + this.accepted = true; + } + send(data: string | ArrayBuffer) { + this.sent.push(data); + } + close(code: number, reason: string) { + this.closedWith = [code, reason]; + } + addEventListener(type: string, fn: Listener) { + this.listeners.set(type, [...(this.listeners.get(type) ?? []), fn]); + } + emit(type: string, event: Record) { + for (const fn of this.listeners.get(type) ?? []) fn(event); + } +} + +let server: FakeSocket; +const g = globalThis as Record; +const original = g.WebSocketPair; +const RealResponse = Response; +afterEach(() => { + g.WebSocketPair = original; + g.Response = RealResponse; +}); +function installPair() { + // Node's Response refuses status 101; the Workers runtime allows it with a webSocket. + g.Response = class extends RealResponse { + constructor(body?: ConstructorParameters[0], init?: ResponseInit) { + super(body, init?.status === 101 ? { ...init, status: 200 } : init); + if (init?.status === 101) Object.defineProperty(this, "status", { value: 101 }); + } + }; + (globalThis as Record).WebSocketPair = class { + 0 = new FakeSocket(); + 1 = (server = new FakeSocket()); + }; +} + +const upgrade = () => new Request("https://emulators.dev/x", { headers: { upgrade: "websocket" } }); + +describe("upgradeWebSocket on the Workers runtime", () => { + it("answers 101, reads Blob messages in order, sends binary as its own buffer, and echoes the client's close", async () => { + installPair(); + const got: Array = []; + const closes: number[] = []; + const res = upgradeWebSocket(upgrade(), { + message: (peer, data) => { + got.push(data); + peer.send(data); + }, + close: (code) => closes.push(code), + }); + expect(res.status).toBe(101); + expect(server.accepted).toBe(true); + server.emit("message", { data: new Blob([new Uint8Array([1, 2, 3])]) }); + server.emit("message", { data: "after" }); + server.emit("message", { data: new Uint8Array([9]).buffer }); + await new Promise((r) => setTimeout(r, 20)); + expect(got.map((d) => (typeof d === "string" ? d : [...d]))).toEqual([[1, 2, 3], "after", [9]]); + expect(server.sent[0]).toBeInstanceOf(ArrayBuffer); + expect([...new Uint8Array(server.sent[0] as ArrayBuffer)]).toEqual([1, 2, 3]); + server.emit("close", { code: 1000, reason: "bye" }); + expect(server.closedWith).toEqual([1000, "bye"]); + expect(closes).toEqual([1000]); + }); + + it("answers a close without a code with 1000, and a plain request with 426", () => { + installPair(); + upgradeWebSocket(upgrade(), {}); + server.emit("close", { code: 1005, reason: "" }); + expect(server.closedWith).toEqual([1000, ""]); + expect(upgradeWebSocket(new Request("https://emulators.dev/x"), {}).status).toBe(426); + }); +}); diff --git a/packages/@emulators/core/src/http.ts b/packages/@emulators/core/src/http.ts index 32b111aec..2de36c9a2 100644 --- a/packages/@emulators/core/src/http.ts +++ b/packages/@emulators/core/src/http.ts @@ -1,4 +1,6 @@ import { createServer as createNodeServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import { takeWebSocketSession } from "./websocket.js"; +import { acceptNodeWebSocket } from "./websocket-node.js"; type BodyInit = ConstructorParameters[0]; type HeadersInit = ConstructorParameters[0]; @@ -189,6 +191,8 @@ export class Context { finalize(response: Response): Response { if (!hasHeaders(this.responseHeaders)) return response; + // A WebSocket upgrade (101, carrying the socket) must reach the host untouched. + if (response.status === 101) return response; const headers = new Headers(response.headers); this.responseHeaders.forEach((value, key) => { headers.set(key, value); @@ -391,6 +395,24 @@ export function serve(options: ServeOptions): Server { res.end(message); } }); + // WebSocket upgrades go through the same handler; a route that accepts one + // answers with a session (see websocket.ts), and anything else is sent back as + // a plain HTTP answer before the socket is closed. + server.on("upgrade", async (req: IncomingMessage, socket, head: Buffer) => { + try { + const response = await options.fetch(nodeRequestToFetchRequest(req)); + const session = takeWebSocketSession(response); + if (session && acceptNodeWebSocket(req.headers, socket, head, session)) return; + const status = session ? 400 : response.status; + const body = session ? "Invalid WebSocket handshake." : await response.text(); + socket.end( + `HTTP/1.1 ${status} ${status === 400 ? "Bad Request" : response.statusText || "Error"}\r\n` + + `Content-Type: text/plain; charset=utf-8\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`, + ); + } catch { + socket.destroy(); + } + }); server.listen(port, options.hostname); return server; } diff --git a/packages/@emulators/core/src/index.ts b/packages/@emulators/core/src/index.ts index 1f450e4d4..dfe5a49e2 100644 --- a/packages/@emulators/core/src/index.ts +++ b/packages/@emulators/core/src/index.ts @@ -13,6 +13,7 @@ export { deserializeValue, } from "./store.js"; export { createServer, type ServerOptions } from "./server.js"; +export { upgradeWebSocket, isWebSocketUpgrade, type WebSocketPeer, type WebSocketSession } from "./websocket.js"; export { Hono, Context, diff --git a/packages/@emulators/core/src/ledger.ts b/packages/@emulators/core/src/ledger.ts index fae40fa5f..9f5f90c5e 100644 --- a/packages/@emulators/core/src/ledger.ts +++ b/packages/@emulators/core/src/ledger.ts @@ -1,3 +1,4 @@ +import { WEBSOCKET_SESSION_HEADER } from "./websocket.js"; import type { MiddlewareHandler } from "./http.js"; import type { AppEnv, AuthUser, AuthApp } from "./middleware/auth.js"; import type { WebhookDispatcher } from "./webhooks.js"; @@ -194,11 +195,14 @@ export function createLedgerMiddleware(ledger: RequestLedger, options: LedgerOpt } if (!response) return; - const responseBody = c.get("ledgerOmitResponseBody") - ? { body: BINARY_BODY_OMITTED } - : isStreamingContentType(response.headers.get("content-type") ?? "") - ? { body: STREAMING_BODY_OMITTED } - : await readBody(response.clone(), maxBodyChars); + const upgraded = response.status === 101 || response.headers.has(WEBSOCKET_SESSION_HEADER); + const responseBody = upgraded + ? { body: "" } + : c.get("ledgerOmitResponseBody") + ? { body: BINARY_BODY_OMITTED } + : isStreamingContentType(response.headers.get("content-type") ?? "") + ? { body: STREAMING_BODY_OMITTED } + : await readBody(response.clone(), maxBodyChars); const route = c.req.routePath; const operationId = c.get("operationId"); const sideEffects = (c.get("ledgerEffects") as LedgerSideEffect[] | undefined) ?? []; diff --git a/packages/@emulators/core/src/websocket-node.ts b/packages/@emulators/core/src/websocket-node.ts new file mode 100644 index 000000000..25c735f6f --- /dev/null +++ b/packages/@emulators/core/src/websocket-node.ts @@ -0,0 +1,161 @@ +import { createHash } from "crypto"; +import type { Duplex } from "stream"; +import type { WebSocketPeer, WebSocketSession } from "./websocket.js"; + +// The server side of RFC 6455 for Node's `upgrade` event: the opening handshake, +// client frames (always masked; fragmented messages reassembled), ping/pong, and +// the closing handshake. Enough for the emulator's own WebSocket controls. + +const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; +/** The largest message accepted; a bigger one closes the connection with 1009. */ +export const MAX_WEBSOCKET_MESSAGE_BYTES = 1024 * 1024; + +const OP = { continuation: 0x0, text: 0x1, binary: 0x2, close: 0x8, ping: 0x9, pong: 0xa } as const; + +function frame(opcode: number, payload: Uint8Array): Buffer { + const len = payload.length; + const head = len < 126 ? Buffer.alloc(2) : len < 65536 ? Buffer.alloc(4) : Buffer.alloc(10); + head[0] = 0x80 | opcode; + if (len < 126) head[1] = len; + else if (len < 65536) { + head[1] = 126; + head.writeUInt16BE(len, 2); + } else { + head[1] = 127; + head.writeBigUInt64BE(BigInt(len), 2); + } + return Buffer.concat([head, payload]); +} + +function closePayload(code: number, reason: string): Buffer { + const text = Buffer.from(reason, "utf8").subarray(0, 123); + const out = Buffer.alloc(2 + text.length); + out.writeUInt16BE(code, 0); + text.copy(out, 2); + return out; +} + +/** Complete the opening handshake on `socket` and run `session`; false when the request is not a valid upgrade. */ +export function acceptNodeWebSocket( + headers: Record, + socket: Duplex, + head: Buffer, + session: WebSocketSession, +): boolean { + const key = headers["sec-websocket-key"]; + if (typeof key !== "string" || headers["sec-websocket-version"] !== "13") return false; + const accept = createHash("sha1") + .update(key + GUID) + .digest("base64"); + socket.write( + "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + + `Sec-WebSocket-Accept: ${accept}\r\n\r\n`, + ); + + let buffer: Buffer = head.length ? Buffer.from(head) : Buffer.alloc(0); + let fragments: Buffer[] = []; + let fragmentOpcode = 0; + let fragmentBytes = 0; + let closeSent = false; + let finished = false; + + const finish = (code: number, reason: string) => { + if (finished) return; + finished = true; + session.close?.(code, reason); + }; + const peer: WebSocketPeer = { + send(data) { + if (closeSent || socket.destroyed) return; + socket.write(typeof data === "string" ? frame(OP.text, Buffer.from(data, "utf8")) : frame(OP.binary, data)); + }, + close(code = 1000, reason = "") { + if (closeSent || socket.destroyed) return; + closeSent = true; + socket.write(frame(OP.close, closePayload(code, reason))); + finish(code, reason); + // The client answers with its own close frame and ends the connection; end ours after a grace period. + setTimeout(() => socket.destroy(), 2000).unref?.(); + }, + }; + + const fail = (code: number, reason: string) => { + peer.close(code, reason); + }; + + socket.on("data", (chunk: Buffer) => { + buffer = buffer.length ? Buffer.concat([buffer, chunk]) : chunk; + for (;;) { + if (buffer.length < 2) return; + const fin = (buffer[0]! & 0x80) !== 0; + const opcode = buffer[0]! & 0x0f; + const masked = (buffer[1]! & 0x80) !== 0; + let len = buffer[1]! & 0x7f; + let offset = 2; + if (len === 126) { + if (buffer.length < 4) return; + len = buffer.readUInt16BE(2); + offset = 4; + } else if (len === 127) { + if (buffer.length < 10) return; + const big = buffer.readBigUInt64BE(2); + if (big > BigInt(MAX_WEBSOCKET_MESSAGE_BYTES)) return fail(1009, "message too big"); + len = Number(big); + offset = 10; + } + if (!masked) return fail(1002, "client frames must be masked"); + if (len > MAX_WEBSOCKET_MESSAGE_BYTES) return fail(1009, "message too big"); + if (buffer.length < offset + 4 + len) return; + const mask = buffer.subarray(offset, offset + 4); + const payload = Buffer.from(buffer.subarray(offset + 4, offset + 4 + len)); + for (let i = 0; i < payload.length; i++) payload[i]! ^= mask[i & 3]!; + buffer = buffer.subarray(offset + 4 + len); + + if (opcode === OP.close) { + const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1005; + const reason = payload.length > 2 ? payload.subarray(2).toString("utf8") : ""; + if (!closeSent) { + closeSent = true; + // Echo the code, as the closing handshake asks (1005 means none was given: answer 1000). + socket.write(frame(OP.close, payload.length >= 2 ? payload.subarray(0, 2) : closePayload(1000, ""))); + } + finish(code, reason); + socket.end(); + return; + } + if (opcode === OP.ping) { + if (!closeSent) socket.write(frame(OP.pong, payload)); + continue; + } + if (opcode === OP.pong) continue; + if (opcode === OP.text || opcode === OP.binary) { + if (fragments.length) return fail(1002, "new message before the last one finished"); + if (fin) { + session.message?.(peer, opcode === OP.text ? payload.toString("utf8") : new Uint8Array(payload)); + } else { + fragments = [payload]; + fragmentOpcode = opcode; + fragmentBytes = payload.length; + } + continue; + } + if (opcode === OP.continuation) { + if (!fragments.length) return fail(1002, "continuation without a message"); + fragments.push(payload); + fragmentBytes += payload.length; + if (fragmentBytes > MAX_WEBSOCKET_MESSAGE_BYTES) return fail(1009, "message too big"); + if (fin) { + const whole = Buffer.concat(fragments); + fragments = []; + session.message?.(peer, fragmentOpcode === OP.text ? whole.toString("utf8") : new Uint8Array(whole)); + } + continue; + } + return fail(1002, `unknown opcode ${opcode}`); + } + }); + socket.on("close", () => finish(1006, "")); + socket.on("error", () => socket.destroy()); + session.open?.(peer); + return true; +} diff --git a/packages/@emulators/core/src/websocket.ts b/packages/@emulators/core/src/websocket.ts new file mode 100644 index 000000000..ecce04c75 --- /dev/null +++ b/packages/@emulators/core/src/websocket.ts @@ -0,0 +1,118 @@ +/** + * Server-side WebSockets for emulator routes, on two hosts with one interface: + * + * - Cloudflare Workers (and Durable Objects): a `WebSocketPair`, answered with a 101. + * - Node (`serve` in http.ts): the route answers with a marker header; the server's + * `upgrade` handler finds the session by it and speaks RFC 6455 on the socket. + * + * A route builds a `WebSocketSession` and returns `upgradeWebSocket(request, session)`. + */ + +export interface WebSocketPeer { + send(data: string | Uint8Array): void; + /** Close with a status code (1000, normal, by default). */ + close(code?: number, reason?: string): void; +} + +export interface WebSocketSession { + open?(peer: WebSocketPeer): void; + message?(peer: WebSocketPeer, data: string | Uint8Array): void; + /** The connection closed, by either side; `code` is the close code received or sent. */ + close?(code: number, reason: string): void; +} + +/** Header a Node route response carries so `serve` can find the session to attach. */ +export const WEBSOCKET_SESSION_HEADER = "x-emulate-websocket-session"; + +const pending = new Map(); + +/** True when the request asks to upgrade to a WebSocket. */ +export function isWebSocketUpgrade(request: Request): boolean { + return (request.headers.get("upgrade") ?? "").toLowerCase() === "websocket"; +} + +interface WorkersWebSocket { + accept(): void; + send(data: string | ArrayBuffer | Uint8Array): void; + close(code?: number, reason?: string): void; + addEventListener(type: "message", fn: (event: { data: string | ArrayBuffer | Blob }) => void): void; + addEventListener(type: "close", fn: (event: { code: number; reason: string }) => void): void; + addEventListener(type: "error", fn: () => void): void; +} + +/** Accept the upgrade and run `session` on the connection. A request that is not an upgrade gets a 426. */ +export function upgradeWebSocket(request: Request, session: WebSocketSession): Response { + if (!isWebSocketUpgrade(request)) { + return new Response("Expected a WebSocket upgrade (Upgrade: websocket).", { + status: 426, + headers: { upgrade: "websocket", "content-type": "text/plain; charset=utf-8" }, + }); + } + const Pair = (globalThis as { WebSocketPair?: new () => Record }).WebSocketPair; + if (Pair) { + const pair = new Pair(); + const [client, server] = [pair[0]!, pair[1]!]; + server.accept(); + let closed = false; + const peer: WebSocketPeer = { + send: (data) => { + // Binary goes out as its own ArrayBuffer, which the runtime takes over. + if (!closed) server.send(typeof data === "string" ? data : data.slice().buffer); + }, + close: (code = 1000, reason = "") => { + if (closed) return; + closed = true; + server.close(code, reason); + session.close?.(code, reason); + }, + }; + // Binary messages can arrive as a Blob (the default binaryType in some runtimes), + // which is read asynchronously; a queue keeps messages in the order they came. + try { + (server as { binaryType?: string }).binaryType = "arraybuffer"; + } catch { + // not supported: Blobs are read below + } + let queue: Promise = Promise.resolve(); + server.addEventListener("message", (event) => { + const data = event.data as string | ArrayBuffer | Blob; + queue = queue.then(async () => { + const message = + typeof data === "string" + ? data + : data instanceof ArrayBuffer + ? new Uint8Array(data).slice() + : new Uint8Array(await data.arrayBuffer()); + session.message?.(peer, message); + }); + }); + server.addEventListener("close", (event) => { + if (closed) return; + closed = true; + // Answer the client's close with the same code, completing the closing handshake. + try { + server.close(event.code === 1005 ? 1000 : event.code, event.reason); + } catch { + // already closed + } + session.close?.(event.code, event.reason); + }); + server.addEventListener("error", () => peer.close(1011, "error")); + session.open?.(peer); + return new Response(null, { status: 101, webSocket: client } as ResponseInit); + } + const now = Date.now(); + for (const [id, entry] of pending) if (entry.expires < now) pending.delete(id); + const id = crypto.randomUUID(); + pending.set(id, { session, expires: now + 30_000 }); + return new Response(null, { status: 200, headers: { [WEBSOCKET_SESSION_HEADER]: id } }); +} + +/** The session a Node route response named, once; used by `serve`'s upgrade handler. */ +export function takeWebSocketSession(response: Response): WebSocketSession | undefined { + const id = response.headers.get(WEBSOCKET_SESSION_HEADER); + if (!id) return undefined; + const entry = pending.get(id); + pending.delete(id); + return entry?.session; +} diff --git a/packages/@emulators/openai/src/__tests__/websocket.test.ts b/packages/@emulators/openai/src/__tests__/websocket.test.ts new file mode 100644 index 000000000..28fcd9824 --- /dev/null +++ b/packages/@emulators/openai/src/__tests__/websocket.test.ts @@ -0,0 +1,87 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; +import { openaiPlugin } from "../index.js"; + +const servers: FreePortServer[] = []; +afterEach(async () => { + await Promise.all(servers.splice(0).map((s) => s.close())); +}); + +async function start() { + const http = await serveOnFreePort({ hostname: "127.0.0.1" }); + servers.push(http); + const base = `127.0.0.1:${http.port}`; + const emulator = createServer(openaiPlugin, { baseUrl: `http://${base}` }); + http.use(emulator.app.fetch); + return { base, emulator }; +} + +/** Open a socket with Node's own WebSocket client and collect what arrives. */ +function connect(url: string) { + const ws = new WebSocket(url); + ws.binaryType = "arraybuffer"; + const received: Array<{ data: string | ArrayBuffer; at: number }> = []; + const opened = new Promise((resolve, reject) => { + ws.addEventListener("open", () => resolve()); + ws.addEventListener("error", () => reject(new Error("socket error"))); + }); + const closed = new Promise<{ code: number; wasClean: boolean }>((resolve) => + ws.addEventListener("close", (e) => resolve(e as unknown as { code: number; wasClean: boolean })), + ); + ws.addEventListener("message", (e) => received.push({ data: (e as MessageEvent).data, at: Date.now() })); + const until = async (n: number, ms = 5000) => { + const end = Date.now() + ms; + while (received.length < n && Date.now() < end) await new Promise((r) => setTimeout(r, 5)); + return received; + }; + return { ws, received, opened, closed, until }; +} + +describe("emulator WebSocket control", () => { + it("echoes text and binary messages and closes cleanly with the client's code", async () => { + const { base } = await start(); + const c = connect(`ws://${base}/_emulate/openai/websocket`); + await c.opened; + c.ws.send("hello"); + c.ws.send(new Uint8Array([0, 1, 2, 255])); + const long = "x".repeat(70_000); // a 64-bit length frame + c.ws.send(long); + const got = await c.until(3); + expect(got[0]!.data).toBe("hello"); + expect([...new Uint8Array(got[1]!.data as ArrayBuffer)]).toEqual([0, 1, 2, 255]); + expect(got[2]!.data).toBe(long); + c.ws.close(1000, "done"); + const e = await c.closed; + expect([e.code, e.wasClean]).toEqual([1000, true]); + }); + + it("sends the asked number of messages, interval apart, then stays open until closed", async () => { + const { base } = await start(); + const c = connect(`ws://${base}/_emulate/openai/websocket?chunks=4&interval_ms=60`); + await c.opened; + const t0 = Date.now(); + const got = await c.until(4); + expect(got.map((m) => JSON.parse(m.data as string).n)).toEqual([1, 2, 3, 4]); + expect(got.every((m) => JSON.parse(m.data as string).of === 4)).toBe(true); + expect(got[3]!.at - t0).toBeGreaterThanOrEqual(4 * 60 - 15); + for (let i = 1; i < 4; i++) expect(got[i]!.at - got[i - 1]!.at).toBeGreaterThanOrEqual(45); + // Still open and still echoing after the paced messages. + await new Promise((r) => setTimeout(r, 150)); + expect(c.received).toHaveLength(4); + c.ws.send("still here"); + expect((await c.until(5))[4]!.data).toBe("still here"); + c.ws.close(); + const e = await c.closed; + expect(e.wasClean).toBe(true); + }); + + it("answers a plain GET with 426 and refuses bad pacing values", async () => { + const { base } = await start(); + const plain = await fetch(`http://${base}/_emulate/openai/websocket`); + expect(plain.status).toBe(426); + expect(plain.headers.get("upgrade")).toBe("websocket"); + expect((await fetch(`http://${base}/_emulate/openai/websocket?chunks=-1`)).status).toBe(400); + const bad = connect(`ws://${base}/_emulate/openai/websocket?interval_ms=60001`); + await expect(bad.opened).rejects.toThrow(); + }); +}); diff --git a/packages/@emulators/openai/src/index.ts b/packages/@emulators/openai/src/index.ts index 935426b51..efdd22892 100644 --- a/packages/@emulators/openai/src/index.ts +++ b/packages/@emulators/openai/src/index.ts @@ -6,6 +6,7 @@ import { responsesRoutes } from "./routes/responses.js"; import { chatRoutes } from "./routes/chat.js"; import { modelRoutes } from "./routes/models.js"; import { controlRoutes } from "./routes/control.js"; +import { websocketRoutes } from "./routes/websocket.js"; import { MAX_REQUEST_BYTES, requestTooLargeResponse } from "./common.js"; export { getOpenAIStore, type OpenAIStore } from "./store.js"; @@ -77,6 +78,7 @@ export const openaiPlugin: ServicePlugin = { return next(); }); controlRoutes(ctx); + websocketRoutes(ctx); responsesRoutes(ctx); chatRoutes(ctx); modelRoutes(ctx); diff --git a/packages/@emulators/openai/src/manifest.ts b/packages/@emulators/openai/src/manifest.ts index 65197cec4..f35273491 100644 --- a/packages/@emulators/openai/src/manifest.ts +++ b/packages/@emulators/openai/src/manifest.ts @@ -27,6 +27,16 @@ export const manifest: ServiceManifest = { kind: "provider-specific", title: "WebSocket and Realtime transports", status: "unsupported", + notes: "OpenAI's own WebSocket protocols (the Realtime API and WebSocket mode) are not emulated.", + }, + { + id: "websocket-control", + kind: "provider-specific", + title: "Emulator WebSocket endpoint (echo and paced messages)", + status: "supported", + basePath: "/_emulate/openai/websocket", + notes: + "An emulator control, not OpenAI behaviour: GET /_emulate/openai/websocket accepts the upgrade and echoes each message as it was received; ?chunks=N&interval_ms=M (the paced-answer controls) also sends N messages of its own, M ms apart, then stays open. It closes when the client closes, answering with the client's code. A deploy of the hosted emulator ends open connections.", }, ], auth: [ diff --git a/packages/@emulators/openai/src/routes/websocket.ts b/packages/@emulators/openai/src/routes/websocket.ts new file mode 100644 index 000000000..bcc8c62f5 --- /dev/null +++ b/packages/@emulators/openai/src/routes/websocket.ts @@ -0,0 +1,49 @@ +import type { RouteContext, WebSocketSession } from "@emulators/core"; +import { upgradeWebSocket } from "@emulators/core"; +import { MAX_CHUNKS, MAX_INTERVAL_MS } from "../answers.js"; + +/** + * GET /_emulate/openai/websocket: an emulator control, not OpenAI's Realtime or + * WebSocket protocol. It accepts the upgrade and echoes each message it receives, + * text or binary, as it was. With `?chunks=N&interval_ms=M` (the paced-answer + * controls) it also sends N messages of its own, M ms apart, then stays open, so a + * client can hold a busy connection or an idle one. Either side may close; a close + * from the client is answered with the same code. + */ +export function websocketRoutes({ app }: RouteContext): void { + app.get("/_emulate/openai/websocket", (c) => { + const chunks = c.req.query("chunks") ?? "0"; + const interval = c.req.query("interval_ms") ?? "0"; + const n = Number(chunks); + const ms = Number(interval); + if (!Number.isInteger(n) || n < 0 || n > MAX_CHUNKS) { + return c.json({ error: "invalid_request", message: `chunks must be an integer from 0 to ${MAX_CHUNKS}.` }, 400); + } + if (!Number.isInteger(ms) || ms < 0 || ms > MAX_INTERVAL_MS) { + return c.json( + { error: "invalid_request", message: `interval_ms must be an integer from 0 to ${MAX_INTERVAL_MS}.` }, + 400, + ); + } + let timer: ReturnType | undefined; + const session: WebSocketSession = { + open(peer) { + let sent = 0; + const tick = () => { + if (sent >= n) return; + sent++; + peer.send(JSON.stringify({ type: "emulate.message", n: sent, of: n, at: new Date().toISOString() })); + if (sent < n) timer = setTimeout(tick, ms); + }; + if (n > 0) timer = setTimeout(tick, ms); + }, + message(peer, data) { + peer.send(data); + }, + close() { + if (timer) clearTimeout(timer); + }, + }; + return upgradeWebSocket(c.req.raw, session); + }); +} diff --git a/skills/openai/SKILL.md b/skills/openai/SKILL.md index e47cc7f1a..029f49125 100644 --- a/skills/openai/SKILL.md +++ b/skills/openai/SKILL.md @@ -51,6 +51,15 @@ curl -X POST "$OPENAI_EMULATOR_URL/_emulate/openai/keys/primary/rate-limit" -H " curl "$OPENAI_EMULATOR_URL/_emulate/openai/usage" ``` +## WebSocket endpoint + +An emulator control, not OpenAI's Realtime or WebSocket protocol: it echoes each message and can send messages of its own at a pace. + +```bash +# Echo only; or add ?chunks=600&interval_ms=1000 for 600 messages a second apart +npx wscat -c "wss://emulators.dev/openai//_emulate/openai/websocket?chunks=600&interval_ms=1000" +``` + ## Discovery `GET /_emulate/manifest` lists what is supported, partial and unsupported (tools, images, audio, embeddings, stored responses and Realtime are not emulated). `GET /_emulate/ledger` records each call with its operation id, status and key name; request bodies over 64 KiB are recorded by size only, and bodies over 32 MiB are refused with `413 request_too_large`. Per-service docs live at `https://docs.emulators.dev/openai`. From 2eef800c9182f423c8f31640241fb96ed26719db Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:41:30 -0800 Subject: [PATCH 2/2] Measure the WebSocket test's pacing between messages, and close clients first --- .../openai/src/__tests__/websocket.test.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/@emulators/openai/src/__tests__/websocket.test.ts b/packages/@emulators/openai/src/__tests__/websocket.test.ts index 28fcd9824..f9789f238 100644 --- a/packages/@emulators/openai/src/__tests__/websocket.test.ts +++ b/packages/@emulators/openai/src/__tests__/websocket.test.ts @@ -3,7 +3,11 @@ import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/c import { openaiPlugin } from "../index.js"; const servers: FreePortServer[] = []; +const sockets: WebSocket[] = []; afterEach(async () => { + // Clients first: a server cannot finish closing while a WebSocket is still open on it. + for (const ws of sockets.splice(0)) if (ws.readyState <= 1) ws.close(); + await new Promise((r) => setTimeout(r, 20)); await Promise.all(servers.splice(0).map((s) => s.close())); }); @@ -19,6 +23,7 @@ async function start() { /** Open a socket with Node's own WebSocket client and collect what arrives. */ function connect(url: string) { const ws = new WebSocket(url); + sockets.push(ws); ws.binaryType = "arraybuffer"; const received: Array<{ data: string | ArrayBuffer; at: number }> = []; const opened = new Promise((resolve, reject) => { @@ -57,14 +62,14 @@ describe("emulator WebSocket control", () => { it("sends the asked number of messages, interval apart, then stays open until closed", async () => { const { base } = await start(); - const c = connect(`ws://${base}/_emulate/openai/websocket?chunks=4&interval_ms=60`); + const c = connect(`ws://${base}/_emulate/openai/websocket?chunks=4&interval_ms=100`); await c.opened; - const t0 = Date.now(); const got = await c.until(4); expect(got.map((m) => JSON.parse(m.data as string).n)).toEqual([1, 2, 3, 4]); expect(got.every((m) => JSON.parse(m.data as string).of === 4)).toBe(true); - expect(got[3]!.at - t0).toBeGreaterThanOrEqual(4 * 60 - 15); - for (let i = 1; i < 4; i++) expect(got[i]!.at - got[i - 1]!.at).toBeGreaterThanOrEqual(45); + // The server's timer starts when it opens, before the client sees the open: measure the spacing. + expect(got[3]!.at - got[0]!.at).toBeGreaterThanOrEqual(3 * 100 - 30); + for (let i = 1; i < 4; i++) expect(got[i]!.at - got[i - 1]!.at).toBeGreaterThanOrEqual(60); // Still open and still echoing after the paced messages. await new Promise((r) => setTimeout(r, 150)); expect(c.received).toHaveLength(4);