@wolfstar/plugin-sharder 0.0.0 → 0.1.0-next-20260926145943

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,344 +1,344 @@
1
- <div align="center">
2
-
3
- <img src="https://cdn.wolfstar.rocks/wolfstar-assets/wolfstar.png" alt="WolfStar" width="100" />
4
-
5
- # @wolfstar/plugin-sharder
6
-
7
- **Multi-process and multi-machine sharding for `@wolfstar/plugin-gateway`, or any bot.**
8
-
9
- [![version](https://npmx.dev/api/registry/badge/version/@wolfstar/plugin-sharder)](https://npmx.dev/package/@wolfstar/plugin-sharder)
10
- [![downloads](https://npmx.dev/api/registry/badge/downloads/@wolfstar/plugin-sharder)](https://npmx.dev/package/@wolfstar/plugin-sharder)
11
- [![license](https://img.shields.io/github/license/wolfstar-project/plugins?style=flat-square&color=informational)](https://github.com/wolfstar-project/plugins/blob/main/LICENSE)
12
-
13
- </div>
14
-
15
- ## Description
16
-
17
- A `GatewayClient` connects its gateway shards from a single process. This package spreads them
18
- across processes, cluster workers, worker threads, and machines. It implements the sharder RFC of
19
- discord.js, [discordjs/discord.js#8084](https://github.com/discordjs/discord.js/issues/8084), with
20
- the answers given in its thread, and the two implementations drafted for it,
21
- [discordjs/discord.js#7204](https://github.com/discordjs/discord.js/pull/7204) and
22
- [discordjs/discord.js#8859](https://github.com/discordjs/discord.js/pull/8859). See
23
- [RFC alignment](#rfc-alignment) for how each point maps to this package.
24
-
25
- As in the RFC, a **shard** is what the manager spawns (a process, a cluster worker, a worker
26
- thread, or a process on another machine), and it may connect several gateway shards. The manager
27
- talks to each shard through a `ShardChannel`. The package knows nothing about Discord's gateway:
28
- a shard runs any script using `ShardClient`, so it works with `@wolfstar/plugin-gateway`,
29
- `@discordjs/ws`, or another library.
30
-
31
- | Piece | Role |
32
- | -------------------- | -------------------------------------------------------------------------------------------------- |
33
- | `ShardManager` | Spawns and supervises the shards, paces their identifies, carries their messages |
34
- | `ShardChannel` | The manager's handle on one shard: status, pings, messages, requests, restarts |
35
- | `ShardClient` | The shard's side: signals its status, messages and requests, answers requests |
36
- | `ShardManagerProxy` | Runs shards on another machine for one or several managers, and talks to other proxies |
37
- | `ChannelStrategy` | How shards are spawned: `"fork"` (default), `"cluster"`, `"worker"`, `"network"`, or your own |
38
- | `MessageHandler` | How packets are serialized: `"json"` (default), `"v8"`, `"raw"`, or your own |
39
- | `MessageTransformer` | How serialized packets are transformed, composable: `"gzip"`, `"brotli"`, or your own (encryption) |
40
-
41
- ## Installation
42
-
43
- ```bash
44
- pnpm add @wolfstar/plugin-sharder
45
- ```
46
-
47
- ## Usage
48
-
49
- The manager and the shards can share one script: `ShardClient.context` is `null` in the manager.
50
-
51
- ```ts
52
- // bot.ts
53
- import { GatewayClient } from "@wolfstar/plugin-gateway";
54
- import { ShardClient, ShardManager } from "@wolfstar/plugin-sharder";
55
-
56
- if (!ShardClient.context) {
57
- // Discord's recommended shard count, split across one process per CPU core, forking this script.
58
- const manager = new ShardManager({ spawn: { delay: 0 } });
59
- manager.on("shardReady", (channel) =>
60
- console.log(`Shard ${channel.id} (${channel.shards}) is ready`),
61
- );
62
- await manager.spawn();
63
- } else {
64
- const shard = new ShardClient();
65
- const client = new GatewayClient({
66
- ...options,
67
- ...shard.gatewayOptions,
68
- // Identifies are paced by the manager across every process, so the spawn delay can be 0.
69
- gateway: { buildIdentifyThrottler: () => shard.identifyThrottler },
70
- });
71
- // Reuse the manager's GET /gateway/bot rather than requesting it again from every process.
72
- client.gateway.fetchGatewayInformation = () => shard.fetchGatewayInformation();
73
-
74
- const guilds = new Set<string>();
75
- client.on("guildCreate", (guild) => guilds.add(guild.id));
76
- client.on("guildDelete", (_guild, data) => guilds.delete(data.id));
77
- shard.setRequestHandler((body: { type: string }) => {
78
- if (body.type === "guildCount") return guilds.size;
79
- throw new Error(`Unknown request ${body.type}`);
80
- });
81
- shard.setCloseHandler(() => client.destroy());
82
-
83
- let pending = shard.shards.length;
84
- client.on("shardReady", () => {
85
- if (--pending === 0) void shard.ready();
86
- });
87
- await client.connect();
88
- }
89
- ```
90
-
91
- ### Layout
92
-
93
- | Option | Meaning |
94
- | ------------------- | ---------------------------------------------------------------------------------------------- |
95
- | `shards: 9` | 9 shards of one gateway shard each |
96
- | `shards: [3, 3, 3]` | 3 shards of 3 gateway shards each: 0-2, 3-5, 6-8 |
97
- | `shards: "auto"` | (default) the gateway shards split across `clusters` shards (default: one per CPU core) |
98
- | `totalShards` | the total across every manager; `"auto"` is Discord's recommendation (`recommended` rounds it) |
99
- | `shardList` | the gateway shards this manager runs, when several managers split them |
100
-
101
- `"auto"` needs the bot token (`token`, or `DISCORD_TOKEN`) or `gatewayInformation.fetch`. The
102
- manager fetches `GET /gateway/bot` once and caches it for `gatewayInformation.ttl`, keeping its
103
- session start limit up to date with the identifies it grants, and hands it to the shards
104
- (`shard.fetchGatewayInformation()`). A `token` given to the manager is passed to the shards as
105
- `DISCORD_TOKEN`.
106
-
107
- ### Messages and requests
108
-
109
- Messages are raw data, and a request is a message waiting for a reply:
110
-
111
- | From a shard | From the manager | Goes to |
112
- | -------------------------------- | -------------------------------- | -------------------------------- |
113
- | `shard.send(body)` | — | the manager's `message` event |
114
- | `shard.send(body, 2)` | `manager.send(2, body)` | shard 2's `message` event |
115
- | `shard.send(body, "all")` | `manager.broadcast(body)` | every shard |
116
- | `shard.request(body)` | — | the manager's request handler |
117
- | `shard.request(body, { to: 2 })` | `manager.request(2, body)` | shard 2's request handler |
118
- | `shard.broadcastRequest(body)` | `manager.broadcastRequest(body)` | every shard, replies by shard ID |
119
-
120
- `broadcastRequest` replaces discord.js's `broadcastEval` and `fetchClientValues`. With
121
- `{ partial: true }` it resolves with the outcome of every shard, like `Promise.allSettled`, so the
122
- replies that came before a timeout or a failure are kept.
123
-
124
- A request rejects with a `ShardRequestTimeoutError` past its timeout (the manager's
125
- `requestTimeout`, by default the ping timeout), and with the reason of its `signal` when aborted.
126
- Either way the other side is told, and the `signal` of its handler aborts, e.g. to cancel an HTTP
127
- request. A request aborted while it waits for a shard to be ready never leaves the queue. A
128
- throwing or missing handler rejects the request with a `ShardRequestError` carrying the remote
129
- error's name and message.
130
-
131
- A message or request for a shard that is not ready waits for it, within its timeout. With
132
- `spawn.readyHint` (or, without it, the average time the shards took so far), a request for a
133
- starting shard that is not expected to be ready before its timeout fails right away, and a shard
134
- slower than the estimate is emitted as `shardSlowStart`.
135
-
136
- The sharder has no command format and no `eval`, as the RFC settled. `createCommandHandler` and
137
- `command` are an optional, typed layer on top:
138
-
139
- ```ts
140
- const commands = { guildCount: () => guilds.size, guild: (id: string) => guilds.has(id) };
141
- shard.setRequestHandler(createCommandHandler(commands));
142
-
143
- const counts = await manager.broadcastRequest<CommandReply<typeof commands, "guildCount">>(
144
- command<typeof commands>("guildCount"),
145
- );
146
- ```
147
-
148
- ### `Result<T, E>`
149
-
150
- Every operation that can fail has a `try*` twin resolving with a `Result` of
151
- [`@sapphire/result`](https://www.npmjs.com/package/@sapphire/result) (re-exported as `Result`)
152
- rather than rejecting, as suggested in the RFC thread: `trySend`, `tryRequest`, and
153
- `tryBroadcastRequest` on the manager, channels, and shards, and `tryControl` on shards. The error is
154
- a `ShardError`. `tryBroadcastRequest` resolves with one `Result` per shard. A request handler may
155
- return a `Result` as well: `Ok` is the reply, and `Err` the error the requester gets.
156
-
157
- ```ts
158
- shard.setRequestHandler((id: string) =>
159
- guilds.has(id) ? Result.ok(guilds.get(id)) : Result.err(new RangeError("Unknown guild")),
160
- );
161
-
162
- const guild = await manager.tryRequest(0, guildId);
163
- guild.match({ ok: (value) => console.log(value), err: (error) => console.error(error.message) });
164
- const counts = await manager.tryBroadcastRequest<number>({ type: "guildCount" });
165
- const total = counts.reduce((sum, count) => sum + count.unwrapOr(0), 0);
166
- ```
167
-
168
- ### Lifecycle and supervision
169
-
170
- A shard signals its status, and the manager emits it:
171
-
172
- | Status | Set by | When the process stops |
173
- | -------------- | --------------------------------- | ----------------------------------- |
174
- | `Starting` | `new ShardClient()` | restarted, if the supervisor allows |
175
- | `Ready` | `shard.ready()` | restarted, if the supervisor allows |
176
- | `Disconnected` | `shard.disconnected()` | restarted, if the supervisor allows |
177
- | `Reconnecting` | `shard.reconnecting()` | restarted, if the supervisor allows |
178
- | `Exiting` | `shard.exit()` | not restarted |
179
- | `Restarting` | `shard.restart()` | restarted, always |
180
- | `Idle` | the manager, when no process runs | — |
181
-
182
- Crashes go through a supervisor modelled on Erlang/OTP's: a shard crashing more than
183
- `supervisor.intensity` times within `supervisor.period` milliseconds is given up on and emitted as
184
- `shardGiveUp` (with `period: 0`, the default, the crashes are counted in a row until the shard is
185
- ready again, and `intensity: -1`, the default, never gives up). `supervisor.strategy` picks what
186
- else restarts: `"one-for-one"` (the default), `"one-for-all"`, or `"rest-for-one"`. A shard that
187
- fails before it is ready (the RFC's `error` signal) is emitted as `shardError` with a
188
- `ShardSpawnError`.
189
-
190
- Shards start one at a time, `spawn.delay` apart. One that is not ready within `spawn.timeout` is
191
- killed and tried again at the end of the queue. The manager pings every ready shard each
192
- `ping.interval` (`delaySinceReceived` counts from the last answer instead); one that stops
193
- answering for `ping.timeout` is emitted as `shardUnresponsive`, or restarted when nothing listens.
194
- `channel.ping` has the latency and the timestamps.
195
-
196
- `manager.restart(id)` and `manager.destroy()` first ask the shard to close, which runs its close
197
- handler, and kill it past the timeout. `manager.restart(id, { rolling: true })` spawns the new shard
198
- first and closes the old one once the new one is ready, for close to no downtime;
199
- `manager.reshard(layout)` does the same for a whole new layout. When the manager dies, a process
200
- shard emits `disconnect` and exits when nothing listens to it; a worker thread stops with it.
201
-
202
- ### Gateway shards
203
-
204
- The manager paces identifies across every process: `shard.identifyThrottler` is `@discordjs/ws`'s
205
- `IIdentifyThrottler`, and the manager grants one identify per `max_concurrency` bucket every
206
- `identify.delay` (5 seconds). Within a shard, `setShardHandler({ start, close })` lets the manager
207
- start and close single gateway shards (`manager.startShard(id)`, `closeShard`, `restartShard`), and
208
- `shard.control()` asks the manager to start, close, or restart shards or gateway shards:
209
-
210
- ```ts
211
- shard.setShardHandler({ start: (id) => connect(id), close: (id) => disconnect(id) });
212
- await shard.control({ action: "restart", target: { shard: 12 } });
213
- await shard.control({ action: "restart", target: { channel: "all" } });
214
- ```
215
-
216
- ### Strategies
217
-
218
- | Strategy | Shards are | Notes |
219
- | ------------------------- | --------------------------------- | -------------------------------------------------------------------------- |
220
- | `ForkStrategy` (`"fork"`) | child processes | The default. Ports must differ per shard. Defaults to the manager's script |
221
- | `ClusterStrategy` | `node:cluster` workers | Ports are shared and balanced. Defaults to the manager's script |
222
- | `WorkerStrategy` | worker threads | Fastest messages, but one crash of the process stops every shard |
223
- | `NetworkStrategy` | processes of `ShardManagerProxy`s | Other machines, over TLS (or plain TCP on trusted networks) |
224
-
225
- A strategy can be given by name, built with `strategyOptions`, and custom ones are registered with
226
- `registerStrategy`. `channel.pid`, `channel.threadId`, and `channel.host` identify each shard.
227
-
228
- ### Several machines
229
-
230
- The manager listens with a `NetworkStrategy`, and a `ShardManagerProxy` on each machine connects to
231
- it, spawns the shards it is given with its own strategy, and carries their messages:
232
-
233
- ```ts
234
- // On the manager's machine.
235
- const manager = new ShardManager({
236
- strategy: new NetworkStrategy({
237
- port: 7000,
238
- token: process.env.SHARDER_TOKEN!,
239
- tls: { key, cert },
240
- }),
241
- totalShards: "auto",
242
- clusters: 16,
243
- });
244
- await manager.spawn();
245
-
246
- // On every other machine.
247
- const proxy = new ShardManagerProxy({
248
- managers: ["manager.internal:7000", "manager-backup.internal:7000"],
249
- token: process.env.SHARDER_TOKEN!,
250
- tls: { ca },
251
- capacity: 8,
252
- strategy: new ForkStrategy({ path: "./bot.js" }),
253
- });
254
- await proxy.connect();
255
- ```
256
-
257
- Spawns go to the connected proxy with the most room, as the proxies report it, and wait when every
258
- proxy is full or none is connected. A proxy losing a manager keeps its shards (`managerLoss:
259
- "keep"`, the default, or `"exit"`) and reconnects; back within the manager's `reconnectGrace`, it
260
- keeps its shards, and past it they are spawned elsewhere and its stale ones killed. Proxies coming
261
- back are not rebalanced: they take the next spawns.
262
-
263
- A proxy serves its managers in one of two modes:
264
-
265
- - `mode: "failover"` (the default): one manager at a time, the first reachable of `managers`,
266
- failing over to the next ones when it loses it, e.g. a primary and a standby manager.
267
- - `mode: "all"`: every manager of `managers` at once, sharing its `capacity` between them, e.g.
268
- managers each running part of the gateway shards (`shardList`). Each manager can have its own
269
- `token` and `tls`, and gets its own `id` (`NetworkStrategy`'s `id` option), which keeps the
270
- shards of different managers apart.
271
-
272
- Messages and requests between two shards of the same manager and the same proxy never go through
273
- the manager. With `peer`, proxies also talk to each other: each listens for peer connections, the
274
- manager tells every proxy which proxy runs which ready shard, and the messages and requests between
275
- shards of different proxies go from one proxy to the other directly. The first one to a new proxy
276
- goes through the manager while the peer connection opens; a packet for a shard that moved or is not
277
- ready is sent back and goes through the manager; a peer connection lost fails the requests waiting
278
- on it right away.
279
-
280
- ```ts
281
- const proxy = new ShardManagerProxy({
282
- managers: ["north.internal:7000", "south.internal:7000"],
283
- mode: "all",
284
- token: process.env.SHARDER_TOKEN!,
285
- capacity: 16,
286
- strategy: new ForkStrategy({ path: "./bot.js" }),
287
- peer: { port: 7001, advertise: "den.internal", tls: { key, cert }, connectTls: { ca } },
288
- });
289
- ```
290
-
291
- ### Serialization and transformers
292
-
293
- The manager tells its shards the names of its message handler and transformers, and they build the
294
- same ones from the registry: custom ones must be registered on both sides, with
295
- `registerMessageHandler` / `registerMessageTransformer` (or `ShardClient.registerMessageHandler` /
296
- `ShardClient.registerMessageTransformer`, as in the RFC). Transformers write in their order and read
297
- in the reverse one, so `["gzip", "aes"]` compresses then encrypts; they are async, and get the
298
- channel they work for. `"v8"` keeps `Map`s, `Set`s, `Date`s, `BigInt`s, and typed arrays, which
299
- JSON loses; `"raw"` passes values as they are to channels that clone them (worker threads, process
300
- IPC), without transformers or the network.
301
-
302
- ```ts
303
- ShardClient.registerMessageTransformer("aes", () => new AesTransformer(process.env.SHARDER_KEY!));
304
- const manager = new ShardManager({ messageHandler: "v8", transformers: ["gzip", "aes"] });
305
- ```
306
-
307
- ## RFC alignment
308
-
309
- | Source | Point | Here |
310
- | -------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
311
- | RFC | `ShardManager` with a strategy, by instance or name | `strategy` (instance or name) and `registerStrategy` |
312
- | RFC | Worker, Fork (default), Cluster, Network strategies | `WorkerStrategy`, `ForkStrategy`, `ClusterStrategy`, `NetworkStrategy` |
313
- | RFC | Manager configures the clients through the environment | `ShardContext` in `WOLFSTAR_SHARDER` (or worker data), `DISCORD_TOKEN` |
314
- | RFC | Lifecycle events, invalid messages printed when unhandled | `shardCreate` … `shardInvalidMessage`, `console.error` fallbacks |
315
- | RFC | Missing pings restart the shard when unhandled | `shardUnresponsive`, restart without listeners |
316
- | RFC | Requests time out within the ping timeout, globally or per request | `requestTimeout` (defaults to `ping.timeout`), `timeout` per request |
317
- | RFC | `ShardClient` signals: Starting, Ready, Exit, Restarting | `ShardStatus` (plus #7204's `Disconnected` and `Reconnecting`) |
318
- | RFC | `registerMessageHandler` / `registerMessageTransformer` | `ShardClient.register*` and the module-level registries |
319
- | RFC | JSON and V8 message handlers | `JsonMessageHandler`, `V8MessageHandler` (plus #7204's `RawMessageHandler`) |
320
- | RFC | Composable transformers, reverse order when reading, Gzip and Brotli | `MessageTransformer` with its channel context, `GzipTransformer`, `BrotliTransformer` |
321
- | RFC | `ShardManagerProxy` over an encrypted network, local routing | `ShardManagerProxy`, TLS, messages between its shards routed locally |
322
- | RFC answers | Raw data, no `eval`; opt-in replies with timeouts; async transformers | Messages vs requests, `RequestOptions`, async `write`/`read` |
323
- | RFC answers | Cancel requests, dequeue them, `AbortController` in shards | `signal`, dropped from the ready queue, `signal` in handlers |
324
- | RFC answers | Partial results of aborted broadcasts | `broadcastRequest(body, { partial: true })` |
325
- | RFC answers | Enqueue messages for shards not ready, with a ready-time hint | `waitForReady`, `spawn.readyHint` (or measured), early failure, `shardSlowStart` |
326
- | RFC answers | `error` signal when a shard fails before ready | `shardError` with `ShardSpawnError` |
327
- | RFC answers | Configurable restart limits, alerts, Erlang supervisors | `supervisor` intensity, period, strategy; `shardGiveUp` |
328
- | RFC answers | Manager death: configurable, default die | `disconnect` event, exit without listeners; proxy `managerLoss` |
329
- | RFC answers | Proxies: capacity, queue when full, failover managers, no rebalancing | `capacity` with `Load` reports, pending spawns, `managers` list, `reconnectGrace` |
330
- | RFC answers | `Result<T, E>` instead of `try`/`catch` | `try*` methods, handlers returning a `Result`, `ShardError` |
331
- | RFC answers | Proxies with several managers | `mode: "failover"` or `mode: "all"`, per-manager `token`, `tls`, and `id` |
332
- | RFC | Proxies routing to shards they host, and to other proxies (P2P) | Local routing, `peer` connections, the manager's directory of ready shards |
333
- | RFC answers | Optional built-in command layer | `createCommandHandler`, `command` |
334
- | RFC answers | Identify processes and threads for observability | `channel.pid`, `threadId`, `host`; worker threads named `shard <id>` |
335
- | #7204 | `totalShards`, `shardList`, `clusters` (CPU count), `"auto"` | Layout options |
336
- | #7204 | Respawn budget that resets on ready | `supervisor` with `period: 0` |
337
- | #7204 | Fetch `/gateway/bot` once in the manager and share it | `gatewayInformation`, `shard.fetchGatewayInformation()` |
338
- | #7204 | `fetchRecommendedShards` with `guildsPerShard` and `multipleOf` | `fetchRecommendedShardCount`, `recommended` |
339
- | #7204 | Ping with `delaySinceReceived` | `ping.delaySinceReceived` |
340
- | #7204 / #8859 | Restart all shards, spawn delay after ready, spawn timeout then requeue | `restartAll`, `spawn.delay`, `spawn.timeout` |
341
- | #8859 | Manager-side "channel" to each shard | `ShardChannel`, `manager.channels` |
342
- | #8859 | Start, close, restart single gateway shards, from the manager or shards | `setShardHandler`, `startShard` & co., `shard.control()` |
343
- | #8859 | Strategies with `init` and `destroy` | `ChannelStrategy.init` / `destroy` |
344
- | #7204 comments | Cross-process identify pacing, minimal-downtime restarts and resharding | `identifyThrottler`, `restart(id, { rolling })`, `reshard()` |
1
+ <div align="center">
2
+
3
+ <img src="https://cdn.wolfstar.rocks/wolfstar-assets/wolfstar.png" alt="WolfStar" width="100" />
4
+
5
+ # @wolfstar/plugin-sharder
6
+
7
+ **Multi-process and multi-machine sharding for `@wolfstar/plugin-gateway`, or any bot.**
8
+
9
+ [![version](https://npmx.dev/api/registry/badge/version/@wolfstar/plugin-sharder)](https://npmx.dev/package/@wolfstar/plugin-sharder)
10
+ [![downloads](https://npmx.dev/api/registry/badge/downloads/@wolfstar/plugin-sharder)](https://npmx.dev/package/@wolfstar/plugin-sharder)
11
+ [![license](https://img.shields.io/github/license/wolfstar-project/plugins?style=flat-square&color=informational)](https://github.com/wolfstar-project/plugins/blob/main/LICENSE)
12
+
13
+ </div>
14
+
15
+ ## Description
16
+
17
+ A `GatewayClient` connects its gateway shards from a single process. This package spreads them
18
+ across processes, cluster workers, worker threads, and machines. It implements the sharder RFC of
19
+ discord.js, [discordjs/discord.js#8084](https://github.com/discordjs/discord.js/issues/8084), with
20
+ the answers given in its thread, and the two implementations drafted for it,
21
+ [discordjs/discord.js#7204](https://github.com/discordjs/discord.js/pull/7204) and
22
+ [discordjs/discord.js#8859](https://github.com/discordjs/discord.js/pull/8859). See
23
+ [RFC alignment](#rfc-alignment) for how each point maps to this package.
24
+
25
+ As in the RFC, a **shard** is what the manager spawns (a process, a cluster worker, a worker
26
+ thread, or a process on another machine), and it may connect several gateway shards. The manager
27
+ talks to each shard through a `ShardChannel`. The package knows nothing about Discord's gateway:
28
+ a shard runs any script using `ShardClient`, so it works with `@wolfstar/plugin-gateway`,
29
+ `@discordjs/ws`, or another library.
30
+
31
+ | Piece | Role |
32
+ | -------------------- | -------------------------------------------------------------------------------------------------- |
33
+ | `ShardManager` | Spawns and supervises the shards, paces their identifies, carries their messages |
34
+ | `ShardChannel` | The manager's handle on one shard: status, pings, messages, requests, restarts |
35
+ | `ShardClient` | The shard's side: signals its status, messages and requests, answers requests |
36
+ | `ShardManagerProxy` | Runs shards on another machine for one or several managers, and talks to other proxies |
37
+ | `ChannelStrategy` | How shards are spawned: `"fork"` (default), `"cluster"`, `"worker"`, `"network"`, or your own |
38
+ | `MessageHandler` | How packets are serialized: `"json"` (default), `"v8"`, `"raw"`, or your own |
39
+ | `MessageTransformer` | How serialized packets are transformed, composable: `"gzip"`, `"brotli"`, or your own (encryption) |
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ pnpm add @wolfstar/plugin-sharder
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ The manager and the shards can share one script: `ShardClient.context` is `null` in the manager.
50
+
51
+ ```ts
52
+ // bot.ts
53
+ import { GatewayClient } from "@wolfstar/plugin-gateway";
54
+ import { ShardClient, ShardManager } from "@wolfstar/plugin-sharder";
55
+
56
+ if (!ShardClient.context) {
57
+ // Discord's recommended shard count, split across one process per CPU core, forking this script.
58
+ const manager = new ShardManager({ spawn: { delay: 0 } });
59
+ manager.on("shardReady", (channel) =>
60
+ console.log(`Shard ${channel.id} (${channel.shards}) is ready`),
61
+ );
62
+ await manager.spawn();
63
+ } else {
64
+ const shard = new ShardClient();
65
+ const client = new GatewayClient({
66
+ ...options,
67
+ ...shard.gatewayOptions,
68
+ // Identifies are paced by the manager across every process, so the spawn delay can be 0.
69
+ gateway: { buildIdentifyThrottler: () => shard.identifyThrottler },
70
+ });
71
+ // Reuse the manager's GET /gateway/bot rather than requesting it again from every process.
72
+ client.gateway.fetchGatewayInformation = () => shard.fetchGatewayInformation();
73
+
74
+ const guilds = new Set<string>();
75
+ client.on("guildCreate", (guild) => guilds.add(guild.id));
76
+ client.on("guildDelete", (_guild, data) => guilds.delete(data.id));
77
+ shard.setRequestHandler((body: { type: string }) => {
78
+ if (body.type === "guildCount") return guilds.size;
79
+ throw new Error(`Unknown request ${body.type}`);
80
+ });
81
+ shard.setCloseHandler(() => client.destroy());
82
+
83
+ let pending = shard.shards.length;
84
+ client.on("shardReady", () => {
85
+ if (--pending === 0) void shard.ready();
86
+ });
87
+ await client.connect();
88
+ }
89
+ ```
90
+
91
+ ### Layout
92
+
93
+ | Option | Meaning |
94
+ | ------------------- | ---------------------------------------------------------------------------------------------- |
95
+ | `shards: 9` | 9 shards of one gateway shard each |
96
+ | `shards: [3, 3, 3]` | 3 shards of 3 gateway shards each: 0-2, 3-5, 6-8 |
97
+ | `shards: "auto"` | (default) the gateway shards split across `clusters` shards (default: one per CPU core) |
98
+ | `totalShards` | the total across every manager; `"auto"` is Discord's recommendation (`recommended` rounds it) |
99
+ | `shardList` | the gateway shards this manager runs, when several managers split them |
100
+
101
+ `"auto"` needs the bot token (`token`, or `DISCORD_TOKEN`) or `gatewayInformation.fetch`. The
102
+ manager fetches `GET /gateway/bot` once and caches it for `gatewayInformation.ttl`, keeping its
103
+ session start limit up to date with the identifies it grants, and hands it to the shards
104
+ (`shard.fetchGatewayInformation()`). A `token` given to the manager is passed to the shards as
105
+ `DISCORD_TOKEN`.
106
+
107
+ ### Messages and requests
108
+
109
+ Messages are raw data, and a request is a message waiting for a reply:
110
+
111
+ | From a shard | From the manager | Goes to |
112
+ | -------------------------------- | -------------------------------- | -------------------------------- |
113
+ | `shard.send(body)` | — | the manager's `message` event |
114
+ | `shard.send(body, 2)` | `manager.send(2, body)` | shard 2's `message` event |
115
+ | `shard.send(body, "all")` | `manager.broadcast(body)` | every shard |
116
+ | `shard.request(body)` | — | the manager's request handler |
117
+ | `shard.request(body, { to: 2 })` | `manager.request(2, body)` | shard 2's request handler |
118
+ | `shard.broadcastRequest(body)` | `manager.broadcastRequest(body)` | every shard, replies by shard ID |
119
+
120
+ `broadcastRequest` replaces discord.js's `broadcastEval` and `fetchClientValues`. With
121
+ `{ partial: true }` it resolves with the outcome of every shard, like `Promise.allSettled`, so the
122
+ replies that came before a timeout or a failure are kept.
123
+
124
+ A request rejects with a `ShardRequestTimeoutError` past its timeout (the manager's
125
+ `requestTimeout`, by default the ping timeout), and with the reason of its `signal` when aborted.
126
+ Either way the other side is told, and the `signal` of its handler aborts, e.g. to cancel an HTTP
127
+ request. A request aborted while it waits for a shard to be ready never leaves the queue. A
128
+ throwing or missing handler rejects the request with a `ShardRequestError` carrying the remote
129
+ error's name and message.
130
+
131
+ A message or request for a shard that is not ready waits for it, within its timeout. With
132
+ `spawn.readyHint` (or, without it, the average time the shards took so far), a request for a
133
+ starting shard that is not expected to be ready before its timeout fails right away, and a shard
134
+ slower than the estimate is emitted as `shardSlowStart`.
135
+
136
+ The sharder has no command format and no `eval`, as the RFC settled. `createCommandHandler` and
137
+ `command` are an optional, typed layer on top:
138
+
139
+ ```ts
140
+ const commands = { guildCount: () => guilds.size, guild: (id: string) => guilds.has(id) };
141
+ shard.setRequestHandler(createCommandHandler(commands));
142
+
143
+ const counts = await manager.broadcastRequest<CommandReply<typeof commands, "guildCount">>(
144
+ command<typeof commands>("guildCount"),
145
+ );
146
+ ```
147
+
148
+ ### `Result<T, E>`
149
+
150
+ Every operation that can fail has a `try*` twin resolving with a `Result` of
151
+ [`@sapphire/result`](https://www.npmjs.com/package/@sapphire/result) (re-exported as `Result`)
152
+ rather than rejecting, as suggested in the RFC thread: `trySend`, `tryRequest`, and
153
+ `tryBroadcastRequest` on the manager, channels, and shards, and `tryControl` on shards. The error is
154
+ a `ShardError`. `tryBroadcastRequest` resolves with one `Result` per shard. A request handler may
155
+ return a `Result` as well: `Ok` is the reply, and `Err` the error the requester gets.
156
+
157
+ ```ts
158
+ shard.setRequestHandler((id: string) =>
159
+ guilds.has(id) ? Result.ok(guilds.get(id)) : Result.err(new RangeError("Unknown guild")),
160
+ );
161
+
162
+ const guild = await manager.tryRequest(0, guildId);
163
+ guild.match({ ok: (value) => console.log(value), err: (error) => console.error(error.message) });
164
+ const counts = await manager.tryBroadcastRequest<number>({ type: "guildCount" });
165
+ const total = counts.reduce((sum, count) => sum + count.unwrapOr(0), 0);
166
+ ```
167
+
168
+ ### Lifecycle and supervision
169
+
170
+ A shard signals its status, and the manager emits it:
171
+
172
+ | Status | Set by | When the process stops |
173
+ | -------------- | --------------------------------- | ----------------------------------- |
174
+ | `Starting` | `new ShardClient()` | restarted, if the supervisor allows |
175
+ | `Ready` | `shard.ready()` | restarted, if the supervisor allows |
176
+ | `Disconnected` | `shard.disconnected()` | restarted, if the supervisor allows |
177
+ | `Reconnecting` | `shard.reconnecting()` | restarted, if the supervisor allows |
178
+ | `Exiting` | `shard.exit()` | not restarted |
179
+ | `Restarting` | `shard.restart()` | restarted, always |
180
+ | `Idle` | the manager, when no process runs | — |
181
+
182
+ Crashes go through a supervisor modelled on Erlang/OTP's: a shard crashing more than
183
+ `supervisor.intensity` times within `supervisor.period` milliseconds is given up on and emitted as
184
+ `shardGiveUp` (with `period: 0`, the default, the crashes are counted in a row until the shard is
185
+ ready again, and `intensity: -1`, the default, never gives up). `supervisor.strategy` picks what
186
+ else restarts: `"one-for-one"` (the default), `"one-for-all"`, or `"rest-for-one"`. A shard that
187
+ fails before it is ready (the RFC's `error` signal) is emitted as `shardError` with a
188
+ `ShardSpawnError`.
189
+
190
+ Shards start one at a time, `spawn.delay` apart. One that is not ready within `spawn.timeout` is
191
+ killed and tried again at the end of the queue. The manager pings every ready shard each
192
+ `ping.interval` (`delaySinceReceived` counts from the last answer instead); one that stops
193
+ answering for `ping.timeout` is emitted as `shardUnresponsive`, or restarted when nothing listens.
194
+ `channel.ping` has the latency and the timestamps.
195
+
196
+ `manager.restart(id)` and `manager.destroy()` first ask the shard to close, which runs its close
197
+ handler, and kill it past the timeout. `manager.restart(id, { rolling: true })` spawns the new shard
198
+ first and closes the old one once the new one is ready, for close to no downtime;
199
+ `manager.reshard(layout)` does the same for a whole new layout. When the manager dies, a process
200
+ shard emits `disconnect` and exits when nothing listens to it; a worker thread stops with it.
201
+
202
+ ### Gateway shards
203
+
204
+ The manager paces identifies across every process: `shard.identifyThrottler` is `@discordjs/ws`'s
205
+ `IIdentifyThrottler`, and the manager grants one identify per `max_concurrency` bucket every
206
+ `identify.delay` (5 seconds). Within a shard, `setShardHandler({ start, close })` lets the manager
207
+ start and close single gateway shards (`manager.startShard(id)`, `closeShard`, `restartShard`), and
208
+ `shard.control()` asks the manager to start, close, or restart shards or gateway shards:
209
+
210
+ ```ts
211
+ shard.setShardHandler({ start: (id) => connect(id), close: (id) => disconnect(id) });
212
+ await shard.control({ action: "restart", target: { shard: 12 } });
213
+ await shard.control({ action: "restart", target: { channel: "all" } });
214
+ ```
215
+
216
+ ### Strategies
217
+
218
+ | Strategy | Shards are | Notes |
219
+ | ------------------------- | --------------------------------- | -------------------------------------------------------------------------- |
220
+ | `ForkStrategy` (`"fork"`) | child processes | The default. Ports must differ per shard. Defaults to the manager's script |
221
+ | `ClusterStrategy` | `node:cluster` workers | Ports are shared and balanced. Defaults to the manager's script |
222
+ | `WorkerStrategy` | worker threads | Fastest messages, but one crash of the process stops every shard |
223
+ | `NetworkStrategy` | processes of `ShardManagerProxy`s | Other machines, over TLS (or plain TCP on trusted networks) |
224
+
225
+ A strategy can be given by name, built with `strategyOptions`, and custom ones are registered with
226
+ `registerStrategy`. `channel.pid`, `channel.threadId`, and `channel.host` identify each shard.
227
+
228
+ ### Several machines
229
+
230
+ The manager listens with a `NetworkStrategy`, and a `ShardManagerProxy` on each machine connects to
231
+ it, spawns the shards it is given with its own strategy, and carries their messages:
232
+
233
+ ```ts
234
+ // On the manager's machine.
235
+ const manager = new ShardManager({
236
+ strategy: new NetworkStrategy({
237
+ port: 7000,
238
+ token: process.env.SHARDER_TOKEN!,
239
+ tls: { key, cert },
240
+ }),
241
+ totalShards: "auto",
242
+ clusters: 16,
243
+ });
244
+ await manager.spawn();
245
+
246
+ // On every other machine.
247
+ const proxy = new ShardManagerProxy({
248
+ managers: ["manager.internal:7000", "manager-backup.internal:7000"],
249
+ token: process.env.SHARDER_TOKEN!,
250
+ tls: { ca },
251
+ capacity: 8,
252
+ strategy: new ForkStrategy({ path: "./bot.js" }),
253
+ });
254
+ await proxy.connect();
255
+ ```
256
+
257
+ Spawns go to the connected proxy with the most room, as the proxies report it, and wait when every
258
+ proxy is full or none is connected. A proxy losing a manager keeps its shards (`managerLoss:
259
+ "keep"`, the default, or `"exit"`) and reconnects; back within the manager's `reconnectGrace`, it
260
+ keeps its shards, and past it they are spawned elsewhere and its stale ones killed. Proxies coming
261
+ back are not rebalanced: they take the next spawns.
262
+
263
+ A proxy serves its managers in one of two modes:
264
+
265
+ - `mode: "failover"` (the default): one manager at a time, the first reachable of `managers`,
266
+ failing over to the next ones when it loses it, e.g. a primary and a standby manager.
267
+ - `mode: "all"`: every manager of `managers` at once, sharing its `capacity` between them, e.g.
268
+ managers each running part of the gateway shards (`shardList`). Each manager can have its own
269
+ `token` and `tls`, and gets its own `id` (`NetworkStrategy`'s `id` option), which keeps the
270
+ shards of different managers apart.
271
+
272
+ Messages and requests between two shards of the same manager and the same proxy never go through
273
+ the manager. With `peer`, proxies also talk to each other: each listens for peer connections, the
274
+ manager tells every proxy which proxy runs which ready shard, and the messages and requests between
275
+ shards of different proxies go from one proxy to the other directly. The first one to a new proxy
276
+ goes through the manager while the peer connection opens; a packet for a shard that moved or is not
277
+ ready is sent back and goes through the manager; a peer connection lost fails the requests waiting
278
+ on it right away.
279
+
280
+ ```ts
281
+ const proxy = new ShardManagerProxy({
282
+ managers: ["north.internal:7000", "south.internal:7000"],
283
+ mode: "all",
284
+ token: process.env.SHARDER_TOKEN!,
285
+ capacity: 16,
286
+ strategy: new ForkStrategy({ path: "./bot.js" }),
287
+ peer: { port: 7001, advertise: "den.internal", tls: { key, cert }, connectTls: { ca } },
288
+ });
289
+ ```
290
+
291
+ ### Serialization and transformers
292
+
293
+ The manager tells its shards the names of its message handler and transformers, and they build the
294
+ same ones from the registry: custom ones must be registered on both sides, with
295
+ `registerMessageHandler` / `registerMessageTransformer` (or `ShardClient.registerMessageHandler` /
296
+ `ShardClient.registerMessageTransformer`, as in the RFC). Transformers write in their order and read
297
+ in the reverse one, so `["gzip", "aes"]` compresses then encrypts; they are async, and get the
298
+ channel they work for. `"v8"` keeps `Map`s, `Set`s, `Date`s, `BigInt`s, and typed arrays, which
299
+ JSON loses; `"raw"` passes values as they are to channels that clone them (worker threads, process
300
+ IPC), without transformers or the network.
301
+
302
+ ```ts
303
+ ShardClient.registerMessageTransformer("aes", () => new AesTransformer(process.env.SHARDER_KEY!));
304
+ const manager = new ShardManager({ messageHandler: "v8", transformers: ["gzip", "aes"] });
305
+ ```
306
+
307
+ ## RFC alignment
308
+
309
+ | Source | Point | Here |
310
+ | -------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
311
+ | RFC | `ShardManager` with a strategy, by instance or name | `strategy` (instance or name) and `registerStrategy` |
312
+ | RFC | Worker, Fork (default), Cluster, Network strategies | `WorkerStrategy`, `ForkStrategy`, `ClusterStrategy`, `NetworkStrategy` |
313
+ | RFC | Manager configures the clients through the environment | `ShardContext` in `WOLFSTAR_SHARDER` (or worker data), `DISCORD_TOKEN` |
314
+ | RFC | Lifecycle events, invalid messages printed when unhandled | `shardCreate` … `shardInvalidMessage`, `console.error` fallbacks |
315
+ | RFC | Missing pings restart the shard when unhandled | `shardUnresponsive`, restart without listeners |
316
+ | RFC | Requests time out within the ping timeout, globally or per request | `requestTimeout` (defaults to `ping.timeout`), `timeout` per request |
317
+ | RFC | `ShardClient` signals: Starting, Ready, Exit, Restarting | `ShardStatus` (plus #7204's `Disconnected` and `Reconnecting`) |
318
+ | RFC | `registerMessageHandler` / `registerMessageTransformer` | `ShardClient.register*` and the module-level registries |
319
+ | RFC | JSON and V8 message handlers | `JsonMessageHandler`, `V8MessageHandler` (plus #7204's `RawMessageHandler`) |
320
+ | RFC | Composable transformers, reverse order when reading, Gzip and Brotli | `MessageTransformer` with its channel context, `GzipTransformer`, `BrotliTransformer` |
321
+ | RFC | `ShardManagerProxy` over an encrypted network, local routing | `ShardManagerProxy`, TLS, messages between its shards routed locally |
322
+ | RFC answers | Raw data, no `eval`; opt-in replies with timeouts; async transformers | Messages vs requests, `RequestOptions`, async `write`/`read` |
323
+ | RFC answers | Cancel requests, dequeue them, `AbortController` in shards | `signal`, dropped from the ready queue, `signal` in handlers |
324
+ | RFC answers | Partial results of aborted broadcasts | `broadcastRequest(body, { partial: true })` |
325
+ | RFC answers | Enqueue messages for shards not ready, with a ready-time hint | `waitForReady`, `spawn.readyHint` (or measured), early failure, `shardSlowStart` |
326
+ | RFC answers | `error` signal when a shard fails before ready | `shardError` with `ShardSpawnError` |
327
+ | RFC answers | Configurable restart limits, alerts, Erlang supervisors | `supervisor` intensity, period, strategy; `shardGiveUp` |
328
+ | RFC answers | Manager death: configurable, default die | `disconnect` event, exit without listeners; proxy `managerLoss` |
329
+ | RFC answers | Proxies: capacity, queue when full, failover managers, no rebalancing | `capacity` with `Load` reports, pending spawns, `managers` list, `reconnectGrace` |
330
+ | RFC answers | `Result<T, E>` instead of `try`/`catch` | `try*` methods, handlers returning a `Result`, `ShardError` |
331
+ | RFC answers | Proxies with several managers | `mode: "failover"` or `mode: "all"`, per-manager `token`, `tls`, and `id` |
332
+ | RFC | Proxies routing to shards they host, and to other proxies (P2P) | Local routing, `peer` connections, the manager's directory of ready shards |
333
+ | RFC answers | Optional built-in command layer | `createCommandHandler`, `command` |
334
+ | RFC answers | Identify processes and threads for observability | `channel.pid`, `threadId`, `host`; worker threads named `shard <id>` |
335
+ | #7204 | `totalShards`, `shardList`, `clusters` (CPU count), `"auto"` | Layout options |
336
+ | #7204 | Respawn budget that resets on ready | `supervisor` with `period: 0` |
337
+ | #7204 | Fetch `/gateway/bot` once in the manager and share it | `gatewayInformation`, `shard.fetchGatewayInformation()` |
338
+ | #7204 | `fetchRecommendedShards` with `guildsPerShard` and `multipleOf` | `fetchRecommendedShardCount`, `recommended` |
339
+ | #7204 | Ping with `delaySinceReceived` | `ping.delaySinceReceived` |
340
+ | #7204 / #8859 | Restart all shards, spawn delay after ready, spawn timeout then requeue | `restartAll`, `spawn.delay`, `spawn.timeout` |
341
+ | #8859 | Manager-side "channel" to each shard | `ShardChannel`, `manager.channels` |
342
+ | #8859 | Start, close, restart single gateway shards, from the manager or shards | `setShardHandler`, `startShard` & co., `shard.control()` |
343
+ | #8859 | Strategies with `init` and `destroy` | `ChannelStrategy.init` / `destroy` |
344
+ | #7204 comments | Cross-process identify pacing, minimal-downtime restarts and resharding | `identifyThrottler`, `restart(id, { rolling })`, `reshard()` |