fix: measure TeamSpeak latency over its protocol

This commit is contained in:
illusia committed 2026-09-06 14:04:41 +08:00
1 parent dcc52c4530
commit a295ff4b27
7 files changed
+167 -47

No files matched your search

+3
View File
@@ -10,6 +10,7 @@
- 增加可展开的网络性能面板,显示浏览器、WebSpeak 与 TeamSpeak 之间的延迟和丢包率。
- 管理员连接测试改用多次网络探测并显示丢包率。
- 统一中文、English、Deutsch 的旗帜代码语言菜单。
- 修复 TeamSpeak 使用 TCP 探测导致的误报丢包,并修正语言菜单异常留白。
### English
@@ -19,6 +20,7 @@
- Added an expandable network performance panel with latency and packet loss across the browser, WebSpeak, and TeamSpeak path.
- Updated the administrator connection test to use repeated reachability probes and report packet loss.
- Unified the Chinese, English, and German flag/code language menu.
- Fixed false packet-loss reports caused by probing the TeamSpeak UDP service with TCP, and corrected excess space in the language menu.
### Deutsch
@@ -28,6 +30,7 @@
- Aufklappbares Netzwerkleistungsfeld mit Latenz und Paketverlust zwischen Browser, WebSpeak und TeamSpeak ergänzt.
- Verbindungstest in der Administration auf wiederholte Erreichbarkeitsprüfungen mit Paketverlustanzeige umgestellt.
- Einheitliches Sprachmenü mit Flaggen und Sprachcodes für Chinesisch, Englisch und Deutsch ergänzt.
- Falsche Paketverlustmeldungen durch TCP-Prüfung des UDP-Dienstes behoben und übermäßigen Leerraum im Sprachmenü korrigiert.
## [0.1.6] — 2026-09-04
+3 -3
View File
@@ -130,7 +130,7 @@ WebSpeak 面向希望通过网页提供 TeamSpeak 语音服务的个人、社区
| 版本 | 日期 | 摘要 |
| --- | --- | --- |
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | 增加德语支持、Telegram 群组入口、网络性能面板和丢包率测试,优化语言菜单与桌面端音量控制,修复伴奏音量波动。 |
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | 增加德语支持、Telegram 群组入口、网络性能面板和丢包率测试,修复 TeamSpeak 探测误报、语言菜单留白与伴奏音量波动。 |
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | 新增桌面端伴奏、身份保持提醒和网站图标,并修复 WebRTC 下的成员独立音量。 |
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | 修复身份保持逻辑,优化主题切换按钮。 |
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | 修复 WebRTC 语音和频道聊天,优化管理页、日志与移动端布局。 |
@@ -268,7 +268,7 @@ WebSpeak is built for individuals, communities, and server operators who want to
| Version | Date | Summary |
| --- | --- | --- |
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Added German support, a Telegram community link, network performance and packet-loss checks; refined the language menu and desktop volume control; fixed accompaniment volume fluctuations. |
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Added German support, a Telegram community link, network performance and packet-loss checks; fixed false TeamSpeak probe results, language-menu spacing, and accompaniment volume fluctuations. |
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Added desktop accompaniment, remembered-identity guidance, and the site icon; fixed per-member volume under WebRTC. |
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Fixed identity persistence and refined the theme switch. |
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | Fixed WebRTC voice and channel chat; improved administration, logs, and mobile layouts. |
@@ -406,7 +406,7 @@ WebSpeak ist ein selbst gehosteter TeamSpeak-3-/TeamSpeak-6-Webclient und ein Sp
| Version | Datum | Zusammenfassung |
| --- | --- | --- |
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Deutsche Oberfläche, Telegram-Link, Netzwerkleistungs- und Paketverlustprüfung hinzugefügt; Sprachmenü und Desktop-Lautstärkeregler verbessert; Lautstärkeschwankungen bei Begleittönen behoben. |
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Deutsche Oberfläche, Telegram-Link sowie Netzwerk- und Paketverlustprüfung hinzugefügt; falsche TeamSpeak-Messungen, Sprachmenü-Leerraum und Begleitton-Schwankungen behoben. |
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Desktop-Begleitton, Hinweise zur Identität und Website-Symbol hinzugefügt; individuelle Lautstärke unter WebRTC korrigiert. |
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Identitätsspeicherung korrigiert und Designumschaltung verbessert. |
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | WebRTC und Kanalchat korrigiert; Administrationsseite, Protokolle und Mobilansicht verbessert. |
+21 -7
View File
@@ -7,7 +7,7 @@ import { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpea
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
import { probeTeamSpeak, TeamSpeakProbeError } from "../server/teamspeak-probe.js";
import { pingTeamSpeak } from "../server/network-probe.js";
import { collectTeamSpeakPings, type TeamSpeakPingAttempt } from "../server/network-probe.js";
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
@@ -164,16 +164,30 @@ export class AdminService {
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
}
try {
// The admin connection test is a reachability check. A TCP endpoint
// probe avoids creating a temporary TeamSpeak client and lets the UI
// report packet loss. Keep the injected TeamSpeak probe for tests and
// compatibility with callers that explicitly need protocol discovery.
// The admin connection test uses the real TeamSpeak client protocol.
// A raw TCP connect is not valid here because TeamSpeak voice/client
// traffic is UDP; it would report 100% loss while normal voice works.
// Keep the injected probe for tests and compatibility with callers that
// explicitly need protocol discovery.
if (this.probe === probeTeamSpeak) {
const result = await pingTeamSpeak(target, { attempts: 4 });
let lastServerName: string | null = null;
const result = await collectTeamSpeakPings(async (): Promise<TeamSpeakPingAttempt> => {
try {
const probe = await this.probe(target, password, this.logger);
lastServerName = probe.serverName;
return { ok: true, latencyMs: probe.latencyMs };
} catch (error: unknown) {
return {
ok: false,
latencyMs: null,
errorCode: error instanceof TeamSpeakProbeError ? error.code : "INTERNAL_ERROR",
};
}
}, { attempts: 4 });
const publicResult = {
ok: result.ok,
latencyMs: result.latencyMs ?? 0,
serverName: null,
serverName: lastServerName,
requiresPassword: Boolean(password),
packetLossPercent: result.packetLossPercent,
attempts: result.attempts,
+78 -35
View File
@@ -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);
}
+4 -2
View File
@@ -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,
+51
View File
@@ -0,0 +1,51 @@
import assert from "node:assert/strict";
import test from "node:test";
import { collectTeamSpeakPings, pingTeamSpeakSession, summarizeTeamSpeakPings } from "../src/server/network-probe.js";
test("TeamSpeak latency probe uses the protocol command channel", async () => {
let command = "";
const result = await pingTeamSpeakSession(async (value) => {
command = value;
return [];
});
assert.equal(command, "version");
assert.equal(result.ok, true);
assert.equal(result.errorCode, undefined);
assert.equal(typeof result.latencyMs, "number");
});
test("TeamSpeak protocol probe classifies a timeout and aggregates packet loss", async () => {
const timeout = await pingTeamSpeakSession(async () => {
throw new Error("packet ack timeout");
});
assert.deepEqual(timeout, { ok: false, latencyMs: null, errorCode: "TIMEOUT" });
let calls = 0;
const result = await collectTeamSpeakPings(async () => {
calls += 1;
return calls === 2
? { ok: false, latencyMs: null, errorCode: "TIMEOUT" }
: { ok: true, latencyMs: calls };
}, { attempts: 4 });
assert.equal(calls, 4);
assert.equal(result.ok, true);
assert.equal(result.packetLossPercent, 25);
assert.equal(result.successfulAttempts, 3);
assert.deepEqual(result.samples, [1, 3, 4]);
});
test("TeamSpeak ping summary reports complete loss without fake latency", () => {
const result = summarizeTeamSpeakPings([
{ ok: false, latencyMs: null, errorCode: "UNREACHABLE" },
{ ok: false, latencyMs: null, errorCode: "UNREACHABLE" },
]);
assert.deepEqual(result, {
ok: false,
latencyMs: null,
packetLossPercent: 100,
attempts: 2,
successfulAttempts: 0,
samples: [],
errorCode: "UNREACHABLE",
});
});
+7
View File
@@ -153,9 +153,15 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
right: 0;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-auto-rows: minmax(38px, max-content);
align-items: start;
align-content: start;
gap: 3px;
width: 218px;
height: auto;
max-height: none;
padding: 7px;
overflow: visible;
background: #fff;
border: 1px solid #dce9e5;
border-radius: 13px;
@@ -166,6 +172,7 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
.language-option {
display: flex;
align-items: center;
align-self: start;
min-width: 0;
gap: 8px;
min-height: 38px;