aster.public
Python API reference for Aster 0.3.893.
Generated from the installed public preview package. Import from aster in
applications. Use the tested quickstart
for a complete producer and consumer, and the
compatibility guide
for package and feature boundaries.
High-level, declarative producer.
Starts a single aster.Node that serves blobs + docs + gossip
(iroh built-in protocols) alongside aster RPC (aster/1) and any
enabled admission ALPNs -- all on one endpoint, one node ID.
Gate 0 is the Rust GatePolicy attached to the node (self.gate):
every inbound connection on every protocol (blobs, docs, gossip,
aster/1) is admitted or rejected in Rust at the QUIC handshake. With
consumer admission active (allow_all_consumers=False) the gate is
PROTECTED: only the admission ALPN is open until the peer presents a
valid credential, which admits it into the gate's store. With
allow_all_consumers=True it is OPEN_DEV.
Create an Aster RPC server.
Interceptors are not wired by default. Deadlines
(caller deadline, method timeout, handler_timeout) and
requires= (Gate 3) are enforced by the Rust dispatcher. The
other interceptors -- rate limiting, auth, circuit breaking,
metrics, audit logging, retry hints -- are active only when you
pass them via the interceptors parameter; for production use,
wire at least RateLimitInterceptor. All interceptors live in
aster.interceptors.
Args:
services: List of @service-decorated class instances to serve.
At least one is required.
config: Optional AsterConfig for trust, storage, and
networking settings. If omitted, settings are loaded from
environment variables and defaults. With storage_path
set the node is persistent; its key is kept in
secret_key_file (default <storage_path>/node.key).
peer: Optional peer name for this server (used in config lookup
and identity file resolution).
identity: Path to .aster-identity file (default: auto-detected
from CWD). Overrides config.identity_file.
root_pubkey: 32-byte ed25519 public key for the trust anchor.
Overrides config.root_pubkey if both are set.
allow_all_consumers: If True, skip consumer admission
(open gate). Overrides config.allow_all_consumers.
gate: Optional aster.GatePolicy to use as Gate 0
instead of the one derived from allow_all_consumers.
handler_timeout: Cap on any handler, in seconds (default 300;
<= 0 = no cap). Enforced in Rust together with the
caller's deadline and each method's timeout.
allow_all_producers: Must be True (the default). Producer
mesh admission (aster.producer_admission) is not
supported; False raises NotImplementedError.
Overrides config.allow_all_producers.
Example::
@service(name="MyService", version=1)
class MyService:
@rpc()
async def hello(self, req: HelloRequest) -> HelloResponse:
return HelloResponse(message=f"Hello {req.name}")
async with AsterServer(services=[MyService()]) as srv:
print(srv.address)
await srv.serve()
Spawn the accept loop; return an aggregate task. (Gate 0 runs in Rust.)
await server.serve() blocks until cancellation. The second call
returns the same task (idempotent).
Graceful shutdown: stop accepting new connections, drain existing ones.
Compatible with Kubernetes preStop hooks and SIGTERM handling.
After drain completes, call close() to shut down the node.
Args: grace_period: Seconds to wait for in-flight requests to complete.
Connection address for this server (aster1... ticket).
Pass this to AsterClient(address=...) or aster shell
to connect. Includes relay address (if available) and direct
addresses for LAN connectivity.
TEST-ONLY. Snapshot of per-connection session state for
tier-2 chaos test assertions. Maps connection_id to a dict
with keys active_session_count and last_opened_session_id.
Production code MUST NOT read this -- it exists so tests can
verify reap semantics (connection entries drop on close) and
session accounting without reaching into private fields.
Mirrors TypeScript AsterServer2.debugConnectionSnapshot
and Java AsterServer.debugConnectionSnapshot.
High-level, declarative consumer.
Reads configuration from AsterConfig (env vars / TOML file)
just like AsterServer. In dev mode (no credentials, ephemeral
producer), AsterClient() with just ASTER_ENDPOINT_ADDR set is
enough. In production, set ASTER_ENROLLMENT_CREDENTIAL to the
path of a pre-signed token from the operator.
endpoint_addr may be a base64 NodeAddr string (as printed by
AsterServer), an EndpointId hex string (when discovery is
enabled), a NodeAddr object, or raw NodeAddr.to_bytes()
bytes.
Create an Aster RPC client.
Args:
config: Optional AsterConfig. If omitted, settings are
loaded from environment variables.
peer: Peer name for identity file lookup.
identity: Path to .aster-identity file (default: auto-detected
from CWD). Overrides config.identity_file.
address: The server's address. Accepts:
- aster1... compact ticket (recommended)
- Base64-encoded NodeAddr
- Hex EndpointId (requires discovery)
endpoint_addr: Alias for address (back-compat).
root_pubkey: 32-byte ed25519 public key of the server's trust
anchor. Required for credential-based admission.
enrollment_credential_file: Path to a pre-signed enrollment
credential (.cred file from aster enroll).
Example::
# Dev mode -- open gate, no credentials
client = AsterClient(address="aster1...")
await client.connect()
# Production -- with credential
client = AsterClient(
address="aster1...",
root_pubkey=pub_key,
enrollment_credential_file="my-agent.cred",
)
await client.connect()
Create endpoint, run admission if credential present, store services.
Idempotent -- second call is a no-op.
Reconnect after a connection drop.
Closes stale connections, re-runs admission, and rebuilds the services list. Uses exponential backoff on repeated failures.
Open a new client-bound session against the peer's RPC
connection. Allocates a fresh monotonic sessionId (per spec
§6) on the underlying (peer, connection); every RPC made via
ClientSession.client(...) threads that id into its
StreamHeader so the server routes them into the same
session-scoped service instance.
service_cls picks which of the producer's announced RPC
addresses to bind to. If omitted, the first advertised RPC
channel on any service is used -- fine when the producer only
serves one channel but explicit is clearer.
Return an RPC client for service_cls.
64-char hex namespace_id for the registry doc.
Empty string if no registry doc was provided by the producer.
True if the server admitted this client without a credential.
When True, the server is running with allow_all_consumers=True
and no credential was required. Useful for clients (e.g. the shell)
that want to suppress identity-related banners that are irrelevant
on open-gate servers.
Create a dynamic proxy client for a shared (stream-per-call) service.
On first call per service, fetches the published contract manifest
from the producer's registry doc, synthesises request/response types
via DynamicTypeFactory, and builds a Fory XLANG codec that
speaks the same wire as the typed client. Subsequent calls to
proxy(...) for the same service reuse the cached manifest.
No local type definitions needed -- call methods with dicts and receive dicts back::
mc = await client.proxy("MissionControl")
result = await mc.getStatus({"agent_id": "edge-1"})
print(result["status"])
For session-scoped services, use session() instead.
Args:
service_name: The service name (e.g., "MissionControl").
Returns:
A ProxyClient with method stubs for each RPC method.
Raises:
TypeError: If the service is session-scoped (use session()).
Create a dynamic proxy client for a session-scoped service.
Opens a single bidirectional QUIC stream and multiplexes calls over it. Maintains a lock to ensure one call in flight at a time (spec requirement). Call methods with dicts, receive dicts::
agent = await client.session("AgentSession")
result = await agent.register({"agent_id": "edge-1"})
print(result["assignment"])
await agent.close()
For shared (stream-per-call) services, use proxy() instead.
Args:
service_name: The service name (e.g., "AgentSession").
Returns: A session proxy with method stubs. Must be closed when done.
Node, trust, storage and logging configuration (frozen).
Three ways to get one::
config = AsterConfig.from_env() # ASTER_* env
config = AsterConfig.from_file("aster.toml") # file, then env overrides
config = AsterConfig(storage_path="/var/lib/app", relay_mode="disabled")
Derive a modified copy with replace(). Pass it to
aster.Node.start(), aster.AsterServer or
aster.AsterClient. Construction validates every value through
the Rust aster::AsterConfig (ValueError / TypeError on bad
input).
File holding the root public key (hex, or JSON {"public_key": ...}).
Cloud instance identity document token (ASTER_ENROLLMENT_CREDENTIAL_IID).
Producer address a consumer dials (aster1... ticket / NodeAddr / id).
32-byte node key (accepts SecretKey / 64-hex too). Fixes the node id.
Force the listener on or off; None enables it when health_port != 0.
Defaults overlaid with ASTER_* environment variables.
aster.toml overlaid with ASTER_* environment variables.
Raises FileNotFoundError for a missing file and ValueError for
malformed TOML or invalid values.
A copy with changes applied (validated); provenance is kept.
The root public key from root_pubkey and/or root_pubkey_file.
A missing file is ignored. A malformed file, or a file that disagrees
with the inline key, raises ValueError.
The effective node key: secret_key_file (loaded, or created
from secret_key / a fresh key) or secret_key. None when
neither is set (the node then gets a fresh identity). Writes the key
file when it is missing -- the same step Node.start performs.
identity_file if it exists, else ./.aster-identity if it
exists, else None.
Load [node] secret_key and a [[peers]] entry from the
.aster-identity credential file.
Peer selection: peer_name wins; else the first peer with role;
else the first peer. Returns (None, None) when no identity file is
configured or found in the working directory.
Like load_identity(), from an explicit path.
Render the resolved configuration with provenance and masking.
Sensitive fields (secret_key, enrollment_credential_file,
enrollment_credential_iid) are masked. Returns the rendered text
(also printed to stdout).
A running Aster node (blobs + docs + gossip, plus any extra ALPNs).
Start a node from config (an aster.AsterConfig; default: an
in-memory node with default relays). alpns adds inbound ALPNs on top
of config.alpns; poll them with accept_aster().
gate attaches a GatePolicy (and turns admission hooks on): every
inbound peer is then admitted or rejected in Rust by that policy.
The node is persistent when config.storage_path is set. A
config.secret_key_file is loaded, or created (mode 0600) from
config.secret_key or a fresh key; a malformed file, or one that
disagrees with secret_key, raises ValueError.
The node's secret key (restore the identity via
AsterConfig(secret_key=...) or persist it with write_file).
Await the next incoming connection on a custom ALPN. Returns
(alpn: bytes, IrohConnection). Raises when the node closes.
This node's admission requests as an async iterator (async for req
in node.admission()). Needs enable_hooks=True and no gate; can be
taken once. With outbound=True this node's own dials are yielded too
(as ConnectRequest); otherwise they are allowed.
Decide Gate 0 in Python over the upcall channel instead of the
admission() iterator: handler is an aster.AdmissionHandler
(async def connect(peer, alpn) -> bool, async def handshake(peer,
alpn, is_alive) -> bool | (code, reason); a missing method answers
unimplemented, so that kind's failure mode decides). Each request
is its own asyncio task; no answer applies the admission_connect /
admission_handshake upcall policy (fail-closed: a handshake rejects
with 403 "hook unavailable"). Keep that policy's timeout below the
node's hook timeout. Needs enable_hooks=True and no gate; takes
the node's admission (the iterator is then unavailable).
This node's expose registry (aster.Expose): expose local sockets
to peers, with an optional Python authorize hook.
Teach this node how to reach other directly (tests / local setups).
This node's topology view (v1 per-peer proximity; v2 shared swarm).
Populates only when the node runs with enable_monitoring=True.
A lease backend on the designated grantor grantor_id
(aster.lease.Grantor over RPC). Every op is bound to this node's
authenticated identity. The grantor must be dialable (discovery or
add_node_addr). Awaitable GrantorSerializer.
Serve aster.lease.Grantor over serializer (a MemorySerializer,
with its authorizer if set, or a Python aster.lease.LeaseSerializer
answered by upcall) on this node, making it a designated grantor. Start the node with
alpns=[b"aster/1"]. This owns the node's RPC accept loop -- don't
also run an RPC server on it. open_revoke=True lets any admitted
caller revoke (default: the operator role only). Returns a
LeaseGrantorServer; close() stops serving.
A node secret key (32-byte Ed25519 seed). Its repr never shows the key.
The on-disk form is the secret key file: 64 hex characters plus a
newline (read_file / write_file / load_or_generate), shared with the
Rust SDK and every other binding.
A 32-byte Ed25519 public key (an identity / trust anchor).
A node / endpoint id (the node's Ed25519 public key, 64 hex chars). Equal to (and hashes like) its hex string.
Class decorator to mark a class as an Aster RPC service.
Supports three calling forms::
@service # bare -- name = class name
@service("AgentControl") # explicit name
@service(name="AgentControl", version=2) # keyword name
@service(version=2, scoped="session") # keyword-only, name = class name
Args:
name_or_cls: Service name (str), or the class itself when used as
bare @service without parentheses. Defaults to the class name.
name: Explicit service name (keyword-only alias for name_or_cls).
version: The service version (default: 1).
serialization: Supported serialization modes. Defaults to [XLANG].
scoped: Service scope: "shared" or "session". Default "shared".
The legacy alias "stream" is still accepted on input.
interceptors: List of interceptor classes to apply to all methods.
max_concurrent_streams: Maximum concurrent QUIC streams per
connection (i.e. per client peer). When a client exceeds
this limit, additional streams are rejected at the QUIC
layer. This applies to the server as a whole, not
per-service. None means unlimited.
Returns: A decorator function (or the decorated class if used bare).
Decorator to mark a method as a server-streaming RPC.
Can be used as: @server_stream # without parens @server_stream() # with parens @server_stream(timeout=30.0) # with options
Args: method_or_timeout: Either the method (when used without parens) or a timeout value. timeout: Optional timeout in seconds. serialization: Override the serialization mode for this method.
Returns: A decorator function or the decorated method.
Example::
@service(name="MyService", version=1)
class MyService:
@server_stream
async def watch_items(self, req: WatchRequest) -> AsyncIterator[ItemUpdate]:
for item in items:
yield ItemUpdate(item=item)
Decorator to mark a method as a client-streaming RPC.
Can be used as: @client_stream # without parens @client_stream() # with parens @client_stream(timeout=30.0) # with options
Args: method_or_timeout: Either the method (when used without parens) or a timeout value. idempotent: Whether the method is safe to retry. serialization: Override the serialization mode for this method.
Returns: A decorator function or the decorated method.
Example::
@service(name="MyService", version=1)
class MyService:
@client_stream
async def aggregate(self, reqs: AsyncIterator[NumberRequest]) -> SumResponse:
total = 0
async for req in reqs:
total += req.value
return SumResponse(total=total)
Decorator to mark a method as a bidirectional-streaming RPC.
Can be used as: @bidi_stream # without parens @bidi_stream() # with parens @bidi_stream(timeout=30.0) # with options
Args: method_or_timeout: Either the method (when used without parens) or a timeout value. timeout: Optional timeout in seconds. serialization: Override the serialization mode for this method.
Returns: A decorator function or the decorated method.
Example::
@service(name="MyService", version=1)
class MyService:
@bidi_stream
async def chat(
self, requests: AsyncIterator[ChatMessage]
) -> AsyncIterator[ChatMessage]:
async for req in requests:
yield ChatMessage(text=f"echo: {req.text}")
Declare a stable wire identity for a dataclass.
The tag string is split on the last / into
(namespace, typename). If there is no /
the namespace is the empty string.
Use @wire_type when you need explicit control over the wire
identity of a type (production services, cross-language compat).
If omitted, the @service decorator auto-derives a tag from the
module + class name at decoration time.
Args:
tag: Wire type tag (e.g., "billing/Invoice").
metadata: Optional dict mapping field names to Metadata objects
for describing individual fields to AI agents.
Example::
@wire_type("billing/Invoice")
@dataclass
class Invoice:
customer: str = ""
amount: float = 0.0
paid: bool = False
Serialization rules:
Supported field types:
str,int,float,bool,bytes,list[T],dict[str, V],Optional[T], and other@wire_typedataclasses.Use
Optional[T]for nullable fields.Integer widths: a plain
intis a zig-zagvarint64(Rusti64). Usepyfory.Int32forvarint32(Rusti32),pyfory.FixedInt32for a fixed 4-byteint32,pyfory.Int8/pyfory.Int16/pyfory.Float32etc. for the other widths.Every field must have a default value. Fory XLANG needs defaults for construction. Use
""for strings,0for ints,Falsefor bools, andfield(default_factory=list)for collections. Such defaults are not part of the contract (the field is published as required); usecontract_default()to publish one.@rpcmethods must return a@wire_typedataclass, not None. Even if your response has no fields, define an empty response type::@wire_type("myapp/AckResult") @dataclass class AckResult: ok: bool = TrueGeneric wrapper types (e.g.,
SignedRequest[T]) are supported. The@wire_typetag is on the outer class; the type parameter is resolved at manifest extraction time.
Declare a field default that is part of the contract.
Every @wire_type dataclass field needs a Python construction default,
but a plain default (name: str = "") does not enter the contract:
the field is published as required. Wrap the default in
contract_default to publish it (required = false plus the
canonical default bytes), exactly like Rust's #[aster(default = …)]::
@wire_type("defaults.v1/Settings")
@dataclass
class Settings:
name: str = "" # required
state: str = contract_default("idle")
retries: pyfory.Int32 = contract_default(-3)
tags: list[str] = contract_default(default_factory=list)
Changing a contract default changes contract_id (it is a breaking
change); Fory payload bytes are unaffected. Supported in v1: str,
bool, pyfory.Int32 (varint32), int (varint64), float
(float64), Optional of those with a non-None value, and empty
list / set / dict. Anything else raises TypeError when the
contract is computed.
Extra keyword arguments go to pyfory.field() when they are pyfory
field options (id, nullable, ...), else to
dataclasses.field().
Require ANY ONE of the listed roles (OR logic).
The caller is admitted if they have at least one of the specified roles. Accepts plain strings or str enum values.
Example::
@rpc(requires=any_of("ops.logs", "ops.admin"))
async def tail_logs(self, req): ...
@rpc(requires=any_of(Role.LOGS, Role.ADMIN))
async def tail_logs(self, req): ...
Require ALL of the listed roles (AND logic).
The caller is admitted only if they have every specified role. Accepts plain strings or str enum values.
Example::
@rpc(requires=all_of("ops.status", "ops.admin"))
async def admin_status(self, req): ...
@rpc(requires=all_of(Role.STATUS, Role.ADMIN))
async def admin_status(self, req): ...
Serialization protocol negotiated between client and server.
Only XLANG interoperates across bindings; NATIVE and ROW are reserved (Aster-SPEC §5.1). The former JSON mode (3) is retired.
Exception raised when an RPC call fails.
Catch this in client code to handle server-side errors::
from aster import RpcError, StatusCode
try:
resp = await svc.my_method(request)
except RpcError as e:
print(f"RPC failed: {e.code.name} -- {e.message}")
if e.details:
print(f"Details: {e.details}")
Attributes:
code: The StatusCode describing the failure category.
message: A human-readable error description.
details: Arbitrary string key/value pairs carrying extra context.
RPC status codes.
Codes 0-16 mirror gRPC's google.rpc.Code semantically. Codes
100+ are Aster-native and have no gRPC equivalent. The 17-99
range is reserved as a buffer in case gRPC ever extends its enum.
A common gripe with gRPC's status codes is that there are too few of them to express the variety of failures real services actually hit -- everything ends up shoehorned into a handful of overloaded categories. The 100+ space gives Aster room to mint more precise codes over time, signalling clearly that they are intentionally separate from the gRPC vocabulary.
Use these to inspect errors returned by the server::
try:
resp = await svc.get_status(req)
except RpcError as e:
if e.code == StatusCode.NOT_FOUND:
print("Service not found")
elif e.code == StatusCode.CONTRACT_VIOLATION:
print("Wire shape doesn't match the contract")
Raised when a consumer is refused by the server's admission check.
The server never reveals why admission failed (no oracle leak), so this exception enumerates the common causes as a hint to the user rather than a precise diagnosis.
Raised when the wire payload doesn't match the published contract.
Carries the offending field names in details under the key
unexpected_fields (comma-separated, sanitized via repr).
Context for a single RPC call, available to interceptors and handlers.
Passed to every interceptor in the chain. Read service and method
to know which RPC is being called. Use metadata to pass headers
between client and server. Check remaining_seconds for deadline
awareness.
Attributes:
service: The service name (e.g., "MissionControl").
method: The method name (e.g., "getStatus").
call_id: Unique ID for this call (auto-generated UUID).
peer: Remote peer identifier (endpoint ID hex).
metadata: Key/value headers sent with the call.
attributes: Enrollment attributes from the consumer's credential.
deadline: Absolute deadline as epoch timestamp, or None.
is_streaming: True for streaming RPC patterns.
pattern: RPC pattern ("unary", "server_stream", etc.).
idempotent: True if the method is safe to retry.
attempt: Current retry attempt number (starts at 1).
tunnel: Server-side handle for minting tunnel tickets bound to
this RPC's connection. None on the client side or when
the dispatch path doesn't surface a connection.
peer_addr: Peer's UDP (host, port) tuple when the selected
QUIC path is direct. None when relayed.
relay_url: Relay server URL when the selected path goes through
a relay. None for direct paths. The peer's own IP is
not visible through a relay path.
rtt_micros: Round-trip-time for the selected path in
microseconds, or None if not yet measured.
Base interceptor interface.
Validates and enforces call deadlines.
Args:
skew_tolerance_ms: Milliseconds of clock-skew tolerance added to the
deadline when checking on receipt. A request whose deadline has
already passed by more than this tolerance is rejected immediately
with DEADLINE_EXCEEDED. Defaults to 5000 ms (5 seconds).
Injects and/or validates auth metadata.
Provides retry policy hints for client calls.
Simple CLOSED → OPEN → HALF_OPEN circuit breaker.
Give back a half-open probe slot taken by before_call for a call
whose outcome says nothing about the peer's health (an error code
the breaker does not count, a cancelled call, or a call refused by
another breaker). Without this the breaker stays half-open with no
free slot and refuses every later call.
Captures structured audit events for requests, responses, and errors.
The ops listener: GET /healthz, /readyz, /metrics (Prometheus text),
served by aster::ops and fed by the built-in instruments. Disabled by
default in AsterServer (health_port = 0); the default bind address is
127.0.0.1.
await HealthServer.start(node, host="127.0.0.1", port=0). Port 0
binds an ephemeral port (see port). Joins, or starts from the
environment, the observability pipeline and gives it the Prometheus
pull reader.