Skip to content

feat: add @wolfstar/plugin-sharder, implementing the discord.js sharder RFC - #112

Merged
RedStar071 merged 4 commits into
feat/guild-extrasfrom
feat/sharder
Sep 25, 2026
Merged

RedStar071 merged 4 commits into
feat/guild-extrasfrom
feat/sharder

Conversation

@RedStar071

@RedStar071 RedStar071 commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Stacked on #111.

🔗 Linked issue

Related to #54 (the last item of the roadmap: multi-process sharding).

🧭 Context

A GatewayClient connects 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.

  • Manager. The strategy can be given as an instance or by name (fork by default, cluster, worker, network, plus a registry for custom ones), with init/destroy hooks. Layout options come from #7204 (shards, totalShards, shardList, and clusters defaulting to the CPU count, with "auto"). The manager fetches GET /gateway/bot once and shares it with the shards, and passes the token to them as DISCORD_TOKEN.
  • Supervision. Modelled on Erlang/OTP supervisors, as suggested in the thread: intensity and period, plus one-for-one, one-for-all or rest-for-one. shardGiveUp is the alert vladfrangu asked for. shardError carries a ShardSpawnError when a shard fails before it's ready (the RFC's error signal). Rolling restarts and reshard() keep downtime close to zero, as discussed in #7204's comments.
  • Pings. The manager pings each shard, as in both drafts, with delaySinceReceived from #7204. A shard that stops answering fires shardUnresponsive, or gets restarted if nothing listens.
  • Ready hint. kyranet's proposal: 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 fires shardSlowStart.
  • Client. RFC statuses plus Disconnected/Reconnecting from #7204. Also the RFC's ShardClient.registerMessageHandler/registerMessageTransformer, with the client building its codec from the names the manager sends, and a close handler.
  • Gateway shards. identifyThrottler is @discordjs/ws's IIdentifyThrottler: the manager paces identifies per max_concurrency bucket across every process. setShardHandler plus manager.startShard/closeShard/restartShard and shard.control() port #8859's per-gateway-shard ops.
  • Messages. Raw data, with opt-in replies, timeouts and abort. Aborting a request that is still queued drops it before it is sent, and the other side's handler gets an aborted signal. partial broadcasts return settled results. createCommandHandler/command is the optional command layer SpaceEEC suggested.
  • Serialization. JSON, V8 and raw handlers (raw comes from #7204). Transformers are async, composable, get the channel they work for, and ship with gzip and Brotli.
  • Network. NetworkStrategy plus ShardManagerProxy, over TLS or plain TCP, with token auth and heartbeats:
    • spawns go to the proxy with the most room, as proxies report it (Load), and are queued while none has room;
    • a proxy that loses a manager keeps its shards by default (managerLoss);
    • if it comes back within reconnectGrace, it keeps its shards; after that they're respawned elsewhere and its stale ones killed;
    • proxies aren't rebalanced.
  • Several managers. A proxy works in one of two modes, both answering the thread's questions. 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 of shardList. Each manager can have its own token, TLS and id, and shards of different managers are never routed to each other.
  • Peer proxies (P2P). With 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 are try* twins of every fallible operation (trySend, tryRequest, tryBroadcastRequest on the manager, channels and shards, plus tryControl), each resolving with a Result whose error is a ShardError. Request handlers can return a Result too: Ok is the reply, Err is the error the requester gets.
  • Observability. channel.pid, channel.threadId and channel.host, and worker threads are named after their shard.

Key changes

Area Change
New package @wolfstar/plugin-sharder: ShardManager, ShardChannel, ShardClient, ShardManagerProxy, ShardPing, strategies and registry, message handlers and transformers with registries, supervisor, identify queue, gateway information cache, command helpers
Tests 46 tests. Unit tests over an in-memory strategy (layouts, registries, requests, partial broadcasts, abort, codec, commands, identify pacing, gateway shard control, supervisor strategies, rolling restart, reshard, ready hint, pings). Integration tests spawning real forks, cluster workers and worker threads, plus a manager and proxies over TCP: local routing, waiting for a proxy, wrong token, reconnecting within the grace, respawning after it, a proxy serving two managers at once, shards on different proxies talking through peer connections without the manager. Plus the Result methods
Repo Labels, labeler, root README row; the plugin-gateway README points to the package for multi-process setups

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.

🤖 AI disclosure: Wolfstar Agent Kit modified this description. My AI open-source policy.

@coldtea-pr-lens

coldtea-pr-lens Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

◈ PR Lens

PR Lens paused analysis for this repository — the fair-use limit was reached. It resumes automatically at 2026-09-25T18:00:00.000Z.

@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.

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 (spawnDelay apart), respawns crashed ones within a respawns budget, 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 the ChannelStrategy/ClientTransport extension points for custom transports.
  • Protocol & serialization: an Op-tagged packet format (PacketCodec), JsonMessageHandler/V8MessageHandler, and composable GzipTransformer/BrotliTransformer.
  • Tests: an in-memory MemoryStrategy for 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-gateway README's Limitations section.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Sonnet | 𝕏

@RedStar071 RedStar071 changed the title feat: add @wolfstar/plugin-sharder for multi-process sharding feat: add @wolfstar/plugin-sharder, implementing the discord.js sharder RFC Sep 25, 2026
@pkg-pr-new

pkg-pr-new Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@wolfstar/plugin-api

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

@wolfstar/plugin-cache

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

@wolfstar/plugin-gateway

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

@wolfstar/plugin-i18next

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

@wolfstar/plugin-logger

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

@wolfstar/plugin-sharder

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

@wolfstar/plugin-subcommands-advanced

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

commit: f5afc67

@RedStar071
RedStar071 added this pull request to stack #96 September 25, 2026 15:13

@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 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 Shard with ShardChannel, adding markStopped(reason) as the shared terminal state for a supervisor give-up, and routed both the initial-spawn and crash-respawn give-up paths through ShardManager.supervise()/#startWithRetries() consistently.
  • Added the RFC's network strategy: ShardManagerProxy, NetworkStrategy, and network/Connection.ts — TCP/TLS with constant-time token auth (tokensMatch), manager failover across a managers list, reconnectGrace before 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) and IdentifyQueue (per-bucket max_concurrency pacing, exposed as @discordjs/ws's IIdentifyThrottler).
  • Added ShardPing, util/gateway.ts (GET /gateway/bot fetch/cache/recommended-shard-count), util/commands.ts (createCommandHandler/command), and strategies/registry.ts (registerStrategy/resolveStrategy).
  • Expanded ShardClient with gateway shard control (setShardHandler, control()), identifyThrottler, fetchGatewayInformation(), and a watchdog-based managerUnresponsive event.
  • Rewrote the test suite (manager.test.ts, messages.test.ts, expanded strategies.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 at ShardClient.ts:338-348) still throws synchronously on an already-aborted signal instead of rejecting — only broadcastRequest() was made async in this commit; request() is otherwise unchanged from the original report. Left the existing thread open rather than re-flagging it.

Pullfrog  | Fix it ➔ | View workflow run | Using Claude Sonnet | 𝕏

@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.

[!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>-returning try* twins (tryRequest/tryBroadcastRequest/trySend/tryControl) backed by toResult/settledToResults in util/requests.ts.
  • Added ShardManagerProxy.mode: "failover" | "all" for serving multiple ManagerLinks, and peer-to-peer proxy routing (peer option, PeerHello/PeerWelcome/PeerPacket/Load/Status/Directory frames, Connection.sendPeer/readPeer, NetworkStrategy.id, #sendDirectory()/#queueDirectory()).
  • Extended tests (tests/messages.test.ts, tests/strategies.test.ts) covering the Result twins, 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Sonnet | 𝕏

@pullfrog

pullfrog Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Your Claude subscription has hit its usage limit. It resets at 7:20pm (UTC). Re-trigger Pullfrog after the reset, or add an ANTHROPIC_API_KEY repo secret — Pullfrog routes around an exhausted subscription automatically when one is present.

Add repo secret → · Model settings → · Setup docs → · Ask in Discord →

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using Claude Sonnet | 𝕏

@pullfrog

pullfrog Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Your Claude subscription has hit its usage limit. It resets at 7:20pm (UTC). Re-trigger Pullfrog after the reset, or add an ANTHROPIC_API_KEY repo secret — Pullfrog routes around an exhausted subscription automatically when one is present.

Add repo secret → · Model settings → · Setup docs → · Ask in Discord →

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using Claude Sonnet | 𝕏

@RedStar071
RedStar071 merged commit 2742425 into main Sep 25, 2026
22 of 25 checks passed
@RedStar071
RedStar071 deleted the feat/sharder branch September 25, 2026 18:02
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.

1 participant