diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts index 886d09a7c3f..0e7fff44a3a 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts @@ -4,8 +4,9 @@ import { v2RateLimiterModuleMock, v2RouteMocks, } from '@sim/testing' +import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock' import { NextRequest } from 'next/server' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ plan: vi.fn() })) @@ -31,6 +32,37 @@ const auth = { keyType: 'workspace' as const, } +/** The next request is sent with a personal key of its own user, a caller apart from `auth`'s. */ +function asCaller(userId: string) { + v2RouteMocks.authenticate.mockResolvedValueOnce({ + principal: { kind: 'personal_api_key', userId, keyId: `key-${userId}`, access: 'read' }, + rateLimitSubjectIds: [`api-key:key-${userId}`, `user:${userId}`], + rateLimitSubscription: null, + keyType: 'personal', + }) +} + +/** A plan whose body declares no length, so it reserves a body at the cap, and never arrives. */ +function stalledPlan(onRead: () => void) { + return POST( + new NextRequest(`http://localhost:3000/api/v2/workspaces/${WORKSPACE_ID}/source/plan`, { + method: 'POST', + headers: { 'x-api-key': 'key', 'content-type': 'application/json' }, + body: new ReadableStream( + { + pull() { + onRead() + return new Promise(() => {}) + }, + }, + { highWaterMark: 0 } + ), + duplex: 'half', + }), + { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) } + ) +} + const WORKFLOW = "// @sim-sdk 1\nexport default workflow('W', () => {})\n" /** Units each limiter key was charged. */ @@ -48,6 +80,11 @@ function plan(files: Record) { } describe('POST /api/v2/workspaces/{workspaceId}/source/plan', () => { + afterEach(() => { + resetEnvMock() + vi.useRealTimers() + }) + beforeEach(() => { charged.clear() v2RouteMocks.authenticate.mockResolvedValue(auth) @@ -125,8 +162,11 @@ describe('POST /api/v2/workspaces/{workspaceId}/source/plan', () => { mocks.plan.mockImplementation( () => new Promise((resolve) => finish.push(() => resolve(result))) ) - // No declared length, so each reserves a body at the cap. - const running = Array.from({ length: 4 }, () => plan({ 'workflows/a/workflow.ts': WORKFLOW })) + // No declared length, so each reserves a body at the cap: four callers fill the lane. + const running = Array.from({ length: 4 }, (_, caller) => { + asCaller(`filler-${caller}`) + return plan({ 'workflows/a/workflow.ts': WORKFLOW }) + }) await vi.waitFor(() => expect(finish).toHaveLength(4)) let read = false @@ -168,4 +208,62 @@ describe('POST /api/v2/workspaces/{workspaceId}/source/plan', () => { } expect((await plan({ 'workflows/a/workflow.ts': WORKFLOW })).status).toBe(200) }) + + it('answers 404 on the dedicated MCP host before admitting the caller or reading the body', async () => { + const MCP_HOST = 'mcp.sim.test' + setEnv({ SIM_MCP_URL: `https://${MCP_HOST}/mcp` }) + const request = new NextRequest( + `http://${MCP_HOST}/api/v2/workspaces/${WORKSPACE_ID}/source/plan`, + { + method: 'POST', + headers: { 'x-api-key': 'key', 'content-type': 'application/json', host: MCP_HOST }, + body: JSON.stringify({ files: {}, kinds: ['workflow'] }), + } + ) + + const response = await POST(request, { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) }) + + expect(response.status).toBe(404) + expect(request.bodyUsed).toBe(false) + expect(v2RouteMocks.authenticate).not.toHaveBeenCalled() + expect(mocks.plan).not.toHaveBeenCalled() + }) + + it('holds one caller to a cap’s worth of bodies, so its burst leaves room for another caller', async () => { + const result = await mocks.plan() + const finish: Array<() => void> = [] + mocks.plan.mockImplementation( + () => new Promise((resolve) => finish.push(() => resolve(result))) + ) + // Each declares no length, so each would reserve a body at the cap. + const burst = Array.from({ length: 4 }, () => plan({ 'workflows/a/workflow.ts': WORKFLOW })) + await vi.waitFor(() => expect(finish).toHaveLength(1)) + + asCaller('other') + const other = plan({ 'workflows/a/workflow.ts': WORKFLOW }) + await vi.waitFor(() => expect(finish).toHaveLength(2)) + for (const done of finish) done() + + expect((await other).status).toBe(200) + expect((await Promise.all(burst)).map((response) => response.status).sort()).toEqual([ + 200, 429, 429, 429, + ]) + }) + + it('refuses a body that stalls past its read deadline with 408 and frees its room', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + let reading: () => void = () => {} + const started = new Promise((resolve) => { + reading = resolve + }) + const stalled = stalledPlan(reading) + await started + + await vi.advanceTimersByTimeAsync(5 * 60_000) + + expect((await stalled).status).toBe(408) + expect(mocks.plan).not.toHaveBeenCalled() + // The same caller's next body at the cap is admitted: the stalled one no longer holds its room. + expect((await plan({ 'workflows/a/workflow.ts': WORKFLOW })).status).toBe(200) + }) }) diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts index 7d8ea3a6b90..91294aee0fd 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts @@ -18,8 +18,9 @@ export const revalidate = 0 * do, without writing: the dry run `sim workspaces source status` reads. Charged to the * source-plan budget as an apply is to the write budget (see `workspaceApplyRateCost`), so a * status never spends the source-write budget an apply needs. Plans run in their own slots: a - * server already running as many plans as it allows answers 429, and applies never wait on them. - * Answers 403 while the `workflow-code` flag is off. + * server already running as many plans as it allows answers 429, and applies never wait on them; + * so does a caller already sending a cap's worth of bodies. A body not received by its deadline + * answers 408. Answers 403 while the `workflow-code` flag is off. */ export const POST = defineV2JsonRoute({ contract: v2PlanWorkspaceSourceContract, diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts index 3dff9d8ce34..ce3448792e7 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts @@ -5,8 +5,9 @@ import { v2RateLimiterModuleMock, v2RouteMocks, } from '@sim/testing' +import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock' import { NextRequest } from 'next/server' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ apply: vi.fn(), read: vi.fn(), authorizeRead: vi.fn() })) @@ -57,6 +58,16 @@ function apply( ) } +/** The next request is sent with a personal key of its own user, a caller apart from `auth`'s. */ +function asCaller(userId: string) { + v2RouteMocks.authenticate.mockResolvedValueOnce({ + principal: { kind: 'personal_api_key', userId, keyId: `key-${userId}`, access: 'write' }, + rateLimitSubjectIds: [`api-key:key-${userId}`, `user:${userId}`], + rateLimitSubscription: null, + keyType: 'personal', + }) +} + /** `count` errors of one workflow folder, as a plan refusal pins them to it. */ function folderErrors(count: number): WorkspaceSourceDiagnostic[] { return Array.from({ length: count }, (_, index) => ({ @@ -146,9 +157,14 @@ describe('POST /api/v2/workspaces/{workspaceId}/source', () => { ? new Promise((resolve) => finish.push(() => resolve(result))) : Promise.resolve({ ...result, dryRun: false }) ) - const running = Array.from({ length: 4 }, () => apply('?dry=true')) + // Four callers, as one caller holds no more than one body at the cap in a lane. + const running = Array.from({ length: 4 }, (_, caller) => { + asCaller(`planner-${caller}`) + return apply('?dry=true') + }) await vi.waitFor(() => expect(finish).toHaveLength(4)) + asCaller('one-more') expect((await apply('?dry=true')).status).toBe(429) expect((await apply('')).status).toBe(200) @@ -262,3 +278,38 @@ describe('GET /api/v2/workspaces/{workspaceId}/source', () => { expect(data.diagnostics.at(-1)).toMatchObject({ code: 'I_FINDINGS_TRUNCATED' }) }) }) + +describe('the workspace source routes on the dedicated MCP host', () => { + const MCP_HOST = 'mcp.sim.test' + + beforeEach(() => { + setEnv({ SIM_MCP_URL: `https://${MCP_HOST}/mcp` }) + v2RouteMocks.authenticate.mockResolvedValue(auth) + v2RouteMocks.preauthRate.mockResolvedValue(V2_PREAUTH_RATE_LIMIT_ALLOWED) + v2RouteMocks.operationRate.mockResolvedValue(V2_OPERATION_RATE_LIMIT_ALLOWED) + }) + + afterEach(() => { + resetEnvMock() + }) + + it('answers a get and an apply 404 before admitting the caller or reading the body', async () => { + const url = `http://${MCP_HOST}/api/v2/workspaces/${WORKSPACE_ID}/source` + const params = { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) } + const write = new NextRequest(url, { + method: 'POST', + headers: { 'x-api-key': 'key', 'content-type': 'application/json', host: MCP_HOST }, + body: JSON.stringify({ files: {}, kinds: ['workflow'] }), + }) + + expect( + (await GET(new NextRequest(url, { headers: { 'x-api-key': 'key', host: MCP_HOST } }), params)) + .status + ).toBe(404) + expect((await POST(write, params)).status).toBe(404) + expect(write.bodyUsed).toBe(false) + expect(v2RouteMocks.authenticate).not.toHaveBeenCalled() + expect(mocks.read).not.toHaveBeenCalled() + expect(mocks.apply).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts index 049d9b7c606..974f434ed5c 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts @@ -52,7 +52,8 @@ export const GET = defineV2JsonRoute({ * written before it. A real apply draws on the source-write budget and a dry run, which writes * nothing, on the source-plan budget the status plan route uses (`v2RateLimits.sourceApply`), each * charged per workflow folder sent with its files (`workspaceApplyRateCost`), and runs in an apply - * or a plan slot to match; a server already running as many as it allows answers 429. + * or a plan slot to match; a server already running as many as it allows answers 429, as does a + * caller already sending a cap's worth of bodies. A body not received by its deadline answers 408. */ export const POST = defineV2JsonRoute({ contract: v2ApplyWorkspaceSourceContract, diff --git a/apps/sim/lib/api/mcp/dispatch.test.ts b/apps/sim/lib/api/mcp/dispatch.test.ts index a6c8d901793..f99d12880a0 100644 --- a/apps/sim/lib/api/mcp/dispatch.test.ts +++ b/apps/sim/lib/api/mcp/dispatch.test.ts @@ -103,6 +103,21 @@ describe('dispatchMcpOperation', () => { expect(getOAuthAccessTokenAudience()).toEqual({}) }) + it('declares the length of the body it sends, so a route reserves only what it holds', async () => { + await dispatchMcpOperation( + { + operation: 'completeFileUpload', + params: { uploadId: 'up-1' }, + body: { workspaceId: 'wörkspace-1' }, + headers: { 'upload-token': 'token' }, + }, + context + ) + const request = dispatched() + const sent = new Uint8Array(await request.arrayBuffer()) + expect(request.headers.get('content-length')).toBe(String(sent.byteLength)) + }) + it.each([ [{ tableId: 't' }, 'Missing path parameter rowId.'], [{ tableId: 't', rowId: 'r', extra: 'x' }, 'Unknown path parameter extra'], diff --git a/apps/sim/lib/api/mcp/dispatch.ts b/apps/sim/lib/api/mcp/dispatch.ts index 39c134f25d1..13a66227816 100644 --- a/apps/sim/lib/api/mcp/dispatch.ts +++ b/apps/sim/lib/api/mcp/dispatch.ts @@ -81,14 +81,21 @@ function resolvePath( } } -/** The dispatched request's headers: inherited context, the verified credential, and caller-settable contract headers. */ +/** + * The dispatched request's headers: inherited context, the verified credential, caller-settable + * contract headers, and the body's type and length, so a route that reserves room for a body + * before reading it reserves what this one holds. + */ function buildHeaders( call: McpOperationCall, context: McpDispatchContext, - hasBody: boolean + body: string | undefined ): Headers | { error: string } { const headers = new Headers({ accept: 'application/json', [CLIENT_INFO_HEADER]: 'mcp' }) - if (hasBody) headers.set('content-type', 'application/json') + if (body !== undefined) { + headers.set('content-type', 'application/json') + headers.set('content-length', String(new TextEncoder().encode(body).byteLength)) + } for (const name of INHERITED_HEADERS) { const value = context.inbound.headers.get(name) if (value) headers.set(name, value) @@ -208,7 +215,8 @@ export async function dispatchMcpRequest( 'Streaming is not supported over MCP. Omit stream to wait for the result, or set async: true and poll getWorkflowRun.', } } - const headers = buildHeaders(call, context, hasBody) + const body = hasBody ? JSON.stringify(call.body ?? {}) : undefined + const headers = buildHeaders(call, context, body) if ('error' in headers) return { rejected: headers.error } const route = await handler() @@ -219,7 +227,7 @@ export async function dispatchMcpRequest( const request = new NextRequest(url, { method: contract.method, headers, - body: hasBody ? JSON.stringify(call.body ?? {}) : undefined, + body, signal: context.signal, }) const response = await withOAuthAccessTokenAudience(context.audience, () => diff --git a/apps/sim/lib/api/server/routes/types.ts b/apps/sim/lib/api/server/routes/types.ts index 7aa80ca3099..bb5dd788fc7 100644 --- a/apps/sim/lib/api/server/routes/types.ts +++ b/apps/sim/lib/api/server/routes/types.ts @@ -42,6 +42,16 @@ export interface JsonErrorResponseDescriptor { headers?: HeadersInit } +/** + * Room a route holds for a request's body from before it is read until the request is answered: + * `release` frees it, however the request ends, and a body not read within `readDeadlineMs` is + * refused so a stalled upload cannot keep it. + */ +export interface BodyReservation { + release(): void + readDeadlineMs: number +} + export interface JsonRouteDefinition< C extends JsonApiRouteContract, O extends ApplicationOperation, diff --git a/apps/sim/lib/api/server/routes/v2-json-route.ts b/apps/sim/lib/api/server/routes/v2-json-route.ts index 749f0bce7aa..a180d544a65 100644 --- a/apps/sim/lib/api/server/routes/v2-json-route.ts +++ b/apps/sim/lib/api/server/routes/v2-json-route.ts @@ -5,6 +5,7 @@ import { LRUCache } from 'lru-cache' import type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' import { booleanQueryFlagSchema } from '@/lib/api/contracts/primitives' +import { isOffAppHost } from '@/lib/api/mcp/host-routing' import { recordRateLimitSnapshot } from '@/lib/api/server/rate-limit-context' import { type CopilotRouteUseCase, @@ -20,6 +21,7 @@ import { requireJsonRouteDefinition, } from '@/lib/api/server/routes/definition' import type { + BodyReservation, JsonApiRouteContract, JsonNextRouteHandler, JsonRouteContext, @@ -328,6 +330,11 @@ function declaresNonJsonBody(request: Request): boolean { return subtype !== 'json' && !subtype.endsWith('+json') } +/** A body a route's read deadline stopped, as `408` in the v2 envelope. */ +function v2BodyReadTimeoutResponse(): NextResponse { + return v2Error('BAD_REQUEST', 'The request body was not received in time.', { status: 408 }) +} + /** * The v2 answer to a body that could not be read as JSON: `415` when the caller * declared a non-JSON media type, `400` otherwise. @@ -603,7 +610,10 @@ interface V2JsonRouteOptions beforeParse?(args: { request: NextRequest @@ -611,11 +621,12 @@ interface V2JsonRouteOptions }): void | Promise /** - * Runs once the caller is admitted, before the body is read, and returns a release called once - * the request is answered, however it ends: a hold that must cover reading the body, such as - * room reserved for a large one. What it throws is rendered by `errorPolicy`. + * Runs once the caller is admitted, before the body is read: a hold that must cover reading the + * body, such as room reserved for a large one, released once the request is answered, however + * it ends. A body not read by the reservation's deadline is answered 408. What it throws is + * rendered by `errorPolicy`. */ - reserveBody?(request: NextRequest): () => void + reserveBody?(args: { request: NextRequest; principal: Principal }): BodyReservation onSuccess?(args: { principal: Principal input: NoInfer @@ -682,6 +693,10 @@ export function defineV2JsonRoute< `Route received ${request.method} for ${options.contract.method} contract ${options.contract.path}` ) } + // The dedicated MCP host serves nothing but the MCP server. The proxy answers its other paths + // 404, but its matcher leaves out the routes that read their own large bodies, so they answer + // it here, before admitting the caller or reserving room for a body. + if (isOffAppHost(request)) return v2Error('NOT_FOUND', 'Not found') const admission = await admitRateLimitedV2Request( request, @@ -708,20 +723,26 @@ export function defineV2JsonRoute< } } - let release: (() => void) | undefined + let reservation: BodyReservation | undefined try { - release = options.reserveBody?.(request) + reservation = options.reserveBody?.({ request, principal: auth.principal }) } catch (error) { const response = options.errorPolicy.render(error) if (response) return response throw error } + const readDeadline = reservation ? new AbortController() : undefined + const readTimer = reservation + ? setTimeout(() => readDeadline?.abort(), reservation.readDeadlineMs) + : undefined try { const parsed = await parseRequest(options.contract, request, context ?? {}, { ...V2_PARSE_DEFAULTS, invalidJsonResponse: () => v2InvalidBodyResponse(request), + bodyReadTimeoutResponse: v2BodyReadTimeoutResponse, ...options.parseOptions, + bodyReadSignal: readDeadline?.signal, validationErrorResponseBySlice: v2ValidationError, }) if (!parsed.success) return parsed.response @@ -808,7 +829,8 @@ export function defineV2JsonRoute< throw error } } finally { - release?.() + clearTimeout(readTimer) + reservation?.release() } }, { diff --git a/apps/sim/lib/api/server/validation.ts b/apps/sim/lib/api/server/validation.ts index dd1f1396932..047e01c5ce5 100644 --- a/apps/sim/lib/api/server/validation.ts +++ b/apps/sim/lib/api/server/validation.ts @@ -116,6 +116,12 @@ export interface ParseRequestOptions { * truncates its body and {@link maxBodyBytes} applies unclamped. */ bypassesProxy?: boolean + /** + * Stops reading the body once aborted, as a route's read deadline does; a body it stops is + * answered by {@link bodyReadTimeoutResponse} (by default a 408). + */ + bodyReadSignal?: AbortSignal + bodyReadTimeoutResponse?: () => NextResponse /** Treat an absent or whitespace-only body as `undefined` before contract validation. */ optionalJsonBody?: boolean /** @@ -138,6 +144,11 @@ export function isZodError(error: unknown): error is z.ZodError { return error instanceof ZodError } +/** The default 408 for a request body {@link ParseRequestOptions.bodyReadSignal} stopped reading. */ +function bodyReadTimeoutResponse(): NextResponse<{ error: string }> { + return NextResponse.json({ error: 'Request body was not received in time' }, { status: 408 }) +} + /** The default 400 for a request body that is not valid JSON. */ export function invalidJsonBodyResponse(): NextResponse<{ error: string }> { return NextResponse.json({ error: 'Request body must be valid JSON' }, { status: 400 }) @@ -178,7 +189,11 @@ const REQUEST_BODY_LABEL = 'Request body' * uses {@link TextDecoder} so a leading UTF-8 BOM is stripped, matching the spec * "UTF-8 decode" behavior of `request.json()`. */ -async function readJsonBodyWithLimit(request: Request, maxBytes: number): Promise { +async function readJsonBodyWithLimit( + request: Request, + maxBytes: number, + signal?: AbortSignal +): Promise { assertContentLengthWithinLimit(request.headers, maxBytes, REQUEST_BODY_LABEL) const stream = request.body @@ -189,6 +204,7 @@ async function readJsonBodyWithLimit(request: Request, maxBytes: number): Promis const buffer = await readStreamToBufferWithLimit(stream, { maxBytes, label: REQUEST_BODY_LABEL, + signal, }) return JSON.parse(new TextDecoder().decode(buffer)) } @@ -197,20 +213,24 @@ export async function parseJsonBody( request: Request, invalidJson: ParseRequestOptions['invalidJson'] = 'response', maxBytes: number = DEFAULT_MAX_JSON_BODY_BYTES, - bypassesProxy = false + bypassesProxy = false, + signal?: AbortSignal ): Promise< | { success: true; data: unknown } | { success: false - reason: 'too_large' | 'invalid_json' + reason: 'too_large' | 'invalid_json' | 'timeout' response: NextResponse<{ error: string }> } > { const limit = clampToProxyLimit(maxBytes, bypassesProxy) try { - return { success: true, data: await readJsonBodyWithLimit(request, limit) } + return { success: true, data: await readJsonBodyWithLimit(request, limit, signal) } } catch (error) { if (invalidJson === 'throw') throw error + if (signal?.aborted) { + return { success: false, reason: 'timeout', response: bodyReadTimeoutResponse() } + } if (isPayloadSizeLimitError(error)) { return { success: false, @@ -239,12 +259,13 @@ export async function parseJsonBody( export async function parseOptionalJsonBody( request: Request, maxBytes: number = DEFAULT_MAX_JSON_BODY_BYTES, - bypassesProxy = false + bypassesProxy = false, + signal?: AbortSignal ): Promise< | { success: true; data: unknown } | { success: false - reason: 'too_large' | 'invalid_json' + reason: 'too_large' | 'invalid_json' | 'timeout' response: NextResponse<{ error: string }> } > { @@ -255,7 +276,11 @@ export async function parseOptionalJsonBody( const stream = request.body const text = stream ? new TextDecoder().decode( - await readStreamToBufferWithLimit(stream, { maxBytes: limit, label: REQUEST_BODY_LABEL }) + await readStreamToBufferWithLimit(stream, { + maxBytes: limit, + label: REQUEST_BODY_LABEL, + signal, + }) ) : await request.text() @@ -264,6 +289,9 @@ export async function parseOptionalJsonBody( } return { success: true, data: JSON.parse(text) } } catch (error) { + if (signal?.aborted) { + return { success: false, reason: 'timeout', response: bodyReadTimeoutResponse() } + } if (isPayloadSizeLimitError(error)) { return { success: false, @@ -330,14 +358,23 @@ export async function parseRequest( let body: unknown if (shouldReadJsonBody(contract)) { const parsedBody = options?.optionalJsonBody - ? await parseOptionalJsonBody(request, options.maxBodyBytes, options.bypassesProxy) + ? await parseOptionalJsonBody( + request, + options.maxBodyBytes, + options.bypassesProxy, + options.bodyReadSignal + ) : await parseJsonBody( request, options?.invalidJson, options?.maxBodyBytes, - options?.bypassesProxy + options?.bypassesProxy, + options?.bodyReadSignal ) if (!parsedBody.success) { + if (options?.bodyReadTimeoutResponse && parsedBody.reason === 'timeout') { + return { success: false, response: options.bodyReadTimeoutResponse() } + } if ( options?.invalidJsonResponse && 'reason' in parsedBody && diff --git a/apps/sim/lib/workflows/api/source-slots.test.ts b/apps/sim/lib/workflows/api/source-slots.test.ts index c6adeeb88cd..555b5a18e1c 100644 --- a/apps/sim/lib/workflows/api/source-slots.test.ts +++ b/apps/sim/lib/workflows/api/source-slots.test.ts @@ -1,10 +1,19 @@ /** * @vitest-environment node */ -import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { PrincipalSubjectUserRequiredError } from '@sim/auth/principal' +import { + createExecutorPrincipal, + createSessionPrincipal, +} from '@sim/testing/factories/principal.factory' +import { createMockRequest } from '@sim/testing/mocks/request.mock' import { generateId } from '@sim/utils/id' import { describe, expect, it } from 'vitest' -import { renderSourceSlotBusy, withSourceSlot } from '@/lib/workflows/api/source-slots' +import { + renderSourceSlotBusy, + reserveWorkspaceSourceBody, + withSourceSlot, +} from '@/lib/workflows/api/source-slots' import { workspaceSourceOperations } from '@/lib/workspace-source/application/operations' const principal = createSessionPrincipal({ userId: generateId(), sessionId: generateId() }) @@ -74,3 +83,17 @@ describe('withSourceSlot', () => { await expect(Promise.all(planning)).resolves.toHaveLength(4) }) }) + +describe('reserveWorkspaceSourceBody', () => { + it('refuses a caller with no person or workspace key behind it rather than pooling every such caller', () => { + const request = createMockRequest({ + method: 'POST', + url: 'https://sim.test/api/v2/workspaces/ws-1/source/plan', + headers: { 'content-length': '2' }, + }) + const reserve = reserveWorkspaceSourceBody('plan') + expect(() => + reserve({ request, principal: createExecutorPrincipal({ subjectUserId: undefined }) }) + ).toThrow(PrincipalSubjectUserRequiredError) + }) +}) diff --git a/apps/sim/lib/workflows/api/source-slots.ts b/apps/sim/lib/workflows/api/source-slots.ts index 0bd04b8caf6..080f0ca4960 100644 --- a/apps/sim/lib/workflows/api/source-slots.ts +++ b/apps/sim/lib/workflows/api/source-slots.ts @@ -1,8 +1,9 @@ +import { type Principal, requirePrincipalSubjectUserId } from '@sim/auth/principal' import { WORKSPACE_SOURCE_REQUEST_MAX_BYTES } from '@sim/workspace-code/limits' import type { NextRequest, NextResponse } from 'next/server' import { booleanQueryFlagSchema } from '@/lib/api/contracts/primitives' import { internalErrorResponse } from '@/lib/api/server/routes' -import type { JsonErrorResponseDescriptor } from '@/lib/api/server/routes/types' +import type { BodyReservation, JsonErrorResponseDescriptor } from '@/lib/api/server/routes/types' import type { ApplicationOperation, AuthorizingUseCase } from '@/lib/core/application' import { v2Error } from '@/app/api/v2/lib/response' @@ -38,19 +39,52 @@ class SourceSlotBusyError extends Error { /** Bytes of workspace source bodies each lane holds at once, reserved before they are read. */ const heldSourceBodyBytes: Record = { read: 0, editor: 0, plan: 0, apply: 0 } +/** + * Bytes of a lane's bodies each caller holds, by {@link bodyHolderOf}. A caller may hold one body + * at the cap's worth in a lane (or several smaller ones), so no one caller, however many requests + * it sends, holds room another needs. + */ +const heldSourceBodyBytesByHolder: Record> = { + read: new Map(), + editor: new Map(), + plan: new Map(), + apply: new Map(), +} + +/** + * The slowest a source body is read at before its reservation lapses, past a grace for the first + * bytes: a cap-sized body has about four minutes, under the server's request timeout, and a body + * that stalls releases its room instead of holding it until the socket times out. + */ +const SOURCE_BODY_MIN_BYTES_PER_SECOND = 256 * 1024 +const SOURCE_BODY_READ_GRACE_MS = 30_000 + +/** + * Who a body is held for: the workspace a key belongs to, or the person behind any other + * credential. Throws for a principal with no person behind it, so no such caller shares one + * holder with every other. + */ +function bodyHolderOf(principal: Principal): string { + if (principal.kind === 'workspace_api_key') return `workspace:${principal.workspaceId}` + // actorless-unsupported: the source routes admit only session, personal key, OAuth token, and workspace key callers; an actorless caller has no holder to bound its bodies by. + return `user:${requirePrincipalSubjectUserId(principal)}` +} + /** * A route's `reserveBody` for a workspace source apply or plan, whose body is read outside the * proxy's 10 MiB buffer and before the use case takes a slot: room for the body in its lane * (`laneOf`, or the lane it picks for the request), as many bytes as the lane's slots hold bodies * at the cap, reserved before the body is read. A body reserves its declared length (Node never * delivers more than one declares), or the cap when it declares none. Refused with a `429` (see - * {@link renderSourceSlotBusy}) when the lane's bodies already leave too little room, so a burst - * cannot hold more bodies in memory than the lane would ever run. + * {@link renderSourceSlotBusy}) when the lane's bodies already leave too little room, or the + * caller already holds a cap's worth in the lane, so a burst cannot hold more bodies in memory + * than the lane would ever run and one caller cannot hold every other caller's room. The body + * must arrive by its deadline, which grows with its size, or it is refused and its room freed. */ export function reserveWorkspaceSourceBody( laneOf: SourceLane | ((request: NextRequest) => SourceLane) -): (request: NextRequest) => () => void { - return (request) => { +): (args: { request: NextRequest; principal: Principal }) => BodyReservation { + return ({ request, principal }) => { const lane = typeof laneOf === 'function' ? laneOf(request) : laneOf const declared = Number(request.headers.get('content-length') ?? Number.NaN) const bytes = @@ -58,17 +92,33 @@ export function reserveWorkspaceSourceBody( ? Math.min(declared, WORKSPACE_SOURCE_REQUEST_MAX_BYTES) : WORKSPACE_SOURCE_REQUEST_MAX_BYTES const budget = SOURCE_LANES[lane].max * WORKSPACE_SOURCE_REQUEST_MAX_BYTES + const holders = heldSourceBodyBytesByHolder[lane] + const holder = bodyHolderOf(principal) + const heldByHolder = holders.get(holder) ?? 0 + if (heldByHolder + bytes > WORKSPACE_SOURCE_REQUEST_MAX_BYTES) { + throw new SourceSlotBusyError( + `You are already sending as many source ${SOURCE_LANES[lane].noun} as this server holds for one caller; retry once one finishes.` + ) + } if (heldSourceBodyBytes[lane] + bytes > budget) { throw new SourceSlotBusyError( `This server is already reading as many source ${SOURCE_LANES[lane].noun} as it holds at once; retry shortly.` ) } heldSourceBodyBytes[lane] += bytes + holders.set(holder, heldByHolder + bytes) let released = false - return () => { - if (released) return - released = true - heldSourceBodyBytes[lane] -= bytes + return { + readDeadlineMs: + SOURCE_BODY_READ_GRACE_MS + Math.ceil((bytes / SOURCE_BODY_MIN_BYTES_PER_SECOND) * 1000), + release: () => { + if (released) return + released = true + heldSourceBodyBytes[lane] -= bytes + const remaining = (holders.get(holder) ?? 0) - bytes + if (remaining > 0) holders.set(holder, remaining) + else holders.delete(holder) + }, } } }