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.

class AsterServer:

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.

AsterServer( services: list, *, config: aster.config.AsterConfig | None = None, peer: str | None = None, identity: str | None = None, root_pubkey: bytes | None = None, allow_all_consumers: bool | None = None, allow_all_producers: bool | None = None, channel_name: str = 'rpc', codec: typing.Any | None = None, interceptors: list[typing.Any] | None = None, gate: aster._aster.GatePolicy | None = None, nonce_store: typing.Any | None = None, registry_namespace: str = '', max_sessions_per_connection: int | None = None, handler_timeout: float | None = None)

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()
async def start(self) -> None:

Create the unified node and compute ServiceSummary list. Idempotent.

def serve(self) -> _asyncio.Task:

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

async def drain(self, grace_period: float = 10.0) -> None:

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.

async def close(self) -> None:

Cancel serve loops and close the node. Safe to call multiple times.

health: typing.Any | None

The aster.HealthServer started from [health] config, or None.

address: str

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.

endpoint_id: str

Hex endpoint ID of this server's node.

def debug_connection_snapshot(self) -> dict[int, dict[str, int]]:

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.

services: list[aster.registry.models.ServiceSummary]

List of services hosted by this server.

root_pubkey: bytes | None

The 32-byte ed25519 trust anchor public key, or None.

gate: aster._aster.GatePolicy

This server's Gate 0 policy (aster.GatePolicy).

gate.admit(peer) / gate.revoke(peer) change who may connect; changes apply to new connections.

node: aster._aster.Node

The underlying aster.Node (escape hatch for direct access).

blobs: Any

Blobs client backed by this node.

docs: Any

Docs client backed by this node.

gossip: Any

Gossip client backed by this node.

endpoint: Any

Escape hatch: the NetClient view of this node's endpoint.

class AsterClient:

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.

AsterClient( *, config: aster.config.AsterConfig | None = None, peer: str | None = None, identity: str | None = None, address: str | None = None, endpoint_addr: NodeAddr | str | bytes | None = None, root_pubkey: bytes | None = None, enrollment_credential_file: str | None = None, channel_name: str = 'rpc')

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()
async def connect(self) -> None:

Create endpoint, run admission if credential present, store services.

Idempotent -- second call is a no-op.

async def reconnect(self) -> None:

Reconnect after a connection drop.

Closes stale connections, re-runs admission, and rebuilds the services list. Uses exponential backoff on repeated failures.

async def open_session( self, *, service_cls: type | None = None, channel: str | None = None) -> aster.runtime.ClientSession:

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.

async def client( self, service_cls: type, *, channel: str | None = None, codec: typing.Any | None = None, interceptors: list[typing.Any] | None = None) -> aster.client.ServiceClient:

Return an RPC client for service_cls.

registry_namespace: str

64-char hex namespace_id for the registry doc.

Empty string if no registry doc was provided by the producer.

open_gate: bool

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.

async def proxy(self, service_name: str) -> aster.runtime.ProxyClient:

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

async def session(self, service_name: str) -> aster.runtime.SessionProxyClient:

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.

@dataclass(frozen=True)
class AsterConfig:

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

root_pubkey: bytes | None = None

32-byte Ed25519 root public key (accepts PublicKey / hex too).

root_pubkey_file: str | None = None

File holding the root public key (hex, or JSON {"public_key": ...}).

enrollment_credential_file: str | None = None

Enrollment credential presented during admission.

enrollment_credential_iid: str | None = None

Cloud instance identity document token (ASTER_ENROLLMENT_CREDENTIAL_IID).

allow_all_consumers: bool = False

Skip the consumer admission gate.

allow_all_producers: bool = True

Schema parity with Rust; the Python binding only supports True.

endpoint_addr: str | None = None

Producer address a consumer dials (aster1... ticket / NodeAddr / id).

storage_path: str | None = None

Persistent node directory; None = in-memory.

gc_interval_ms: int | None = None

Blob GC interval in ms; None / 0 = no GC.

secret_key: bytes | None = None

32-byte node key (accepts SecretKey / 64-hex too). Fixes the node id.

secret_key_file: str | None = None

64-hex secret key file, loaded or created at start.

local_discovery: bool = False

mDNS local discovery (ASTER_LOCAL_DISCOVERY).

health_port: int = 0

TCP port of the ops listener. 0 means disabled unless health_enabled.

health_host: str = '127.0.0.1'

Bind host (localhost only by default; pod probes need 0.0.0.0).

health_enabled: bool | None = None

Force the listener on or off; None enables it when health_port != 0.

identity_file: str | None = None

.aster-identity credential file (default: ./.aster-identity).

@classmethod
def from_env(cls) -> aster.config.AsterConfig:

Defaults overlaid with ASTER_* environment variables.

@classmethod
def from_file(cls, path: str | os.PathLike) -> aster.config.AsterConfig:

aster.toml overlaid with ASTER_* environment variables.

Raises FileNotFoundError for a missing file and ValueError for malformed TOML or invalid values.

def replace(self, **changes: Any) -> aster.config.AsterConfig:

A copy with changes applied (validated); provenance is kept.

def to_dict(self) -> dict[str, typing.Any]:

All fields as plain values.

is_persistent: bool

Whether storage_path selects a persistent node.

def resolve_root_pubkey(self) -> bytes | None:

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.

def resolve_secret_key(self) -> Optional[aster._aster.SecretKey]:

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.

def resolve_identity_path(self) -> str | None:

identity_file if it exists, else ./.aster-identity if it exists, else None.

def load_identity( self, peer_name: str | None = None, role: str | None = None) -> tuple[bytes | None, dict | 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.

def load_identity_from_path( self, path: str | os.PathLike, peer_name: str | None = None, role: str | None = None) -> tuple[bytes | None, dict | None]:

Like load_identity(), from an explicit path.

def print_config(self, *, json: bool = False) -> str:

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

class Node:

A running Aster node (blobs + docs + gossip, plus any extra ALPNs).

def start(config=None, *, alpns=None, gate=None):

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.

def node_id(self, /):

This node's id as a hex string (same value as str(node.id)).

def node_addr(self, /):

Return the node's address info (debug format).

def node_addr_info(self, /):

Return the node's structured address info.

def secret_key(self, /):

The node's secret key (restore the identity via AsterConfig(secret_key=...) or persist it with write_file).

def export_secret_key(self, /):

The node's secret key as 32 raw bytes.

def accept_aster(self, /):

Await the next incoming connection on a custom ALPN. Returns (alpn: bytes, IrohConnection). Raises when the node closes.

def admission(self, /, *, outbound=False):

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.

def serve_admission(self, /, handler):

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

def expose(self, /):

This node's expose registry (aster.Expose): expose local sockets to peers, with an optional Python authorize hook.

def has_hooks(self, /):

Whether this node was started with enable_hooks=True.

def add_node_addr(self, /, other):

Teach this node how to reach other directly (tests / local setups).

def topology(self, /):

This node's topology view (v1 per-peer proximity; v2 shared swarm). Populates only when the node runs with enable_monitoring=True.

def lease_grantor(self, /, grantor_id):

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.

def serve_lease_grantor(self, /, serializer, *, open_revoke=False):

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.

def shutdown(self, /):

Gracefully shut down the node (flushes persistent state first).

def close(self, /):

Alias for shutdown().

id

This node's id.

gate

The attached GatePolicy, if any.

class SecretKey:

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.

def generate():

Generate a fresh random key from the OS CSPRNG.

def from_bytes(data):

Construct from the raw 32 bytes.

def from_hex(s):

Parse 64 hex characters.

def read_file(path):

Read a secret key file. Raises ValueError if it is missing or malformed.

def read_file_if_exists(path):

Like read_file, but None when the file does not exist.

def load_or_generate(path):

Load the key file at path, or generate a key and write it there.

def write_file(self, /, path):

Write this key as a secret key file (mode 0600, parents created). Raises ValueError if the file already exists.

def to_bytes(self, /):

The raw 32 bytes.

def to_hex(self, /):

The 64-char lowercase hex form (the key file's content).

def public_key(self, /):

The matching public key.

def node_id(self, /):

The node id a node started with this key has.

class PublicKey:

A 32-byte Ed25519 public key (an identity / trust anchor).

def from_bytes(data):

The type of the None singleton.

def from_hex(s):

The type of the None singleton.

def to_bytes(self, /):

The type of the None singleton.

def to_hex(self, /):

The type of the None singleton.

def node_id(self, /):

The node id for this key (same 32 bytes, typed as a NodeId).

class NodeId:

A node / endpoint id (the node's Ed25519 public key, 64 hex chars). Equal to (and hashes like) its hex string.

def from_hex(hex):

The type of the None singleton.

def from_bytes(data):

The type of the None singleton.

def to_hex(self, /):

The type of the None singleton.

def to_bytes(self, /):

The type of the None singleton.

def public_key(self, /):

The public key this id is.

def service( name_or_cls=None, *, name: str | None = None, version: int = 1, serialization: list[aster.rpc_types.SerializationMode] | aster.rpc_types.SerializationMode | None = None, scoped: str = 'shared', interceptors: list[type] | None = None, max_concurrent_streams: int | None = None, requires: aster.contract.identity.CapabilityRequirement | None = None, public: bool = False, metadata: Any = None) -> Union[Callable[[type], type], type]:

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

def server_stream( method_or_timeout: Union[Callable[~P, AsyncIterator[Any]], float, NoneType] = None, name: str | None = None, timeout: float | None = None, serialization: aster.rpc_types.SerializationMode | None = None, requires: aster.contract.identity.CapabilityRequirement | None = None, metadata: Any = None) -> Callable[~P, AsyncIterator[Any]]:

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)
def client_stream( method_or_timeout: Union[Callable[~P, Any], float, NoneType] = None, name: str | None = None, idempotent: bool = False, serialization: aster.rpc_types.SerializationMode | None = None, requires: aster.contract.identity.CapabilityRequirement | None = None, metadata: Any = None) -> Union[Callable[~P, Any], Callable]:

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)
def bidi_stream( method_or_timeout: Union[Callable[~P, AsyncIterator[Any]], float, NoneType] = None, name: str | None = None, timeout: float | None = None, serialization: aster.rpc_types.SerializationMode | None = None, requires: aster.contract.identity.CapabilityRequirement | None = None, metadata: Any = None) -> Callable[~P, AsyncIterator[Any]]:

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}")
def wire_type(tag: str, *, metadata: dict | None = None):

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

  • Use Optional[T] for nullable fields.

  • Integer widths: a plain int is a zig-zag varint64 (Rust i64). Use pyfory.Int32 for varint32 (Rust i32), pyfory.FixedInt32 for a fixed 4-byte int32, pyfory.Int8 / pyfory.Int16 / pyfory.Float32 etc. for the other widths.

  • Every field must have a default value. Fory XLANG needs defaults for construction. Use "" for strings, 0 for ints, False for bools, and field(default_factory=list) for collections. Such defaults are not part of the contract (the field is published as required); use contract_default() to publish one.

  • @rpc methods must return a @wire_type dataclass, not None. Even if your response has no fields, define an empty response type::

    @wire_type("myapp/AckResult")
    @dataclass
    class AckResult:
        ok: bool = True
    
  • Generic wrapper types (e.g., SignedRequest[T]) are supported. The @wire_type tag is on the outer class; the type parameter is resolved at manifest extraction time.

def contract_default( default: Any = <dataclasses._MISSING_TYPE object>, *, default_factory: Any = <dataclasses._MISSING_TYPE object>, **field_kwargs: Any) -> Any:

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

def any_of(*roles: str) -> aster.contract.identity.CapabilityRequirement:

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): ...
def all_of(*roles: str) -> aster.contract.identity.CapabilityRequirement:

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): ...
class SerializationMode(enum.IntEnum):

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.

class RpcError(builtins.Exception):

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.

@classmethod
def from_status( cls, code: aster.status.StatusCode, message: str = '', details: dict[str, str] | None = None) -> aster.status.RpcError:

Create the most specific RpcError subclass for a status code.

class StatusCode(enum.IntEnum):

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")
class AdmissionDeniedError(builtins.PermissionError):

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.

def format_hint(self) -> str:

Return a multi-line actionable hint suitable for CLI output.

class ContractViolationError(aster.public.RpcError):

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

@dataclass
class CallContext:

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.

@classmethod
def current(cls) -> aster.interceptors.base.CallContext | None:

Return the CallContext for the RPC currently being dispatched.

Returns None when called outside an RPC handler invocation.

class Interceptor(abc.ABC):

Base interceptor interface.

class DeadlineInterceptor(aster.public.Interceptor):

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

def timeout_seconds(self, ctx: aster.interceptors.base.CallContext) -> float | None:

Return remaining seconds until deadline, or None if no deadline set.

class AuthInterceptor(aster.public.Interceptor):

Injects and/or validates auth metadata.

class RetryInterceptor(aster.public.Interceptor):

Provides retry policy hints for client calls.

class CircuitBreakerInterceptor(aster.public.Interceptor):

Simple CLOSED → OPEN → HALF_OPEN circuit breaker.

def release_probe(self) -> None:

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.

class AuditLogInterceptor(aster.public.Interceptor):

Captures structured audit events for requests, responses, and errors.

class HealthServer:

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.

def start(node, host=Ellipsis, port=0):

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.

def set_ready(self, /, ready):

The type of the None singleton.

def set_healthy(self, /, healthy):

The type of the None singleton.

def is_ready(self, /):

The type of the None singleton.

def is_healthy(self, /):

The type of the None singleton.

def set_services(self, /, services):

The number of registered services /readyz reports.

def set_registry(self, /, published):

Whether the registry / contracts are published (/readyz).

def check(self, /, name):

A named readiness check; /readyz is ready only while all are true.

def remove_check(self, /, name):

The type of the None singleton.

def stop(self, /):

Stop listening and release the owned observability reference. Concurrent calls join shutdown before returning; cached state/address remain usable.

addr

The bound host:port.