djshard 0.0.0-stage → 0.1.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/README.md +57 -2
- package/dist/index.cjs +418 -0
- package/dist/index.d.cts +147 -0
- package/dist/index.d.mts +147 -0
- package/dist/index.mjs +411 -0
- package/package.json +45 -4
package/README.md
CHANGED
|
@@ -1,3 +1,58 @@
|
|
|
1
|
-
#
|
|
1
|
+
# djshard
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Discord ボット向けのシャーディングライブラリ(Bun 用)。discord-hybrid-sharding(1 プロセスで複数シャード)と discord-cross-hosting(複数マシンへの分散)の機能をまとめたもので、Kubernetes 用のオペレーター(Go)も付いています。
|
|
4
|
+
|
|
5
|
+
## 単一マシンで使う
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// manager.ts
|
|
9
|
+
import { ClusterManager } from "djshard";
|
|
10
|
+
const manager = new ClusterManager("./bot.ts", { shardsPerCluster: 4 }); // totalShards: "auto" + DISCORD_TOKEN
|
|
11
|
+
await manager.spawn();
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
// bot.ts
|
|
16
|
+
import { Client } from "discord.js";
|
|
17
|
+
import { ClusterClient, getInfo } from "djshard";
|
|
18
|
+
const info = getInfo();
|
|
19
|
+
const client = new Client({ intents: [], shards: info.shards, shardCount: info.totalShards });
|
|
20
|
+
client.cluster = new ClusterClient(client);
|
|
21
|
+
await client.login();
|
|
22
|
+
|
|
23
|
+
const guilds = await client.cluster.broadcastEval((c) => c.guilds.cache.size); // 全クラスタ分
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## 複数マシンで使う(k8s なし)
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { Bridge } from "djshard";
|
|
30
|
+
await new Bridge({ port: 4444, auth: "secret", machines: 3, totalShards: "auto", token }).listen();
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
各マシンで `new ClusterManager("./bot.ts", { bridge: { url: "ws://bridge:4444", auth: "secret" } })` を起動します。`broadcastEval` は全マシンにまたがって実行されます。
|
|
34
|
+
|
|
35
|
+
## Kubernetes
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
kubectl apply -f operator/config/crd.yaml -f operator/config/operator.yaml
|
|
39
|
+
kubectl create secret generic discord --from-literal=token=...
|
|
40
|
+
kubectl apply -f operator/config/example.yaml
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
オペレーターは `ShardCluster` ごとに StatefulSet と認証用の Secret を作り、`DJSHARD_BRIDGE_URL` / `DJSHARD_AUTH` / `DJSHARD_ID` を最初のコンテナに注入します。`ClusterManager` はこれらの環境変数を自動で読み込みます。ブリッジはオペレーター本体の中で動き、Pod 名の序数(`mybot-2` → 2)でシャードを割り当てます。
|
|
44
|
+
|
|
45
|
+
## 制約
|
|
46
|
+
|
|
47
|
+
- オペレーターは 1 レプリカのみで動かしてください(接続はメモリ上で保持しています)。
|
|
48
|
+
- `replicas` / `totalShards` / `shardsPerCluster` を変更すると全 Pod がローリング再起動されます。再起動中は、同じシャードを新旧の Pod が一時的に重複して持つことがあります。
|
|
49
|
+
- ブリッジ通信は平文の ws です。認証トークンでしか保護していないため、クラスタ外へは公開しないでください。
|
|
50
|
+
- broadcastEval の戻り値は JSON にシリアライズできる値に限ります。
|
|
51
|
+
|
|
52
|
+
## 開発
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
bun run build # tsdown -> dist/
|
|
56
|
+
bun run ci # oxlint + oxfmt --check + bun check + bun test + build
|
|
57
|
+
cd operator && go test ./...
|
|
58
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let node_events = require("node:events");
|
|
3
|
+
let node_os = require("node:os");
|
|
4
|
+
let node_crypto = require("node:crypto");
|
|
5
|
+
// src/shared.ts
|
|
6
|
+
const toSource = (s) => typeof s === "function" ? s.toString() : s;
|
|
7
|
+
/** Correlates request ids with responses; one instance per connection. */
|
|
8
|
+
var Pending = class {
|
|
9
|
+
#next = 0;
|
|
10
|
+
#map = /* @__PURE__ */ new Map();
|
|
11
|
+
open(timeout = 3e4) {
|
|
12
|
+
const id = ++this.#next;
|
|
13
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
14
|
+
const timer = setTimeout(() => this.#map.delete(id) && reject(/* @__PURE__ */ new Error(`request ${id} timed out`)), timeout);
|
|
15
|
+
this.#map.set(id, {
|
|
16
|
+
resolve,
|
|
17
|
+
reject,
|
|
18
|
+
timer
|
|
19
|
+
});
|
|
20
|
+
return {
|
|
21
|
+
id,
|
|
22
|
+
promise
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
settle(m) {
|
|
26
|
+
const p = this.#map.get(m.id);
|
|
27
|
+
if (!p) return;
|
|
28
|
+
this.#map.delete(m.id);
|
|
29
|
+
clearTimeout(p.timer);
|
|
30
|
+
if (m.ok) p.resolve(m.data);
|
|
31
|
+
else p.reject(new Error(m.error));
|
|
32
|
+
}
|
|
33
|
+
rejectAll(reason) {
|
|
34
|
+
for (const p of this.#map.values()) {
|
|
35
|
+
clearTimeout(p.timer);
|
|
36
|
+
p.reject(new Error(reason));
|
|
37
|
+
}
|
|
38
|
+
this.#map.clear();
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/** Await `work` and send its outcome back as a `res` message. */
|
|
42
|
+
function respond(id, work, send) {
|
|
43
|
+
work().then((data) => send({
|
|
44
|
+
t: "res",
|
|
45
|
+
id,
|
|
46
|
+
ok: true,
|
|
47
|
+
data
|
|
48
|
+
}), (e) => send({
|
|
49
|
+
t: "res",
|
|
50
|
+
id,
|
|
51
|
+
ok: false,
|
|
52
|
+
error: String(e?.message ?? e)
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
55
|
+
function chunk(totalShards, shardsPerCluster) {
|
|
56
|
+
return Array.from({ length: Math.ceil(totalShards / shardsPerCluster) }, (_, c) => Array.from({ length: Math.min(shardsPerCluster, totalShards - c * shardsPerCluster) }, (_, i) => c * shardsPerCluster + i));
|
|
57
|
+
}
|
|
58
|
+
/** Clusters for machine `slot` out of `machines`. Mirrors assignment() in operator/bridge.go. */
|
|
59
|
+
function assignment(totalShards, shardsPerCluster, machines, slot) {
|
|
60
|
+
const all = chunk(totalShards, shardsPerCluster);
|
|
61
|
+
const per = Math.ceil(all.length / machines);
|
|
62
|
+
const clusters = all.slice(slot * per, slot * per + per).map((shards, i) => ({
|
|
63
|
+
id: slot * per + i,
|
|
64
|
+
shards
|
|
65
|
+
}));
|
|
66
|
+
return {
|
|
67
|
+
t: "assign",
|
|
68
|
+
totalShards,
|
|
69
|
+
totalClusters: all.length,
|
|
70
|
+
clusters
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
async function fetchRecommendedShards(token) {
|
|
74
|
+
const res = await fetch("https://discord.com/api/v10/gateway/bot", { headers: { Authorization: `Bot ${token}` } });
|
|
75
|
+
if (!res.ok) throw new Error(`GET /gateway/bot failed: ${res.status}`);
|
|
76
|
+
return (await res.json()).shards;
|
|
77
|
+
}
|
|
78
|
+
const safeEqual = (a, b) => {
|
|
79
|
+
const x = Buffer.from(a), y = Buffer.from(b);
|
|
80
|
+
return x.length === y.length && (0, node_crypto.timingSafeEqual)(x, y);
|
|
81
|
+
};
|
|
82
|
+
// src/manager.ts
|
|
83
|
+
/**
|
|
84
|
+
* Spawns one process per cluster, each running several shards.
|
|
85
|
+
* Events: "spawn" (clusterId), "exit" (clusterId, code), "debug" (message).
|
|
86
|
+
*/
|
|
87
|
+
var ClusterManager = class extends node_events.EventEmitter {
|
|
88
|
+
file;
|
|
89
|
+
clusters = /* @__PURE__ */ new Map();
|
|
90
|
+
totalShards = 0;
|
|
91
|
+
totalClusters = 0;
|
|
92
|
+
#opts;
|
|
93
|
+
#bridge;
|
|
94
|
+
#ws;
|
|
95
|
+
#online = false;
|
|
96
|
+
#wsPending = new Pending();
|
|
97
|
+
#assignKey = "";
|
|
98
|
+
#queue = Promise.resolve();
|
|
99
|
+
#closed = false;
|
|
100
|
+
constructor(file, opts = {}) {
|
|
101
|
+
super();
|
|
102
|
+
this.file = file;
|
|
103
|
+
const env = process.env;
|
|
104
|
+
this.#opts = {
|
|
105
|
+
totalShards: "auto",
|
|
106
|
+
shardsPerCluster: 4,
|
|
107
|
+
token: env.DISCORD_TOKEN,
|
|
108
|
+
spawnDelay: 5500,
|
|
109
|
+
respawn: true,
|
|
110
|
+
...opts
|
|
111
|
+
};
|
|
112
|
+
const url = opts.bridge?.url ?? env.DJSHARD_BRIDGE_URL;
|
|
113
|
+
this.#bridge = url ? {
|
|
114
|
+
url,
|
|
115
|
+
auth: opts.bridge?.auth ?? env.DJSHARD_AUTH ?? "",
|
|
116
|
+
id: opts.bridge?.id ?? env.DJSHARD_ID ?? (0, node_os.hostname)()
|
|
117
|
+
} : void 0;
|
|
118
|
+
}
|
|
119
|
+
/** Resolves once the first set of clusters has been spawned. */
|
|
120
|
+
async spawn() {
|
|
121
|
+
if (this.#bridge) {
|
|
122
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
123
|
+
this.once("assigned", resolve);
|
|
124
|
+
this.once("rejected", reject);
|
|
125
|
+
this.#connect();
|
|
126
|
+
return promise;
|
|
127
|
+
}
|
|
128
|
+
const { shardsPerCluster, token } = this.#opts;
|
|
129
|
+
let total = this.#opts.totalShards;
|
|
130
|
+
if (total === "auto") {
|
|
131
|
+
if (!token) throw new Error("totalShards \"auto\" needs a token");
|
|
132
|
+
total = await fetchRecommendedShards(token);
|
|
133
|
+
}
|
|
134
|
+
const clusters = chunk(total, shardsPerCluster).map((shards, id) => ({
|
|
135
|
+
id,
|
|
136
|
+
shards
|
|
137
|
+
}));
|
|
138
|
+
return this.#apply({
|
|
139
|
+
t: "assign",
|
|
140
|
+
totalShards: total,
|
|
141
|
+
totalClusters: clusters.length,
|
|
142
|
+
clusters
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
/** Runs `script` on every cluster (across all machines when bridged). */
|
|
146
|
+
broadcastEval(script, opts = {}) {
|
|
147
|
+
const source = toSource(script);
|
|
148
|
+
if (!this.#bridge) return this.evalLocal(source, opts);
|
|
149
|
+
if (!this.#online) return Promise.reject(/* @__PURE__ */ new Error("bridge not connected"));
|
|
150
|
+
const { id, promise } = this.#wsPending.open(opts.timeout);
|
|
151
|
+
this.#send({
|
|
152
|
+
t: "eval",
|
|
153
|
+
id,
|
|
154
|
+
script: source,
|
|
155
|
+
context: opts.context,
|
|
156
|
+
cluster: opts.cluster
|
|
157
|
+
});
|
|
158
|
+
return promise;
|
|
159
|
+
}
|
|
160
|
+
/** Runs `script` on this machine's clusters only. */
|
|
161
|
+
evalLocal(script, { context, cluster, timeout } = {}) {
|
|
162
|
+
const targets = [...this.clusters.values()].filter((c) => cluster === void 0 || c.id === cluster);
|
|
163
|
+
return Promise.all(targets.map((c) => {
|
|
164
|
+
if (!c.proc || c.proc.killed) return Promise.reject(/* @__PURE__ */ new Error(`cluster ${c.id} is not running`));
|
|
165
|
+
const { id, promise } = c.pending.open(timeout);
|
|
166
|
+
c.proc.send({
|
|
167
|
+
t: "eval",
|
|
168
|
+
id,
|
|
169
|
+
script,
|
|
170
|
+
context
|
|
171
|
+
});
|
|
172
|
+
return promise;
|
|
173
|
+
}));
|
|
174
|
+
}
|
|
175
|
+
/** Kills every cluster in order and spawns them again. */
|
|
176
|
+
respawnAll() {
|
|
177
|
+
const clusters = [...this.clusters.values()].map(({ id, shards }) => ({
|
|
178
|
+
id,
|
|
179
|
+
shards
|
|
180
|
+
}));
|
|
181
|
+
return this.#apply({
|
|
182
|
+
t: "assign",
|
|
183
|
+
totalShards: this.totalShards,
|
|
184
|
+
totalClusters: this.totalClusters,
|
|
185
|
+
clusters
|
|
186
|
+
}, true);
|
|
187
|
+
}
|
|
188
|
+
destroy() {
|
|
189
|
+
this.#closed = true;
|
|
190
|
+
this.#ws?.close();
|
|
191
|
+
for (const c of this.clusters.values()) this.#stop(c);
|
|
192
|
+
}
|
|
193
|
+
#apply(a, force = false) {
|
|
194
|
+
return this.#queue = this.#queue.then(async () => {
|
|
195
|
+
const key = JSON.stringify(a);
|
|
196
|
+
if (key === this.#assignKey && !force) return;
|
|
197
|
+
this.#assignKey = key;
|
|
198
|
+
for (const c of this.clusters.values()) this.#stop(c);
|
|
199
|
+
this.clusters.clear();
|
|
200
|
+
this.totalShards = a.totalShards;
|
|
201
|
+
this.totalClusters = a.totalClusters;
|
|
202
|
+
for (const [i, { id, shards }] of a.clusters.entries()) {
|
|
203
|
+
if (this.#closed) return;
|
|
204
|
+
if (i > 0) await Bun.sleep(this.#opts.spawnDelay);
|
|
205
|
+
const c = {
|
|
206
|
+
id,
|
|
207
|
+
shards,
|
|
208
|
+
pending: new Pending(),
|
|
209
|
+
stopped: false
|
|
210
|
+
};
|
|
211
|
+
this.clusters.set(id, c);
|
|
212
|
+
this.#start(c);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
#start(c) {
|
|
217
|
+
const info = {
|
|
218
|
+
id: c.id,
|
|
219
|
+
shards: c.shards,
|
|
220
|
+
totalShards: this.totalShards,
|
|
221
|
+
totalClusters: this.totalClusters
|
|
222
|
+
};
|
|
223
|
+
c.proc = Bun.spawn([process.execPath, this.file], {
|
|
224
|
+
env: {
|
|
225
|
+
...process.env,
|
|
226
|
+
DJSHARD_CLUSTER: JSON.stringify(info)
|
|
227
|
+
},
|
|
228
|
+
stdio: [
|
|
229
|
+
"inherit",
|
|
230
|
+
"inherit",
|
|
231
|
+
"inherit"
|
|
232
|
+
],
|
|
233
|
+
ipc: (m) => {
|
|
234
|
+
if (m.t === "res") c.pending.settle(m);
|
|
235
|
+
else if (m.t === "eval") respond(m.id, () => this.broadcastEval(m.script, m), (r) => c.proc?.send(r));
|
|
236
|
+
},
|
|
237
|
+
onExit: (_, code) => {
|
|
238
|
+
c.pending.rejectAll(`cluster ${c.id} exited`);
|
|
239
|
+
this.emit("exit", c.id, code);
|
|
240
|
+
if (!c.stopped && !this.#closed && this.#opts.respawn) setTimeout(() => c.stopped || this.#start(c), 5e3);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
this.emit("spawn", c.id);
|
|
244
|
+
}
|
|
245
|
+
#stop(c) {
|
|
246
|
+
c.stopped = true;
|
|
247
|
+
c.proc?.kill();
|
|
248
|
+
}
|
|
249
|
+
#send(m) {
|
|
250
|
+
this.#ws?.send(JSON.stringify(m));
|
|
251
|
+
}
|
|
252
|
+
#connect() {
|
|
253
|
+
const b = this.#bridge;
|
|
254
|
+
const ws = this.#ws = new WebSocket(b.url);
|
|
255
|
+
ws.onopen = () => this.#send({
|
|
256
|
+
t: "hello",
|
|
257
|
+
auth: b.auth,
|
|
258
|
+
name: b.id
|
|
259
|
+
});
|
|
260
|
+
ws.onmessage = (e) => this.#onBridge(JSON.parse(String(e.data)));
|
|
261
|
+
ws.onclose = () => {
|
|
262
|
+
this.#online = false;
|
|
263
|
+
this.#wsPending.rejectAll("bridge disconnected");
|
|
264
|
+
this.emit("debug", "bridge disconnected");
|
|
265
|
+
if (!this.#closed) setTimeout(() => this.#connect(), 5e3);
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
#onBridge(m) {
|
|
269
|
+
switch (m.t) {
|
|
270
|
+
case "assign":
|
|
271
|
+
this.#online = true;
|
|
272
|
+
this.#apply(m).then(() => this.emit("assigned"));
|
|
273
|
+
break;
|
|
274
|
+
case "eval":
|
|
275
|
+
respond(m.id, () => this.evalLocal(m.script, m), (r) => this.#send(r));
|
|
276
|
+
break;
|
|
277
|
+
case "res":
|
|
278
|
+
this.#wsPending.settle(m);
|
|
279
|
+
break;
|
|
280
|
+
case "error":
|
|
281
|
+
this.emit("debug", `bridge: ${m.message}`);
|
|
282
|
+
this.emit("rejected", new Error(m.message));
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
// src/client.ts
|
|
287
|
+
/** Cluster info injected by ClusterManager. Throws outside a managed cluster process. */
|
|
288
|
+
function getInfo() {
|
|
289
|
+
const raw = process.env.DJSHARD_CLUSTER;
|
|
290
|
+
if (!raw) throw new Error("not running inside a djshard cluster");
|
|
291
|
+
return JSON.parse(raw);
|
|
292
|
+
}
|
|
293
|
+
/** Runs inside a cluster process. `client` is what broadcastEval scripts receive. */
|
|
294
|
+
var ClusterClient = class {
|
|
295
|
+
client;
|
|
296
|
+
info = getInfo();
|
|
297
|
+
#pending = new Pending();
|
|
298
|
+
constructor(client) {
|
|
299
|
+
this.client = client;
|
|
300
|
+
process.on("message", (m) => {
|
|
301
|
+
if (m.t === "res") this.#pending.settle(m);
|
|
302
|
+
else if (m.t === "eval") respond(m.id, async () => evaluate(m.script, this.client, m.context), (r) => process.send(r));
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
get id() {
|
|
306
|
+
return this.info.id;
|
|
307
|
+
}
|
|
308
|
+
/** Runs `script` on every cluster across every machine; results ordered by cluster. */
|
|
309
|
+
broadcastEval(script, opts = {}) {
|
|
310
|
+
const { id, promise } = this.#pending.open(opts.timeout);
|
|
311
|
+
process.send({
|
|
312
|
+
t: "eval",
|
|
313
|
+
id,
|
|
314
|
+
script: toSource(script),
|
|
315
|
+
context: opts.context,
|
|
316
|
+
cluster: opts.cluster
|
|
317
|
+
});
|
|
318
|
+
return promise;
|
|
319
|
+
}
|
|
320
|
+
/** e.g. fetchClientValues("guilds.cache.size") */
|
|
321
|
+
fetchClientValues(path) {
|
|
322
|
+
return this.broadcastEval((c, p) => p.split(".").reduce((o, k) => o?.[k], c), { context: path });
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
function evaluate(script, client, context) {
|
|
326
|
+
return new Function("client", "context", `return (${script})(client, context)`)(client, context);
|
|
327
|
+
}
|
|
328
|
+
// src/bridge.ts
|
|
329
|
+
/** Hands out shard ranges to ClusterManagers on several hosts and routes cross-host broadcastEval. */
|
|
330
|
+
var Bridge = class {
|
|
331
|
+
opts;
|
|
332
|
+
totalShards = 0;
|
|
333
|
+
#slots;
|
|
334
|
+
#sticky = /* @__PURE__ */ new Map();
|
|
335
|
+
#server;
|
|
336
|
+
constructor(opts) {
|
|
337
|
+
this.opts = opts;
|
|
338
|
+
this.#slots = Array(opts.machines).fill(void 0);
|
|
339
|
+
}
|
|
340
|
+
/** Starts listening; returns the bound port. */
|
|
341
|
+
async listen() {
|
|
342
|
+
const { totalShards, token } = this.opts;
|
|
343
|
+
if (totalShards === "auto" && !token) throw new Error("totalShards \"auto\" needs a token");
|
|
344
|
+
this.totalShards = totalShards === "auto" ? await fetchRecommendedShards(token) : totalShards;
|
|
345
|
+
this.#server = Bun.serve({
|
|
346
|
+
port: this.opts.port ?? 4444,
|
|
347
|
+
fetch: (req, server) => server.upgrade(req, { data: {
|
|
348
|
+
id: "",
|
|
349
|
+
slot: -1,
|
|
350
|
+
pending: new Pending()
|
|
351
|
+
} }) ? void 0 : new Response("djshard bridge", { status: 426 }),
|
|
352
|
+
websocket: {
|
|
353
|
+
message: (ws, raw) => {
|
|
354
|
+
let m;
|
|
355
|
+
try {
|
|
356
|
+
m = JSON.parse(String(raw));
|
|
357
|
+
} catch {
|
|
358
|
+
return ws.close(1003, "bad json");
|
|
359
|
+
}
|
|
360
|
+
this.#onMessage(ws, m);
|
|
361
|
+
},
|
|
362
|
+
close: (ws) => {
|
|
363
|
+
if (this.#slots[ws.data.slot] === ws) this.#slots[ws.data.slot] = void 0;
|
|
364
|
+
ws.data.pending.rejectAll(`machine ${ws.data.id} disconnected`);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
return this.#server.port;
|
|
369
|
+
}
|
|
370
|
+
/** Runs `script` on every cluster of every connected machine. */
|
|
371
|
+
async broadcastEval(script, opts = {}) {
|
|
372
|
+
return (await Promise.all(this.#slots.filter((ws) => ws !== void 0).map((ws) => {
|
|
373
|
+
const { id, promise } = ws.data.pending.open(opts.timeout);
|
|
374
|
+
send(ws, {
|
|
375
|
+
t: "eval",
|
|
376
|
+
id,
|
|
377
|
+
script: toSource(script),
|
|
378
|
+
context: opts.context,
|
|
379
|
+
cluster: opts.cluster
|
|
380
|
+
});
|
|
381
|
+
return promise;
|
|
382
|
+
}))).flat();
|
|
383
|
+
}
|
|
384
|
+
close() {
|
|
385
|
+
this.#server?.stop(true);
|
|
386
|
+
}
|
|
387
|
+
#onMessage(ws, m) {
|
|
388
|
+
if (ws.data.slot < 0) {
|
|
389
|
+
if (m.t !== "hello" || typeof m.auth !== "string" || !safeEqual(m.auth, this.opts.auth)) return ws.close(1008, "unauthorized");
|
|
390
|
+
const prev = this.#sticky.get(m.name);
|
|
391
|
+
const slot = prev !== void 0 && !this.#slots[prev] ? prev : this.#slots.findIndex((s) => !s);
|
|
392
|
+
if (slot < 0) {
|
|
393
|
+
send(ws, {
|
|
394
|
+
t: "error",
|
|
395
|
+
message: "no free machine slot"
|
|
396
|
+
});
|
|
397
|
+
return ws.close(1008, "full");
|
|
398
|
+
}
|
|
399
|
+
Object.assign(ws.data, {
|
|
400
|
+
id: String(m.name),
|
|
401
|
+
slot
|
|
402
|
+
});
|
|
403
|
+
this.#slots[slot] = ws;
|
|
404
|
+
this.#sticky.set(ws.data.id, slot);
|
|
405
|
+
return send(ws, assignment(this.totalShards, this.opts.shardsPerCluster ?? 4, this.opts.machines, slot));
|
|
406
|
+
}
|
|
407
|
+
if (m.t === "eval") respond(m.id, () => this.broadcastEval(m.script, m), (r) => send(ws, r));
|
|
408
|
+
else if (m.t === "res") ws.data.pending.settle(m);
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
const send = (ws, m) => ws.send(JSON.stringify(m));
|
|
412
|
+
exports.Bridge = Bridge;
|
|
413
|
+
exports.ClusterClient = ClusterClient;
|
|
414
|
+
exports.ClusterManager = ClusterManager;
|
|
415
|
+
exports.assignment = assignment;
|
|
416
|
+
exports.chunk = chunk;
|
|
417
|
+
exports.fetchRecommendedShards = fetchRecommendedShards;
|
|
418
|
+
exports.getInfo = getInfo;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { Subprocess } from "bun";
|
|
3
|
+
type Msg = {
|
|
4
|
+
t: "hello";
|
|
5
|
+
auth: string;
|
|
6
|
+
name: string;
|
|
7
|
+
} | {
|
|
8
|
+
t: "assign";
|
|
9
|
+
totalShards: number;
|
|
10
|
+
totalClusters: number;
|
|
11
|
+
clusters: {
|
|
12
|
+
id: number;
|
|
13
|
+
shards: number[];
|
|
14
|
+
}[];
|
|
15
|
+
} | {
|
|
16
|
+
t: "eval";
|
|
17
|
+
id: number;
|
|
18
|
+
script: string;
|
|
19
|
+
context?: unknown;
|
|
20
|
+
cluster?: number;
|
|
21
|
+
} | {
|
|
22
|
+
t: "res";
|
|
23
|
+
id: number;
|
|
24
|
+
ok: boolean;
|
|
25
|
+
data?: unknown;
|
|
26
|
+
error?: string;
|
|
27
|
+
} | {
|
|
28
|
+
t: "error";
|
|
29
|
+
message: string;
|
|
30
|
+
};
|
|
31
|
+
type Assign = Extract<Msg, {
|
|
32
|
+
t: "assign";
|
|
33
|
+
}>;
|
|
34
|
+
type Script<C = any, X = any, R = unknown> = string | ((client: C, context: X) => R);
|
|
35
|
+
interface EvalOptions {
|
|
36
|
+
context?: unknown;
|
|
37
|
+
/** Only run on this cluster id. */
|
|
38
|
+
cluster?: number;
|
|
39
|
+
timeout?: number;
|
|
40
|
+
}
|
|
41
|
+
/** Correlates request ids with responses; one instance per connection. */
|
|
42
|
+
declare class Pending {
|
|
43
|
+
#private;
|
|
44
|
+
open(timeout?: number): {
|
|
45
|
+
id: number;
|
|
46
|
+
promise: Promise<any>;
|
|
47
|
+
};
|
|
48
|
+
settle(m: Extract<Msg, {
|
|
49
|
+
t: "res";
|
|
50
|
+
}>): void;
|
|
51
|
+
rejectAll(reason: string): void;
|
|
52
|
+
}
|
|
53
|
+
export declare function chunk(totalShards: number, shardsPerCluster: number): number[][];
|
|
54
|
+
/** Clusters for machine `slot` out of `machines`. Mirrors assignment() in operator/bridge.go. */
|
|
55
|
+
export declare function assignment(totalShards: number, shardsPerCluster: number, machines: number, slot: number): Assign;
|
|
56
|
+
export declare function fetchRecommendedShards(token: string): Promise<number>;
|
|
57
|
+
interface ManagerOptions {
|
|
58
|
+
/** Ignored when a bridge is used (the bridge decides). Default "auto". */
|
|
59
|
+
totalShards?: number | "auto";
|
|
60
|
+
shardsPerCluster?: number;
|
|
61
|
+
/** Needed for totalShards "auto". Default DISCORD_TOKEN. */
|
|
62
|
+
token?: string;
|
|
63
|
+
/** Delay between cluster spawns, for identify rate limits. */
|
|
64
|
+
spawnDelay?: number;
|
|
65
|
+
respawn?: boolean;
|
|
66
|
+
/** Cross-host mode. Defaults from DJSHARD_BRIDGE_URL / DJSHARD_AUTH / DJSHARD_ID (set by the k8s operator). */
|
|
67
|
+
bridge?: {
|
|
68
|
+
url: string;
|
|
69
|
+
auth: string;
|
|
70
|
+
id?: string;
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
interface Cluster {
|
|
74
|
+
id: number;
|
|
75
|
+
shards: number[];
|
|
76
|
+
proc?: Subprocess;
|
|
77
|
+
pending: Pending;
|
|
78
|
+
stopped: boolean;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Spawns one process per cluster, each running several shards.
|
|
82
|
+
* Events: "spawn" (clusterId), "exit" (clusterId, code), "debug" (message).
|
|
83
|
+
*/
|
|
84
|
+
export declare class ClusterManager extends EventEmitter {
|
|
85
|
+
#private;
|
|
86
|
+
readonly file: string;
|
|
87
|
+
readonly clusters: Map<number, Cluster>;
|
|
88
|
+
totalShards: number;
|
|
89
|
+
totalClusters: number;
|
|
90
|
+
constructor(file: string, opts?: ManagerOptions);
|
|
91
|
+
/** Resolves once the first set of clusters has been spawned. */
|
|
92
|
+
spawn(): Promise<void>;
|
|
93
|
+
/** Runs `script` on every cluster (across all machines when bridged). */
|
|
94
|
+
broadcastEval<R>(script: Script<any, any, R>, opts?: EvalOptions): Promise<Awaited<R>[]>;
|
|
95
|
+
/** Runs `script` on this machine's clusters only. */
|
|
96
|
+
evalLocal(script: string, { context, cluster, timeout }?: EvalOptions): Promise<any[]>;
|
|
97
|
+
/** Kills every cluster in order and spawns them again. */
|
|
98
|
+
respawnAll(): Promise<void>;
|
|
99
|
+
destroy(): void;
|
|
100
|
+
}
|
|
101
|
+
interface ClusterInfo {
|
|
102
|
+
id: number;
|
|
103
|
+
/** Pass to your Discord client as `shards`. */
|
|
104
|
+
shards: number[];
|
|
105
|
+
/** Pass to your Discord client as `shardCount`. */
|
|
106
|
+
totalShards: number;
|
|
107
|
+
totalClusters: number;
|
|
108
|
+
}
|
|
109
|
+
/** Cluster info injected by ClusterManager. Throws outside a managed cluster process. */
|
|
110
|
+
export declare function getInfo(): ClusterInfo;
|
|
111
|
+
/** Runs inside a cluster process. `client` is what broadcastEval scripts receive. */
|
|
112
|
+
export declare class ClusterClient<C = unknown> {
|
|
113
|
+
#private;
|
|
114
|
+
readonly client: C;
|
|
115
|
+
readonly info: ClusterInfo;
|
|
116
|
+
constructor(client: C);
|
|
117
|
+
get id(): number;
|
|
118
|
+
/** Runs `script` on every cluster across every machine; results ordered by cluster. */
|
|
119
|
+
broadcastEval<R, X = undefined>(script: Script<C, X, R>, opts?: EvalOptions & {
|
|
120
|
+
context?: X;
|
|
121
|
+
}): Promise<Awaited<R>[]>;
|
|
122
|
+
/** e.g. fetchClientValues("guilds.cache.size") */
|
|
123
|
+
fetchClientValues(path: string): Promise<unknown[]>;
|
|
124
|
+
}
|
|
125
|
+
interface BridgeOptions {
|
|
126
|
+
port?: number;
|
|
127
|
+
/** Shared secret every machine must present. */
|
|
128
|
+
auth: string;
|
|
129
|
+
/** Number of machines the clusters are split across. */
|
|
130
|
+
machines: number;
|
|
131
|
+
totalShards: number | "auto";
|
|
132
|
+
shardsPerCluster?: number;
|
|
133
|
+
token?: string;
|
|
134
|
+
}
|
|
135
|
+
/** Hands out shard ranges to ClusterManagers on several hosts and routes cross-host broadcastEval. */
|
|
136
|
+
export declare class Bridge {
|
|
137
|
+
#private;
|
|
138
|
+
readonly opts: BridgeOptions;
|
|
139
|
+
totalShards: number;
|
|
140
|
+
constructor(opts: BridgeOptions);
|
|
141
|
+
/** Starts listening; returns the bound port. */
|
|
142
|
+
listen(): Promise<number>;
|
|
143
|
+
/** Runs `script` on every cluster of every connected machine. */
|
|
144
|
+
broadcastEval<R>(script: Script<any, any, R>, opts?: EvalOptions): Promise<Awaited<R>[]>;
|
|
145
|
+
close(): void;
|
|
146
|
+
}
|
|
147
|
+
export type { BridgeOptions, ClusterInfo, EvalOptions, ManagerOptions, Script };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { Subprocess } from "bun";
|
|
3
|
+
type Msg = {
|
|
4
|
+
t: "hello";
|
|
5
|
+
auth: string;
|
|
6
|
+
name: string;
|
|
7
|
+
} | {
|
|
8
|
+
t: "assign";
|
|
9
|
+
totalShards: number;
|
|
10
|
+
totalClusters: number;
|
|
11
|
+
clusters: {
|
|
12
|
+
id: number;
|
|
13
|
+
shards: number[];
|
|
14
|
+
}[];
|
|
15
|
+
} | {
|
|
16
|
+
t: "eval";
|
|
17
|
+
id: number;
|
|
18
|
+
script: string;
|
|
19
|
+
context?: unknown;
|
|
20
|
+
cluster?: number;
|
|
21
|
+
} | {
|
|
22
|
+
t: "res";
|
|
23
|
+
id: number;
|
|
24
|
+
ok: boolean;
|
|
25
|
+
data?: unknown;
|
|
26
|
+
error?: string;
|
|
27
|
+
} | {
|
|
28
|
+
t: "error";
|
|
29
|
+
message: string;
|
|
30
|
+
};
|
|
31
|
+
type Assign = Extract<Msg, {
|
|
32
|
+
t: "assign";
|
|
33
|
+
}>;
|
|
34
|
+
type Script<C = any, X = any, R = unknown> = string | ((client: C, context: X) => R);
|
|
35
|
+
interface EvalOptions {
|
|
36
|
+
context?: unknown;
|
|
37
|
+
/** Only run on this cluster id. */
|
|
38
|
+
cluster?: number;
|
|
39
|
+
timeout?: number;
|
|
40
|
+
}
|
|
41
|
+
/** Correlates request ids with responses; one instance per connection. */
|
|
42
|
+
declare class Pending {
|
|
43
|
+
#private;
|
|
44
|
+
open(timeout?: number): {
|
|
45
|
+
id: number;
|
|
46
|
+
promise: Promise<any>;
|
|
47
|
+
};
|
|
48
|
+
settle(m: Extract<Msg, {
|
|
49
|
+
t: "res";
|
|
50
|
+
}>): void;
|
|
51
|
+
rejectAll(reason: string): void;
|
|
52
|
+
}
|
|
53
|
+
export declare function chunk(totalShards: number, shardsPerCluster: number): number[][];
|
|
54
|
+
/** Clusters for machine `slot` out of `machines`. Mirrors assignment() in operator/bridge.go. */
|
|
55
|
+
export declare function assignment(totalShards: number, shardsPerCluster: number, machines: number, slot: number): Assign;
|
|
56
|
+
export declare function fetchRecommendedShards(token: string): Promise<number>;
|
|
57
|
+
interface ManagerOptions {
|
|
58
|
+
/** Ignored when a bridge is used (the bridge decides). Default "auto". */
|
|
59
|
+
totalShards?: number | "auto";
|
|
60
|
+
shardsPerCluster?: number;
|
|
61
|
+
/** Needed for totalShards "auto". Default DISCORD_TOKEN. */
|
|
62
|
+
token?: string;
|
|
63
|
+
/** Delay between cluster spawns, for identify rate limits. */
|
|
64
|
+
spawnDelay?: number;
|
|
65
|
+
respawn?: boolean;
|
|
66
|
+
/** Cross-host mode. Defaults from DJSHARD_BRIDGE_URL / DJSHARD_AUTH / DJSHARD_ID (set by the k8s operator). */
|
|
67
|
+
bridge?: {
|
|
68
|
+
url: string;
|
|
69
|
+
auth: string;
|
|
70
|
+
id?: string;
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
interface Cluster {
|
|
74
|
+
id: number;
|
|
75
|
+
shards: number[];
|
|
76
|
+
proc?: Subprocess;
|
|
77
|
+
pending: Pending;
|
|
78
|
+
stopped: boolean;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Spawns one process per cluster, each running several shards.
|
|
82
|
+
* Events: "spawn" (clusterId), "exit" (clusterId, code), "debug" (message).
|
|
83
|
+
*/
|
|
84
|
+
export declare class ClusterManager extends EventEmitter {
|
|
85
|
+
#private;
|
|
86
|
+
readonly file: string;
|
|
87
|
+
readonly clusters: Map<number, Cluster>;
|
|
88
|
+
totalShards: number;
|
|
89
|
+
totalClusters: number;
|
|
90
|
+
constructor(file: string, opts?: ManagerOptions);
|
|
91
|
+
/** Resolves once the first set of clusters has been spawned. */
|
|
92
|
+
spawn(): Promise<void>;
|
|
93
|
+
/** Runs `script` on every cluster (across all machines when bridged). */
|
|
94
|
+
broadcastEval<R>(script: Script<any, any, R>, opts?: EvalOptions): Promise<Awaited<R>[]>;
|
|
95
|
+
/** Runs `script` on this machine's clusters only. */
|
|
96
|
+
evalLocal(script: string, { context, cluster, timeout }?: EvalOptions): Promise<any[]>;
|
|
97
|
+
/** Kills every cluster in order and spawns them again. */
|
|
98
|
+
respawnAll(): Promise<void>;
|
|
99
|
+
destroy(): void;
|
|
100
|
+
}
|
|
101
|
+
interface ClusterInfo {
|
|
102
|
+
id: number;
|
|
103
|
+
/** Pass to your Discord client as `shards`. */
|
|
104
|
+
shards: number[];
|
|
105
|
+
/** Pass to your Discord client as `shardCount`. */
|
|
106
|
+
totalShards: number;
|
|
107
|
+
totalClusters: number;
|
|
108
|
+
}
|
|
109
|
+
/** Cluster info injected by ClusterManager. Throws outside a managed cluster process. */
|
|
110
|
+
export declare function getInfo(): ClusterInfo;
|
|
111
|
+
/** Runs inside a cluster process. `client` is what broadcastEval scripts receive. */
|
|
112
|
+
export declare class ClusterClient<C = unknown> {
|
|
113
|
+
#private;
|
|
114
|
+
readonly client: C;
|
|
115
|
+
readonly info: ClusterInfo;
|
|
116
|
+
constructor(client: C);
|
|
117
|
+
get id(): number;
|
|
118
|
+
/** Runs `script` on every cluster across every machine; results ordered by cluster. */
|
|
119
|
+
broadcastEval<R, X = undefined>(script: Script<C, X, R>, opts?: EvalOptions & {
|
|
120
|
+
context?: X;
|
|
121
|
+
}): Promise<Awaited<R>[]>;
|
|
122
|
+
/** e.g. fetchClientValues("guilds.cache.size") */
|
|
123
|
+
fetchClientValues(path: string): Promise<unknown[]>;
|
|
124
|
+
}
|
|
125
|
+
interface BridgeOptions {
|
|
126
|
+
port?: number;
|
|
127
|
+
/** Shared secret every machine must present. */
|
|
128
|
+
auth: string;
|
|
129
|
+
/** Number of machines the clusters are split across. */
|
|
130
|
+
machines: number;
|
|
131
|
+
totalShards: number | "auto";
|
|
132
|
+
shardsPerCluster?: number;
|
|
133
|
+
token?: string;
|
|
134
|
+
}
|
|
135
|
+
/** Hands out shard ranges to ClusterManagers on several hosts and routes cross-host broadcastEval. */
|
|
136
|
+
export declare class Bridge {
|
|
137
|
+
#private;
|
|
138
|
+
readonly opts: BridgeOptions;
|
|
139
|
+
totalShards: number;
|
|
140
|
+
constructor(opts: BridgeOptions);
|
|
141
|
+
/** Starts listening; returns the bound port. */
|
|
142
|
+
listen(): Promise<number>;
|
|
143
|
+
/** Runs `script` on every cluster of every connected machine. */
|
|
144
|
+
broadcastEval<R>(script: Script<any, any, R>, opts?: EvalOptions): Promise<Awaited<R>[]>;
|
|
145
|
+
close(): void;
|
|
146
|
+
}
|
|
147
|
+
export type { BridgeOptions, ClusterInfo, EvalOptions, ManagerOptions, Script };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { hostname } from "node:os";
|
|
3
|
+
import { timingSafeEqual } from "node:crypto";
|
|
4
|
+
// src/shared.ts
|
|
5
|
+
const toSource = (s) => typeof s === "function" ? s.toString() : s;
|
|
6
|
+
/** Correlates request ids with responses; one instance per connection. */
|
|
7
|
+
var Pending = class {
|
|
8
|
+
#next = 0;
|
|
9
|
+
#map = /* @__PURE__ */ new Map();
|
|
10
|
+
open(timeout = 3e4) {
|
|
11
|
+
const id = ++this.#next;
|
|
12
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
13
|
+
const timer = setTimeout(() => this.#map.delete(id) && reject(/* @__PURE__ */ new Error(`request ${id} timed out`)), timeout);
|
|
14
|
+
this.#map.set(id, {
|
|
15
|
+
resolve,
|
|
16
|
+
reject,
|
|
17
|
+
timer
|
|
18
|
+
});
|
|
19
|
+
return {
|
|
20
|
+
id,
|
|
21
|
+
promise
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
settle(m) {
|
|
25
|
+
const p = this.#map.get(m.id);
|
|
26
|
+
if (!p) return;
|
|
27
|
+
this.#map.delete(m.id);
|
|
28
|
+
clearTimeout(p.timer);
|
|
29
|
+
if (m.ok) p.resolve(m.data);
|
|
30
|
+
else p.reject(new Error(m.error));
|
|
31
|
+
}
|
|
32
|
+
rejectAll(reason) {
|
|
33
|
+
for (const p of this.#map.values()) {
|
|
34
|
+
clearTimeout(p.timer);
|
|
35
|
+
p.reject(new Error(reason));
|
|
36
|
+
}
|
|
37
|
+
this.#map.clear();
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/** Await `work` and send its outcome back as a `res` message. */
|
|
41
|
+
function respond(id, work, send) {
|
|
42
|
+
work().then((data) => send({
|
|
43
|
+
t: "res",
|
|
44
|
+
id,
|
|
45
|
+
ok: true,
|
|
46
|
+
data
|
|
47
|
+
}), (e) => send({
|
|
48
|
+
t: "res",
|
|
49
|
+
id,
|
|
50
|
+
ok: false,
|
|
51
|
+
error: String(e?.message ?? e)
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
54
|
+
function chunk(totalShards, shardsPerCluster) {
|
|
55
|
+
return Array.from({ length: Math.ceil(totalShards / shardsPerCluster) }, (_, c) => Array.from({ length: Math.min(shardsPerCluster, totalShards - c * shardsPerCluster) }, (_, i) => c * shardsPerCluster + i));
|
|
56
|
+
}
|
|
57
|
+
/** Clusters for machine `slot` out of `machines`. Mirrors assignment() in operator/bridge.go. */
|
|
58
|
+
function assignment(totalShards, shardsPerCluster, machines, slot) {
|
|
59
|
+
const all = chunk(totalShards, shardsPerCluster);
|
|
60
|
+
const per = Math.ceil(all.length / machines);
|
|
61
|
+
const clusters = all.slice(slot * per, slot * per + per).map((shards, i) => ({
|
|
62
|
+
id: slot * per + i,
|
|
63
|
+
shards
|
|
64
|
+
}));
|
|
65
|
+
return {
|
|
66
|
+
t: "assign",
|
|
67
|
+
totalShards,
|
|
68
|
+
totalClusters: all.length,
|
|
69
|
+
clusters
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
async function fetchRecommendedShards(token) {
|
|
73
|
+
const res = await fetch("https://discord.com/api/v10/gateway/bot", { headers: { Authorization: `Bot ${token}` } });
|
|
74
|
+
if (!res.ok) throw new Error(`GET /gateway/bot failed: ${res.status}`);
|
|
75
|
+
return (await res.json()).shards;
|
|
76
|
+
}
|
|
77
|
+
const safeEqual = (a, b) => {
|
|
78
|
+
const x = Buffer.from(a), y = Buffer.from(b);
|
|
79
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
80
|
+
};
|
|
81
|
+
// src/manager.ts
|
|
82
|
+
/**
|
|
83
|
+
* Spawns one process per cluster, each running several shards.
|
|
84
|
+
* Events: "spawn" (clusterId), "exit" (clusterId, code), "debug" (message).
|
|
85
|
+
*/
|
|
86
|
+
var ClusterManager = class extends EventEmitter {
|
|
87
|
+
file;
|
|
88
|
+
clusters = /* @__PURE__ */ new Map();
|
|
89
|
+
totalShards = 0;
|
|
90
|
+
totalClusters = 0;
|
|
91
|
+
#opts;
|
|
92
|
+
#bridge;
|
|
93
|
+
#ws;
|
|
94
|
+
#online = false;
|
|
95
|
+
#wsPending = new Pending();
|
|
96
|
+
#assignKey = "";
|
|
97
|
+
#queue = Promise.resolve();
|
|
98
|
+
#closed = false;
|
|
99
|
+
constructor(file, opts = {}) {
|
|
100
|
+
super();
|
|
101
|
+
this.file = file;
|
|
102
|
+
const env = process.env;
|
|
103
|
+
this.#opts = {
|
|
104
|
+
totalShards: "auto",
|
|
105
|
+
shardsPerCluster: 4,
|
|
106
|
+
token: env.DISCORD_TOKEN,
|
|
107
|
+
spawnDelay: 5500,
|
|
108
|
+
respawn: true,
|
|
109
|
+
...opts
|
|
110
|
+
};
|
|
111
|
+
const url = opts.bridge?.url ?? env.DJSHARD_BRIDGE_URL;
|
|
112
|
+
this.#bridge = url ? {
|
|
113
|
+
url,
|
|
114
|
+
auth: opts.bridge?.auth ?? env.DJSHARD_AUTH ?? "",
|
|
115
|
+
id: opts.bridge?.id ?? env.DJSHARD_ID ?? hostname()
|
|
116
|
+
} : void 0;
|
|
117
|
+
}
|
|
118
|
+
/** Resolves once the first set of clusters has been spawned. */
|
|
119
|
+
async spawn() {
|
|
120
|
+
if (this.#bridge) {
|
|
121
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
122
|
+
this.once("assigned", resolve);
|
|
123
|
+
this.once("rejected", reject);
|
|
124
|
+
this.#connect();
|
|
125
|
+
return promise;
|
|
126
|
+
}
|
|
127
|
+
const { shardsPerCluster, token } = this.#opts;
|
|
128
|
+
let total = this.#opts.totalShards;
|
|
129
|
+
if (total === "auto") {
|
|
130
|
+
if (!token) throw new Error("totalShards \"auto\" needs a token");
|
|
131
|
+
total = await fetchRecommendedShards(token);
|
|
132
|
+
}
|
|
133
|
+
const clusters = chunk(total, shardsPerCluster).map((shards, id) => ({
|
|
134
|
+
id,
|
|
135
|
+
shards
|
|
136
|
+
}));
|
|
137
|
+
return this.#apply({
|
|
138
|
+
t: "assign",
|
|
139
|
+
totalShards: total,
|
|
140
|
+
totalClusters: clusters.length,
|
|
141
|
+
clusters
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/** Runs `script` on every cluster (across all machines when bridged). */
|
|
145
|
+
broadcastEval(script, opts = {}) {
|
|
146
|
+
const source = toSource(script);
|
|
147
|
+
if (!this.#bridge) return this.evalLocal(source, opts);
|
|
148
|
+
if (!this.#online) return Promise.reject(/* @__PURE__ */ new Error("bridge not connected"));
|
|
149
|
+
const { id, promise } = this.#wsPending.open(opts.timeout);
|
|
150
|
+
this.#send({
|
|
151
|
+
t: "eval",
|
|
152
|
+
id,
|
|
153
|
+
script: source,
|
|
154
|
+
context: opts.context,
|
|
155
|
+
cluster: opts.cluster
|
|
156
|
+
});
|
|
157
|
+
return promise;
|
|
158
|
+
}
|
|
159
|
+
/** Runs `script` on this machine's clusters only. */
|
|
160
|
+
evalLocal(script, { context, cluster, timeout } = {}) {
|
|
161
|
+
const targets = [...this.clusters.values()].filter((c) => cluster === void 0 || c.id === cluster);
|
|
162
|
+
return Promise.all(targets.map((c) => {
|
|
163
|
+
if (!c.proc || c.proc.killed) return Promise.reject(/* @__PURE__ */ new Error(`cluster ${c.id} is not running`));
|
|
164
|
+
const { id, promise } = c.pending.open(timeout);
|
|
165
|
+
c.proc.send({
|
|
166
|
+
t: "eval",
|
|
167
|
+
id,
|
|
168
|
+
script,
|
|
169
|
+
context
|
|
170
|
+
});
|
|
171
|
+
return promise;
|
|
172
|
+
}));
|
|
173
|
+
}
|
|
174
|
+
/** Kills every cluster in order and spawns them again. */
|
|
175
|
+
respawnAll() {
|
|
176
|
+
const clusters = [...this.clusters.values()].map(({ id, shards }) => ({
|
|
177
|
+
id,
|
|
178
|
+
shards
|
|
179
|
+
}));
|
|
180
|
+
return this.#apply({
|
|
181
|
+
t: "assign",
|
|
182
|
+
totalShards: this.totalShards,
|
|
183
|
+
totalClusters: this.totalClusters,
|
|
184
|
+
clusters
|
|
185
|
+
}, true);
|
|
186
|
+
}
|
|
187
|
+
destroy() {
|
|
188
|
+
this.#closed = true;
|
|
189
|
+
this.#ws?.close();
|
|
190
|
+
for (const c of this.clusters.values()) this.#stop(c);
|
|
191
|
+
}
|
|
192
|
+
#apply(a, force = false) {
|
|
193
|
+
return this.#queue = this.#queue.then(async () => {
|
|
194
|
+
const key = JSON.stringify(a);
|
|
195
|
+
if (key === this.#assignKey && !force) return;
|
|
196
|
+
this.#assignKey = key;
|
|
197
|
+
for (const c of this.clusters.values()) this.#stop(c);
|
|
198
|
+
this.clusters.clear();
|
|
199
|
+
this.totalShards = a.totalShards;
|
|
200
|
+
this.totalClusters = a.totalClusters;
|
|
201
|
+
for (const [i, { id, shards }] of a.clusters.entries()) {
|
|
202
|
+
if (this.#closed) return;
|
|
203
|
+
if (i > 0) await Bun.sleep(this.#opts.spawnDelay);
|
|
204
|
+
const c = {
|
|
205
|
+
id,
|
|
206
|
+
shards,
|
|
207
|
+
pending: new Pending(),
|
|
208
|
+
stopped: false
|
|
209
|
+
};
|
|
210
|
+
this.clusters.set(id, c);
|
|
211
|
+
this.#start(c);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
#start(c) {
|
|
216
|
+
const info = {
|
|
217
|
+
id: c.id,
|
|
218
|
+
shards: c.shards,
|
|
219
|
+
totalShards: this.totalShards,
|
|
220
|
+
totalClusters: this.totalClusters
|
|
221
|
+
};
|
|
222
|
+
c.proc = Bun.spawn([process.execPath, this.file], {
|
|
223
|
+
env: {
|
|
224
|
+
...process.env,
|
|
225
|
+
DJSHARD_CLUSTER: JSON.stringify(info)
|
|
226
|
+
},
|
|
227
|
+
stdio: [
|
|
228
|
+
"inherit",
|
|
229
|
+
"inherit",
|
|
230
|
+
"inherit"
|
|
231
|
+
],
|
|
232
|
+
ipc: (m) => {
|
|
233
|
+
if (m.t === "res") c.pending.settle(m);
|
|
234
|
+
else if (m.t === "eval") respond(m.id, () => this.broadcastEval(m.script, m), (r) => c.proc?.send(r));
|
|
235
|
+
},
|
|
236
|
+
onExit: (_, code) => {
|
|
237
|
+
c.pending.rejectAll(`cluster ${c.id} exited`);
|
|
238
|
+
this.emit("exit", c.id, code);
|
|
239
|
+
if (!c.stopped && !this.#closed && this.#opts.respawn) setTimeout(() => c.stopped || this.#start(c), 5e3);
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
this.emit("spawn", c.id);
|
|
243
|
+
}
|
|
244
|
+
#stop(c) {
|
|
245
|
+
c.stopped = true;
|
|
246
|
+
c.proc?.kill();
|
|
247
|
+
}
|
|
248
|
+
#send(m) {
|
|
249
|
+
this.#ws?.send(JSON.stringify(m));
|
|
250
|
+
}
|
|
251
|
+
#connect() {
|
|
252
|
+
const b = this.#bridge;
|
|
253
|
+
const ws = this.#ws = new WebSocket(b.url);
|
|
254
|
+
ws.onopen = () => this.#send({
|
|
255
|
+
t: "hello",
|
|
256
|
+
auth: b.auth,
|
|
257
|
+
name: b.id
|
|
258
|
+
});
|
|
259
|
+
ws.onmessage = (e) => this.#onBridge(JSON.parse(String(e.data)));
|
|
260
|
+
ws.onclose = () => {
|
|
261
|
+
this.#online = false;
|
|
262
|
+
this.#wsPending.rejectAll("bridge disconnected");
|
|
263
|
+
this.emit("debug", "bridge disconnected");
|
|
264
|
+
if (!this.#closed) setTimeout(() => this.#connect(), 5e3);
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
#onBridge(m) {
|
|
268
|
+
switch (m.t) {
|
|
269
|
+
case "assign":
|
|
270
|
+
this.#online = true;
|
|
271
|
+
this.#apply(m).then(() => this.emit("assigned"));
|
|
272
|
+
break;
|
|
273
|
+
case "eval":
|
|
274
|
+
respond(m.id, () => this.evalLocal(m.script, m), (r) => this.#send(r));
|
|
275
|
+
break;
|
|
276
|
+
case "res":
|
|
277
|
+
this.#wsPending.settle(m);
|
|
278
|
+
break;
|
|
279
|
+
case "error":
|
|
280
|
+
this.emit("debug", `bridge: ${m.message}`);
|
|
281
|
+
this.emit("rejected", new Error(m.message));
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
// src/client.ts
|
|
286
|
+
/** Cluster info injected by ClusterManager. Throws outside a managed cluster process. */
|
|
287
|
+
function getInfo() {
|
|
288
|
+
const raw = process.env.DJSHARD_CLUSTER;
|
|
289
|
+
if (!raw) throw new Error("not running inside a djshard cluster");
|
|
290
|
+
return JSON.parse(raw);
|
|
291
|
+
}
|
|
292
|
+
/** Runs inside a cluster process. `client` is what broadcastEval scripts receive. */
|
|
293
|
+
var ClusterClient = class {
|
|
294
|
+
client;
|
|
295
|
+
info = getInfo();
|
|
296
|
+
#pending = new Pending();
|
|
297
|
+
constructor(client) {
|
|
298
|
+
this.client = client;
|
|
299
|
+
process.on("message", (m) => {
|
|
300
|
+
if (m.t === "res") this.#pending.settle(m);
|
|
301
|
+
else if (m.t === "eval") respond(m.id, async () => evaluate(m.script, this.client, m.context), (r) => process.send(r));
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
get id() {
|
|
305
|
+
return this.info.id;
|
|
306
|
+
}
|
|
307
|
+
/** Runs `script` on every cluster across every machine; results ordered by cluster. */
|
|
308
|
+
broadcastEval(script, opts = {}) {
|
|
309
|
+
const { id, promise } = this.#pending.open(opts.timeout);
|
|
310
|
+
process.send({
|
|
311
|
+
t: "eval",
|
|
312
|
+
id,
|
|
313
|
+
script: toSource(script),
|
|
314
|
+
context: opts.context,
|
|
315
|
+
cluster: opts.cluster
|
|
316
|
+
});
|
|
317
|
+
return promise;
|
|
318
|
+
}
|
|
319
|
+
/** e.g. fetchClientValues("guilds.cache.size") */
|
|
320
|
+
fetchClientValues(path) {
|
|
321
|
+
return this.broadcastEval((c, p) => p.split(".").reduce((o, k) => o?.[k], c), { context: path });
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
function evaluate(script, client, context) {
|
|
325
|
+
return new Function("client", "context", `return (${script})(client, context)`)(client, context);
|
|
326
|
+
}
|
|
327
|
+
// src/bridge.ts
|
|
328
|
+
/** Hands out shard ranges to ClusterManagers on several hosts and routes cross-host broadcastEval. */
|
|
329
|
+
var Bridge = class {
|
|
330
|
+
opts;
|
|
331
|
+
totalShards = 0;
|
|
332
|
+
#slots;
|
|
333
|
+
#sticky = /* @__PURE__ */ new Map();
|
|
334
|
+
#server;
|
|
335
|
+
constructor(opts) {
|
|
336
|
+
this.opts = opts;
|
|
337
|
+
this.#slots = Array(opts.machines).fill(void 0);
|
|
338
|
+
}
|
|
339
|
+
/** Starts listening; returns the bound port. */
|
|
340
|
+
async listen() {
|
|
341
|
+
const { totalShards, token } = this.opts;
|
|
342
|
+
if (totalShards === "auto" && !token) throw new Error("totalShards \"auto\" needs a token");
|
|
343
|
+
this.totalShards = totalShards === "auto" ? await fetchRecommendedShards(token) : totalShards;
|
|
344
|
+
this.#server = Bun.serve({
|
|
345
|
+
port: this.opts.port ?? 4444,
|
|
346
|
+
fetch: (req, server) => server.upgrade(req, { data: {
|
|
347
|
+
id: "",
|
|
348
|
+
slot: -1,
|
|
349
|
+
pending: new Pending()
|
|
350
|
+
} }) ? void 0 : new Response("djshard bridge", { status: 426 }),
|
|
351
|
+
websocket: {
|
|
352
|
+
message: (ws, raw) => {
|
|
353
|
+
let m;
|
|
354
|
+
try {
|
|
355
|
+
m = JSON.parse(String(raw));
|
|
356
|
+
} catch {
|
|
357
|
+
return ws.close(1003, "bad json");
|
|
358
|
+
}
|
|
359
|
+
this.#onMessage(ws, m);
|
|
360
|
+
},
|
|
361
|
+
close: (ws) => {
|
|
362
|
+
if (this.#slots[ws.data.slot] === ws) this.#slots[ws.data.slot] = void 0;
|
|
363
|
+
ws.data.pending.rejectAll(`machine ${ws.data.id} disconnected`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
return this.#server.port;
|
|
368
|
+
}
|
|
369
|
+
/** Runs `script` on every cluster of every connected machine. */
|
|
370
|
+
async broadcastEval(script, opts = {}) {
|
|
371
|
+
return (await Promise.all(this.#slots.filter((ws) => ws !== void 0).map((ws) => {
|
|
372
|
+
const { id, promise } = ws.data.pending.open(opts.timeout);
|
|
373
|
+
send(ws, {
|
|
374
|
+
t: "eval",
|
|
375
|
+
id,
|
|
376
|
+
script: toSource(script),
|
|
377
|
+
context: opts.context,
|
|
378
|
+
cluster: opts.cluster
|
|
379
|
+
});
|
|
380
|
+
return promise;
|
|
381
|
+
}))).flat();
|
|
382
|
+
}
|
|
383
|
+
close() {
|
|
384
|
+
this.#server?.stop(true);
|
|
385
|
+
}
|
|
386
|
+
#onMessage(ws, m) {
|
|
387
|
+
if (ws.data.slot < 0) {
|
|
388
|
+
if (m.t !== "hello" || typeof m.auth !== "string" || !safeEqual(m.auth, this.opts.auth)) return ws.close(1008, "unauthorized");
|
|
389
|
+
const prev = this.#sticky.get(m.name);
|
|
390
|
+
const slot = prev !== void 0 && !this.#slots[prev] ? prev : this.#slots.findIndex((s) => !s);
|
|
391
|
+
if (slot < 0) {
|
|
392
|
+
send(ws, {
|
|
393
|
+
t: "error",
|
|
394
|
+
message: "no free machine slot"
|
|
395
|
+
});
|
|
396
|
+
return ws.close(1008, "full");
|
|
397
|
+
}
|
|
398
|
+
Object.assign(ws.data, {
|
|
399
|
+
id: String(m.name),
|
|
400
|
+
slot
|
|
401
|
+
});
|
|
402
|
+
this.#slots[slot] = ws;
|
|
403
|
+
this.#sticky.set(ws.data.id, slot);
|
|
404
|
+
return send(ws, assignment(this.totalShards, this.opts.shardsPerCluster ?? 4, this.opts.machines, slot));
|
|
405
|
+
}
|
|
406
|
+
if (m.t === "eval") respond(m.id, () => this.broadcastEval(m.script, m), (r) => send(ws, r));
|
|
407
|
+
else if (m.t === "res") ws.data.pending.settle(m);
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
const send = (ws, m) => ws.send(JSON.stringify(m));
|
|
411
|
+
export { Bridge, ClusterClient, ClusterManager, assignment, chunk, fetchRecommendedShards, getInfo };
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "djshard",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Clustered + cross-host sharding for Discord bots on Bun, with a Kubernetes operator",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist"
|
|
7
|
+
],
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "./dist/index.cjs",
|
|
10
|
+
"module": "./dist/index.mjs",
|
|
11
|
+
"types": "./dist/index.d.cts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"import": {
|
|
15
|
+
"types": "./dist/index.d.mts",
|
|
16
|
+
"default": "./dist/index.mjs"
|
|
17
|
+
},
|
|
18
|
+
"require": {
|
|
19
|
+
"types": "./dist/index.d.cts",
|
|
20
|
+
"default": "./dist/index.cjs"
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsdown",
|
|
26
|
+
"lint": "oxlint",
|
|
27
|
+
"fmt": "oxfmt",
|
|
28
|
+
"fmt:check": "oxfmt --check",
|
|
29
|
+
"typecheck": "bun check",
|
|
30
|
+
"test": "bun test",
|
|
31
|
+
"ci": "bun run lint && bun run fmt:check && bun run typecheck && bun test && bun run build",
|
|
32
|
+
"prepublishOnly": "bun run build"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@types/bun": "latest",
|
|
36
|
+
"oxfmt": "^0.78.0",
|
|
37
|
+
"oxlint": "^1",
|
|
38
|
+
"tsdown": "^0.23.7",
|
|
39
|
+
"typescript": "^7.0.2"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"typescript": "^7"
|
|
43
|
+
},
|
|
44
|
+
"engines": {
|
|
45
|
+
"bun": ">=1.2"
|
|
46
|
+
}
|
|
47
|
+
}
|