API Reference
Complete constructor properties, method signatures, middleware chains, error tables, and TypeScript definitions for AfterLink.
Server Class Reference
Instantiated via new Server(options) or the wrapper helper createServer(options).
Server Options Parameters
| Option | Type | Default | Description |
|---|---|---|---|
| port | number | 8080 | TCP port configuration range. |
| host | string | '0.0.0.0' | Network interface address mapping. |
| idleTimeout | number | 60000 | Heartbeat delay threshold in milliseconds. |
| maxConnections | number | 10000 | Peak concurrent active sockets allowance limits. |
| tls | object | null | Pass key, cert buffers to activate secure TLS handshakes. |
| metrics | object | null | Enable Prometheus endpoint and set custom port/path options. |
| tracing | TracingManager | null | OpenTelemetry-compliant context propagation instance. |
Registers a callback listener for specific route requests or system handshake events, optionally verifying with Zod validation models.
Signature
server.on(route: string, handler: (socket, payload) => void, schema?: ZodSchema)
Injects global middleware functions into the connection processing stack (e.g. JWT validations or packet logging).
Signature
server.use(middleware: (socket, frame, next) => void)
Pushes pub/sub broadcasts directly onto channel topics. Server manages delivery lists and relays MSG_BROADCAST (0x05) frames automatically.
Signature
server.publish(channel: string, payload: any)
Transmits identical raw payload buffers to all active client sockets regardless of routing channel configurations.
Signature
server.broadcast(type: string, payload: any)
Closes raw TCP bindings gracefully, terminating keepalive heartbeats, and closing active connections correctly.
Signature
server.close(callback?: () => void): Promise<void>
@ajaymyth/cluster Package Reference
Instantiated via new ClusterManager(options) to manage worker process forks, Redis-backed shared pub/sub routing, worker crash detection/restarts, and SIGUSR2 rolling restarts.
ClusterManager Options
| Option | Type | Default | Description |
|---|---|---|---|
| workers | number | 'auto' | 'auto' | Number of worker processes to fork (defaults to CPU core count). |
| redis | string | object | 'redis://127.0.0.1:6379' | Redis connection URL or Redis.Cluster node array for multi-node routing. |
| autoRestart | boolean | true | Automatically fork new worker process on worker crash. |
| rollingRestart | boolean | true | Enable zero-downtime rolling restarts on SIGUSR2 process signals. |
Initializes worker clusters with automatic load distribution across primary TCP sockets and synchronizes pub/sub state across node boundaries via Redis pub/sub.
Usage Signature
import { ClusterManager } from '@ajaymyth/cluster';
const cluster = new ClusterManager({
workers: 'auto',
redis: { nodes: ['10.0.0.1:6379', '10.0.0.2:6379'] }
});
cluster.start(); Metrics & Observability Reference
AfterLink v2 includes built-in Prometheus metric collection and OpenTelemetry tracing propagation via AsyncLocalStorage.
Configuring metrics exposes HTTP endpoints for Prometheus scrapers (e.g. /__metrics) and provides Grafana dashboard templates. The TracingManager propagates trace IDs across binary frame headers using AsyncLocalStorage context.
Configuration Signature
import { Server, TracingManager } from '@ajaymyth/server';
const tracing = new TracingManager({ serviceName: 'order-service' });
const server = new Server({
port: 8080,
metrics: { enabled: true, port: 9090, path: '/metrics' },
tracing
}); Client Class Reference
Instantiated via new Client(options) or the wrapper helper createClient(options).
Client Options Parameters
| Option | Type | Default | Description |
|---|---|---|---|
| host | string | '127.0.0.1' | Host address of target AfterLink server. |
| port | number | 8080 | Destination binding TCP port range. |
| autoReconnect | boolean | true | Triggers socket re-connections upon socket drops. |
| maxRetries | number | 10 | Limits reconnection sequences before throwing errors. |
Triggers asynchronous handshakes to establish active socket bindings, or tears down established socket connections gracefully.
Signature
client.connect(): Promise<void> | client.disconnect(): Promise<void>
Dispatches structured RPC request packets (MSG_REQUEST) and returns matching Promise response elements resolving when server returns matching seq IDs.
Signature
client.request(route: string, body: any, options?: object): Promise<any>
Binds call functions to specific pub/sub streams. Instructs server routing layers by pushing MSG_SUBSCRIBE frames immediately.
Signature
client.subscribe(channel: string, callback: (payload, channel) => void): void
Publishes messages onto specified routing channels. Packages fields and transmits a single MSG_PUBLISH (0x03) packet.
Signature
client.publish(channel: string, payload: any): void
Establishes interactive, multi-frame streaming pipelines. Dispatches structured MSG_STREAM packets sequentially and ends with a MSG_STREAM_END marker.
Signature
client.stream(route: string, body: any): Promise<ReadableStream>
Python & Dart SDK API Reference
AfterLink v2 provides native Python and Dart client & server SDKs matching the 16-byte Protocol v2 header layout.
Provides AsyncServer, AsyncClient, and SyncClient wrapper with full type hints and Pydantic validation support.
from afterlink import AsyncClient
client = AsyncClient(host="127.0.0.1", port=8080)
await client.connect()
# RPC with priority queue & routing key
response = await client.request(
"users.get",
{"id": 42},
priority=7,
routing_key="users"
) Supports native TCP and web WebSocket transports with conditional compilation loaders and standard MessagePack serialization.
import 'package:afterlink/afterlink.dart';
final client = AfterLinkClient(host: '127.0.0.1', port: 8080);
await client.connect();
// Pub/sub with priority level
client.publish(
'chat.global',
{'text': 'Hello Dart!'},
priority: 5,
); Protocol Error Codes
| Error Code | Error Constant | Diagnostic Description & Root Cause |
|---|---|---|
| 100 | ERR_MAGIC_MISMATCH | Invalid magic identifier bytes. Sockets from hostile scans or HTTP requests. |
| 101 | ERR_VERSION_UNSUPPORTED | The client version constant is incompatible with this server. |
| 400 | ERR_BAD_FRAME | Corrupt framing format structure, 16-byte header or length offsets mismatch. |
| 401 | ERR_UNAUTHORIZED | Missing, invalid or expired handshake JWT authentication tokens. |
| 404 | ERR_ROUTE_NOT_FOUND | No matching method path listener exists on this server. |
| 422 | ERR_VALIDATION_FAILED | The frame payload model does not conform to the registered Zod/Pydantic validation schema. |
| 429 | ERR_RATE_LIMITED | Connection request counts exceeded maximum specified configurations. |
| 500 | ERR_INTERNAL_SERVER | Unhandled exception occurred in server-side handler code. |
TypeScript Declarations
Full TypeScript definitions for the core interfaces: