@wolfstar/plugin-sharder 0.0.0
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/LICENSE +202 -0
- package/README.md +344 -0
- package/dist/esm/index.d.ts +2052 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +3491 -0
- package/dist/esm/index.js.map +1 -0
- package/package.json +57 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +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
|
+
[](https://npmx.dev/package/@wolfstar/plugin-sharder)
|
|
10
|
+
[](https://npmx.dev/package/@wolfstar/plugin-sharder)
|
|
11
|
+
[](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()` |
|