From c473fc2d9b817d463c8a2dea1a03604855b3ff83 Mon Sep 17 00:00:00 2001 From: Rafal Leszko Date: Wed, 21 Oct 2026 10:59:49 +0200 Subject: [PATCH 1/3] feat(serverless): address an environment on invoke and getTask (RUNSERV-1238) An app id now names one copy per environment. The client takes serverlessEnvironment, each call can override it, and unset sends nothing so the platform keeps reading production. Waiting polls in the invocation's environment, since a task carries none of its own. Signed-off-by: Rafal Leszko --- README.md | 14 ++++++ src/client.ts | 7 +++ src/serverless.ts | 38 ++++++++++++++-- src/types/sdk.ts | 6 +++ src/types/serverless.ts | 11 +++++ test/serverless.test.ts | 97 +++++++++++++++++++++++++++++++++++++++++ 6 files changed, 169 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ecb2329..d37a86c 100644 --- a/README.md +++ b/README.md @@ -634,6 +634,20 @@ const task = await client.getTask('image-tools', accepted.id) A task that runs and fails comes back with `status: 'failed'` and its `error` set. Only a failure to start throws. +An app id names one copy of the app per environment. Calls go to `production` unless you name another environment, for the whole client or for one call. Waiting polls the task in the environment it was invoked in; when you call `getTask` yourself, pass that same environment. + +```typescript +const client = await createClient({ apiKey, serverlessEnvironment: 'staging' }) + +const task = await client.invoke({ appId: 'image-tools', endpointPath: 'generate' }) + +const accepted = await client.invoke( + { appId: 'image-tools', endpointPath: 'train', environment: 'dev' }, + { wait: false }, +) +const later = await client.getTask('image-tools', accepted.id, { environment: 'dev' }) +``` + ## Content metadata `client.content.*` exposes Runware's curated model catalog as read-only metadata — names, AIRs, headlines, capabilities, pricing, examples. Public information, no extra cost. diff --git a/src/client.ts b/src/client.ts index 045ca77..6bad830 100644 --- a/src/client.ts +++ b/src/client.ts @@ -190,6 +190,10 @@ export type RunwareClient = { * the same id again returns the task it already names instead of starting a * second, so a call whose response was lost is safe to repeat. * + * `environment` selects which copy of the app to call, falling back to + * `config.serverlessEnvironment` and then to `production`. Waiting polls the + * task in that same environment. + * * Rejects with a `RunwareError` when the task fails to start. A task that * runs and fails comes back with `status: 'failed'` and its `error` set, * because that is an outcome rather than a broken call. @@ -205,6 +209,9 @@ export type RunwareClient = { * `invoke` already waits for you, so reach for this when you want to poll * yourself: after `invoke` with `wait: false`, or from a different process * than the one that submitted the task. + * + * Pass the `environment` the task was invoked in. It falls back to + * `config.serverlessEnvironment` and then to `production`. */ getTask: ( appId: string, diff --git a/src/serverless.ts b/src/serverless.ts index 69f20b3..40ce3d6 100644 --- a/src/serverless.ts +++ b/src/serverless.ts @@ -14,6 +14,7 @@ import { generateUUID } from './utils/uuid' const APP_ID_PATTERN = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/ const ENDPOINT_PATH_PATTERN = /^[a-z]([a-z0-9-]{0,62}[a-z0-9])?$/ +const ENVIRONMENT_PATTERN = /^[a-z0-9][a-z0-9._-]{0,62}$/ const TASK_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ const DEFAULT_POLL_INTERVAL_MS = 2000 @@ -107,6 +108,18 @@ const validateEndpointPath = (endpointPath: unknown): string => { return endpointPath } +const validateEnvironment = (environment: unknown): string | undefined => { + if (environment === undefined || environment === null) { return undefined } + if (typeof environment !== 'string' || !ENVIRONMENT_PATTERN.test(environment)) { + throw createRunwareError( + 'invalidParameter', + `environment "${String(environment)}" is invalid: use 1 to 63 lowercase letters, digits, hyphens, underscores or periods, starting with a letter or digit`, + { parameter: 'environment' }, + ) + } + return environment +} + const validateTaskId = (taskId: unknown): string => { if (typeof taskId !== 'string' || !TASK_ID_PATTERN.test(taskId)) { throw createRunwareError( @@ -212,6 +225,15 @@ type HttpResult = { status: number, body: unknown } const createServerlessApi = (config: SDKConfig) => { const origin = config.serverlessBaseUrl.replace(/\/+$/, '') + /** The per-call environment, else the client's, else none. */ + const resolveEnvironment = (environment: string | undefined): string | undefined => + validateEnvironment(environment ?? config.serverlessEnvironment) + + const appUrl = (appId: string, path: string, environment: string | undefined): string => { + const url = `${origin}/v1/apps/${appId}/${path}` + return environment === undefined ? url : `${url}?environment=${environment}` + } + const fetchOnce = async ( url: string, init: RequestInit, @@ -320,8 +342,9 @@ const createServerlessApi = (config: SDKConfig) => { ): Promise => { const app = validateAppId(appId) const id = validateTaskId(taskId) + const environment = resolveEnvironment(options?.environment) const result = await request( - `${origin}/v1/apps/${app}/tasks/${id}`, + appUrl(app, `tasks/${id}`, environment), { method: 'GET' }, options?.timeout ?? config.timeout, options?.signal, @@ -332,9 +355,13 @@ const createServerlessApi = (config: SDKConfig) => { /** * Polls until the task reaches a terminal state. Never resubmits: the task * is already running, and a second invocation would be a second charge. + * + * Polls in the environment the task was invoked in. A task carries no + * environment of its own, and a poll without one would read production. */ const waitForTask = async ( task: ServerlessTask, + environment: string | undefined, options: InvokeOptions | undefined, startedAt: number, ): Promise => { @@ -347,9 +374,10 @@ const createServerlessApi = (config: SDKConfig) => { while (!isTerminal(current.status)) { if (Date.now() - startedAt > budget) { + const environmentArg = environment === undefined ? '' : `, { environment: "${environment}" }` throw createRunwareError( 'timeout', - `Task ${current.id} is still running after ${budget}ms. It was not cancelled: poll getTask("${current.appId}", "${current.id}") to pick it up.`, + `Task ${current.id} is still running after ${budget}ms. It was not cancelled: poll getTask("${current.appId}", "${current.id}"${environmentArg}) to pick it up.`, { taskUUID: current.id }, ) } @@ -358,6 +386,7 @@ const createServerlessApi = (config: SDKConfig) => { try { current = await getTask(current.appId, current.id, { + ...(environment !== undefined ? { environment } : {}), ...(options?.timeout !== undefined ? { timeout: options.timeout } : {}), ...(options?.signal ? { signal: options.signal } : {}), }) @@ -382,6 +411,7 @@ const createServerlessApi = (config: SDKConfig) => { const appId = validateAppId(params.appId) const endpointPath = validateEndpointPath(params.endpointPath) const taskId = resolveTaskId(params.taskId) + const environment = resolveEnvironment(params.environment) const wait = options?.wait !== false const deliveryMethod = wait ? (options?.deliveryMethod ?? 'async') : 'async' const route = deliveryMethod === 'sync' ? 'invoke-sync' : 'invoke-async' @@ -396,7 +426,7 @@ const createServerlessApi = (config: SDKConfig) => { const startedAt = Date.now() const result = await request( - `${origin}/v1/apps/${appId}/${route}/${endpointPath}`, + appUrl(appId, `${route}/${endpointPath}`, environment), { method: 'POST', body }, timeoutMs, options?.signal, @@ -408,7 +438,7 @@ const createServerlessApi = (config: SDKConfig) => { return task } - return waitForTask(task, options, startedAt) + return waitForTask(task, environment, options, startedAt) } return { invoke, getTask } diff --git a/src/types/sdk.ts b/src/types/sdk.ts index 01ffb50..92dd864 100644 --- a/src/types/sdk.ts +++ b/src/types/sdk.ts @@ -24,6 +24,12 @@ export type SDKConfig = { * `https://api.serverless.runware.ai`. Used by `invoke` and `getTask`. */ serverlessBaseUrl: string + /** + * Serverless environment `invoke` and `getTask` address, such as `staging`. + * An app id names one copy per environment. Unset sends no environment, + * which the platform reads as `production`. Optional. + */ + serverlessEnvironment?: string /** Transport to use. Default: `websocket`. */ transport: TransportType /** diff --git a/src/types/serverless.ts b/src/types/serverless.ts index f9a7976..a9e5204 100644 --- a/src/types/serverless.ts +++ b/src/types/serverless.ts @@ -62,6 +62,12 @@ export type InvokeParams = { * retry from a different process land on the same task. */ taskId?: string + /** + * Environment of the app copy to invoke. Falls back to + * `config.serverlessEnvironment`, then to `production`. Waiting polls the + * task in this same environment. + */ + environment?: string } export type InvokeOptions = { @@ -100,6 +106,11 @@ export type InvokeOptions = { } export type GetTaskOptions = { + /** + * Environment the task was invoked in. Falls back to + * `config.serverlessEnvironment`, then to `production`. + */ + environment?: string /** Per-request timeout in ms. Falls back to `config.timeout`. */ timeout?: number signal?: AbortSignal diff --git a/test/serverless.test.ts b/test/serverless.test.ts index 97f0e97..d43cba7 100644 --- a/test/serverless.test.ts +++ b/test/serverless.test.ts @@ -473,3 +473,100 @@ describe('getTask', () => { expect(calls).toHaveLength(0) }) }) + +describe('environment', () => { + const ASYNC_URL = 'https://serverless.test.com/v1/apps/my-app/invoke-async/generate' + const TASK_ID = '7c9e6679-7425-40de-944b-e07fc1f90ae7' + const TASK_URL = `https://serverless.test.com/v1/apps/my-app/tasks/${TASK_ID}` + const pending = () => task({ status: 'pending', output: null, completedAt: null }) + const ok = (): Reply => ({ status: 200, body: task() }) + + it('sends no environment when none is set', async () => { + const { impl, calls } = mockFetch([ok(), ok()]) + const api = createServerlessApi(config(impl)) + + await api.invoke({ appId: 'my-app', endpointPath: 'generate' }) + await api.getTask('my-app', TASK_ID) + + expect(calls.map((call) => call.url)).toEqual([ASYNC_URL, TASK_URL]) + }) + + it('addresses the client environment', async () => { + const { impl, calls } = mockFetch([ok(), ok()]) + const api = createServerlessApi(config(impl, { serverlessEnvironment: 'staging' })) + + await api.invoke({ appId: 'my-app', endpointPath: 'generate' }) + await api.getTask('my-app', TASK_ID) + + expect(calls.map((call) => call.url)).toEqual([ + `${ASYNC_URL}?environment=staging`, `${TASK_URL}?environment=staging`, + ]) + }) + + it('lets a per-call environment override the client one', async () => { + const { impl, calls } = mockFetch([ok(), ok()]) + const api = createServerlessApi(config(impl, { serverlessEnvironment: 'production' })) + + await api.invoke({ appId: 'my-app', endpointPath: 'generate', environment: 'staging' }) + await api.getTask('my-app', TASK_ID, { environment: 'staging' }) + + expect(calls.map((call) => call.url)).toEqual([ + `${ASYNC_URL}?environment=staging`, `${TASK_URL}?environment=staging`, + ]) + }) + + it('polls in the environment the task was invoked in', async () => { + const { impl, calls } = mockFetch([ + { status: 202, body: pending() }, { status: 200, body: pending() }, ok(), + ]) + const api = createServerlessApi(config(impl)) + + const result = await api.invoke( + { appId: 'my-app', endpointPath: 'generate', environment: 'staging' }, + { pollInterval: 0 }, + ) + + expect(result.status).toBe('completed') + expect(calls.slice(1).map((call) => call.url)).toEqual([ + `${TASK_URL}?environment=staging`, `${TASK_URL}?environment=staging`, + ]) + }) + + it('names the environment when the poll budget runs out', async () => { + const { impl } = mockFetch(Array.from({ length: 40 }, () => ({ status: 200, body: pending() }))) + const api = createServerlessApi(config(impl, { pollTimeout: 0 })) + + await expect(api.invoke( + { appId: 'my-app', endpointPath: 'generate', environment: 'staging' }, + { pollInterval: 0 }, + )).rejects.toThrow('{ environment: "staging" }) to pick it up') + }) + + const impossible = [ + '', + 'Staging', + '-dev', + 'a/b', + 'a'.repeat(64), + ] + for (const environment of impossible) { + it(`rejects the environment ${JSON.stringify(environment)} before asking the API`, async () => { + const { impl, calls } = mockFetch([]) + const api = createServerlessApi(config(impl)) + + const error = await api.invoke({ appId: 'my-app', endpointPath: 'generate', environment }) + .catch((caught: unknown) => caught) + + expect(isRunwareError(error) && error.parameter).toBe('environment') + expect(calls).toHaveLength(0) + }) + } + + it('rejects an invalid client environment before asking the API', async () => { + const { impl, calls } = mockFetch([]) + const api = createServerlessApi(config(impl, { serverlessEnvironment: 'Staging' })) + + await expect(api.getTask('my-app', TASK_ID)).rejects.toThrow('environment "Staging" is invalid') + expect(calls).toHaveLength(0) + }) +}) From df51b473dacaf59f0848ae24d55e4505ff177959 Mon Sep 17 00:00:00 2001 From: Rafal Leszko Date: Wed, 21 Oct 2026 11:13:43 +0200 Subject: [PATCH 2/3] fix(serverless): check the client environment when built (RUNSERV-1238) Review follow-ups: an invalid serverlessEnvironment now fails in createClient and names the config field, and the query value is encoded. Tests cover the name boundaries, null from untyped JS, the hint without an environment and the smoke test's optional RUNWARE_SERVERLESS_TEST_ENVIRONMENT. Signed-off-by: Rafal Leszko --- src/serverless.ts | 9 +++--- src/types/sdk.ts | 4 +-- test/integration/smoke.test.ts | 3 ++ test/serverless.test.ts | 53 ++++++++++++++++++++++++++++++---- 4 files changed, 58 insertions(+), 11 deletions(-) diff --git a/src/serverless.ts b/src/serverless.ts index 40ce3d6..f823b65 100644 --- a/src/serverless.ts +++ b/src/serverless.ts @@ -108,13 +108,13 @@ const validateEndpointPath = (endpointPath: unknown): string => { return endpointPath } -const validateEnvironment = (environment: unknown): string | undefined => { +const validateEnvironment = (environment: unknown, parameter = 'environment'): string | undefined => { if (environment === undefined || environment === null) { return undefined } if (typeof environment !== 'string' || !ENVIRONMENT_PATTERN.test(environment)) { throw createRunwareError( 'invalidParameter', - `environment "${String(environment)}" is invalid: use 1 to 63 lowercase letters, digits, hyphens, underscores or periods, starting with a letter or digit`, - { parameter: 'environment' }, + `${parameter} "${String(environment)}" is invalid: use 1 to 63 lowercase letters, digits, hyphens, underscores or periods, starting with a letter or digit`, + { parameter }, ) } return environment @@ -224,6 +224,7 @@ type HttpResult = { status: number, body: unknown } const createServerlessApi = (config: SDKConfig) => { const origin = config.serverlessBaseUrl.replace(/\/+$/, '') + validateEnvironment(config.serverlessEnvironment, 'serverlessEnvironment') /** The per-call environment, else the client's, else none. */ const resolveEnvironment = (environment: string | undefined): string | undefined => @@ -231,7 +232,7 @@ const createServerlessApi = (config: SDKConfig) => { const appUrl = (appId: string, path: string, environment: string | undefined): string => { const url = `${origin}/v1/apps/${appId}/${path}` - return environment === undefined ? url : `${url}?environment=${environment}` + return environment === undefined ? url : `${url}?environment=${encodeURIComponent(environment)}` } const fetchOnce = async ( diff --git a/src/types/sdk.ts b/src/types/sdk.ts index 92dd864..a5b5f3e 100644 --- a/src/types/sdk.ts +++ b/src/types/sdk.ts @@ -26,8 +26,8 @@ export type SDKConfig = { serverlessBaseUrl: string /** * Serverless environment `invoke` and `getTask` address, such as `staging`. - * An app id names one copy per environment. Unset sends no environment, - * which the platform reads as `production`. Optional. + * An app id names one copy per environment. Default: unset, which sends no + * environment and the platform reads as `production`. */ serverlessEnvironment?: string /** Transport to use. Default: `websocket`. */ diff --git a/test/integration/smoke.test.ts b/test/integration/smoke.test.ts index 8a56639..d8b5430 100644 --- a/test/integration/smoke.test.ts +++ b/test/integration/smoke.test.ts @@ -29,6 +29,8 @@ const describeIf = apiKey ? describe : describe.skip const serverlessBaseUrl = process.env.RUNWARE_SERVERLESS_BASE_URL const serverlessApp = process.env.RUNWARE_SERVERLESS_TEST_APP const serverlessEndpoint = process.env.RUNWARE_SERVERLESS_TEST_ENDPOINT +// Optional: the environment of the app copy to call. Unset means production. +const serverlessEnvironment = process.env.RUNWARE_SERVERLESS_TEST_ENVIRONMENT || undefined const serverlessPayload = JSON.parse(process.env.RUNWARE_SERVERLESS_TEST_PAYLOAD ?? '{}') as Record const describeServerless = (apiKey && serverlessBaseUrl && serverlessApp && serverlessEndpoint) ? describe @@ -38,6 +40,7 @@ const serverlessClient = async () => createClient({ apiKey: apiKey!, transport: 'rest', serverlessBaseUrl: serverlessBaseUrl!, + ...(serverlessEnvironment ? { serverlessEnvironment } : {}), }) const IMAGE_MODEL = 'runware:400@2' // Flux 2 Klein 9b — cheap and fast diff --git a/test/serverless.test.ts b/test/serverless.test.ts index d43cba7..d170d1b 100644 --- a/test/serverless.test.ts +++ b/test/serverless.test.ts @@ -546,7 +546,10 @@ describe('environment', () => { '', 'Staging', '-dev', + '.dev', + '_dev', 'a/b', + 'staging\n', 'a'.repeat(64), ] for (const environment of impossible) { @@ -562,11 +565,51 @@ describe('environment', () => { }) } - it('rejects an invalid client environment before asking the API', async () => { - const { impl, calls } = mockFetch([]) - const api = createServerlessApi(config(impl, { serverlessEnvironment: 'Staging' })) + const allowed = [ + 'pr-12', + 'feature_x', + 'v1.2', + '1st', + 'a'.repeat(63), + ] + for (const environment of allowed) { + it(`accepts the environment ${JSON.stringify(environment)}`, async () => { + const { impl, calls } = mockFetch([ok()]) + const api = createServerlessApi(config(impl)) - await expect(api.getTask('my-app', TASK_ID)).rejects.toThrow('environment "Staging" is invalid') - expect(calls).toHaveLength(0) + await api.invoke({ appId: 'my-app', endpointPath: 'generate', environment }) + + expect(calls[0]!.url).toBe(`${ASYNC_URL}?environment=${environment}`) + }) + } + + it('rejects an invalid client environment when the client is built', () => { + const { impl } = mockFetch([]) + + let error: unknown + try { createServerlessApi(config(impl, { serverlessEnvironment: 'Staging' })) } catch (caught) { error = caught } + + expect(isRunwareError(error) && error.parameter).toBe('serverlessEnvironment') + expect(String(error)).toContain('serverlessEnvironment "Staging" is invalid') + }) + + it('treats a null client environment from untyped JS as unset', async () => { + const { impl, calls } = mockFetch([ok()]) + const unset = null as unknown as string + const api = createServerlessApi(config(impl, { serverlessEnvironment: unset })) + + await api.invoke({ appId: 'my-app', endpointPath: 'generate' }) + + expect(calls[0]!.url).toBe(ASYNC_URL) + }) + + it('names no environment in the hint when none is set', async () => { + const { impl } = mockFetch(Array.from({ length: 40 }, () => ({ status: 200, body: pending() }))) + const api = createServerlessApi(config(impl, { pollTimeout: 0 })) + + await expect(api.invoke( + { appId: 'my-app', endpointPath: 'generate' }, + { pollInterval: 0 }, + )).rejects.toThrow(`getTask("my-app", "${TASK_ID}") to pick it up`) }) }) From e6c94a427865b3d53d3ef70e2ad5d6783247732e Mon Sep 17 00:00:00 2001 From: Rafal Leszko Date: Wed, 21 Oct 2026 13:29:22 +0200 Subject: [PATCH 3/3] feat(serverless): stop retrying an environment paused at its budget (RUNSERV-1238) A paused environment answers invoke with a 429 that holds until the budget is raised or the UTC month turns, so retrying it, or sleeping on its Retry-After, only delays the error. It now rejects with a quota error at once; any other 429 is still retried. Signed-off-by: Rafal Leszko --- README.md | 2 +- src/errors.ts | 2 +- src/serverless.ts | 11 +++++++++-- test/serverless.test.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 52 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d37a86c..97eb431 100644 --- a/README.md +++ b/README.md @@ -634,7 +634,7 @@ const task = await client.getTask('image-tools', accepted.id) A task that runs and fails comes back with `status: 'failed'` and its `error` set. Only a failure to start throws. -An app id names one copy of the app per environment. Calls go to `production` unless you name another environment, for the whole client or for one call. Waiting polls the task in the environment it was invoked in; when you call `getTask` yourself, pass that same environment. +An app id names one copy of the app per environment. Calls go to `production` unless you name another environment, for the whole client or for one call. Waiting polls the task in the environment it was invoked in; when you call `getTask` yourself, pass that same environment. An environment paused at its monthly budget refuses an invocation with a `quota` error, which is not retried: it holds until the budget is raised or the UTC month turns. ```typescript const client = await createClient({ apiKey, serverlessEnvironment: 'staging' }) diff --git a/src/errors.ts b/src/errors.ts index a374c36..8d18fd4 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -132,7 +132,7 @@ export const deriveCode = (raw: string): ErrorCode => { if (raw === 'aborted') { return 'aborted' } if (raw === 'connectionFailed' || raw === 'notConnected' || raw === 'notOpen' || raw === 'reconnectionFailed' || raw === 'disconnected') { return 'connection' } - if (raw.includes('Credits') || raw.includes('Quota') || raw.includes('Balance') || raw === 'quotaExceeded' || raw === 'paymentRequired') { return 'quota' } + if (raw.includes('Credits') || raw.includes('Quota') || raw.includes('Balance') || raw === 'quotaExceeded' || raw === 'paymentRequired' || raw === 'environmentPaused') { return 'quota' } if (raw.includes('RateLimit') || raw === 'rateLimitExceeded') { return 'rateLimit' } if (SAFETY_CODES.has(raw)) { return 'safety' } diff --git a/src/serverless.ts b/src/serverless.ts index f823b65..4c08ab4 100644 --- a/src/serverless.ts +++ b/src/serverless.ts @@ -37,6 +37,12 @@ const SYNC_MIN_TIMEOUT_MS = 300000 const RETRYABLE_STATUS = (status: number): boolean => status === 408 || status === 429 || (status >= 500 && status < 600) +/** + * The 429 an environment paused at its monthly budget answers invoke with. It + * holds until the budget is raised or the UTC month turns, so it is not retried. + */ +const ENVIRONMENT_PAUSED_TYPE = 'https://docs.runware.ai/serverless/errors#environment-paused' + const TERMINAL: ReadonlySet = new Set(['completed', 'failed']) export const isTerminal = (status: string): boolean => TERMINAL.has(status as TaskStatus) @@ -174,7 +180,8 @@ const problemToError = ( message = `${message}\n${lines.join('\n')}` } - const error = createRunwareError(rawCodeForStatus(status), message, { statusCode: status }) + const rawCode = problem.type === ENVIRONMENT_PAUSED_TYPE ? 'environmentPaused' : rawCodeForStatus(status) + const error = createRunwareError(rawCode, message, { statusCode: status }) if (typeof problem.type === 'string' && problem.type !== 'about:blank') { error.problemType = problem.type } @@ -313,7 +320,7 @@ const createServerlessApi = (config: SDKConfig) => { lastError = error const retryable = (() => { - if (isRunwareError(error) && error.code === 'aborted') { return false } + if (isRunwareError(error) && (error.code === 'aborted' || error.code === 'quota')) { return false } if (isRunwareError(error) && error.code === 'timeout') { return true } if (isRunwareError(error) && error.statusCode !== undefined) { return RETRYABLE_STATUS(error.statusCode) diff --git a/test/serverless.test.ts b/test/serverless.test.ts index d170d1b..be12e61 100644 --- a/test/serverless.test.ts +++ b/test/serverless.test.ts @@ -613,3 +613,44 @@ describe('environment', () => { )).rejects.toThrow(`getTask("my-app", "${TASK_ID}") to pick it up`) }) }) + +describe('budget', () => { + const paused = { + type: 'https://docs.runware.ai/serverless/errors#environment-paused', + title: 'Too Many Requests', + status: 429, + detail: 'environment "staging" is paused at its monthly budget', + } + + it('does not retry an environment paused at its budget', async () => { + const replies = Array.from({ length: 4 }, () => ({ + status: 429, + headers: { 'Retry-After': '0' }, + body: paused, + })) + const { impl, calls } = mockFetch(replies) + const api = createServerlessApi(config(impl, { maxRetries: 3 })) + + const error = await api.invoke({ appId: 'my-app', endpointPath: 'generate', environment: 'staging' }) + .catch((caught: unknown) => caught) + + expect(calls).toHaveLength(1) + if (!isRunwareError(error)) { throw error } + expect(error.code).toBe('quota') + expect(error.retryable).toBe(false) + expect(error.statusCode).toBe(429) + expect(error.message).toContain('paused at its monthly budget') + }) + + it('still retries any other 429', async () => { + const { impl, calls } = mockFetch([ + { status: 429, headers: { 'Retry-After': '0' }, body: { status: 429 } }, { status: 200, body: task() }, + ]) + const api = createServerlessApi(config(impl, { maxRetries: 2 })) + + const result = await api.invoke({ appId: 'my-app', endpointPath: 'generate' }) + + expect(result.status).toBe('completed') + expect(calls).toHaveLength(2) + }) +})