Python server
AsterServer makes Python service methods callable by other peers. It owns
one Iroh node and the RPC dispatcher; your application supplies decorated
handlers and owns any files, downstream requests, or subscriptions they use.
The same node can also provide blobs, documents, and gossip, each with its own
capability and resource requirements.
Before you start
Section titled “Before you start”Follow the complete Python tutorial for installation and matching producer/consumer definitions. The fragments here assume their named service classes are available. Start with a shared unary service; add streams for incremental messages or a session factory for private state across calls. Protected access also needs a deployment trust root and provisioned consumer credentials; a public ticket alone grants no permission.
Register and serve
Section titled “Register and serve”from aster import AsterServerfrom my_services import HelloService
async with AsterServer(services=[HelloService()], allow_all_consumers=True) as srv: print(f"Listening at: {srv.address}") await srv.serve() # blocks until Ctrl+CThis development fragment permits unenrolled consumers and requires the
imported service implementation. Entering the context starts the node and
launches serving; awaiting serve() keeps this task alive. Exiting the context
closes the server. Use the tutorial for the complete runnable program.
Constructor
Section titled “Constructor”This signature sketch uses application-supplied values. Optional overrides
are only needed when configuration and identity loading do not supply them;
trusted_root_public_key must contain the deployment’s 32-byte public key.
AsterServer( services=[HelloService(), OtherService()], # required config=AsterConfig(...), # optional identity=".aster-identity", # optional: path to identity file peer="billing-producer", # optional: select peer from identity file root_pubkey=trusted_root_public_key, # optional override allow_all_consumers=True, # optional override allow_all_producers=True, # optional override codec=ForyCodec(...), # optional interceptors=[DeadlineInterceptor()], # optional)services (required)
Section titled “services (required)”Pass @service-decorated instances for shared services and decorated classes
for session-scoped factories. At least one service is required; an empty list
raises ValueError. A session class must accept peer in its constructor so
the runtime can create a fresh instance for each connection-scoped session.
from aster import service, rpcfrom dataclasses import dataclass
@dataclassclass HelloRequest: name: str = ""
@dataclassclass HelloResponse: message: str = ""
@serviceclass HelloService: @rpc async def say_hello(self, req: HelloRequest) -> HelloResponse: return HelloResponse(message=f"Hello, {req.name}!")peer (optional)
Section titled “peer (optional)”Selects a peer entry from the .aster-identity file by name. When an .aster-identity file is present (in the current directory or at the path set by ASTER_IDENTITY_FILE), AsterServer loads the node secret key and the matching producer credential automatically.
# With identity file -- loads node key + root_pubkey from .aster-identity:async with AsterServer(services=[MyService()], identity=".aster-identity", peer="billing-producer", allow_all_consumers=False) as srv: await srv.serve()If identity is omitted, AsterServer auto-detects .aster-identity in the current directory (or the path set by ASTER_IDENTITY_FILE). If peer is omitted, it auto-selects the first [[peers]] entry with role = "producer". Without an identity file, explicit configuration still applies. Set
allow_all_consumers=True explicitly for an ephemeral development server.
For protected access, pass allow_all_consumers=False explicitly even when
the identity entry supplies a root; wrapper development-mode detection also
examines the base config.
The identity file provides: the node secret_key (stable EndpointId), the root_pubkey (trust anchor for the mesh), and the signed enrollment credential. You do not need to set root_pubkey, ASTER_SECRET_KEY, or ASTER_ROOT_PUBKEY_FILE separately when using an identity file.
config (optional)
Section titled “config (optional)”An AsterConfig object that bundles trust, storage, and network settings. If you do not pass one, AsterServer calls AsterConfig.from_env() automatically, which reads ASTER_* environment variables.
from aster import AsterConfig
# From environment variables (default behavior)config = AsterConfig.from_env()
# From a TOML file with env overridesconfig = AsterConfig.from_file("aster.toml")
# Inline for testingconfig = AsterConfig( root_pubkey=pub_bytes, allow_all_consumers=False,)Inline overrides
Section titled “Inline overrides”These keyword arguments override the corresponding AsterConfig fields when both are present:
| Argument | Type | Default (from config) | Purpose |
|---|---|---|---|
peer |
str | None |
None |
Select a peer entry from .aster-identity by name |
root_pubkey |
bytes | None |
Resolved from config or identity file | 32-byte ed25519 root public key (deployment trust anchor) |
allow_all_consumers |
bool | None |
False |
Skip consumer admission gate |
allow_all_producers |
bool | None |
True |
Compatibility option; keep True. False raises NotImplementedError |
Serialization and interceptors
Section titled “Serialization and interceptors”| Argument | Type | Default | Purpose |
|---|---|---|---|
codec |
ForyCodec | None |
Auto-created XLANG codec | Custom Fory serialization codec |
interceptors |
list | None |
[] |
Server-side interceptors applied to every RPC call |
Handler patterns and sessions
Section titled “Handler patterns and sessions”| Decorator | Handler shape |
|---|---|
@rpc |
Async request → response |
@server_stream |
Async generator yielding responses |
@client_stream |
Async request iterator → one response |
@bidi_stream |
Async request iterator → async response generator |
Use explicit wire types and matching request/response annotations. The service guide covers decorators and streaming examples. Yield responses incrementally, propagate cancellation into downstream work, and avoid holding shared locks while waiting for stream backpressure.
@service(..., scoped="session") declares state for a connection-scoped
session ID. Pass that decorated class, rather than an existing instance, in
services so the runtime can construct private state. For a CounterService
declared with session scope and a constructor accepting peer, registration is:
# API fragment: CounterService and its payloads are defined by the application.server = AsterServer(services=[CounterService], allow_all_consumers=True)This is open development registration; start and close it using the lifecycle below. Several sessions may share a connection, and calls within a session can overlap. Keep mutable state safe across asynchronous interleaving. See the session guide for lifecycle and factories.
Rust enforces effective call deadlines and capability requirements before application dispatch. Use typed RPC errors for intended application refusals; unexpected failures become internal statuses. Do not assume timeout or cancellation rolls back a completed mutation. Release application subscriptions and other resources before server shutdown.
Lifecycle
Section titled “Lifecycle”| Operation | State and application responsibility |
|---|---|
Construct AsterServer |
Hold configuration and service definitions; no running endpoint yet |
await start() |
Create the node and service metadata; address becomes available |
serve() |
Start dispatcher/handler tasks and return their task; await it to retain application lifetime |
await close() |
Cancel server tasks and shut down the owned node; release application resources first |
async with |
Perform startup and begin serving on entry; close on exit |
Phase 1: start()
Section titled “Phase 1: start()”Creates the iroh node and computes service metadata. Called automatically by async with.
Startup resolves configuration, creates the node, and registers service
metadata. serve() owns the subsequent dispatcher and handler tasks.
After start(), you can read properties like srv.address and srv.services.
Phase 2: serve()
Section titled “Phase 2: serve()”Spawns background tasks and returns an asyncio.Task. The task runs until cancelled.
async with AsterServer(services=[HelloService()], allow_all_consumers=True) as srv: # serve() is called automatically by __aenter__, but you can also call it manually: task = srv.serve() # returns an asyncio.Task (idempotent) await task # blocks until cancellationserve() starts the Rust dispatcher and its Python handler tasks. Rust accepts
RPC connections and enforces Gate 0. Consumer-admission connections are
forwarded to Python for credential verification and service discovery, including
in open development mode. An optional background task registers published services.
Phase 3: close()
Section titled “Phase 3: close()”Cancels all subtasks and shuts down the node. Called automatically by async with on exit.
await srv.close() # safe to call multiple timesThe unified node
Section titled “The unified node”AsterServer builds one Iroh node with one endpoint ID. That endpoint serves:
The protocols share the node’s identity and connection pool. Each QUIC connection negotiates one ALPN. Admission allows a peer through the configured connection gate; it does not grant every RPC role, document namespace, blob, or gossip capability. Supply the permissions required by the chosen protocol as described in the data guide.
Properties
Section titled “Properties”All properties require that start() has been called (they raise RuntimeError otherwise).
Identity and addressing
Section titled “Identity and addressing”srv.address # aster1... connection address (one address for everything)srv.root_pubkey # bytes | None -- the root public key for this deploymentService metadata
Section titled “Service metadata”srv.services # list[ServiceSummary]Each ServiceSummary has:
name– service name (from the@servicedecorator)version– service version (default 1)contract_id– deterministic BLAKE3 hash of the canonical service contractchannels– dict mapping channel name to base64NodeAddr
for s in srv.services: print(f"{s.name} v{s.version} contract_id={s.contract_id[:16]}...")Iroh protocol access
Section titled “Iroh protocol access”The server exposes lazy clients for all iroh protocols:
# Content-addressed blob storagehash_and_tag = await srv.blobs.add_bytes(b"hello world")
# CRDT document syncdoc = await srv.docs.create()
# Pub-sub gossiptopic = await srv.gossip.subscribe(topic_id, [])
# Escape hatch: the raw IrohNodenode_id = srv.node.endpoint_id()| Property | Type | Description |
|---|---|---|
srv.blobs |
BlobsClient |
Content-addressed blob storage |
srv.docs |
DocsClient |
CRDT document sync |
srv.gossip |
GossipClient |
Pub-sub gossip messaging |
srv.node |
IrohNode |
Raw node (escape hatch for advanced use) |
srv.endpoint |
NetClient |
Low-level QUIC endpoint access |
Admission flags
Section titled “Admission flags”Consumer admission (allow_all_consumers)
Section titled “Consumer admission (allow_all_consumers)”Controls whether consumers must present a credential before making RPC calls.
| Value | Behavior |
|---|---|
False (default) |
Consumer admission is active. The aster.consumer_admission ALPN is registered. Consumers must run the admission handshake (present a signed credential) before they can connect on aster/1. |
True |
Open development admission. Peers can connect directly; method capability requirements still apply. |
Producer admission (allow_all_producers)
Section titled “Producer admission (allow_all_producers)”Producer admission is unsupported. Keep allow_all_producers=True or
omit it; setting it to False raises NotImplementedError. It does not enable
a second credential workflow.
Gate 0: connection-level access control
Section titled “Gate 0: connection-level access control”Rust enforces the connection admission gate. The consumer-admission ALPN remains reachable so credentials can be presented. Successful admission adds the peer’s endpoint ID to the allowlist; protected non-admission protocols reject unknown peers. Individual protocols and RPC methods can still apply further permissions.
Protected producer example
Section titled “Protected producer example”This protected producer requires a provisioned .aster-identity with a
task-producer entry and deployment trust root. For a local development
program without provisioning, use the quickstart.
import asynciofrom dataclasses import dataclassfrom aster import AsterServer, AsterConfig, service, rpc
@dataclassclass TaskRequest: task_id: str = "" payload: str = ""
@dataclassclass TaskResponse: status: str = "" result: str = ""
@service("TaskRunner", version=2)class TaskRunnerService: @rpc(timeout=30.0, idempotent=True) async def run_task(self, req: TaskRequest) -> TaskResponse: # Your business logic here return TaskResponse(status="completed", result=f"Processed {req.task_id}")
async def main(): config = AsterConfig.from_env()
async with AsterServer( services=[TaskRunnerService()], config=config, identity=".aster-identity", peer="task-producer", allow_all_consumers=False, ) as srv: print(f"TaskRunner v2 serving at {srv.address}") for s in srv.services: print(f" {s.name} contract_id={s.contract_id}")
# You can also use iroh protocols alongside RPC: blob_hash = await srv.blobs.add_bytes(b"model weights v2.1") print(f"Stored blob: {blob_hash}")
await srv.serve()
asyncio.run(main())Configuration via environment
Section titled “Configuration via environment”When no config= is passed, AsterServer calls AsterConfig.from_env(). The recommended production approach is to use an .aster-identity file (generated by aster enroll node) alongside environment variables for deployment-specific settings:
# Identity file (contains node key + enrollment credential):ASTER_IDENTITY_FILE=/etc/aster/.aster-identity # default: .aster-identity in cwd
# NetworkASTER_RELAY_MODE=defaultASTER_BIND_ADDR=0.0.0.0:9000
# StorageASTER_STORAGE_PATH=/var/lib/aster # omit for in-memoryThe config object resolves environment and TOML settings first. The server then merges the selected identity entry and applies explicit constructor overrides. An identity file can therefore supply the node key and trust root without separate environment variables. See configuration for the distinction between config resolution and wrapper overrides.
You can also use a TOML file for network and storage settings:
[trust]allow_all_consumers = falseallow_all_producers = true
[network]relay_mode = "default"
[storage]path = "/var/lib/aster"config = AsterConfig.from_file("aster.toml")async with AsterServer(services=[...], config=config, identity=".aster-identity", peer="billing-producer", allow_all_consumers=False) as srv: ...Use config.print_config() to inspect the config object’s values and their
provenance. It does not report every later wrapper override; also inspect the
identity selection and constructor arguments when diagnosing startup:
[trust] root_pubkey : <not set> (default) allow_all_consumers : False (default) allow_all_producers : True (default) [network] secret_key : <not set> (default) relay_mode : <default> (default)