Skip to content

TypeScript server

AsterServer makes decorated TypeScript methods callable by other peers. It owns the node and native dispatcher; your application supplies handlers, generated service metadata, and the process lifetime that keeps them available.

Use one shared service for ordinary commands, streams for incremental messages, and session-scoped services for private state across calls. Configure admission separately from these handler choices.

For a complete standalone producer, use the tested quickstart. It includes explicit development admission and the Node event-loop keepalive workaround. The fragments below describe APIs and assume the application owns its process lifecycle.

The high-level server wrapper that handles service registration, endpoint creation, and health endpoints.

import { AsterServer } from '@aster-rpc/aster';
import { HelloService } from './service.js';
const server = new AsterServer({
services: [new HelloService()],
allowAllConsumers: true, // Development example.
config: {
logFormat: 'json',
},
});
await server.start();
console.log("Producer ready at:", server.address);
try { await server.serve(); }
finally { await server.close(); }

HelloService must have been processed by aster-gen and compiled with the application. The address is a public connection ticket. Awaiting serve() retains this task; the standalone process also needs the quickstart’s owned keepalive timer while native work is pending.

Lifecycle checkpoint What your application does
Before start() Load service definitions and generated metadata; select admission policy
After start() Read the ticket and make the running service available to callers
While serving Retain the server and process lifetime; finish or cancel application work
During close() Release subscriptions and other application resources before process exit
Option Type Default Description
services object[] Required Array of @Service-decorated instances
config Partial<AsterConfig> {} Override config values
identity string undefined Path to a .aster-identity TOML file
peer string undefined Peer name to load from the identity file
allowAllConsumers boolean false Open-gate mode (dev). Set false for trusted mode.
interceptors Interceptor[] [] Server-side interceptors
Method Returns Description
start() Promise<void> Start the server (create node, publish contracts, open admission)
serve() Promise<void> Block until the server is shut down (Ctrl+C in scripts)
close() Promise<void> Graceful shutdown
localTransport() LocalTransport In-process transport for testing
Property Type Description
address string aster1... ticket consumers connect to
running boolean Whether the server is running
registry ServiceRegistry The service registry
config AsterConfig Resolved configuration
import { ServiceRegistry, LocalTransport } from '@aster-rpc/aster';
import { HelloService } from './service.js';
const registry = new ServiceRegistry();
registry.register(new HelloService());
const transport = new LocalTransport(registry);
Method Returns Description
register(instance) ServiceInfo Register a @Service-decorated instance
lookup(name, version?) ServiceInfo | undefined Look up by name and optional version
lookupMethod(service, method) [ServiceInfo, MethodInfo] | undefined Look up a specific method
services() IterableIterator<ServiceInfo> All registered services
size number Number of registered services
@Service({ name: "Echo", version: 1 })
class EchoService { ... }
@Rpc({ timeout: 30, idempotent: true })
async echo(req: EchoRequest): Promise<EchoResponse> { ... }

The aster-gen build step reads request/response types from the AST, so you don’t need to pass them in the decorator. Optional keys: timeout, idempotent, requires, serialization. See TypeScript Build Setup.

@ServerStream()
async *watchItems(req: WatchRequest): AsyncGenerator<ItemUpdate> { ... }
@ClientStream()
async uploadBatch(requests: AsyncIterable<Item>): Promise<BatchResult> { ... }
@BidiStream()
async *chat(requests: AsyncIterable<Message>): AsyncGenerator<Message> { ... }
@WireType("myapp/Invoice")
class Invoice {
amount = 0;
currency = "USD";
constructor(init?: Partial<Invoice>) { if (init) Object.assign(this, init); }
}

The TypeScript binding exports these interceptors:

import {
RetryInterceptor,
RateLimitInterceptor,
AuthInterceptor,
CircuitBreakerInterceptor,
CompressionInterceptor,
AuditLogInterceptor,
CapabilityInterceptor,
} from '@aster-rpc/aster';
const rateLimit = new RateLimitInterceptor({ globalRps: 1000, perServiceRps: 500 });

Configure interceptors using the TypeScript API reference. Client retry policies and server admission have different responsibilities; a retry interceptor does not make a mutation idempotent.

Deadlines are enforced by the shared Rust dispatch path using method and per-call settings. The TypeScript package does not export DeadlineInterceptor in TypeScript.

Built-in RPC metrics are recorded in the shared Rust telemetry pipeline. See observability for configuration.

@Service({ name: "Counter", scoped: "session" }) declares session scope. Rust dispatch keys state by connection and session ID, so multiple sessions can share a peer connection. Do not key session state only by peer identity. Calls can overlap across streams; protect mutable state against asynchronous interleaving. See session-scoped services for factory and lifetime rules.

Protected admission is the default. Use a provisioned identity and peer entry for credential-based deployments; the consumer-admission handshake verifies credentials before protected RPC access. allowAllConsumers: true is the explicit development setting. Method capability requirements still apply and must use verified attributes rather than caller-supplied metadata.

Throw an exported RpcError subtype for an intentional application failure. Unexpected handler errors become internal statuses. For streams, a terminal failure can follow already-delivered payloads; callers must handle both partial data and the final status. Cancellation or deadline expiry does not roll back committed application writes.

Keep server-owned data handles within the server lifetime and close independent subscriptions explicitly. close() joins native server shutdown; finish application-owned work and telemetry flushing before exiting the process. For a standalone Node producer, use the quickstart’s owned timer so pending native work keeps the process alive with the native addon.