Skip to content

Container APIs in SDK 2.9 ​

The paired @opencloud/server and browser SDK 2.9.0 add Function-to-container operations and resumable managed Files for container jobs. Container compute must be enabled and funded on the installation; see how to check and the guide's manifests and limits. Existing releases keep their SDK pin and bytes. The browser has no opencloud.containers namespace: it calls a declared Function, which decides what input and work the caller may request.

Submit and inspect a job from a Function ​

For the guide's report job, place this in functions/start-report/index.ts and declare it with access: user:

ts
import { defineFunction, schema } from "@opencloud/server";

export default defineFunction({
  input: schema.object({
    requestKey: schema.string(),
    fileId: schema.uuid(),
  }),
  handler: async ({ input, containers }) => {
    return containers.run("report", { format: "csv" }, {
      idempotencyKey: input.requestKey,
      inputFileIds: [input.fileId],
    });
  },
});

The browser supplies one stable request key for the user's intended job and retains it after a timeout. Use 8–128 letters, digits, dots, underscores, colons or hyphens. Reuse the same key only with the same input and File IDs. Do not generate another key inside every retry of the Function. Validate any business permissions in the Function before submitting work; the capability does not itself grant permission to process arbitrary user data.

Function context methodResult
containers.run(name, input, { idempotencyKey, inputFileIds?, timeoutMs? })Retained execution projection
containers.get(executionId, { timeoutMs? }?)Current execution projection in this app/environment
containers.cancel(executionId, { idempotencyKey, timeoutMs? })Execution with recorded cancellation intent
containers.request(name, request, { timeoutMs? }?){ status, headers, body: Uint8Array }

Input is JSON, at most 64 KiB. File selection is at most 16 distinct UUIDs, within the job's declared input policy. The SDK does not accept runtime image, command, resource or permission overrides. timeoutMs bounds the SDK request; it does not replace the job's execution deadline. Its default is 20 seconds; the SDK accepts 1–900,000 milliseconds, still subject to the Function's own remaining execution time and platform request deadlines.

The execution projection includes:

  • executionId, workloadName, immutable revisionId, environment, and developmentSessionId (null in production);
  • state (see job states), waitReason (why a queued or retry_wait job hasn't started, or null), attempt, acceptedAt, startedAt, finishedAt, queueDeadline, executionDeadline, and phaseDeadline;
  • safe error, committed outputFileIds, and independent completionDelivery. error is null, or { statusCode, code, message, details }: details has category, origin, phase, retryScope, retryable and billingDisposition, and when they apply exitCode, signal, workloadName, executionId, instanceId and attempt. Show message to people and branch on code;
  • statusUrl, the execution's path on the OpenCloud API;
  • usage quantities, gross/credit/net estimated cost, price IDs, pending evidence count, and observation/settlement timestamps.

The SDK's types name these: OpenCloudContainerExecution, its OpenCloudContainerWaitReason, and OpenCloudContainerErrorCode for an error.code (a newer platform may add codes, so keep a default branch).

run returns acceptance, not the completed output. get succeeds as a read even when state is failed, timed_out, cancelled or outcome_unknown. Inspect the returned state and error rather than treating an HTTP success as job success. Cancellation does not undo effects that already occurred.

A refused call throws an OpenCloudError. Its code is the platform's code, such as COMPUTE_NO_CAPACITY or FILE_INPUT_UNAVAILABLE, and status the HTTP status. Its details is the platform's whole error body, so the compute fields are in error.details.details. The error's own retryable is true for every 429 and 5xx answer; error.details.details.retryable says whether the same request can still succeed. PLATFORM_REQUEST_FAILED means the platform's answer carried no code of its own; read status and message. A Function that doesn't catch the error answers its own caller with the same status and code.

Which executions a Function can read with get depends on its access:

  • system: any execution of its app in the same environment, so a queue consumer can collect a job that a user's Function started;
  • user, or public with a signed-in caller: executions started for the same user, by any of the app's Functions, so a status Function can follow a job another one started;
  • public without a signed-in caller: only the executions it started itself.

Anything else answers COMPUTE_NOT_FOUND. cancel is only for the Function (and user) that started the execution: another Function that may read it gets 403 COMPUTE_CANCEL_PRODUCER_ONLY, and one that may not gets COMPUTE_NOT_FOUND, as for get. So start and cancel a job in the same Function, with an action in its input if you need both. The app's owners see and can cancel every execution in the CLI and dashboard.

User-scoped files ​

When the app's files are user-scoped (files.access: user), every file belongs to a user. A job that takes input files, or declares outputs, must therefore be started for a signed-in user: from an access: user Function, or a public one with a signed-in caller. Its inputs must be that user's files, and that user owns its outputs and can download them in the browser with opencloud.files.download(). A system Function, or a public one without a signed-in caller, gets 401 AUTH_REQUIRED ("User-scoped files require an authenticated user") for such a job; it can still start jobs without input files or declared outputs. In a development session the signed-in user is one of the session's synthetic users. A job started from the CLI or the dashboard is started for the person using it (see Input and output files).

A queue consumer whose job was enqueued with files: { read: [...] } can't use containers at all: every call answers 403 FILE_DELEGATION_INVALID. Start such a container job from the Function that received the upload, with the file's ID in inputFileIds.

From upload to download ​

The guide's report job end to end, with files.access: user. The page uploads the file and starts the job through start-report (above), then polls a second access: user Function until the job ends:

ts
// functions/report-status/index.ts
import { defineFunction, schema } from "@opencloud/server";

export default defineFunction({
  input: schema.object({ executionId: schema.uuid() }),
  handler: async ({ input, containers }) => containers.get(input.executionId),
});

Inside the image, the job reads its input and writes its outputs:

js
// /app/job.mjs
import { mkdir, readFile, writeFile } from "node:fs/promises";

const input = JSON.parse(await readFile("/work/input.json", "utf8"));
const { files } = JSON.parse(await readFile("/work/inputs/index.json", "utf8"));
const csv = await readFile(files[0].path, "utf8");
await mkdir("/work/output", { recursive: true });
await writeFile("/work/output/summary.csv", summarise(csv, input.format));

The page maps each output ID to its file name with files.info():

js
import { opencloud } from "/_opencloud/sdk.js";

const FINAL = ["succeeded", "failed", "timed_out", "cancelled", "outcome_unknown"];

async function runReport(selectedFile) {
  const file = await opencloud.files.upload({ data: selectedFile, name: selectedFile.name });
  // One key per intended job, kept so a retry after a lost answer finds it.
  const requestKey = `report:${file.id}`;
  let execution = await opencloud.functions.call("start-report", { requestKey, fileId: file.id });
  while (!FINAL.includes(execution.state)) {
    await new Promise((resolve) => setTimeout(resolve, 2_000));
    execution = await opencloud.functions.call("report-status", { executionId: execution.executionId });
  }
  if (execution.state !== "succeeded") throw new Error(execution.error?.message ?? execution.state);
  // Each output is a managed File named after the file the job wrote.
  return Promise.all(execution.outputFileIds.map((id) => opencloud.files.info(id)));
}

// For each returned { id, name, size }: show name, and on click
// opencloud.files.save(id) opens the browser's save dialog.

The outputs belong to the user who started the job, so only that user's files.info(), download() and save() see them. Use downloadStream() for large files.

Request a service from a Function ​

ts
const response = await containers.request("web", {
  path: "/api/status",
  method: "GET",
}, { timeoutMs: 20_000 });

if (response.status !== 200) {
  // Decide how the app represents this service response.
  return { available: false, status: response.status };
}
return JSON.parse(new TextDecoder().decode(response.body));

request accepts a relative app path, optional method (GET by default), string headers, and a string or Uint8Array body. Methods are GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS. Request bodies are bounded to 4 MiB and response bodies to 32 MiB; use Files for larger content. A larger request body throws 413 COMPUTE_REQUEST_TOO_LARGE before anything is sent, with the size and the limit in its message. A response over 32 MiB throws 502 COMPUTE_UPSTREAM_FAILED, whose compute details say origin: "app" and whose message names the limit: at once when its Content-Length says so (the message names that length too), or once it passes the limit when it is sent without one. If the connection to the service breaks part way, the call throws COMPUTE_UPSTREAM_FAILED saying how many bytes arrived; the request may have had its effects. This API returns a buffered byte array; use the service's app route for browser streaming, SSE or WebSockets. There is no timeoutSeconds field in the request object.

A Function runs in 150 MB of memory. The body arrives as raw bytes and is held once, so a 32 MiB response with a Content-Length costs the Function about 32 MiB. A response sent without one (chunked) is read into a buffer that doubles as it grows, so near the limit it briefly costs about twice its size. Leave room for what the Function does with it, and put larger results in Files. A Function also receives a response slowly: testers measured between 0.6 and 5 MB a second, so a response of a few MiB can take longer than the default timeoutMs of 20 seconds. Give a call that may return more than about 5 MiB timeoutMs: 120_000 (the most is 900_000). A call that runs out of time throws PLATFORM_REQUEST_FAILED with status 504, and its message names the timeoutMs that ended it.

The result is { status, headers, body }. headers holds the service's response headers, lowercase, without content-length, cookies (set-cookie), connection-level headers and platform headers (x-opencloud-*, x-forwarded-*). body is a Uint8Array of the whole body, so its length is body.byteLength. It is a view of the buffer the answer was read into, not a copy: use body itself, or body.slice() for a separate copy, rather than body.buffer.

The service receives path exactly as given. A paused service answers COMPUTE_SERVICE_UNAVAILABLE. A service with no running copy starts one first, which can take longer than the default timeoutMs of 20 seconds (see cold starts); give such calls a longer timeoutMs.

The platform resolves the service in the Function's captured app revision and environment. It selects the destination and strips privileged headers. A name, header or URL supplied by app code cannot select another app, a worker address or an arbitrary destination. The SDK never automatically replays an HTTP request after an uncertain result; design mutating service endpoints with their own durable idempotency.

Inside a container ​

@opencloud/container 1.0.0 is the Node.js client a container uses to call the Functions and record the metrics its manifest permits. It has only invokeFunction and recordMetric, and no dependencies. It is an ES module and isn't published on npm: a compute-enabled installation provides it as the package file opencloud-container-1.0.0.tgz. Copy that file into your build folder, install it when you build the image, and import the package by name:

dockerfile
COPY opencloud-container-1.0.0.tgz ./
RUN npm install ./opencloud-container-1.0.0.tgz
js
import { createContainerClient } from "@opencloud/container";

const opencloud = createContainerClient();
await opencloud.invokeFunction("checkpoint", { completed: 12 }, {
  idempotencyKey: "batch-001:checkpoint-12",
});
await opencloud.recordMetric("backlog_depth", 3, {
  idempotencyKey: "batch-001:backlog-12",
});

Both names must appear in the container's manifest permissions. The Function must be declared access: system; it receives no browser user or Data token. The metric and every dimension name/value must be declared under observability.metrics. recordMetric(name, value, { idempotencyKey, dimensions?, signal? }) records a finite value; its key is 8–120 safe characters. A metric the container may not record, an undeclared dimension value or a negative counter increment is refused with 422 COMPUTE_METRIC_INVALID; the app's limit of 1,200 measurements a minute (and 100,000 kept) with 429 COMPUTE_METRIC_LIMIT. invokeFunction(name, input, { idempotencyKey, signal? }) accepts 64 KiB JSON input and an 8–128 character key, returning the Function's result.

The client finds everything it needs in the container's environment:

  • OPENCLOUD_CONTAINER_GATEWAY_URL, the HTTPS address it calls. createContainerClient() throws a ContainerError when it is missing, for example when you run the image on your own computer; pass gatewayUrl and getCapabilityToken to test it there.
  • OPENCLOUD_CONTAINER_CAPABILITY_FILE, which is /opencloud/capability: the copy's credential. OpenCloud replaces it every 30 seconds, and the client reads it again for every call. Do not copy, print or cache it, replace it with an account token, or put it in the image.
  • /opencloud/ca.pem, the certificate authority of the gateway address, which Node.js trusts through NODE_EXTRA_CA_CERTS.

The client has no Files, Data, integration, billing or owner-management API.

A job's process also finds its own run in the environment: OPENCLOUD_EXECUTION_ID (the ID that containers.get, onComplete and the CLI name) and OPENCLOUD_EXECUTION_ATTEMPT (1, then 2 and so on for its retries). Use them to key progress a Function records per run, and to make an attempt's effects idempotent, for example ${process.env.OPENCLOUD_EXECUTION_ID}:checkpoint-12.

js
const run = process.env.OPENCLOUD_EXECUTION_ID;
const attempt = Number(process.env.OPENCLOUD_EXECUTION_ATTEMPT);
await opencloud.invokeFunction("progress", { run, attempt, done: 40 }, {
  idempotencyKey: `${run}:progress-40`,
});

Start serving, then load state ​

Calls work as soon as the process starts, with one exception. A service copy that a deploy, rollback, restore or dev sync starts before its release goes live gets 503 COMPUTE_NOT_LIVE until the switch, and the switch waits until every new copy is ready. So start serving, and answering probes, first. Then load state through a Function, and retry COMPUTE_NOT_LIVE with the same key:

js
import { createServer } from "node:http";
import { createContainerClient, ContainerError } from "@opencloud/container";

const opencloud = createContainerClient();
let board = null;

// handleRequest answers the probe path at once, even while board is null.
createServer(handleRequest).listen(Number(process.env.PORT), "0.0.0.0");

async function untilLive(call) {
  for (;;) {
    try {
      return await call();
    } catch (error) {
      if (!(error instanceof ContainerError) || error.code !== "COMPUTE_NOT_LIVE") throw error;
      await new Promise((resolve) => setTimeout(resolve, 2_000));
    }
  }
}

board = await untilLive(() =>
  opencloud.invokeFunction("load-board", {}, { idempotencyKey: "load-board:startup" }),
);

Checkpoint as you go ​

A copy can be stopped at any time. After SIGTERM, its Function calls still work for its 10 seconds only when a restart, scale-down, pause, host maintenance or changed secret stopped it, or its job was cancelled. A deploy, rollback or dev sync refuses the old copy's calls at once with 409 COMPUTE_RELEASE_REPLACED, and other stops with 403 COMPUTE_AUTHORITY_REVOKED. Metrics are refused after the signal. So save progress through a Function as you go, not only on SIGTERM (see When a copy stops):

js
let stopping = false;
process.on("SIGTERM", () => { stopping = true; });

while (!stopping) {
  const step = await nextStep();
  await opencloud.invokeFunction("checkpoint", { step: step.id }, {
    idempotencyKey: `checkpoint:${step.id}`,
  });
}

Errors and repeated calls ​

Neither method retries by itself. ContainerError has code, status, requestId, retryable and details, and its message is the platform's own text when the platform answered:

  • retryable is true for 429 and 5xx answers, and for a request that didn't complete (COMPUTE_CAPABILITY_UNAVAILABLE, after a network failure or the client's 60-second timeout).

  • status 0 means the client sent nothing: it refused the call itself. A metric name, value or dimension that isn't valid (a value that isn't a finite number, say) is COMPUTE_METRIC_INVALID, and its message says which. A malformed key or Function name, an input over 64 KiB, or an unreadable capability file is COMPUTE_CAPABILITY_INVALID.

  • Every answer from the platform, success or refusal, names a request ID in its x-request-id header; a refusal's is requestId, and the host's log line for the refusal names the same one. Quote it, with OPENCLOUD_CONTAINER_INSTANCE_ID, when you ask for help. It is null only when the client sent nothing (status 0) or the request didn't complete.

  • details holds the platform's scalar classification of a refusal, such as retryable and upstreamStatus, or is null.

The platform's codes are listed under Errors, in "Calls from a container". A Function that throws, or answers with an error status, reaches the container as 502 COMPUTE_FUNCTION_FAILED, with the Function's status in details.upstreamStatus but without its message; its logs say why. The host waits at most 30 seconds for an answer, so keep these Functions quick: a slower call fails with 503 COMPUTE_RUNTIME_UNAVAILABLE, although the Function may still finish.

OpenCloud remembers each key for the copy that used it. Repeating a key returns the first call's result once that call has succeeded, COMPUTE_OUTCOME_UNKNOWN while it still runs or its outcome is unknown, and COMPUTE_FUNCTION_FAILED once its failure is confirmed; use a new key to try a failed effect again. The same key with a different input is COMPUTE_IDEMPOTENCY_CONFLICT. A COMPUTE_NOT_LIVE refusal runs nothing, so the same key works afterwards. A restarted or replacement copy remembers no keys, so make each Function's effect safe to repeat as well, for example with a unique key in its table. A transport timeout can mean that an effect already happened: inspect durable state and reuse the same key when recovering.

Other languages ​

The client is a thin HTTPS wrapper, so any language can make the same calls. Read the capability file for every call, send it as a bearer token, and trust /opencloud/ca.pem when connecting to this address:

text
POST $OPENCLOUD_CONTAINER_GATEWAY_URL/_opencloud/containers/invoke-function
Authorization: Bearer <contents of /opencloud/capability>
Content-Type: application/json

{"name":"checkpoint","input":{"completed":12},"idempotencyKey":"batch-001:checkpoint-12"}

The answer is {"result": ...}, holding the Function's result. Metrics go to /_opencloud/containers/record-metric as up to 20 measurements, such as {"measurements":[{"name":"backlog_depth","value":3,"idempotencyKey":"batch-001:backlog-12"}]}, and the answer is {"accepted": 1}. A malformed measurement, such as a value that isn't a finite number, is 422 COMPUTE_METRIC_INVALID with details.field naming the field (measurements.0.value). Refusals use the platform's error body.

Resumable job inputs ​

SDK 2.9 browser and Function Files clients add an explicitly separate upload workflow for a declared job's larger input files:

MethodPurpose
files.beginUpload({ workloadName, name, contentType, sizeBytes, sha256, idempotencyKey })Allocate a bounded upload session
files.uploadStatus(uploadSessionId)Read the authoritative next offset and state
files.uploadChunk(uploadSessionId, { offsetBytes, data, sha256 })Append one verified chunk
files.completeUpload(uploadSessionId)Verify the whole file and publish its opaque File ID
files.abortUpload(uploadSessionId)Abort an unfinished upload
files.downloadStream(fileOrId)Return metadata and data: ReadableStream<Uint8Array>

sizeBytes and offsetBytes are canonical nonnegative decimal strings, and SHA-256 values are lowercase hex. The begin key is a UUID. A session reports uploadSessionId, fileId, sizeBytes, sha256, offsetBytes, chunkBytes, state and expiresAt; retain its ID to resume. While chunks keep arriving, expiresAt moves to 30 minutes after the latest progress, but never past 24 hours after the session began; an expired session's partial bytes are removed. Browser chunks use Blob, Function chunks use Uint8Array. Respect the returned chunkBytes (at most 8 MiB), exact offset and chunk digest. Compute the full-file hash incrementally for large files instead of reading several GiB into browser or Function memory.

js
// selectedFile, wholeFileSha256 and sha256Blob come from the app's file picker
// and bounded hashing code. Persist uploadKey and the session ID for recovery.
const session = await opencloud.files.beginUpload({
  workloadName: "report",
  name: selectedFile.name,
  contentType: selectedFile.type || "application/octet-stream",
  sizeBytes: String(selectedFile.size),
  sha256: wholeFileSha256,
  idempotencyKey: uploadKey,
});

let status = await opencloud.files.uploadStatus(session.uploadSessionId);
while (status.state === "uploading" && BigInt(status.offsetBytes) < BigInt(status.sizeBytes)) {
  const offset = Number(status.offsetBytes); // This API is bounded to 10 GiB.
  const chunk = selectedFile.slice(offset, offset + status.chunkBytes);
  status = await opencloud.files.uploadChunk(session.uploadSessionId, {
    offsetBytes: status.offsetBytes,
    data: chunk,
    sha256: await sha256Blob(chunk),
  });
}
const completed = await opencloud.files.completeUpload(session.uploadSessionId);
// Pass completed.fileId to the app's producer Function after publication.

On a lost response, read uploadStatus before deciding which bytes to send. Do not start another session or change keys simply because the previous response was ambiguous. Only a published complete file is eligible for job input. Use abortUpload when the user abandons an unfinished upload.

The selected workload's job.inputs.maxTotalGiB bounds each upload, up to 10 GiB; the eventual job also enforces total selected bytes and file count. Normal Files ownership/RLS and current environment remain in force. This does not change files.maxUploadBytes, upload, replace, attach, or existing Function queue file delegation. Buffered downloads above 100 MiB require the streaming API (FILE_STREAM_REQUIRED).

Self-hosted infrastructure for agent-built applications.