Pular para o conteúdo
Português (BR)

gRPC

Este conteúdo não está disponível em sua língua ainda.

The framework provides two actor classes for gRPC:

ClassRole
GrpcServerActorHosts a gRPC server; exposes service methods.
GrpcClientActorConnects to a remote gRPC service; calls methods.

Both wrap @grpc/grpc-js. Useful when you have Protobuf-typed contracts and want the broker-actor lifecycle (reconnect, buffer, subscriber fan-out) for client-side calls.

Both actors are configured with a fluent options builder — GrpcServerOptions.create()… / GrpcClientOptions.create()… — and spawned like any other actor.

The server is a concrete actor: spawn it directly. It loads the proto, registers the method handlers, and binds in preStart — the spawn call returns before the bind completes, so give it a moment before the first client call.

Each method maps to a handler actor that receives the inbound call as a message. Handlers are keyed by method name in the handlers map; any method absent from the map is reported as UNIMPLEMENTED.

import {
Actor,
} from 'actor-ts';
import {
GrpcServerActor,
GrpcServerOptions,
type GrpcUnaryCall,
type GrpcServerStreamCall,
} from 'actor-ts/io';
// A unary handler: reply once via `respond`.
class GetSensorHandler extends Actor<GrpcUnaryCall> {
override onReceive(call: GrpcUnaryCall): void {
const id = (call.request as { id: string }).id;
call.respond({ id, label: `sensor-${id}` });
}
}
// A server-stream handler: emit chunks via `send`, finish via `complete`.
class WatchSensorHandler extends Actor<GrpcServerStreamCall> {
override onReceive(call: GrpcServerStreamCall): void {
const limit = (call.request as { limit?: number }).limit ?? 5;
for (let i = 0; i < limit; i++) {
call.send({ value: 20 + i, ts: Date.now() });
}
call.complete();
}
}
const getHandler = system.spawn(GetSensorHandler, 'get');
const watchHandler = system.spawn(WatchSensorHandler, 'watch');
const grpcServerOptions = GrpcServerOptions.create()
.withProtoPath(protoPath)
.withPackageName('sensor.v1')
.withServiceName('SensorService')
.withBind('127.0.0.1:50051')
.withHandlers({
GetSensor: { kind: 'unary', target: getHandler },
WatchSensor: { kind: 'serverStream', target: watchHandler },
});
const server = system.spawn(
() => new GrpcServerActor(
grpcServerOptions,
),
'grpc-server',
);

The bind address is a single host:port string via withBind; packageName and serviceName are set separately. Each handler descriptor is { kind, target } where kind is 'unary', 'serverStream', 'clientStream', or 'bidi'.

The framework de-serializes the Protobuf payload and hands the handler a typed call object:

Handler kindCall typeReply API
unaryGrpcUnaryCallrespond(res) / respondError(message, code?)
serverStreamGrpcServerStreamCallsend(chunk) / complete() / fail(message, code?)
clientStreamGrpcClientStreamCallonData(target) / respond(res) / respondError(message, code?)
bidiGrpcBidiCallonData(target) / send(chunk) / complete()

Every call carries method, the deserialized request (except the client-stream and bidi calls, which stream their requests), and a metadata record. respondError / fail take an optional numeric status code that defaults to 13 (INTERNAL).

metadata holds the client’s request headers, so a handler can make a per-call decision — check an authorization header, read a tenant id. Two edges follow from the record holding strings: a header sent more than once collapses to its first value, and binary (-bin) headers are omitted entirely. A header nobody sent reads as undefined, names like constructor included — the record has no prototype, so a lookup never succeeds by accident.

An onData subscriber receives GrpcRequestStreamInbound — either { kind: 'chunk', chunk } or { kind: 'end' }.

import { match, P } from 'ts-pattern';
import {
Actor,
} from 'actor-ts';
import {
GrpcClientActor,
GrpcClientOptions,
type GrpcInbound,
type ReplyMessage,
type RpcErrorMessage,
type StreamDataMessage,
type StreamErrorMessage,
type StreamStartedMessage,
} from 'actor-ts/io';
const grpcClientOptions = GrpcClientOptions.create()
.withProtoPath(protoPath)
.withPackageName('sensor.v1')
.withServiceName('SensorService')
.withEndpoint('127.0.0.1:50051');
const client = system.spawn(
() => new GrpcClientActor(
grpcClientOptions,
),
'sensor-client',
);
// A collector actor receives every reply / stream frame as `GrpcInbound`.
class ReplyCollector extends Actor<GrpcInbound> {
override onReceive(message: GrpcInbound): void {
match(message)
.with({ kind: 'reply' }, (m) => this.onReply(m))
.with({ kind: 'stream-started' }, (m) => this.onStreamStarted(m))
.with({ kind: 'stream-data' }, (m) => this.onStreamData(m))
.with({ kind: 'stream-end' }, () => this.onStreamEnd())
// Unary and streaming failures are reported the same way.
.with(P.union({ kind: 'rpc-error' }, { kind: 'stream-error' }), (m) => this.onError(m))
.exhaustive();
}
private onReply(message: ReplyMessage): void {
console.log('unary reply:', message.response);
}
// A client or bidi stream is open — `message.handle` addresses its writes.
private onStreamStarted(message: StreamStartedMessage): void {
console.log('stream open:', message.handle.streamId);
}
private onStreamData(message: StreamDataMessage): void {
console.log('stream chunk:', message.chunk);
}
private onStreamEnd(): void {
console.log('stream complete');
}
private onError(message: RpcErrorMessage | StreamErrorMessage): void {
console.error('error:', message.error.message);
}
}
const collector = system.spawn(ReplyCollector, 'collector');
// Make a unary call — the reply is delivered to `target`.
client.tell({ kind: 'unary', method: 'GetSensor', request: { id: 'rt-7' }, target: collector });

The endpoint is a single host:port string via withEndpoint. Every call names a target actor; the actor routes the reply and any stream frames there. .withDeadlineMs(30000) (the default) bounds unary calls only. A gRPC deadline covers a whole RPC, and one value cannot both fail a request/response call promptly and let a long-lived stream run, so the three streaming modes are left unbounded.

Replies and stream frames arrive at the target actor as a GrpcInbound discriminated union:

kindFieldsMeaning
replyresponseUnary or client-stream completion.
stream-startedhandleA client or bidi stream is open — see below.
stream-datastreamId, chunkOne stream chunk.
stream-endstreamIdStream closed cleanly.
stream-errorstreamId, errorStream failed.
rpc-errorerrorUnary / call setup failed.

gRPC has four call types, and the framework covers all four:

TypeClient sendsServer returnsClient-side kinds
UnaryOne requestOne responseunary
Server-streamingOne requestStream of responsesserverStream
Client-streamingStream of requestsOne responseclientStreamStart / clientStreamSend / clientStreamClose
Bi-directional streamingStream of requestsStream of responsesbidiStart / bidiSend / bidiClose

Each client-side call is a command you tell the client actor; the kind selects the call type.

// Server-streaming: one request, N chunks routed to `target`.
client.tell({
kind: 'serverStream',
method: 'WatchSensor',
request: { id: 'rt-7', limit: 5 },
target: collector,
});
// Client-streaming: open a stream, then push requests into it.
client.tell({ kind: 'clientStreamStart', method: 'ReportReadings', target: collector });

clientStreamStart returns nothing directly. The actor delivers a stream-started frame to target carrying a GrpcStreamHandle, and that handle is what addresses every subsequent write:

// Inside the collector, on the `stream-started` frame:
const handle = message.handle;
client.tell({ kind: 'clientStreamSend', handle, chunk: { value: 21.5 } });
client.tell({ kind: 'clientStreamClose', handle });

clientStreamClose half-closes the request stream; the server’s single response then arrives as an ordinary reply, and a failure as rpc-error.

The handle has two fields, with two different jobs. streamId is the correlation id — the same number this stream’s frames carry, so one collector can multiplex several concurrent streams. token is the capability: a tell carries no verified sender, so a sequential id would let anything that can reach the client actor write into a stream it never opened. The token is 64 bits of crypto-grade randomness, which makes the lookup itself the ownership check — pass the handle around exactly as carefully as you would a write handle.

On the server, a client-streaming method is registered with kind: 'clientStream' and its handler consumes the request stream via onData, answering once:

class ReportReadingsHandler extends Actor<GrpcClientStreamCall> {
override onReceive(call: GrpcClientStreamCall): void {
let count = 0;
const sink = { tell: (m: GrpcRequestStreamInbound): void => {
match(m)
.with({ kind: 'chunk' }, () => { count++; })
.with({ kind: 'end' }, () => call.respond({ count }))
.exhaustive();
} } as unknown as ActorRef<GrpcRequestStreamInbound>;
call.onData(sink);
}
}

Chunks that arrive before the handler subscribes are held and replayed on the first onData, so nothing is lost in the turn between the call landing in the handler’s mailbox and the handler running.

Bidi opens exactly the way a client stream does, and keeps both directions open:

client.tell({ kind: 'bidiStart', method: 'Chat', target: collector });

The handshake is the same one: a stream-started frame carrying a GrpcStreamHandle, and that handle addresses every send and the close.

// Inside the collector, on the `stream-started` frame:
const handle = message.handle;
client.tell({ kind: 'bidiSend', handle, chunk: { text: 'hello' } });
client.tell({ kind: 'bidiClose', handle });

The server’s responses arrive as ordinary stream-data frames, followed by stream-end when the call completes — a bidi RPC answers with a stream, so there is no single reply. Those frames carry handle.streamId, the correlation id; the token half of the handle never appears on an inbound frame, because it is the capability.

Both properties matter, and they are separate. The handshake is its own frame so that a server message can never be mistaken for it — it used to ride in as a stream-data chunk shaped { __streamId }, and __streamId is a perfectly legal protobuf field name. And the send/close registry is keyed by the token so that a guessed or stolen streamId buys nothing: ids are sequential, and knowing one hands you the next.

Server-stream calls also carry a streamId on their stream-data / stream-end frames, so a single collector can multiplex several concurrent streams. Streams stay open until either side closes them or the actor stops.

A send or close whose handle is well formed but names no live stream is a silent no-op. That is a race you should expect in correct code: the server closed the stream, or the connection dropped, and the notice — stream-end, stream-error or reply — had not reached you when the write went out.

A command carrying no usable handle at all is a different thing, and it is answered differently: it becomes a DeadLetter on the event stream, addressed to the client actor. Nothing the framework mints looks like that, so it means a caller reached the actor with a shape the command type forbids — a plain-JavaScript tell, a deserialised message, or a handle read back out of a field that was cleared. Subscribe to DeadLetter (or run a DeadLetterQueue) if you want those surfaced; the letter carries the offending command. Neither case disturbs the connection, and neither loses the messages queued behind it.

TLS is opt-in via withCredentials. When omitted, both actors default to insecure ({ kind: 'insecure' }). Certificates are supplied as Uint8Array values, not file paths:

import { readFileSync } from 'node:fs';
// Server: supply cert + key. Add `rootCerts` to require client
// certs (mTLS).
const grpcServerOptions = GrpcServerOptions.create()
.withProtoPath(protoPath)
.withPackageName('sensor.v1')
.withServiceName('SensorService')
.withBind('0.0.0.0:50051')
.withHandlers({ /* … */ })
.withCredentials({
kind: 'tls',
cert: readFileSync('./server.crt'),
key: readFileSync('./server.key'),
});
new GrpcServerActor(
grpcServerOptions,
);
// Client: pass `rootCerts` to verify the server; add cert + key for mTLS.
const grpcClientOptions = GrpcClientOptions.create()
.withProtoPath(protoPath)
.withPackageName('sensor.v1')
.withServiceName('SensorService')
.withEndpoint('sensor.svc:50051')
.withCredentials({
kind: 'tls',
rootCerts: readFileSync('./ca.crt'),
});
new GrpcClientActor(
grpcClientOptions,
);

For mutual TLS (mTLS), add the peer’s cert + key to the credentials object.

withChannelOptions passes grpc-js channel arguments through verbatim — to new grpc.Server(...) on the server, and to the service-client constructor on the client. It is the hardening surface for a bind that faces anything less than fully trusted.

Why it needs its own knob: withDeadlineMs bounds an RPC, and a connection outlives every RPC on it. Nothing else this framework exposes reaches the connection, so without these an idle or abusive peer is never reaped.

// Server: reap idle and over-age connections, cap concurrency, and
// keep probing a connection that has gone quiet.
const grpcServerOptions = GrpcServerOptions.create()
.withProtoPath(protoPath)
.withPackageName('sensor.v1')
.withServiceName('SensorService')
.withBind('0.0.0.0:50051')
.withHandlers({ /* … */ })
.withChannelOptions({
'grpc.max_connection_idle_ms': 300_000,
'grpc.max_connection_age_ms': 1_800_000,
'grpc.max_concurrent_streams': 128,
'grpc.keepalive_permit_without_calls': 1,
});
// Client: the same pass-through, on the channel this client opens.
const grpcClientOptions = GrpcClientOptions.create()
.withProtoPath(protoPath)
.withPackageName('sensor.v1')
.withServiceName('SensorService')
.withEndpoint('sensor.svc:50051')
.withChannelOptions({
'grpc.keepalive_time_ms': 20_000,
'grpc.max_receive_message_length': 4 * 1024 * 1024,
});

The four worth reaching for first on a public bind:

OptionWhat it bounds
grpc.max_connection_idle_msHow long a connection nobody is using survives.
grpc.max_connection_age_msHow long any connection survives, so a long-lived one cannot outlive its authorization.
grpc.max_concurrent_streamsCalls one connection may have in flight.
grpc.keepalive_permit_without_callsWhether idle connections are probed, so a silently dead peer is noticed (1 = yes).

Values are string | number, which is the whole gRPC channel-argument domain — a boolean knob is spelled 0 / 1. grpc-js’s own defaults apply to anything you leave out; the framework passes nothing when you never call withChannelOptions, rather than an empty object.

The keys are grpc-js’s, not the framework’s, and that has a cost worth stating: they change with the peer’s releases, nothing in actor-ts validates them, and a typo is silently ignored rather than rejected. Check them against the channel-argument documentation for the grpc-js version you have installed.

There is deliberately no HOCON leaf for any of this — the same call the broker TLS material got. A key nobody validates does not belong in a config file, where a misspelling would be invisible until production.

The server can host the standard grpc.health.v1.Health service next to yours, so grpc_health_probe, the Kubernetes gRPC probe and gRPC load balancers can ask the node whether it is ready.

The status is not a second notion of “healthy”: it comes from the same HealthCheckRegistry that feeds the management server’s /ready endpoint — the one per ActorSystem, reached with healthChecksOf(system), already carrying the framework’s own cluster readiness checks. Passing that registry to withHealth is the opt-in:

import { healthChecksOf } from 'actor-ts/management';
const health = healthChecksOf(system);
health.addReadiness(() => ({ name: 'journal', status: journal.isConnected() }));
const grpcServerOptions = GrpcServerOptions.create()
.withProtoPath(protoPath)
.withPackageName('sensor.v1')
.withServiceName('SensorService')
.withBind('0.0.0.0:50051')
.withHandlers({ /* … */ })
.withHealth(health);

Check answers SERVING only while every readiness check passes, and NOT_SERVING as soon as one fails — literally the same rule /ready applies, the exported isHealthy. It is re-evaluated per call, so nothing is cached. Because both read healthChecksOf(system), the gRPC service and /ready stay in lockstep by construction; a bare new HealthCheckRegistry() here would fork them, and only one of the two would be the answer a load balancer acts on.

That includes going out of service: after cluster.leave() the cluster’s readiness checks stay registered and fail, so Check answers NOT_SERVING for a drained node rather than SERVING on an empty registry.

The HealthCheckRequest.service field selects what is being asked about:

serviceAnswer
'' (empty)The whole server — the usual probe.
sensor.v1.SensorServiceThe served service, fully qualified.
SensorServiceSame, bare name accepted as a convenience.
grpc.health.v1.HealthThe health service itself.
anything elseNOT_FOUND (status code 5).

Only Check is implemented; Watch answers UNIMPLEMENTED, which is the documented signal for a client to fall back to polling Check.

Per-instance builder options take precedence over HOCON, which takes precedence over built-in defaults. The HOCON keys live under actor-ts.io.broker.grpc.server and actor-ts.io.broker.grpc.client:

actor-ts.io.broker.grpc {
server {
proto-path = "./proto/sensor.proto"
package-name = "sensor.v1"
service-name = "SensorService"
bind = "0.0.0.0:50051"
}
client {
proto-path = "./proto/sensor.proto"
package-name = "sensor.v1"
service-name = "SensorService"
endpoint = "sensor.svc:50051"
deadline = 30s
}
}

Handlers, TLS credentials and channel options are supplied through the builder, not HOCON.

Terminal window
npm install @grpc/grpc-js @grpc/proto-loader
# or: bun add @grpc/grpc-js @grpc/proto-loader

Both packages are peer dependencies.

Two primary fits:

  1. Service-to-service inside a cluster where Protobuf-typed contracts matter for evolution.
  2. External clients that already speak gRPC (mobile apps, other-language services).

For internal actor-to-actor communication inside a cluster, the cluster transport is better — typed via TypeScript directly, no Protobuf required. gRPC is for cross-language or external-contract cases.