The FastAPI pattern
The library's second example front end puts the TUI crawler's barrow adventure behind an HTTP API: the same authored content behind a terminal and a web server. osrlib behaves the same whichever of the two calls the GameSession. The server patterns the example demonstrates are the per-session lock, the interpreter registered on both session paths, player visibility enforced before data leaves the server, saves that never leave the server, and the mapping from osrlib's typed exceptions to HTTP statuses. The exception hierarchy and the status map below covers osrlib.errors in full. Run instructions are in the example's README on GitHub.
The example is small, five endpoints in examples/fastapi_crawler/app.py, and every server snippet below is included from that file, so the page always matches the code. The server snippets don't run on their own. The one self-contained runnable block is the exception demonstration.
One session, one lock
A GameSession executes one command at a time and isn't safe to share across threads. FastAPI runs plain def endpoints in a threadpool, so any two requests can run concurrently. The store makes that safe by giving every session a separate lock:
_store_lock = threading.Lock()
_sessions: dict[str, tuple[GameSession, threading.Lock]] = {}
_saves: dict[str, dict] = {}
The server holds the session's lock for every execute and every view read, so one session's commands run one at a time while separate sessions run in parallel. The outer _store_lock only guards the dictionaries themselves. The endpoints are deliberately synchronous: the engine is synchronous and CPU-bound, so an async facade would add nothing.
Creating and restoring sessions
A session begins with a stamped party document (the JSON envelope party_to_document produces and party_from_document validates) or with a save id from an earlier server-side snapshot. The request must have exactly one of the two, and the request model checks that before the handler runs:
class CreateSession(BaseModel):
"""The `POST /sessions` body: a stamped party document, or a save id to restore.
`seed` exists for reproducible demos and the tests; production clients omit it
and the server draws one — the master seed is a server-side secret either way.
"""
party_document: dict | None = None
save_id: str | None = None
seed: int | None = None
@model_validator(mode="after")
def _party_or_save(self) -> CreateSession:
if (self.party_document is None) == (self.save_id is None):
raise ValueError("exactly one of party_document or save_id is required")
return self
The handler then branches on which field arrived:
@app.post("/sessions")
def create_session(request: CreateSession) -> dict:
"""Create a session from a party document, or restore one from a server-side save.
The response carries the schema handshake and the new session id — never the
seed.
"""
if request.save_id is not None:
with _store_lock:
document = _saves.get(request.save_id)
if document is None:
raise HTTPException(status_code=404, detail=f"unknown save id {request.save_id!r}")
session = restore_session(document)
elif request.party_document is not None:
members = party_from_document(request.party_document)
seed = request.seed if request.seed is not None else secrets.randbits(63)
session = new_session(Party(members=members), seed=seed)
else: # unreachable: the body model requires exactly one of the two
raise HTTPException(status_code=422, detail="exactly one of party_document or save_id is required")
session_id = secrets.token_hex(8)
with _store_lock:
_sessions[session_id] = (session, threading.Lock())
return {"session_id": session_id, "schema_version": SCHEMA_VERSION, "engine_version": engine_version()}
Look at two details of that handler:
- The master seed is a server secret. By default the server draws it (
secrets.randbits(63)) and no response ever contains it, because a client with the seed can predict every roll the engine will make. The optionalseedfield exists for reproducible demos and tests, and even when the client supplies it, the server never sends it back. - The response is the schema handshake.
schema_versionandengine_versioncome fromosrlib.versioning, so a client can detect a server whose schema version is newer than the client's before it sends anything else. Determinism, saves, and replay covers what each version stamp guarantees.
The served content and its interpreter
The barrow is authored content: gated doors, a fetch quest, the works. The content does nothing until you register the Interpreter on the session (see Gates, triggers, and quests). The server does that setup in content.py, on both entry paths: the fresh session and the restored one. For a fresh session, the server registers the interpreter as soon as it builds the session:
def new_session(party: Party, *, seed: int) -> GameSession:
"""Create a session serving the barrow, with the adventure's quest in play.
Args:
party: The party, in marching order.
seed: The master seed — a server-side secret.
Returns:
The session, in town, at round 0.
"""
session = GameSession.new(party, build_adventure(), seed=seed)
session.register_listener(Interpreter(session))
return session
For a restored session, the server registers it again, because a save contains data and a listener is code. The save has the quest's state, the fired-marks, and the journal, but the session can't react to any of it until the server attaches the listener again:
def restore_session(document: Mapping[str, object]) -> GameSession:
"""Restore a session from a save document, re-registering the interpreter.
Args:
document: A save document from the server-side store.
Returns:
The restored session.
Raises:
ContentValidationError: If the save document is malformed.
SaveVersionError: If the save's schema version is newer than the engine's.
"""
session = load_game(document)
session.register_listener(Interpreter(session))
return session
If you forget the second registration, a restored barrow session still validates and loads, but its triggers and quests silently stop running.
The command endpoint
One endpoint accepts every command in the engine's registry, each a typed model with a JSON Schema (see the command schema reference). parse_command turns the request body into a typed command, returning None for a command_type that isn't in the registry:
@app.post("/sessions/{session_id}/commands")
def execute_command(session_id: str, body: dict) -> dict:
"""Parse and execute one command under the session lock.
An unknown `command_type` is a 422 (the additive-schema contract: this server
doesn't understand the command, so it never reaches the engine). A rejected
command is a 200 — rejections are game feedback, and they cost the client
nothing: no draws, no clock time, no log entry.
"""
session, lock = _session_or_404(session_id)
command = parse_command(body)
if command is None:
raise HTTPException(status_code=422, detail=f"unknown command type {body.get('command_type')!r}")
with lock:
result = session.execute(command)
return {
"accepted": result.accepted,
"rejections": [rejection.model_dump(mode="json") for rejection in result.rejections],
"events": [event.model_dump(mode="json") for event in result.events if event.visibility is Visibility.PLAYER],
}
A request has one of three outcomes, checked in order:
- An unknown
command_typereturns 422 before the engine sees it: schemas grow additively, so a newer client may send commands this server doesn't have, and the server answers that it doesn't understand rather than guessing. - A known command with a malformed payload (a direction that doesn't exist, a negative quantity) raises
ContentValidationErrorinsideparse_command, which the exception handler below maps to 422. - A well-formed command executes under the session lock and returns the
CommandResultenvelope:accepted, the rejections, and the events, filtered toVisibility.PLAYERon their way out. Referee-visibility events (hidden rolls, referee bookkeeping) never cross the wire.
Rejections are results, not errors
The status codes in this API follow one rule: an in-fiction rejection is a 200. When the party tries to walk through a wall, the engine rejects the command. That's a rules outcome the client should render, not a transport failure. The response arrives with accepted: false and a machine-readable rejection code (see the rejection code reference), and it costs the client nothing: a rejected command draws no dice, advances no clock, and appends nothing to the log, so a confused client can probe freely without corrupting the game. Sessions, commands, and events teaches the rejection contract in depth.
Exceptions are the opposite case. An exception means the caller broke the out-of-fiction contract, for example by sending a malformed document or replaying an incompatible save. The server maps exceptions to 4xx and 5xx statuses.
The exception hierarchy and the status map
osrlib.errors is a small hierarchy of typed exceptions for out-of-fiction failures:
OsrlibError- the root. Catching it catches every exception that osrlib defines.ContentValidationError- malformed rules content at a library boundary: a dice expression that doesn't parse, an adventure that failsvalidate_adventure, a serialized document whose structure or kind isn't what the loader expects.SaveVersionError- a document whoseschema_versionis newer than this library understands, raised bycheck_documentso the library doesn't silently misread the payload.ReplayVersionError- a command log replayed under a different engine version, where any rules change may legitimately alter outcomes. The example never raises it (it exposes no replay endpoint), but a front end that replays command logs has to choose a status for it too.
Two kinds of failure are outside the hierarchy. Programmer misuse (bad argument types, out-of-range values) raises the standard library's ValueError or TypeError. That's a bug in the calling code, not a condition to map to a status. In-fiction refusals, as above, aren't exceptions at all.
The example registers one handler per exception type it expects, plus a 404 helper for ids that aren't in the store:
@app.exception_handler(ContentValidationError)
def _content_validation_error(request: Request, error: ContentValidationError) -> JSONResponse:
"""Malformed content — a bad party document or command payload — is a 422."""
return JSONResponse(status_code=422, content={"detail": str(error)})
@app.exception_handler(SaveVersionError)
def _save_version_error(request: Request, error: SaveVersionError) -> JSONResponse:
"""A document from a newer engine is a conflict with this server's, a 409."""
return JSONResponse(status_code=409, content={"detail": str(error)})
def _session_or_404(session_id: str) -> tuple[GameSession, threading.Lock]:
with _store_lock:
entry = _sessions.get(session_id)
if entry is None:
raise HTTPException(status_code=404, detail=f"unknown session id {session_id!r}")
return entry
This table lists every outcome and its status:
| Outcome | Where it comes from | Status |
|---|---|---|
| Rejected command | the engine rejected it: accepted is false |
200 |
Unknown command_type |
parse_command returns None |
422 |
ContentValidationError |
malformed party document, command payload, or save | 422 |
SaveVersionError |
a document stamped by a newer library | 409 |
| Unknown session or save id | the id isn't in the store | 404 |
| Anything else | a bug, by definition | 500 |
You can exercise the hierarchy without a server. This block runs as written:
from osrlib.errors import ContentValidationError, OsrlibError, ReplayVersionError, SaveVersionError
from osrlib.persistence import load_game
from osrlib.versioning import SCHEMA_VERSION, check_document
# The typed hierarchy: every failure osrlib raises on its own authority is an OsrlibError.
assert issubclass(ContentValidationError, OsrlibError)
assert issubclass(SaveVersionError, OsrlibError)
assert issubclass(ReplayVersionError, OsrlibError)
# A structurally broken document is malformed content: ContentValidationError (the app's 422).
try:
load_game({"kind": "not-a-save"})
raise AssertionError("expected ContentValidationError")
except ContentValidationError:
pass
# A document stamped by a newer library is a version conflict: SaveVersionError (the app's 409).
newer = {"kind": "save", "schema_version": SCHEMA_VERSION + 1, "payload": {}}
try:
check_document(newer, expected_kind="save")
raise AssertionError("expected SaveVersionError")
except SaveVersionError:
pass
The player view at the wire
The only read of the full game state that the API offers is the player projection, session.view(Visibility.PLAYER), serialized verbatim:
@app.get("/sessions/{session_id}/view")
def player_view(session_id: str) -> dict:
"""The player projection — the only game-state read the API offers."""
session, lock = _session_or_404(session_id)
with lock:
view = session.view(Visibility.PLAYER)
return view.model_dump(mode="json")
The API has no referee-view endpoint, because the server never trusts the client. The PlayerView is an enumerated whitelist of explored cells, public character sheets, masked magic items, monster groups without hit points, the journal as written, and the active quests with their revealed objectives. Unexplored geometry, undiscovered secret doors, monster internals, session flags, and the seed can't leak, because they were never in the projection to begin with. A client that renders only what this endpoint returns cannot cheat. Views and visibility goes through the whitelist field by field.
Authored content reaches a web client in two more ways, both through the command endpoint. The player-visible quest and journal events (a quest activated, an objective completed, a beat added) arrive in the response's events like any other, so an incremental client can render story progress without re-fetching the view. A gate's refusal arrives in rejections[].params.refusal: authored words the player is meant to read, in an ordinary accepted: false response, so a web client's rejection renderer should print that field when it is present (see Gates, triggers, and quests).
Saves stay on the server
A save document contains everything the API withholds: the master seed, referee state, and the full logs. The example never sends one anywhere. Snapshots go into a server-side store, and only an opaque id crosses the wire:
@app.post("/sessions/{session_id}/save")
def save_session(session_id: str) -> dict:
"""Snapshot into the server-side save store; only the opaque id crosses the wire."""
session, lock = _session_or_404(session_id)
with lock:
document = save_game(session)
save_id = secrets.token_hex(8)
with _store_lock:
_saves[save_id] = document
return {"save_id": save_id}
Restoring is the save_id path through POST /sessions above: the server calls load_game, re-registers the Interpreter (the one listener this server runs, shown in the served content section), and returns a new session id. The in-memory store is a deliberate simplification, and swapping in a database changes nothing about the pattern.
Where next
- Sessions, commands, and events - the command loop this API wraps: modes, rejections, the event log.
- Views and visibility - what the player projection contains and why.
- The command schema reference - every command this endpoint accepts, with its JSON Schema and legal modes.
- LLM referees - the opposite case: an agent that's supposed to see everything.