Skip to main content

PooledSandbox

Struct PooledSandbox 

Source
pub struct PooledSandbox { /* private fields */ }
Expand description

A sandbox acquired from a pool.

This wrapper ensures the sandbox is returned to the pool when dropped. It implements Deref and DerefMut to allow transparent access to the underlying Sandbox.

Implementations§

Source§

impl PooledSandbox

Source

pub fn sandbox(&self) -> &Sandbox

Get a reference to the underlying sandbox.

Source

pub fn sandbox_mut(&mut self) -> &mut Sandbox

Get a mutable reference to the underlying sandbox.

Source

pub fn detach(self) -> Sandbox

Detach the sandbox from the pool, preventing it from being returned.

This consumes the PooledSandbox and returns the underlying Sandbox. The sandbox will not be returned to the pool.

Note: This still releases the semaphore permit, so another sandbox can be created to take its place in the pool.

Source

pub fn with_callbacks(self, callbacks: Vec<Box<dyn Callback>>) -> Self

Set callbacks for this request.

These will be cleared automatically when the sandbox is returned to the pool.

Source

pub fn with_trace_handler<H: TraceHandler + 'static>(self, handler: H) -> Self

Set a trace handler for this request.

This will be cleared automatically when the sandbox is returned to the pool.

Source

pub fn with_output_handler<H: OutputHandler + 'static>(self, handler: H) -> Self

Set an output handler for this request.

This will be cleared automatically when the sandbox is returned to the pool.

Source

pub fn with_resource_limits(self, limits: ResourceLimits) -> Self

Set resource limits for this request.

These will be reset to defaults when the sandbox is returned to the pool.

Source

pub fn with_vfs_storage(self, storage: Arc<dyn VfsStorage>) -> Self

Available on crate feature vfs only.

Set VFS storage for this request.

This will be cleared automatically when the sandbox is returned to the pool. The provided storage replaces the default scrubbing storage created during execution, allowing pre-populated files to be available to Python code.

Methods from Deref<Target = Sandbox>§

Source

pub async fn execute(&self, code: &str) -> Result<ExecuteResult, Error>

Execute Python code in the sandbox.

If an OutputHandler was configured, stdout is streamed to it during execution. If a TraceHandler was configured, trace events are emitted during execution.

Returns the final result including complete stdout and collected trace events.

§Errors

Returns an error if the Python code fails to execute or a resource limit is exceeded.

Source

pub async fn execute_with_journal(&self, code: &str) -> ReplayOutcome

Execute Python code with callback-result replay and journaling.

This behaves like execute but additionally records a CallbackJournal of every callback invocation, and — if a previous journal was configured via SandboxBuilder::with_replay_journal — replays matching callbacks from that journal instead of invoking them live. See the replay module for the full model.

The returned ReplayOutcome always carries the freshly-recorded journal, even when execution fails, so a later resubmission can replay everything that completed.

Each call uses fresh replay state, so a sandbox may be executed repeatedly without the journal cursor leaking between runs.

§Security

Replayed journal entries are returned to Python verbatim — the callback is not re-executed. A crafted journal can therefore inject arbitrary values into the script. Only replay journals produced by a trusted source (e.g. a previous run of the same sandbox, or a journal verified via HMAC signature). See the replay module docs for details.

Source

pub fn type_stubs(&self) -> &str

Get combined type stubs for all loaded libraries. Useful for including in LLM context windows.

Source

pub fn callbacks(&self) -> &HashMap<String, Arc<dyn Callback>>

Get a reference to the registered callbacks.

Source

pub fn preamble(&self) -> &str

Get the Python preamble code.

Source

pub fn trace_handler(&self) -> &Option<Arc<dyn TraceHandler>>

Get a reference to the trace handler.

Source

pub fn output_handler(&self) -> &Option<Arc<dyn OutputHandler>>

Get a reference to the output handler.

Source

pub fn resource_limits(&self) -> &ResourceLimits

Get a reference to the resource limits.

Source

pub fn executor(&self) -> Arc<PythonExecutor>

Get a reference to the Python executor.

This allows creating a SessionExecutor from a pooled sandbox, enabling state persistence between executions.

Source

pub fn execute_cancellable(&self, code: &str) -> ExecutionHandle

Execute Python code with cancellation support.

Returns an ExecutionHandle that can be used to cancel the execution or wait for its completion.

§Example
let handle = sandbox.execute_cancellable("while True: pass").await?;

// Cancel after 5 seconds from another task
let cancel_handle = handle.clone();
tokio::spawn(async move {
    tokio::time::sleep(Duration::from_secs(5)).await;
    cancel_handle.cancel();
});

// Wait for result
match handle.wait().await {
    Ok(result) => println!("Completed: {}", result.stdout),
    Err(Error::Cancelled) => println!("Cancelled"),
    Err(e) => println!("Error: {e}"),
}
§Errors

Returns an error if the execution cannot be started.

Trait Implementations§

Source§

impl Debug for PooledSandbox

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for PooledSandbox

Source§

type Target = Sandbox

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for PooledSandbox

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl Drop for PooledSandbox

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> GetSetFdFlags for T

Source§

fn get_fd_flags(&self) -> Result<FdFlags, Error>
where T: AsFilelike,

Query the “status” flags for the self file descriptor.
Source§

fn new_set_fd_flags(&self, fd_flags: FdFlags) -> Result<SetFdFlags<T>, Error>
where T: AsFilelike,

Create a new SetFdFlags value for use with set_fd_flags. Read more
Source§

fn set_fd_flags(&mut self, set_fd_flags: SetFdFlags<T>) -> Result<(), Error>
where T: Sized + AsFilelike,

Set the “status” flags for the self file descriptor. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Pointee for T

Source§

type Pointer = u32

Source§

fn debug( pointer: <T as Pointee>::Pointer, f: &mut Formatter<'_>, ) -> Result<(), Error>

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more