Skip to content

feat(plugin-broker): distribute gateway events across processes over Redis Streams - #140

Merged
RedStar071 merged 1 commit into
137-plugin-cache-codecfrom
136-plugin-broker
Sep 27, 2026
Merged

RedStar071 merged 1 commit into
137-plugin-cache-codecfrom
136-plugin-broker

Conversation

@RedStar071

Copy link
Copy Markdown
Member

🔗 Linked issue

resolves #136

Note

Stacked on #139 (137-plugin-cache-codec), so @wolfstar/plugin-broker can depend on the real CacheCodec/jsonCodec exported by @wolfstar/plugin-cache instead of a local duplicate. Base branch should move to main once #139 merges.

🧭 Context

@wolfstar/plugin-gateway runs the gateway in-process and @wolfstar/plugin-sharder spreads shards across processes, but nothing distributes events across processes: one gateway process feeding N worker processes, where the worker count scales independently and a worker can restart/crash/deploy without dropping the gateway connection. WolfStar's own MessageBroker (Redis Streams, no consumer group) let every worker receive every message with no load sharing, lost messages published while a worker was down, and its ack() was a no-op against a non-existent pending-entries list. This PR is the MVP core-mechanics slice of the RFC in #136: producer, consumer-group consumer, and the BrokerListener piece — XAUTOCLAIM reclaim of dead consumers, maxDeliveries/dead-letter, forwardGatewayDispatches, and signal-driven shutdown are left to follow-up issues.

📚 Description

  • createBroker({ redis, stream, maxLength?, codec? }) → publish(event, payload), doing XADD <stream> [MAXLEN ~ <maxLength>] * event <event> payload <base64>.
  • BrokerConsumer (configured through the new ClientOptions.broker, installed by @wolfstar/plugin-broker/register): start() runs XGROUP CREATE ... MKSTREAM (idempotent, ignoring BUSYGROUP), then reads this consumer's own pending entries first (XREADGROUP ... STREAMS <stream> 0, redelivering anything left by a crash under the same consumer name) before new ones (... STREAMS <stream> >, BLOCKing). Implements the framework's Listener.Emitter contract itself, so BrokerListener pieces bind to it the same way EventGatewayListener pieces bind to a GatewayClient — a dedicated internal dispatch collects every listener's promise for one entry, awaits them, and only then XACKs; a throwing listener leaves the entry pending.
  • BrokerListener<Event> + RegisterAsBrokerListener(event, options), mirroring EventGatewayListener/RegisterAsGatewayListener exactly, typed through an augmentable BrokerEvents map.
  • The ./register plugin hook splits construction (preGenericsInitialization, synchronous, only builds the inert BrokerConsumer) from starting it (postListen, async, fires once client.listen() has loaded every piece and started serving) — see the design-decision note below.
  • BrokerRedisClientLike mirrors plugin-cache's RedisClientLike convention: only the exact ioredis overloads used (xadd, xgroup CREATE, xreadgroup with/without BLOCK, xack), verified against real Redis/Cluster types by a tests/types/ioredis.ts consumption test (wired into the root typecheck script the same way plugin-cache's and plugin-gateway's already are).
  • Package scaffolded like plugin-logger (exports map, tsdown, peer on @wolfstar/http-framework); regular workspace dependency on @wolfstar/plugin-cache for CacheCodec/jsonCodec.

Design decision: ClientOptions.broker + postListen, not a manual createBrokerConsumer().start()

An automated review on the issue argued against wiring the consumer through ClientOptions at all, citing that the framework's Plugin hooks all run synchronously during the base Client constructor. I checked the framework's compiled source (node_modules/@wolfstar/http-framework/dist/esm/index.js): preGenericsInitialization/preInitialization/postInitialization do run in the constructor, but preLoad and postListen run inside client.load() and client.listen() respectively — after every piece (including BrokerListeners) is loaded and, for postListen, once the server is already listening. That's exactly the async-setup use case those two hooks exist for, and it's the same point GatewayClient.start() calls connect() at. This PR only does synchronous construction in preGenericsInitialization (mirroring plugin-logger's new Logger()) and defers the actual Redis connection / XGROUP CREATE / read loop to postListen, which keeps the RFC's new Client({ broker: {...} }) ergonomics without the timing problem the review was (correctly, in general, just not here) concerned about.

I also considered building the ack-gating on the framework's AsyncEventEmitter (which Client itself extends) as the same review suggested, since it already tracks in-flight listener promises via waitForAllListenersToComplete(). I checked its implementation too: a listener's rejection is captured and re-emitted as an async "error" event on the next tick, which throws if nothing listens for "error" — a real footgun for a class that doesn't otherwise need that machinery. BrokerConsumer implements the minimal Listener.Emitter contract directly instead (six methods), with dispatch state scoped to the one entry being processed.

Key changes

Before After
No way to distribute gateway events across worker processes @wolfstar/plugin-broker: producer + consumer-group consumer + BrokerListener piece
WolfStar's in-house MessageBroker: no consumer group, no real ack, unbounded stream growth Real consumer groups, ack-after-listeners-resolve with pending-on-throw, MAXLEN ~ trimming

Type of Change

  • New feature (non-breaking change which adds functionality)
  • Bug fix (non-breaking change which fixes an issue)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation change
  • Workflow / CI change

Pre-flight Checklist

  • I have read the Contributing Guidelines (if applicable)
  • My code follows the code style of this project
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have updated the documentation accordingly
  • I added a changeset with pnpm changeset (or pnpm changeset add --empty if no release is needed). See .changeset/README.md.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Reviewed the full diff of @wolfstar/plugin-broker, a new package distributing gateway events across processes over Redis Streams (MVP slice of RFC #136).

  • createBroker/Broker (src/lib/broker.ts): publishes to a Redis stream via XADD [MAXLEN ~] * event <event> payload <base64>.
  • BrokerConsumer (src/BrokerConsumer.ts): a consumer-group reader that implements the framework's Listener.Emitter contract itself, draining a restarted consumer's own pending entries before new ones, and only XACKing once every dispatched listener's promise resolves.
  • BrokerListener/RegisterAsBrokerListener (src/BrokerListener.ts, src/util/decorators.ts): mirror plugin-gateway's EventGatewayListener/RegisterAsGatewayListener shape, typed through an augmentable BrokerEvents map.
  • ./register plugin hook (src/register.ts): splits synchronous construction (preGenericsInitialization) from the async Redis connection/read loop (postListen), gated on ClientOptions.broker.
  • BrokerRedisClientLike (src/lib/redis.ts): a narrow ioredis-overload-matching interface, verified against real Redis/Cluster types via a tests/types/ioredis.ts consumption test wired into the root typecheck script.
  • Package scaffolding (exports map, sideEffects, tsdown.config.ts, root README/labeler/labels/knip.json entries) follows the plugin-logger template.

Two claims in the PR body were independently verified rather than taken on trust, since both are load-bearing for correctness:

  • The #drain("0") own-pending-entries loop relies on XREADGROUP ... STREAMS s 0 returning nil (not an empty per-stream array) once a consumer's PEL is empty — confirmed against Redis's documented behavior. Without this, the loop would busy-spin instead of falling through to blocking reads of new entries. FakeStreamRedis mirrors this correctly.
  • The preGenericsInitialization/postListen hook split (and the claim that postListen fires after pieces are loaded) was checked directly against @wolfstar/[email protected]'s compiled source: preGenericsInitialization does run synchronously in the Client constructor, and postListen does run inside listen(), after GatewayClient.start()'s load() → listen() → connect() sequence has loaded every BrokerListener piece.

Both check out. Test coverage (throwing-listener-leaves-pending, same-name-restart redelivery, no-listener-still-acks, once-unload timing) exercises real state transitions rather than tautological assertions. No issues found.

Pullfrog  | View workflow run | Using Claude Sonnet | 𝕏

@RedStar071
RedStar071 added this pull request to stack #141 September 27, 2026 12:39
RedStar071 added a commit that referenced this pull request Sep 27, 2026
The push token lacks the workflow OAuth scope, which GitHub requires
to push any change under .github/workflows/. Reverting this one file
from the previous commit so the rest of the fix can land; the
"plugin-broker" scope entry needs to be added by someone with that
scope (or via the GitHub UI) for PR #140's title check to pass.
…Redis Streams

New @wolfstar/plugin-broker package: createBroker publishes events over
a Redis stream (XADD MAXLEN ~), and a BrokerConsumer configured through
ClientOptions.broker reads them through a consumer group (XGROUP CREATE
... MKSTREAM, XREADGROUP, XACK), redelivering a restarted consumer's own
pending entries. BrokerListener pieces, loaded from the listeners
directory like plugin-gateway's EventGatewayListener, are typed per
event through an augmentable BrokerEvents map and only acked once every
matching listener resolves; a throwing listener leaves its entry
pending. Payloads are encoded with a CacheCodec from plugin-cache.

MVP slice of the RFC: XAUTOCLAIM reclaim of dead consumers, maxDeliveries
+ dead-letter, forwardGatewayDispatches, and signal-driven shutdown are
left to follow-ups.

Closes #136.
@pkg-pr-new

pkg-pr-new Bot commented Sep 27, 2026

Copy link
Copy Markdown

Open in StackBlitz

@wolfstar/plugin-api

pnpm add https://pkg.pr.new/wolfstar-project/plugins/@wolfstar/plugin-api@140

@wolfstar/plugin-broker

pnpm add https://pkg.pr.new/wolfstar-project/plugins/@wolfstar/plugin-broker@140

@wolfstar/plugin-cache

pnpm add https://pkg.pr.new/wolfstar-project/plugins/@wolfstar/plugin-cache@140

@wolfstar/plugin-gateway

pnpm add https://pkg.pr.new/wolfstar-project/plugins/@wolfstar/plugin-gateway@140

@wolfstar/plugin-i18next

pnpm add https://pkg.pr.new/wolfstar-project/plugins/@wolfstar/plugin-i18next@140

@wolfstar/plugin-logger

pnpm add https://pkg.pr.new/wolfstar-project/plugins/@wolfstar/plugin-logger@140

@wolfstar/plugin-sharder

pnpm add https://pkg.pr.new/wolfstar-project/plugins/@wolfstar/plugin-sharder@140

@wolfstar/plugin-subcommands-advanced

pnpm add https://pkg.pr.new/wolfstar-project/plugins/@wolfstar/plugin-subcommands-advanced@140

commit: f3d791e

@RedStar071
RedStar071 merged commit 46a3336 into main Sep 27, 2026
15 of 16 checks passed
@RedStar071
RedStar071 deleted the 136-plugin-broker branch September 27, 2026 13:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RFC: @wolfstar/plugin-broker — distribute gateway events across processes over Redis Streams

1 participant