Repository navigation
feat: add @wolfstar/plugin-sharder, implementing the discord.js sharder RFC - #112
Conversation
◈ PR LensPR Lens paused analysis for this repository — the fair-use limit was reached. It resumes automatically at 2026-09-25T18:00:00.000Z. |
There was a problem hiding this comment.
Important
A couple of concrete correctness bugs in the shard lifecycle/request machinery — see inline comments.
Reviewed changes
Reviewed the new @wolfstar/plugin-sharder package end to end (31 files, all new except the repo-wiring edits) plus a reviewfrog specialist trace of the Shard/ShardManager lifecycle for interleaving races.
ShardManager: spawns shards one at a time through a serialized queue (spawnDelayapart), respawns crashed ones within arespawnsbudget, routes messages/requests between shards.Shard: the manager's per-shard handle — start/close/restart, ready-waiters, ping watchdog, its own crash-loop budget.ShardClient: the shard-side API — status signalling,send/request/broadcastRequest, request/close handlers, default IPC/worker-port transport.- Strategies:
ForkStrategy,ClusterStrategy,WorkerStrategy(process / cluster worker / worker thread), plus theChannelStrategy/ClientTransportextension points for custom transports. - Protocol & serialization: an
Op-tagged packet format (PacketCodec),JsonMessageHandler/V8MessageHandler, and composableGzipTransformer/BrotliTransformer. - Tests: an in-memory
MemoryStrategyfor protocol/lifecycle unit tests, plus integration tests spawning real forks, cluster workers, and worker threads. - Repo wiring: labeler/labels entries, root README row, and a cross-link from the
plugin-gatewayREADME's Limitations section.
Claude Sonnet | 𝕏
@wolfstar/plugin-api
@wolfstar/plugin-cache
@wolfstar/plugin-gateway
@wolfstar/plugin-i18next
@wolfstar/plugin-logger
@wolfstar/plugin-sharder
@wolfstar/plugin-subcommands-advanced
commit: |
There was a problem hiding this comment.
> ℹ️ No new issues in this commit. One previously flagged issue is still unresolved — see below.
Reviewed changes
This commit is a near-total rewrite completing the sharder RFC's remaining pieces, not an incremental patch — read end to end alongside a manual lifecycle-race trace (no reviewfrog specialist needed this round; nothing surfaced that a specialist could move the needle on).
- Replaced
ShardwithShardChannel, addingmarkStopped(reason)as the shared terminal state for a supervisor give-up, and routed both the initial-spawn and crash-respawn give-up paths throughShardManager.supervise()/#startWithRetries()consistently. - Added the RFC's network strategy:
ShardManagerProxy,NetworkStrategy, andnetwork/Connection.ts— TCP/TLS with constant-time token auth (tokensMatch), manager failover across amanagerslist,reconnectGracebefore treating a disconnected proxy's shards as dead, and local routing between two shards of the same proxy via a separate negative-nonce space. - Added
Supervisor(Erlang/OTP-style crash-window accounting) andIdentifyQueue(per-bucketmax_concurrencypacing, exposed as@discordjs/ws'sIIdentifyThrottler). - Added
ShardPing,util/gateway.ts(GET /gateway/botfetch/cache/recommended-shard-count),util/commands.ts(createCommandHandler/command), andstrategies/registry.ts(registerStrategy/resolveStrategy). - Expanded
ShardClientwith gateway shard control (setShardHandler,control()),identifyThrottler,fetchGatewayInformation(), and a watchdog-basedmanagerUnresponsiveevent. - Rewrote the test suite (
manager.test.ts,messages.test.ts, expandedstrategies.test.ts) to match, including coverage for supervisor give-up, one-for-all/rest-for-one, rolling restarts, resharding, and the network strategy/proxy.
Prior findings, rechecked against this commit
- ✅ Fixed: a shard exhausting its respawn budget mid-crash-loop used to stay in limbo instead of
stopped—ShardChannel.markStopped()now closes that gap. Resolved the thread. - ✅ Fixed:
restart()racing a concurrent crash-respawn used to silently no-op — the rewritten#startWithRetries()/supervise()handle this consistently now. Resolved the thread. ⚠️ Still open:ShardClient.request()(now atShardClient.ts:338-348) still throws synchronously on an already-abortedsignalinstead of rejecting — onlybroadcastRequest()was madeasyncin this commit;request()is otherwise unchanged from the original report. Left the existing thread open rather than re-flagging it.
Claude Sonnet | 𝕏
7a1f12d to
c566832
Compare
There was a problem hiding this comment.
[!IMPORTANT]
Two correctness bugs in the new peer-routing logic, plus one earlier finding that's still unaddressed.
Reviewed changes
Reviewed the third round of commits on this PR (56bd50c..7a1f12d), plus a reviewfrog specialist trace of the new ShardManagerProxy peer/routing paths for interleaving races.
- Added
Result<T, E>-returningtry*twins (tryRequest/tryBroadcastRequest/trySend/tryControl) backed bytoResult/settledToResultsinutil/requests.ts. - Added
ShardManagerProxy.mode: "failover" | "all"for serving multipleManagerLinks, and peer-to-peer proxy routing (peeroption,PeerHello/PeerWelcome/PeerPacket/Load/Status/Directoryframes,Connection.sendPeer/readPeer,NetworkStrategy.id,#sendDirectory()/#queueDirectory()). - Extended tests (
tests/messages.test.ts,tests/strategies.test.ts) covering theResulttwins,mode: "all"multi-manager capacity sharing, and direct peer-to-peer shard requests — none of which exercise the connection-loss interleavings flagged below.
Also re-checked the still-open thread on ShardClient.ts:342-352/util/requests.ts:47-53 (pre-aborted signal throwing synchronously instead of rejecting) — unchanged in this round, left as-is since it's already tracked.
Claude Sonnet | 𝕏
c566832 to
f093dce
Compare
|
Your Claude subscription has hit its usage limit. It resets at 7:20pm (UTC). Re-trigger Pullfrog after the reset, or add an Add repo secret → · Model settings → · Setup docs → · Ask in Discord →
|
…eer requests A bounced request now only drops its own peer route.
f093dce to
f5afc67
Compare
|
Your Claude subscription has hit its usage limit. It resets at 7:20pm (UTC). Re-trigger Pullfrog after the reset, or add an Add repo secret → · Model settings → · Setup docs → · Ask in Discord →
|

Stacked on #111.
🔗 Linked issue
Related to #54 (the last item of the roadmap: multi-process sharding).
🧭 Context
A
GatewayClientconnects all its gateway shards from a single process. This PR adds a separate package,@wolfstar/plugin-sharder, that implements discord.js's sharder RFC (discordjs/discord.js#8084) in full. It follows the answers given in the RFC thread (vladfrangu, kyranet, SpaceEEC, ncs-pl, …) and the two drafts, #7204 and #8859, including their comments and review. The package README has a table mapping each point to the code.📚 Description
As in the RFC, a shard is what the manager spawns: a process, a cluster worker, a worker thread, or a process on another machine. One shard may connect several gateway shards. The manager talks to each shard through a
ShardChannel, the naming kyranet argued for in #8859's review. The package knows nothing about Discord's gateway protocol.forkby default,cluster,worker,network, plus a registry for custom ones), withinit/destroyhooks. Layout options come from #7204 (shards,totalShards,shardList, andclustersdefaulting to the CPU count, with"auto"). The manager fetchesGET /gateway/botonce and shares it with the shards, and passes the token to them asDISCORD_TOKEN.shardGiveUpis the alert vladfrangu asked for.shardErrorcarries aShardSpawnErrorwhen a shard fails before it's ready (the RFC'serrorsignal). Rolling restarts andreshard()keep downtime close to zero, as discussed in #7204's comments.delaySinceReceivedfrom #7204. A shard that stops answering firesshardUnresponsive, or gets restarted if nothing listens.spawn.readyHint, or the average ready time of the shards so far. A request that can't make it before the shard is ready fails right away, and a slow start firesshardSlowStart.Disconnected/Reconnectingfrom #7204. Also the RFC'sShardClient.registerMessageHandler/registerMessageTransformer, with the client building its codec from the names the manager sends, and a close handler.identifyThrottleris @discordjs/ws'sIIdentifyThrottler: the manager paces identifies permax_concurrencybucket across every process.setShardHandlerplusmanager.startShard/closeShard/restartShardandshard.control()port #8859's per-gateway-shard ops.signal.partialbroadcasts return settled results.createCommandHandler/commandis the optional command layer SpaceEEC suggested.NetworkStrategyplusShardManagerProxy, over TLS or plain TCP, with token auth and heartbeats:Load), and are queued while none has room;managerLoss);reconnectGrace, it keeps its shards; after that they're respawned elsewhere and its stale ones killed;mode: "failover"connects to one manager at a time and fails over to the next.mode: "all"connects to every manager at once and shares its capacity between them, e.g. managers that each own part ofshardList. Each manager can have its own token, TLS andid, and shards of different managers are never routed to each other.peer, proxies listen for each other. The manager sends every proxy a directory of which proxy runs which ready shard, and messages and requests between shards of different proxies go proxy to proxy. The first packet goes through the manager while the peer connection opens. Packets for a shard that moved or isn't ready bounce back and go through the manager. A lost peer connection fails its pending requests right away. Traffic between shards of the same proxy stays local, as before.Result<T, E>. Uses@sapphire/result, the port suggested in the thread. There aretry*twins of every fallible operation (trySend,tryRequest,tryBroadcastRequeston the manager, channels and shards, plustryControl), each resolving with aResultwhose error is aShardError. Request handlers can return aResulttoo:Okis the reply,Erris the error the requester gets.channel.pid,channel.threadIdandchannel.host, and worker threads are named after their shard.Key changes
@wolfstar/plugin-sharder:ShardManager,ShardChannel,ShardClient,ShardManagerProxy,ShardPing, strategies and registry, message handlers and transformers with registries, supervisor, identify queue, gateway information cache, command helpersResultmethodsType of Change
Pre-flight Checklist
pnpm changeset(orpnpm changeset add --emptyif no release is needed). See .changeset/README.md.