Skip to content

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
portnumber8080TCP port configuration range.
hoststring'0.0.0.0'Network interface address mapping.
idleTimeoutnumber60000Heartbeat delay threshold in milliseconds.
maxConnectionsnumber10000Peak concurrent active sockets allowance limits.
tlsobjectnullPass key, cert buffers to activate secure TLS handshakes.
metricsobjectnullEnable Prometheus endpoint and set custom port/path options.
tracingTracingManagernullOpenTelemetry-compliant context propagation instance.
server.on() method
Callback Hooks

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)
server.use() method
Middleware

Injects global middleware functions into the connection processing stack (e.g. JWT validations or packet logging).

Signature

server.use(middleware: (socket, frame, next) => void)
server.publish() method
Pub/Sub

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)
server.broadcast() method
Fan-Out

Transmits identical raw payload buffers to all active client sockets regardless of routing channel configurations.

Signature

server.broadcast(type: string, payload: any)
server.close() method
Shutdown

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
workersnumber | 'auto''auto'Number of worker processes to fork (defaults to CPU core count).
redisstring | object'redis://127.0.0.1:6379'Redis connection URL or Redis.Cluster node array for multi-node routing.
autoRestartbooleantrueAutomatically fork new worker process on worker crash.
rollingRestartbooleantrueEnable zero-downtime rolling restarts on SIGUSR2 process signals.
ClusterManager API class
Node Clustering

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.

Prometheus & OTel Tracing observability
Telemetry

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
hoststring'127.0.0.1'Host address of target AfterLink server.
portnumber8080Destination binding TCP port range.
autoReconnectbooleantrueTriggers socket re-connections upon socket drops.
maxRetriesnumber10Limits reconnection sequences before throwing errors.
client.connect() / disconnect() method
Connection Lifecycle

Triggers asynchronous handshakes to establish active socket bindings, or tears down established socket connections gracefully.

Signature

client.connect(): Promise<void>  |  client.disconnect(): Promise<void>
client.request() method
RPC Loop

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>
client.subscribe() method
Pub/Sub

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
client.publish() method
Pub/Sub

Publishes messages onto specified routing channels. Packages fields and transmits a single MSG_PUBLISH (0x03) packet.

Signature

client.publish(channel: string, payload: any): void
client.stream() method
Streaming

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.

Python SDK (PyPI: afterlink) Python 3.8+

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"
)
Dart SDK (pub.dev: afterlink) Dart 3.0+

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: