Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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' })

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.
Expand Down
7 changes: 7 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' }
Expand Down
50 changes: 44 additions & 6 deletions src/serverless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -36,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<TaskStatus> = new Set<TaskStatus>(['completed', 'failed'])

export const isTerminal = (status: string): boolean => TERMINAL.has(status as TaskStatus)
Expand Down Expand Up @@ -107,6 +114,18 @@ const validateEndpointPath = (endpointPath: unknown): string => {
return endpointPath
}

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',
`${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
}

const validateTaskId = (taskId: unknown): string => {
if (typeof taskId !== 'string' || !TASK_ID_PATTERN.test(taskId)) {
throw createRunwareError(
Expand Down Expand Up @@ -161,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
}
Expand Down Expand Up @@ -211,6 +231,16 @@ 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 =>
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=${encodeURIComponent(environment)}`
}

const fetchOnce = async (
url: string,
Expand Down Expand Up @@ -290,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)
Expand Down Expand Up @@ -320,8 +350,9 @@ const createServerlessApi = (config: SDKConfig) => {
): Promise<ServerlessTask> => {
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,
Expand All @@ -332,9 +363,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<ServerlessTask> => {
Expand All @@ -347,9 +382,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 },
)
}
Expand All @@ -358,6 +394,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 } : {}),
})
Expand All @@ -382,6 +419,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'
Expand All @@ -396,7 +434,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,
Expand All @@ -408,7 +446,7 @@ const createServerlessApi = (config: SDKConfig) => {
return task
}

return waitForTask(task, options, startedAt)
return waitForTask(task, environment, options, startedAt)
}

return { invoke, getTask }
Expand Down
6 changes: 6 additions & 0 deletions src/types/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. Default: unset, which sends no
* environment and the platform reads as `production`.
*/
serverlessEnvironment?: string
/** Transport to use. Default: `websocket`. */
transport: TransportType
/**
Expand Down
11 changes: 11 additions & 0 deletions src/types/serverless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions test/integration/smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>
const describeServerless = (apiKey && serverlessBaseUrl && serverlessApp && serverlessEndpoint)
? describe
Expand All @@ -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
Expand Down
Loading
Loading