mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
fix: measure TeamSpeak latency over its protocol
This commit is contained in:
1 parent
dcc52c4530
commit
a295ff4b27
7 files changed
+167
-47
No files matched your search
+78
-35
@@ -1,7 +1,11 @@
|
||||
import { createConnection } from "node:net";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
export type TeamSpeakPingErrorCode = "HOST_NOT_FOUND" | "UNREACHABLE" | "TIMEOUT";
|
||||
export type TeamSpeakPingErrorCode =
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "TIMEOUT"
|
||||
| "INVALID_PASSWORD"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "SERVER_REJECTED"
|
||||
| "INTERNAL_ERROR";
|
||||
|
||||
export interface TeamSpeakPingAttempt {
|
||||
ok: boolean;
|
||||
@@ -19,45 +23,48 @@ export interface TeamSpeakPingResult {
|
||||
errorCode?: TeamSpeakPingErrorCode;
|
||||
}
|
||||
|
||||
export type TeamSpeakCommandExecutor = (command: string, timeoutMs?: number) => Promise<unknown>;
|
||||
|
||||
/**
|
||||
* Probe the TeamSpeak TCP endpoint without creating a TeamSpeak client.
|
||||
* Browsers cannot send ICMP, and TeamSpeak does not expose an ICMP-style UDP
|
||||
* echo, so a short TCP connect is the portable reachability signal available
|
||||
* to the gateway. The socket is destroyed immediately after the handshake.
|
||||
* Measure an already connected TeamSpeak session using the protocol's own
|
||||
* command channel. TeamSpeak voice/query traffic is UDP; a TCP connect to
|
||||
* port 9987 is therefore not a valid reachability test and reports false
|
||||
* packet loss even while voice works normally.
|
||||
*/
|
||||
export function pingTeamSpeakPort(
|
||||
target: TeamSpeakTarget,
|
||||
export async function pingTeamSpeakSession(
|
||||
execute: TeamSpeakCommandExecutor,
|
||||
timeoutMs = 1_500,
|
||||
): Promise<TeamSpeakPingAttempt> {
|
||||
return new Promise((resolve) => {
|
||||
const startedAt = Date.now();
|
||||
const socket = createConnection({ host: target.host, port: target.port });
|
||||
let settled = false;
|
||||
|
||||
const finish = (result: TeamSpeakPingAttempt) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
socket.setTimeout(timeoutMs, () => finish({ ok: false, latencyMs: null, errorCode: "TIMEOUT" }));
|
||||
socket.once("connect", () => finish({ ok: true, latencyMs: Math.max(0, Date.now() - startedAt) }));
|
||||
socket.once("error", (error: NodeJS.ErrnoException) => finish({
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
// `version` is read-only and is handled by both TS3 and TS6.
|
||||
await execute("version", timeoutMs);
|
||||
return { ok: true, latencyMs: Math.max(0, Date.now() - startedAt) };
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: null,
|
||||
errorCode: error.code === "ENOTFOUND" || error.code === "EAI_AGAIN" ? "HOST_NOT_FOUND" : "UNREACHABLE",
|
||||
}));
|
||||
});
|
||||
errorCode: classifyProbeError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function pingTeamSpeak(
|
||||
target: TeamSpeakTarget,
|
||||
options: { attempts?: number; timeoutMs?: number } = {},
|
||||
export async function collectTeamSpeakPings(
|
||||
probe: () => Promise<TeamSpeakPingAttempt>,
|
||||
options: { attempts?: number } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
const attempts = Math.max(1, Math.min(8, Math.floor(options.attempts ?? 4)));
|
||||
const timeoutMs = Math.max(250, Math.min(5_000, Math.floor(options.timeoutMs ?? 1_500)));
|
||||
const results = await Promise.all(Array.from({ length: attempts }, () => pingTeamSpeakPort(target, timeoutMs)));
|
||||
const results: TeamSpeakPingAttempt[] = [];
|
||||
// Keep attempts sequential. This measures the real protocol path without
|
||||
// opening several temporary TeamSpeak sessions at the same time.
|
||||
for (let index = 0; index < attempts; index += 1) {
|
||||
results.push(await probe());
|
||||
}
|
||||
return summarizeTeamSpeakPings(results, attempts);
|
||||
}
|
||||
|
||||
export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempts = results.length): TeamSpeakPingResult {
|
||||
const normalizedAttempts = Math.max(1, attempts);
|
||||
const samples = results
|
||||
.filter((result): result is TeamSpeakPingAttempt & { latencyMs: number } => result.ok && result.latencyMs !== null)
|
||||
.map((result) => result.latencyMs)
|
||||
@@ -67,10 +74,46 @@ export async function pingTeamSpeak(
|
||||
return {
|
||||
ok: samples.length > 0,
|
||||
latencyMs: samples.length ? samples[Math.floor(samples.length / 2)] : null,
|
||||
packetLossPercent: Math.round(((attempts - samples.length) / attempts) * 100),
|
||||
attempts,
|
||||
packetLossPercent: Math.round(((normalizedAttempts - samples.length) / normalizedAttempts) * 100),
|
||||
attempts: normalizedAttempts,
|
||||
successfulAttempts: samples.length,
|
||||
samples,
|
||||
...(errorCode ? { errorCode } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const lower = text.toLocaleLowerCase();
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found/.test(lower)) return "HOST_NOT_FOUND";
|
||||
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
|
||||
if (/password|authentication|invalid.*credential/.test(lower)) return "INVALID_PASSWORD";
|
||||
if (/protocol|version|handshake|negotiat/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED";
|
||||
if (/reject|full|denied/.test(lower)) return "SERVER_REJECTED";
|
||||
return "UNREACHABLE";
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a small compatibility helper for callers that only need one protocol
|
||||
* attempt. It deliberately has no host/port argument because the connected
|
||||
* TeamSpeak session owns the actual resolved endpoint.
|
||||
*/
|
||||
export function pingTeamSpeakPort(
|
||||
execute: TeamSpeakCommandExecutor,
|
||||
timeoutMs = 1_500,
|
||||
): Promise<TeamSpeakPingAttempt> {
|
||||
return pingTeamSpeakSession(execute, timeoutMs);
|
||||
}
|
||||
|
||||
/*
|
||||
* This function used to open a raw TCP socket to the TeamSpeak voice port.
|
||||
* That transport is not TeamSpeak's client protocol and must not be used for
|
||||
* reachability measurements. Keep the aggregation logic above independent of
|
||||
* the connection setup so admin tests can supply a real protocol probe.
|
||||
*/
|
||||
export async function pingTeamSpeak(
|
||||
probe: () => Promise<TeamSpeakPingAttempt>,
|
||||
options: { attempts?: number } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
return collectTeamSpeakPings(probe, options);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import { SessionManager, type ManagedSession, type SessionTeardownReason } from
|
||||
import { parseClientCommand, type ClientCommand } from "./voice-protocol.js";
|
||||
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js";
|
||||
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioStats, type WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
import { pingTeamSpeakPort } from "./network-probe.js";
|
||||
import { pingTeamSpeakSession } from "./network-probe.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
@@ -873,7 +873,9 @@ async function handleCommand(
|
||||
const now = Date.now();
|
||||
if (now - entry.lastLatencyProbeAt < 150) return;
|
||||
entry.lastLatencyProbeAt = now;
|
||||
const result = await pingTeamSpeakPort(entry.target);
|
||||
const result = await pingTeamSpeakSession(
|
||||
(request, timeoutMs) => entry.tsClient.execCommandWithResponse(request, timeoutMs),
|
||||
);
|
||||
sendJson({
|
||||
type: "latencyPong",
|
||||
sequence,
|
||||
|
||||
Reference in new issue
Block a user