From f9129dfa47321ff1622076a1f03dc3bf32b0ca0f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:30:07 -0800 Subject: [PATCH 1/2] fix(workspace-source): read apply and plan bodies past 10 MiB, refuse oversized ones locally --- apps/docs/content/docs/cli/reference.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- .../docs/platform/self-hosting/networking.mdx | 2 + .../[workspaceId]/source/plan/route.test.ts | 9 ++ .../[workspaceId]/source/plan/route.ts | 2 +- .../[workspaceId]/source/route.test.ts | 19 +++ .../workspaces/[workspaceId]/source/route.ts | 2 +- apps/sim/proxy.test.ts | 7 ++ apps/sim/proxy.ts | 9 +- .../commands/protocol/source-exit-codes.ts | 2 +- .../protocol/workspace-source-apply.test.ts | 21 +++- .../protocol/workspace-source-apply.ts | 5 +- .../protocol/workspace-source-check.test.ts | 40 +++++++ .../protocol/workspace-source-check.ts | 2 +- .../commands/protocol/workspace-source-dir.ts | 109 ++++++++++++------ .../protocol/workspace-source-get.test.ts | 12 +- .../protocol/workspace-source-status.test.ts | 29 +++++ .../protocol/workspace-source-status.ts | 29 +++-- packages/workspace-code/src/kinds/registry.ts | 38 +++++- packages/workspace-code/src/limits.ts | 8 +- packages/workspace-code/src/promote.ts | 25 +--- 21 files changed, 276 insertions(+), 98 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 6c054ff1717..5aea13c947d 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -10129,7 +10129,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), a --run test run did not complete (the apply is written; deployments/ was not applied), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), a --run test run did not complete (the apply is written; deployments/ was not applied), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large (apply part of it with --only); 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [executeWorkflow](/api-reference/workflows/executeWorkflowV2). diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 60950234009..68812f900c7 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -763,7 +763,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), a --run test run did not complete (the apply is written; deployments/ was not applied), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), a --run test run did not complete (the apply is written; deployments/ was not applied), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large (apply part of it with --only); 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [executeWorkflow](/api-reference/workflows/executeWorkflowV2). diff --git a/apps/docs/content/docs/platform/self-hosting/networking.mdx b/apps/docs/content/docs/platform/self-hosting/networking.mdx index f929a7f665b..19c953b1641 100644 --- a/apps/docs/content/docs/platform/self-hosting/networking.mdx +++ b/apps/docs/content/docs/platform/self-hosting/networking.mdx @@ -259,6 +259,8 @@ A reverse-proxy limit of at least 250 MB clears these configured defaults; use t Most `/api` requests also pass through Next.js Proxy. The current app configuration leaves its `proxyClientMaxBodySize` at 10 MiB. Larger bodies are truncated to that buffer rather than automatically rejected by Next.js; the route may then fail to parse them. Receiving larger custom-route bodies requires changing `experimental.proxyClientMaxBodySize` in the app build, which increases per-request memory use. The shared JSON parser separately clamps contract-validated bodies to 10 MiB, so raising the Next.js buffer alone does not increase their limit. See [Next.js proxy body buffering](https://nextjs.org/docs/app/api-reference/config/next-config-js/proxyClientMaxBodySize). +Workspace source apply and plan requests (`POST /api/v2/workspaces/{workspaceId}/source` and `/source/plan`) skip Next.js Proxy and accept bodies up to 58 MB, so your reverse proxy must allow that size for large table rows to apply. + **With object storage configured**, regular file uploads do not flow through the proxy — the browser `PUT`s them directly to the bucket using a presigned URL, so the proxy limits matter only for chat attachments, API payloads, and webhook bodies. On the default local-disk storage there is no presigned path and every upload goes through the proxy, so its body limit applies to all of them. ## Outbound connectivity 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 59e5579c238..eccc8475b2a 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 @@ -109,4 +109,13 @@ describe('POST /api/v2/workspaces/{workspaceId}/source/plan', () => { expect(data.diagnostics).toHaveLength(1_001) expect(data.diagnostics.at(-1)).toMatchObject({ code: 'I_FINDINGS_TRUNCATED' }) }) + + it('reads a body past the 10 MiB proxy ceiling whole, as a large table rows file sends', async () => { + const rows = `${'{"code":"a","note":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}\n'.repeat(160_000)}` + + const response = await plan({ 'tables/leads.rows.jsonl': rows }) + + expect(response.status).toBe(200) + expect(mocks.plan.mock.calls[0][0].input.files['tables/leads.rows.jsonl']).toBe(rows) + }) }) 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 39be49146cf..32865f1d97b 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 @@ -27,7 +27,7 @@ export const POST = defineV2JsonRoute({ operation: workspaceSourceOperations.plan, rateLimit: v2RateLimits.sourcePlan, errorPolicy: v2WorkspaceSourceErrorPolicy, - parseOptions: { maxBodyBytes: WORKSPACE_SOURCE_REQUEST_MAX_BYTES }, + parseOptions: { maxBodyBytes: WORKSPACE_SOURCE_REQUEST_MAX_BYTES, bypassesProxy: true }, mapInput: ({ params, body }) => ({ workspaceId: params.workspaceId, files: body.files, 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 1c31117b52b..3dff9d8ce34 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 @@ -199,6 +199,25 @@ describe('POST /api/v2/workspaces/{workspaceId}/source', () => { expect(data.diagnostics).toHaveLength(1_001) expect(data.diagnostics.at(-1)).toMatchObject({ code: 'I_FINDINGS_TRUNCATED' }) }) + + it('reads a body past the 10 MiB proxy ceiling whole, as a large table rows file sends', async () => { + mocks.apply.mockResolvedValue({ + workspaceId: WORKSPACE_ID, + dryRun: false, + plan: [], + applied: [], + needBlobs: [], + files: {}, + base: { version: 1, workspaceId: WORKSPACE_ID, resources: {} }, + diagnostics: [], + }) + const rows = `${'{"code":"a","note":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}\n'.repeat(160_000)}` + + const response = await apply('', { 'tables/leads.rows.jsonl': rows }) + + expect(response.status).toBe(200) + expect(mocks.apply.mock.calls[0][0].input.files['tables/leads.rows.jsonl']).toBe(rows) + }) }) /** `count` warnings, one per workflow, as a stored workspace whose tables are gone reads. */ 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 85db85b0cfa..76fcb2e0ec2 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts @@ -55,7 +55,7 @@ export const POST = defineV2JsonRoute({ operation: workspaceSourceOperations.apply, rateLimit: v2RateLimits.sourceApply, errorPolicy: v2WorkspaceSourceErrorPolicy, - parseOptions: { maxBodyBytes: WORKSPACE_SOURCE_REQUEST_MAX_BYTES }, + parseOptions: { maxBodyBytes: WORKSPACE_SOURCE_REQUEST_MAX_BYTES, bypassesProxy: true }, mapInput: ({ params, query, body }) => ({ workspaceId: params.workspaceId, files: body.files, diff --git a/apps/sim/proxy.test.ts b/apps/sim/proxy.test.ts index 0b922053604..564df021759 100644 --- a/apps/sim/proxy.test.ts +++ b/apps/sim/proxy.test.ts @@ -261,6 +261,11 @@ describe('proxy matcher', () => { expect(matches('/api/internal/project-file-doc/project-1/file-1/persist')).toBe(false) }) + it('leaves a workspace source apply and plan unbuffered, so a body past 10 MB reaches the route', () => { + expect(matches('/api/v2/workspaces/ws-1/source')).toBe(false) + expect(matches('/api/v2/workspaces/ws-1/source/plan')).toBe(false) + }) + it('runs for the marketing documents, so the indexing policy reaches them', () => { expect(matches('/index.md')).toBe(true) expect(matches('/llms.txt')).toBe(true) @@ -278,6 +283,8 @@ describe('proxy matcher', () => { expect(matches('/api/internal/project-file-doc/project-1/file-1/persist/other')).toBe(true) expect(matches('/api/internal/file-doc/persist/other')).toBe(true) expect(matches('/api/internal/file-doc/seed')).toBe(true) + expect(matches('/api/v2/workspaces/ws-1/source/blobs')).toBe(true) + expect(matches('/api/v2/workspaces/ws-1/source/blobs/missing')).toBe(true) }) }) diff --git a/apps/sim/proxy.ts b/apps/sim/proxy.ts index 6381e13aaf8..e0fb7e33e51 100644 --- a/apps/sim/proxy.ts +++ b/apps/sim/proxy.ts @@ -500,10 +500,11 @@ export const config = { '/login', '/signup', '/invite/:path*', // Match invitation routes - // Runtime CORS. The desktop's raw upload routes and the realtime relay's document persists are - // left out: running the proxy makes Next buffer the body, cutting it off at its 10 MB proxy - // limit, and those bodies are whole files or document snapshots. - '/api/((?!desktop/tool/(?:import|file)$|internal/file-doc/persist$|internal/project-file-doc/[^/]+/[^/]+/persist$).*)', + // Runtime CORS. The desktop's raw upload routes, the realtime relay's document persists and a + // workspace source apply or plan are left out: running the proxy makes Next buffer the body, + // cutting it off at its 10 MB proxy limit, and those bodies are whole files, document + // snapshots or a workspace's source (each route caps its own body). + '/api/((?!desktop/tool/(?:import|file)$|internal/file-doc/persist$|internal/project-file-doc/[^/]+/[^/]+/persist$|v2/workspaces/[^/]+/source(?:/plan)?$).*)', // Next's image optimizer fetches public editorial images without a User-Agent. '/((?!api/|api$|_next/static|_next/image|(?:blog|changelog)/.*\\.(?:avif|gif|jpe?g|png|svg|webp)$|ingest|favicon.ico|logo/|landing/|static/|footer/|social/|enterprise/|favicon/|twitter/|robots.txt|sitemap.xml).*)', ], diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index 57fc092e4e1..aa7d2b8bdbc 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -159,7 +159,7 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo 'workflows source create': 'the source is too large', 'workflows source get': 'the workflow is too large to print as source', 'workflows source status': STATUS_TOO_LARGE, - 'workspaces source apply': 'the directory is too large', + 'workspaces source apply': 'the directory is too large (apply part of it with --only)', 'workspaces source status': STATUS_TOO_LARGE, }, }, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index 53b0a150798..a7d0b88c2a9 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -15,7 +15,10 @@ import { } from 'node:fs' import { hostname, tmpdir } from 'node:os' import { basename, dirname, join } from 'node:path' -import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' +import { + WORKSPACE_SOURCE_LIMITS, + WORKSPACE_SOURCE_REQUEST_MAX_BYTES, +} from '@sim/workspace-code/limits' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SimApiError } from '../../http/client' import { cacheCatalogText } from '../../test/catalog-cache' @@ -1624,6 +1627,22 @@ describe('workspaces source apply', () => { expect(request).not.toHaveBeenCalled() }) + it('refuses a request over the body cap before sending it, exit 7, naming the bytes by folder and the --only split', async () => { + // Each control character is six bytes once JSON-escaped, so the body passes the cap. + const escapedBytes = Math.ceil(WORKSPACE_SOURCE_REQUEST_MAX_BYTES / 6) + 1 + write('tables/leads.rows.jsonl', '\u0001'.repeat(escapedBytes)) + request.mockResolvedValue(answer()) + + await expect(apply('--dry')).rejects.toMatchObject({ + code: 'SOURCE_TOO_LARGE', + exitCode: 7, + message: expect.stringMatching( + /over the \d+-byte limit; nothing was sent\. Bytes by folder: tables \d+, workflows \d+\. .*`--only tables`, then `--only workflows`/ + ), + }) + expect(request).not.toHaveBeenCalled() + }) + it('refuses a directory listing more binary files than one holds before hashing any, exit 7', async () => { write('files/a.bin', 'a') write('knowledge/kb/docs/b.txt', 'b') diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 1992e5b9e97..b9115e5daf0 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -14,7 +14,7 @@ import { resourceAddress, type WorkspaceKind, } from '@sim/workspace-code' -import { isBlobPath, KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' +import { declaredKeys, isBlobPath, KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' import { workflowFolder } from '@sim/workspace-code/kinds/workflow' import { kindOfPath, WORKSPACE_BASE_FILE } from '@sim/workspace-code/layout' import { @@ -96,9 +96,9 @@ import { stageBlobs, } from './workspace-source-blobs' import { + assertRequestFits, assertWorkspaceDir, assertWorkspacePaths, - declaredKeys, kindFolders, ONLY_KINDS_HELP, parseKinds, @@ -781,6 +781,7 @@ export function attachWorkspaceSourceApply(source: Command): void { }, provenance: { client: 'cli', ...provenance }, } + assertRequestFits(body) const response = await client.request( 'applyWorkspaceSource', { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts index e016df3ea58..91a0b7bc97a 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts @@ -305,6 +305,46 @@ describe('sim workspaces source check', () => { expect(process.exitCode).toBe(1) }) + it('fails on a table declaration the dry run refuses, at its line, rather than skipping the table and its rows', async () => { + writeFile( + 'tables/plans.ts', + [ + '// @sim-sdk 1', + "import { column, defineTable } from '@sim/workflow-sdk/workspace'", + 'export default defineTable({', + " name: 'plans',", + ' columns: {', + ' code: column.string({ required: true, unique: true }),', + " tier: column.select({ options: ['free', 'free'] }),", + " price: column.currency({ currencyCode: 'NOTACODE' }),", + ' },', + " rows: { mode: 'managed', key: 'code' },", + '})', + '', + ].join('\n') + ) + writeFile('tables/plans.rows.jsonl', '{"code":"a","nope":1}\n') + + await check() + + const found = (stdoutJson().diagnostics as Array>).map( + ({ file, line, message }) => ({ file, line, message }) + ) + expect(found).toEqual([ + expect.objectContaining({ + file: 'tables/plans.ts', + line: 7, + message: expect.stringContaining('Option "free" is listed twice'), + }), + expect.objectContaining({ + file: 'tables/plans.ts', + line: 8, + message: expect.stringContaining('"NOTACODE" is not a supported currency code'), + }), + ]) + expect(process.exitCode).toBe(1) + }) + it('a rows file with more bad lines than one file lists exits 1, as source errors, not 7 as a size limit', async () => { writeFile( 'tables/plans.ts', diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts index 160b05aa373..9516faaeb0d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -155,7 +155,7 @@ export function attachWorkspaceSourceCheck(source: Command): void { file, line, column, - } of declarations.rowFindings) { + } of declarations.tableFindings) { findings.push({ code, severity, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 33f15336798..4d4d0ab0542 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -6,6 +6,7 @@ */ import { realpath, stat } from 'node:fs/promises' import { mapWithConcurrency } from '@sim/utils/concurrency' +import { utf8ByteLength } from '@sim/utils/paste' import { compareStrings } from '@sim/utils/string' import type { ChildResultFields, WorkflowInput } from '@sim/workflow-code' import { SOURCE_CODE_DIR, SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' @@ -26,8 +27,7 @@ import { type WorkspaceDiagnosticCode, type WorkspaceKind, } from '@sim/workspace-code' -import { fileKindGroupKey } from '@sim/workspace-code/kinds/entries' -import { FILE_KIND_CODECS, isBlobPath, KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' +import { declaredKeys, isBlobPath, KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' import { columnName, createTableCodec, @@ -46,7 +46,10 @@ import { kindOfPath, WORKSPACE_BASE_FILE, } from '@sim/workspace-code/layout' -import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' +import { + WORKSPACE_SOURCE_LIMITS, + WORKSPACE_SOURCE_REQUEST_MAX_BYTES, +} from '@sim/workspace-code/limits' import { RATE_LIMITED_EXIT_CODE, SOURCE_BUSY_EXIT_CODE, @@ -288,25 +291,6 @@ export async function writtenLocalDeclarations( return localDeclarations(files) } -/** - * The keys `files` (path → text) declare for `kind`: a root file's entries, or the resources its - * folder's paths group into. `null` for a root file that is absent or does not read, whose keys - * are unknown. - */ -export function declaredKeys( - kind: WorkspaceKind, - files: Readonly> -): string[] | null { - if (!isFileKind(kind)) { - const paths = Object.keys(files).filter((path) => kindOfPath(path) === kind) - return [...KIND_LAYOUTS[kind].group(paths).groups.keys()] - } - const file = KIND_DIRS[kind] - if (!Object.hasOwn(files, file)) return null - const read = FILE_KIND_CODECS[kind].parse(fileKindGroupKey(kind), { [file]: files[file] }, []) - return read.decl ? Object.keys(read.decl) : null -} - /** * The kinds whose keys an offline check holds a workflow's references to. A skill counts too: a * built-in skill is stored by id and never printed as `skill('')`, so a key names a @@ -346,11 +330,13 @@ export interface WorkspaceDeclarations { /** Each declared table's columns, by table key and then by stored column name. */ tables: ReadonlyMap> /** - * What the declared rows of each table (`tables/.rows.jsonl`) hold that an apply refuses, - * each at its line: a line that is not a JSON object of declared columns, a managed key two - * lines share, and a row the write refuses (`refusedTableRows`). + * What an apply refuses in each table's files, each at its line: a declaration the table codec + * cannot read (an option listed twice, an unsupported currency code), whose table then goes + * unchecked, and in the declared rows of a table that reads (`tables/.rows.jsonl`) a line + * that is not a JSON object of declared columns, a managed key two lines share, and a row the + * write refuses (`refusedTableRows`). */ - rowFindings: readonly RowFinding[] + tableFindings: readonly TableFinding[] /** What `workspace.d.ts` types from the directory's declarations (`localDeclarations`). */ local: LocalDeclarations /** @@ -371,10 +357,10 @@ export interface WorkspaceDeclarations { } /** - * A finding about a line of a table's rows file: `E_TABLE_ROWS`, an error, or the - * `I_FINDINGS_TRUNCATED` that ends a long list. + * A finding about a line of a table's files: its declaration's codec finding, or about its rows + * file `E_TABLE_ROWS`, an error, or the `I_FINDINGS_TRUNCATED` that ends a long list. */ -interface RowFinding { +interface TableFinding { code: WorkspaceDiagnosticCode severity: FlatDiagnostic['severity'] message: string @@ -410,41 +396,59 @@ export async function readWorkspaceDeclarations(root: string): Promise>() - const rowFindings: RowFinding[] = [] + const tableFindings: TableFinding[] = [] for (const [key, tablePaths] of KIND_LAYOUTS.table.group( paths.filter((path) => kindOfPath(path) === 'table') ).groups) { const rowsPath = tableRowsPath(key) - const { decl } = declaredTable( + const { decl, diagnostics } = declaredTable( key, tablePaths.filter((path) => path !== rowsPath), files ) + tableFindings.push(...diagnostics.map((finding) => declarationFinding(key, finding))) if (!decl) continue tables.set(key, declaredColumns(decl)) - rowFindings.push(...tableRowFindings(key, decl, files[rowsPath])) + tableFindings.push(...tableRowFindings(key, decl, files[rowsPath])) } return { ...(secrets ? { envNames: new Set(secrets) } : {}), keys, tables, - rowFindings, + tableFindings, local: localDeclarations(files), } } +/** A finding of table `key`'s declaration codec, at its span or else the declaration's first line. */ +function declarationFinding( + key: string, + finding: ParsedTable['diagnostics'][number] +): TableFinding { + const { code, severity, message, hint, span } = finding + return { + code, + severity, + message, + ...(hint ? { hint } : {}), + file: span?.file ?? `${KIND_DIRS.table}/${key}${DECLARATION_EXTENSION}`, + line: span?.line ?? 1, + column: span?.column ?? 1, + } +} + /** * The findings of table `key`'s rows file, read against `decl` (its declaration, read without the * file): the reader's own (a line that is not a JSON object of declared columns, a managed key two * lines share) and each row the write refuses, at the row's line. */ -function tableRowFindings(key: string, decl: TableDecl, text: string | undefined): RowFinding[] { +function tableRowFindings(key: string, decl: TableDecl, text: string | undefined): TableFinding[] { const file = tableRowsPath(key) const rows = decl.rows if (!rows || text === undefined) return [] const parsed = parseTableRows(key, text, rows, new Set(Object.keys(decl.columns))) const read = parsed.diagnostics.map( - ({ code, severity, message, hint, span }): RowFinding => ({ + ({ code, severity, message, hint, span }): TableFinding => ({ code, severity, message, @@ -455,7 +459,7 @@ function tableRowFindings(key: string, decl: TableDecl, text: string | undefined }) ) const refused = refusedTableRows(decl, parsed.data).map( - ({ row, errors }): RowFinding => ({ + ({ row, errors }): TableFinding => ({ code: 'E_TABLE_ROWS', severity: 'error', message: `Line ${parsed.lines[row] ?? 1} does not fit the declared columns: ${errors.join('; ')}.`, @@ -823,6 +827,39 @@ export async function readWorkspaceDir( return { kinds, files, blobs, ignored, unnamed, hashed, ...(base ? { base } : {}) } } +/** Whether the JSON `body` of an apply or status is within what the server reads of one. */ +export function requestFits(body: unknown): boolean { + return utf8ByteLength(JSON.stringify(body)) <= WORKSPACE_SOURCE_REQUEST_MAX_BYTES +} + +/** + * Refuses (exit 7) an apply or status whose JSON `body` is over what the server reads of one, + * before it is sent: the server would answer only that the body is too large. Names the bytes + * each folder carries, largest first, and the `--only` split that sends them in turn. + */ +export function assertRequestFits(body: { files: Readonly> }): void { + const bytes = utf8ByteLength(JSON.stringify(body)) + if (bytes <= WORKSPACE_SOURCE_REQUEST_MAX_BYTES) return + const byFolder = new Map() + for (const [path, text] of Object.entries(body.files)) { + const kind = kindOfPath(path) + if (kind === null) continue + const folder = KIND_DIRS[kind] + byFolder.set(folder, (byFolder.get(folder) ?? 0) + utf8ByteLength(JSON.stringify(text))) + } + const folders = [...byFolder].sort(([, a], [, b]) => b - a) + const carried = folders.map(([folder, size]) => `${folder} ${size}`).join(', ') + const [largest, ...rest] = folders.map(([folder]) => folder) + const split = + largest !== undefined && rest.length > 0 + ? ` Send part of it at a time with --only: for example \`--only ${largest}\`, then \`--only ${rest.join(',')}\`.` + : '' + throw new SourceDirError( + `The request would carry ${bytes} bytes, over the ${WORKSPACE_SOURCE_REQUEST_MAX_BYTES}-byte limit; nothing was sent. Bytes by folder: ${carried}.${split}`, + { code: 'SOURCE_TOO_LARGE', exitCode: SOURCE_TOO_LARGE_EXIT_CODE } + ) +} + /** `.sim/skipped.json`, or `null` when nothing was skipped. */ export function skippedFile(skipped: readonly unknown[]): string | null { return skipped.length > 0 ? `${JSON.stringify(skipped, null, 2)}\n` : null diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts index 4f63d65fc96..b353a3cfe89 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts @@ -37,8 +37,11 @@ const RESOURCES_PATH = '/api/v2/workspaces/ws_local/workflows/source/resources' const CATALOG = JSON.parse( readFileSync(join(__dirname, '../../../../workflow-sdk/test/fixtures/catalog.json'), 'utf8') ) -const LEADS = "// @sim-sdk 1\nexport default defineTable({ name: 'leads', columns: {} })\n" -const ACCOUNTS = "// @sim-sdk 1\nexport default defineTable({ name: 'accounts', columns: {} })\n" +/** A table declaration as a get prints it. */ +const table = (name: string) => + `// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\nexport default defineTable({ name: '${name}', columns: { email: column.string() } })\n` +const LEADS = table('leads') +const ACCOUNTS = table('accounts') let rootDir: string let dir: string @@ -1225,10 +1228,7 @@ describe('the type check of workspaces source check', () => { ) await get() expect(existsSync(join(dir, '.sim/sdk/workspace.d.ts'))).toBe(true) - writeFileSync( - join(dir, 'tables/daily_totals.ts'), - "// @sim-sdk 1\nimport { defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({ name: 'daily_totals', columns: {} })\n" - ) + writeFileSync(join(dir, 'tables/daily_totals.ts'), table('daily_totals')) writeInserting('daily_totals') await runWorkspaceSource('check', dir) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts index 3b14878c17f..fcec388ecb0 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts @@ -481,6 +481,35 @@ describe('workspaces source status', () => { expect(mockRequest.mock.calls[0][1].query).toBeUndefined() }) + it('sends an unchanged workflow folder by its base when the whole directory is over the body cap', async () => { + // Each control character is six bytes once JSON-escaped: the workflow alone fits one apply's + // workflow budget and the rows alone fit the body, but not both. + const workflow = `${INGEST}// ${'\u0001'.repeat(7_000_000)}\n` + const files: Record = { + ...GOT, + 'workflows/ingest/workflow.ts': workflow, + 'tables/leads.rows.jsonl': '\u0001'.repeat(3_000_000), + } + for (const [path, text] of Object.entries(files)) write(path, text) + write( + '.sim/written.json', + JSON.stringify({ + version: 1, + files: Object.fromEntries( + Object.entries(files).map(([path, text]) => [path, digest(text)]) + ), + }) + ) + mockRequest.mockResolvedValue(dry()) + + await run('status') + + const sent = sentFiles()[0] + expect(sent['workflows/ingest/workflow.ts']).toBeUndefined() + expect(sent['workflows/ingest/.sim/base.json']).toBe(INGEST_BASE) + expect(sent['tables/leads.rows.jsonl']).toBe(files['tables/leads.rows.jsonl']) + }) + it('past one dry run, sends an unchanged workflow folder by its base and an edited one whole', async () => { const files: Record = { ...GOT } for (let index = 0; index < 100; index++) { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts index c349732f218..535bce8b8ca 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -72,10 +72,12 @@ import { import { withSourceExitCode } from './source-tree' import { type Diagnostic, shellWord, summaryFileOption } from './source-ui' import { + assertRequestFits, assertWorkspaceDir, ONLY_KINDS_HELP, parseKinds, readWorkspaceDir, + requestFits, type WorkspaceSubmission, withUnchangedWorkflowsPruned, } from './workspace-source-dir' @@ -295,16 +297,18 @@ function planLine(plan: WorkspacePlanSummary): string { /** * Whether one dry run can compare every workflow folder whole: within the workflows and bytes - * one apply evaluates. Past either, the status sends unchanged folders by their base, as an apply - * does, and says their server edits went unchecked. + * one apply evaluates, and with every other folder in a body the server reads whole. Past any, + * the status sends unchanged folders by their base, as an apply does, and says their server + * edits went unchecked. */ -function fitsWhole(files: Readonly>): boolean { - const paths = Object.keys(files).filter((path) => kindOfPath(path) === 'workflow') +function fitsWhole(body: PlanWorkspaceSourceBody): boolean { + const paths = Object.keys(body.files).filter((path) => kindOfPath(path) === 'workflow') const folders = KIND_LAYOUTS.workflow.group(paths).groups.size - const bytes = paths.reduce((sum, path) => sum + utf8ByteLength(files[path]), 0) + const bytes = paths.reduce((sum, path) => sum + utf8ByteLength(body.files[path]), 0) return ( folders <= WORKSPACE_SOURCE_LIMITS.maxWorkflows && - bytes <= WORKSPACE_SOURCE_LIMITS.maxWorkflowBytes + bytes <= WORKSPACE_SOURCE_LIMITS.maxWorkflowBytes && + requestFits(body) ) } @@ -387,17 +391,18 @@ export function attachWorkspaceSourceStatus(source: Command): void { if (local.readFrom === null && profile.sources.workspaceId === 'flag') { workspaceScope = ` --workspace ${target}` } - let submission = local.submission - if (!fitsWhole(submission.files)) { - submission = withUnchangedWorkflowsPruned(submission, local.written, target) - note = `More workflow folders than one dry run compares: an unchanged folder's server edits are not checked (\`${PREFIX} get\` shows them).` - } - const body: PlanWorkspaceSourceBody = { + const planBody = (submission: WorkspaceSubmission): PlanWorkspaceSourceBody => ({ files: submission.files, kinds: submission.kinds, blobs: submission.blobs, ...(submission.base ? { base: submission.base } : {}), options: { allowDelete: true, ...(only ? { only } : {}) }, + }) + let body = planBody(local.submission) + if (!fitsWhole(body)) { + body = planBody(withUnchangedWorkflowsPruned(local.submission, local.written, target)) + assertRequestFits(body) + note = `More workflow folders than one dry run compares: an unchanged folder's server edits are not checked (\`${PREFIX} get\` shows them).` } try { const response = await connection.client.request( diff --git a/packages/workspace-code/src/kinds/registry.ts b/packages/workspace-code/src/kinds/registry.ts index 6b866e6305c..6b709d809a4 100644 --- a/packages/workspace-code/src/kinds/registry.ts +++ b/packages/workspace-code/src/kinds/registry.ts @@ -4,11 +4,19 @@ * The table kind's content rules depend on the server's column-type catalog, so this registry * holds layouts; the server's kind adapters hold the full codecs. */ -import type { FileKind, KindCodec, KindLayout, WorkspaceKind } from '../kind' +import { + type FileKind, + isFileKind, + KIND_DIRS, + type KindCodec, + type KindLayout, + type WorkspaceKind, +} from '../kind' import { kindOfPath } from '../layout' import { WORKSPACE_KIND_SPECS } from '../specs' import { credentialCodec } from './credentials' import { deploymentCodec } from './deployment' +import { fileKindGroupKey } from './entries' import { fileCodec } from './files' import { knowledgeCodec } from './knowledge' import { mcpCodec } from './mcp' @@ -41,11 +49,8 @@ export const BLOB_KIND_CODECS = { file: fileCodec, } as const satisfies { readonly [K in WorkspaceKind]?: KindCodec } -/** - * The codec of each kind one root file declares whole, for a client that reads the keys the file - * declares (to type them in `workspace.d.ts`). Neither needs a catalog. - */ -export const FILE_KIND_CODECS = { +/** The codec of each kind one root file declares whole, which {@link declaredKeys} reads. */ +const FILE_KIND_CODECS = { secret: secretCodec, credential: credentialCodec, } as const satisfies { readonly [K in FileKind]: KindCodec } @@ -71,3 +76,24 @@ export function isBlobPath(path: string): boolean { export function isResourceKeyed(kind: WorkspaceKind): boolean { return WORKSPACE_KIND_SPECS[kind].resourceKind !== null } + +/** + * The keys `files` (path → text) declare for `kind`: the resources its folder's `paths` group into + * (every path of `files` unless given, so a caller can count blob paths it holds no text for), or + * the entries of its root file. `null` for a root file that is absent or does not read, whose keys + * are unknown. + */ +export function declaredKeys( + kind: WorkspaceKind, + files: Readonly>, + paths: readonly string[] = Object.keys(files) +): string[] | null { + if (!isFileKind(kind)) { + const own = paths.filter((path) => kindOfPath(path) === kind) + return [...KIND_LAYOUTS[kind].group(own).groups.keys()] + } + const file = KIND_DIRS[kind] + if (!Object.hasOwn(files, file)) return null + const read = FILE_KIND_CODECS[kind].parse(fileKindGroupKey(kind), { [file]: files[file] }, []) + return read.decl ? Object.keys(read.decl) : null +} diff --git a/packages/workspace-code/src/limits.ts b/packages/workspace-code/src/limits.ts index c15fd771fad..60e1866796d 100644 --- a/packages/workspace-code/src/limits.ts +++ b/packages/workspace-code/src/limits.ts @@ -52,9 +52,11 @@ export const WORKSPACE_SOURCE_LIMITS = { } as const /** - * Body cap for a workspace source apply: declarations, table rows and workflow files doubled for - * JSON string escaping, plus room for the base and the blob manifest (blob bytes are staged - * beforehand). + * Body cap for a workspace source apply or plan: declarations, table rows and workflow files + * doubled for JSON string escaping, plus room for the base and the blob manifest (blob bytes are + * staged beforehand). Both routes are left out of the `apps/sim/proxy.ts` matcher, so this cap, + * not {@link SOURCE_REQUEST_BODY_CEILING_BYTES}, is the one in force; the CLI refuses a larger body + * before sending it. */ export const WORKSPACE_SOURCE_REQUEST_MAX_BYTES = 2 * diff --git a/packages/workspace-code/src/promote.ts b/packages/workspace-code/src/promote.ts index f4f36f77b5c..abb358883b5 100644 --- a/packages/workspace-code/src/promote.ts +++ b/packages/workspace-code/src/promote.ts @@ -26,9 +26,8 @@ import { resourceAddress, type WorkspaceBaseV1, } from './base' -import { isFileKind, KIND_DIRS, type WorkspaceKind } from './kind' -import { fileKindGroupKey } from './kinds/entries' -import { FILE_KIND_CODECS, KIND_LAYOUTS } from './kinds/registry' +import type { WorkspaceKind } from './kind' +import { declaredKeys, KIND_LAYOUTS } from './kinds/registry' import { workflowFolder } from './kinds/workflow' import { kindOfPath } from './layout' @@ -82,24 +81,6 @@ function isWorkflowRecord(path: string): boolean { return relative === SOURCE_LOCK_FILE || relative === SOURCE_BASE_FILE } -/** The keys the directory declares for `kind`, from its paths or its root file. */ -function declaredKeys( - kind: WorkspaceKind, - files: Readonly>, - paths: readonly string[] -): Set { - if (!isFileKind(kind)) { - return new Set( - KIND_LAYOUTS[kind].group(paths.filter((path) => kindOfPath(path) === kind)).groups.keys() - ) - } - const file = KIND_DIRS[kind] - const text = files[file] - if (text === undefined) return new Set() - const read = FILE_KIND_CODECS[kind].parse(fileKindGroupKey(kind), { [file]: text }, []) - return new Set(read.decl ? Object.keys(read.decl) : []) -} - /** * `.sim/targets/.json`: what one target workspace held after the last promotion from * this directory, so the next promotion compares with it rather than with the target as it is @@ -225,7 +206,7 @@ export function promotionSubmission(input: PromotionInput): PromotionSubmission } const paths = [...Object.keys(files), ...input.blobPaths] const declared = new Map( - input.kinds.map((kind) => [kind, declaredKeys(kind, files, paths)] as const) + input.kinds.map((kind) => [kind, new Set(declaredKeys(kind, files, paths))] as const) ) for (const key of declared.get('workflow') ?? []) { const folder = workflowFolder(key) From a471ce312ca3ba256a613a138774425ab5cf15b2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:09:18 -0800 Subject: [PATCH 2/2] fix(workspace-source): reserve body room before reading, check size before staging --- .../[workspaceId]/source/plan/route.test.ts | 50 +++++ .../[workspaceId]/source/plan/route.ts | 3 +- .../workspaces/[workspaceId]/source/route.ts | 8 +- .../lib/api/server/routes/v2-json-route.ts | 179 ++++++++++-------- apps/sim/lib/workflows/api/index.ts | 7 +- apps/sim/lib/workflows/api/source-slots.ts | 64 ++++++- .../protocol/workspace-source-apply.test.ts | 34 ++-- .../protocol/workspace-source-apply.ts | 138 +++++++------- .../protocol/workspace-source-status.test.ts | 8 +- .../protocol/workspace-source-status.ts | 2 +- 10 files changed, 323 insertions(+), 170 deletions(-) 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 eccc8475b2a..886d09a7c3f 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 @@ -118,4 +118,54 @@ describe('POST /api/v2/workspaces/{workspaceId}/source/plan', () => { expect(response.status).toBe(200) expect(mocks.plan.mock.calls[0][0].input.files['tables/leads.rows.jsonl']).toBe(rows) }) + + it('refuses a body unread with 429 once the plans in flight hold as many bodies as their slots, and frees the room of every answered request', async () => { + const result = await mocks.plan() + const finish: Array<() => void> = [] + 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 })) + await vi.waitFor(() => expect(finish).toHaveLength(4)) + + let read = false + const unread = await POST( + new NextRequest(`http://localhost:3000/api/v2/workspaces/${WORKSPACE_ID}/source/plan`, { + method: 'POST', + headers: { 'x-api-key': 'key', 'content-type': 'application/json', 'content-length': '2' }, + body: new ReadableStream( + { + pull(controller) { + read = true + controller.enqueue(new TextEncoder().encode('{}')) + controller.close() + }, + }, + { highWaterMark: 0 } + ), + duplex: 'half', + }), + { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) } + ) + expect(unread.status).toBe(429) + expect(read).toBe(false) + + for (const done of finish) done() + await Promise.all(running) + mocks.plan.mockResolvedValue(result) + // More malformed bodies one after another than the lane holds at once: each frees its room. + for (let attempt = 0; attempt < 5; attempt++) { + const malformed = await 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: '{', + }), + { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) } + ) + expect(malformed.status).toBe(400) + } + 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 32865f1d97b..7d8ea3a6b90 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 @@ -1,7 +1,7 @@ import { WORKSPACE_SOURCE_REQUEST_MAX_BYTES } from '@sim/workspace-code/limits' import { v2PlanWorkspaceSourceContract } from '@/lib/api/contracts/v2/workspace-source' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' -import { withSourceSlot } from '@/lib/workflows/api' +import { reserveWorkspaceSourceBody, withSourceSlot } from '@/lib/workflows/api' import { presentWorkspaceApply, v2WorkspaceSourceErrorPolicy, @@ -28,6 +28,7 @@ export const POST = defineV2JsonRoute({ rateLimit: v2RateLimits.sourcePlan, errorPolicy: v2WorkspaceSourceErrorPolicy, parseOptions: { maxBodyBytes: WORKSPACE_SOURCE_REQUEST_MAX_BYTES, bypassesProxy: true }, + reserveBody: reserveWorkspaceSourceBody('plan'), mapInput: ({ params, body }) => ({ workspaceId: params.workspaceId, files: body.files, 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 76fcb2e0ec2..049d9b7c606 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts @@ -4,7 +4,12 @@ import { v2GetWorkspaceSourceContract, } from '@/lib/api/contracts/v2/workspace-source' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' -import { applyOrDryRunLane, withSourceSlot } from '@/lib/workflows/api' +import { + applyOrDryRunLane, + applyOrDryRunRequestLane, + reserveWorkspaceSourceBody, + withSourceSlot, +} from '@/lib/workflows/api' import { presentWorkspaceApply, v2WorkspaceSourceErrorPolicy, @@ -56,6 +61,7 @@ export const POST = defineV2JsonRoute({ rateLimit: v2RateLimits.sourceApply, errorPolicy: v2WorkspaceSourceErrorPolicy, parseOptions: { maxBodyBytes: WORKSPACE_SOURCE_REQUEST_MAX_BYTES, bypassesProxy: true }, + reserveBody: reserveWorkspaceSourceBody(applyOrDryRunRequestLane), mapInput: ({ params, query, body }) => ({ workspaceId: params.workspaceId, files: body.files, 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 60ba56870a0..749f0bce7aa 100644 --- a/apps/sim/lib/api/server/routes/v2-json-route.ts +++ b/apps/sim/lib/api/server/routes/v2-json-route.ts @@ -610,6 +610,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`. + */ + reserveBody?(request: NextRequest): () => void onSuccess?(args: { principal: Principal input: NoInfer @@ -702,94 +708,107 @@ export function defineV2JsonRoute< } } - const parsed = await parseRequest(options.contract, request, context ?? {}, { - ...V2_PARSE_DEFAULTS, - invalidJsonResponse: () => v2InvalidBodyResponse(request), - ...options.parseOptions, - validationErrorResponseBySlice: v2ValidationError, - }) - if (!parsed.success) return parsed.response - - const credentialFacts: V2CredentialFacts = { - keyType: auth.keyType, - keyExpiresAt: auth.keyExpiresAt, + let release: (() => void) | undefined + try { + release = options.reserveBody?.(request) + } catch (error) { + const response = options.errorPolicy.render(error) + if (response) return response + throw error } - if (request.method === 'HEAD' && options.headSafe === false) { - let input: I + try { + const parsed = await parseRequest(options.contract, request, context ?? {}, { + ...V2_PARSE_DEFAULTS, + invalidJsonResponse: () => v2InvalidBodyResponse(request), + ...options.parseOptions, + validationErrorResponseBySlice: v2ValidationError, + }) + if (!parsed.success) return parsed.response + + const credentialFacts: V2CredentialFacts = { + keyType: auth.keyType, + keyExpiresAt: auth.keyExpiresAt, + } + + if (request.method === 'HEAD' && options.headSafe === false) { + let input: I + try { + input = options.mapInput(parsed.data, credentialFacts) + } catch (error) { + const response = options.errorPolicy.render(error) + if (response) return response + throw error + } + return v2HeadAuthorizationResponse({ + useCase: options.useCase, + principal: auth.principal, + input, + request, + errorPolicy: options.errorPolicy, + }) + } + try { - input = options.mapInput(parsed.data, credentialFacts) + const input = options.mapInput(parsed.data, credentialFacts) + // A Mothership request is admitted without a rate limit, so it is charged nothing more. + if (options.rateLimitCost && 'rateLimitSubjectIds' in auth) { + const cost = Math.min( + options.rateLimitCost(input), + options.rateLimit.maxCost ?? Number.POSITIVE_INFINITY + ) + const limited = + cost > 1 + ? await options.rateLimit.enforce(request, auth, options.operation, cost - 1) + : null + if (limited) return limited + } + const result = await options.useCase.execute({ + principal: auth.principal, + input, + request, + }) + const entityTag = options.entityTag ? `"${options.entityTag(result)}"` : undefined + if (entityTag && entityTagMatches(request, entityTag)) { + await options.onSuccess?.({ principal: auth.principal, input, result }) + return notModifiedResponse(entityTag) + } + const responseSchema = options.contract.response + if (responseSchema.mode !== 'json') { + throw new Error('V2 JSON route response mode changed after initialization') + } + const cacheKey = entityTag ? `${entityTag} ${JSON.stringify(parsed.data)}` : undefined + const cached = cacheKey ? validatedByTag?.get(cacheKey) : undefined + const validatedBody: unknown = + cached ?? responseSchema.schema.parse(await options.present(result, parsed.data)) + if ( + cacheKey && + cached === undefined && + validatedBody !== undefined && + validatedBody !== null + ) { + validatedByTag?.set(cacheKey, validatedBody) + } + const responseStatus = options.statusForResult?.(result) ?? successStatus + if (!successStatuses.includes(responseStatus)) { + throw new Error( + `V2 JSON route produced undeclared success status ${responseStatus}; expected ${successStatuses.join(', ')}` + ) + } + await options.onSuccess?.({ principal: auth.principal, input, result }) + return NextResponse.json(validatedBody, { + status: responseStatus, + headers: entityTag + ? { 'Cache-Control': REVALIDATE_CACHE_CONTROL, ETag: entityTag } + : { 'Cache-Control': 'private, no-store' }, + }) } catch (error) { const response = options.errorPolicy.render(error) if (response) return response throw error } - return v2HeadAuthorizationResponse({ - useCase: options.useCase, - principal: auth.principal, - input, - request, - errorPolicy: options.errorPolicy, - }) - } - - try { - const input = options.mapInput(parsed.data, credentialFacts) - // A Mothership request is admitted without a rate limit, so it is charged nothing more. - if (options.rateLimitCost && 'rateLimitSubjectIds' in auth) { - const cost = Math.min( - options.rateLimitCost(input), - options.rateLimit.maxCost ?? Number.POSITIVE_INFINITY - ) - const limited = - cost > 1 - ? await options.rateLimit.enforce(request, auth, options.operation, cost - 1) - : null - if (limited) return limited - } - const result = await options.useCase.execute({ - principal: auth.principal, - input, - request, - }) - const entityTag = options.entityTag ? `"${options.entityTag(result)}"` : undefined - if (entityTag && entityTagMatches(request, entityTag)) { - await options.onSuccess?.({ principal: auth.principal, input, result }) - return notModifiedResponse(entityTag) - } - const responseSchema = options.contract.response - if (responseSchema.mode !== 'json') { - throw new Error('V2 JSON route response mode changed after initialization') - } - const cacheKey = entityTag ? `${entityTag} ${JSON.stringify(parsed.data)}` : undefined - const cached = cacheKey ? validatedByTag?.get(cacheKey) : undefined - const validatedBody: unknown = - cached ?? responseSchema.schema.parse(await options.present(result, parsed.data)) - if ( - cacheKey && - cached === undefined && - validatedBody !== undefined && - validatedBody !== null - ) { - validatedByTag?.set(cacheKey, validatedBody) - } - const responseStatus = options.statusForResult?.(result) ?? successStatus - if (!successStatuses.includes(responseStatus)) { - throw new Error( - `V2 JSON route produced undeclared success status ${responseStatus}; expected ${successStatuses.join(', ')}` - ) - } - await options.onSuccess?.({ principal: auth.principal, input, result }) - return NextResponse.json(validatedBody, { - status: responseStatus, - headers: entityTag - ? { 'Cache-Control': REVALIDATE_CACHE_CONTROL, ETag: entityTag } - : { 'Cache-Control': 'private, no-store' }, - }) - } catch (error) { - const response = options.errorPolicy.render(error) - if (response) return response - throw error + } finally { + release?.() } }, { diff --git a/apps/sim/lib/workflows/api/index.ts b/apps/sim/lib/workflows/api/index.ts index 0ff72cc9f44..e224e3a0773 100644 --- a/apps/sim/lib/workflows/api/index.ts +++ b/apps/sim/lib/workflows/api/index.ts @@ -11,7 +11,12 @@ export { presentV2RunError } from '@/lib/workflows/api/run-error' export { presentV2RunPause } from '@/lib/workflows/api/run-pause' export { withBoundSourceFindings } from '@/lib/workflows/api/source-findings' export { presentSourceOutcome } from '@/lib/workflows/api/source-presenters' -export { applyOrDryRunLane, withSourceSlot } from '@/lib/workflows/api/source-slots' +export { + applyOrDryRunLane, + applyOrDryRunRequestLane, + reserveWorkspaceSourceBody, + withSourceSlot, +} from '@/lib/workflows/api/source-slots' export { presentV2WorkflowTrigger, presentV2WorkspaceSchedule, diff --git a/apps/sim/lib/workflows/api/source-slots.ts b/apps/sim/lib/workflows/api/source-slots.ts index 865b57c3023..0bd04b8caf6 100644 --- a/apps/sim/lib/workflows/api/source-slots.ts +++ b/apps/sim/lib/workflows/api/source-slots.ts @@ -1,4 +1,6 @@ -import type { NextResponse } from 'next/server' +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 { ApplicationOperation, AuthorizingUseCase } from '@/lib/core/application' @@ -27,14 +29,62 @@ const SOURCE_BUSY_HEADERS = { 'Retry-After': '5' } /** A source request refused because this process already runs as many as it may. */ class SourceSlotBusyError extends Error { - constructor(readonly lane: SourceLane) { - super( - `This server is already running ${SOURCE_LANES[lane].max} source ${SOURCE_LANES[lane].noun}; retry shortly.` - ) + constructor(message: string) { + super(message) this.name = 'SourceSlotBusyError' } } +/** 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 } + +/** + * 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. + */ +export function reserveWorkspaceSourceBody( + laneOf: SourceLane | ((request: NextRequest) => SourceLane) +): (request: NextRequest) => () => void { + return (request) => { + const lane = typeof laneOf === 'function' ? laneOf(request) : laneOf + const declared = Number(request.headers.get('content-length') ?? Number.NaN) + const bytes = + Number.isSafeInteger(declared) && declared >= 0 + ? Math.min(declared, WORKSPACE_SOURCE_REQUEST_MAX_BYTES) + : WORKSPACE_SOURCE_REQUEST_MAX_BYTES + const budget = SOURCE_LANES[lane].max * WORKSPACE_SOURCE_REQUEST_MAX_BYTES + 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 + let released = false + return () => { + if (released) return + released = true + heldSourceBodyBytes[lane] -= bytes + } + } +} + +/** + * The lane of a request to a source apply route that also serves dry runs, read from its `dry` + * query (or the deprecated `dryRun`) before the request is parsed: {@link applyOrDryRunLane}'s. + */ +export function applyOrDryRunRequestLane(request: NextRequest): SourceLane { + const { searchParams } = request.nextUrl + const dry = booleanQueryFlagSchema.safeParse( + searchParams.get('dry') ?? searchParams.get('dryRun') + ) + return applyOrDryRunLane({ dryRun: dry.data === true }) +} + /** * `useCase`, run in one of its lane's slots (`laneOf`, or the lane it picks for the input): a get, * plan or apply (each holds a workflow's or a directory's worth of text, stored state and @@ -51,7 +101,9 @@ export function withSourceSlot( async execute(args) { const lane = typeof laneOf === 'function' ? laneOf(args.input) : laneOf if (runningSourceRequests[lane] >= SOURCE_LANES[lane].max) { - throw new SourceSlotBusyError(lane) + throw new SourceSlotBusyError( + `This server is already running ${SOURCE_LANES[lane].max} source ${SOURCE_LANES[lane].noun}; retry shortly.` + ) } runningSourceRequests[lane] += 1 try { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index a7d0b88c2a9..ef931ccf38e 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1627,21 +1627,27 @@ describe('workspaces source apply', () => { expect(request).not.toHaveBeenCalled() }) - it('refuses a request over the body cap before sending it, exit 7, naming the bytes by folder and the --only split', async () => { - // Each control character is six bytes once JSON-escaped, so the body passes the cap. - const escapedBytes = Math.ceil(WORKSPACE_SOURCE_REQUEST_MAX_BYTES / 6) + 1 - write('tables/leads.rows.jsonl', '\u0001'.repeat(escapedBytes)) - request.mockResolvedValue(answer()) + it.each([['--dry'], ['--yes']])( + 'with %s, refuses a request over the body cap before sending or staging anything, exit 7, naming the bytes by folder and the --only split', + async (flag) => { + // Each control character is six bytes once JSON-escaped, so the body passes the cap. + const escapedBytes = Math.ceil(WORKSPACE_SOURCE_REQUEST_MAX_BYTES / 6) + 1 + write('tables/leads.rows.jsonl', '\u0001'.repeat(escapedBytes)) + write('files/new.bin', 'new bytes') + request.mockResolvedValue(answer()) - await expect(apply('--dry')).rejects.toMatchObject({ - code: 'SOURCE_TOO_LARGE', - exitCode: 7, - message: expect.stringMatching( - /over the \d+-byte limit; nothing was sent\. Bytes by folder: tables \d+, workflows \d+\. .*`--only tables`, then `--only workflows`/ - ), - }) - expect(request).not.toHaveBeenCalled() - }) + await expect(apply(flag)).rejects.toMatchObject({ + code: 'SOURCE_TOO_LARGE', + exitCode: 7, + message: expect.stringMatching( + /over the \d+-byte limit; nothing was sent\. Bytes by folder: tables \d+, workflows \d+\. .*`--only tables`, then `--only workflows`/ + ), + }) + expect(request).not.toHaveBeenCalled() + expect(staging.asked).toEqual([]) + expect(staging.uploaded).toEqual([]) + } + ) it('refuses a directory listing more binary files than one holds before hashing any, exit 7', async () => { write('files/a.bin', 'a') diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index b9115e5daf0..e6a30e5729d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -765,22 +765,27 @@ export function attachWorkspaceSourceApply(source: Command): void { ) ?? undefined ) const provenance = await gitProvenance(options.dir) + /** The apply request of `submission` (as `kinds` limit it). */ + const applyBody = ( + submission: WorkspaceSubmission, + kinds: readonly WorkspaceKind[] | undefined + ): ApplyWorkspaceSourceBody => ({ + files: submission.files, + kinds: submission.kinds, + blobs: submission.blobs, + ...(submission.base ? { base: submission.base } : {}), + options: { + ...(options.allowDelete ? { allowDelete: true } : {}), + ...(kinds ? { only: [...kinds] } : {}), + }, + provenance: { client: 'cli', ...provenance }, + }) const post = async ( submission: WorkspaceSubmission, dry: boolean, kinds: readonly WorkspaceKind[] | undefined ) => { - const body: ApplyWorkspaceSourceBody = { - files: submission.files, - kinds: submission.kinds, - blobs: submission.blobs, - ...(submission.base ? { base: submission.base } : {}), - options: { - ...(options.allowDelete ? { allowDelete: true } : {}), - ...(kinds ? { only: [...kinds] } : {}), - }, - provenance: { client: 'cli', ...provenance }, - } + const body = applyBody(submission, kinds) assertRequestFits(body) const response = await client.request( 'applyWorkspaceSource', @@ -942,59 +947,64 @@ export function attachWorkspaceSourceApply(source: Command): void { const writeFlow = ( commit: WorkspaceSubmission, held: Written - ): SourceWriteFlow => ({ - mode, - preview: async () => reported(await send(submission, true)), - show: (preview) => { - // A machine result carries the plan, so `2>&1` stays one document; a person asked - // to confirm still reads it. - if (!findings.machine || mode === 'ask') printPlan(preview.plan, preview.diagnostics) - findings.print(preview.diagnostics) - }, - refuses: (preview) => preview.refuses === true, - previewExitCode, - // Without a preview, stage the blobs the base does not hold as they are. - beforeCommit: (preview) => - stage(commit, preview ? new Set(preview.needBlobs) : blobsToStage(commit)), - commit: async () => { - const sent = reported( - await send(commit, false, commit === submission ? only : commit.kinds) - ) - if (commit !== firstWrite) { - // The deployments write: the first write already printed its workflows' findings, - // which mergedApply drops from the result too. - findings.print(sent.diagnostics.filter((finding) => finding.kind !== 'workflow')) - return sent - } - const answer = gated ? withoutDeferredWarnings(sent) : sent - findings.print(answer.diagnostics) - return answer - }, - save: async (answer) => { - // A promotion leaves the directory bound to the workspace it was read from, and - // records what it left in the target for the next promotion to compare with. - if (promotion) { - await savePromotion(options.dir, promotion.target, promotion, answer) - return - } - const workspaceCatalog = cachedCatalog(workspaceId) - const { records, unrecorded } = workspaceCatalog - ? await workflowFolderRecords(client, workspaceId, workspaceCatalog, answer.files) - : { records: [], unrecorded: [] } - await saveApplied(options.dir, answer, commit, held, records) - const unrecordedWarning = unrecordedFoldersWarning(unrecorded) - if (unrecordedWarning) printError(unrecordedWarning) - }, - report, - question: `Apply these changes to workspace ${workspaceId}?`, - command: applyCommand(options, sim), - interrupt: { - verb: 'apply', - dir: options.dir, - noun: 'workspace', - ifAnswerLost: answerLostHint(options.dir, sim), - }, - }) + ): SourceWriteFlow => { + const commitKinds = commit === submission ? only : commit.kinds + return { + mode, + preview: async () => reported(await send(submission, true)), + show: (preview) => { + // A machine result carries the plan, so `2>&1` stays one document; a person asked + // to confirm still reads it. + if (!findings.machine || mode === 'ask') + printPlan(preview.plan, preview.diagnostics) + findings.print(preview.diagnostics) + }, + refuses: (preview) => preview.refuses === true, + previewExitCode, + // Without a preview, stage the blobs the base does not hold as they are; a request too + // large to send stages nothing. + beforeCommit: (preview) => { + assertRequestFits(applyBody(commit, commitKinds)) + return stage(commit, preview ? new Set(preview.needBlobs) : blobsToStage(commit)) + }, + commit: async () => { + const sent = reported(await send(commit, false, commitKinds)) + if (commit !== firstWrite) { + // The deployments write: the first write already printed its workflows' findings, + // which mergedApply drops from the result too. + findings.print(sent.diagnostics.filter((finding) => finding.kind !== 'workflow')) + return sent + } + const answer = gated ? withoutDeferredWarnings(sent) : sent + findings.print(answer.diagnostics) + return answer + }, + save: async (answer) => { + // A promotion leaves the directory bound to the workspace it was read from, and + // records what it left in the target for the next promotion to compare with. + if (promotion) { + await savePromotion(options.dir, promotion.target, promotion, answer) + return + } + const workspaceCatalog = cachedCatalog(workspaceId) + const { records, unrecorded } = workspaceCatalog + ? await workflowFolderRecords(client, workspaceId, workspaceCatalog, answer.files) + : { records: [], unrecorded: [] } + await saveApplied(options.dir, answer, commit, held, records) + const unrecordedWarning = unrecordedFoldersWarning(unrecorded) + if (unrecordedWarning) printError(unrecordedWarning) + }, + report, + question: `Apply these changes to workspace ${workspaceId}?`, + command: applyCommand(options, sim), + interrupt: { + verb: 'apply', + dir: options.dir, + noun: 'workspace', + ifAnswerLost: answerLostHint(options.dir, sim), + }, + } + } /** * Prints how a written apply ended (its plan, what it held back, where it stopped) and * sets its exit status. Returns whether it wrote every change it planned. diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts index fcec388ecb0..de73a97d6b5 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts @@ -550,9 +550,13 @@ describe('workspaces source status', () => { expect(sent['workflows/w7/workflow.ts']).toBe(`${INGEST}// edited\n`) expect(sent['workflows/w8/workflow.ts']).toBeUndefined() expect(sent['workflows/w8/.sim/base.json']).toBe(INGEST_BASE) - expect(printed().note).toContain('More workflow folders than one dry run compares') + expect(printed().note).toContain( + 'More workflow folders or request bytes than one dry run compares' + ) const markdown = readFileSync(summary, 'utf8') - expect(markdown).toContain('The server check was incomplete: More workflow folders') + expect(markdown).toContain( + 'The server check was incomplete: More workflow folders or request bytes' + ) expect(markdown).toContain('- table leads: changed on the server') }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts index 535bce8b8ca..fe6c47a7fed 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -402,7 +402,7 @@ export function attachWorkspaceSourceStatus(source: Command): void { if (!fitsWhole(body)) { body = planBody(withUnchangedWorkflowsPruned(local.submission, local.written, target)) assertRequestFits(body) - note = `More workflow folders than one dry run compares: an unchanged folder's server edits are not checked (\`${PREFIX} get\` shows them).` + note = `More workflow folders or request bytes than one dry run compares: an unchanged folder's server edits are not checked (\`${PREFIX} get\` shows them).` } try { const response = await connection.client.request(