feat(ws): support for custom worker messaging (#10241)

This commit is contained in:
DD
2024-05-03 17:53:09 +03:00
committed by GitHub
parent 6cf094c282
commit 728164ed86
2 changed files with 24 additions and 1 deletions

View File

@@ -132,6 +132,10 @@ const manager = new WebSocketManager({
new WorkerShardingStrategy(manager, {
shardsPerWorker: 2,
workerPath: './worker.js',
// Optionally, if you you have custom messaging, like for analytic collection, you can use this:
async unknownPayloadHandler(data: any) {
// handle data here :3
},
}),
});
```
@@ -140,6 +144,7 @@ And your `worker.ts` file:
```ts
import { WorkerBootstrapper, WebSocketShardEvents } from '@discordjs/ws';
import { parentPort } from 'node:worker_threads';
const bootstrapper = new WorkerBootstrapper();
void bootstrapper.bootstrap({
@@ -158,6 +163,9 @@ void bootstrapper.bootstrap({
});
},
});
// This will go to `unknownPayloadHandler` in the main thread, or be ignored if not provided
parentPort!.postMessage({ custom: 'data' });
```
## Links

View File

@@ -66,6 +66,10 @@ export interface WorkerShardingStrategyOptions {
* Dictates how many shards should be spawned per worker thread.
*/
shardsPerWorker: number | 'all';
/**
* Handles a payload not recognized by the handler.
*/
unknownPayloadHandler?(payload: any): unknown;
/**
* Path to the worker file to use. The worker requires quite a bit of setup, it is recommended you leverage the {@link WorkerBootstrapper} class.
*/
@@ -225,7 +229,13 @@ export class WorkerShardingStrategy implements IShardingStrategy {
.on('messageerror', (err) => {
throw err;
})
.on('message', async (payload: WorkerReceivePayload) => this.onMessage(worker, payload));
.on('message', async (payload: any) => {
if ('op' in payload) {
await this.onMessage(worker, payload);
} else {
await this.options.unknownPayloadHandler?.(payload);
}
});
this.#workers.push(worker);
for (const shardId of workerData.shardIds) {
@@ -347,6 +357,11 @@ export class WorkerShardingStrategy implements IShardingStrategy {
break;
}
default: {
await this.options.unknownPayloadHandler?.(payload);
break;
}
}
}