コンテンツにスキップ
日本語

EventStream

このコンテンツはまだ日本語訳がありません。

Defined in: src/EventStream.ts:113

A simple system-wide pub/sub bus. Subscribers register against a channel; publications are matched against it and tell’d to every actor interested, or handed to every callback interested.

Two kinds of subscriber. An actor, by its ref (subscribe), receives an event through its mailbox. A plain callback (subscribeFunction) is called inside publish, with no actor to spawn, name or stop (#1433). The actor is the default — its mailbox orders, buffers and isolates what it receives — and the callback is for code with nothing to spawn: a counter, a test, a bridge to code outside the actor tree.

Two ways to name a channel. A class, matched with instanceof, so subclass instances reach base-class subscribers — which is what makes an abstract base the most useful channel there is. Or an event’s kind, named by an EventKey or by the bare string, matched on the discriminant: the form the project’s own message convention needs, since a kind-discriminated plain type has no constructor to hand over and until recently could not be subscribed to at all — even though publish has always accepted one.

Predicate-filtered subscriptions (#85). Each subscription may carry an optional predicate that runs against the event before delivery — only events the predicate accepts are tell’d to the subscriber. Useful for high-frequency channels (cluster events, metrics) where the consumer only cares about a slice of the traffic and would otherwise have to filter inside its own onReceive. A predicate that throws is treated as “no match” for that delivery; the subscription stays active.

new EventStream(): EventStream

EventStream

optional log?: EventStreamLogger

Defined in: src/EventStream.ts:167

Optional logger used to surface predicate failures. Assigned by ActorSystem once its main logger has been constructed; tests that instantiate EventStream directly can leave it undefined — the bus stays functional, errors just stay silent.


traceSubscriptions: boolean = false

Defined in: src/EventStream.ts:185

Trace subscribe and unsubscribe at debug — actor-ts.diagnostics.debug.event-stream (#867). Assigned by ActorSystem from the resolved settings; a bus a test builds by hand keeps the shipped answer, which is silence.

A field on the bus rather than a Config read, exactly like log beside it: the stream is constructed before the settings are resolved and has no way to reach them, and the two switches this file needs are worth two assignments rather than a reference back to the system.

Subscription lifecycle only, never publish. That path runs on every actor start, every stop and every dead letter, and a config key that can put a log call there is not a diagnostic — it is an outage switch.

get hasSubscribers(): boolean

Defined in: src/EventStream.ts:507

Whether anything is listening at all — a subscription of either kind, or the observer.

Coarse on purpose — any channel, any subscriber. Callers use it to skip constructing an event, which is only sound when the answer covers every channel; a per-channel query would let a caller skip building an event a different channel’s subscriber was entitled to. The observer is entitled to every event, so it counts for the same reason: left out, an observer on an otherwise quiet system never saw an actor start or stop. So does a callback, for which it would have been the same silence. With DevTools attached the cost comes back, which is the intended trade.

boolean

publish(event): void

Defined in: src/EventStream.ts:560

Publish an event to all matching subscribers: the observer first, then every actor subscriber, then every callback.

The recipient set is fixed when the publish starts. subscriber.tell can run synchronously — a PromiseActorRef, a test probe, an actor on an inline dispatcher — so a handler may subscribe or unsubscribe while the event is still being delivered.

The two operations used to disagree about what that meant, because of how they happened to be written rather than by decision: unsubscribe reassigns subscriptions, so the loop kept walking the array it started with and a removed subscriber still got the event, while subscribe pushes into that same array, so a subscriber added mid-delivery received an event published before it existed (#645).

Iterating a snapshot settles it in the direction that was already true for unsubscribe: everyone subscribed when publish was called receives the event, and nobody else. Delivering to a subscriber that did not exist at publish time is the indefensible half; delivering one last event to a subscriber on its way out is harmless — it lands in dead letters like any other message to a stopped actor.

One bad subscription cannot take the others down (#1010). Everything done on a subscription’s behalf runs under a guard, because all three steps can throw: instanceof on a channel that turned out not to be one, the predicate, and subscriber.tell. Only the predicate used to be guarded, so a single faulty entry raised a TypeError into whoever called publish — and since the throw escaped the loop, every subscription registered after it silently stopped receiving anything, in an order no caller controls. That reached far: publish runs on every actor start, every actor stop and every dead-lettered tell, so it turned ref.tell, an API that does not throw by contract, into one that did. The warning each guard ends in is guarded as well (warnContained): it renders the thrown value, which can throw too.

Callbacks come last (#1433), under a guard of their own — see callCallbacks for their order, their recipient rule and the depth bound a callback that publishes runs into.

object

void


subscribe<TEvent>(subscriber, channel, predicate?): boolean

Defined in: src/EventStream.ts:221

Subscribe an actor ref to a channel. Returns true if a new subscription was added; false if a duplicate was rejected.

Naming the channel. A class, an EventKey, or the bare kind string. The string is the shorthand and it costs the type: TEvent has nothing to be inferred from and falls back to unknown, so a predicate written against it sees unknown unless the caller spells the argument out — subscribe<UserLoggedInEvent>(ref, 'user-logged-in'), which also makes the string itself checkable against the type’s kind.

A key and its string are the same channel: subscribing both ways dedups, and either one unsubscribes the other. A class and a kind are not, even when the class’s instances carry that kind — those are two channels selecting overlapping events, exactly like a base class and its subclass, and an actor holding both subscriptions receives both deliveries.

Dedup rules. Without predicate, only one subscription per (subscriber, channel) is kept — re-calling subscribe is a no-op. With a predicate, every call adds a new subscription: predicates are values without an identity contract, so dedup’ing across them would be unreliable; users wanting “replace this filter” should unsubscribe first.

TEvent

ActorRef

EventChannel<TEvent>

(event) => boolean

boolean

TypeError when subscriber is not an ActorRef, or when channel is neither a usable instanceof right-hand side nor a non-empty kind. Failing on the line that wrote the subscription is the whole point: the alternative is a subscription that poisons an unrelated publish in another actor much later (#1010) — or, for a subscriber, every actor stop after it (see assertSubscriber). It throws rather than returning false, because false already means “duplicate rejected” and conflating the two destroys the signal the return value carries.


subscribeFunction<TEvent>(channel, callback): () => void

Defined in: src/EventStream.ts:433

Subscribe a plain callback to a channel — no actor to spawn, name or stop (#1433). Returns the handle that ends this subscription.

The channel is named exactly as for subscribe — a class, an EventKey or the bare kind string — and a class or a key types the callback’s parameter.

Delivery is synchronous. The callback runs inside publish, on the publisher’s stack, after every actor subscriber has been told, so an event a callback causes still reaches the actors after the event that caused it. That is the price of having no mailbox: a slow callback slows every publish of its channel, which for the framework’s own events means every actor start, stop or dead letter. Work that takes time belongs in an actor.

The handle. Every call is a subscription of its own — no dedup, so the same function subscribed twice is called twice — and its handle ends exactly that one; calling it again does nothing. Once it has returned the callback is not called again, not even with an event already being delivered: a ref’s one late event lands in dead letters, but a callback has no mailbox, and a late call would run code its owner has already torn down. A callback subscribed while an event is being delivered starts with the next one. No actor stop reaches it — the unsubscribe every stop makes concerns refs only — so the handle is how its owner ends it.

The system’s end ends it too. A ref subscription ends with its actor; a callback has none, so it ends with the system: it still sees every event of the shutdown, the stops included, and is not called again from the moment the system reports itself terminated — not by a late publish, not by a dead letter, not during the flush terminate() still waits for before it resolves. Subscribing while the system terminates is allowed and sees the rest of the shutdown. Subscribing after it has terminated is refused, because nothing would be left to end that subscription.

A failing callback stays its own problem. A throw is reported 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, only kept from rejecting unhandled — which Node answers with a process exit — and its rejection is reported the same way.

A callback must not publish on its own channel, directly or through another callback: the nested publish calls it again before its first call has returned, and so on down the stack. Publishing on another channel is fine. Past MAX_EVENT_STREAM_CALLBACK_DEPTH nested levels the bus calls no callback for the nested event, nor for anything else published in the same cascade — everything one call of the outermost publish set off — and warns once for it. The deliveries already under way finish, and the cascades of the outermost event’s other callbacks are their own, so what a loop costs is the bound plus, at each of its levels, one call for every other callback its events reach — not one more path for each of them.

TEvent

EventChannel<TEvent>

(event) => void

() => void

TypeError when channel is unusable, as subscribe does, or when callback is not a function — or is a class, an EventKey or a string, which is what that slot holds when the two arguments were swapped, and which the message answers with the order. Refused on the line that wrote it, rather than stored to fail at every delivery after it.

Error once the system this bus belongs to has terminated.


unsubscribe<TEvent>(subscriber, channel?): boolean

Defined in: src/EventStream.ts:289

Unsubscribe a (subscriber, channel) pair, or every subscription the actor holds when channel is omitted. Removes ALL matching entries — including predicate-bearing ones; finer-grained removal (one specific predicate at a time) isn’t supported because predicates have no stable identity.

The test is !== undefined, not truthiness. Truthiness was correct while a channel could only be a constructor; with kind strings legal, '' is a supplied channel that reads as falsy, and the old shape would have taken the omitted-channel branch and dropped every subscription the actor held.

The channel is resolved exactly as subscribe resolved it, so it is named by identity rather than by object: EventKey.of('x') mints a fresh key on every call and would match nothing under ===. An invalid channel throws here too — quietly removing nothing is how a subscription survives a cleanup that believed it had done its job (#645, #763). So does a subscriber that is not an ActorRef, which on an empty stream used to return false like a cleanup that simply had nothing to remove.

TEvent

ActorRef

EventChannel<TEvent>

boolean