Skip to content

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.

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.

from aster import AsterServer
from 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+C

This 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.

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
)

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, rpc
from dataclasses import dataclass
@dataclass
class HelloRequest:
name: str = ""
@dataclass
class HelloResponse:
message: str = ""
@service
class HelloService:
@rpc
async def say_hello(self, req: HelloRequest) -> HelloResponse:
return HelloResponse(message=f"Hello, {req.name}!")

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.

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 overrides
config = AsterConfig.from_file("aster.toml")
# Inline for testing
config = AsterConfig(
root_pubkey=pub_bytes,
allow_all_consumers=False,
)

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
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
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.

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

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.

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 cancellation

serve() 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.

Cancels all subtasks and shuts down the node. Called automatically by async with on exit.

await srv.close() # safe to call multiple times

AsterServer builds one Iroh node with one endpoint ID. That endpoint serves:

One identity, separate protocol connectionsOne Iroh endpointShared identity and network configurationProtocol routerSelects the handler by ALPNData protocolsBlobsImmutable contentDocumentsSigned, replicated entriesGossipLive peer messagesAster protocolsRPCaster/1Consumer admissionaster.consumer_admissionOne identity, separate protocol connectionsOne Iroh endpointShared identity and network configurationProtocol routerSelects the handler by ALPNData protocolsBlobsImmutable contentDocumentsSigned, replicated entriesGossipLive peer messagesAster protocolsRPCaster/1Consumer admissionaster.consumer_admission
Each ALPN uses its own QUIC connection. Sharing an endpoint does not put RPC, blobs, and gossip on one connection.

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.

All properties require that start() has been called (they raise RuntimeError otherwise).

srv.address # aster1... connection address (one address for everything)
srv.root_pubkey # bytes | None -- the root public key for this deployment
srv.services # list[ServiceSummary]

Each ServiceSummary has:

  • name – service name (from the @service decorator)
  • version – service version (default 1)
  • contract_id – deterministic BLAKE3 hash of the canonical service contract
  • channels – dict mapping channel name to base64 NodeAddr
for s in srv.services:
print(f"{s.name} v{s.version} contract_id={s.contract_id[:16]}...")

The server exposes lazy clients for all iroh protocols:

# Content-addressed blob storage
hash_and_tag = await srv.blobs.add_bytes(b"hello world")
# CRDT document sync
doc = await srv.docs.create()
# Pub-sub gossip
topic = await srv.gossip.subscribe(topic_id, [])
# Escape hatch: the raw IrohNode
node_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

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 is unsupported. Keep allow_all_producers=True or omit it; setting it to False raises NotImplementedError. It does not enable a second credential workflow.

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.

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 asyncio
from dataclasses import dataclass
from aster import AsterServer, AsterConfig, service, rpc
@dataclass
class TaskRequest:
task_id: str = ""
payload: str = ""
@dataclass
class 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())

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:

Terminal window
# Identity file (contains node key + enrollment credential):
ASTER_IDENTITY_FILE=/etc/aster/.aster-identity # default: .aster-identity in cwd
# Network
ASTER_RELAY_MODE=default
ASTER_BIND_ADDR=0.0.0.0:9000
# Storage
ASTER_STORAGE_PATH=/var/lib/aster # omit for in-memory

The 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:

aster.toml
[trust]
allow_all_consumers = false
allow_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)