Skip to content

About

redu sandbox SDK for Java

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

redu-sandbox-sdk-java

A Java client for the redu.cloud API. Version 0.1 covers sandboxes: isolated machines started from a template, for running commands. It has the features and semantics of the Go, TypeScript, Python, Rust and Ruby clients (redu-sandbox-sdk-go is the reference).

Where sandboxes are not available for an account, every sandbox route answers it 403 sandboxes_not_available.

Install

From Maven Central: cloud.redu:redu-sandbox-sdk:0.1.0, package cloud.redu.sandbox. With Maven:

<dependency>
  <groupId>cloud.redu</groupId>
  <artifactId>redu-sandbox-sdk</artifactId>
  <version>0.1.0</version>
</dependency>

With Gradle:

implementation("cloud.redu:redu-sandbox-sdk:0.1.0")

Quick start

ReduClient client = ReduClient.builder().apiKey(System.getenv("REDU_API_KEY")).build();
Sandboxes sandboxes = client.sandboxes();

Sandbox sb = sandboxes.create(CreateSandboxInput.of("ubuntu-node").timeoutS(600));
try {
    ExecOutcome out = sandboxes.exec(sb.id(), ExecInput.command("node -v"));
    System.out.println(out.exitCode() + " " + out.stdout());
} finally {
    sandboxes.delete(sb.id());
}

In the examples below, client is a ReduClient and id is a sandbox's id.

Credentials

Builder method Sent as Notes
apiKey(key) Authorization: Bearer <key> The key needs sandbox:*, or the route's own sandbox:<action>. A full-access * key does not include sandboxes: 403 insufficient_scope.
token(token), tokenSource(supplier) Authorization: Bearer <token> A signed-in session's access token. A supplier hands a fresh token to each request.

Give one of them. With neither, the client reads REDU_API_KEY from the environment. The base URL defaults to REDU_API_BASE, else https://console.redu.cloud.

ReduClient fromEnv = ReduClient.builder().build(); // REDU_API_KEY, and REDU_API_BASE when it is set
ReduClient withSession = ReduClient.builder()
        .tokenSource(() -> fetchAccessToken()) // your sign-in's current access token, asked per request
        .build();

sandboxesEnabled() tells whether sandboxes are on for the caller's account (from GET /v1/capabilities):

boolean on = client.sandboxesEnabled();

Sandboxes

Method of client.sandboxes() Route Answer
templates() GET /v1/sandboxes/templates List<Template> (name, vcpus, memoryMb, diskGb, price)
list() GET /v1/sandboxes your live sandboxes
get(id) GET /v1/sandboxes/{id} one Sandbox
create(in, opts) POST /v1/sandboxes the Sandbox once it is running
exec(id, in, opts) POST /v1/sandboxes/{id}/exec ExecOutcome: exit code, stdout, stderr
delete(id, opts) DELETE /v1/sandboxes/{id} returns once it is gone
addPublicName(id, in, opts) POST /v1/sandboxes/{id}/dns PublicName (id, domain, port, url) once it serves
removePublicName(id, dnsId, opts) DELETE /v1/sandboxes/{id}/dns/{dns_id} returns once it no longer serves
openTerminal(id, in, opts) POST /v1/sandboxes/{id}/terminal an OpenedTerminal: a TerminalSession (websocket url, one-time token) or the web Terminal (url, username, password)
closeTerminal(id, opts) DELETE /v1/sandboxes/{id}/terminal TerminalClosed: whether a terminal was stopped, and platformTerminals
extend(id, timeoutS, opts) POST /v1/sandboxes/{id}/extend ExtendedSandbox: the sandbox with its new expiresAt (null: no end)
pause, resume, suspend(id, opts) POST /v1/sandboxes/{id}/pause, /resume, /suspend SandboxState (status, already, from, expiresAt)
readFile(id, path) GET /v1/sandboxes/{id}/files?path= the bytes of a file of at most 8 MiB
readFileRange(id, path, offset, length) the same, with a Range one FileRange (data, offset, next, size)
readFileRanges(id, path, opts, fn), readLargeFile(id, path, out, opts) the same, part after part each part to fn as it comes, or the whole file to an OutputStream
writeFile(id, path, data, opts) PUT /v1/sandboxes/{id}/files?path= WrittenFile (path, bytes)
startCommand(id, in, opts) POST /v1/sandboxes/{id}/commands StartedCommand, running in the background
listCommands(id) GET /v1/sandboxes/{id}/commands the running ones and the last 32 that ended
getCommand(id, commandId, opts) GET /v1/sandboxes/{id}/commands/{command_id} CommandOutput: the command and its output past the offsets
followCommand(id, commandId, opts, fn), waitForCommand(...) the same, until it ends its output to fn as it comes, or CommandEnd with all of it
stopCommand(id, commandId, signal) DELETE /v1/sandboxes/{id}/commands/{command_id} the Command, signalled
takeSnapshot(id, name, opts) POST /v1/sandboxes/{id}/snapshots the SandboxSnapshot once it is taken
listSnapshots() GET /v1/sandboxes/snapshots your snapshots, oldest first
getSnapshot(snapshotId) GET /v1/sandboxes/snapshots/{snapshot_id} one SandboxSnapshot
deleteSnapshot(snapshotId, opts) DELETE /v1/sandboxes/snapshots/{snapshot_id} returns once it is gone
fork(id, in, opts) POST /v1/sandboxes/{id}/fork the new Sandbox, a running copy
changeEgress(id, policy, opts) PUT /v1/sandboxes/{id}/egress EgressChange: its rules now, and how many connections they closed
egressLog(id, since, limit) GET /v1/sandboxes/{id}/egress/log one EgressLog page: events, nextSince, more
readEgressLog(id, opts, fn) the same, page after page each event to fn; the nextSince to read from later
auditLog(id, opts) GET /v1/sandboxes/{id}/audit one AuditLog page: events, nextSince, more
readAuditLog(id, opts, fn) the same, page after page each AuditEvent to fn; the nextSince to read from later
resize(id, in, opts) POST /v1/sandboxes/{id}/resize ResizedSandbox: the sandbox at its new size, from, to, price
getLifecycle(id) GET /v1/sandboxes/{id}/lifecycle SandboxLifecycle: its idle pause, its end and its spend in one view
setLifecycle(id, in, opts) PUT /v1/sandboxes/{id}/lifecycle LifecycleChanged: the lifecycle after the change, and what it changed
limits() GET /v1/sandboxes/limits SandboxLimits: the account's limits, what is used and what is left, how long its sandboxes may live, and its free sandbox
listEnded(opts) GET /v1/sandboxes?state=ended one EndedSandboxPage of the sandboxes that ended in the last 7 days, and nextCursor
getEnded(id) GET /v1/sandboxes/{id}?state=ended one EndedSandbox
buildTemplate(in, opts) POST /v1/sandboxes/templates/builds the TemplateBuild, once accepted (queued)
listTemplateBuilds() GET /v1/sandboxes/templates/builds your builds, newest first
getTemplateBuild(buildId) GET /v1/sandboxes/templates/builds/{build_id} one TemplateBuild, with its log
cancelTemplateBuild(buildId) DELETE /v1/sandboxes/templates/builds/{build_id} TemplateBuildCancel: cancelling, finishing, forgotten or pending
deleteTemplate(templateId, opts) DELETE /v1/sandboxes/templates/{template_id} returns once it is gone
setSecrets(id, secrets, opts), removeSecrets(id, opts) PUT, DELETE /v1/sandboxes/{id}/secrets SandboxSecrets: names and hosts, never a value
getSsh(id) GET /v1/sandboxes/{id}/ssh SandboxSsh: its SSH server, keys, host keys and how to connect
addSshKey(id, key, opts), removeSshKey(id, fingerprint, opts), removeAllSshKeys(id, opts) POST, DELETE /v1/sandboxes/{id}/ssh/keys the SandboxSsh after the change
openSsh(id, idleTimeoutS) POST /v1/sandboxes/{id}/ssh one connection: SshSession (url, one-time token, knownHosts, a ready ssh command)
getRequest(workflowId) GET /v1/sandboxes/requests/{workflow_id} one read of a request that answered 202
waitForRequest(workflowId, timeout) the same, until it ends how it ended (RequestState)

Every options argument may be left out (an overload without it) or passed as null for the defaults. Every method that can answer 202 has a start form that does not wait and returns a Started<T> (the value, or the 202's PendingRequest): startCreate, startDelete, startAddPublicName, startRemovePublicName, startOpenTerminal, startCloseTerminal, startExtend, startPause, startResume, startSuspend, startTakeSnapshot, startDeleteSnapshot, startFork, startResize, startChangeEgress, startSetLifecycle, startBuildTemplate, startDeleteTemplate, startSetSecrets, startRemoveSecrets, startAddSshKey, startRemoveSshKey, startRemoveAllSshKeys, startOpenSsh.

Extend, pause, suspend, resume, files and background commands need the redu API version that adds them (the API of 20 Nov 2026). An API from before answers them 404 not_found. Snapshots, forks, egress rules and the connection log need the version after it (also 20 Nov 2026): an API from before answers their routes 404 not_found, and refuses fromSnapshot and egress in a create with 400 validation_error. A create's size and private network, the resize and the audit log need the version after that (20 Nov 2026, later): an API from before answers them 404 not_found and refuses vcpus, memoryMb, diskGb, networkId and volumes in a create. The storage prices (a template's storagePerGbMonth and pausedOrSuspended..., a snapshot's price) need the version of the evening of 20 Nov 2026, and changeEgress and resizeRange the version of 21 Nov 2026: an API from before answers changeEgress 404 not_found, and the fields it does not send are null. A sandbox's lifecycle, the limits, ended sandboxes, templates built from container images, secrets, SSH and the terminal over the platform's websocket need the API version of 27 Nov 2026: an API from before answers their routes 404 not_found, and refuses idlePauseS or secrets in a create with 400 validation_error. A sandbox with no end, the free sandbox and the limits' maxLifetimeS, noEnd and freeSandbox need the API version of 1 Dec 2026: an API from before refuses timeout_s 0 and free with 400 validation_error, and its limits leave the three null.

Create

Sandbox sb = client.sandboxes().create(CreateSandboxInput.of("ubuntu-node") // a name or id from templates()
        .name("build-42")
        .timeoutS(3600)                   // seconds, see "Lifetime and no end"; deleted by itself at its end
        .env(Map.of("NODE_ENV", "test"))
        .isPublic(true)                   // it can then have public names and a web terminal
        .maxSpend(2.0));                  // GBP: see "Spend cap"

A field left unset is left out of the body (the API's schema is strict). redu answers 201 once the sandbox is running. When it is still being made after about 40 seconds, redu answers 202 with a workflow_id, and create waits for it through GET /v1/sandboxes/requests/{workflow_id}, reading it every 5 seconds for at most CreateOptions.waitTimeout (by default the longest the request can run: 40 minutes for a create). startCreate hands the 202 back instead:

Started<Sandbox> started = client.sandboxes().startCreate(CreateSandboxInput.of("ubuntu-node"), null);
Sandbox sb = started.isDone()
        ? started.value()
        : client.sandboxes().waitForRequest(started.pending().workflowId(), null).sandbox();

The client never sends a create twice by itself: a create whose answer was lost may still be running, and a second one makes a second sandbox (list() shows the first one once it is ready). CreateOptions.idempotencyKey lets you repeat a create safely once the first one has answered: redu stores that answer for the key for 24 hours.

Sandbox big = client.sandboxes().create(CreateSandboxInput.of("ubuntu-node").vcpus(2).memoryMb(2048).diskGb(8));
System.out.println(big.vcpus() + " vCPUs, " + big.memoryMb() + " MB"); // 2 vCPUs, 2048 MB

A create from a template takes a size: vcpus 1 to 4, memoryMb one of 1024, 2048, 4096 and 8192 (Sandboxes.SANDBOX_MEMORY_MB), and diskGb 1 to 10 (at least that much disk: a template with more keeps its own). Each one left unset is the template's own (templates() lists them; a template smaller than 1024 MB gets 1024), and a sandbox made from a snapshot has the snapshot's size (the client refuses a size with fromSnapshot). 400 size_unsupported when the template cannot be made at that size. It is billed at the same price for its size. networkId puts the sandbox on one of your private networks (GET /v1/private_networks): it reaches your machines there (their own security groups decide what it may reach), all its traffic leaves through that network (one with no router to the internet gives it no internet), and it is not public, so not with isPublic(true). 404 network_not_found, 409 network_unusable (no IPv4 subnet). Every read shows vcpus(), memoryMb(), diskGb() and networkId(). The client checks only the types; redu checks the bounds (400 validation_error).

Sandbox work = client.sandboxes().create(CreateSandboxInput.of("ubuntu-node")
        .volumes(VolumeMount.of("6a0e3c43-0d7e-4b8e-9b1f-2a6f5f1b9c01").mountPath("/work"))); // GET /v1/volumes/list
SandboxVolume v = work.volumes().get(0);
System.out.println(v.mountPath() + " " + v.status()); // /work attached
client.sandboxes().delete(work.id()); // the volume is unmounted and detached, and keeps its data

volumes attaches and mounts up to two volumes of yours (Sandboxes.VOLUMES_MAX), from a template only (the client refuses them with fromSnapshot): each a VolumeMount (its id; mountPath, by default /mnt/volumes/<id>; and format). format (true when unset) formats a volume on which no filesystem, partition table or other signature is found, so a blank one, and one written raw, loses its data; one with a signature is mounted as it is (format(false): a volume with none fails the create instead). When the sandbox is deleted or ends, its volumes are unmounted and detached and keep their data; a volume is never deleted with its sandbox, and it is billed as any volume. An API key needs volume:attach (or volume:*) beside its sandbox scope. Every read shows them as volumes() (each a SandboxVolume: volumeId, mountPath, status). A sandbox with volumes is not snapshotted, forked or suspended (409 sandbox_has_volumes: pause it instead). 404 volume_not_found, 409 volume_in_use, volume_not_available, volumes_unavailable, 400 volume_unsupported, too_many_volumes, 502 volume_attach_failed (no sandbox was made, and the volumes stay available).

Lifetime and no end

SandboxLimits limits = client.sandboxes().limits();
CreateSandboxInput in = CreateSandboxInput.of("ubuntu-node");
if (Boolean.TRUE.equals(limits.noEnd())) {
    in.timeoutS(Sandboxes.NO_END);      // no end: it runs until it is deleted
} else if (limits.maxLifetimeS() != null) {
    in.timeoutS(limits.maxLifetimeS()); // the longest this account may give
}
Sandbox sb = client.sandboxes().create(in);
System.out.println(sb.expiresAt() == null ? "no end" : sb.expiresAt());

A sandbox is deleted by itself at its expiresAt(), timeoutS seconds after its create (3600 when left out), unless it is extended. A timeoutS is 60 up to your account's longest life, limits().maxLifetimeS() (2592000, 30 days, for an account with no card; at most 31536000, 365 days). redu checks it, not this client: it refuses a lifetime the account may not have (400 validation_error on timeout_s).

Sandboxes.NO_END (0), at a create or an extend, asks for a sandbox with no end: it runs until you delete it, or until its maxSpend, its API key's monthly cap or a suspended account ends it, and it is billed by use as any sandbox. Every read shows its expiresAt() and maxExpiresAt() as null, which never means it has ended. It is for an account with a card, where limits().noEnd() is true (the create's other billing checks still apply), never for a sandbox with volumes, and never for the free sandbox. A fork and a lifecycle change never take 0: extend the sandbox for that (the copy, once it runs). A sandbox with no end keeps it, so a later extend changes nothing.

Code What it means
403 no_end_needs_card the account has no card: give timeoutS in seconds, or add a payment method
403 free_sandbox_options the free sandbox never has no end (see "The free sandbox")
503 no_end_unavailable no end cannot be given right now: nothing was made or changed (an existing sandbox keeps the end it had). Try again in a few minutes, or give timeoutS in seconds and extend it later
400 validation_error on timeout_s, with the reason: no end is not offered, the sandbox has volumes, or the ask is above your longest life

The platform's maintenance (an update or a planned restart of the server a sandbox runs on) pauses a sandbox with no end for a few minutes and brings it back as it was; open connections, terminals and SSH sessions are cut. A sandbox lives on one server with its memory and disk, so a hardware failure there can still end it: a sandbox with no end that ended so is listed among the ended sandboxes with EndedSandbox.LOST.

The free sandbox

SandboxLimits.FreeSandbox free = client.sandboxes().limits().freeSandbox(); // null: redu does not say
if (free != null) {
    System.out.println(free.available() + " " + free.hoursUsed() + " of " + free.hoursPerMonth() + " hours used, "
            + free.hoursLeft() + " left until " + free.resetsAt());
}

An account with the free tier has one free sandbox: 1 vCPU and 1 GB of memory from a template, never charged, one at a time, with 50 hours a calendar month (UTC) of running and paused time (suspended time does not count). An account with no card has it during its 7-day trial; an account with a card has it every month, beside its paid sandboxes. When the month's hours are used it is deleted, and a new one can be made from the 1st of the next month. CreateSandboxInput.free(true) asks for it and free(false) for a paid sandbox; left unset, nothing is sent, and an account with no card gets its free sandbox while any other gets a paid one. It takes no snapshot, other vcpus or memoryMb, diskGb, isPublic, networkId, volumes or maxSpend, and it never has no end: it lives at most 30 days after its create, extends included (freeSandbox().maxLifetimeS(); a longer timeoutS is a 400 validation_error). It keeps its size, and it costs nothing, so a lifecycle change takes no maxSpend for it either. It is created through the redu MCP only, so from this client such a create is refused 403 free_sandbox_mcp_only; once made it is used here as any sandbox, and every read shows free() true. limits().freeSandbox() says whether your account can have it now (available(), and reason() when not), its hours used and left this month, and when they reset (resetsAt()).

Code What it means
403 free_sandbox_mcp_only it is created through the redu MCP only
403 free_sandbox_options the create asked for something it does not take; or Sandboxes.NO_END at an extend, or a maxSpend in a lifecycle change
403 free_sandbox_exists the account has its free sandbox already: use it, or delete it to make another
409 free_sandbox_creating the account's free sandbox is being created
402 free_sandbox_hours_used its hours for this month are used: a new one can be made from the 1st (UTC)
403 free_sandbox_size a resize of it: it keeps its size
403 free_sandbox_unavailable the account cannot have a free sandbox now: its setup is not complete

Each is redu's own answer, never sent again by the client (SandboxErrorCodes.FREE_SANDBOX_*).

Spend cap (maxSpend)

maxSpend is a cap in GBP for one sandbox (at least 0.10, at most 1000; a smaller one is refused with 400 validation_error). When what the sandbox has cost reaches it, the sandbox is deleted, and nothing is charged above it. The sandbox can keep running past its cap for up to one usage interval of the sandbox service plus a minute before it is deleted; that run is not charged. A sandbox made with one shows spend() (so far), maxSpend() and spendUpdatedAt() (when the usage spend comes from was read; null before the first read), so spend can trail what the sandbox has cost. With the same API version, each template has a price(). Every amount is a double.

maxSpend needs the redu API version that adds sandbox spend caps. An API without it refuses the field (400 validation_error). A key with a monthly sandbox cap that has been reached gets 402 spend_cap_reached on create.

Exec

ExecOutcome out = client.sandboxes().exec(id, ExecInput.argv("node", "-e", "console.log(1 + 1)")
        .env(Map.of("A", "1"))
        .cwd("/root")
        .stdin("...")
        .timeoutMs(30000)); // 1000 to 30000
if (out.exitCode() != null) { // null when a signal ended it (out.signal())
    System.out.println(out.exitCode() + " " + out.stdout() + out.stderr());
}
System.out.println(out.durationMs() + " " + out.idempotencyKey() + " " + out.attempts());

durationMs() is a Double: it can carry a fraction. ExecInput.command("...") runs a command line with /bin/sh -c instead of a program and its arguments.

A command runs for at most 30 seconds. Start longer work in the background (see "Background commands"). Stdout and stderr are cut at 64 KiB each.

A command is not safe to run twice, so every call carries an Idempotency-Key (yours, or a new random one), and the answers decide what happens next:

Answer Did it run? What the client does
200 yes returns the result
202 (no result after about 40 s) may have sends it again with the same key, which never runs it twice and answers from the first run
no answer (lost connection, timeout, a proxy's error page) may have the same: sends it again with the same key
a 2xx whose body is not JSON (unexpected_answer) may have: the request got through the same; on the last attempt it throws with Ran.UNKNOWN
502 exec_outcome_unknown may have sends it once more with the same key; a second one is final (Ran.UNKNOWN)
502 exec_result_lost yes throws (Ran.YES): check its effects before running it again
503 exec_not_started, 429 sandbox_busy no the key keeps this answer for about a day, so with its own key the client tries once more under a new key; with your key it throws (Ran.NO)
409 idempotency_key_reused no throws: the same key was used for another command
any other error no, or unknown after an earlier lost answer throws
the thread is interrupted unknown while a request was in flight throws canceled

At most ExecOptions.maxAttempts requests (default 4) are sent per call. Every exec error carries ran() and idempotencyKey(), so you know whether running it again is safe and under which key it was tried. To repeat a command yourself after Ran.UNKNOWN, call exec again with the same input and that key:

ExecInput hi = ExecInput.command("echo hi");
try {
    client.sandboxes().exec(id, hi);
} catch (ReduException e) {
    if (e.ran() != Ran.UNKNOWN) {
        throw e;
    }
    client.sandboxes().exec(id, hi, new ExecOptions().idempotencyKey(e.idempotencyKey()));
}

Public names

A sandbox made with isPublic(true) can have one public https name per port. The program must listen on 0.0.0.0:<port> and keep running after the command that starts it.

client.sandboxes().exec(id, ExecInput.command(
        "nohup python3 -m http.server 8000 --bind 0.0.0.0 > /tmp/http.log 2>&1 &"));
PublicName name = client.sandboxes().addPublicName(id, PublicNameInput.port(8000));
System.out.println(name.url()); // https://...redu.cloud
client.sandboxes().removePublicName(id, name.id());

Without domain(...) a name is generated under redu.cloud; a domain of your own must be verified for your account first. 409 sandbox_not_public for a sandbox made without isPublic, 409 port_already_named for a port that has a name or is getting one.

Terminal

openTerminal gives a root shell in the sandbox. Where the platform offers terminals over its websocket, any live sandbox gets one, private ones included; elsewhere a sandbox made with isPublic(true) gets the web terminal, a root shell in the browser at a public name of port 7681, behind a username and a password.

OpenedTerminal t = client.sandboxes().openTerminal(id, new TerminalInput().cols(120).rows(40), null);
if (t instanceof TerminalSession session) {
    System.out.println(session.url() + " " + session.protocol()); // open within 60 s, once, with your client
} else if (t instanceof Terminal web) {
    System.out.println(web.url() + " " + web.username() + " " + web.password()); // answered only now
}
TerminalClosed closed = client.sandboxes().closeTerminal(id);
System.out.println(closed.terminal() + " " + closed.platformTerminals()); // web: stopped; websocket: ended

It answers an OpenedTerminal of one of two kinds: tell them apart with kind() (websocket or web), instanceof, or asSession() and asWeb().

A TerminalSession carries a one-time token(), good for 60 seconds and one session: open url() with a websocket client of your own, offering subprotocols() (or with the token as a bearer token); binary messages are the terminal's input and output. TerminalInput sets its cols and rows (1 to 1000) and idleTimeoutS (60 to 3600 seconds with no byte either way); the web terminal ignores them. When redu answers 202 (a suspended sandbox is woken first), it keeps no token for later, so the client opens it again after the poll interval, up to 3 requests in all (Sandboxes.SESSION_OPEN_ATTEMPTS), then throws still_pending (status 202); startOpenTerminal hands the 202 back instead. closeTerminal ends these too where the platform can: platformTerminals() is ended (with platformTerminalsEnded()), or not_closed when it cannot (they end when their connection closes, after their idle timeout, or when the sandbox is deleted). TerminalSession.toString() never shows the token, and no error ever carries it.

The web Terminal: anyone with the URL and the password has the shell. redu answers the password once and keeps it nowhere: opening the terminal again restarts it with a new password and keeps the URL. When the open answers 202, the password comes with the 202 and the URL with the request's end; openTerminal puts them together. If its wait ends early (wait_timeout), that password is lost with it; startOpenTerminal hands the 202 (with the password) back instead. Terminal.toString() and PendingRequest.toString() never show the password, and no error ever carries a terminal answer's body. closeTerminal says what it found: stopped, none (no terminal was running), or not_stopped (the sandbox is paused or not running: its name is removed, but the terminal may run again with its old password, so close it again once the sandbox runs, or delete the sandbox). One open or close runs at a time per sandbox: 409 terminal_busy.

Extend

ExtendedSandbox x = client.sandboxes().extend(id, 7200); // seconds from now, or Sandboxes.NO_END
System.out.println(x.expiresAt() + " " + x.previousExpiresAt() + " " + x.extended() + " " + x.capped());

The sandbox then ends timeoutS seconds from now, never sooner than it already would (extended() is false then), and, where a longest life holds, at most that long after it was created (capped() is true when that cut the ask): the platform's (maxExpiresAt(), null where it has none), and 30 days for an account with no card and for the free sandbox. Sandboxes.NO_END takes its end away (see "Lifetime and no end"): expiresAt() is then null. Calling it again is safe, so it works as a keep-alive; leave ExtendOptions.idempotencyKey unset for that, since a repeated key replays the first answer and extends nothing. A sandbox costs while it lives. 409 sandbox_deleting, 402 max_spend_reached or spend_cap_reached, and 404 sandbox_not_found once it has ended.

Pause, suspend, resume

client.sandboxes().pause(id);   // CPUs stop, memory kept: no CPU charge
client.sandboxes().suspend(id); // memory saved and freed: no memory charge
SandboxState r = client.sandboxes().resume(id);
System.out.println(r.status() + " " + r.from()); // running disk

Each returns a SandboxState: status(), already() (it was in that state), from() ("disk" after a suspend) and expiresAt(). A paused sandbox refuses commands (409 sandbox_not_running); a suspended one is resumed by its next command (ExecOutcome.resumed()). Both are still deleted at expiresAt (unless it has no end) and still count against your limits. A 202 is waited on. Codes: 409 sandbox_suspended (a suspended sandbox cannot be paused), 409 sandbox_cannot_suspend (a command or file transfer runs in it, or it was just created: try again in a minute, or pause it), 409 sandbox_resume_unavailable (no room right now: it stays suspended with its memory and files), 409 sandbox_state_busy (another change of it is under way). No Idempotency-Key is ever sent with these: redu's replay cache keys on the credential and the key, whatever the route, so a reused key would replay a pause's answer for a resume.

A paused or suspended sandbox is billed for storage only: its memory at the storage rate. Each template's price() shows it: pausedOrSuspendedPerHour(), pausedOrSuspendedPerMonth() (730 hours) and storagePerGbMonth().

Files

Sandboxes s = client.sandboxes();
s.writeFile(id, "/root/app/main.py", "print('hi')\n".getBytes(StandardCharsets.UTF_8),
        new WriteFileOptions().mode("644"));
byte[] data = s.readFile(id, "/root/app/main.py"); // at most 8 MiB
ByteArrayOutputStream buf = new ByteArrayOutputStream(); // any OutputStream: a file, a digest
long n = s.readLargeFile(id, "/root/app/main.py", buf); // any size, 8 MiB per request
s.readFileRanges(id, "/root/app/main.py", part ->
        System.out.println(part.offset() + " " + part.data().length + " " + part.size())); // -1: unknown

Paths are absolute (at most 4096 characters). readFile throws 413 file_too_large for a file over 8 MiB (its message says the size): read it with readLargeFile, or part by part with readFileRanges or readFileRange(id, path, offset, length) (length 0: to the end), which follows the Content-Range of each answer. 416 range_not_satisfiable past the end, 404 file_not_found when the sandbox has no such file. writeFile sends at most Sandboxes.FILE_WRITE_MAX_BYTES (12517376 bytes, 12 MiB less 64 KiB; a larger file is refused with an IllegalArgumentException before anything is sent), replaces a file that is there, and creates missing parent folders. A file call is never sent again by the client on a lost answer.

Background commands

Sandboxes s = client.sandboxes();
StartedCommand cmd = s.startCommand(id, CommandInput.command("npm run build").cwd("/root/app"));
s.followCommand(id, cmd.id(), o -> System.out.print(o.stdout()));
CommandEnd end = s.waitForCommand(id, cmd.id()); // or all of it at the end
System.out.println(end.command().exitCode() + " " + end.stdout() + " " + end.stdoutLost());
s.stopCommand(id, cmd.id(), Sandboxes.SIGNAL_KILL); // null sends TERM

A background command runs for up to an hour (timeoutMs, default and most 3600000), at most 16 at once per sandbox (429 sandbox_busy). startCommand follows exec's rules for a lost answer and its Idempotency-Key (the table above): the same key never starts it twice, and its errors carry ran() and idempotencyKey(). getCommand reads the output past stdoutOffset and stderrOffset, waiting up to waitMs (20000 at most) for more; ask again from stdoutNext() and stderrNext(). followCommand does that until the command has ended and all its output is read (FollowOptions.timeout stops following with wait_timeout, its details() holding the offsets to follow on from; the command runs on, and each read waits at most the time left). The sandbox keeps the last 1 MiB of each stream: what was written faster than it was read is counted in stdoutLost and stderrLost. A read refused with 429 sandbox_busy, or one that got no answer, is read again (three tries in all). 404 command_not_found once it is forgotten (the last 32 ended ones are kept).

Snapshots

Sandboxes s = client.sandboxes();
SandboxSnapshot snap = s.takeSnapshot(id, "before-upgrade"); // its files, memory and running programs
Sandbox again = s.create(CreateSandboxInput.fromSnapshot(snap.id()).name("from-snapshot"));
List<SandboxSnapshot> all = s.listSnapshots(); // oldest first, each with its status
s.deleteSnapshot(snap.id()); // sandboxes made from it keep running

A snapshot is taken of a running or paused sandbox, which pauses for about a second while it is written. It is kept until you delete it, also after the sandbox is gone, on the server the sandbox runs on: it is not a backup. A sandbox created from it (CreateSandboxInput.fromSnapshot, in place of a template) starts as the sandbox was at that moment, at its size, and its fromSnapshot() names the snapshot. One take runs at a time per sandbox, and your account holds a limited number of snapshots. A 202 is waited on, as a create's.

The client never sends a take twice by itself. How a take can end (the codes are constants in SandboxErrorCodes):

Answer Was it taken? What to do
201 yes the SandboxSnapshot
503 snapshot_not_taken no, nothing was kept take it again
503 snapshot_outcome_unknown it may have been list the snapshots, and wait a few minutes before taking another: if it was taken, it counts against your limit, possibly without being listed
no answer (network_error), canceled, wait_timeout it may have been, or may still be list the snapshots before taking another (for wait_timeout, read the request later)
409 sandbox_busy_for_snapshot, snapshot_not_possible, snapshot_limit_reached, snapshot_in_progress no take it between commands, resume a suspended sandbox first, delete a snapshot, or wait for the take under way
try {
    client.sandboxes().takeSnapshot(id);
} catch (ReduException e) {
    if (e.is(SandboxErrorCodes.SNAPSHOT_OUTCOME_UNKNOWN)) {
        System.out.println(client.sandboxes().listSnapshots().size()); // it may exist: look first
    } else if (!e.is(SandboxErrorCodes.SNAPSHOT_NOT_TAKEN)) {
        throw e;
    }
}

A create from a snapshot answers 404 snapshot_not_found, 409 snapshot_unavailable (still being taken, being deleted, or failed) or 503 snapshot_server_unavailable (the server that keeps it cannot start a sandbox from it right now: nothing was made). A delete answers 409 snapshot_deleting while the snapshot is still being taken or another delete holds it.

Resize

ResizedSandbox r = client.sandboxes().resize(id, new ResizeInput().vcpus(4).memoryMb(4096));
System.out.println(r.from().vcpus() + " to " + r.to().vcpus() + " vCPUs, GBP " + r.price().busyPerHour()
        + " an hour busy");

resize changes a running sandbox's vCPUs (1 to 4) and memory (1024 to 8192 MB, within its template's range: memory moves in 2 MB steps, and a shrink stops at what the sandbox can free) live: nothing restarts, and its files and programs stay. Set either or both. It answers a ResizedSandbox: the sandbox at its new size, from and to (each a SandboxSize) and price at that size, which it is billed at from then on. The size is a target, not a step, so asking again for the same size is safe. A 202 is waited on through GET /v1/sandboxes/requests/sandbox-resize-<id>; startResize hands it back. 409 resize_not_available (SandboxErrorCodes.RESIZE_NOT_AVAILABLE): the template cannot be resized, nothing changed, and a new sandbox at the size you need is the way. 409 resize_busy carries the resize under way as its workflowId(). 400 resize_out_of_range, 409 resize_refused (try again in a minute), 429 resize_limit_reached, 502 resize_failed (nothing changed), resize_incomplete and resize_outcome_unknown (get shows the size it has, which is what it is billed at). The free sandbox keeps its size: 403 free_sandbox_size.

SandboxResizeRange range = client.sandboxes().get(id).resizeRange(); // null: the general bounds apply
if (range != null) {
    System.out.println(range.minVcpus() + " to " + range.maxVcpus() + " vCPUs, up to " + range.maxMemoryMb() + " MB");
    System.out.println(range.allows(2, 2048) ? "inside" : "outside"); // inside
}

Every read shows the sandbox's own resizeRange() when the sandbox service reports it (a SandboxResizeRange: vCPUs minVcpus to maxVcpus, memory minMemoryMb to maxMemoryMb in steps of memoryStepMb), set by the size it was created at and fixed while it lives. It is null when redu leaves it out (the service reported no range: the general bounds apply) and when redu sends it null (the service reports that the sandbox cannot be resized). allows(vcpus, memoryMb) (either null: not asked) says whether a resize to that size is inside it; redu answers one outside it 400 resize_out_of_range.

Fork

Sandbox copy = client.sandboxes().fork(id, new ForkInput().name("try-2").timeoutS(600));
System.out.println(copy.id() + " " + copy.forkedFrom()); // a new sandbox, running; forkedFrom is id

A fork is a new sandbox: a running copy of a running or paused one as it is now (its files, memory and running programs), at its template and size, public when it is (with no public names yet), and with its egress rules. The original goes on, pausing a moment while its memory is copied. Programs keep running in the copy, so whatever they do outside now happens twice, and connections open at the moment of the copy are cut in the copy. Its commands get only the env given here, and its maxSpend is its own: the original's cap is not copied. It is billed as any sandbox and counts against your limits. Its timeoutS is finite (60 and up): extend the copy with Sandboxes.NO_END for no end. Like a create, a fork is never sent twice by the client (CreateOptions.idempotencyKey repeats one safely once it has answered), and a 202 is waited on: do not fork again meanwhile, or there will be two copies. 409 fork_not_now (a command or a file transfer runs in it: fork it between commands), 409 fork_unsupported, 409 sandbox_not_running, 503 fork_no_room (a copy starts on the same server as its original, which is full: try again in a few minutes).

Egress rules

EgressPolicy egress = EgressPolicy.denyByDefault() // a connection no rule matches is refused
        .rule(EgressRule.allowHosts("pypi.org", "*.pythonhosted.org").onPorts(443))
        .rule(EgressRule.allowCidrs("198.51.100.0/24").onPortRange(5432, 5433));
Sandbox sb = client.sandboxes().create(CreateSandboxInput.of("ubuntu-node").egress(egress));
System.out.println(sb.egress().defaultAction() + " " + sb.egress().rules().size()); // deny 2

Egress rules limit the TCP connections a sandbox may open. They are set at its create and tried in order: the first that matches decides, and the default action decides the rest. A create without them allows everything (egress().allowsAll()). A host rule matches the name a TLS or HTTP connection carries: an exact name, or *.example.com for every name under it (not example.com itself). A cidr rule matches IPv4 networks (a bare address is a /32). Ports are numbers or ranges. A rule gives hosts or cidrs, not both. At most 32 rules, 256 host names and 128 address ranges in all, and 32 ports per rule: redu checks them and answers 400 validation_error with the reason. Loopback, link-local and multicast addresses are never reachable. Every read of the sandbox shows its rules (Sandbox.egress(), with updatedAt), a fork keeps them, and EgressPolicy.of(sb.egress()) gives another sandbox the same ones.

EgressChange change = client.sandboxes().changeEgress(id, EgressPolicy.denyByDefault()
        .rule(EgressRule.allowHosts("pypi.org", "*.pythonhosted.org", "registry.npmjs.org").onPorts(443)));
System.out.println(change.egress().rules().get(0).hosts().size() + " hosts, " + change.connectionsClosed()
        + " connections closed");

changeEgress replaces a running or paused sandbox's rules, live: nothing restarts, and the open connections the new rules refuse are closed. It takes what a create's egress takes, with the same rules and limits; EgressPolicy.allowByDefault() with no rules removes every rule. It returns an EgressChange: egress(), the rules now (every read shows them from then on), and connectionsClosed(). A 202 is waited on through GET /v1/sandboxes/requests/sandbox-egress-rules-<id>; startChangeEgress hands it back. One change of a sandbox's rules runs at a time: 409 egress_change_busy carries the one under way as its workflowId(). Sending the same rules again is safe, but the client never sends a change twice by itself: after 502 egress_change_outcome_unknown (it may have been made; get shows the rules last confirmed) send the same rules again yourself. 409 egress_change_unavailable (SandboxErrorCodes.EGRESS_CHANGE_UNAVAILABLE): this platform cannot change a running sandbox's rules yet, nothing changed, and it keeps the rules it was created with, so create a sandbox with the rules you need. 409 egress_change_unsupported (it started before its rules could be changed while it runs), egress_not_filtered, sandbox_suspended (resume it first), sandbox_changing (a resize, a suspend or a resume of it runs: try again in a moment), sandbox_ending, sandbox_not_running; 400 egress_rules_refused.

Connection log

Sandboxes s = client.sandboxes();
EgressLog page = s.egressLog(id, 0, 100); // one page: from the start, at most 100 events
long next = s.readEgressLog(id, e -> System.out.println(e.type() + " " + e.host() + " " + e.port()));
s.readEgressLog(id, new EgressLogOptions().since(next), e -> System.out.println(e.type())); // what came after

Each event has a type(): connect (host, address, port, protocol), denied (the number of the rule that denied it, or default), closed (bytesOut, bytesIn, durationMs), failed, or refused before any rule (reason too_many_open, too_fast or local_address, with counts), and a seq() and at(). egressLog reads one page after since (0, or a page's nextSince), at most limit events (1 to 500; 0 for redu's 200). readEgressLog reads page after page while redu says more may follow: a page can come back empty with more true (the records it read were a command's, not connections), and it reads on. It stops at a page that says no more, or at a nextSince that does not move, so it never asks for the same page twice and never hands an event twice. It returns the nextSince to read from later.

Audit log

AuditChain chain = new AuditChain();
long next = client.sandboxes().readAuditLog(id, chain::add); // AuditChainException where the chain breaks
System.out.println(chain.checked() + " records checked, " + chain.withheld() + " withheld, read on from " + next);

The sandbox's own event log, oldest first: each command sent to it through the API (exec.request, exec.result, exec.kill), each file read or write through the API (file.read, file.write), its outbound connections (egress.connect, egress.close, ...), the programs started and ended inside it as it reports them (proc.exec, proc.exit), the rule decisions that refuse something (rule.deny), and the machine's own life (sandbox.claim, vm.paused, vm.resumed, ...); never a command's env, its output or a file's content. Each AuditEvent is a record exactly as the sandbox service wrote it: seq(), tNs() and monoNs() (nanoseconds), sandboxId(), source(), kind(), trust(), data(), prev() and h(), with record() (the whole record, every number as written) and text() (its own JSON text). trust host is written by the host from what it saw; guest is reported from inside the sandbox, which a program with root there can stop or forge. A record redu cannot answer whole comes withheld() in its place (platform_detail, too_large or not_json), with its seq, at, kind, source, trust, prev, h and bytes. The answer is read by the client's own JSON reader, so a record keeps its exact text.

AuditChain checks the hash chain exactly as redu describes it: seq counts 1, 2, 3 without gaps, prev is the h of the record before (64 zeros for seq 1), and h is the SHA-256 of the record without its h, written as Python's json.dumps(record, sort_keys=True, separators=(",", ":")) writes it. add throws AuditChainException (with seq() and reason(): SEQ, PREV, HASH or UNREADABLE) at the first break; a withheld record's own h cannot be checked, the order across it can. AuditChain.verify(events) checks a list, new AuditChain(seq, h) goes on from a record checked before, and AuditChain.digest(text) is the h of one record's text. Read from since 0 to check from the first record. AuditLogOptions.kind(...) (an event kind or a family of kinds such as exec, file.write or vm, up to 10) leaves the other kinds out, so a page read with it is checked record by record with AuditChain.verifyEach. The chain has no key or signature: it shows a record changed or removed in the middle, not a log cut at its end or replaced as a whole.

auditLog reads one page (limit 1 to 500; 0 for redu's 200); readAuditLog reads on as readEgressLog does, and never asks the same page twice. At most 2 reads of your account's logs run at once: 429 too_many_log_reads is asked again after its Retry-After, as a 202 is. 502 event_log_unreadable: the log cannot be read past that since. The log is read only while the sandbox exists.

Lifecycle

What puts a sandbox to sleep and what ends it, in one place: its idle pause, its end, and its spend against its cap.

SandboxLifecycle l = client.sandboxes().getLifecycle(id);
System.out.println(l.idlePauseS() + " " + l.expiresAt() + " " + l.maxExpiresAt() + " " + l.spend() + " "
        + l.maxSpend());
LifecycleChanged after = client.sandboxes().setLifecycle(id, new LifecycleInput()
        .idlePauseS(300) // paused after 5 minutes without activity; 0 never pauses it
        .maxSpend(5.0)   // GBP, above what it has cost so far; removeMaxSpend() removes the cap
        .timeoutS(7200)); // as extend does
System.out.println(after.changed().idlePauseS() + " " + after.changed().maxSpend() + " "
        + after.changed().expiresAt());

idlePauseS (0 to 86400 seconds; 0 never pauses it) also goes in a create (CreateSandboxInput.idlePauseS) and a fork (ForkInput.idlePauseS; without it the copy keeps the original's): the sandbox is paused after that long without activity (no command, file transfer or connection), billed for its memory only, and resumes on its next command. Every read shows it (Sandbox.idlePauseS(), null when none is reported). In setLifecycle a field left unset stays as it is: timeoutS works as extend does, but never gives no end (0 is refused: extend with Sandboxes.NO_END does that), maxSpend must be above what the sandbox has cost so far (409 max_spend_below_spend), and removeMaxSpend() removes the cap (the free sandbox costs nothing, so it takes neither: 403 free_sandbox_options). getLifecycle shows expiresAt() and maxExpiresAt() null for a sandbox with no end, idlePauseChangeable() (409 idle_pause_not_changeable while it is false) and the API key's monthly cap (keySpendCap()). One change of a sandbox's lifecycle runs at a time: 409 lifecycle_busy carries the one under way as its workflowId(). A 202 is waited on through GET /v1/sandboxes/requests/sandbox-lifecycle-<id>; startSetLifecycle hands it back. Sending the same change again is safe, but the client never sends one twice by itself: after 502 idle_pause_outcome_unknown send it again yourself. A change that failed after its idle pause or its cap was applied says so in the error: LifecycleChanges.appliedOf(e). 402 max_spend_reached, spend_cap_reached; 503 usage_not_current (try again in a few minutes).

Limits and ended sandboxes

SandboxLimits limits = client.sandboxes().limits();
System.out.println(limits.available().vcpus() + " vCPUs left, " + limits.used().sandboxes() + " sandboxes");

EndedSandboxPage page = client.sandboxes().listEnded(new EndedListOptions().limit(20));
while (true) {
    for (EndedSandbox e : page.sandboxes()) {
        System.out.println(e.id() + " " + e.endedAt() + " " + e.endReason() + " " + e.spend());
    }
    if (page.nextCursor() == null) {
        break;
    }
    page = client.sandboxes().listEnded(new EndedListOptions().limit(20).cursor(page.nextCursor()));
}

limits() answers the account's limits (sandboxes, vCPUs, memory, disk), what counts against them now (used(), and byStatus()), what is left (available()), the snapshot limit, and redu's own words on what counts (counted()) and how to have them raised (raise()). maxLifetimeS() and noEnd() say how long your sandboxes may live (see "Lifetime and no end"), and freeSandbox() shows your free sandbox (see "The free sandbox"); each is null when redu does not answer it (an API from before 1 Dec 2026, or a free sandbox that could not be read). Ended sandboxes are the ones that ended in the last 7 days, newest end first, from redu's own record: each with endedAt(), endReason() (EndedSandbox.DELETED, EXPIRED, MAX_SPEND, KEY_SPEND_CAP, LOST, or null), what it cost (spend()) and readableUntil(). A page holds at most 100 (Sandboxes.ENDED_PAGE_MAX_LIMIT; 50 when no limit is set); nextCursor() is null on the last one. getEnded(id) reads one (404 sandbox_not_found otherwise, a live sandbox included). Both are reads: a 202 or a lost answer is read again.

Templates from container images

Sandboxes s = client.sandboxes();
TemplateBuild build = s.buildTemplate(TemplateBuildInput.of("my-python", "python:3.12").memoryMb(2048));
build = s.getTemplateBuild(build.id()); // with its log
while (!build.isEnded()) {
    Thread.sleep(15_000);
    build = s.getTemplateBuild(build.id());
}
if (build.templateId() != null) {
    Sandbox sb = s.create(CreateSandboxInput.of(build.templateId())); // a sandbox of your own template
    System.out.println(sb.id() + " " + sb.template()); // ... my-python
    s.delete(sb.id());
    s.deleteTemplate(build.templateId()); // its storage charge ends
}

A build is accepted (queued) and then goes on by itself, through pulling, unpacking, building, uploading and registering, to done (with its templateId()) or failed (with its error()): getTemplateBuild reads it with its log(). TemplateBuildInput.of(name, image) takes a name (1 to 100 letters, digits, ., _ and -, once per account) and an image ([registry/]repository[:tag][@sha256:digest], Docker Hub when no registry is named), with the default vcpus, memoryMb and diskGb of its sandboxes. registryAuth(username, password) is for a private image: it is used for that one build, kept nowhere, and never shown by this client (TemplateBuildInput.toString() redacts it). One build runs at a time per account (409 template_build_in_progress), so a repeat never starts two, and the client never repeats one by itself. A built template is billed as stored data, as a snapshot is (price()), from when its build is done until deleteTemplate deletes it; 409 template_in_use while snapshots need it (the error's details().get("snapshots") names them: delete those first). cancelTemplateBuild cancels a running build (cancelling, or finishing once it is registering, too late to stop) and forgets one that ended (forgotten; pending: cancel it again in a moment). 409 template_name_taken, template_limit_reached, template_builds_unavailable; 429 template_build_rate_limited (not the generic rate limit: never sent again by the client); 400 template_build_refused; 402 spend_cap_reached.

Secrets

Sandbox withKey = client.sandboxes().create(CreateSandboxInput.of("ubuntu-node")
        .secrets(SecretInput.of("OPENAI_API_KEY", loadOpenAiKey(), "api.openai.com")));
System.out.println(withKey.secrets()); // names and hosts, never a value
client.sandboxes().setSecrets(withKey.id(), List.of()); // replaces them all, values included; empty: none
client.sandboxes().removeSecrets(withKey.id());

A secret is bound to hosts: the sandbox sees a placeholder in its env variable, and the platform puts the real value into requests to those hosts only, so code in the sandbox never reads it. Each SecretInput has a name (capitals, digits and _, not also in env), a value (1 to 8192 printable ASCII characters) and 1 to 16 host names (no wildcards, no addresses); up to 16 secrets. Every read names each secret and its hosts (Sandbox.secrets(), a list of SecretView), never its value. A value is never shown back: it lives in the sandbox's own memory, and to keep the sandbox through the platform's maintenance (an update or a planned restart) it is written into the sandbox's saved state on the server it runs on, readable by the platform only, and removed when the sandbox is brought back. This client never shows a value: SecretInput.toString() redacts it, and a secret it refuses before sending is named by its place and name. setSecrets replaces them all, values included, so send the whole list each time; removeSecrets removes them, whatever the account's billing state. One change at a time: 409 secrets_change_busy carries the one under way as its workflowId(). 409 secrets_unavailable, secrets_unsupported (it started before it could have secrets: create a new one), secrets_need_egress_filtering, sandbox_not_running; 400 secrets_refused; 502 secrets_failed, secrets_outcome_unknown (send the same list again).

SSH

Sandboxes s = client.sandboxes();
SandboxSsh ssh = s.addSshKey(id, readPublicKey()); // the one line of your .pub file
System.out.println(ssh.connect().sshConfig() + ssh.knownHosts()); // for ~/.ssh/config and ~/.ssh/known_hosts
SshSession once = s.openSsh(id);
System.out.println(once.ssh()); // a ready ssh command for one connection, within 60 seconds
s.removeSshKey(id, ssh.keys().get(0).fingerprint());
s.removeAllSshKeys(id); // the SSH server stops, and its sessions through the platform end

SSH reaches any live sandbox of yours through the platform, private ones included, when its template has an SSH server (409 ssh_unsupported otherwise; 409 ssh_unavailable where the platform has none). addSshKey adds one public key and starts the server (keys only, root); removeSshKey removes one by its SHA256 fingerprint; removeAllSshKeys removes every key, stops the server and ends the sessions open through the platform. Each answers the sandbox's SandboxSsh: server(), keys(), hostKeys(), the knownHosts() lines that pin them, and connect() (an sshConfig() block and the ssh() command). Adding or removing a key needs an API key with sandbox:ssh; openSsh needs sandbox:ssh_connect. openSsh answers ONE connection: an SshSession with a websocket url, a one-time token (60 seconds, once) and a ready ssh() command for it (it needs websocat); it is opened again on a 202 as a websocket terminal is, and SshSession.toString() never shows the token. One change of the keys at a time: 409 ssh_keys_busy carries the one under way as its workflowId(). 400 ssh_key_refused; 403 denied_by_sandbox_rules; 502 ssh_failed, ssh_outcome_unknown (getSsh, then send the change again).

Errors

Every refusal or failure of redu's is a ReduException (unchecked). An input the client refuses before sending anything (an empty id, a relative file path, a file too large to write, a secret without hosts) is an IllegalArgumentException. No error of this client ever carries a secret's value, registry credentials, a terminal's password or a session's token.

try {
    client.sandboxes().get(id);
} catch (ReduException e) {
    if (!e.is("sandbox_not_found")) {
        throw e;
    }
    System.out.println(e.status() + " " + e.reduMessage() + " " + e.hint()); // 404, and redu's sentences
}
Method Meaning
status() the HTTP status, or 0 when no answer came back
code() redu's stable code (quota_exceeded, sandbox_not_public, ...; those of snapshots, forks, a create's size, network and volumes, a resize, the logs, a change of egress rules, a lifecycle, template builds, secrets, SSH, a sandbox with no end and the free sandbox are constants in SandboxErrorCodes), or one of the client's own: network_error, canceled, wait_timeout, still_pending, unexpected_answer
reduMessage(), hint() redu's sentences, unchanged (getMessage() adds the code and the status)
details() the rest of redu's error, as a Jackson JsonNode (a validation error's issues, a scope error's required_scope, a lifecycle change's applied, a template's snapshots)
retryAfter() from Retry-After
workflowId() when the error is how a request that answered 202 ended, or a wait for it; on resize_busy, egress_change_busy, lifecycle_busy, secrets_change_busy and ssh_keys_busy the change under way; on a session's still_pending the last request's
ran(), idempotencyKey() on exec and startCommand errors (see the table above)
method(), path() the request's

A 429 rate_limited is sent again by the client after its Retry-After (up to maxRateLimitRetries, default 2): redu's rate limits answer before any route runs, so nothing was done. A break in an audit log's chain is not an answer of redu's: AuditChainException is an unchecked exception of its own (see "Audit log").

Options

ReduClient client = ReduClient.builder()
        .apiKey(System.getenv("REDU_API_KEY"))
        .baseUrl("https://console.redu.cloud")
        .httpClient(HttpClient.newHttpClient())
        .requestTimeout(Duration.ofSeconds(120)) // one HTTP request; redu holds one up to about 40 s
        .pollInterval(Duration.ofSeconds(5))     // between reads of a request that answered 202
        .maxRateLimitRetries(2)
        .userAgent("my-agent/1.0")
        .build();

Keep requestTimeout well above redu's own waits: about 40 s before a route answers 202, and up to 10 s for a read of a request that answered 202 (GET /v1/sandboxes/requests/{workflow_id} waits for the request to end before it answers 202 again).

The default HttpClient speaks HTTP/1.1. Java's client sends a request again by itself only for a GET or a HEAD whose kept-alive connection broke, never a POST or a DELETE, so a keyed create, take or fork is never replayed behind your back.

Development

The build and the tests run in the official Maven image (no JDK needed on the host):

docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp/home -e MAVEN_CONFIG=/tmp/home/.m2 \
  -v "$PWD":/work -v "$HOME/.m2":/tmp/home/.m2 -w /work \
  maven:3.9.9-eclipse-temurin-21 mvn -B -Duser.home=/tmp/home verify

The tests run against src/test/java/cloud/redu/sandbox/FakeRedu.java, a local com.sun.net.httpserver server that answers as the redu API's sandbox routes do (a port of redu-sandbox-sdk-go's fake). When those routes change, change the fake with them. ReadmeTest checks that every java block of this README is in ReadmeExamples.java, which the tests compile and, where no real credential is needed, run against the fake. NoDashesTest fails on any em dash or en dash in the repo, and PublishReadyTest checks the LICENSE, the POM's publishing metadata, this README's install and license lines, and its wording. src/test/resources/audit-chain.json holds a real audit log as the sandbox service wrote it, and JSON texts with the hash Python's json module gives them, which the chain check must match. .github/workflows/test.yml runs the whole suite on Java 17 and 21 on every push and pull request.

Releasing

RELEASING.md says how a version goes to Maven Central: the release profile builds the source and javadoc jars, signs every file with GPG and uploads them to the Central Portal, where the deployment waits to be published by hand. A build without the profile needs no GPG key. ReduClient.VERSION carries the same number as the POM.

License

Apache-2.0. Copyright 2026 REDU CLOUD LTD. See LICENSE.

About

redu sandbox SDK for Java

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages