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

Event stream

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

The event stream is one ActorSystem’s bus for one-to-many messaging that doesn’t fit the parent-child or sender-receiver shape. Any actor can subscribe to a class of event, or to a kind-discriminated type — and so can a plain callback; any code can publish; the bus matches and tells the event to every subscribed actor, and calls every subscribed callback.

It is node-local, and that is by design: an ActorSystem is one node, so a publish here reaches that node’s subscribers and nobody else’s. The counterpart that crosses nodes is cluster.eventStream — the same channel forms, cluster-wide. Everything below is about the local bus.

import { Actor, ActorSystem } from 'actor-ts';
class UserLoggedIn {
constructor(public readonly userId: string) {}
}
class AuditLogger extends Actor<UserLoggedIn> {
override preStart(): void {
this.context.system.eventStream.subscribe(this.context.self, UserLoggedIn);
}
override onReceive(event: UserLoggedIn): void {
this.log.info(`user ${event.userId} logged in`);
}
}
class MetricsCollector extends Actor<UserLoggedIn> {
override preStart(): void {
this.context.system.eventStream.subscribe(this.context.self, UserLoggedIn);
}
override onReceive(event: UserLoggedIn): void {
this.incrementCounter('logins');
}
}
const system = ActorSystem.create('demo');
system.spawnAnonymous(AuditLogger);
system.spawnAnonymous(MetricsCollector);
// Anywhere — including outside an actor:
system.eventStream.publish(new UserLoggedIn('user-42'));
// → both subscribers receive the event

The publisher doesn’t know how many subscribers exist, and the subscribers don’t know who’s publishing. That’s the whole point — loose coupling for cross-cutting concerns (logging, metrics, audit, fan-out alerts).

// A channel is named by a class, by an EventKey, or by the bare kind string.
type EventChannel<TEvent> =
| (abstract new (...args: any[]) => TEvent)
| EventKey<TEvent>
| KindOf<TEvent>;
class EventStream {
subscribe<TEvent>(
subscriber: ActorRef,
channel: EventChannel<TEvent>,
predicate?: (event: TEvent) => boolean,
): boolean;
unsubscribe<TEvent>(subscriber: ActorRef, channel?: EventChannel<TEvent>): boolean;
subscribeFunction<TEvent>(
channel: EventChannel<TEvent>,
callback: (event: TEvent) => void,
): () => void;
publish(event: object): void;
}

Four operations:

  • subscribe(ref, channel) — register an actor’s interest. The channel is a class, an EventKey, or a kind string. Returns true if a new subscription was added, false if a duplicate was ignored, and throws a TypeError if the channel is unusable (see the caution below) or if ref is not an ActorRef — anything without a callable tell and equals and a path. A function passed as ref is refused the same way: subscribeFunction is the form that takes one.
  • unsubscribe(ref, channel?) — remove an actor’s subscriptions. With a channel, just that one; without, every subscription for that ref. It throws on the same two mistakes, even when nothing is subscribed: a cleanup with a typo in it fails rather than reporting that it had nothing to remove.
  • subscribeFunction(channel, callback) — subscribe a plain callback, with no actor to spawn, name or stop. Returns the () => void handle that ends the subscription; the rules are under Callback subscriptions. The channel comes first here, where subscribe puts the ref first, so it throws a TypeError naming that order when the callback slot holds a class, an EventKey or a string — the call written the other way round — as it does for an unusable channel or any other callback that is not a function.
  • publish(event) — fire-and-forget. The bus walks its subscription list, matches each subscription’s channel, and tells every matching actor; then it calls every matching callback.

Class channels match with instanceof, so subclass instances reach base-class subscribers:

class SystemEvent {}
class UserLoggedIn extends SystemEvent {}
class UserLoggedOut extends SystemEvent {}
eventStream.subscribe(auditor, SystemEvent); // catches both
eventStream.subscribe(loginCounter, UserLoggedIn); // catches only the in-events

This makes hierarchical event taxonomies easy: subscribers pick their level.

Messages tells you to prefer plain objects ({ kind: 'x', n: 1 }) over classes — and a plain type has no constructor to hand subscribe. Name it by its kind instead. A type and a const of the same name give it the call shape a class gets for free:

import { EventKey } from 'actor-ts';
export type UserLoggedInEvent = {
readonly kind: 'user-logged-in';
readonly userId: string;
};
export const UserLoggedInEvent = EventKey.of<UserLoggedInEvent>('user-logged-in');
class AuditLogger extends Actor<UserLoggedInEvent> {
override preStart(): void {
this.context.system.eventStream.subscribe(this.context.self, UserLoggedInEvent);
}
override onReceive(event: UserLoggedInEvent): void {
this.log.info(`user ${event.userId} logged in`);
}
}
system.eventStream.publish({ kind: 'user-logged-in', userId: 'user-42' });

The key carries the event type, so a predicate written against it sees the real shape without you annotating the parameter:

eventStream.subscribe(auditor, UserLoggedInEvent, (event) => event.userId !== 'system');

The bare kind string is the shorthand, and it costs the type — there is nothing for TEvent to be inferred from, so the predicate sees unknown. Supplying the argument brings the typing back and makes the string itself checkable against the type’s kind:

eventStream.subscribe(auditor, 'user-logged-in'); // predicate sees unknown
eventStream.subscribe<UserLoggedInEvent>(auditor, 'user-logged-in'); // typed, and the string is checked

Two identity rules follow from this:

  • A key and its string are the same channel. Subscribing both ways dedups, and either form unsubscribes the other — including a freshly built EventKey.of('user-logged-in').
  • A class and a kind are two channels, even when the class’s instances carry that kind. They select overlapping events, just like a base class and its subclass, so an actor holding both subscriptions receives two deliveries per publish.
eventStream.subscribe(
metricsActor,
HttpResponse,
(event) => event.status >= 500, // only deliver 5xx responses
);

For high-frequency channels (cluster events, every HTTP response, every metric tick), filtering on the bus side is cheaper than filtering inside each subscriber’s onReceive.

Three details:

  • No dedup for predicate-bearing subscriptions. Without a predicate, the bus dedups per (subscriber, channel) pair — re-calling subscribe is a no-op. With a predicate, every call adds a new subscription, because predicate functions have no identity contract. “Replace this filter” means unsubscribe then subscribe again.
  • A throwing predicate is treated as “no match” for that delivery. Other subscribers are unaffected; the subscription stays active. A warning is logged via the system logger.
  • Predicates run at publish time, on the publisher’s stack. Keep them fast and pure — a heavy predicate slows every publish.

An actor is the default subscriber: its mailbox orders, buffers and isolates what it receives. When there is nothing to spawn — a counter, a test, a bridge to code outside the actor tree — subscribe a plain function instead:

import { ActorStopped, ActorSystem } from 'actor-ts';
const system = ActorSystem.create('demo');
const stopped = new Set<string>();
const unsubscribe = system.eventStream.subscribeFunction(ActorStopped, (event) => {
stopped.add(event.actor.path.toString());
});
// When the code that subscribed is torn down:
unsubscribe();

The channel is named exactly as for subscribe — a class, an EventKey or a kind string — and a class or a key types the callback’s parameter. The rest follows from having no mailbox:

  • Delivery is synchronous. The callback runs inside publish, on the publisher’s stack, after every actor subscriber has been told. A slow callback slows every publish of its channel, and for the framework’s own events that means every actor start, stop or dead letter. Work that takes time belongs in an actor.
  • The handle ends exactly one subscription. Every call subscribes anew, even with the same function, and calling a handle twice does nothing. Once the handle has returned, the callback is not called again — not even with an event that was already being delivered. A callback subscribed during a delivery starts with the next event.
  • A failing callback stays its own problem. A throw is logged at warn and skips that callback for that event; it stays subscribed, and everyone else still receives the event. A returned promise is not awaited, and its rejection is logged the same way instead of surfacing as an unhandled rejection. That holds whatever was thrown, as it does for every failure the bus contains: a value the logger cannot render — an error whose message getter throws, say — is left out of the warning, which is written without it.
  • No actor stop ends a callback subscription; the system’s end does. The callback sees the whole shutdown, every ActorStopped included, and is not called again once the system has terminated. Subscribing after that throws, since nothing would be left to end the subscription. While the system is still terminating, subscribing works — there is no actor to spawn.

DevTools has an event-stream panel that tails the bus in a browser — useful when the question is whether anything is being published at all.

Three good fits:

  1. Cross-cutting observation — logging, metrics, audit. Many subscribers, none of which the publisher should know about.
  2. Node-wide notifications — “the cluster gained a member,” “the cache flushed.” The cluster extension publishes its own events here; you can subscribe and react. Membership events are worth reading carefully, because they look like an exception and are not: you see other nodes’ membership changes because every node publishes its own copy, derived from the gossip it merged — not because the event crossed the wire.
  3. De-coupling actor wiring in tests — instead of plumbing a spy ref through five layers, publish on the stream and let the spy subscribe directly.

The framework publishes several event types you can subscribe to:

EventWhere it comes from
DeadLetterEvery message routed to /deadLetters is published here and logged — one throttled info line naming the recipient, the sender and the message’s class, never the payload. Nothing keeps it, so with no subscriber and no queue the message itself is gone. Each carries the recipient it failed to reach. For a bounded, optionally durable record with replay, see Dead letters.
DispatcherErrorA unit of work scheduled on a dispatcher threw where no supervisor could see it. Carries the dispatcher id, the cause, and the ActorRef whose turn it was (null for work belonging to no actor). Quiet by design — see Dispatchers.
SchedulerErrorA task handed to scheduler.scheduleOnceFunction / scheduleAtFixedRateFunction threw inside a raw timer callback, where no supervisor could see it. Carries the cause — and nothing else, because a scheduled task is an anonymous closure and a system has exactly one scheduler. The message-delivery forms do not publish here. See Timers and scheduling.
MemberUp, MemberRemoved, MemberUnreachable, …Concrete cluster membership events published by the cluster extension. Subscribe to each class directly — ClusterEvent is a union type, not a subscribable base class. See Cluster.
ReachabilityChangedThe publishing node’s own failure detector gained or lost sight of a peer — a local observation, unlike MemberUnreachable, which may have arrived in gossip. See Failure detector.
Broker eventsBrokerActor subclasses publish connect/disconnect/lag events.

Everything the framework itself publishes is a class, so class channels remain the way to reach all of the above. Kind channels are for your own application events.

One cluster event is deliberately not here: CurrentClusterState is delivered only to the listener that asked for it, by cluster.subscribe(listener, { replayMode: 'snapshot' }). It states where that subscriber is starting from, which is not news to anybody else, so it never reaches this bus.

See each extension’s docs for the full event vocabulary it publishes.

  • Cluster event stream — this bus, but cluster-wide: the same class and kind channels reaching every node. Also how to bridge a channel of this bus onto that one.
  • DistributedPubSub — cluster-wide publish/subscribe with topic routing; string topics chosen at runtime, and anycast.
  • Actor system — system.eventStream is where you reach the bus.
  • Messages — the shape rules (immutable, no method refs) apply equally to events, and the kind convention documented there is directly subscribable.

The EventStream API reference covers the full surface.