From 29a592752a265ae1277b690848087a3cba890165 Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:29:49 -0800 Subject: [PATCH] Hosted request limits that cannot reset an isolate; paced X media downloads A 100 MiB request body to a hosted OpenAI instance answered 500 (Cloudflare 1101): the Durable Object's isolate exceeded its 128 MB memory limit and was reset, ending every request in it, a paced stream on the same instance included. From about 24 MiB it failed now and then, as the body was held several times over: the Worker buffered it, the ledger's clone kept a second copy, and each save kept the JSON of the whole store. - The Worker refuses a body over the service's limit with a 413 before reading it, in the provider's error shape where it has one, and streams every other body to the instance. Hosted limit 16 MiB. - The OpenAI emulator accepts request bodies up to 32 MiB, locally too, and refuses a larger one with 413 request_too_large in OpenAI's error shape. OpenAI documents no overall limit for these endpoints. - The ledger records a body declared over 1 MiB by size, without a clone. - A save keeps a fingerprint of each stored value, not its JSON. - A write that would take an instance's stored data past 32 MiB is refused with a 507; GET /_emulate/persistence shows the size and the budget. - A local server ends the connection after answering a request whose body it did not read. X: a DM attachment's download can be paced, the same controls as the OpenAI emulator's paced answers: attachment.stream { chunks, interval_ms } in the seed or on /_emulate/x/dm/arrive, or POST /_emulate/x/media/:media_key/stream. Unpaced stays the default. --- README.md | 6 +- apps/web/app/docs/deployment/page.mdx | 2 +- apps/web/app/docs/openai/page.mdx | 2 +- apps/web/app/docs/x/page.mdx | 2 +- .../src/__tests__/hosted-writes.test.ts | 32 +++- .../src/__tests__/request-limits.test.ts | 144 ++++++++++++++++++ .../cloudflare/src/durable-object.ts | 72 +++++++-- .../@emulators/cloudflare/src/services.ts | 29 ++++ packages/@emulators/cloudflare/src/worker.ts | 51 ++++++- packages/@emulators/core/src/http.ts | 6 + packages/@emulators/core/src/ledger.ts | 18 ++- .../openai/src/__tests__/openai.test.ts | 54 ++++++- packages/@emulators/openai/src/common.ts | 55 ++++++- packages/@emulators/openai/src/index.ts | 8 + packages/@emulators/openai/src/manifest.ts | 2 +- .../x/src/__tests__/webhooks-media.test.ts | 98 ++++++++++++ packages/@emulators/x/src/dm-seed.ts | 4 + packages/@emulators/x/src/manifest.ts | 2 +- packages/@emulators/x/src/media-pacing.ts | 103 +++++++++++++ packages/@emulators/x/src/routes/control.ts | 28 +++- packages/@emulators/x/src/routes/media.ts | 5 +- skills/openai/SKILL.md | 2 +- skills/x/SKILL.md | 2 +- 23 files changed, 692 insertions(+), 35 deletions(-) create mode 100644 packages/@emulators/cloudflare/src/__tests__/request-limits.test.ts create mode 100644 packages/@emulators/x/src/media-pacing.ts diff --git a/README.md b/README.md index a72806915..8a575fad2 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 @@ -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 diff --git a/apps/web/app/docs/deployment/page.mdx b/apps/web/app/docs/deployment/page.mdx index b0269036b..470aefd26 100644 --- a/apps/web/app/docs/deployment/page.mdx +++ b/apps/web/app/docs/deployment/page.mdx @@ -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 diff --git a/apps/web/app/docs/openai/page.mdx b/apps/web/app/docs/openai/page.mdx index a20623da7..35a91c41f 100644 --- a/apps/web/app/docs/openai/page.mdx +++ b/apps/web/app/docs/openai/page.mdx @@ -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"}}`. diff --git a/apps/web/app/docs/x/page.mdx b/apps/web/app/docs/x/page.mdx index fdd276b28..65bf26ccc 100644 --- a/apps/web/app/docs/x/page.mdx +++ b/apps/web/app/docs/x/page.mdx @@ -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. diff --git a/packages/@emulators/cloudflare/src/__tests__/hosted-writes.test.ts b/packages/@emulators/cloudflare/src/__tests__/hosted-writes.test.ts index 50f73161c..add89712f 100644 --- a/packages/@emulators/cloudflare/src/__tests__/hosted-writes.test.ts +++ b/packages/@emulators/cloudflare/src/__tests__/hosted-writes.test.ts @@ -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; // eslint-disable-line @typescript-eslint/no-explicit-any @@ -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(/^$/); + }, 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 () => { diff --git a/packages/@emulators/cloudflare/src/__tests__/request-limits.test.ts b/packages/@emulators/cloudflare/src/__tests__/request-limits.test.ts new file mode 100644 index 000000000..04c6a6c8d --- /dev/null +++ b/packages/@emulators/cloudflare/src/__tests__/request-limits.test.ts @@ -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; // eslint-disable-line @typescript-eslint/no-explicit-any + +function memoryState() { + const map = new Map(); + const copy = (v: unknown): T => JSON.parse(JSON.stringify(v)) as T; + return { + storage: { + get: async (k: string) => (map.has(k) ? copy(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 (o?: { prefix?: string }) => + new Map([...map].filter(([k]) => !o?.prefix || k.startsWith(o.prefix)).map(([k, v]) => [k, copy(v)])), + }, + blockConcurrencyWhile: (fn: () => Promise) => fn(), + }; +} + +function hosted() { + const objects = new Map(); + 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 { + 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 { + 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) => + 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, + ); + }); +}); diff --git a/packages/@emulators/cloudflare/src/durable-object.ts b/packages/@emulators/cloudflare/src/durable-object.ts index fe4d821c4..d90bcb574 100644 --- a/packages/@emulators/cloudflare/src/durable-object.ts +++ b/packages/@emulators/cloudflare/src/durable-object.ts @@ -129,6 +129,32 @@ const ledgerEntryKey = (id: string): string => `${LEDGER_ENTRY_PREFIX}${encodeKe const ledgerIdNumber = (key: string): number => Number(decodeKeyPart(key.slice(LEDGER_ENTRY_PREFIX.length)).replace(/^req_/, "")); const webhookSubKey = (id: number): string => `${WEBHOOK_SUB_PREFIX}${id}`; +const isStoreKey = (key: string) => + key === SNAPSHOT_META_KEY || key.startsWith(SNAPSHOT_ITEM_PREFIX) || key.startsWith(SNAPSHOT_DATA_PREFIX); + +/** + * The most an instance's stored data (its store, as JSON) may grow to on the hosted + * surface. An instance's object has 128 MB of memory, and a save holds the store and + * the request at once; past this, the isolate runs out and is reset with every + * request in it. A write that would pass it is refused with a 507 instead. + */ +export const INSTANCE_STORE_BUDGET_BYTES = 32 * 1024 * 1024; + +/** + * The length and a 64-bit FNV-1a hash (two 32-bit lanes) of a JSON string: enough + * to tell whether a stored value changed without keeping the value. + */ +function fingerprint(json: string): string { + let a = 0x811c9dc5; + let b = 0x01000193 ^ json.length; + for (let i = 0; i < json.length; i++) { + const c = json.charCodeAt(i); + a = Math.imul(a ^ c, 0x01000193); + b = Math.imul(b ^ c, 0x5bd1e995) ^ (b >>> 15); + } + return `${json.length}:${(a >>> 0).toString(36)}:${(b >>> 0).toString(36)}`; +} + // One Durable Object instance == one stateful emulator instance. Its `store` // lives in DO memory (single-threaded → the serialized-write consistency the // in-process emulator already assumes). After every mutating request, the @@ -138,7 +164,9 @@ const webhookSubKey = (id: number): string => `${WEBHOOK_SUB_PREFIX}${id}`; // real API's 401/403. Mint tokens at runtime via `POST /__token`. export class EmulatorDurableObject { private live?: Live; - // The JSON of every snapshot and ledger value last written to storage, by key. + // A fingerprint (length and 64-bit hash of the JSON) of every value last written + // to storage, by key. Not the JSON itself: that would keep a second copy of the + // whole store in memory for as long as the instance lives. // `persist()` writes only the keys whose value changed and deletes only the // keys the state no longer has, so a request that changed nothing costs no // storage writes and the cost of a request does not grow with stored history. @@ -488,11 +516,12 @@ export class EmulatorDurableObject { private async readWritten(): Promise> { const written = new Map(); for (const prefix of [SNAPSHOT_ITEM_PREFIX, SNAPSHOT_DATA_PREFIX, MINTED_PREFIX, WEBHOOK_SUB_PREFIX]) { - for (const [key, value] of await this.storage.list({ prefix })) written.set(key, JSON.stringify(value)); + for (const [key, value] of await this.storage.list({ prefix })) + written.set(key, fingerprint(JSON.stringify(value))); } for (const key of [SNAPSHOT_META_KEY, LEDGER_META_KEY, FAULTS_KEY, TOKENS_COMPLETE_KEY, WEBHOOKS_KEY]) { const value = await this.storage.get(key); - if (value !== undefined) written.set(key, JSON.stringify(value)); + if (value !== undefined) written.set(key, fingerprint(JSON.stringify(value))); } return written; } @@ -514,13 +543,11 @@ export class EmulatorDurableObject { const puts: Array<{ key: string; value: unknown }> = []; const entries = this.persistedEntries(live, withStore); for (const [key, value] of entries) { - const json = JSON.stringify(value); - if (written.get(key) === json) continue; + const print = fingerprint(JSON.stringify(value)); + if (written.get(key) === print) continue; puts.push({ key, value }); - written.set(key, json); + written.set(key, print); } - const isStoreKey = (key: string) => - key === SNAPSHOT_META_KEY || key.startsWith(SNAPSHOT_ITEM_PREFIX) || key.startsWith(SNAPSHOT_DATA_PREFIX); const deletes = [...written.keys()].filter((key) => !entries.has(key) && (withStore || !isStoreKey(key))); for (const key of deletes) written.delete(key); @@ -572,6 +599,14 @@ export class EmulatorDurableObject { } } + /** The size of the instance's stored data as last saved: the sum of its store values' JSON. */ + private async storedBytes(): Promise { + const written = (this.written ??= await this.readWritten()); + let total = 0; + for (const [key, print] of written) if (isStoreKey(key)) total += Number(print.slice(0, print.indexOf(":"))); + return total; + } + private async readWebhooks(): Promise { const counters = await this.storage.get(WEBHOOKS_KEY); if (!counters) return undefined; @@ -638,7 +673,26 @@ export class EmulatorDurableObject { const live = await this.ensure(service, instance, baseUrl, preset); if (path === "/_emulate/persistence" && request.method === "GET") { - return Response.json({ failures: [...this.saveFailures].reverse() }); + return Response.json({ + failures: [...this.saveFailures].reverse(), + stored_bytes: await this.storedBytes(), + budget_bytes: INSTANCE_STORE_BUDGET_BYTES, + }); + } + if (MUTATES(request.method)) { + const incoming = SERVICES[service].requestBodiesNotStored + ? 0 + : Number(request.headers.get("content-length") ?? 0) || 0; + const stored = await this.storedBytes(); + if (stored + incoming > INSTANCE_STORE_BUDGET_BYTES) { + return Response.json( + { + error: "instance_storage_full", + message: `This hosted instance holds ${stored} bytes of data; with this ${incoming}-byte request it would pass its ${INSTANCE_STORE_BUDGET_BYTES}-byte budget. Reset or re-seed the instance, or use a new one.`, + }, + { status: 507 }, + ); + } } const res = await live.app.fetch(request); // A plugin can ask for a save after a read that changed state (X counts GETs diff --git a/packages/@emulators/cloudflare/src/services.ts b/packages/@emulators/cloudflare/src/services.ts index 913f605af..ffaa89568 100644 --- a/packages/@emulators/cloudflare/src/services.ts +++ b/packages/@emulators/cloudflare/src/services.ts @@ -80,7 +80,9 @@ import { import { issueCredential as openaiIssueCredential, manifest as openaiManifest, + MAX_REQUEST_BYTES as OPENAI_MAX_REQUEST_BYTES, openaiPlugin, + requestTooLargeResponse as openaiRequestTooLarge, seedFromConfig as openaiSeed, } from "@emulators/openai"; import { @@ -130,6 +132,30 @@ export interface ServiceEntry { // Provider-specific credential issuance (e.g. AWS access keys) that doesn't fit // the bearer / api-key / oauth-client paths below. issueCredential?: (store: Store, baseUrl: string, request: CredentialRequest) => IssuedCredential; + // The largest request body this service accepts on the hosted surface, when it is + // not HOSTED_MAX_REQUEST_BYTES, and its refusal in the provider's own error shape. + maxRequestBytes?: number; + requestTooLarge?: (limit: number) => Response; + // True when the service never keeps a request body (it reads and answers), so a + // request's size does not count against the instance's store budget. + requestBodiesNotStored?: boolean; +} + +/** + * The largest request body any hosted instance accepts. An 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 a larger body is refused with a 413 before it is read. + */ +export const HOSTED_MAX_REQUEST_BYTES = 16 * 1024 * 1024; + +export function hostedRequestTooLarge(limit: number): Response { + return Response.json( + { + error: "request_too_large", + message: `Request body too large. Hosted emulators accept request bodies of up to ${limit} bytes.`, + }, + { status: 413 }, + ); } export const SERVICES: Record = { @@ -417,6 +443,9 @@ export const SERVICES: Record = { seedFromConfig: openaiSeed, defaultFallback: () => ({ login: "default", id: 1, scopes: [] }), issueCredential: openaiIssueCredential, + maxRequestBytes: OPENAI_MAX_REQUEST_BYTES, + requestTooLarge: openaiRequestTooLarge, + requestBodiesNotStored: true, }, zapier: { plugin: zapierPlugin, diff --git a/packages/@emulators/cloudflare/src/worker.ts b/packages/@emulators/cloudflare/src/worker.ts index 898c89647..b4f91d260 100644 --- a/packages/@emulators/cloudflare/src/worker.ts +++ b/packages/@emulators/cloudflare/src/worker.ts @@ -6,7 +6,7 @@ import { servicesCatalog, } from "@emulators/core"; import { EmulatorDurableObject } from "./durable-object.js"; -import { SERVICES } from "./services.js"; +import { HOSTED_MAX_REQUEST_BYTES, SERVICES, hostedRequestTooLarge } from "./services.js"; import { SERVICE_ICONS } from "./icons.js"; import { consoleHtml } from "./console-html.js"; @@ -81,6 +81,31 @@ const wantsJson = (request: Request): boolean => { return a.includes("application/json") && !a.includes("text/html"); }; +/** The whole stream, or null once it passes `limit` bytes (reading stops there). */ +async function readUpTo(stream: ReadableStream, limit: number): Promise { + const reader = stream.getReader(); + const parts: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > limit) { + // Not awaited: the rest of the body may never arrive, and cancelling must not hold the answer. + void reader.cancel().catch(() => {}); + return null; + } + parts.push(value); + } + const out = new Uint8Array(total); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.byteLength; + } + return out.buffer; +} + async function forwardToDurableObject( env: Env, request: Request, @@ -92,8 +117,26 @@ async function forwardToDurableObject( headers.set("x-emulator-instance", opts.instance); headers.set("x-emulator-base-url", opts.baseUrl); if (opts.mcpMode) headers.set("x-emulator-mcp-mode", opts.mcpMode); - const hasBody = request.method !== "GET" && request.method !== "HEAD"; - const body = hasBody ? await request.arrayBuffer() : undefined; + const hasBody = request.method !== "GET" && request.method !== "HEAD" && request.body !== null; + // Refuse an oversized body before reading it, and otherwise pass it through as a + // stream, so no request can fill an isolate's memory and reset it with every + // other request in it. A body of unknown length is read up to the limit. + const entry = SERVICES[opts.service]; + const limit = entry?.maxRequestBytes ?? HOSTED_MAX_REQUEST_BYTES; + const tooLarge = () => (entry?.requestTooLarge ?? hostedRequestTooLarge)(limit); + let body: ReadableStream | ArrayBuffer | undefined; + if (hasBody) { + const declared = Number(request.headers.get("content-length") ?? NaN); + if (Number.isFinite(declared)) { + if (declared > limit) return tooLarge(); + body = request.body!; + } else { + const read = await readUpTo(request.body!, limit); + if (!read) return tooLarge(); + body = read; + headers.set("content-length", String(read.byteLength)); + } + } // Manual redirect: the emulator's OAuth callbacks return 302s (e.g. → the app's // redirect_uri). Without this, the Worker→DO stub.fetch FOLLOWS the redirect // internally and re-fetches the DO by the Location path, mangling it. @@ -101,6 +144,8 @@ async function forwardToDurableObject( method: request.method, headers, body, + // A streamed body needs a half-duplex request (fetch standard; Node enforces it). + ...(body instanceof ReadableStream ? { duplex: "half" } : {}), redirect: "manual", }); const id = env.EMULATOR.idFromName(`${opts.service}:${opts.instance}`); diff --git a/packages/@emulators/core/src/http.ts b/packages/@emulators/core/src/http.ts index 6dbe4cb58..32b111aec 100644 --- a/packages/@emulators/core/src/http.ts +++ b/packages/@emulators/core/src/http.ts @@ -377,7 +377,13 @@ export function serve(options: ServeOptions): Server { try { const request = nodeRequestToFetchRequest(req); const response = await options.fetch(request); + // A handler that answered without reading the whole body (a 413, say) ends + // the connection once the answer is sent, as a server does, rather than leave + // a client that is still uploading waiting on a peer that stopped reading. + const unread = !req.complete; + if (unread) res.setHeader("Connection", "close"); await writeFetchResponse(res, response, req.method?.toUpperCase() === "HEAD"); + if (unread) res.once("finish", () => req.socket.destroy()); } catch (err) { const message = err instanceof Error ? err.message : "Internal Server Error"; res.statusCode = 500; diff --git a/packages/@emulators/core/src/ledger.ts b/packages/@emulators/core/src/ledger.ts index e35684a09..fae40fa5f 100644 --- a/packages/@emulators/core/src/ledger.ts +++ b/packages/@emulators/core/src/ledger.ts @@ -76,6 +76,8 @@ export interface LedgerSnapshot { const DEFAULT_MAX_ENTRIES = 1000; const DEFAULT_MAX_BODY_CHARS = 20000; +/** Request bodies declared larger than this are recorded by size only, without a clone. */ +export const LEDGER_CLONE_LIMIT = 1024 * 1024; const REDACTED = "[redacted]"; const STREAMING_BODY_OMITTED = ""; const BINARY_BODY_OMITTED = ""; @@ -166,8 +168,12 @@ export function createLedgerMiddleware(ledger: RequestLedger, options: LedgerOpt c.header("X-Correlation-Id", correlationId); // Cloned now, read once the handler has run, so a handler can ask for the - // body to be recorded by size only. - const requestClone = c.req.raw.clone(); + // body to be recorded by size only. A body declared larger than + // LEDGER_CLONE_LIMIT is not cloned at all: the clone would hold a second + // full copy until the response, and only its first characters are kept. + const declaredBytes = Number(c.req.header("content-length") ?? NaN); + const recordBySize = Number.isFinite(declaredBytes) && declaredBytes > LEDGER_CLONE_LIMIT; + const requestClone = recordBySize ? undefined : c.req.raw.clone(); const requestHeaders = redactHeaders(rawHeaders); // Snapshot existing webhook delivery ids so we can correlate the ones this @@ -176,10 +182,12 @@ export function createLedgerMiddleware(ledger: RequestLedger, options: LedgerOpt const beforeDeliveryIds = webhooks ? new Set(webhooks.getDeliveries().map((d) => d.id)) : undefined; const response = await next(); - const omittedRequestBytes = c.get("ledgerRequestBodyBytes"); + const handlerBytes = c.get("ledgerRequestBodyBytes"); + const omittedRequestBytes = + typeof handlerBytes === "number" ? handlerBytes : recordBySize ? declaredBytes : undefined; let requestBody: { body?: unknown; bodyTruncated?: boolean; bodyBytes?: number }; - if (typeof omittedRequestBytes === "number") { - await requestClone.body?.cancel().catch(() => {}); + if (typeof omittedRequestBytes === "number" || !requestClone) { + await requestClone?.body?.cancel().catch(() => {}); requestBody = { body: ``, bodyBytes: omittedRequestBytes }; } else { requestBody = await readBody(requestClone, maxBodyChars); diff --git a/packages/@emulators/openai/src/__tests__/openai.test.ts b/packages/@emulators/openai/src/__tests__/openai.test.ts index 6780cdde7..743ab8f81 100644 --- a/packages/@emulators/openai/src/__tests__/openai.test.ts +++ b/packages/@emulators/openai/src/__tests__/openai.test.ts @@ -2,7 +2,14 @@ import { afterEach, describe, expect, it } from "vitest"; import type { AddressInfo } from "net"; import OpenAI from "openai"; import { createServer, serve } from "@emulators/core"; -import { openaiPlugin, seedFromConfig, getOpenAIStore, approxTokens, type OpenAISeedConfig } from "../index.js"; +import { + openaiPlugin, + seedFromConfig, + getOpenAIStore, + approxTokens, + MAX_REQUEST_BYTES, + type OpenAISeedConfig, +} from "../index.js"; type Json = Record; // eslint-disable-line @typescript-eslint/no-explicit-any @@ -379,6 +386,51 @@ describe("keys, models, limits and the ledger", () => { expect(usage.calls[0]).toMatchObject({ key_name: "primary", request_bytes: entry.request.bodyBytes }); }); + it("refuses a body over its stated limit with a 413 in OpenAI's error shape, through the official SDK", async () => { + const { client, ledger } = await start(); + const big = "a".repeat(MAX_REQUEST_BYTES + 1); + const err = await client() + .responses.create({ model: "gpt-5-mini", input: big }) + .catch((e: unknown) => e); + expect(err).toBeInstanceOf(OpenAI.APIError); + expect((err as InstanceType).status).toBe(413); + expect((err as InstanceType).error).toEqual({ + message: `Request body too large. The emulator accepts request bodies of up to ${MAX_REQUEST_BYTES} bytes.`, + type: "invalid_request_error", + param: null, + code: "request_too_large", + }); + expect(ledger.list()[0]!.response.status).toBe(413); + }); + + it("refuses a body of undeclared length once it passes the limit, and accepts one under it", async () => { + const { raw } = await start({ answer_rules: [{ answer: "ok" }] }); + const stream = (bytes: number) => { + const head = new TextEncoder().encode('{"model":"gpt-5-mini","input":"'); + const tail = new TextEncoder().encode('"}'); + let sent = 0; + const middle = bytes - head.length - tail.length; + return new ReadableStream({ + start(controller) { + controller.enqueue(head); + }, + pull(controller) { + if (sent >= middle) { + controller.enqueue(tail); + return controller.close(); + } + const n = Math.min(1024 * 1024, middle - sent); + controller.enqueue(new Uint8Array(n).fill(97)); + sent += n; + }, + }); + }; + const send = (bytes: number) => + raw("/v1/responses", { method: "POST", body: stream(bytes), duplex: "half" } as RequestInit); + expect((await send(MAX_REQUEST_BYTES + 1024)).status).toBe(413); + expect((await send(4 * 1024 * 1024)).status).toBe(200); + }); + it("keeps one usage record per call whose counts match the responses", async () => { const { client, control, store } = await start({ answer_rules: [{ answer: "Two words" }] }); const a = await client().responses.create({ model: "gpt-5-mini", input: "one" }); diff --git a/packages/@emulators/openai/src/common.ts b/packages/@emulators/openai/src/common.ts index 35d4a9a9d..17d8a4188 100644 --- a/packages/@emulators/openai/src/common.ts +++ b/packages/@emulators/openai/src/common.ts @@ -143,9 +143,62 @@ export function checkKeyLimit( /** Request bodies above this many bytes are recorded in the ledger by size only. */ export const LEDGER_BODY_LIMIT = 64 * 1024; +/** + * The largest request body the emulator accepts, in bytes. OpenAI documents no + * overall limit for these endpoints (only 50 MB across the files in one request), + * so this is the emulator's own, stated in its docs and manifest. A larger body is + * refused with a 413 before it is read. + */ +export const MAX_REQUEST_BYTES = 32 * 1024 * 1024; + +/** The 413 for a body over MAX_REQUEST_BYTES, in OpenAI's error shape. */ +export function requestTooLargeResponse(limit = MAX_REQUEST_BYTES): Response { + return new Response( + JSON.stringify({ + error: { + message: `Request body too large. The emulator accepts request bodies of up to ${limit} bytes.`, + type: "invalid_request_error", + param: null, + code: "request_too_large", + }, + }), + { status: 413, headers: { "content-type": "application/json" } }, + ); +} + +/** The declared body size, or null when the request does not say. */ +function declaredLength(c: Context): number | null { + const n = Number(c.req.header("content-length") ?? NaN); + return Number.isFinite(n) ? n : null; +} + +/** The body as text, or null once it passes `limit` bytes (reading stops there). */ +async function readLimitedText(c: Context, limit: number): Promise { + const stream = c.req.raw.body; + if (!stream) return ""; + const reader = stream.getReader(); + const parts: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.length; + if (total > limit) { + // Not awaited: the rest of the body may never arrive, and cancelling must not hold the answer. + void reader.cancel().catch(() => {}); + return null; + } + parts.push(value); + } + return Buffer.concat(parts).toString("utf8"); +} + /** Read and parse the JSON body, recording a large one in the ledger by size only. */ export async function readJsonBody(c: Context): Promise<{ body: Record; bytes: number } | Response> { - const raw = await c.req.text(); + const declared = declaredLength(c); + if (declared !== null && declared > MAX_REQUEST_BYTES) return requestTooLargeResponse(); + const raw = await readLimitedText(c, MAX_REQUEST_BYTES); + if (raw === null) return requestTooLargeResponse(); const bytes = Buffer.byteLength(raw, "utf8"); if (bytes > LEDGER_BODY_LIMIT) c.set("ledgerRequestBodyBytes", bytes); try { diff --git a/packages/@emulators/openai/src/index.ts b/packages/@emulators/openai/src/index.ts index 4642c92fe..935426b51 100644 --- a/packages/@emulators/openai/src/index.ts +++ b/packages/@emulators/openai/src/index.ts @@ -6,10 +6,12 @@ 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 { MAX_REQUEST_BYTES, requestTooLargeResponse } from "./common.js"; export { getOpenAIStore, type OpenAIStore } from "./store.js"; export type * from "./store.js"; export { approxTokens } from "./text.js"; +export { MAX_REQUEST_BYTES, requestTooLargeResponse } from "./common.js"; export { manifest } from "./manifest.js"; export interface OpenAISeedConfig { @@ -68,6 +70,12 @@ export const openaiPlugin: ServicePlugin = { name: "openai", register(app, store, webhooks, baseUrl, tokenMap): void { const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap }; + // Refuse an oversized body before any route reads it. + app.use("/v1/*", async (c, next) => { + const declared = Number(c.req.header("content-length") ?? NaN); + if (Number.isFinite(declared) && declared > MAX_REQUEST_BYTES) return requestTooLargeResponse(); + return next(); + }); controlRoutes(ctx); responsesRoutes(ctx); chatRoutes(ctx); diff --git a/packages/@emulators/openai/src/manifest.ts b/packages/@emulators/openai/src/manifest.ts index f9222bcf4..65197cec4 100644 --- a/packages/@emulators/openai/src/manifest.ts +++ b/packages/@emulators/openai/src/manifest.ts @@ -20,7 +20,7 @@ export const manifest: ServiceManifest = { title: "Server-sent event streaming", status: "supported", notes: - "Responses API events in the documented order with sequence_number; Chat Completions chunks ending with data: [DONE]. Pacing (chunks and interval) is set per answer.", + "Responses API events in the documented order with sequence_number; Chat Completions chunks ending with data: [DONE]. Pacing (chunks and interval) is set per answer. Request bodies are limited to 32 MiB (the emulator's own limit; OpenAI documents none for these endpoints): a larger one answers 413 request_too_large before it is read.", }, { id: "realtime", diff --git a/packages/@emulators/x/src/__tests__/webhooks-media.test.ts b/packages/@emulators/x/src/__tests__/webhooks-media.test.ts index 5aedd011c..53c1d7f56 100644 --- a/packages/@emulators/x/src/__tests__/webhooks-media.test.ts +++ b/packages/@emulators/x/src/__tests__/webhooks-media.test.ts @@ -704,3 +704,101 @@ describe("X media", () => { expect(((await steal.json()) as Json).type).toBe("https://api.x.com/2/problems/dm-bad-media"); }); }); + +describe("paced DM media download (an emulator control)", () => { + async function download(call: (path: string, token?: string) => Promise, path: string, token: string) { + const started = Date.now(); + const dl = await call(path, token); + const reader = dl.body!.getReader(); + const parts: Uint8Array[] = []; + const gaps: number[] = []; + let last = Date.now(); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + gaps.push(Date.now() - last); + last = Date.now(); + parts.push(value); + } + return { dl, bytes: Buffer.concat(parts), parts: parts.length, ms: Date.now() - started, gaps }; + } + + it("sends a seeded attachment in exactly the asked pieces, interval apart, and the same bytes as unpaced", async () => { + const size = 1024 * 1024 + 7; + const { call, mint, control } = setup({ + dm_conversations: [ + { + participants: ["developer", "alice"], + messages: [ + { from: "alice", text: "paced", attachment: { bytes: size, stream: { chunks: 8, interval_ms: 60 } } }, + { from: "alice", text: "plain", attachment: { bytes: size } }, + ], + }, + ], + }); + const dev = mint(DEV); + const read = (await ( + await call(`/2/dm_events?expansions=attachments.media_keys&media.fields=url`, dev) + ).json()) as Json; + const byText = new Map( + (read.data as Json[]).map((e) => [ + e.text, + read.includes.media.find((m: Json) => m.media_key === e.attachments.media_keys[0]).url, + ]), + ); + const paced = await download(call, new URL(byText.get("paced")!).pathname, dev); + const plain = await download(call, new URL(byText.get("plain")!).pathname, dev); + expect(paced.dl.headers.get("content-length")).toBe(String(size)); + expect(paced.bytes.length).toBe(size); + expect(paced.parts).toBe(8); + expect(paced.ms).toBeGreaterThanOrEqual(7 * 60 - 10); + expect(Math.min(...paced.gaps.slice(1))).toBeGreaterThanOrEqual(50); + // Unpaced stays the default. + expect(plain.bytes.length).toBe(size); + expect(plain.ms).toBeLessThan(paced.ms); + + // The same file unpaced is byte for byte what was paced. + const pacedKey = read.includes.media.find((m: Json) => m.url === byText.get("paced")).media_key; + expect(((await (await control(`/media/${pacedKey}`)).json()) as Json).stream).toEqual({ + chunks: 8, + interval_ms: 60, + }); + await control(`/media/${pacedKey}/stream`, {}); + const again = await download(call, new URL(byText.get("paced")!).pathname, dev); + expect(again.bytes.equals(paced.bytes)).toBe(true); + }); + + it("paces any attachment through the control plane, rejects bad values, and clears", async () => { + const { call, mint, control } = setup(); + const dev = mint(DEV); + const arrived = (await ( + await control("/dm/arrive", { to: "developer", from: "alice", attachment: { bytes: 300_000 } }) + ).json()) as Json; + const key = arrived.media_keys[0] as string; + expect((await control(`/media/${key}/stream`, { chunks: 0 })).status).toBe(400); + expect((await control(`/media/${key}/stream`, { chunks: 3, interval_ms: 60001 })).status).toBe(400); + expect( + ((await (await control(`/media/${key}/stream`, { chunks: 3, interval_ms: 40 })).json()) as Json).stream, + ).toEqual({ + chunks: 3, + interval_ms: 40, + }); + const read = (await ( + await call(`/2/dm_events?expansions=attachments.media_keys&media.fields=url`, dev) + ).json()) as Json; + const path = new URL(read.includes.media[0].url).pathname; + const paced = await download(call, path, dev); + expect([paced.parts, paced.bytes.length]).toEqual([3, 300_000]); + expect(paced.ms).toBeGreaterThanOrEqual(2 * 40 - 10); + expect(((await (await control(`/media/${key}/stream`, { stream: null })).json()) as Json).stream).toBeNull(); + expect( + ( + await control("/dm/arrive", { + to: "developer", + from: "alice", + attachment: { bytes: 10, stream: { chunks: -1 } }, + }) + ).status, + ).toBe(400); + }); +}); diff --git a/packages/@emulators/x/src/dm-seed.ts b/packages/@emulators/x/src/dm-seed.ts index 1551e1be6..3f1a33500 100644 --- a/packages/@emulators/x/src/dm-seed.ts +++ b/packages/@emulators/x/src/dm-seed.ts @@ -1,5 +1,6 @@ import type { Store } from "@emulators/core"; import { getXStore, xNumericId } from "./store.js"; +import { parseMediaPacing, setMediaPacing } from "./media-pacing.js"; import type { XDmConversation } from "./entities.js"; import { DM_RETENTION_MS, @@ -16,6 +17,8 @@ export interface XSeedAttachment { media_category?: string; width?: number; height?: number; + /** Pace the download: exactly `chunks` pieces, `interval_ms` apart (an emulator control). */ + stream?: { chunks: number; interval_ms?: number }; } export interface XSeedDmConversation { @@ -148,6 +151,7 @@ export function seedDmConversation(store: Store, spec: XSeedDmConversation, now created_at_ms: at, expires_at_ms: at + 24 * 3600 * 1000, }); + if (a.stream) setMediaPacing(store, key, parseMediaPacing(a.stream, "attachment.stream")); mediaKeys.push(key); } xs.dmEvents.insert({ diff --git a/packages/@emulators/x/src/manifest.ts b/packages/@emulators/x/src/manifest.ts index bdbcaed27..f05b182e6 100644 --- a/packages/@emulators/x/src/manifest.ts +++ b/packages/@emulators/x/src/manifest.ts @@ -159,7 +159,7 @@ export const manifest: ServiceManifest = { path: "/2/dm_conversations/media/:dm_id/:media_id/:resource_id", status: "partial", summary: - "Streams a DM attachment to a participant with dm.read. Seeded and generated media are deterministic placeholder bytes; the media url X returns is not documented, so includes.media.url points here.", + "Streams a DM attachment to a participant with dm.read. Seeded and generated media are deterministic placeholder bytes; the media url X returns is not documented, so includes.media.url points here. Emulator control, not X behaviour: a download can be paced as exactly chunks pieces interval_ms apart (attachment.stream in the seed or on /_emulate/x/dm/arrive, or POST /_emulate/x/media/:media_key/stream); unpaced by default.", }, { operationId: "getDirectMessagesEventsByConversationId", diff --git a/packages/@emulators/x/src/media-pacing.ts b/packages/@emulators/x/src/media-pacing.ts new file mode 100644 index 000000000..e3aab4c99 --- /dev/null +++ b/packages/@emulators/x/src/media-pacing.ts @@ -0,0 +1,103 @@ +import type { Store } from "@emulators/core"; + +/** + * How a DM attachment's download is paced: exactly `chunks` pieces, `interval_ms` + * apart, the same controls the OpenAI emulator has for a paced answer. An emulator + * control, not X behaviour; unpaced (the default) sends the file as fast as it goes. + */ +export interface MediaPacing { + chunks: number; + interval_ms: number; +} + +export const MAX_PACING_CHUNKS = 10000; +export const MAX_PACING_INTERVAL_MS = 60000; +const PACING_KEY = "x.media_pacing"; + +function pacingMap(store: Store): Map { + let map = store.getData>(PACING_KEY); + if (!map) { + map = new Map(); + store.setData(PACING_KEY, map); + } + return map; +} + +/** Validate `{ chunks, interval_ms }`; throws with the field at fault. */ +export function parseMediaPacing(value: unknown, where = "stream"): MediaPacing { + const v = value as Record | null; + if (!v || typeof v !== "object") throw new Error(`${where} must be { chunks, interval_ms }.`); + const chunks = v.chunks; + const interval = v.interval_ms ?? 0; + if (!Number.isInteger(chunks) || (chunks as number) < 1 || (chunks as number) > MAX_PACING_CHUNKS) { + throw new Error(`${where}.chunks must be an integer from 1 to ${MAX_PACING_CHUNKS}.`); + } + if (!Number.isInteger(interval) || (interval as number) < 0 || (interval as number) > MAX_PACING_INTERVAL_MS) { + throw new Error(`${where}.interval_ms must be an integer from 0 to ${MAX_PACING_INTERVAL_MS}.`); + } + return { chunks: chunks as number, interval_ms: interval as number }; +} + +export function getMediaPacing(store: Store, mediaKey: string): MediaPacing | null { + return pacingMap(store).get(mediaKey) ?? null; +} + +export function setMediaPacing(store: Store, mediaKey: string, pacing: MediaPacing | null): void { + if (pacing) pacingMap(store).set(mediaKey, pacing); + else pacingMap(store).delete(mediaKey); +} + +/** + * Re-chunk `source` (exactly `size` bytes) into `pacing.chunks` pieces of equal size + * (the last one shorter), waiting `interval_ms` between pieces. Holds at most one + * piece in memory. Cancelling the response stops it. + */ +export function pacedStream( + source: ReadableStream, + size: number, + pacing: MediaPacing, +): ReadableStream { + const chunks = Math.max(1, Math.min(pacing.chunks, size || 1)); + const pieceBytes = Math.max(1, Math.ceil(size / chunks)); + const reader = source.getReader(); + let pending: Uint8Array = new Uint8Array(0); + let sent = 0; + let pieces = 0; + let timer: ReturnType | undefined; + return new ReadableStream({ + async pull(controller) { + if (sent >= size) { + controller.close(); + return; + } + if (pieces > 0 && pacing.interval_ms > 0) { + await new Promise((resolve) => (timer = setTimeout(resolve, pacing.interval_ms))); + } + const want = Math.min(pieceBytes, size - sent); + const piece = new Uint8Array(want); + let filled = 0; + while (filled < want) { + if (pending.length === 0) { + const { done, value } = await reader.read(); + if (done) break; + pending = value; + } + const take = Math.min(want - filled, pending.length); + piece.set(pending.subarray(0, take), filled); + pending = pending.subarray(take); + filled += take; + } + if (filled === 0) { + controller.close(); + return; + } + controller.enqueue(filled === want ? piece : piece.subarray(0, filled)); + sent += filled; + pieces++; + }, + cancel(reason) { + if (timer) clearTimeout(timer); + return reader.cancel(reason); + }, + }); +} diff --git a/packages/@emulators/x/src/routes/control.ts b/packages/@emulators/x/src/routes/control.ts index b1941e801..f419247bd 100644 --- a/packages/@emulators/x/src/routes/control.ts +++ b/packages/@emulators/x/src/routes/control.ts @@ -13,6 +13,7 @@ import { import { clearRateWindows, getRateLimitConfig, rateLimitState, setRateLimitConfig } from "../rate-limits.js"; import { ensureOneToOne, recordHeldDeliveries, storeAndDeliverMessage } from "./dm.js"; import type { XSeedAttachment } from "../dm-seed.js"; +import { getMediaPacing, parseMediaPacing, setMediaPacing } from "../media-pacing.js"; /** * X-specific control calls under `/_emulate/x`. They are emulator controls, not @@ -59,6 +60,12 @@ export function controlRoutes({ app, store, baseUrl, webhooks }: RouteContext): const mediaKeys: string[] = []; if (body.attachment && typeof body.attachment === "object") { const a = body.attachment as XSeedAttachment; + let pacing = null; + try { + pacing = a.stream === undefined ? null : parseMediaPacing(a.stream, "attachment.stream"); + } catch (err) { + return bad(c, err instanceof Error ? err.message : "Invalid attachment.stream."); + } const mediaType = a.media_type ?? "image/jpeg"; const category = mediaType === "image/gif" ? "dm_gif" : mediaType.startsWith("video/") ? "dm_video" : "dm_image"; const mediaId = nextStoredId(store); @@ -78,6 +85,7 @@ export function controlRoutes({ app, store, baseUrl, webhooks }: RouteContext): created_at_ms: Date.now(), expires_at_ms: Date.now() + 24 * 3600 * 1000, }); + if (pacing) setMediaPacing(store, key, pacing); mediaKeys.push(key); } if (!text && mediaKeys.length === 0) return bad(c, "Give `text`, `attachment`, or both."); @@ -182,7 +190,25 @@ export function controlRoutes({ app, store, baseUrl, webhooks }: RouteContext): /** GET /_emulate/x/media/:media_key: metadata for a media key (uploaded, seeded or generated). */ app.get("/_emulate/x/media/:media_key", (c) => { const media = findMediaByKey(store, c.req.param("media_key")); - return media ? c.json({ media }) : bad(c, "No such media.", 404); + return media ? c.json({ media, stream: getMediaPacing(store, media.media_key) }) : bad(c, "No such media.", 404); + }); + + /** + * POST /_emulate/x/media/:media_key/stream: pace this attachment's download, an + * emulator control: `{ chunks, interval_ms }` sends exactly `chunks` pieces + * `interval_ms` apart; `{ "stream": null }` (or an empty body) sends it unpaced again. + */ + app.post("/_emulate/x/media/:media_key/stream", async (c) => { + const media = findMediaByKey(store, c.req.param("media_key")); + if (!media) return bad(c, "No such media.", 404); + const body = (await c.req.json().catch(() => ({}))) as Record; + const clear = Object.keys(body).length === 0 || body.stream === null; + try { + setMediaPacing(store, media.media_key, clear ? null : parseMediaPacing(body.stream ?? body)); + } catch (err) { + return bad(c, err instanceof Error ? err.message : "Invalid stream."); + } + return c.json({ media_key: media.media_key, stream: getMediaPacing(store, media.media_key) }); }); // Rate limits: configuration and the open windows. diff --git a/packages/@emulators/x/src/routes/media.ts b/packages/@emulators/x/src/routes/media.ts index 5438cd8af..c19e88817 100644 --- a/packages/@emulators/x/src/routes/media.ts +++ b/packages/@emulators/x/src/routes/media.ts @@ -3,6 +3,7 @@ import { recordSideEffect } from "@emulators/core"; import { getXStore } from "../store.js"; import type { XMedia, XUser } from "../entities.js"; import { requireUserContext } from "./auth.js"; +import { getMediaPacing, pacedStream } from "../media-pacing.js"; import { PROBLEM, invalidRequest, problem } from "./problems.js"; import { findEvent, @@ -318,7 +319,9 @@ export function mediaRoutes({ app, store }: RouteContext): void { } c.set("ledgerOmitResponseBody", true); recordSideEffect(c, { type: "custom", collection: "x.media", id: media.media_key, summary: `${media.size} bytes` }); - return new Response(withLength(mediaStream(store, media), media.size), { + const pacing = getMediaPacing(store, media.media_key); + const body = pacing ? pacedStream(mediaStream(store, media), media.size, pacing) : mediaStream(store, media); + return new Response(withLength(body, media.size), { status: 200, headers: { // The spec declares the body as application/octet-stream. diff --git a/skills/openai/SKILL.md b/skills/openai/SKILL.md index 83ad1ddb1..e47cc7f1a 100644 --- a/skills/openai/SKILL.md +++ b/skills/openai/SKILL.md @@ -53,4 +53,4 @@ curl "$OPENAI_EMULATOR_URL/_emulate/openai/usage" ## 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. Per-service docs live at `https://docs.emulators.dev/openai`. +`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`. diff --git a/skills/x/SKILL.md b/skills/x/SKILL.md index 123dbab11..9c131c3c8 100644 --- a/skills/x/SKILL.md +++ b/skills/x/SKILL.md @@ -38,7 +38,7 @@ Seed a large history with `dm_conversations[].generate` or `dm_bulk` (computed o ## Media -Upload with `POST /2/media/upload` or the chunked `initialize`/`append`/`finalize`, attach with `attachments: [{ media_id }]`, and download from the `url` in `includes.media` (`GET /2/dm_conversations/media/:dm_id/:media_key/:media_id`, streamed). +Upload with `POST /2/media/upload` or the chunked `initialize`/`append`/`finalize`, attach with `attachments: [{ media_id }]`, and download from the `url` in `includes.media` (`GET /2/dm_conversations/media/:dm_id/:media_key/:media_id`, streamed). To send a download slowly (an emulator control), set `stream: { chunks, interval_ms }` on the attachment or `POST /_emulate/x/media/:media_key/stream` with `{"chunks":300,"interval_ms":100}`, as with the OpenAI emulator's paced answers. ## Webhooks