djshard 0.1.0 → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ROBOT
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,58 +1,142 @@
1
1
  # djshard
2
2
 
3
- Discord ボット向けのシャーディングライブラリ(Bun 用)。discord-hybrid-sharding(1 プロセスで複数シャード)と discord-cross-hosting(複数マシンへの分散)の機能をまとめたもので、Kubernetes 用のオペレーター(Go)も付いています。
3
+ Clustered and cross-host sharding for Discord bots on [Bun](https://bun.sh), plus a Kubernetes operator.
4
4
 
5
- ## 単一マシンで使う
5
+ djshard combines what [discord-hybrid-sharding](https://github.com/meister03/discord-hybrid-sharding) and [discord-cross-hosting](https://github.com/meister03/discord-cross-hosting) do:
6
+
7
+ - **Clusters**: one process runs several shards, so you need far fewer processes than shards.
8
+ - **Cross-host**: shards are split across machines, and `broadcastEval` reaches every cluster on every machine.
9
+ - **Kubernetes**: a Go operator turns a `ShardCluster` resource into a StatefulSet and acts as the bridge between pods.
10
+
11
+ djshard is not tied to any Discord library. It tells each cluster which shards to run, and you pass them to your client.
12
+
13
+ > [!NOTE]
14
+ > djshard runs on Bun only. It uses `Bun.spawn` and `Bun.serve`.
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ bun add djshard
20
+ # or
21
+ npm install djshard
22
+ pnpm add djshard
23
+ yarn add djshard
24
+ ```
25
+
26
+ Both ESM (`import`) and CommonJS (`require`) builds are published. Any package manager can install it,
27
+ but the code must run on Bun: it uses `Bun.spawn` and `Bun.serve`.
28
+
29
+ ## Single machine
6
30
 
7
31
  ```ts
8
32
  // manager.ts
9
33
  import { ClusterManager } from "djshard";
10
- const manager = new ClusterManager("./bot.ts", { shardsPerCluster: 4 }); // totalShards: "auto" + DISCORD_TOKEN
34
+
35
+ const manager = new ClusterManager("./bot.ts", { shardsPerCluster: 4 });
36
+ manager.on("exit", (id, code) => console.warn(`cluster ${id} exited with ${code}`));
11
37
  await manager.spawn();
12
38
  ```
13
39
 
14
40
  ```ts
15
- // bot.ts
41
+ // bot.ts: runs once per cluster
16
42
  import { Client } from "discord.js";
17
43
  import { ClusterClient, getInfo } from "djshard";
44
+
18
45
  const info = getInfo();
19
46
  const client = new Client({ intents: [], shards: info.shards, shardCount: info.totalShards });
20
47
  client.cluster = new ClusterClient(client);
21
48
  await client.login();
22
49
 
23
- const guilds = await client.cluster.broadcastEval((c) => c.guilds.cache.size); // 全クラスタ分
50
+ // Runs on every cluster; results are ordered by cluster id.
51
+ const counts = await client.cluster.broadcastEval((c) => c.guilds.cache.size);
52
+ const same = await client.cluster.fetchClientValues("guilds.cache.size");
24
53
  ```
25
54
 
26
- ## 複数マシンで使う(k8s なし)
55
+ When `totalShards` is `"auto"` (the default), the manager asks Discord for the recommended shard count using `DISCORD_TOKEN`.
56
+
57
+ ### `ClusterManager` options
58
+
59
+ | Option | Default | Description |
60
+ | ------------------ | -------------------- | --------------------------------------------------------------------- |
61
+ | `totalShards` | `"auto"` | Total shard count. Ignored when a bridge is used, because it decides. |
62
+ | `shardsPerCluster` | `4` | Shards per process. |
63
+ | `token` | `DISCORD_TOKEN` | Used to look up the recommended shard count. |
64
+ | `spawnDelay` | `5500` | Milliseconds between cluster spawns, to respect identify rate limits. |
65
+ | `respawn` | `true` | Restart clusters that exit. |
66
+ | `bridge` | from `DJSHARD_*` env | `{ url, auth, id? }`. Turns on cross-host mode. |
67
+
68
+ `broadcastEval(script, { context, cluster, timeout })` passes `context` to the script as its second argument and runs it only on `cluster` when one is given. Scripts are serialized with `toString()`, so they must not capture outer variables. Pass values through `context` instead. Return values must be JSON- or structured-clone-serializable.
69
+
70
+ ## Multiple machines (without Kubernetes)
71
+
72
+ Run one bridge:
27
73
 
28
74
  ```ts
29
75
  import { Bridge } from "djshard";
30
- await new Bridge({ port: 4444, auth: "secret", machines: 3, totalShards: "auto", token }).listen();
76
+
77
+ const bridge = new Bridge({ port: 4444, auth: process.env.BRIDGE_AUTH!, machines: 3, totalShards: "auto", token });
78
+ await bridge.listen();
79
+ ```
80
+
81
+ On every machine:
82
+
83
+ ```ts
84
+ const manager = new ClusterManager("./bot.ts", {
85
+ bridge: { url: "ws://bridge-host:4444", auth: process.env.BRIDGE_AUTH!, id: "machine-a" },
86
+ });
87
+ await manager.spawn();
31
88
  ```
32
89
 
33
- 各マシンで `new ClusterManager("./bot.ts", { bridge: { url: "ws://bridge:4444", auth: "secret" } })` を起動します。`broadcastEval` は全マシンにまたがって実行されます。
90
+ The bridge gives each machine a contiguous range of clusters. A machine that reconnects with the same `id` gets the same range back. Its clusters keep running while it is disconnected.
34
91
 
35
92
  ## Kubernetes
36
93
 
37
94
  ```sh
38
95
  kubectl apply -f operator/config/crd.yaml -f operator/config/operator.yaml
39
- kubectl create secret generic discord --from-literal=token=...
96
+ kubectl create secret generic discord --from-literal=token=YOUR_TOKEN
40
97
  kubectl apply -f operator/config/example.yaml
41
98
  ```
42
99
 
43
- オペレーターは `ShardCluster` ごとに StatefulSet と認証用の Secret を作り、`DJSHARD_BRIDGE_URL` / `DJSHARD_AUTH` / `DJSHARD_ID` を最初のコンテナに注入します。`ClusterManager` はこれらの環境変数を自動で読み込みます。ブリッジはオペレーター本体の中で動き、Pod 名の序数(`mybot-2` → 2)でシャードを割り当てます。
100
+ ```yaml
101
+ apiVersion: djshard.ro80t.com/v1alpha1
102
+ kind: ShardCluster
103
+ metadata: { name: mybot }
104
+ spec:
105
+ replicas: 3
106
+ shardsPerCluster: 4
107
+ # totalShards: 32 # omit to use Discord's recommendation (resolved once)
108
+ tokenSecretRef: { name: discord, key: token }
109
+ template:
110
+ spec:
111
+ containers:
112
+ - name: bot
113
+ image: mybot:latest
114
+ command: [bun, manager.ts]
115
+ ```
44
116
 
45
- ## 制約
117
+ For each `ShardCluster`, the operator:
46
118
 
47
- - オペレーターは 1 レプリカのみで動かしてください(接続はメモリ上で保持しています)。
48
- - `replicas` / `totalShards` / `shardsPerCluster` を変更すると全 Pod がローリング再起動されます。再起動中は、同じシャードを新旧の Pod が一時的に重複して持つことがあります。
49
- - ブリッジ通信は平文の ws です。認証トークンでしか保護していないため、クラスタ外へは公開しないでください。
50
- - broadcastEval の戻り値は JSON にシリアライズできる値に限ります。
119
+ - creates a StatefulSet and a Secret holding a random bridge token,
120
+ - injects `DJSHARD_BRIDGE_URL`, `DJSHARD_AUTH`, `DJSHARD_ID` and `DISCORD_TOKEN` into the first container,
121
+ - serves the bridge itself and assigns shards by pod ordinal (`mybot-2` gets slot 2),
122
+ - fails over: when a pod has been disconnected for 30 seconds (operator flag `--failover-grace`), its clusters are spread over the remaining pods; when it reconnects it gets them back. Pods only start and stop the clusters that changed hands,
123
+ - rolls every pod when `replicas`, `totalShards` or `shardsPerCluster` changes.
51
124
 
52
- ## 開発
125
+ Your `manager.ts` is the same as in single-machine mode, because `ClusterManager` picks up the `DJSHARD_*` variables automatically.
53
126
 
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
- ```
127
+ The operator image is published to `ghcr.io/ro80t/djshard-operator` with every release, tagged with the release version and `latest`. To run your own build, build `operator/Dockerfile` and change the image in `operator/config/operator.yaml`.
128
+
129
+ ## Limitations
130
+
131
+ - Run the operator as a single replica. Bot connections live in its memory.
132
+ - During a rolling restart, an old pod and a new pod can briefly own the same shard. Discord drops the older session.
133
+ - Failover assumes a disconnected pod is dead. A pod that is alive but cut off from the operator keeps running its shards while another pod takes them over.
134
+ - The standalone `Bridge` (without Kubernetes) does not fail over.
135
+ - Bridge traffic is plain WebSocket protected only by the shared token. Keep it inside the cluster or private network.
136
+ - A cluster that hangs without exiting is not detected (there is no heartbeat).
137
+ - Identify rate limits (`max_concurrency`) are only respected within one machine, through `spawnDelay`.
138
+ - Only the process mode exists. There is no worker-thread mode or custom IPC messages yet.
139
+
140
+ ## Contributing
141
+
142
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
package/dist/index.cjs CHANGED
@@ -159,7 +159,7 @@ var ClusterManager = class extends node_events.EventEmitter {
159
159
  }
160
160
  /** Runs `script` on this machine's clusters only. */
161
161
  evalLocal(script, { context, cluster, timeout } = {}) {
162
- const targets = [...this.clusters.values()].filter((c) => cluster === void 0 || c.id === cluster);
162
+ const targets = [...this.clusters.values()].filter((c) => cluster === void 0 || c.id === cluster).sort((a, b) => a.id - b.id);
163
163
  return Promise.all(targets.map((c) => {
164
164
  if (!c.proc || c.proc.killed) return Promise.reject(/* @__PURE__ */ new Error(`cluster ${c.id} is not running`));
165
165
  const { id, promise } = c.pending.open(timeout);
@@ -191,15 +191,23 @@ var ClusterManager = class extends node_events.EventEmitter {
191
191
  for (const c of this.clusters.values()) this.#stop(c);
192
192
  }
193
193
  #apply(a, force = false) {
194
- return this.#queue = this.#queue.then(async () => {
194
+ const run = this.#queue.catch(() => {}).then(async () => {
195
195
  const key = JSON.stringify(a);
196
196
  if (key === this.#assignKey && !force) return;
197
197
  this.#assignKey = key;
198
- for (const c of this.clusters.values()) this.#stop(c);
198
+ const sameLayout = !force && a.totalShards === this.totalShards && a.totalClusters === this.totalClusters;
199
+ const kept = /* @__PURE__ */ new Map();
200
+ for (const c of this.clusters.values()) {
201
+ const want = a.clusters.find((x) => x.id === c.id);
202
+ if (sameLayout && want && String(want.shards) === String(c.shards)) kept.set(c.id, c);
203
+ else this.#stop(c);
204
+ }
199
205
  this.clusters.clear();
206
+ for (const [id, c] of kept) this.clusters.set(id, c);
200
207
  this.totalShards = a.totalShards;
201
208
  this.totalClusters = a.totalClusters;
202
- for (const [i, { id, shards }] of a.clusters.entries()) {
209
+ const added = a.clusters.filter((x) => !kept.has(x.id));
210
+ for (const [i, { id, shards }] of added.entries()) {
203
211
  if (this.#closed) return;
204
212
  if (i > 0) await Bun.sleep(this.#opts.spawnDelay);
205
213
  const c = {
@@ -212,6 +220,8 @@ var ClusterManager = class extends node_events.EventEmitter {
212
220
  this.#start(c);
213
221
  }
214
222
  });
223
+ this.#queue = run;
224
+ return run;
215
225
  }
216
226
  #start(c) {
217
227
  const info = {
@@ -257,7 +267,15 @@ var ClusterManager = class extends node_events.EventEmitter {
257
267
  auth: b.auth,
258
268
  name: b.id
259
269
  });
260
- ws.onmessage = (e) => this.#onBridge(JSON.parse(String(e.data)));
270
+ ws.onmessage = (e) => {
271
+ let m;
272
+ try {
273
+ m = JSON.parse(String(e.data));
274
+ } catch {
275
+ return this.emit("debug", "bridge sent bad json");
276
+ }
277
+ this.#onBridge(m);
278
+ };
261
279
  ws.onclose = () => {
262
280
  this.#online = false;
263
281
  this.#wsPending.rejectAll("bridge disconnected");
@@ -269,7 +287,7 @@ var ClusterManager = class extends node_events.EventEmitter {
269
287
  switch (m.t) {
270
288
  case "assign":
271
289
  this.#online = true;
272
- this.#apply(m).then(() => this.emit("assigned"));
290
+ this.#apply(m).then(() => this.emit("assigned"), (e) => this.emit("rejected", e));
273
291
  break;
274
292
  case "eval":
275
293
  respond(m.id, () => this.evalLocal(m.script, m), (r) => this.#send(r));
@@ -386,7 +404,13 @@ var Bridge = class {
386
404
  }
387
405
  #onMessage(ws, m) {
388
406
  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");
407
+ if (m.t !== "hello" || typeof m.auth !== "string" || !safeEqual(m.auth, this.opts.auth)) {
408
+ send(ws, {
409
+ t: "error",
410
+ message: "unauthorized"
411
+ });
412
+ return ws.close(1008, "unauthorized");
413
+ }
390
414
  const prev = this.#sticky.get(m.name);
391
415
  const slot = prev !== void 0 && !this.#slots[prev] ? prev : this.#slots.findIndex((s) => !s);
392
416
  if (slot < 0) {
package/dist/index.mjs CHANGED
@@ -158,7 +158,7 @@ var ClusterManager = class extends EventEmitter {
158
158
  }
159
159
  /** Runs `script` on this machine's clusters only. */
160
160
  evalLocal(script, { context, cluster, timeout } = {}) {
161
- const targets = [...this.clusters.values()].filter((c) => cluster === void 0 || c.id === cluster);
161
+ const targets = [...this.clusters.values()].filter((c) => cluster === void 0 || c.id === cluster).sort((a, b) => a.id - b.id);
162
162
  return Promise.all(targets.map((c) => {
163
163
  if (!c.proc || c.proc.killed) return Promise.reject(/* @__PURE__ */ new Error(`cluster ${c.id} is not running`));
164
164
  const { id, promise } = c.pending.open(timeout);
@@ -190,15 +190,23 @@ var ClusterManager = class extends EventEmitter {
190
190
  for (const c of this.clusters.values()) this.#stop(c);
191
191
  }
192
192
  #apply(a, force = false) {
193
- return this.#queue = this.#queue.then(async () => {
193
+ const run = this.#queue.catch(() => {}).then(async () => {
194
194
  const key = JSON.stringify(a);
195
195
  if (key === this.#assignKey && !force) return;
196
196
  this.#assignKey = key;
197
- for (const c of this.clusters.values()) this.#stop(c);
197
+ const sameLayout = !force && a.totalShards === this.totalShards && a.totalClusters === this.totalClusters;
198
+ const kept = /* @__PURE__ */ new Map();
199
+ for (const c of this.clusters.values()) {
200
+ const want = a.clusters.find((x) => x.id === c.id);
201
+ if (sameLayout && want && String(want.shards) === String(c.shards)) kept.set(c.id, c);
202
+ else this.#stop(c);
203
+ }
198
204
  this.clusters.clear();
205
+ for (const [id, c] of kept) this.clusters.set(id, c);
199
206
  this.totalShards = a.totalShards;
200
207
  this.totalClusters = a.totalClusters;
201
- for (const [i, { id, shards }] of a.clusters.entries()) {
208
+ const added = a.clusters.filter((x) => !kept.has(x.id));
209
+ for (const [i, { id, shards }] of added.entries()) {
202
210
  if (this.#closed) return;
203
211
  if (i > 0) await Bun.sleep(this.#opts.spawnDelay);
204
212
  const c = {
@@ -211,6 +219,8 @@ var ClusterManager = class extends EventEmitter {
211
219
  this.#start(c);
212
220
  }
213
221
  });
222
+ this.#queue = run;
223
+ return run;
214
224
  }
215
225
  #start(c) {
216
226
  const info = {
@@ -256,7 +266,15 @@ var ClusterManager = class extends EventEmitter {
256
266
  auth: b.auth,
257
267
  name: b.id
258
268
  });
259
- ws.onmessage = (e) => this.#onBridge(JSON.parse(String(e.data)));
269
+ ws.onmessage = (e) => {
270
+ let m;
271
+ try {
272
+ m = JSON.parse(String(e.data));
273
+ } catch {
274
+ return this.emit("debug", "bridge sent bad json");
275
+ }
276
+ this.#onBridge(m);
277
+ };
260
278
  ws.onclose = () => {
261
279
  this.#online = false;
262
280
  this.#wsPending.rejectAll("bridge disconnected");
@@ -268,7 +286,7 @@ var ClusterManager = class extends EventEmitter {
268
286
  switch (m.t) {
269
287
  case "assign":
270
288
  this.#online = true;
271
- this.#apply(m).then(() => this.emit("assigned"));
289
+ this.#apply(m).then(() => this.emit("assigned"), (e) => this.emit("rejected", e));
272
290
  break;
273
291
  case "eval":
274
292
  respond(m.id, () => this.evalLocal(m.script, m), (r) => this.#send(r));
@@ -385,7 +403,13 @@ var Bridge = class {
385
403
  }
386
404
  #onMessage(ws, m) {
387
405
  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");
406
+ if (m.t !== "hello" || typeof m.auth !== "string" || !safeEqual(m.auth, this.opts.auth)) {
407
+ send(ws, {
408
+ t: "error",
409
+ message: "unauthorized"
410
+ });
411
+ return ws.close(1008, "unauthorized");
412
+ }
389
413
  const prev = this.#sticky.get(m.name);
390
414
  const slot = prev !== void 0 && !this.#slots[prev] ? prev : this.#slots.findIndex((s) => !s);
391
415
  if (slot < 0) {
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "djshard",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Clustered + cross-host sharding for Discord bots on Bun, with a Kubernetes operator",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/ro80t/djshard.git"
8
+ },
5
9
  "files": [
6
10
  "dist"
7
11
  ],
@@ -29,18 +33,19 @@
29
33
  "typecheck": "bun check",
30
34
  "test": "bun test",
31
35
  "ci": "bun run lint && bun run fmt:check && bun run typecheck && bun test && bun run build",
32
- "prepublishOnly": "bun run build"
36
+ "prepublishOnly": "bun run build",
37
+ "skills": "skills experimental_install",
38
+ "release": "bun run build && changeset publish"
33
39
  },
34
40
  "devDependencies": {
41
+ "@changesets/cli": "^3.0.3",
35
42
  "@types/bun": "latest",
36
43
  "oxfmt": "^0.78.0",
37
44
  "oxlint": "^1",
45
+ "skills": "^1.8.1",
38
46
  "tsdown": "^0.23.7",
39
47
  "typescript": "^7.0.2"
40
48
  },
41
- "peerDependencies": {
42
- "typescript": "^7"
43
- },
44
49
  "engines": {
45
50
  "bun": ">=1.2"
46
51
  }