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
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ Documentation is a separate site at `https://docs.emulators.dev`. Per-service do

### Deployment

The emulator worker is named `emulate-hosts`. It serves `emulators.dev/*` (the apex catalog) and `*.emulators.dev/*`, that is every service and instance subdomain. The `EmulatorDurableObject` class is declared through a wrangler `migrations` entry (`new_classes`). Each stateful instance is backed by one `EmulatorDurableObject`; the store snapshot, the request ledger, armed faults, every token the instance has issued (OAuth access tokens, API keys, bearer credentials, and their revocations) and webhook subscriptions are persisted to Durable Object storage, so an instance keeps them across eviction and deploys. The ledger and tokens are saved after every request, reads included (each ledger entry once, as its own value); the store after every write. Values over the storage limit for a single value are split across several, so a large body saves like any other. A save that fails never changes the answer: the response goes out and the failure is listed at `GET /_emulate/persistence`, and the next save catches up. A deploy still closes open streams, which clients reconnect. Hosted emulators are HTTPS only: a plain `http` request is redirected to the same address over `https` with a `308`, which keeps the method and body.
The emulator worker is named `emulate-hosts`. It serves `emulators.dev/*` (the apex catalog) and `*.emulators.dev/*`, that is every service and instance subdomain. The `EmulatorDurableObject` class is declared through a wrangler `migrations` entry (`new_classes`). Each stateful instance is backed by one `EmulatorDurableObject`; the store snapshot, the request ledger, armed faults, every token the instance has issued (OAuth access tokens, API keys, bearer credentials, and their revocations) and webhook subscriptions are persisted to Durable Object storage, so an instance keeps them across eviction and deploys. The ledger and tokens are saved after every request, reads included (each ledger entry once, as its own value); the store after every write. Values over the storage limit for a single value are split across several, so a large body saves like any other. A save that fails never changes the answer: the response goes out and the failure is listed at `GET /_emulate/persistence`, and the next save catches up. A deploy still closes open streams, which clients reconnect. Each instance runs in a Durable Object with 128 MB of memory, and an isolate that runs out is reset with every request in it, so hosted instances refuse what would exhaust it rather than fail: a request body over 16 MiB (32 MiB for the OpenAI emulator) is refused with a `413` before it is read, in the provider's error shape where it has one, and a write that would take an instance's stored data past 32 MiB is refused with a `507` (`instance_storage_full`; reset or re-seed the instance). `GET /_emulate/persistence` shows the stored size and the budget. Request bodies over 1 MiB are recorded in the ledger by size only. Hosted emulators are HTTPS only: a plain `http` request is redirected to the same address over `https` with a `308`, which keeps the method and body.

The docs site (`apps/web`, worker name `emulate-docs`) serves `docs.emulators.dev`. Because that host is more specific than `*.emulators.dev`, it wins for docs traffic.

Expand Down Expand Up @@ -1078,7 +1078,7 @@ x:

### Media

`POST /2/media/upload` (one request), `POST /2/media/upload/initialize`, `/:id/append`, `/:id/finalize` and `GET /2/media/upload?command=STATUS` (all `media.write`). Attach with `attachments: [{ media_id }]` on a send. Participants download with `GET /2/dm_conversations/media/:dm_id/:media_key/:media_id` (`dm.read`), streamed; `includes.media[].url` points there.
`POST /2/media/upload` (one request), `POST /2/media/upload/initialize`, `/:id/append`, `/:id/finalize` and `GET /2/media/upload?command=STATUS` (all `media.write`). Attach with `attachments: [{ media_id }]` on a send. Participants download with `GET /2/dm_conversations/media/:dm_id/:media_key/:media_id` (`dm.read`), streamed; `includes.media[].url` points there. Pace a DM attachment's download with `stream: { chunks, interval_ms }` on a seeded or arriving attachment, or `POST /_emulate/x/media/:media_key/stream`, the same controls as the OpenAI emulator's paced answers: exactly `chunks` pieces `interval_ms` apart (for example 90 MiB as 300 pieces 100 ms apart arrives in about 30 s). An emulator control, not X behaviour; downloads are unpaced unless asked, and `{"stream": null}` clears it.

### Webhooks and the X Activity API

Expand Down 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. 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 the Realtime and WebSocket transports are not emulated.

## Zapier MCP

Expand Down
2 changes: 1 addition & 1 deletion apps/web/app/docs/deployment/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ OAuth and OpenID Connect discovery documents (`/.well-known/oauth-protected-reso

## Instance model

The `emulate-hosts` worker serves `emulators.dev/*` (the apex catalog) and `*.emulators.dev/*` (service and instance hosts). Each stateful instance is backed by one Cloudflare Durable Object. The `EmulatorDurableObject` class is declared through a wrangler `migrations` entry (`new_classes`), and the instance state, the request ledger, armed faults, every token the instance has issued (revocations included) and webhook subscriptions are kept in Durable Object storage, so an instance keeps them across eviction and deploys. A save that fails never changes the answer; the failure is listed at `GET /_emulate/persistence`. A deploy still closes open streams, which clients reconnect. Hosted emulators are HTTPS only: plain `http` is redirected to `https` with a `308`.
The `emulate-hosts` worker serves `emulators.dev/*` (the apex catalog) and `*.emulators.dev/*` (service and instance hosts). Each stateful instance is backed by one Cloudflare Durable Object. The `EmulatorDurableObject` class is declared through a wrangler `migrations` entry (`new_classes`), and the instance state, the request ledger, armed faults, every token the instance has issued (revocations included) and webhook subscriptions are kept in Durable Object storage, so an instance keeps them across eviction and deploys. A save that fails never changes the answer; the failure is listed at `GET /_emulate/persistence`. A deploy still closes open streams, which clients reconnect. Each instance runs in a Durable Object with 128 MB of memory, and an isolate that runs out is reset with every request in it, so hosted instances refuse what would exhaust it rather than fail: a request body over 16 MiB (32 MiB for the OpenAI emulator) is refused with a `413` before it is read, in the provider's error shape where it has one, and a write that would take an instance's stored data past 32 MiB is refused with a `507` (`instance_storage_full`; reset or re-seed the instance). `GET /_emulate/persistence` shows the stored size and the budget. Request bodies over 1 MiB are recorded in the ledger by size only. Hosted emulators are HTTPS only: plain `http` is redirected to `https` with a `308`.

```text
POST https://github.emulators.dev/_emulate/instances
Expand Down
2 changes: 1 addition & 1 deletion apps/web/app/docs/openai/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@ That key answers `429` with code `rate_limit_exceeded`, `Retry-After` in seconds

## Usage and the ledger

Token counts are approximate: one token per four characters of text, rounded up. They are the same in every response and in `GET /_emulate/openai/usage`, which lists each call with its key, model, input and output tokens, whether it streamed and the request size, with totals. Request bodies over 64 KiB are recorded in `/_emulate/ledger` by size only.
Token counts are approximate: one token per four characters of text, rounded up. They are the same in every response and in `GET /_emulate/openai/usage`, which lists each call with its key, model, input and output tokens, whether it streamed and the request size, with totals. Request bodies over 64 KiB are recorded in `/_emulate/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"}}`.
2 changes: 1 addition & 1 deletion apps/web/app/docs/x/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ x:
- `POST /2/media/upload` — the whole file, base64 in JSON or raw in multipart
- `POST /2/media/upload/initialize`, `POST /2/media/upload/:id/append`, `POST /2/media/upload/:id/finalize` — chunked, segments up to 8 MB
- `GET /2/media/upload?command=STATUS&media_id=...`
- `GET /2/dm_conversations/media/:dm_id/:media_key/:media_id` — the attachment's bytes for a participant, streamed with `content-length`
- `GET /2/dm_conversations/media/:dm_id/:media_key/:media_id` — the attachment's bytes for a participant, streamed with `content-length`. Pace a DM attachment's download with `stream: { chunks, interval_ms }` on a seeded or arriving attachment, or `POST /_emulate/x/media/:media_key/stream`, the same controls as the OpenAI emulator's paced answers: exactly `chunks` pieces `interval_ms` apart (for example 90 MiB as 300 pieces 100 ms apart arrives in about 30 s). An emulator control, not X behaviour; downloads are unpaced unless asked, and `{"stream": null}` clears it.

Seeded attachments are deterministic placeholder bytes of the declared size. No transcoding happens; video reports `succeeded` at once.

Expand Down
32 changes: 28 additions & 4 deletions packages/@emulators/cloudflare/src/__tests__/hosted-writes.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { writeFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { ChunkedStorage, STORAGE_VALUE_LIMIT } from "../chunked-storage.js";
import { EmulatorDurableObject } from "../durable-object.js";
import { EmulatorDurableObject, INSTANCE_STORE_BUDGET_BYTES } from "../durable-object.js";
import worker, { type Env } from "../worker.js";

type Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -151,9 +151,33 @@ describe("what a hosted request writes", () => {
const issue = (await (await h.call(`${base}/repos/ada/widget/issues/${number}`, { headers: auth })).json()) as Json;
expect(issue.body.length).toBe(body.length);
const ledger = (await (await h.call(`${base}/_emulate/ledger`)).json()) as Json;
expect(
(ledger.entries as Json[]).find((e) => e.method === "POST" && e.path.endsWith("/issues"))!.request.bodyTruncated,
).toBe(true);
// A body over 1 MiB is recorded by its size, without a second copy of it.
const entry = (ledger.entries as Json[]).find((e) => e.method === "POST" && e.path.endsWith("/issues"))!;
expect(entry.request.bodyBytes).toBeGreaterThan(8 * 1024 * 1024);
expect(String(entry.request.body)).toMatch(/^<request body omitted: \d+ bytes>$/);
}, 60000);

it("refuses a write that would take the instance past its store budget, and keeps answering reads", async () => {
const h = hosted();
await h.json(`${base}/__seed`, seed);
const auth = await credential(h);
const body = "x".repeat(8 * 1024 * 1024);
const statuses: number[] = [];
for (let i = 0; i < 4; i++) {
statuses.push((await h.json(`${base}/repos/ada/widget/issues`, { title: `big ${i}`, body }, auth)).status);
}
expect(statuses).toEqual([201, 201, 201, 507]);
// The refusal names the budget; a small write still fits under it.
const refused = (await (
await h.json(`${base}/repos/ada/widget/issues`, { title: "again", body }, auth)
).json()) as Json;
expect(refused.error).toBe("instance_storage_full");
expect((await h.json(`${base}/repos/ada/widget/issues`, { title: "small" }, auth)).status).toBe(201);
expect((await h.call(`${base}/repos/ada/widget/issues/1`, { headers: auth })).status).toBe(200);
const persistence = (await (await h.call(`${base}/_emulate/persistence`)).json()) as Json;
expect(persistence.stored_bytes).toBeGreaterThan(24 * 1024 * 1024);
expect(persistence.budget_bytes).toBe(INSTANCE_STORE_BUDGET_BYTES);
expect(persistence.failures).toEqual([]);
}, 60000);

it("answers even when storage refuses the write, and shows the failure on the control plane", async () => {
Expand Down
144 changes: 144 additions & 0 deletions packages/@emulators/cloudflare/src/__tests__/request-limits.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { describe, expect, it } from "vitest";
import { MAX_REQUEST_BYTES as OPENAI_MAX } from "@emulators/openai";
import { EmulatorDurableObject } from "../durable-object.js";
import { HOSTED_MAX_REQUEST_BYTES } from "../services.js";
import worker, { type Env } from "../worker.js";

type Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any

function memoryState() {
const map = new Map<string, unknown>();
const copy = <T>(v: unknown): T => JSON.parse(JSON.stringify(v)) as T;
return {
storage: {
get: async <T>(k: string) => (map.has(k) ? copy<T>(map.get(k)) : undefined),
put: async (k: string, v: unknown) => void map.set(k, copy(v)),
delete: async (k: string | string[]) =>
Array.isArray(k) ? k.filter((x) => map.delete(x)).length : map.delete(k),
list: async <T>(o?: { prefix?: string }) =>
new Map([...map].filter(([k]) => !o?.prefix || k.startsWith(o.prefix)).map(([k, v]) => [k, copy<T>(v)])),
},
blockConcurrencyWhile: <T>(fn: () => Promise<T>) => fn(),
};
}

function hosted() {
const objects = new Map<string, EmulatorDurableObject>();
const fetched: string[] = [];
const env = {
EMULATE_HOST_SUFFIX: "emulators.dev",
EMULATOR: {
idFromName: (name: string) => name,
get(id: unknown) {
const key = String(id);
if (!objects.has(key)) objects.set(key, new EmulatorDurableObject(memoryState() as never, {}));
const object = objects.get(key)!;
return {
fetch: (request: Request) => {
fetched.push(new URL(request.url).pathname);
return object.fetch(request);
},
};
},
},
} as unknown as Env;
return { call: (req: Request) => worker.fetch(req, env), fetched };
}

/** A body that claims `length` bytes and fails the test if anyone reads it. */
function unreadable(): ReadableStream<Uint8Array> {
return new ReadableStream({
pull() {
throw new Error("the body was read");
},
});
}

/** A body of `bytes` bytes with no declared length, sent in 1 MiB pieces. */
function chunked(bytes: number, prefix = ""): ReadableStream<Uint8Array> {
const enc = new TextEncoder();
let sent = 0;
let first = true;
return new ReadableStream({
pull(controller) {
if (sent >= bytes) return controller.close();
const head = first ? enc.encode(prefix) : new Uint8Array(0);
first = false;
const n = Math.min(1024 * 1024, bytes - sent) - head.length;
const piece = new Uint8Array(head.length + n).fill(97);
piece.set(head, 0);
sent += piece.length;
controller.enqueue(piece);
},
});
}

const post = (url: string, body: RequestInit["body"], headers: Record<string, string>) =>
new Request(url, { method: "POST", headers, body, duplex: "half" } as RequestInit);

describe("request bodies over the hosted limit", () => {
it("refuses an oversized OpenAI body with OpenAI's 413 shape, without reading it or reaching the instance", async () => {
const h = hosted();
const res = await h.call(
post("https://emulators.dev/openai/run/v1/responses", unreadable(), {
"content-type": "application/json",
"content-length": String(100 * 1024 * 1024),
authorization: "Bearer sk-proj-emulate-default-key",
}),
);
expect(res.status).toBe(413);
expect(await res.json()).toEqual({
error: {
message: `Request body too large. The emulator accepts request bodies of up to ${OPENAI_MAX} bytes.`,
type: "invalid_request_error",
param: null,
code: "request_too_large",
},
});
expect(h.fetched).toEqual([]);
});

it("refuses a body of undeclared length once it passes the limit", async () => {
const h = hosted();
const res = await h.call(
post("https://emulators.dev/openai/run/v1/responses", chunked(OPENAI_MAX + 1, '{"input":"'), {
"content-type": "application/json",
authorization: "Bearer sk-proj-emulate-default-key",
}),
);
expect(res.status).toBe(413);
expect(((await res.json()) as Json).error.code).toBe("request_too_large");
expect(h.fetched).toEqual([]);
});

it("refuses other services' oversized bodies with the hosted limit", async () => {
const h = hosted();
const res = await h.call(
post("https://emulators.dev/github/run/repos/a/b/issues", unreadable(), {
"content-type": "application/json",
"content-length": String(HOSTED_MAX_REQUEST_BYTES + 1),
}),
);
expect(res.status).toBe(413);
expect(((await res.json()) as Json).error).toBe("request_too_large");
expect(h.fetched).toEqual([]);
});

it("passes a body at the limit through, declared or not", async () => {
const h = hosted();
const input = "a".repeat(2 * 1024 * 1024);
const body = JSON.stringify({ model: "gpt-5-mini", input });
const auth = { "content-type": "application/json", authorization: "Bearer sk-proj-emulate-default-key" };
const declared = await h.call(
post("https://emulators.dev/openai/run/v1/responses", body, { ...auth, "content-length": String(body.length) }),
);
expect(declared.status).toBe(200);
const undeclared = await h.call(
post("https://emulators.dev/openai/run/v1/responses", new Blob([body]).stream(), auth),
);
expect(undeclared.status).toBe(200);
expect(((await undeclared.json()) as Json).usage.input_tokens).toBe(
((await declared.json()) as Json).usage.input_tokens,
);
});
});
Loading
Loading