Skip to main content

chainguard_sandbox/
lib.rs

1//! Simple Chainguard Sandbox SDK for Rust: create a sandbox on Chainguard Workspaces, run commands
2//! in it, move files in and out, and delete it. The API is shaped like the E2B, Vercel Sandbox and
3//! Modal SDKs, and matches the Go, Python and TypeScript SDKs.
4//!
5//! **Unofficial.** This SDK isn't affiliated with or supported by Chainguard. It's compatible with
6//! `chainctl` 0.2.398 and the Sessions API it uses.
7//!
8//! ```no_run
9//! use chainguard_sandbox::{CreateOptions, Sandbox};
10//!
11//! #[tokio::main]
12//! async fn main() -> chainguard_sandbox::Result<()> {
13//!     let out = Sandbox::with(CreateOptions { packages: Some(vec!["bash".into(), "python-3.13".into()]), ..Default::default() }, async |sbx| {
14//!         let r = sbx.commands.run("python3 -c 'print(2+2)'").await?;
15//!         sbx.files.write("notes/hello.txt", "hi").await?;
16//!         Ok(r.stdout)
17//!     })
18//!     .await?; // the sandbox is deleted here
19//!     print!("{out}"); // 4
20//!     Ok(())
21//! }
22//! ```
23//!
24//! Programs without an async runtime use [`blocking`].
25//!
26//! The first call opens your browser to log in to Chainguard; the login is saved and shared with
27//! the Go, Python and TypeScript SDKs. Workspaces must be turned on for your organization once
28//! ([`enable_workspaces`], or `chainguard-sandbox enable`).
29//!
30//! The layers:
31//!
32//! - [`Sandbox`], [`Commands`], [`Files`]: the simple sandbox API.
33//! - [`workspaces`]: the lower-level client (sessions, exec, login, tokens, the platform API).
34
35#![warn(missing_debug_implementations)]
36
37/// `Debug` that prints the type name only (for types holding callbacks or tokens).
38macro_rules! opaque_debug {
39    ($($t:ty),* $(,)?) => {$(
40        impl std::fmt::Debug for $t {
41            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42                f.debug_struct(stringify!($t)).finish_non_exhaustive()
43            }
44        }
45    )*};
46}
47pub(crate) use opaque_debug;
48
49pub mod blocking;
50mod commands;
51mod error;
52mod files;
53mod sandbox;
54#[rustfmt::skip] // generated by scripts/gen_sandbox_scripts.py
55mod scripts;
56mod setup;
57mod untar;
58pub mod workspaces;
59
60pub use commands::{
61    CommandHandle, CommandResult, Commands, DEFAULT_COMMAND_TIMEOUT, ProcessInfo, RunOptions,
62    StartOptions, TextCallback, WaitOptions,
63};
64pub use error::{Error, Result};
65pub use files::{EntryInfo, FileType, Files, WriteEntry, WriteInfo};
66#[doc(hidden)]
67pub use sandbox::shorten_timings_for_tests;
68pub use sandbox::{
69    ConnectOptions, CreateOptions, DEFAULT_PACKAGES, DEFAULT_WORKDIR, GitSource, Info,
70    Organization, Sandbox, document, kill, list, list_organizations,
71};
72pub use setup::{SetupOptions, WorkspacesStatus, enable_workspaces, workspaces_status};
73pub use workspaces::TermsDocument;
74
75pub(crate) fn workspaces_random_id() -> String {
76    workspaces::random_hex(8)
77}
78
79pub(crate) fn workspaces_clean_path(p: &str) -> String {
80    workspaces::clean_path(p)
81}
82
83/// The shell scripts' source text, for the test that compares them with the Go source.
84#[doc(hidden)]
85pub fn script_text_for_tests() -> Vec<(&'static str, &'static str)> {
86    use scripts::*;
87    vec![
88        ("runScript", RUN_SCRIPT),
89        ("startScript", START_SCRIPT),
90        ("pollScript", POLL_SCRIPT),
91        ("killScript", KILL_SCRIPT),
92        ("listScript", LIST_SCRIPT),
93        ("resolvePidScript", RESOLVE_PID_SCRIPT),
94        ("readScript", READ_SCRIPT),
95        ("existsScript", EXISTS_SCRIPT),
96        ("makeDirScript", MAKE_DIR_SCRIPT),
97        ("removeScript", REMOVE_SCRIPT),
98        ("appendScript", APPEND_SCRIPT),
99        ("finishScript", FINISH_SCRIPT),
100        ("untarScript", UNTAR_SCRIPT),
101        ("tarScript", TAR_SCRIPT),
102        ("statFn", STAT_FN),
103        ("infoScript", INFO_SCRIPT),
104        ("listDirScript", LIST_DIR_SCRIPT),
105        ("renameScript", RENAME_SCRIPT),
106    ]
107}