Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 8c28848

Browse files
committed
Use worker threads for pinging
1 parent ae15f37 commit 8c28848

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

src/Kirin/utils/ping.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import JavaProtocol, { NewPingResult } from 'minecraft-protocol';
22
import { ServerStatus } from '../classes/Server.js';
33
import BedrockProtocol from 'bedrock-protocol';
4+
import { Worker } from 'worker_threads';
5+
import { fileURLToPath } from 'url';
6+
import path from 'path';
7+
8+
const __filename = fileURLToPath(import.meta.url);
9+
const __dirname = path.dirname(__filename);
410

511
export interface PingData {
612
status: Exclude<ServerStatus, 'Starting'|'Stopping'>;
@@ -21,8 +27,22 @@ export interface PingOptions {
2127
export type JavaPingOptions = Omit<PingOptions, 'protocol'> & { protocol: 'java' };
2228
export type BedrockPingOptions = Omit<PingOptions, 'protocol' | 'timeout'> & { protocol: 'bedrock' };
2329

24-
export async function pingServer(options: JavaPingOptions|BedrockPingOptions): Promise<PingData> {
25-
return options.protocol === 'java' ? pingJavaServer(options) : pingBedrockServer(options);
30+
export async function pingServer(options: (JavaPingOptions|BedrockPingOptions) & { useWorkerThread?: boolean; }): Promise<PingData> {
31+
if (options.useWorkerThread === false) {
32+
return options.protocol === 'java' ? await pingJavaServer(options) : await pingBedrockServer(options);
33+
}
34+
35+
return new Promise((res, rej) => {
36+
const worker = new Worker(path.join(__dirname, './ping.worker.js'), {
37+
workerData: options
38+
});
39+
40+
worker.on('message', res);
41+
worker.on('error', rej);
42+
worker.on('exit', code => {
43+
if (code !== 0) rej(new Error(`Ping worker exited with an error code: ${code}`));
44+
});
45+
});
2646
}
2747

2848
export async function pingJavaServer(options: JavaPingOptions): Promise<PingData> {

src/Kirin/utils/ping.worker.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { parentPort, workerData } from 'worker_threads';
2+
import { BedrockPingOptions, JavaPingOptions, PingData, pingBedrockServer, pingJavaServer } from './ping.js';
3+
4+
if (!parentPort) process.exit(1);
5+
6+
const pingOptions: JavaPingOptions|BedrockPingOptions = workerData;
7+
const pingData: PingData = pingOptions.protocol === 'java' ? await pingJavaServer(pingOptions) : await pingBedrockServer(pingOptions);
8+
9+
parentPort.postMessage(pingData);

0 commit comments

Comments
 (0)