Repository navigation
feat(plugin-broker): distribute gateway events across processes over Redis Streams - #140
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
✅ 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 viaXADD [MAXLEN ~] * event <event> payload <base64>.BrokerConsumer(src/BrokerConsumer.ts): a consumer-group reader that implements the framework'sListener.Emittercontract itself, draining a restarted consumer's own pending entries before new ones, and onlyXACKing once every dispatched listener's promise resolves.BrokerListener/RegisterAsBrokerListener(src/BrokerListener.ts,src/util/decorators.ts): mirrorplugin-gateway'sEventGatewayListener/RegisterAsGatewayListenershape, typed through an augmentableBrokerEventsmap../registerplugin hook (src/register.ts): splits synchronous construction (preGenericsInitialization) from the async Redis connection/read loop (postListen), gated onClientOptions.broker.BrokerRedisClientLike(src/lib/redis.ts): a narrowioredis-overload-matching interface, verified against realRedis/Clustertypes via atests/types/ioredis.tsconsumption test wired into the roottypecheckscript.- Package scaffolding (exports map,
sideEffects,tsdown.config.ts, root README/labeler/labels/knip.json entries) follows theplugin-loggertemplate.
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 onXREADGROUP ... STREAMS s 0returningnil(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.FakeStreamRedismirrors this correctly. - The
preGenericsInitialization/postListenhook split (and the claim thatpostListenfires after pieces are loaded) was checked directly against@wolfstar/[email protected]'s compiled source:preGenericsInitializationdoes run synchronously in theClientconstructor, andpostListendoes run insidelisten(), afterGatewayClient.start()'sload() → listen() → connect()sequence has loaded everyBrokerListenerpiece.
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.
Claude Sonnet | 𝕏
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.
7 of 11 tasks
…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.
RedStar071
force-pushed
the
136-plugin-broker
branch
from
September 27, 2026 13:27
2ac2083 to
f3d791e
Compare
@wolfstar/plugin-api
@wolfstar/plugin-broker
@wolfstar/plugin-cache
@wolfstar/plugin-gateway
@wolfstar/plugin-i18next
@wolfstar/plugin-logger
@wolfstar/plugin-sharder
@wolfstar/plugin-subcommands-advanced
commit: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

🔗 Linked issue
resolves #136
Note
Stacked on #139 (
137-plugin-cache-codec), so@wolfstar/plugin-brokercan depend on the realCacheCodec/jsonCodecexported by@wolfstar/plugin-cacheinstead of a local duplicate. Base branch should move tomainonce #139 merges.🧭 Context
@wolfstar/plugin-gatewayruns the gateway in-process and@wolfstar/plugin-sharderspreads 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 ownMessageBroker(Redis Streams, no consumer group) let every worker receive every message with no load sharing, lost messages published while a worker was down, and itsack()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 theBrokerListenerpiece —XAUTOCLAIMreclaim 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), doingXADD <stream> [MAXLEN ~ <maxLength>] * event <event> payload <base64>.BrokerConsumer(configured through the newClientOptions.broker, installed by@wolfstar/plugin-broker/register):start()runsXGROUP CREATE ... MKSTREAM(idempotent, ignoringBUSYGROUP), 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'sListener.Emittercontract itself, soBrokerListenerpieces bind to it the same wayEventGatewayListenerpieces bind to aGatewayClient— a dedicated internal dispatch collects every listener's promise for one entry, awaits them, and only thenXACKs; a throwing listener leaves the entry pending.BrokerListener<Event>+RegisterAsBrokerListener(event, options), mirroringEventGatewayListener/RegisterAsGatewayListenerexactly, typed through an augmentableBrokerEventsmap../registerplugin hook splits construction (preGenericsInitialization, synchronous, only builds the inertBrokerConsumer) from starting it (postListen, async, fires onceclient.listen()has loaded every piece and started serving) — see the design-decision note below.BrokerRedisClientLikemirrorsplugin-cache'sRedisClientLikeconvention: only the exactioredisoverloads used (xadd,xgroup CREATE,xreadgroupwith/withoutBLOCK,xack), verified against realRedis/Clustertypes by atests/types/ioredis.tsconsumption test (wired into the roottypecheckscript the same wayplugin-cache's andplugin-gateway's already are).plugin-logger(exportsmap,tsdown, peer on@wolfstar/http-framework); regular workspace dependency on@wolfstar/plugin-cacheforCacheCodec/jsonCodec.Design decision:
ClientOptions.broker+postListen, not a manualcreateBrokerConsumer().start()An automated review on the issue argued against wiring the consumer through
ClientOptionsat all, citing that the framework'sPluginhooks all run synchronously during the baseClientconstructor. I checked the framework's compiled source (node_modules/@wolfstar/http-framework/dist/esm/index.js):preGenericsInitialization/preInitialization/postInitializationdo run in the constructor, butpreLoadandpostListenrun insideclient.load()andclient.listen()respectively — after every piece (includingBrokerListeners) is loaded and, forpostListen, once the server is already listening. That's exactly the async-setup use case those two hooks exist for, and it's the same pointGatewayClient.start()callsconnect()at. This PR only does synchronous construction inpreGenericsInitialization(mirroringplugin-logger'snew Logger()) and defers the actual Redis connection /XGROUP CREATE/ read loop topostListen, which keeps the RFC'snew 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(whichClientitself extends) as the same review suggested, since it already tracks in-flight listener promises viawaitForAllListenersToComplete(). 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.BrokerConsumerimplements the minimalListener.Emittercontract directly instead (six methods), with dispatch state scoped to the one entry being processed.Key changes
@wolfstar/plugin-broker: producer + consumer-group consumer +BrokerListenerpieceMessageBroker: no consumer group, no real ack, unbounded stream growthMAXLEN ~trimmingType of Change
Pre-flight Checklist
pnpm changeset(orpnpm changeset add --emptyif no release is needed). See .changeset/README.md.