Lifespan and state¶
Some things live longer than a run: a connection to a service, a cache, a
counter. The lifespan of an application runs around its life, and what it
yields is the state every run reads
as ctx.state. This page covers the lifespan, the state, and starting an
application once for several runs with async with app:.
A lifespan¶
import contextlib
from collections.abc import AsyncIterator
from typing import Any
import fastsandbox
from fastsandbox import Context, FastSandbox
@contextlib.asynccontextmanager
async def lifespan(app: FastSandbox) -> AsyncIterator[dict[str, Any]]:
runs: list[str] = []
yield {"runs": runs}
print(f"{app.name}: {len(runs)} runs")
app = FastSandbox("digests", lifespan=lifespan)
@app.task(kit="shell")
async def sha256(ctx: Context, text: str) -> str:
"""The SHA-256 digest of a text, computed in a sandbox."""
output = await ctx.sandbox.exec(
["sh", "-c", 'printf %s "$1" | sha256sum', "sh", text], check=True
)
ctx.state["runs"].append(ctx.run_id)
return output.stdout.split()[0]
async def main() -> None:
async with app:
for text in ("one", "two", "three"):
print(await app.run("sha256", text=text))
if __name__ == "__main__":
fastsandbox.run(main())
FastSandbox(lifespan=...) takes a function that
receives the application and returns an async context manager, here written
with contextlib.asynccontextmanager:
- The code before
yieldruns when the application starts, on the host. - What it yields, a mapping or
None, becomes the state:ctx.statein every run, andapp.statewhile the application is started.Nonegives an empty state. - The code after
yieldruns when the application stops.
While the application is started, every run gets the same state: sha256
appends to the list the lifespan created, and the lifespan reads it at the end.
An application that is not started enters its lifespan for each run, and each
run then has a state of its own (see below).
Starting the application once¶
Without async with app:, every run starts the application for itself: it
connects to the daemon, enters the lifespan, runs the task and stops again. A
program that runs several tasks starts it once instead:
async with app:connects one client, enters the lifespan once, and every run inside the block uses both.mainabove runs three tasks with one client, and the lifespan prints its summary once, when the block ends.- An application cannot be started twice at once: entering
async with app:again inside the block raisesTaskError. - Once the block has ended, runs start the application for themselves again.
The dependencies of a task, on the contrary, are resolved for each run: they hold what belongs to one run and its sandbox, the lifespan what belongs to the application.
Choosing the client¶
The application connects to the daemon of the current user, through the socket
connect() finds. Its constructor chooses otherwise:
socket="/path/to/sandboxd.sock"connects to another socket;client=gives aClientalready connected, used as it is;kits=gives theKitCachethe kits come from, instead of the one of the process: one that keeps them in a directory, or one that compiles them with thesbxCLI (KitCache(sbx="sbx")). A cache that compiles launches each sandbox from the package it compiled.
That is also how tests point an application at the fake daemon: see Testing.