Skip to content

bioamla.server

The HTTP API is described by its OpenAPI document, openapi.json (regenerate it with bioamla serve --openapi docs/api/openapi.json; a test fails while it is out of date).

bioamla.server

bioamla.server — run bioamla commands in workspaces on this machine, over HTTP.

Install with pip install 'bioamla[server]' and start with bioamla serve. The design (workspaces, jobs, the security model) is described in Workspaces, remote work and agent skills.

AccessDenied

Bases: BioamlaError

A request touched a path it may not use (HTTP 403).

Identity dataclass

Who a request acts as. One user for now; more with a later multi-user server.

PathPolicy

Every path the server touches must resolve inside the workspace root, or inside one of the folders allow-listed for linking (e.g. an archive of recordings).

Paths are resolved with symlinks followed, so a link inside a workspace can't reach outside the allowed folders.

Parameters:

Name Type Description Default
root str | Path

The folder holding the server's workspaces.

required
linkable list[str | Path] | tuple

Folders outside root that workspaces may link in place.

()

allowed property

allowed: tuple[Path, ...]

The resolved folders a path may be in: the root, then the linkable folders.

authorize

authorize(
    identity: Identity,
    path: str | Path,
    base: str | Path | None = None,
) -> Path

The resolved path (relative paths against base, default the root), if identity may use it.

A path from a client is taken literally (~ isn't expanded).

Parameters:

Name Type Description Default
identity Identity

Who is asking.

required
path str | Path

The path, absolute or relative.

required
base str | Path | None

What a relative path is relative to (default: the root).

None

A workspace's metadata (its .bioamla folder and the files directly in it: workspace.toml, artifacts.json, config.toml, history.jsonl) is never a request's to read or write; the server changes it only through the workspace API. Subfolders such as .bioamla/imported are allowed.

Raises:

Type Description
AccessDenied

If it resolves outside every allowed folder, or to a workspace's metadata.

InvalidInputError

If it isn't a usable path (e.g. contains a NUL).

path_check

path_check(identity: Identity, base: str | Path) -> Any

check(path) -> str: :meth:authorize for identity, relative paths against base, as an operation context's path_check.

workspace_dir

workspace_dir(identity: Identity, name: str) -> Path

The directory of the workspace called name under the root.

The workspace's .bioamla folder and workspace.toml must be inside it, not links to somewhere else.

Parameters:

Name Type Description Default
identity Identity

Who is asking.

required
name str

The workspace's folder name under the root.

required

Raises:

Type Description
InvalidInputError

If name isn't a plain folder name.

AccessDenied

If the workspace, or its metadata, resolves outside the root.

NotFoundError

If there's no such workspace.

new_workspace_dir

new_workspace_dir(identity: Identity, name: str) -> Path

Where a new workspace called name goes: a folder directly under the root.

Raises:

Type Description
InvalidInputError

If name isn't a plain folder name.

AccessDenied

If it would resolve outside the root.

WorkspaceError

If something already exists there.

Unauthenticated

Bases: BioamlaError

A request presented no valid token (HTTP 401).

ServerConfig dataclass

How a server runs.

Attributes:

Name Type Description
root Path

Folder holding the server's workspaces.

token str

The bearer token clients must present.

linkable list[Path]

Folders outside root that workspaces may link (e.g. an archive of recordings), used in place.

max_jobs int

How many jobs may run at once (machine-learning jobs: one at a time).

job_timeout float | None

Seconds a running job may go without reporting anything before it's stopped (None: no limit).

max_window float

The longest audio window a client may ask for, in seconds.

check_token

check_token(
    presented: str | None, expected: str
) -> Identity

The identity for a bearer token.

Parameters:

Name Type Description Default
presented str | None

The token the request sent, or None if it sent none.

required
expected str

The server's token.

required

Raises:

Type Description
Unauthenticated

If it doesn't match.

read_or_create_token

read_or_create_token(path: str | Path) -> str

The server token stored in path, creating one if it's missing.

A new token is written to a private temporary file and then linked into place, so a server starting at the same moment never reads a half-written token: whichever process links first wins, and the others read its token.

On POSIX systems the file is created with mode 0600 and an existing file that other users can access is refused. On Windows the file gets the folder's default access rules and isn't checked; keep it in a folder only you can read.

Parameters:

Name Type Description Default
path str | Path

The token file (~ is expanded).

required

Returns:

Type Description
str

The token.

Raises:

Type Description
InvalidInputError

If the file isn't one line holding a token (empty, several lines, spaces, not UTF-8), or other users can access it (POSIX).

ConfigError

If the file or its folder can't be created or read.

create_app

create_app(config: ServerConfig) -> FastAPI

The API application for config.

Parameters:

Name Type Description Default
config ServerConfig

The workspace root, token and linkable folders.

required

Returns:

Type Description
FastAPI

A FastAPI application. app.state.policy is its :class:PathPolicy,

FastAPI

app.state.identity the dependency that checks the token and

FastAPI

app.state.jobs its :class:~bioamla.server.jobs.JobRunner.

Raises:

Type Description
ConfigError

If BIOAMLA_DECODE_TIMEOUT or BIOAMLA_ENCODE_TIMEOUT isn't a positive number.

envelope

envelope(result: Any) -> dict[str, Any]

The success envelope for result, as bioamla --json reports it.

Parameters:

Name Type Description Default
result Any

The route's result; dataclasses, paths and the like are made JSON-ready.

required

Returns:

Type Description
dict[str, Any]

{"bioamla": <version>, "ok": True, "result": ...}.

openapi_spec

openapi_spec() -> dict[str, Any]

The OpenAPI document of the /v1 API.

Raises:

Type Description
DependencyError

If an extra is missing: its operations would have no routes, so the document would be incomplete. Generate it with every extra (pip install 'bioamla[all,server]').

write_openapi_spec

write_openapi_spec(path: str | Path) -> Path

Write :func:openapi_spec to path as indented JSON.

Raises:

Type Description
DependencyError

If an extra is missing (see :func:openapi_spec).

OSError

If it can't be written.

Jobs

bioamla.server.jobs

Jobs: long operations run in worker processes, with status, progress and cancel.

A job-kind operation posted to /v1/workspaces/{ws}/operations/{name} is queued and answered at once (202) with the job. Each job runs in its own worker process (see :mod:bioamla.server._worker), so a crash or a cancel can't take the server down. At most max_jobs run at once, and at most one machine-learning job (models.*, batch.models.*); the rest wait in order.

Routes:

  • GET /v1/jobs: every job this server has run since it started (?workspace= narrows them)
  • GET /v1/jobs/{id}: its status, progress, and its result or error once done
  • GET /v1/jobs/{id}/events: its events as server-sent events (status, progress, notice, log), from the start or after Last-Event-ID, until it finishes
  • GET /v1/jobs/{id}/log: its notices and log lines as text
  • POST /v1/jobs/{id}/cancel: ask it to stop. A queued job is dropped; a running one is asked through its cancel check, and its worker is ended if it hasn't stopped after a grace period.

With a timeout (bioamla serve --job-timeout), a running job that sends nothing (no progress, notice, log line or result) for that long is stopped the same way and fails with JobTimeout; a long job that keeps reporting progress runs on.

Jobs are kept in memory; each is also recorded in its workspace's history (with job set to its id), so the record outlives the server.

Job dataclass

One job: what it runs, where, and how it's going.

Attributes:

Name Type Description
id str

The job id.

operation str

The operation it runs.

workspace str

The workspace's name on the server.

user str

Who submitted it.

request dict[str, Any]

The request, as JSON-ready data.

status str

queued, running, succeeded, failed or cancelled.

created float

When it was submitted (epoch seconds).

started float | None

When its worker started.

finished float | None

When it finished.

progress dict[str, int] | None

The latest {"done", "total"}.

result Any

The operation's result once it succeeded, as the routes report it.

error dict[str, str] | None

{"type", "message"} once it failed or was cancelled.

events list[dict[str, Any]]

Everything that happened, in order (each with an id).

want_wire bool

Whether the submitter asked for the typed result.

wire dict[str, Any] | None

{"wire"} or {"wire_error"} once it succeeded, if asked for.

ml property

ml: bool

Whether it's a machine-learning job.

to_dict

to_dict() -> dict[str, Any]

The job as the API reports it (result and error once done).

JobRunner

Runs jobs in worker processes, a few at a time and one ML job at a time.

Parameters:

Name Type Description Default
root Path

The server's workspace root.

required
linkable list[Path] | tuple

Folders outside root that operations may use.

()
max_jobs int

How many jobs may run at once.

2
cancel_grace float

Seconds a cancelled job gets to stop before its worker is ended (and as long again before it is killed).

5.0
poll float

Seconds between checks on the workers.

0.05
keep_jobs int

Finished jobs kept for the job routes; older ones are forgotten (their history records stay in their workspaces).

200
max_events int

Events kept per job; past that, further progress and log events are dropped (status events and the latest progress are always kept).

5000
timeout float | None

Seconds a running job may go without sending anything (progress, a notice, a log line, its result) before it's stopped and failed with JobTimeout (None: no limit), so a hung worker can't hold a slot forever while a long job that reports progress runs on.

None

Raises:

Type Description
InvalidInputError

If timeout isn't positive.

submit

submit(
    ws_dir: Path,
    workspace: str,
    name: str,
    request: Any,
    user: str,
    wire: bool = False,
) -> Job

Queue the operation name on request (already validated) in ws_dir; with wire, its result is also kept in the typed wire form.

get

get(job_id: str) -> Job

The job job_id.

Raises:

Type Description
NotFoundError

If there's no such job.

events_after

events_after(
    job: Job, after: int
) -> tuple[list[dict[str, Any]], bool]

The job's events with ids above after, and whether it has finished.

Takes no lock, so it never waits on the runner (event ids are positions in the list, which only grows, and a job's final event is added before its status changes).

cancel

cancel(job_id: str) -> Job

Ask the job to stop: a queued job is dropped, a running one asked to stop.

Raises:

Type Description
NotFoundError

If there's no such job.

close

close() -> None

Stop the runner: queued jobs are dropped and running workers ended.

is_ml

is_ml(name: str) -> bool

Whether the operation name is a machine-learning job (one at a time).

add_job_routes

add_job_routes(
    app: Any,
    api_version: str,
    envelope: Any,
    runner: JobRunner,
) -> None

Add the job routes and make app.state.submit_job queue jobs on runner.

Workspaces and files

bioamla.server.workspaces_api

Workspace and file routes: the server's workspaces, their settings and their files.

  • GET /v1/workspaces: the workspaces under the server root
  • POST /v1/workspaces: create one ({"name", "title"})
  • GET /v1/workspaces/{ws}: its status (metadata, artifact counts, last runs)
  • GET /v1/workspaces/{ws}/config: its settings (.bioamla/config.toml)
  • PUT|DELETE /v1/workspaces/{ws}/config/{key}: set ({"value"}) or remove one
  • GET /v1/workspaces/{ws}/files?path=&recursive=&sha256=: list a folder (or one file), with each file's SHA-256 when asked
  • GET /v1/workspaces/{ws}/files/{path}: download a file
  • PUT /v1/workspaces/{ws}/files/{path}: upload a file (the request body, as is; ?overwrite=true to replace one)
  • GET /v1/workspaces/{ws}/audio/{path}?start=&duration=&sample_rate=: a window of a recording, decoded on the server and returned as a float32 WAV, so a viewer can show a few seconds of a long recording without downloading it

Every path goes through the server's path policy, so it must resolve inside the workspace root or a linkable folder, and never to a workspace's metadata. Uploads go only into the workspace named in the URL. To use recordings in a linkable folder without copying them, link them with the workspace.add operation.

The server only writes a workspace's own settings, never the server user's file.

add_workspace_routes

add_workspace_routes(
    app: FastAPI, api_version: str, envelope: Any
) -> None

Add the workspace and file routes to app.

OpenAPI document

bioamla.server.openapi

The server's OpenAPI document, as committed in docs/api/openapi.json.

A running server serves its own at /v1/openapi.json; this is the same document for an app with no workspaces, with info.version set to the API version (v1) rather than the bioamla version, so it changes only when the API does. Regenerate it with bioamla serve --openapi docs/api/openapi.json; a test fails while the committed file is out of date.

openapi_spec

openapi_spec() -> dict[str, Any]

The OpenAPI document of the /v1 API.

Raises:

Type Description
DependencyError

If an extra is missing: its operations would have no routes, so the document would be incomplete. Generate it with every extra (pip install 'bioamla[all,server]').

write_openapi_spec

write_openapi_spec(path: str | Path) -> Path

Write :func:openapi_spec to path as indented JSON.

Raises:

Type Description
DependencyError

If an extra is missing (see :func:openapi_spec).

OSError

If it can't be written.