Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions apps/web/app/docs/openai/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
86 changes: 86 additions & 0 deletions packages/@emulators/core/src/__tests__/websocket.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { afterEach, describe, expect, it } from "vitest";
import { upgradeWebSocket } from "../websocket.js";

type Listener = (event: Record<string, unknown>) => void;

/** A stand-in for the Workers runtime's WebSocketPair: records what the server end does. */
class FakeSocket {
sent: Array<string | ArrayBuffer> = [];
closedWith: [number, string] | null = null;
accepted = false;
private listeners = new Map<string, Listener[]>();
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<string, unknown>) {
for (const fn of this.listeners.get(type) ?? []) fn(event);
}
}

let server: FakeSocket;
const g = globalThis as Record<string, unknown>;
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<typeof Response>[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<string, unknown>).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<string | Uint8Array> = [];
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);
});
});
22 changes: 22 additions & 0 deletions packages/@emulators/core/src/http.ts
Original file line number Diff line number Diff line change
@@ -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<typeof Response>[0];
type HeadersInit = ConstructorParameters<typeof Headers>[0];
Expand Down Expand Up @@ -189,6 +191,8 @@ export class Context<E = unknown, _P extends string = string> {

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);
Expand Down Expand Up @@ -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;
}
Expand Down
1 change: 1 addition & 0 deletions packages/@emulators/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
14 changes: 9 additions & 5 deletions packages/@emulators/core/src/ledger.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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: "<websocket upgrade>" }
: 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) ?? [];
Expand Down
161 changes: 161 additions & 0 deletions packages/@emulators/core/src/websocket-node.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | string[] | undefined>,
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;
}
Loading
Loading