Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(exec): add sync: bool mode to POST /exec and Rust support (#3111)

lfld287acfda3880a81
diff --git a/docs/reference/README.md b/docs/reference/README.md
index a73ae1a48..3acd67985 100644
--- a/docs/reference/README.md
+++ b/docs/reference/README.md
@@ -38,17 +38,30 @@ Complete API documentation for each SDK:
| **Reference server** | [`openapi/reference-server/`](../../openapi/reference-server/README.md) | A partial implementation used as a client test fixture, not a conformance target |
The spec is the contract, not an inventory of any one server, and no
-implementation currently serves all 35 paths:
+implementation currently serves all 49 paths:
| Server | Serves | Does not serve |
|--------|--------|----------------|
| `boxlite serve` | boxes, lifecycle, exec, files, snapshots, clone/export/import, metrics, config, me, images (from its local image cache) | registries, `network/tunnel`, `network/inbound`. Volume routes are registered but every operation answers `400 UnsupportedError`, as do `images/usage` and both alias write routes |
| reference server | boxes, lifecycle, exec, files, snapshots, clone/export/import, metrics, config, me | volumes, images, registries, `network/tunnel`, `network/inbound`, attach, and `DELETE …/executions/{exec_id}` (kill) |
+Use `POST /{prefix}/boxes/{box_id}/exec` with `"sync": true` (`sync` defaults
+to `false`) for a non-interactive command that should return its exit code and
+bounded stdout/stderr in one HTTP response. First check that `GET /v1/config`
+advertises `capabilities.sync_exec_enabled: true`; if the flag is missing or
+false, don't send a synchronous request. Sync exec needs no WebSocket and
+sends EOF on stdin. Non-null inline `stdin` (including an empty string) and
+`tty: true` return HTTP `400`. `timeout_seconds` defaults to 30 and must be
+between 0.1 and 300 seconds inclusive; an out-of-range value returns `400`,
+while an execution that exceeds its deadline returns `408`. For streaming or
+TTY, omit `sync` (or set `"sync": false`) and use WebSocket `/attach` on servers
+that support attachment.
+
Read each server's routes rather than either README — both under-report.
`GET /config` does not close this gap: its feature flags (`tty_enabled`,
`streaming_enabled`, `snapshots_enabled`, `clone_enabled`, `export_enabled`,
-`import_enabled`, `inbound_update_enabled`, `exec_user_enabled`) cover only some routes, there is no
+`import_enabled`, `inbound_update_enabled`, `exec_user_enabled`,
+`sync_exec_enabled`) cover only some routes. There is no
flag at all for volumes, images or tunnel, and a flag can disagree with the
routes — the reference server advertises `streaming_enabled: true` while
serving no attach route.
diff --git a/docs/reference/rust/README.md b/docs/reference/rust/README.md
index a1ac58998..4b38eeb3b 100644
--- a/docs/reference/rust/README.md
+++ b/docs/reference/rust/README.md
@@ -452,6 +452,27 @@ HTTP contract, reconfiguration, disable, and generation semantics.
| `mount` | `fn mount(&self) -> MountHandle` | Manage persistent host directory mounts on a local native box |
| `attach` | `async fn attach(&self, options: AttachOptions) -> BoxliteResult<Execution>` | Attach to init or a named live session; only one output reader is allowed |
+#### Synchronous exec
+
+`LiteBox::exec_sync(command)` waits for the command to finish and returns its
+exit code and bounded stdout/stderr. Use `exec_sync_with_limit(command, bytes)`
+to change the capture limit per stream (default 1 MiB). The timeout defaults to
+30 seconds and must be between 0.1 and 300 seconds inclusive. The same deadline
+covers starting the command, waiting for exit, and collecting output. Each
+stream's `*_truncated` flag reports bytes lost to either the capture limit or
+the guest output buffer. Sync exec does not support TTY or stdin input: the
+command receives EOF on stdin. Over HTTP, an out-of-range timeout or non-null
+inline `stdin` returns `400`.
+
+For REST boxes, the SDK requires `capabilities.sync_exec_enabled: true` from
+`GET /v1/config` and caches that configuration per API client. If the flag or
+capabilities object is absent, or the flag is false, the SDK returns
+`BoxliteError::Unsupported` without sending the exec request. A command that
+specifies a `user` still checks `exec_user_enabled` against the live server.
+If the server unexpectedly returns `201 Created`, it started an asynchronous
+execution. The SDK reports its execution ID when available; do not blindly
+retry the command.
+
#### Online disk growth
`ResizeOptions::disk_size_gb` is an absolute capacity in binary GiB, from 1 through 1024.
diff --git a/make/test.mk b/make/test.mk
index 1987a7ec3..b39d5828c 100644
--- a/make/test.mk
+++ b/make/test.mk
@@ -618,7 +618,7 @@ test\:unit\:openapi:
@python3 -m unittest discover -s openapi/reference-server/tests -p 'test_error*.py' -v
test\:unit\:openapi\:server: _ensure-python-deps
- @. .venv/bin/activate && uv run --with fastapi --with uvicorn --with sse-starlette --with PyJWT --with python-multipart --with python-dotenv --with pyyaml --python .venv/bin/python python -m unittest discover -s openapi/reference-server/tests -p 'test_handle_cache.py' -v
+ @. .venv/bin/activate && PYTHONPATH=openapi/reference-server/tests uv run --with fastapi --with uvicorn --with sse-starlette --with PyJWT --with python-multipart --with python-dotenv --with pyyaml --python .venv/bin/python python -m unittest -v test_handle_cache test_exec_sync
test\:unit\:scripts:
@python3 -m unittest discover -s tests/scripts -p 'test_*.py' -v
diff --git a/openapi/box.openapi.yaml b/openapi/box.openapi.yaml
index b176c67e9..5ef7fca0d 100644
--- a/openapi/box.openapi.yaml
+++ b/openapi/box.openapi.yaml
@@ -84,7 +84,12 @@ info:
## Execution Model
- Command execution has three related operations:
+ Use `POST /exec` with `"sync": true` (`sync` defaults to `false`) for
+ non-interactive commands: one HTTP request waits for completion and returns
+ the exit code and bounded stdout/stderr. It does not support `tty: true` or
+ interactive stdin.
+
+ For streaming or interactive commands (default `sync: false`):
1. `POST /exec` creates the execution and returns its guest-assigned `execution_id`.
2. `GET /executions/{exec_id}/attach` upgrades to a bidirectional
WebSocket carrying stdin, stdout, stderr, and in-band control
@@ -862,12 +867,13 @@ paths:
- $ref: "#/components/parameters/boxId"
post:
operationId: startExecution
- summary: Start an asynchronous command execution
+ summary: Start a command execution (async by default, or sync when sync is true)
description: |
- Starts a command in the box and returns an execution ID immediately.
- The box is automatically started if not already running.
+ Starts a command in the box. The box is automatically started if not
+ already running.
- Use the returned `execution_id` to:
+ When `sync` is `false` (or omitted), returns `201` with an
+ `execution_id` immediately. Use the returned `execution_id` to:
- Attach stdio: `GET /executions/{exec_id}/attach` (WebSocket)
- Check status: `GET /executions/{exec_id}`
- Send signal: `POST /executions/{exec_id}/signal`
@@ -878,6 +884,12 @@ paths:
/executions` enumerates the sessions that are still running, so a
client that lost its handle — a crashed process, a dropped
connection — can recover the id and attach or kill it.
+
+ When `sync` is `true`, waits for the command to complete without a
+ WebSocket and returns `200` with `SyncExecResponse`. Stdin receives EOF
+ and `tty: true` is rejected with `400`. Nonzero exit codes still return
+ `200`. On timeout the server attempts to kill the execution and returns
+ `408`.
tags: [Execution]
parameters:
- $ref: "#/components/parameters/idempotencyKey"
@@ -888,8 +900,14 @@ paths:
schema:
$ref: "#/components/schemas/ExecRequest"
responses:
+ "200":
+ description: Command completed (when `sync` is `true`)
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SyncExecResponse"
"201":
- description: Execution started
+ description: Execution started (when `sync` is `false` or omitted)
headers:
Location:
description: URL of the execution resource
@@ -903,6 +921,8 @@ paths:
$ref: "#/components/responses/BadRequestError"
"404":
$ref: "#/components/responses/NotFoundError"
+ "408":
+ $ref: "#/components/responses/RequestTimeoutError"
"409":
$ref: "#/components/responses/ConflictError"
"422":
@@ -3033,6 +3053,10 @@ components:
type: boolean
description: Server honors `ExecRequest.user`.
example: true
+ sync_exec_enabled:
+ type: boolean
+ description: "Whether the server supports synchronous execution (`sync: true`)."
+ example: true
volume_read_only_enabled:
type: boolean
description: "Whether managed-volume mounts may set `read_only: true`."
@@ -4109,7 +4133,10 @@ components:
timeout_seconds:
type: number
minimum: 0.1
- description: Execution timeout in seconds
+ description: >-
+ Execution timeout in seconds. With `sync: true`, the timeout must be 0.1 to 300 seconds
+ inclusive (default 30 seconds). The deadline covers starting the command, waiting for
+ exit, and collecting output. Values outside that range return HTTP 400.
working_dir:
type: string
description: Working directory override for this execution
@@ -4123,6 +4150,22 @@ components:
User to run the command as, Docker format `<name|uid>[:<group|gid>]`.
Absent or empty uses the box default user. Unknown users or groups return 400.
example: "1000:1000"
+ sync:
+ type: boolean
+ default: false
+ description: >-
+ When `true`, wait synchronously for the command to complete and return `200` with
+ `SyncExecResponse` instead of `201` with `ExecResponse`. Requires the server to advertise
+ `sync_exec_enabled: true`. The command receives EOF on standard input. Rejects
+ `tty: true` with HTTP 400.
+ max_output_bytes:
+ type: integer
+ minimum: 1024
+ maximum: 10485760
+ default: 1048576
+ description: >-
+ Maximum captured bytes per stream (stdout and stderr independently).
+ Only applies when `sync` is `true`.
ExecResponse:
type: object
@@ -4134,6 +4177,27 @@ components:
description: Unique execution identifier
example: exec-01HJK5ABCDEF
+ SyncExecResponse:
+ type: object
+ required: [exit_code, stdout, stderr, stdout_truncated, stderr_truncated]
+ properties:
+ exit_code:
+ type: integer
+ stdout:
+ type: string
+ description: Captured stdout decoded as UTF-8 with invalid bytes replaced.
+ stderr:
+ type: string
+ description: Captured stderr decoded as UTF-8 with invalid bytes replaced.
+ stdout_truncated:
+ type: boolean
+ description: Whether the capture limit or the guest output buffer discarded stdout bytes.
+ stderr_truncated:
+ type: boolean
+ description: Whether the capture limit or the guest output buffer discarded stderr bytes.
+ error_message:
+ type: string
+
ExecutionInfo:
type: object
description: Execution status and result
diff --git a/openapi/reference-server/README.md b/openapi/reference-server/README.md
index ff92a1562..f8cb7750e 100644
--- a/openapi/reference-server/README.md
+++ b/openapi/reference-server/README.md
@@ -93,7 +93,7 @@ curl -s -X DELETE http://localhost:8080/v1/demo/boxes/$BOX_ID \
| `/{prefix}/boxes/{id}` | DELETE | Remove box |
| `/{prefix}/boxes/{id}/start` | POST | Start box |
| `/{prefix}/boxes/{id}/stop` | POST | Stop box |
-| `/{prefix}/boxes/{id}/exec` | POST | Execute command |
+| `/{prefix}/boxes/{id}/exec` | POST | Start an asynchronous command (`sync: false`, default) or run synchronously and return exit code + bounded stdout/stderr (`sync: true`) |
| `/{prefix}/boxes/{id}/executions/{eid}` | GET | Execution status |
| `/{prefix}/boxes/{id}/executions/{eid}/signal` | POST | Send signal |
| `/{prefix}/boxes/{id}/executions/{eid}/resize` | POST | Resize TTY |
diff --git a/openapi/reference-server/server.py b/openapi/reference-server/server.py
index 982e37570..e364ab3ca 100644
--- a/openapi/reference-server/server.py
+++ b/openapi/reference-server/server.py
@@ -37,7 +37,7 @@ import tarfile
import tempfile
import time
import uuid
-from contextlib import asynccontextmanager
+from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Literal, Optional
@@ -200,9 +200,14 @@ class ExecCommandRequest(BaseModel):
command: str
args: Optional[list[str]] = None
env: Optional[dict[str, str]] = None
- timeout_seconds: Optional[float] = None
+ # Validate raw sync limits below so invalid types return 400 without coercion.
+ timeout_seconds: Optional[Any] = None
+ max_output_bytes: Optional[Any] = None
working_dir: Optional[str] = None
tty: bool = False
+ sync: bool = False
+ stdin: Optional[str] = None
+ user: Optional[str] = None
class SignalRequest(BaseModel):
@@ -640,6 +645,7 @@ async def get_config():
"exec_timeout_max_seconds": 3600,
"tty_enabled": True,
"streaming_enabled": True,
+ "sync_exec_enabled": True,
"snapshots_enabled": True,
"clone_enabled": True,
"export_enabled": True,
@@ -925,6 +931,18 @@ async def import_box(
# ============================================================================
+async def exec_with_transport_retry(box_handle, command: str, **kwargs):
+ # Box startup and guest bridge establishment can be briefly racy.
+ for _ in range(4):
+ try:
+ return await box_handle.exec(command, **kwargs)
+ except Exception as err:
+ if "transport error" not in str(err).lower():
+ raise
+ await asyncio.sleep(0.2)
+ return await box_handle.exec(command, **kwargs)
+
+
@app.post("/v1/{prefix}/boxes/{box_id}/exec", status_code=201)
async def start_execution(
prefix: str,
@@ -932,6 +950,9 @@ async def start_execution(
req: ExecCommandRequest,
_auth: dict = Depends(require_auth),
):
+ if req.sync:
+ return await _run_sync_execution(box_id, req)
+
box_handle = await get_box_or_404(box_id)
kwargs = {}
@@ -942,22 +963,7 @@ async def start_execution(
if req.tty:
kwargs["tty"] = True
- # Box startup and guest bridge establishment can be briefly racy; retry
- # transient transport errors so exec behaves like a stable REST surface.
- execution = None
- last_error = None
- for _ in range(5):
- try:
- execution = await box_handle.exec(req.command, **kwargs)
- break
- except Exception as err:
- message = str(err).lower()
- if "transport error" not in message:
- raise
- last_error = err
- await asyncio.sleep(0.2)
- if execution is None:
- raise last_error # type: ignore[misc]
+ execution = await exec_with_transport_retry(box_handle, req.command, **kwargs)
exec_id = execution.id()
@@ -982,6 +988,137 @@ async def start_execution(
)
+async def collect_exec_output(stream, limit: int) -> tuple[str, bool]:
+ buffered = bytearray()
+ truncated = False
+ async for chunk in stream:
+ remaining = limit - len(buffered)
+ if remaining == 0:
+ # Keep draining both streams even after the capture limit is reached.
+ truncated = truncated or bool(chunk)
+ continue
+ if isinstance(chunk, str):
+ chunk = chunk.encode("utf-8")
+ buffered.extend(chunk[:remaining])
+ truncated = truncated or len(chunk) > remaining
+ return buffered.decode("utf-8", errors="replace"), truncated
+
+
+def _validate_sync_exec_request(
+ req: ExecCommandRequest,
+) -> tuple[float, int] | JSONResponse:
+ if req.stdin is not None:
+ return error_response(
+ 400,
+ "stdin is not supported for synchronous exec",
+ "InvalidArgumentError",
+ "invalid_argument",
+ )
+ if not req.command:
+ return error_response(
+ 400, "command must not be empty", "InvalidArgumentError", "invalid_argument"
+ )
+ if req.tty:
+ return error_response(
+ 400,
+ "tty is not supported when sync is true",
+ "InvalidArgumentError",
+ "invalid_argument",
+ )
+
+ timeout_seconds = 30.0 if req.timeout_seconds is None else req.timeout_seconds
+ if (
+ isinstance(timeout_seconds, bool)
+ or not isinstance(timeout_seconds, (int, float))
+ or not 0.1 <= timeout_seconds <= 300.0
+ ):
+ return error_response(
+ 400,
+ "timeout_seconds must be between 0.1 and 300",
+ "InvalidArgumentError",
+ "invalid_argument",
+ )
+
+ max_output_bytes = 1_048_576 if req.max_output_bytes is None else req.max_output_bytes
+ if (
+ isinstance(max_output_bytes, bool)
+ or not isinstance(max_output_bytes, int)
+ or max_output_bytes < 1024
+ or max_output_bytes > 10_485_760
+ ):
+ return error_response(
+ 400,
+ "max_output_bytes must be an integer between 1024 and 10485760",
+ "InvalidArgumentError",
+ "invalid_argument",
+ )
+
+ return float(timeout_seconds), max_output_bytes
+
+
+async def _run_sync_execution(box_id: str, req: ExecCommandRequest) -> JSONResponse:
+ validated = _validate_sync_exec_request(req)
+ if isinstance(validated, JSONResponse):
+ return validated
+ timeout_seconds, max_output_bytes = validated
+
+ box_handle = await get_box_or_404(box_id)
+ execution = None
+
+ async def run():
+ nonlocal execution
+ # Synchronous exec is at-most-once: never retry transport errors.
+ execution = await box_handle.exec(
+ req.command,
+ args=req.args,
+ env=list(req.env.items()) if req.env is not None else None,
+ tty=False,
+ cwd=req.working_dir,
+ user=req.user,
+ timeout_secs=timeout_seconds + 5.0,
+ )
+ stdout = execution.stdout()
+ stderr = execution.stderr()
+ stdin = execution.stdin()
+
+ async def wait():
+ await stdin.close() # Commands that read stdin should see EOF.
+ return await execution.wait()
+
+ tasks = (
+ asyncio.create_task(collect_exec_output(stdout, max_output_bytes)),
+ asyncio.create_task(collect_exec_output(stderr, max_output_bytes)),
+ asyncio.create_task(wait()),
+ )
+ try:
+ return await asyncio.gather(*tasks)
+ finally:
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+ try:
+ (stdout, stdout_truncated), (stderr, stderr_truncated), result = (
+ await asyncio.wait_for(run(), timeout=timeout_seconds)
+ )
+ except asyncio.TimeoutError:
+ if execution is not None:
+ with suppress(Exception):
+ await asyncio.wait_for(execution.kill(), timeout=1)
+ return error_response(408, "execution timed out", "TimeoutError", "timeout")
+
+ payload = {
+ "exit_code": result.exit_code,
+ "stdout": stdout,
+ "stderr": stderr,
+ "stdout_truncated": stdout_truncated,
+ "stderr_truncated": stderr_truncated,
+ }
+ if result.error_message:
+ payload["error_message"] = result.error_message
+ return JSONResponse(status_code=200, content=payload)
+
+
@app.get("/v1/{prefix}/boxes/{box_id}/executions")
async def list_executions(
prefix: str,
diff --git a/openapi/reference-server/tests/test_exec_sync.py b/openapi/reference-server/tests/test_exec_sync.py
new file mode 100644
index 000000000..951991b1b
--- /dev/null
+++ b/openapi/reference-server/tests/test_exec_sync.py
@@ -0,0 +1,201 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import unittest
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+from test_handle_cache import SERVER
+
+
+async def chunks(items):
+ for item in items:
+ yield item
+
+
+class ExecSyncTests(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self):
+ self.close_stdin = AsyncMock()
+ self.execution = SimpleNamespace(
+ id=lambda: "exec-async-1",
+ stdout=lambda: chunks(["hello\n"]),
+ stderr=lambda: chunks([b"warning\n"]),
+ stdin=lambda: SimpleNamespace(close=self.close_stdin),
+ wait=AsyncMock(return_value=SimpleNamespace(exit_code=0, error_message=None)),
+ kill=AsyncMock(),
+ )
+ self.box = SimpleNamespace(id="test-box", exec=AsyncMock(return_value=self.execution))
+ self.runtime = SimpleNamespace(get=AsyncMock(return_value=None))
+ for patcher in (
+ patch.object(SERVER, "state", SERVER.AppState()),
+ patch.dict(SERVER.app.dependency_overrides, {SERVER.require_auth: lambda: {}}),
+ ):
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ SERVER.state.runtime = self.runtime
+ SERVER.state.active_boxes_by_id["test-box"] = self.box
+
+ async def post(self, payload, box_id="test-box"):
+ # Call the ASGI app directly to exercise routing and validation without httpx.
+ return await self.request("POST", f"/v1/demo/boxes/{box_id}/exec", payload)
+
+ async def request(self, method, path, payload=None):
+ messages = []
+
+ async def receive():
+ body = b"" if payload is None else json.dumps(payload).encode()
+ return {"type": "http.request", "body": body}
+
+ async def send(message):
+ messages.append(message)
+
+ await SERVER.app({
+ "type": "http", "method": method, "path": path,
+ "headers": [(b"content-type", b"application/json")],
+ "query_string": b"",
+ }, receive, send)
+ return messages[0]["status"], json.loads(messages[1]["body"])
+
+ async def test_config_advertises_sync_exec(self):
+ status, payload = await self.request("GET", "/v1/config")
+ self.assertEqual(status, 200)
+ self.assertIs(payload["capabilities"]["sync_exec_enabled"], True)
+
+ async def test_sync_rejects_stdin_even_when_empty(self):
+ for stdin in ("input", ""):
+ with self.subTest(stdin=stdin):
+ status, payload = await self.post({"command": "echo", "sync": True, "stdin": stdin})
+ self.assertEqual(status, 400)
+ self.assertEqual(payload["error"]["type"], "InvalidArgumentError")
+ self.assertEqual(payload["error"]["code"], "invalid_argument")
+ self.box.exec.assert_not_awaited()
+
+ async def test_async_backward_compatible_when_sync_omitted_or_false(self):
+ for extra in ({}, {"sync": False}):
+ with self.subTest(extra=extra):
+ status, payload = await self.post({"command": "echo", **extra})
+ self.assertEqual(status, 201)
+ self.assertEqual(payload, {"execution_id": "exec-async-1"})
+
+ async def test_success_forwards_sdk_options_and_closes_stdin(self):
+ status, payload = await self.post({
+ "command": "echo", "args": ["hello"], "env": {"LANG": "C"},
+ "timeout_seconds": 12.0, "working_dir": "/tmp", "user": "1000:1000",
+ "sync": True,
+ })
+ self.assertEqual(status, 200)
+ self.assertEqual(payload, {
+ "exit_code": 0, "stdout": "hello\n", "stderr": "warning\n",
+ "stdout_truncated": False, "stderr_truncated": False,
+ })
+ self.box.exec.assert_awaited_once_with(
+ "echo", args=["hello"], env=[("LANG", "C")], tty=False,
+ cwd="/tmp", user="1000:1000", timeout_secs=17.0,
+ )
+ self.close_stdin.assert_awaited_once()
+ self.assertFalse(SERVER.state.active_executions)
+
+ async def test_nonzero_exit_is_a_result(self):
+ self.execution.wait.return_value = SimpleNamespace(
+ exit_code=127, error_message="command not found",
+ )
+ self.execution.stderr = lambda: chunks([b"unknown command\n"])
+ status, payload = await self.post({"command": "unknown", "sync": True})
+ self.assertEqual(status, 200)
+ self.assertEqual(payload["exit_code"], 127)
+ self.assertEqual(payload["stderr"], "unknown command\n")
+ self.assertEqual(payload["error_message"], "command not found")
+
+ async def test_each_stream_is_bounded_and_drained_concurrently_with_wait(self):
+ waiting, stdout_drained, stderr_drained = (asyncio.Event() for _ in range(3))
+
+ async def stream(first, overflow, drained):
+ await waiting.wait()
+ yield first
+ yield overflow
+ yield b"discard this too"
+ drained.set()
+
+ async def wait():
+ waiting.set()
+ await stdout_drained.wait()
+ await stderr_drained.wait()
+ return SimpleNamespace(exit_code=0, error_message=None)
+
+ self.execution.stdout = lambda: stream(b"a" * 1024, b"overflow", stdout_drained)
+ self.execution.stderr = lambda: stream("é" * 513, "overflow", stderr_drained)
+ self.execution.wait.side_effect = wait
+ status, payload = await self.post({
+ "command": "echo", "max_output_bytes": 1024, "timeout_seconds": 1, "sync": True,
+ })
+ self.assertEqual(status, 200)
+ self.assertEqual(payload["stdout"], "a" * 1024)
+ self.assertEqual(payload["stderr"], "é" * 512)
+ self.assertIs(payload["stdout_truncated"], True)
+ self.assertIs(payload["stderr_truncated"], True)
+ self.assertTrue(stdout_drained.is_set() and stderr_drained.is_set())
+
+ async def test_invalid_utf8_and_exact_limit(self):
+ self.execution.stdout = lambda: chunks([b"\xffa", b"\xe2", b"\x82\xac"])
+ self.execution.stderr = lambda: chunks([b"b" * 1024, b""])
+ status, payload = await self.post({
+ "command": "echo", "max_output_bytes": 1024, "sync": True,
+ })
+ self.assertEqual(status, 200)
+ self.assertEqual(payload["stdout"], "\ufffda€")
+ self.assertEqual(payload["stderr"], "b" * 1024)
+ self.assertIs(payload["stdout_truncated"], False)
+ self.assertIs(payload["stderr_truncated"], False)
+
+ async def test_timeout_kills_execution_and_cleans_up_readers(self):
+ blocked = asyncio.Event()
+ closed = []
+
+ async def stream(name):
+ try:
+ await blocked.wait()
+ yield b""
+ finally:
+ closed.append(name)
+
+ self.execution.stdout = lambda: stream("stdout")
+ self.execution.stderr = lambda: stream("stderr")
+ self.execution.wait.side_effect = blocked.wait
+ self.execution.kill.side_effect = RuntimeError("already exited")
+ status, payload = await self.post({
+ "command": "sleep", "timeout_seconds": 0.1, "sync": True,
+ })
+ self.assertEqual(status, 408)
+ self.assertEqual(payload, {"error": {
+ "message": "execution timed out", "type": "TimeoutError", "code": "timeout",
+ }})
+ self.execution.kill.assert_awaited_once()
+ self.assertCountEqual(closed, ["stdout", "stderr"])
+
+ async def test_does_not_retry_transient_transport_error(self):
+ self.box.exec.side_effect = [RuntimeError("gRPC transport error: retry"), self.execution]
+ status, payload = await self.post({"command": "echo", "sync": True})
+ self.assertEqual(status, 503)
+ self.assertEqual(payload["error"]["code"], "upstream_unavailable")
+ self.assertEqual(self.box.exec.await_count, 1)
+
+ async def test_invalid_requests_never_start_execution(self):
+ for fields in (
+ {"command": ""}, {"timeout_seconds": 0.09}, {"timeout_seconds": 301},
+ {"timeout_seconds": True}, {"timeout_seconds": False},
+ {"max_output_bytes": -1}, {"max_output_bytes": 1023},
+ {"max_output_bytes": 10485761}, {"max_output_bytes": 1024.5},
+ {"max_output_bytes": True}, {"max_output_bytes": False}, {"tty": True},
+ ):
+ with self.subTest(fields=fields):
+ status, payload = await self.post({"command": "echo", "sync": True, **fields})
+ self.assertEqual(status, 400)
+ self.assertEqual(payload["error"]["code"], "invalid_argument")
+ self.box.exec.assert_not_awaited()
+
+ async def test_missing_box_returns_404(self):
+ status, _ = await self.post({"command": "echo", "sync": True}, box_id="missing")
+ self.assertEqual(status, 404)
+ self.runtime.get.assert_awaited_once_with("missing")
+ self.box.exec.assert_not_awaited()
diff --git a/openapi/tests/test_exec_sync_spec.py b/openapi/tests/test_exec_sync_spec.py
new file mode 100644
index 000000000..2758c950f
--- /dev/null
+++ b/openapi/tests/test_exec_sync_spec.py
@@ -0,0 +1,78 @@
+"""Check the synchronous execution wire contract on POST /exec."""
+import unittest
+from pathlib import Path
+
+import yaml
+
+SPEC = yaml.safe_load((Path(__file__).resolve().parents[1] / "box.openapi.yaml").read_text())
+SCHEMAS = SPEC["components"]["schemas"]
+EXEC_PATH = "/{prefix}/boxes/{box_id}/exec"
+
+
+class ExecSyncSpecTests(unittest.TestCase):
+ def test_route_and_responses(self):
+ self.assertNotIn(f"{EXEC_PATH}/sync", SPEC["paths"])
+ self.assertNotIn("SyncExecRequest", SCHEMAS)
+
+ post = SPEC["paths"][EXEC_PATH]["post"]
+ self.assertEqual(post["operationId"], "startExecution")
+ self.assertEqual(post["tags"], ["Execution"])
+ self.assertEqual(post.get("security", SPEC["security"]), [{"BearerAuth": []}])
+
+ body = post["requestBody"]
+ self.assertTrue(body["required"])
+ self.assertEqual(body["content"]["application/json"]["schema"], {
+ "$ref": "#/components/schemas/ExecRequest",
+ })
+
+ responses = post["responses"]
+ self.assertEqual(responses["200"]["content"]["application/json"]["schema"], {
+ "$ref": "#/components/schemas/SyncExecResponse",
+ })
+ self.assertEqual(responses["201"]["content"]["application/json"]["schema"], {
+ "$ref": "#/components/schemas/ExecResponse",
+ })
+ for status, name in {
+ "400": "BadRequestError",
+ "404": "NotFoundError",
+ "408": "RequestTimeoutError",
+ "409": "ConflictError",
+ }.items():
+ with self.subTest(status=status):
+ self.assertEqual(responses[status], {"$ref": f"#/components/responses/{name}"})
+ self.assertIn(name, SPEC["components"]["responses"])
+
+ def test_exec_request_sync_fields_and_limits(self):
+ request = SCHEMAS["ExecRequest"]
+ self.assertEqual(request["required"], ["command"])
+ fields = request["properties"]
+ self.assertIn("sync", fields)
+ self.assertEqual(fields["sync"]["type"], "boolean")
+ self.assertIs(fields["sync"]["default"], False)
+
+ timeout = fields["timeout_seconds"]
+ self.assertEqual(timeout["minimum"], 0.1)
+ self.assertIn("`sync: true`", timeout["description"])
+ self.assertIn("0.1 to 300 seconds", timeout["description"])
+ self.assertIn("return HTTP 400", timeout["description"])
+
+ max_output = fields["max_output_bytes"]
+ self.assertEqual(
+ tuple(max_output[k] for k in ("type", "minimum", "maximum", "default")),
+ ("integer", 1024, 10485760, 1048576),
+ )
+
+ def test_config_advertises_optional_sync_exec_capability(self):
+ capabilities = SCHEMAS["ServerConfig"]["properties"]["capabilities"]
+ self.assertEqual(capabilities["properties"]["sync_exec_enabled"]["type"], "boolean")
+ self.assertNotIn("sync_exec_enabled", capabilities.get("required", []))
+
+ def test_response_required_fields(self):
+ response = SCHEMAS["SyncExecResponse"]
+ self.assertCountEqual(response["required"], [
+ "exit_code", "stdout", "stderr", "stdout_truncated", "stderr_truncated",
+ ])
+ self.assertEqual({k: v["type"] for k, v in response["properties"].items()}, {
+ "exit_code": "integer", "stdout": "string", "stderr": "string",
+ "stdout_truncated": "boolean", "stderr_truncated": "boolean", "error_message": "string",
+ })
diff --git a/src/boxlite/src/lib.rs b/src/boxlite/src/lib.rs
index f41cd17a3..0c5487375 100644
--- a/src/boxlite/src/lib.rs
+++ b/src/boxlite/src/lib.rs
@@ -60,7 +60,8 @@ pub use litebox::snapshot_mgr::SnapshotInfo;
pub use litebox::{
AttachOptions, BoxCommand, CopyOptions, ExecResult, ExecStderr, ExecStdin, ExecStdout,
Execution, ExecutionId, ExecutionInfo, ExecutionsHandle, HealthState, HealthStatus,
- MountHandle, MountInfo, MountRequest, MountState,
+ MountHandle, MountInfo, MountRequest, MountState, SyncExecResult, collect_sync_execution,
+ validate_sync_exec,
};
pub use litebox::{SshAccount, SshCaConfig, SshConfig, SshHandle, SshStatus};
pub use metrics::{BoxMetrics, RuntimeMetrics};
diff --git a/src/boxlite/src/litebox/box_impl.rs b/src/boxlite/src/litebox/box_impl.rs
index 39db834e6..6872e3888 100644
--- a/src/boxlite/src/litebox/box_impl.rs
+++ b/src/boxlite/src/litebox/box_impl.rs
@@ -18,7 +18,10 @@ use boxlite_shared::errors::{BoxliteError, BoxliteResult};
use super::attach::AttachOptions;
use super::config::BoxConfig;
-use super::exec::{BoxCommand, ExecStderr, ExecStdin, ExecStdout, Execution};
+use super::exec::{
+ BoxCommand, ExecStderr, ExecStdin, ExecStdout, Execution, SyncExecResult,
+ collect_sync_execution,
+};
use super::state::BoxState;
use crate::disk::Disk;
use crate::event_listener::EventListener;
@@ -608,7 +611,8 @@ impl BoxImpl {
components.stdin_tx.map(ExecStdin::new),
Some(ExecStdout::new(components.stdout_rx)),
Some(ExecStderr::new(components.stderr_rx)),
- ))
+ )
+ .with_output_drops(components.output_drops))
}
/// The guest writes init's exit code before powering the VM off. Recover
@@ -736,7 +740,8 @@ impl BoxImpl {
components.stdin_tx.map(ExecStdin::new),
Some(ExecStdout::new(components.stdout_rx)),
Some(ExecStderr::new(components.stderr_rx)),
- ))
+ )
+ .with_output_drops(components.output_drops))
}
/// Live sessions in the box. Inactive boxes have none; paused boxes reject
@@ -1819,6 +1824,31 @@ impl crate::runtime::backend::BoxBackend for BoxImpl {
self.resize(options).await
}
+ async fn exec_sync(
+ &self,
+ mut command: BoxCommand,
+ max_output_bytes: Option<usize>,
+ ) -> BoxliteResult<SyncExecResult> {
+ let (timeout, limit) = command.sync_exec_limits(max_output_bytes)?;
+ // Let the host deadline fire first, but keep a guest fallback on cancellation.
+ command.timeout = Some(timeout + Duration::from_secs(5));
+ let mut execution = None;
+ let result = tokio::time::timeout(timeout, async {
+ let execution = execution.insert(self.exec(command).await?);
+ collect_sync_execution(execution, limit).await
+ })
+ .await;
+ match result {
+ Ok(result) => result,
+ Err(_) => {
+ if let Some(execution) = execution {
+ let _ = tokio::time::timeout(Duration::from_secs(1), execution.kill()).await;
+ }
+ Err(BoxliteError::Internal("execution timed out".into()))
+ }
+ }
+ }
+
async fn exec(&self, command: BoxCommand) -> BoxliteResult<Execution> {
self.exec(command).await
}
diff --git a/src/boxlite/src/litebox/exec.rs b/src/boxlite/src/litebox/exec.rs
index 74068a000..dbbd7230a 100644
--- a/src/boxlite/src/litebox/exec.rs
+++ b/src/boxlite/src/litebox/exec.rs
@@ -4,14 +4,55 @@
//! The actual execution logic is in BoxImpl::exec().
use crate::BoxliteError;
+use crate::portal::interfaces::exec::OutputDrops;
use crate::runtime::backend::ExecBackend;
use boxlite_shared::errors::BoxliteResult;
-use futures::Stream;
+use futures::{Stream, StreamExt};
use std::pin::Pin;
+use std::sync::atomic::Ordering;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::sync::mpsc;
+pub const DEFAULT_SYNC_EXEC_TIMEOUT_SECS: f64 = 30.0;
+pub const MIN_SYNC_EXEC_TIMEOUT_SECS: f64 = 0.1;
+pub const MAX_SYNC_EXEC_TIMEOUT_SECS: f64 = 300.0;
+pub const DEFAULT_SYNC_EXEC_MAX_OUTPUT_BYTES: usize = 1024 * 1024;
+pub const MIN_SYNC_EXEC_MAX_OUTPUT_BYTES: usize = 1024;
+pub const MAX_SYNC_EXEC_MAX_OUTPUT_BYTES: usize = 10 * 1024 * 1024;
+
+/// Validate synchronous exec parameters and resolve their defaults.
+pub fn validate_sync_exec(
+ command: &str,
+ tty: bool,
+ timeout_seconds: Option<f64>,
+ max_output_bytes: Option<usize>,
+) -> BoxliteResult<(Duration, usize)> {
+ if command.is_empty() {
+ return Err(BoxliteError::InvalidArgument(
+ "command must not be empty".into(),
+ ));
+ }
+ if tty {
+ return Err(BoxliteError::InvalidArgument(
+ "exec_sync does not support tty".into(),
+ ));
+ }
+ let seconds = timeout_seconds.unwrap_or(DEFAULT_SYNC_EXEC_TIMEOUT_SECS);
+ if !(MIN_SYNC_EXEC_TIMEOUT_SECS..=MAX_SYNC_EXEC_TIMEOUT_SECS).contains(&seconds) {
+ return Err(BoxliteError::InvalidArgument(format!(
+ "timeout_seconds must be in {MIN_SYNC_EXEC_TIMEOUT_SECS}..={MAX_SYNC_EXEC_TIMEOUT_SECS}"
+ )));
+ }
+ let limit = max_output_bytes.unwrap_or(DEFAULT_SYNC_EXEC_MAX_OUTPUT_BYTES);
+ if !(MIN_SYNC_EXEC_MAX_OUTPUT_BYTES..=MAX_SYNC_EXEC_MAX_OUTPUT_BYTES).contains(&limit) {
+ return Err(BoxliteError::InvalidArgument(format!(
+ "max_output_bytes must be in {MIN_SYNC_EXEC_MAX_OUTPUT_BYTES}..={MAX_SYNC_EXEC_MAX_OUTPUT_BYTES}"
+ )));
+ }
+ Ok((Duration::from_secs_f64(seconds), limit))
+}
+
/// Command builder for executing programs in a box.
///
/// Provides a builder API similar to `std::process::Command`.
@@ -39,6 +80,18 @@ pub struct BoxCommand {
}
impl BoxCommand {
+ pub(crate) fn sync_exec_limits(
+ &self,
+ max_output_bytes: Option<usize>,
+ ) -> BoxliteResult<(Duration, usize)> {
+ validate_sync_exec(
+ &self.command,
+ self.tty,
+ self.timeout.map(|d| d.as_secs_f64()),
+ max_output_bytes,
+ )
+ }
+
/// Create a new command.
pub fn new(command: impl Into<String>) -> Self {
Self {
@@ -150,6 +203,7 @@ pub struct Execution {
/// Result-channel state held on a separate lock so a parked `wait()`
/// can never block `kill()`/`signal()`/`resize_tty()`.
wait_state: std::sync::Arc<WaitState>,
+ output_drops: Option<OutputDrops>,
}
pub(crate) struct ExecutionInner {
@@ -218,9 +272,15 @@ impl Execution {
id: execution_id,
inner: std::sync::Arc::new(tokio::sync::Mutex::new(inner)),
wait_state: std::sync::Arc::new(wait_state),
+ output_drops: None,
}
}
+ pub(crate) fn with_output_drops(mut self, drops: OutputDrops) -> Self {
+ self.output_drops = Some(drops);
+ self
+ }
+
/// Get the execution ID.
pub fn id(&self) -> &ExecutionId {
&self.id
@@ -318,12 +378,32 @@ impl Execution {
mpsc::UnboundedSender<String>,
mpsc::UnboundedReceiver<Vec<u8>>,
mpsc::UnboundedSender<ExecResult>,
+ ) {
+ Self::stub_with_kill_hook(id, || {})
+ }
+
+ /// Build a stub that invokes a hook when killed.
+ #[cfg(feature = "test-support")]
+ #[allow(clippy::type_complexity)]
+ pub fn stub_with_kill_hook(
+ id: &str,
+ on_kill: impl FnMut() + Send + Sync + 'static,
+ ) -> (
+ Self,
+ mpsc::UnboundedSender<String>,
+ mpsc::UnboundedSender<String>,
+ mpsc::UnboundedReceiver<Vec<u8>>,
+ mpsc::UnboundedSender<ExecResult>,
) {
use async_trait::async_trait;
- struct NoopBackend;
+ struct StubBackend<F>(F);
#[async_trait]
- impl ExecBackend for NoopBackend {
+ impl<F: FnMut() + Send + Sync> ExecBackend for StubBackend<F> {
+ async fn kill(&mut self, _: &str) -> BoxliteResult<()> {
+ (self.0)();
+ Ok(())
+ }
async fn signal(&mut self, _: &str, _: i32) -> BoxliteResult<()> {
Ok(())
}
@@ -346,7 +426,7 @@ impl Execution {
let exec = Self::new(
id.to_string(),
- Box::new(NoopBackend),
+ Box::new(StubBackend(on_kill)),
result_rx,
Some(ExecStdin::new(stdin_tx)),
Some(ExecStdout::new(stdout_rx)),
@@ -356,6 +436,72 @@ impl Execution {
}
}
+/// Exit status and bounded output of a non-interactive execution.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SyncExecResult {
+ pub exit_code: i32,
+ pub stdout: String,
+ pub stderr: String,
+ pub stdout_truncated: bool,
+ pub stderr_truncated: bool,
+ pub error_message: Option<String>,
+}
+
+/// Close stdin and collect both output streams while waiting for exit.
+/// The limit applies independently to the bytes exposed by each `Execution`
+/// output stream. The captured prefix is decoded lossily if it cuts a code point.
+pub async fn collect_sync_execution(
+ execution: &mut Execution,
+ max_output_bytes: usize,
+) -> BoxliteResult<SyncExecResult> {
+ drop(execution.stdin());
+ let stdout = execution.stdout();
+ let stderr = execution.stderr();
+ let output = async {
+ Ok(tokio::join!(
+ capture_output(stdout, max_output_bytes),
+ capture_output(stderr, max_output_bytes),
+ ))
+ };
+ let (exit, ((stdout, stdout_truncated), (stderr, stderr_truncated))) =
+ tokio::try_join!(execution.wait(), output)?;
+ // Read the drop markers after EOF so late gap reports are included.
+ let (stdout_dropped, stderr_dropped) =
+ execution
+ .output_drops
+ .as_ref()
+ .map_or((false, false), |drops| {
+ (
+ drops.stdout.load(Ordering::Relaxed),
+ drops.stderr.load(Ordering::Relaxed),
+ )
+ });
+ Ok(SyncExecResult {
+ exit_code: exit.exit_code,
+ stdout,
+ stderr,
+ stdout_truncated: stdout_truncated || stdout_dropped,
+ stderr_truncated: stderr_truncated || stderr_dropped,
+ error_message: exit.error_message,
+ })
+}
+
+async fn capture_output(
+ stream: Option<impl Stream<Item = String> + Unpin>,
+ limit: usize,
+) -> (String, bool) {
+ let mut bytes = Vec::new();
+ let mut truncated = false;
+ if let Some(mut stream) = stream {
+ while let Some(chunk) = stream.next().await {
+ let keep = chunk.len().min(limit - bytes.len());
+ bytes.extend_from_slice(&chunk.as_bytes()[..keep]);
+ truncated |= keep < chunk.len();
+ }
+ }
+ (String::from_utf8_lossy(&bytes).into_owned(), truncated)
+}
+
/// Exit status of a process.
#[derive(Clone, Debug)]
pub struct ExecResult {
@@ -548,6 +694,122 @@ mod tests {
}
}
+ #[test]
+ fn sync_exec_validates_parameters() {
+ assert_eq!(
+ validate_sync_exec("true", false, None, None).unwrap(),
+ (Duration::from_secs(30), 1024 * 1024)
+ );
+ for (command, tty, timeout, limit) in [
+ ("", false, None, None),
+ ("true", true, None, None),
+ ("true", false, Some(0.099), None),
+ ("true", false, Some(300.001), None),
+ ("true", false, Some(f64::NAN), None),
+ ("true", false, Some(f64::INFINITY), None),
+ ("true", false, None, Some(1023)),
+ ("true", false, None, Some(10 * 1024 * 1024 + 1)),
+ ] {
+ assert!(matches!(
+ validate_sync_exec(command, tty, timeout, limit),
+ Err(BoxliteError::InvalidArgument(_))
+ ));
+ }
+ for (seconds, limit) in [(0.1, 1024), (300.0, 10 * 1024 * 1024)] {
+ assert!(validate_sync_exec("true", false, Some(seconds), Some(limit)).is_ok());
+ }
+ }
+
+ #[tokio::test]
+ async fn sync_exec_collects_until_eof_even_after_truncation() {
+ for (limit, expected, truncated, code) in [(32, "abé-tail", false, 0), (3, "ab�", true, 7)]
+ {
+ let (stdout_tx, stdout_rx) = mpsc::unbounded_channel();
+ let (stderr_tx, stderr_rx) = mpsc::unbounded_channel();
+ let (stdin_tx, mut stdin_rx) = mpsc::unbounded_channel();
+ let (result_tx, result_rx) = mpsc::unbounded_channel();
+ let mut execution = Execution::new(
+ "sync".into(),
+ Box::new(StubExecBackend {
+ kill_observed: StdArc::default(),
+ }),
+ result_rx,
+ Some(ExecStdin::new(stdin_tx)),
+ Some(ExecStdout::new(stdout_rx)),
+ Some(ExecStderr::new(stderr_rx)),
+ );
+ let error_message = (code != 0).then(|| "exit diagnostic".to_string());
+ let producer = async {
+ assert!(stdin_rx.recv().await.is_none());
+ result_tx
+ .send(ExecResult {
+ exit_code: code,
+ error_message: error_message.clone(),
+ })
+ .unwrap();
+ stdout_tx.send("abé".into()).unwrap();
+ tokio::task::yield_now().await;
+ stdout_tx.send("-tail".into()).unwrap();
+ stderr_tx.send("err".into()).unwrap();
+ drop((stdout_tx, stderr_tx));
+ };
+ let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
+ tokio::join!(collect_sync_execution(&mut execution, limit), producer)
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ result.unwrap(),
+ SyncExecResult {
+ exit_code: code,
+ stdout: expected.into(),
+ stderr: "err".into(),
+ stdout_truncated: truncated,
+ stderr_truncated: false,
+ error_message,
+ }
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn sync_exec_reports_guest_drops_below_the_capture_limit() {
+ for (stdout_dropped, stderr_dropped) in [(true, false), (false, true)] {
+ let (stdout_tx, stdout_rx) = mpsc::unbounded_channel();
+ let (stderr_tx, stderr_rx) = mpsc::unbounded_channel();
+ let (result_tx, result_rx) = mpsc::unbounded_channel();
+ let mut execution = Execution::new(
+ "sync".into(),
+ Box::new(StubExecBackend {
+ kill_observed: StdArc::default(),
+ }),
+ result_rx,
+ None,
+ Some(ExecStdout::new(stdout_rx)),
+ Some(ExecStderr::new(stderr_rx)),
+ )
+ .with_output_drops(OutputDrops {
+ stdout: StdArc::new(AtomicBool::new(stdout_dropped)),
+ stderr: StdArc::new(AtomicBool::new(stderr_dropped)),
+ });
+ stdout_tx.send("out".into()).unwrap();
+ stderr_tx.send("err".into()).unwrap();
+ result_tx
+ .send(ExecResult {
+ exit_code: 0,
+ error_message: None,
+ })
+ .unwrap();
+ drop((stdout_tx, stderr_tx, result_tx));
+
+ let result = collect_sync_execution(&mut execution, 1024).await.unwrap();
+ assert_eq!(result.stdout, "out");
+ assert_eq!(result.stderr, "err");
+ assert_eq!(result.stdout_truncated, stdout_dropped);
+ assert_eq!(result.stderr_truncated, stderr_dropped);
+ }
+ }
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn wait_does_not_block_kill() {
let (_result_tx, result_rx) = tokio_mpsc::unbounded_channel::<ExecResult>();
diff --git a/src/boxlite/src/litebox/mod.rs b/src/boxlite/src/litebox/mod.rs
index 7a2e4d709..957518986 100644
--- a/src/boxlite/src/litebox/mod.rs
+++ b/src/boxlite/src/litebox/mod.rs
@@ -28,8 +28,10 @@ pub use attach::AttachOptions;
pub use copy::CopyOptions;
pub(crate) use crash_report::CrashReport;
pub use exec::{
- BoxCommand, ExecResult, ExecStderr, ExecStdin, ExecStdout, Execution, ExecutionId,
- ExecutionInfo,
+ BoxCommand, DEFAULT_SYNC_EXEC_MAX_OUTPUT_BYTES, DEFAULT_SYNC_EXEC_TIMEOUT_SECS, ExecResult,
+ ExecStderr, ExecStdin, ExecStdout, Execution, ExecutionId, ExecutionInfo,
+ MAX_SYNC_EXEC_MAX_OUTPUT_BYTES, MAX_SYNC_EXEC_TIMEOUT_SECS, MIN_SYNC_EXEC_MAX_OUTPUT_BYTES,
+ MIN_SYNC_EXEC_TIMEOUT_SECS, SyncExecResult, collect_sync_execution, validate_sync_exec,
};
pub use executions::ExecutionsHandle;
pub(crate) use manager::BoxManager;
@@ -137,6 +139,24 @@ impl LiteBox {
self.box_backend.exec(command).await
}
+ /// Run a non-interactive command to completion with a 1 MiB capture limit per stream.
+ /// The command timeout defaults to 30 seconds.
+ pub async fn exec_sync(&self, command: BoxCommand) -> BoxliteResult<SyncExecResult> {
+ self.box_backend.exec_sync(command, None).await
+ }
+
+ /// Run a non-interactive command with a custom capture limit per stream.
+ /// The limit must be between 1 KiB and 10 MiB, inclusive.
+ pub async fn exec_sync_with_limit(
+ &self,
+ command: BoxCommand,
+ max_output_bytes: usize,
+ ) -> BoxliteResult<SyncExecResult> {
+ self.box_backend
+ .exec_sync(command, Some(max_output_bytes))
+ .await
+ }
+
/// Get the live execution namespace without starting the box.
/// See [`ExecutionsHandle`].
pub fn executions(&self) -> ExecutionsHandle {
diff --git a/src/boxlite/src/portal/interfaces/exec.rs b/src/boxlite/src/portal/interfaces/exec.rs
index 0928c964e..28ce1afa2 100644
--- a/src/boxlite/src/portal/interfaces/exec.rs
+++ b/src/boxlite/src/portal/interfaces/exec.rs
@@ -3,6 +3,9 @@
//! High-level API for execution operations (unary Exec + output-only Attach +
//! blocking Wait).
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+
use crate::litebox::{BoxCommand, ExecResult};
use boxlite_shared::{
AttachRequest, BoxliteError, BoxliteResult, ExecOutput, ExecRequest, ExecStdin,
@@ -28,6 +31,13 @@ pub struct ExecComponents {
pub stdout_rx: mpsc::UnboundedReceiver<String>,
pub stderr_rx: mpsc::UnboundedReceiver<String>,
pub result_rx: mpsc::UnboundedReceiver<ExecResult>,
+ pub(crate) output_drops: OutputDrops,
+}
+
+#[derive(Clone)]
+pub(crate) struct OutputDrops {
+ pub stdout: Arc<AtomicBool>,
+ pub stderr: Arc<AtomicBool>,
}
impl ExecutionInterface {
@@ -125,7 +135,7 @@ impl ExecutionInterface {
);
// Spawn attach fanout (cancellable)
- ExecProtocol::spawn_attach(
+ let output_drops = ExecProtocol::spawn_attach(
self.client.clone(),
execution_id.clone(),
stdout_tx,
@@ -148,6 +158,7 @@ impl ExecutionInterface {
stdout_rx,
stderr_rx,
result_rx,
+ output_drops,
})
}
@@ -203,7 +214,7 @@ impl ExecutionInterface {
None
};
- ExecProtocol::spawn_attach(
+ let output_drops = ExecProtocol::spawn_attach(
self.client.clone(),
execution_id.clone(),
stdout_tx,
@@ -224,6 +235,7 @@ impl ExecutionInterface {
stdout_rx,
stderr_rx,
result_rx,
+ output_drops,
})
}
@@ -385,7 +397,15 @@ impl ExecProtocol {
stderr_tx: mpsc::UnboundedSender<String>,
shutdown_token: CancellationToken,
connected: Option<tonic::Streaming<ExecOutput>>,
- ) {
+ ) -> OutputDrops {
+ let stdout_closed = stdout_tx.clone();
+ let stderr_closed = stderr_tx.clone();
+ let mut stdout = OutputTracker::new(stdout_tx);
+ let mut stderr = OutputTracker::new(stderr_tx);
+ let output_drops = OutputDrops {
+ stdout: Arc::clone(&stdout.dropped),
+ stderr: Arc::clone(&stderr.dropped),
+ };
tokio::spawn(async move {
let request = AttachRequest {
execution_id: execution_id.clone(),
@@ -417,11 +437,6 @@ impl ExecProtocol {
// cut, doubling visible columns and desyncing TUI cursor
// math (see https://github.com/.../issues/...). Holding
// the trailing partial across chunks fixes this.
- let stdout_closed = stdout_tx.clone();
- let stderr_closed = stderr_tx.clone();
- let mut stdout = OutputTracker::new(stdout_tx);
- let mut stderr = OutputTracker::new(stderr_tx);
-
loop {
// Use select! to handle cancellation while streaming
let output = tokio::select! {
@@ -490,10 +505,11 @@ impl ExecProtocol {
}
Err(e) => {
tracing::debug!(execution_id = %execution_id, error = %e, "Attach failed");
- let _ = stderr_tx.send(format!("Attach failed: {}", e));
+ let _ = stderr.stream.tx.send(format!("Attach failed: {}", e));
}
}
});
+ output_drops
}
fn route_output(output: ExecOutput, stdout: &mut OutputTracker, stderr: &mut OutputTracker) {
@@ -546,6 +562,7 @@ impl ExecProtocol {
}
fn report_gap(output: &mut OutputTracker, source: &str, lost_bytes: u64) {
+ output.dropped.store(true, Ordering::Relaxed);
tracing::warn!(
source,
lost_bytes,
@@ -860,6 +877,7 @@ impl DecodedStream {
struct OutputTracker {
expected_offset: u64,
stream: DecodedStream,
+ dropped: Arc<AtomicBool>,
}
enum ReceivedOutput {
@@ -878,6 +896,7 @@ impl OutputTracker {
Self {
expected_offset: 0,
stream: DecodedStream::new(tx),
+ dropped: Arc::default(),
}
}
@@ -1436,6 +1455,8 @@ mod tests {
);
assert_eq!(stdout_rx.try_recv().ok(), Some("after-gap".to_string()));
assert_eq!(stderr_rx.try_recv().ok(), Some("─".to_string()));
+ assert!(stdout.dropped.load(Ordering::Relaxed));
+ assert!(!stderr.dropped.load(Ordering::Relaxed));
}
#[test]
diff --git a/src/boxlite/src/rest/client.rs b/src/boxlite/src/rest/client.rs
index 70a1738e7..030536a80 100644
--- a/src/boxlite/src/rest/client.rs
+++ b/src/boxlite/src/rest/client.rs
@@ -14,7 +14,10 @@ use boxlite_shared::errors::{BoxliteError, BoxliteResult};
use super::credential::{AccessToken, Credential};
use super::error::{map_http_body, map_plain_reply};
use super::options::BoxliteRestOptions;
-use super::types::{BoxResponse, CreateBoxRequest, ServerConfig};
+use super::types::{
+ BoxResponse, CreateBoxRequest, ExecRequest, ExecResponse, ServerCapabilities, ServerConfig,
+ SyncExecResponse,
+};
use crate::runtime::auth::Principal;
use crate::runtime::cpu_count::CpuCount;
@@ -275,6 +278,10 @@ impl ApiClient {
let builder = self.authorize(builder).await?;
let resp = builder.send().await.map_err(transport_error)?;
+ self.decode_json(resp).await
+ }
+
+ async fn decode_json<T: DeserializeOwned>(&self, resp: reqwest::Response) -> BoxliteResult<T> {
let status = resp.status();
if !status.is_success() {
return self.handle_error(status, resp).await;
@@ -366,6 +373,29 @@ impl ApiClient {
self.send_json(builder).await
}
+ pub async fn post_sync_exec(
+ &self,
+ path: &str,
+ body: &ExecRequest,
+ timeout: Duration,
+ ) -> BoxliteResult<SyncExecResponse> {
+ let builder = self.http.post(self.url(path)).json(body).timeout(timeout);
+ let builder = self.authorize(builder).await?;
+ let resp = builder.send().await.map_err(transport_error)?;
+ if resp.status() == StatusCode::CREATED {
+ let execution_id = resp
+ .json::<ExecResponse>()
+ .await
+ .ok()
+ .map(|result| format!(" (execution_id: {})", result.execution_id))
+ .unwrap_or_default();
+ return Err(BoxliteError::Internal(format!(
+ "sync exec received HTTP 201 Created: the server started an asynchronous execution{execution_id}; do not blindly retry"
+ )));
+ }
+ self.decode_json(resp).await
+ }
+
pub(crate) async fn post_agent<T: DeserializeOwned>(
&self,
path: &str,
@@ -769,16 +799,20 @@ impl ApiClient {
self.get_root("/me").await
}
+ async fn capabilities(&self) -> BoxliteResult<ServerCapabilities> {
+ Ok(self.get_config().await?.capabilities.unwrap_or_default())
+ }
+
pub async fn require_snapshots_enabled(&self) -> BoxliteResult<()> {
- let config = self.get_config().await?;
- let capabilities = config.capabilities.ok_or_else(|| {
- BoxliteError::Unsupported(
- "Remote server did not advertise snapshots capability".to_string(),
- )
- })?;
+ let capabilities = self.capabilities().await?;
ensure_capability("snapshots", capabilities.snapshots_enabled)
}
+ pub async fn require_sync_exec_enabled(&self) -> BoxliteResult<()> {
+ let capabilities = self.capabilities().await?;
+ ensure_capability("sync exec", capabilities.sync_exec_enabled)
+ }
+
pub async fn require_linux_capabilities_enabled(&self) -> BoxliteResult<()> {
// This gate protects a security policy, so a cached positive response
// is insufficient after a server rollback or replacement. Recheck the
diff --git a/src/boxlite/src/rest/litebox.rs b/src/boxlite/src/rest/litebox.rs
index 0810f9b60..4f4f87932 100644
--- a/src/boxlite/src/rest/litebox.rs
+++ b/src/boxlite/src/rest/litebox.rs
@@ -20,7 +20,7 @@ use crate::litebox::copy::CopyOptions;
use crate::litebox::snapshot_mgr::SnapshotInfo;
use crate::litebox::{
AttachOptions, BoxCommand, BoxConnection, BoxTunnel, ExecResult, ExecStderr, ExecStdin,
- ExecStdout, Execution, SshConfig, SshStatus, TunnelOptions,
+ ExecStdout, Execution, SshConfig, SshStatus, SyncExecResult, TunnelOptions,
};
use crate::metrics::BoxMetrics;
use crate::runtime::backend::{BoxBackend, BoxNetworkBackend, SnapshotBackend};
@@ -392,6 +392,38 @@ impl BoxBackend for RestBox {
None,
))
}
+ async fn exec_sync(
+ &self,
+ command: BoxCommand,
+ max_output_bytes: Option<usize>,
+ ) -> BoxliteResult<SyncExecResult> {
+ let (timeout, _) = command.sync_exec_limits(max_output_bytes)?;
+ self.client.require_sync_exec_enabled().await?;
+ if command.user.is_some() {
+ self.client.require_exec_user_enabled().await?;
+ }
+ let mut req = ExecRequest::from_command(&command);
+ req.sync = true;
+ req.max_output_bytes = max_output_bytes;
+ let res = self
+ .client
+ .post_sync_exec(
+ &format!("/boxes/{}/exec", self.id),
+ &req,
+ // Let the server report its deadline before the transport times out.
+ timeout + std::time::Duration::from_secs(30),
+ )
+ .await?;
+ Ok(SyncExecResult {
+ exit_code: res.exit_code,
+ stdout: res.stdout,
+ stderr: res.stderr,
+ stdout_truncated: res.stdout_truncated,
+ stderr_truncated: res.stderr_truncated,
+ error_message: res.error_message,
+ })
+ }
+
async fn exec(&self, command: BoxCommand) -> BoxliteResult<Execution> {
let box_id = self.box_id_str();
if command.user.is_some() {
@@ -4357,6 +4389,267 @@ mod tests {
})
}
+ const SYNC_EXEC_CONFIG: &str = r#"{"capabilities":{"sync_exec_enabled":true}}"#;
+ const SYNC_EXEC_RESULT: &str = r#"{"exit_code":0,"stdout":"","stderr":"","stdout_truncated":false,"stderr_truncated":false}"#;
+
+ async fn serve_sync_exec_config(listener: &TcpListener, config: &str) {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let head = read_request_head(&mut socket).await;
+ assert!(
+ head.starts_with(b"GET /v1/config HTTP/1.1\r\n"),
+ "expected the config request first, got {}",
+ String::from_utf8_lossy(&head),
+ );
+ write_status_response(&mut socket, config).await;
+ }
+
+ async fn serve_sync_exec_once(
+ listener: TcpListener,
+ status: u16,
+ response: &'static str,
+ ) -> serde_json::Value {
+ serve_sync_exec_config(&listener, SYNC_EXEC_CONFIG).await;
+ let (mut socket, _) = listener.accept().await.unwrap();
+ serve_sync_exec_request(&mut socket, status, response).await
+ }
+
+ async fn serve_sync_exec_request(
+ socket: &mut TcpStream,
+ status: u16,
+ response: &str,
+ ) -> serde_json::Value {
+ let read = read_request_head(socket).await;
+ let end = read.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
+ let head = String::from_utf8_lossy(&read[..end]).to_ascii_lowercase();
+ assert!(head.starts_with("post /v1/boxes/sync-box/exec http/1.1\r\n"));
+ assert!(!head.contains("upgrade:"));
+ let length: usize = head
+ .lines()
+ .find_map(|line| line.strip_prefix("content-length:"))
+ .unwrap()
+ .trim()
+ .parse()
+ .unwrap();
+ let mut body = read[end..].to_vec();
+ let received = body.len();
+ body.resize(length, 0);
+ socket.read_exact(&mut body[received..]).await.unwrap();
+ socket.write_all(format!(
+ "HTTP/1.1 {status} Result\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{response}",
+ response.len(),
+ ).as_bytes()).await.unwrap();
+ serde_json::from_slice(&body).unwrap()
+ }
+
+ #[tokio::test]
+ async fn sync_exec_posts_json_and_decodes_the_result_without_websocket() {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let bx = rest_box_for(listener.local_addr().unwrap().port(), "sync-box");
+ let server = tokio::spawn(serve_sync_exec_once(
+ listener,
+ 200,
+ r#"{"exit_code":7,"stdout":"out","stderr":"err","stdout_truncated":true,"stderr_truncated":false,"error_message":"diagnostic"}"#,
+ ));
+ let cmd = BoxCommand::new("echo")
+ .arg("hi")
+ .env("K", "V")
+ .working_dir("/tmp")
+ .timeout(Duration::from_millis(1500));
+ assert_eq!(
+ bx.exec_sync(cmd, Some(2048)).await.unwrap(),
+ SyncExecResult {
+ exit_code: 7,
+ stdout: "out".into(),
+ stderr: "err".into(),
+ stdout_truncated: true,
+ stderr_truncated: false,
+ error_message: Some("diagnostic".into()),
+ }
+ );
+ assert_eq!(
+ server.await.unwrap(),
+ serde_json::json!({
+ "command": "echo", "args": ["hi"], "env": {"K": "V"},
+ "working_dir": "/tmp", "timeout_seconds": 1.5,
+ "tty": false, "sync": true, "max_output_bytes": 2048,
+ })
+ );
+ }
+
+ #[tokio::test]
+ async fn sync_exec_requires_server_advertisement() {
+ for config in [
+ r#"{"capabilities":{}}"#,
+ "{}",
+ r#"{"capabilities":{"sync_exec_enabled":false}}"#,
+ ] {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let bx = rest_box_for(listener.local_addr().unwrap().port(), "sync-box");
+ let (result, posts) = tokio::time::timeout(Duration::from_secs(5), async {
+ let exec = bx.exec_sync(BoxCommand::new("true"), None);
+ tokio::pin!(exec);
+ tokio::select! {
+ (mut socket, _) = async {
+ serve_sync_exec_config(&listener, config).await;
+ // Config closes its socket, so any POST needs a new connection.
+ listener.accept().await.unwrap()
+ } => {
+ serve_sync_exec_request(&mut socket, 200, SYNC_EXEC_RESULT).await;
+ (exec.await, 1)
+ }
+ result = &mut exec => (result, 0),
+ }
+ })
+ .await
+ .unwrap();
+ assert_eq!(posts, 0, "config: {config}");
+ assert!(
+ matches!(result, Err(BoxliteError::Unsupported(_))),
+ "config: {config}, result: {result:?}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn sync_exec_caches_config_and_reuses_the_connection_across_request_timeouts() {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let bx = rest_box_for(listener.local_addr().unwrap().port(), "sync-box");
+ let server = tokio::spawn(async move {
+ // Expect exactly one GET /v1/config followed by two POSTs on the same socket.
+ serve_sync_exec_config(&listener, SYNC_EXEC_CONFIG).await;
+ let (mut socket, _) = listener.accept().await.unwrap();
+ for seconds in [300, 1] {
+ let request = serve_sync_exec_request(&mut socket, 200, SYNC_EXEC_RESULT).await;
+ assert_eq!(
+ request["timeout_seconds"].as_f64(),
+ Some(f64::from(seconds))
+ );
+ }
+ });
+ let result = tokio::time::timeout(Duration::from_secs(5), async {
+ for seconds in [300, 1] {
+ let cmd = BoxCommand::new("true").timeout(Duration::from_secs(seconds));
+ assert_eq!(bx.exec_sync(cmd, None).await.unwrap().exit_code, 0);
+ }
+ server.await.unwrap();
+ })
+ .await;
+ result.expect(
+ "both exec requests must complete on the same connection after one config request",
+ );
+ }
+
+ #[tokio::test]
+ async fn sync_exec_request_times_out_without_a_response() {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let client = client_for(listener.local_addr().unwrap().port());
+ let mut body = ExecRequest::from_command(&BoxCommand::new("true"));
+ body.sync = true;
+ let request =
+ client.post_sync_exec("/boxes/sync-box/exec", &body, Duration::from_millis(50));
+ let stub = async {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let head = read_request_head(&mut socket).await;
+ assert!(head.starts_with(b"POST /v1/boxes/sync-box/exec HTTP/1.1\r\n"));
+ // Keep the socket open without replying until the client returns.
+ socket
+ };
+ let (result, _socket) = tokio::time::timeout(Duration::from_secs(2), async {
+ tokio::join!(request, stub)
+ })
+ .await
+ .expect("the request timeout should fire before the test deadline");
+ assert!(
+ matches!(&result, Err(BoxliteError::Network(msg)) if msg.starts_with("timed out")),
+ "expected a network timeout, got {result:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn sync_exec_maps_http_408() {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let bx = rest_box_for(listener.local_addr().unwrap().port(), "sync-box");
+ let server = tokio::spawn(serve_sync_exec_once(
+ listener,
+ 408,
+ r#"{"error":{"message":"execution timed out","type":"TimeoutError","code":"timeout"}}"#,
+ ));
+ assert!(matches!(bx.exec_sync(BoxCommand::new("true"), None).await,
+ Err(BoxliteError::Internal(msg)) if msg == "server timed out: execution timed out"));
+ assert_eq!(
+ server.await.unwrap(),
+ serde_json::json!({"command": "true", "tty": false, "sync": true})
+ );
+ }
+
+ #[tokio::test]
+ async fn sync_exec_checks_live_user_capability_before_each_named_exec() {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let bx = rest_box_for(listener.local_addr().unwrap().port(), "sync-box");
+ let server = tokio::spawn(async move {
+ for config in [
+ r#"{"capabilities":{"sync_exec_enabled":true,"exec_user_enabled":true}}"#,
+ r#"{"capabilities":{"sync_exec_enabled":true,"exec_user_enabled":false}}"#,
+ r#"{"capabilities":{"sync_exec_enabled":true,"exec_user_enabled":true}}"#,
+ ] {
+ serve_sync_exec_config(&listener, config).await;
+ }
+ let (mut socket, _) = listener.accept().await.unwrap();
+ serve_sync_exec_request(&mut socket, 200, SYNC_EXEC_RESULT).await
+ });
+ tokio::time::timeout(Duration::from_secs(5), async {
+ let cmd = BoxCommand::new("id").user("1000:1000");
+ assert!(matches!(bx.exec_sync(cmd.clone(), None).await,
+ Err(BoxliteError::Unsupported(msg)) if msg.contains("per-exec user")));
+ assert_eq!(bx.exec_sync(cmd, None).await.unwrap().exit_code, 0);
+ let request = server.await.unwrap();
+ assert_eq!(request["user"], "1000:1000");
+ assert_eq!(request["sync"], true);
+ })
+ .await
+ .expect("expected cached sync support and a live user capability check per exec");
+ }
+
+ #[tokio::test]
+ async fn sync_exec_reports_unexpected_created_response() {
+ for (body, execution_id) in [
+ (r#"{"execution_id":"exec-123"}"#, Some("exec-123")),
+ ("{}", None),
+ ] {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let bx = rest_box_for(listener.local_addr().unwrap().port(), "sync-box");
+ let server = tokio::spawn(serve_sync_exec_once(listener, 201, body));
+ let err = bx
+ .exec_sync(BoxCommand::new("true"), None)
+ .await
+ .unwrap_err();
+ let message = err.to_string();
+ assert!(message.contains("201 Created"), "{message}");
+ assert!(
+ message.contains("started an asynchronous execution"),
+ "{message}"
+ );
+ assert!(message.contains("do not blindly retry"), "{message}");
+ if let Some(execution_id) = execution_id {
+ assert!(message.contains(execution_id), "{message}");
+ }
+ assert_eq!(server.await.unwrap()["sync"], true);
+ }
+ }
+
+ #[tokio::test]
+ async fn sync_exec_rejects_tty_before_connecting() {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let bx = rest_box_for(listener.local_addr().unwrap().port(), "sync-box");
+ let result = tokio::time::timeout(
+ Duration::from_secs(1),
+ bx.exec_sync(BoxCommand::new("true").tty(true), None),
+ )
+ .await
+ .unwrap();
+ assert!(matches!(result, Err(BoxliteError::InvalidArgument(_))));
+ }
+
/// `revoke_tunnel()` withdraws exactly the port `tunnel()` would open:
/// one `DELETE /network/tunnel` naming it, and a 204 is success.
#[tokio::test]
diff --git a/src/boxlite/src/rest/types.rs b/src/boxlite/src/rest/types.rs
index ace17ee1d..ba6bdbd87 100644
--- a/src/boxlite/src/rest/types.rs
+++ b/src/boxlite/src/rest/types.rs
@@ -107,6 +107,7 @@ pub(crate) struct ServerCapabilities {
pub import_enabled: Option<bool>,
pub private_tunnels_enabled: Option<bool>,
pub exec_user_enabled: Option<bool>,
+ pub sync_exec_enabled: Option<bool>,
pub volume_read_only_enabled: Option<bool>,
pub typed_mounts_enabled: Option<bool>,
}
@@ -900,6 +901,10 @@ pub(crate) struct ExecRequest {
pub tty: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub sync: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max_output_bytes: Option<usize>,
}
impl ExecRequest {
@@ -918,10 +923,23 @@ impl ExecRequest {
working_dir: cmd.working_dir.clone(),
tty: cmd.tty,
user: cmd.user.clone(),
+ sync: false,
+ max_output_bytes: None,
}
}
}
+#[derive(Debug, Deserialize, Serialize)]
+pub(crate) struct SyncExecResponse {
+ pub exit_code: i32,
+ pub stdout: String,
+ pub stderr: String,
+ pub stdout_truncated: bool,
+ pub stderr_truncated: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_message: Option<String>,
+}
+
#[derive(Debug, Deserialize)]
pub(crate) struct ExecResponse {
pub execution_id: String,
@@ -1635,11 +1653,15 @@ mod tests {
working_dir: Some("/app".to_string()),
tty: false,
user: None,
+ sync: false,
+ max_output_bytes: None,
};
let json = serde_json::to_string(&req).unwrap();
assert!(json.contains("\"command\":\"python3\""));
assert!(json.contains("\"timeout_seconds\":30.0"));
assert!(json.contains("\"working_dir\":\"/app\""));
+ assert!(!json.contains("\"sync\""));
+ assert!(!json.contains("\"max_output_bytes\""));
}
#[test]
diff --git a/src/boxlite/src/runtime/backend.rs b/src/boxlite/src/runtime/backend.rs
index 50af3e37a..ada0e349b 100644
--- a/src/boxlite/src/runtime/backend.rs
+++ b/src/boxlite/src/runtime/backend.rs
@@ -11,7 +11,7 @@ use crate::litebox::copy::CopyOptions;
use crate::litebox::snapshot_mgr::SnapshotInfo;
use crate::litebox::{
AttachOptions, BoxCommand, BoxTunnel, Execution, LiteBox, MountInfo, MountRequest, SshConfig,
- SshStatus,
+ SshStatus, SyncExecResult,
};
use crate::metrics::{BoxMetrics, RuntimeMetrics};
use crate::runtime::options::{
@@ -109,6 +109,12 @@ pub(crate) trait BoxBackend: Send + Sync + Any {
async fn exec(&self, command: BoxCommand) -> BoxliteResult<Execution>;
+ async fn exec_sync(
+ &self,
+ command: BoxCommand,
+ max_output_bytes: Option<usize>,
+ ) -> BoxliteResult<SyncExecResult>;
+
async fn list_executions(&self) -> BoxliteResult<Vec<crate::ExecutionInfo>>;
async fn get_execution(&self, execution_id: &str) -> BoxliteResult<Execution>;
diff --git a/src/cli/src/commands/serve/handlers/config.rs b/src/cli/src/commands/serve/handlers/config.rs
index 1a3307327..bfe75fb73 100644
--- a/src/cli/src/commands/serve/handlers/config.rs
+++ b/src/cli/src/commands/serve/handlers/config.rs
@@ -16,6 +16,7 @@ pub(in crate::commands::serve) async fn get_config() -> Json<ServerConfig> {
export_enabled: true,
import_enabled: true,
exec_user_enabled: true,
+ sync_exec_enabled: true,
volume_read_only_enabled: true,
typed_mounts_enabled: true,
},
diff --git a/src/cli/src/commands/serve/handlers/executions.rs b/src/cli/src/commands/serve/handlers/executions.rs
index 2aa93d727..7e251d8f3 100644
--- a/src/cli/src/commands/serve/handlers/executions.rs
+++ b/src/cli/src/commands/serve/handlers/executions.rs
@@ -4,14 +4,18 @@ use std::sync::Arc;
use std::time::Duration;
use axum::Json;
+use axum::extract::rejection::JsonRejection;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
+use boxlite::{BoxCommand, Execution, collect_sync_execution, validate_sync_exec};
use futures::SinkExt;
use futures::StreamExt;
-use super::super::types::{ExecRequest, ExecResponse, ResizeRequest, SignalRequest};
+use super::super::types::{
+ ExecRequest, ExecResponse, ResizeRequest, SignalRequest, SyncExecResponse,
+};
use super::super::{
ActiveExecution, AppState, MAIN_SESSION_ID_HEADER, RecoveredTerminal, SessionKind,
build_box_command, error_from_boxlite, error_response, get_or_attach_main_session,
@@ -21,8 +25,21 @@ use super::super::{
pub(in crate::commands::serve) async fn start_execution(
State(state): State<Arc<AppState>>,
Path(box_id): Path<String>,
- Json(req): Json<ExecRequest>,
+ request: Result<Json<ExecRequest>, JsonRejection>,
) -> Response {
+ let req = match request {
+ Ok(Json(req)) => req,
+ // A well-formed JSON body with invalid execution arguments (e.g. a
+ // negative output limit or a boolean timeout) is a wire-level 400.
+ Err(JsonRejection::JsonDataError(err)) => {
+ return error_from_boxlite(&boxlite::BoxliteError::InvalidArgument(err.body_text()));
+ }
+ Err(err) => return err.into_response(),
+ };
+ if req.sync {
+ return run_sync_execution(state, box_id, req).await;
+ }
+
let litebox = match get_or_resume_box(&state, &box_id).await {
Ok(b) => b,
Err(resp) => return resp,
@@ -73,6 +90,77 @@ pub(in crate::commands::serve) async fn start_execution(
.into_response()
}
+async fn run_sync_execution(state: Arc<AppState>, box_id: String, req: ExecRequest) -> Response {
+ if req.stdin.is_some() {
+ return error_from_boxlite(&boxlite::BoxliteError::InvalidArgument(
+ "stdin is not supported for synchronous exec".into(),
+ ));
+ }
+ let (timeout, limit) = match validate_sync_exec(
+ &req.command,
+ req.tty,
+ req.timeout_seconds,
+ req.max_output_bytes,
+ ) {
+ Ok(limits) => limits,
+ Err(err) => return error_from_boxlite(&err),
+ };
+ let litebox = match get_or_resume_box(&state, &box_id).await {
+ Ok(bx) => bx,
+ Err(resp) => return resp,
+ };
+ let _in_flight = state.track_sync_exec(litebox.id().as_ref()).await;
+ let mut cmd = BoxCommand::new(req.command)
+ .args(req.args)
+ .timeout(timeout + Duration::from_secs(5));
+ for (key, value) in req.env.into_iter().flatten() {
+ cmd = cmd.env(key, value);
+ }
+ if let Some(dir) = req.working_dir {
+ cmd = cmd.working_dir(dir);
+ }
+ if let Some(user) = req.user {
+ cmd = cmd.user(user);
+ }
+ finish_sync_execution(litebox.exec(cmd), timeout, limit).await
+}
+
+pub(in crate::commands::serve) async fn finish_sync_execution(
+ start: impl std::future::Future<Output = boxlite::BoxliteResult<Execution>>,
+ timeout: Duration,
+ limit: usize,
+) -> Response {
+ let mut execution = None;
+ let result = tokio::time::timeout(timeout, async {
+ let execution = execution.insert(start.await?);
+ collect_sync_execution(execution, limit).await
+ })
+ .await;
+ match result {
+ Ok(Ok(result)) => Json(SyncExecResponse {
+ exit_code: result.exit_code,
+ stdout: result.stdout,
+ stderr: result.stderr,
+ stdout_truncated: result.stdout_truncated,
+ stderr_truncated: result.stderr_truncated,
+ error_message: result.error_message,
+ })
+ .into_response(),
+ Ok(Err(err)) => error_from_boxlite(&err),
+ Err(_) => {
+ if let Some(execution) = execution {
+ let _ = tokio::time::timeout(Duration::from_secs(1), execution.kill()).await;
+ }
+ error_response(
+ StatusCode::REQUEST_TIMEOUT,
+ "execution timed out",
+ "TimeoutError",
+ "timeout",
+ )
+ }
+ }
+}
+
// `Response` carries axum's boxed body which is wide enough to trip
// clippy's `result_large_err`. Error paths are rare lookups so boxing
// every Err is more cost than it saves.
diff --git a/src/cli/src/commands/serve/mod.rs b/src/cli/src/commands/serve/mod.rs
index 4653264fb..50cef123a 100644
--- a/src/cli/src/commands/serve/mod.rs
+++ b/src/cli/src/commands/serve/mod.rs
@@ -99,7 +99,7 @@ struct AppState {
/// Optional expected API key (`--api-key` / `$BOXLITE_SERVE_API_KEY`).
/// `None` ⇒ permissive (no auth enforced).
api_key: Option<String>,
- /// Lifecycle deadlines per box, in seconds.
+ /// Lifecycle deadlines (in seconds) and synchronous execution activity per box.
///
/// Held here rather than in `BoxOptions` because the engine accepts neither
/// on a local runtime, which is what `serve` drives:
@@ -116,7 +116,7 @@ struct AppState {
///
/// In memory only: a restart forgets every deadline, and a box created
/// before it is never swept.
- lifecycle: RwLock<HashMap<String, LifecyclePolicy>>,
+ lifecycle: RwLock<HashMap<String, BoxLifecycle>>,
/// Last observed user activity per box, for AutoStop.
///
/// `serve` holds the `$BOXLITE_HOME` lock for its whole life, so nothing
@@ -161,7 +161,49 @@ impl LifecyclePolicy {
}
}
+#[derive(Default)]
+struct BoxLifecycle {
+ policy: LifecyclePolicy,
+ sync_exec: Arc<std::sync::Mutex<SyncExecActivity>>,
+}
+
+#[derive(Default)]
+struct SyncExecActivity {
+ in_flight: usize,
+ last_activity: Option<Instant>,
+}
+
+impl SyncExecActivity {
+ /// Fold completion into the idle clock, or exempt the box while busy.
+ fn idle_time(&self, idle: std::time::Duration, now: Instant) -> Option<std::time::Duration> {
+ if self.in_flight != 0 {
+ return None;
+ }
+ Some(match self.last_activity {
+ Some(last) => idle.min(now.saturating_duration_since(last)),
+ None => idle,
+ })
+ }
+}
+
+struct SyncExecGuard(Arc<std::sync::Mutex<SyncExecActivity>>);
+
+impl Drop for SyncExecGuard {
+ fn drop(&mut self) {
+ let mut activity = self.0.lock().unwrap();
+ activity.in_flight -= 1;
+ activity.last_activity = Some(Instant::now());
+ }
+}
+
impl AppState {
+ async fn track_sync_exec(&self, box_id: &str) -> SyncExecGuard {
+ let mut lifecycle = self.lifecycle.write().await;
+ let activity = &lifecycle.entry(box_id.to_owned()).or_default().sync_exec;
+ activity.lock().unwrap().in_flight += 1;
+ SyncExecGuard(Arc::clone(activity))
+ }
+
/// Start one wait observer without claiming an output reader.
pub(in crate::commands::serve) async fn watch_recovered(
&self,
@@ -221,7 +263,7 @@ impl AppState {
.retain(|_, active| active.box_id() != box_id);
}
- /// Remember a box's deadlines. A policy with neither set is not stored.
+ /// Remember a box's deadlines without disturbing its in-flight executions.
pub(in crate::commands::serve) async fn set_lifecycle(
&self,
box_id: &str,
@@ -233,7 +275,9 @@ impl AppState {
self.lifecycle
.write()
.await
- .insert(box_id.to_string(), policy);
+ .entry(box_id.to_owned())
+ .or_default()
+ .policy = policy;
}
/// The box's deadlines, or an all-zero policy when it has none.
@@ -242,7 +286,7 @@ impl AppState {
.read()
.await
.get(box_id)
- .copied()
+ .map(|entry| entry.policy)
.unwrap_or_default()
}
@@ -266,8 +310,8 @@ impl AppState {
/// Mark a box as used right now, resetting its AutoStop window.
///
- /// The single write site for the idle clock, so the request middleware and
- /// the sweep agree on what "used" means.
+ /// Synchronous execution completion also updates the canonical clock in
+ /// `SyncExecActivity`, so cancellation can refresh it without awaiting.
pub(in crate::commands::serve) async fn record_box_activity(&self, box_id: &str) {
self.last_activity
.write()
@@ -295,7 +339,7 @@ impl AppState {
///
/// Only `last_activity` is pruned. It is the map unauthenticated input can
/// grow, and re-seeding a live box costs nothing but a fresh window. The
- /// `lifecycle` map is written only by `create_box`, always with a canonical
+ /// `lifecycle` map is written only with a resolved, canonical
/// id, so pruning it would buy nothing and would race: a box created after
/// the caller's `list_info` snapshot would have its deadline dropped and
/// never re-added.
@@ -974,7 +1018,13 @@ async fn run_lifecycle_once(state: &AppState, now: Instant) {
let box_id = info.id.to_string();
// The policy lives here, not on `BoxInfo`: neither deadline is handed
// to the runtime, so neither comes back from it.
- let policy = state.lifecycle_of(&box_id).await;
+ let (policy, sync_exec) = {
+ let lifecycle = state.lifecycle.read().await;
+ let Some(entry) = lifecycle.get(&box_id) else {
+ continue;
+ };
+ (entry.policy, Arc::clone(&entry.sync_exec))
+ };
if policy.is_empty() {
continue;
}
@@ -986,6 +1036,9 @@ async fn run_lifecycle_once(state: &AppState, now: Instant) {
}
let idle = idle_or_seed(&state.last_activity, &box_id, &live, now).await;
+ let Some(idle) = sync_exec.lock().unwrap().idle_time(idle, now) else {
+ continue;
+ };
// The delete deadline uses `last_updated`: for a box at rest that
// transition *is* the stop, which is the anchor AutoDelete wants.
let since_stop = (now_utc - info.last_updated)
@@ -1001,14 +1054,25 @@ async fn run_lifecycle_once(state: &AppState, now: Instant) {
) {
LifecycleAction::Leave => {}
LifecycleAction::Stop => {
- tracing::info!(
- box_id = %box_id,
- idle_secs = idle.as_secs(),
- auto_stop = policy.auto_stop,
- "AutoStop deadline reached, stopping box"
- );
match tokio::time::timeout(LIFECYCLE_OP_TIMEOUT, state.runtime.get(&box_id)).await {
Ok(Ok(Some(bx))) => {
+ // The lookup awaited I/O; an exec may have started or
+ // finished since the first idle check.
+ let deadline = std::time::Duration::from_secs(u64::from(policy.auto_stop));
+ if sync_exec
+ .lock()
+ .unwrap()
+ .idle_time(idle, now)
+ .is_none_or(|idle| idle < deadline)
+ {
+ continue;
+ }
+ tracing::info!(
+ box_id = %box_id,
+ idle_secs = idle.as_secs(),
+ auto_stop = policy.auto_stop,
+ "AutoStop deadline reached, stopping box"
+ );
match tokio::time::timeout(LIFECYCLE_OP_TIMEOUT, bx.stop()).await {
Ok(Ok(())) => {}
Ok(Err(error)) => {
@@ -2336,6 +2400,8 @@ mod tests {
working_dir: None,
tty: false,
user: None,
+ sync: false,
+ max_output_bytes: None,
};
let err = build_box_command(&req).expect_err("invalid timeout should fail");
@@ -2358,6 +2424,8 @@ mod tests {
working_dir: None,
tty: false,
user: user.map(str::to_string),
+ sync: false,
+ max_output_bytes: None,
})
.expect("valid request")
};
@@ -3888,6 +3956,14 @@ mod tests {
/// about it — one consults it, one consults the held AutoStop deadline —
/// and that disagreement is what lets a test tell them apart.
async fn stub_upstream(status: &'static str, auto_resume: bool) -> StubUpstream {
+ stub_upstream_with_pending_exec(status, auto_resume, None).await
+ }
+
+ async fn stub_upstream_with_pending_exec(
+ status: &'static str,
+ auto_resume: bool,
+ exec_started: Option<Arc<tokio::sync::Notify>>,
+ ) -> StubUpstream {
fn canned_box(status: &str, auto_resume: bool) -> serde_json::Value {
serde_json::json!({
"box_id": STUB_BOX_ID,
@@ -3915,9 +3991,14 @@ mod tests {
let execs = Arc::clone(&execs);
move |axum::extract::Path(id): axum::extract::Path<String>| {
let execs = Arc::clone(&execs);
+ let exec_started = exec_started.clone();
async move {
if id == STUB_BOX_ID || id == STUB_BOX_NAME {
execs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if let Some(started) = exec_started {
+ started.notify_one();
+ std::future::pending::<()>().await;
+ }
}
// The reply shape does not matter: the counter is the
// whole point, and every caller here is proving only
@@ -4813,7 +4894,12 @@ mod tests {
);
assert_eq!(created["auto_delete"], 604_800);
assert_eq!(
- state.lifecycle.read().await.get(STUB_BOX_ID).copied(),
+ state
+ .lifecycle
+ .read()
+ .await
+ .get(STUB_BOX_ID)
+ .map(|entry| entry.policy),
Some(LifecyclePolicy {
auto_stop: 900,
auto_delete: 604_800,
diff --git a/src/cli/src/commands/serve/tests/executions.rs b/src/cli/src/commands/serve/tests/executions.rs
index 7fb2f6f7d..4ef98423d 100644
--- a/src/cli/src/commands/serve/tests/executions.rs
+++ b/src/cli/src/commands/serve/tests/executions.rs
@@ -1,8 +1,262 @@
//! No-VM execution status and lifetime boundaries.
-use super::super::handlers::executions::get_execution;
+use std::future::ready;
+
+use super::super::handlers::executions::{finish_sync_execution, get_execution, start_execution};
use super::*;
+async fn sync_response_json(response: axum::response::Response) -> serde_json::Value {
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ serde_json::from_slice(&body).unwrap()
+}
+
+#[tokio::test]
+async fn sync_exec_returns_output_and_truncates_each_stream_independently() {
+ for truncated in [false, true] {
+ let (execution, stdout, stderr, mut stdin, result) = Execution::stub("sync");
+ let out = "a".repeat(if truncated { 1025 } else { 1024 });
+ stdout.send(out).unwrap();
+ stderr.send("err".into()).unwrap();
+ result
+ .send(boxlite::ExecResult {
+ exit_code: 7,
+ error_message: None,
+ })
+ .unwrap();
+ drop((stdout, stderr, result));
+ let response =
+ finish_sync_execution(ready(Ok(execution)), Duration::from_secs(1), 1024).await;
+ assert_eq!(response.status(), StatusCode::OK);
+ assert!(stdin.recv().await.is_none());
+ assert_eq!(
+ sync_response_json(response).await,
+ serde_json::json!({
+ "exit_code": 7,
+ "stdout": "a".repeat(1024),
+ "stderr": "err",
+ "stdout_truncated": truncated,
+ "stderr_truncated": false,
+ })
+ );
+ }
+}
+
+#[tokio::test]
+async fn sync_exec_times_out_and_kills_the_execution() {
+ let (killed_tx, mut killed_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (execution, stdout, stderr, _stdin, result) =
+ Execution::stub_with_kill_hook("sync", move || {
+ killed_tx.send(()).unwrap();
+ });
+ let response =
+ finish_sync_execution(ready(Ok(execution)), Duration::from_millis(100), 1024).await;
+ drop((stdout, stderr, result));
+ assert_eq!(response.status(), StatusCode::REQUEST_TIMEOUT);
+ killed_rx
+ .try_recv()
+ .expect("timeout did not kill the execution");
+ let body = sync_response_json(response).await;
+ assert_eq!(body["error"]["type"], "TimeoutError");
+ assert_eq!(body["error"]["code"], "timeout");
+ assert_eq!(body["error"]["message"], "execution timed out");
+}
+
+#[tokio::test]
+async fn config_advertises_sync_exec() {
+ let (url, server) = serve_router(Arc::new(lifecycle_state())).await;
+ let response = reqwest::get(format!("{url}/v1/config")).await.unwrap();
+ assert_eq!(response.status(), StatusCode::OK);
+ let body: serde_json::Value = response.json().await.unwrap();
+ assert_eq!(body["capabilities"]["sync_exec_enabled"], true);
+ server.abort();
+}
+
+#[tokio::test]
+async fn sync_exec_route_rejects_invalid_arguments() {
+ let (url, server) = serve_router(Arc::new(lifecycle_state())).await;
+ let client = reqwest::Client::new();
+ for request in [
+ r#"{"command":"","sync":true}"#,
+ r#"{"command":"true","sync":true,"timeout_seconds":0.09}"#,
+ r#"{"command":"true","sync":true,"timeout_seconds":301}"#,
+ r#"{"command":"true","sync":true,"timeout_seconds":true}"#,
+ r#"{"command":"true","sync":true,"timeout_seconds":false}"#,
+ r#"{"command":"true","sync":true,"max_output_bytes":true}"#,
+ r#"{"command":"true","sync":true,"max_output_bytes":false}"#,
+ r#"{"command":"true","sync":true,"max_output_bytes":-1}"#,
+ r#"{"command":"true","sync":true,"max_output_bytes":1023}"#,
+ r#"{"command":"true","sync":true,"max_output_bytes":10485761}"#,
+ r#"{"command":"true","sync":true,"tty":true}"#,
+ r#"{"command":"true","sync":true,"stdin":""}"#,
+ ] {
+ let response = client
+ .post(format!("{url}/v1/boxes/does-not-exist/exec"))
+ .header("content-type", "application/json")
+ .body(request)
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{request}");
+ let body: serde_json::Value = response.json().await.unwrap();
+ assert_eq!(body["error"]["type"], "InvalidArgumentError");
+ assert_eq!(body["error"]["code"], "invalid_argument");
+ }
+ server.abort();
+}
+
+#[tokio::test]
+async fn async_exec_route_returns_created_when_sync_is_false_or_omitted() {
+ let upstream_app = axum::Router::new()
+ .route(
+ "/v1/boxes/{id}",
+ axum::routing::get(|| async {
+ axum::Json(serde_json::json!({
+ "box_id": STUB_BOX_ID,
+ "name": STUB_BOX_NAME,
+ "status": "running",
+ "created_at": "2026-01-01T00:00:00Z",
+ "updated_at": "2026-01-01T00:00:00Z",
+ "pid": null,
+ "image": "alpine:latest",
+ "cpus": 1,
+ "memory_mib": 512,
+ "auto_stop": 0,
+ "auto_delete": 0,
+ "auto_resume": true,
+ }))
+ }),
+ )
+ .route(
+ "/v1/boxes/{id}/exec",
+ axum::routing::post(|| async {
+ (
+ StatusCode::CREATED,
+ axum::Json(serde_json::json!({"execution_id": "exec-async-1"})),
+ )
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let upstream_url = format!("http://{}", listener.local_addr().unwrap());
+ let upstream_task = tokio::spawn(async move {
+ let _ = axum::serve(listener, upstream_app).await;
+ });
+
+ let mut state = lifecycle_state();
+ state.runtime = BoxliteRuntime::rest(boxlite::BoxliteRestOptions::new(upstream_url)).unwrap();
+ let (url, server) = serve_router(Arc::new(state)).await;
+ let client = reqwest::Client::new();
+
+ for request in [
+ r#"{"command":"true"}"#,
+ r#"{"command":"true","sync":false}"#,
+ ] {
+ let response = client
+ .post(format!("{url}/v1/boxes/{STUB_BOX_ID}/exec"))
+ .header("content-type", "application/json")
+ .body(request)
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::CREATED, "{request}");
+ let body: serde_json::Value = response.json().await.unwrap();
+ assert_eq!(body["execution_id"], "exec-async-1");
+ }
+
+ server.abort();
+ upstream_task.abort();
+}
+
+#[tokio::test]
+async fn sync_exec_times_out_while_starting_execution() {
+ let upstream = stub_upstream_with_pending_exec(
+ "running",
+ true,
+ Some(Arc::new(tokio::sync::Notify::new())),
+ )
+ .await;
+ let mut state = lifecycle_state();
+ state.runtime =
+ BoxliteRuntime::rest(boxlite::BoxliteRestOptions::new(upstream.url.clone())).unwrap();
+ let (url, server) = serve_router(Arc::new(state)).await;
+ let response = reqwest::Client::new()
+ .post(format!("{url}/v1/boxes/{STUB_BOX_ID}/exec"))
+ .timeout(Duration::from_secs(5))
+ .json(&serde_json::json!({"command": "true", "sync": true, "timeout_seconds": 0.25}))
+ .send()
+ .await
+ .expect("server should time out before the client");
+ assert_eq!(response.status(), StatusCode::REQUEST_TIMEOUT);
+ let body: serde_json::Value = response.json().await.unwrap();
+ assert_eq!(body["error"]["code"], "timeout");
+ assert_eq!(upstream.execs(), 1, "exec should reach upstream once");
+ server.abort();
+ upstream.task.abort();
+}
+
+#[tokio::test]
+async fn sync_exec_prevents_auto_stop_and_cancellation_restarts_the_idle_window() {
+ let started = Arc::new(tokio::sync::Notify::new());
+ let upstream = stub_upstream_with_pending_exec("running", true, Some(started.clone())).await;
+ let mut state = lifecycle_state();
+ state.runtime =
+ BoxliteRuntime::rest(boxlite::BoxliteRestOptions::new(upstream.url.clone())).unwrap();
+ let state = Arc::new(state);
+ state
+ .set_lifecycle(
+ STUB_BOX_ID,
+ LifecyclePolicy {
+ auto_stop: 60,
+ auto_delete: 0,
+ },
+ )
+ .await;
+ let now = Instant::now();
+ state
+ .last_activity
+ .write()
+ .await
+ .insert(STUB_BOX_ID.to_owned(), now - Duration::from_secs(600));
+
+ {
+ let request =
+ serde_json::from_value(serde_json::json!({"command": "true", "sync": true})).unwrap();
+ let handler = start_execution(
+ axum::extract::State(state.clone()),
+ axum::extract::Path(STUB_BOX_NAME.to_owned()),
+ Ok(Json(request)),
+ );
+ tokio::pin!(handler);
+ tokio::select! {
+ _ = started.notified() => {},
+ response = &mut handler => panic!("sync exec returned early: {}", response.status()),
+ _ = tokio::time::sleep(Duration::from_secs(5)) => panic!("exec did not reach upstream"),
+ }
+ run_lifecycle_once(&state, now).await;
+ assert_eq!(
+ upstream.stops(),
+ 0,
+ "in-flight sync exec must prevent AutoStop"
+ );
+ } // Cancel the handler before the upstream responds.
+
+ let finished = Instant::now();
+ run_lifecycle_once(&state, finished).await;
+ assert_eq!(
+ upstream.stops(),
+ 0,
+ "cancellation must refresh the idle clock"
+ );
+ run_lifecycle_once(&state, finished + Duration::from_secs(61)).await;
+ assert_eq!(
+ upstream.stops(),
+ 1,
+ "the cancelled exec must no longer pin the box"
+ );
+ upstream.task.abort();
+}
+
async fn recorded_exit(state: &AppState, box_id: &str, exec_id: &str, code: i32) {
let (execution, _out, _err, _input, result) = Execution::stub(exec_id);
state.watch_recovered(box_id, exec_id, execution).await;
diff --git a/src/cli/src/commands/serve/types.rs b/src/cli/src/commands/serve/types.rs
index 6af9b35b8..922a574ae 100644
--- a/src/cli/src/commands/serve/types.rs
+++ b/src/cli/src/commands/serve/types.rs
@@ -358,6 +358,22 @@ pub(super) struct ExecRequest {
pub tty: bool,
#[serde(default)]
pub user: Option<String>,
+ #[serde(default)]
+ pub sync: bool,
+ /// Per-stream capture limit for sync exec. The handler maps type errors to 400.
+ #[serde(default)]
+ pub max_output_bytes: Option<usize>,
+}
+
+#[derive(Serialize)]
+pub(super) struct SyncExecResponse {
+ pub exit_code: i32,
+ pub stdout: String,
+ pub stderr: String,
+ pub stdout_truncated: bool,
+ pub stderr_truncated: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_message: Option<String>,
}
#[derive(Serialize)]
@@ -399,6 +415,7 @@ pub(super) struct ServerCapabilities {
pub export_enabled: bool,
pub import_enabled: bool,
pub exec_user_enabled: bool,
+ pub sync_exec_enabled: bool,
pub volume_read_only_enabled: bool,
pub typed_mounts_enabled: bool,
}