fix: harden long-video recovery and voice transport handling (#161)

This commit is contained in:
TIANYAO ZHANG committed 2026-10-04 01:27:52 +08:00
1 parent e5879ea106
commit 28c128d0c9
9 files changed
+1298 -114

No files matched your search

+295
View File
@@ -0,0 +1,295 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Client as SDKClient, type ResolvedAddr } from "@honeybbq/teamspeak-client";
import { Resolver } from "@honeybbq/teamspeak-client/discovery";
import { TS3Client, type TS3VoiceSendFailure } from "./client.js";
import type { TrackingVoiceEndpointResolver } from "./voice-endpoint.js";
import type { Logger } from "../logger.js";
type Failure = TS3VoiceSendFailure;
type Harness = { client: SDKClient | null; voiceFramesSent: number };
describe("TS3Client voice send failure lifecycle", () => {
let client: TS3Client;
let sdk: SDKClient;
let logger: Logger;
let records: Array<{ level: string; args: unknown[] }>;
beforeEach(async () => {
vi.useFakeTimers();
// Keep the real SDK object, logger bridge and event dispatch. Replace only
// its network handshake and explicit shutdown so no UDP socket is opened.
vi.spyOn(SDKClient.prototype, "connect").mockImplementation(async function (this: SDKClient) {
this.clid = 42;
this._markConnected();
});
vi.spyOn(SDKClient.prototype, "disconnect").mockImplementation(async function (this: SDKClient) {
this.handler.onClosed?.(null);
});
records = [];
const capture = (level: string) => (...args: unknown[]) => records.push({ level, args });
logger = { info: capture("info"), warn: capture("warn"), error: capture("error"), debug() {} } as unknown as Logger;
client = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "VoiceTest", serverProtocol: "ts3" }, logger);
await client.connect();
sdk = (client as unknown as Harness).client!;
});
afterEach(async () => {
client.disconnect();
await vi.advanceTimersByTimeAsync(0);
vi.restoreAllMocks();
vi.useRealTimers();
});
it.each([false, true])("reports a sanitized first failure after earlier accepted send=%s without throwing", (acceptedFirst) => {
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => {});
if (acceptedFirst) client.sendVoiceData(Buffer.from([1]));
const failures: Failure[] = [];
client.on("voiceSendFailure", event => failures.push(event));
send.mockImplementation(() => { throw Object.assign(new Error("https://user:password@host/?token=credential-secret"), { code: "ERR_SOCKET_DGRAM_NOT_RUNNING", spawnargs: ["credential-secret"] }); });
let result: unknown;
expect(() => { result = client.sendVoiceData(Buffer.from([2])); }).not.toThrow();
expect(result).toBe("retrying");
expect(failures).toEqual([{ code: "ERR_SOCKET_DGRAM_NOT_RUNNING", consecutiveFailures: 1, durationMs: 0 }]);
expect((client as unknown as Harness).voiceFramesSent).toBe(acceptedFirst ? 1 : 0);
expect(records.filter(record => record.level === "warn")).toHaveLength(1);
expect(JSON.stringify(records)).not.toContain("password");
expect(JSON.stringify(records)).not.toContain("credential-secret");
});
it.each([{ code: "credential-secret", message: "credential-secret" }, "credential-secret"])("omits untrusted error codes and primitive error text: %s", error => {
const failures: Failure[] = [];
client.on("voiceSendFailure", event => failures.push(event));
vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw error; });
client.sendVoiceData(Buffer.from([1]));
expect(failures).toEqual([{ consecutiveFailures: 1, durationMs: 0 }]);
expect(JSON.stringify(records)).not.toContain("credential-secret");
});
it("emits one recovery and cancels terminal failure when the next send succeeds", async () => {
const recovered: Failure[] = [];
const terminal: Failure[] = [];
client.on("voiceSendRecovered", event => recovered.push(event));
client.on("voiceSendFailed", event => terminal.push(event));
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw { code: "ENOBUFS" }; });
client.sendVoiceData(Buffer.from([1]));
await vi.advanceTimersByTimeAsync(20);
send.mockImplementation(() => {});
expect(client.sendVoiceData(Buffer.from([2]))).toBe("accepted");
client.sendVoiceData(Buffer.from([3]));
await vi.advanceTimersByTimeAsync(3000);
expect(recovered).toEqual([{ code: "ENOBUFS", consecutiveFailures: 1, durationMs: 20 }]);
expect(terminal).toEqual([]);
expect((client as unknown as Harness).voiceFramesSent).toBe(2);
});
it("bounds persistent failure reporting to one first event and one terminal event per burst", async () => {
const first: Failure[] = [];
const terminal: Failure[] = [];
client.on("voiceSendFailure", event => first.push(event));
client.on("voiceSendFailed", event => terminal.push(event));
vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw { code: "ERR_SOCKET_DGRAM_NOT_RUNNING" }; });
for (let i = 0; i < 100; i++) {
client.sendVoiceData(Buffer.from([1]));
await vi.advanceTimersByTimeAsync(20);
}
expect(first).toHaveLength(1);
expect(terminal).toEqual([{ code: "ERR_SOCKET_DGRAM_NOT_RUNNING", consecutiveFailures: 100, durationMs: 2000 }]);
for (let i = 0; i < 100; i++) expect(client.sendVoiceData(Buffer.from([1]))).toBe("failed");
await vi.advanceTimersByTimeAsync(10000);
expect(terminal).toHaveLength(1);
expect(records.filter(record => ["warn", "error"].includes(record.level)).length).toBeLessThanOrEqual(2);
expect((client as unknown as Harness).voiceFramesSent).toBe(0);
});
it("recovers after the terminal event and allows a fresh failure burst", async () => {
const first: Failure[] = [], recovered: Failure[] = [], terminal: Failure[] = [];
client.on("voiceSendFailure", event => first.push(event));
client.on("voiceSendRecovered", event => recovered.push(event));
client.on("voiceSendFailed", event => terminal.push(event));
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw { code: "EPIPE" }; });
client.sendVoiceData(Buffer.from([1]));
await vi.advanceTimersByTimeAsync(2000);
send.mockImplementation(() => {});
expect(client.sendVoiceData(Buffer.from([1]))).toBe("accepted");
send.mockImplementation(() => { throw { code: "EPIPE" }; });
client.sendVoiceData(Buffer.from([1]));
await vi.advanceTimersByTimeAsync(2000);
expect(first).toHaveLength(2);
expect(recovered).toHaveLength(1);
expect(terminal).toHaveLength(2);
});
it("cancels failure timers on explicit disconnect", async () => {
const terminal: Failure[] = [];
client.on("voiceSendFailed", event => terminal.push(event));
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => {});
client.sendVoiceData(Buffer.from([1]));
send.mockImplementation(() => { throw { code: "EPIPE" }; });
client.sendVoiceData(Buffer.from([1]));
client.disconnect();
expect(client.sendVoiceData(Buffer.from([1]))).toBe("unavailable");
await vi.advanceTimersByTimeAsync(3000);
expect(terminal).toEqual([]);
expect((client as unknown as Harness).voiceFramesSent).toBe(0);
});
it("cancels failure timers on SDK connection loss", async () => {
const terminal: Failure[] = [];
client.on("voiceSendFailed", event => terminal.push(event));
const send = vi.spyOn(sdk, "sendVoice").mockImplementation(() => {});
client.sendVoiceData(Buffer.from([1]));
send.mockImplementation(() => { throw { code: "EPIPE" }; });
client.sendVoiceData(Buffer.from([1]));
sdk.handler.onClosed?.(new Error("synthetic connection loss"));
await vi.advanceTimersByTimeAsync(3000);
expect(terminal).toEqual([]);
expect((client as unknown as Harness).voiceFramesSent).toBe(0);
send.mockClear();
client.sendVoiceData(Buffer.from([1]));
expect(send).not.toHaveBeenCalled();
});
it("does not revive a connection whose handshake was cancelled", async () => {
let finishHandshake!: () => void;
vi.spyOn(SDKClient.prototype, "connect").mockImplementationOnce(function (this: SDKClient) {
return new Promise<void>(resolve => {
finishHandshake = () => {
this.clid = 99;
this._markConnected();
resolve();
};
});
});
const connected = vi.fn();
client.on("connected", connected);
const pending = client.connect();
await Promise.resolve();
expect(finishHandshake).toBeTypeOf("function");
const connectingSdk = (client as unknown as Harness).client!;
const close = vi.spyOn(connectingSdk.handler, "close");
const send = vi.spyOn(connectingSdk, "sendVoice");
client.disconnect();
finishHandshake();
await pending;
await vi.advanceTimersByTimeAsync(0);
expect(client.getClientId()).toBe(0);
expect(connected).not.toHaveBeenCalled();
expect(close).toHaveBeenCalled();
client.sendVoiceData(Buffer.from([1]));
expect(send).not.toHaveBeenCalled();
});
it("ignores old SDK warnings and disconnect callbacks after replacement", async () => {
const terminal: Failure[] = [];
client.on("voiceSendFailed", event => terminal.push(event));
vi.spyOn(sdk, "sendVoice").mockImplementation(() => { throw { code: "EPIPE" }; });
client.sendVoiceData(Buffer.from([1]));
await client.connect();
// Old disconnect dispatch is queued; old socket callbacks may follow it.
const before = records.length;
sdk.logger.warn("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
await vi.advanceTimersByTimeAsync(3000);
expect(client.getClientId()).toBe(42);
expect(records.slice(before).filter(record => record.level === "warn")).toEqual([]);
expect(terminal).toEqual([]);
});
it("does not let an older named-channel lookup move the replacement connection", async () => {
client.disconnect();
await vi.advanceTimersByTimeAsync(0);
client = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "VoiceTest", serverProtocol: "ts3", defaultChannel: "Music" }, logger);
let nextClientId = 101;
vi.mocked(SDKClient.prototype.connect).mockImplementation(async function (this: SDKClient) {
this.clid = nextClientId++;
this._markConnected();
});
let finishOlderLookup!: (rows: Record<string, string>[]) => void;
vi.spyOn(SDKClient.prototype, "execCommandWithResponse").mockImplementation(function (this: SDKClient) {
if (this.clid === 101) return new Promise(resolve => { finishOlderLookup = resolve; });
return Promise.resolve([{ cid: "20", channel_name: "Music" }]);
});
const moves: Array<{ clientId: number; command: string }> = [];
vi.spyOn(SDKClient.prototype, "execCommand").mockImplementation(async function (this: SDKClient, command: string) {
moves.push({ clientId: this.clid, command });
});
const first = client.connect();
for (let i = 0; i < 8; i++) await Promise.resolve();
expect(finishOlderLookup).toBeTypeOf("function");
await client.connect();
finishOlderLookup([{ cid: "10", channel_name: "Music" }]);
await first;
expect(moves).toEqual([{ clientId: 102, command: "clientmove clid=102 cid=20" }]);
expect(records.filter(record => record.args[1] === "Joined channel").map(record => record.args[0])).toEqual([{ channelName: "Music", cid: "20" }]);
expect(client.getClientId()).toBe(102);
});
it("keeps the replacement endpoint when an older DNS resolution finishes last", async () => {
let finishOlderResolution!: (rows: ResolvedAddr[]) => void;
const row = (addr: string): ResolvedAddr => ({ addr, source: "test", expiry: new Date(0) });
vi.spyOn(Resolver.prototype, "resolve").mockImplementationOnce(() => new Promise(resolve => { finishOlderResolution = resolve; }))
.mockResolvedValue([row("192.0.2.2:9987")]);
let sequence = 0;
vi.mocked(SDKClient.prototype.connect).mockImplementation(async function (this: SDKClient) {
const clientId = 101 + sequence++;
const resolver = (client as unknown as { voiceEndpointResolver: TrackingVoiceEndpointResolver }).voiceEndpointResolver;
await resolver.resolve("voice.test:9987");
this.clid = clientId;
this._markConnected();
});
const first = client.connect();
for (let i = 0; i < 8; i++) await Promise.resolve();
expect(finishOlderResolution).toBeTypeOf("function");
await client.connect();
expect(client.getResolvedVoiceEndpoint()).toEqual({ host: "192.0.2.2", port: 9987 });
finishOlderResolution([row("192.0.2.1:9987")]);
await first;
expect(client.getClientId()).toBe(102);
expect(client.getResolvedVoiceEndpoint()).toEqual({ host: "192.0.2.2", port: 9987 });
});
it.each(["10", "Music"])("does not report an old %s channel move after connection replacement", async channel => {
vi.spyOn(SDKClient.prototype, "execCommandWithResponse").mockResolvedValue([{ cid: "10", channel_name: "Music" }]);
let finishMove!: () => void;
const move = vi.spyOn(sdk, "execCommand").mockImplementation(() => new Promise<void>(resolve => { finishMove = resolve; }));
const joining = client.joinChannel(channel);
for (let i = 0; i < 8; i++) await Promise.resolve();
expect(move).toHaveBeenCalledWith("clientmove clid=42 cid=10", 10000);
await client.connect();
finishMove();
await joining;
expect(records.filter(record => record.args[1] === "Joined channel")).toEqual([]);
});
it("does not report a stale channel lookup failure against the new connection", async () => {
let failLookup!: (error: Error) => void;
vi.spyOn(sdk, "execCommandWithResponse").mockImplementation(() => new Promise((_resolve, reject) => { failLookup = reject; }));
const joining = client.joinChannel("Music");
await client.connect();
failLookup(new Error("old credential-secret failure"));
await joining;
expect(records.filter(record => record.level === "error")).toEqual([]);
expect(JSON.stringify(records)).not.toContain("credential-secret");
});
it("keeps safe async UDP error detail while throttling without terminalizing it", async () => {
const terminal: Failure[] = [];
client.on("voiceSendFailed", event => terminal.push(event));
for (let i = 0; i < 100; i++) sdk.logger.warn("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
await vi.advanceTimersByTimeAsync(2000);
const warnings = records.filter(record => record.level === "warn");
expect(warnings).toHaveLength(2);
expect(warnings[0].args[0]).toMatchObject({ code: "ECONNREFUSED", count: 1 });
expect(warnings[1].args[0]).toMatchObject({ code: "ECONNREFUSED", count: 100 });
expect(JSON.stringify(records)).not.toContain("credential-secret");
expect(terminal).toEqual([]);
});
it("discards unsafe async UDP codes and cancels their summary on disconnect", async () => {
sdk.logger.warn("udp send error", { code: "credential-secret", message: "credential-secret" });
client.disconnect();
await vi.advanceTimersByTimeAsync(3000);
expect(records.filter(record => record.level === "warn").filter(record => String(record.args[1]).includes("udp send error"))).toHaveLength(1);
expect(JSON.stringify(records)).not.toContain("credential-secret");
});
});
+169 -62
View File
@@ -80,6 +80,35 @@ export interface TS3VoiceActivity {
clientUid?: string;
}
/** Send acceptance only: an accepted UDP call does not confirm delivery. */
export interface TS3VoiceSendFailure {
code?: string;
consecutiveFailures: number;
durationMs: number;
}
/** Sticky failure status lets playback stay paused when the terminal event
* already fired during another track or an idle URL lookup. */
export type TS3VoiceSendResult = "accepted" | "retrying" | "failed" | "unavailable";
const VOICE_SEND_FAILURE_TIMEOUT_MS = 2_000;
const SAFE_SOCKET_ERROR_CODES = new Set([
"ERR_SOCKET_DGRAM_NOT_RUNNING", "ERR_SOCKET_DGRAM_NOT_CONNECTED",
"EPIPE", "ENOBUFS", "ECONNREFUSED", "ECONNRESET", "EHOSTUNREACH",
"ENETUNREACH", "ENETDOWN", "EACCES", "EPERM", "EINVAL", "EMSGSIZE",
"EAGAIN", "ENOTCONN", "EBADF",
]);
function safeSocketErrorCode(error: unknown): string | undefined {
try {
if (!error || typeof error !== "object") return undefined;
const code = (error as { code?: unknown }).code;
return typeof code === "string" && SAFE_SOCKET_ERROR_CODES.has(code) ? code : undefined;
} catch {
return undefined;
}
}
// Command notifications and UDP voice packets can be reordered in flight.
// Retain a leaving client's UID briefly so its final packet is still
// attributable; a new clientEnter for the same id cancels and overwrites it.
@@ -117,7 +146,10 @@ export class TS3Client extends EventEmitter {
private detectedProtocol: ServerProtocol = "unknown";
private httpQuery: TS6HttpQuery | null = null;
private udpErrorTimer: ReturnType<typeof setTimeout> | null = null;
private readonly voiceEndpointResolver = new TrackingVoiceEndpointResolver();
private connectionGeneration = 0;
private voiceFailureTimer: ReturnType<typeof setTimeout> | null = null;
private voiceFailure: { code?: string; consecutiveFailures: number; startedAt: number } | null = null;
private voiceEndpointResolver = new TrackingVoiceEndpointResolver();
constructor(private options: TS3ClientOptions, logger: Logger) {
super();
@@ -142,18 +174,25 @@ export class TS3Client extends EventEmitter {
}
async connect(): Promise<void> {
this.voiceEndpointResolver.reset();
const generation = ++this.connectionGeneration;
this.resetVoiceSendState();
this.disconnecting = false;
const voiceEndpointResolver = new TrackingVoiceEndpointResolver();
this.voiceEndpointResolver = voiceEndpointResolver;
this.clearVisibleClientUids();
this.httpQuery = null;
// Clean up any existing connection before creating a new one
if (this.client) {
const previousClient = this.client;
this.client = null;
this.clientId = 0;
if (previousClient) {
this.logger.info("Cleaning up previous connection before reconnecting");
try {
await this.client.disconnect();
await previousClient.disconnect();
} catch {
// Ignore errors during cleanup
}
this.client = null;
this.clientId = 0;
if (generation !== this.connectionGeneration) return;
}
const addr = `${this.options.host}:${this.options.port}`;
@@ -173,6 +212,7 @@ export class TS3Client extends EventEmitter {
3000,
{ ts3QueryPort: 10011, ts6HttpPort: 10080 },
);
if (generation !== this.connectionGeneration) return;
this.detectedProtocol = detection.protocol;
if (this.detectedProtocol === "unknown") {
this.logger.warn(
@@ -198,66 +238,65 @@ export class TS3Client extends EventEmitter {
});
}
// Guard against calling connect() while already connected.
// Save detectedProtocol first because disconnect() resets it.
if (this.client) {
this.logger.warn("connect() called while already connected, disconnecting first");
const savedProtocol = this.detectedProtocol;
const savedHttpQuery = this.httpQuery;
this.disconnect();
this.detectedProtocol = savedProtocol;
this.httpQuery = savedHttpQuery;
// Give the old client a moment to tear down
await new Promise((r) => setTimeout(r, 100));
}
this.logger.info(
{ addr, protocol: this.detectedProtocol },
"Connecting to TeamSpeak server (full client protocol)",
);
// Throttle repeated "udp send error" warnings (fires every 20ms during playback if UDP breaks)
let sdkClient: TS3FullClient | null = null;
const isCurrent = () => sdkClient !== null && this.client === sdkClient &&
this.connectionGeneration === generation && !this.disconnecting;
let udpErrorCount = 0;
let udpErrorCode: string | undefined;
const throttledWarn = (msg: string, ...args: unknown[]) => {
if (!isCurrent()) return;
if (typeof msg === "string" && msg.includes("udp send error")) {
udpErrorCount++;
udpErrorCode = args.map(safeSocketErrorCode).find(code => code !== undefined) ?? udpErrorCode;
if (udpErrorCount === 1) {
this.logger.warn(msg);
this.logger.warn({ ...(udpErrorCode ? { code: udpErrorCode } : {}), count: 1 }, "udp send error");
// After 2 seconds, log a summary and reset.
// Clear any previous timer to avoid leaking it.
if (this.udpErrorTimer) clearTimeout(this.udpErrorTimer);
this.udpErrorTimer = setTimeout(() => {
if (!isCurrent()) return;
if (udpErrorCount > 1) {
this.logger.warn(`udp send error (repeated ${udpErrorCount} times, connection may be lost)`);
this.logger.warn({ ...(udpErrorCode ? { code: udpErrorCode } : {}), count: udpErrorCount }, "Repeated udp send error; connection may be lost");
}
udpErrorCount = 0;
udpErrorCode = undefined;
this.udpErrorTimer = null;
}, 2000);
this.udpErrorTimer.unref?.();
}
return;
}
this.logger.warn(msg);
};
this.client = new TS3FullClient(this.identity, addr, this.options.nickname, {
sdkClient = new TS3FullClient(this.identity, addr, this.options.nickname, {
// Forward server password to the protocol library so it can be
// included in clientinit for password-protected servers
serverPassword: this.options.serverPassword,
resolver: this.voiceEndpointResolver,
resolver: voiceEndpointResolver,
logger: {
debug: (msg) => this.logger.debug(msg),
info: (msg) => this.logger.info(msg),
debug: (msg) => { if (isCurrent()) this.logger.debug(msg); },
info: (msg) => { if (isCurrent()) this.logger.info(msg); },
warn: throttledWarn,
error: (msg) => this.logger.error(msg),
error: (msg) => { if (isCurrent()) this.logger.error(msg); },
},
});
this.client = sdkClient;
this.client.on("textMessage", (msg: TextMessage) => {
sdkClient.on("textMessage", (msg: TextMessage) => {
if (!isCurrent()) return;
if (msg.invokerID === this.clientId) return;
this.emit("textMessage", toTS3TextMessage(msg));
});
this.client.on("voiceData", (voice: VoiceData) => {
sdkClient.on("voiceData", (voice: VoiceData) => {
if (!isCurrent()) return;
// The library normally suppresses our own packets; retain the explicit
// guard so a future protocol change cannot make a bot duck itself.
if (voice.clientId === this.clientId) return;
@@ -270,14 +309,20 @@ export class TS3Client extends EventEmitter {
this.emit("voiceActivity", activity);
});
this.client.on("disconnected", (err) => {
this.logger.warn({ err: err?.message }, "Connection closed");
sdkClient.on("disconnected", (err) => {
if (!isCurrent()) return;
const code = safeSocketErrorCode(err);
this.logger.warn(code ? { code } : {}, "Connection closed");
++this.connectionGeneration;
this.resetVoiceSendState();
this.client = null;
this.clientId = 0;
this.clearVisibleClientUids();
this.emit("disconnected");
});
this.client.on("clientEnter", (info: ClientInfo) => {
sdkClient.on("clientEnter", (info: ClientInfo) => {
if (!isCurrent()) return;
this.rememberVisibleClientUid(info.id, info.uid);
this.logger.debug(
{ nickname: info.nickname, id: info.id },
@@ -286,13 +331,15 @@ export class TS3Client extends EventEmitter {
this.emit("clientEnter", info);
});
this.client.on("clientLeave", (ev: ClientLeftViewEvent) => {
sdkClient.on("clientLeave", (ev: ClientLeftViewEvent) => {
if (!isCurrent()) return;
this.releaseVisibleClientUid(ev.id);
this.logger.debug({ id: ev.id }, "Client left");
this.emit("clientLeave", ev);
});
this.client.on("clientMoved", (ev: ClientMovedEvent) => {
sdkClient.on("clientMoved", (ev: ClientMovedEvent) => {
if (!isCurrent()) return;
this.logger.debug(
{ id: ev.id, targetChannelID: ev.targetChannelID.toString() },
"Client moved"
@@ -300,15 +347,22 @@ export class TS3Client extends EventEmitter {
this.emit("clientMoved", ev);
});
await this.client.connect();
await sdkClient.connect();
if (!isCurrent()) {
// DNS/socket setup may finish after disconnect() closed the transport.
// Close it again without waiting on command replies from a stale session.
sdkClient.handler.close();
return;
}
// Note: @honeybbq/teamspeak-client 0.2.x ships a universal clientinit
// (client_version "3.?.? [Build: 5680278000]" + matching signature)
// that works against both TS3 and TS6 servers. The old 3.6.2 monkey-
// patch on handler.sendPacket was removed when we bumped to 0.2.1 — it
// would have replaced the library's new correct version with a stale
// signature and made TS6 handshakes fail.
await this.client.waitConnected();
this.clientId = this.client.clientID();
await sdkClient.waitConnected();
if (!isCurrent()) return;
this.clientId = sdkClient.clientID();
this.voiceFramesSent = 0;
this.logger.info(
{ clientId: this.clientId, protocol: this.detectedProtocol },
@@ -325,25 +379,32 @@ export class TS3Client extends EventEmitter {
);
}
this.emit("connected");
if (isCurrent()) this.emit("connected");
}
async joinChannel(channelName: string, password?: string): Promise<void> {
if (!this.client) return;
const client = this.client;
if (!client || this.disconnecting) return;
const clientId = this.clientId;
const generation = this.connectionGeneration;
const isCurrent = () => this.client === client && this.clientId === clientId &&
this.connectionGeneration === generation && !this.disconnecting;
const isNumeric = /^\d+$/.test(channelName);
if (isNumeric) {
try {
await clientMove(this.client, this.clientId, BigInt(channelName), password);
await clientMove(client, clientId, BigInt(channelName), password);
if (!isCurrent()) return;
this.logger.info({ channelName }, "Joined channel");
} catch (err) {
this.logger.error({ err, channelName }, "Failed to join channel");
if (isCurrent()) this.logger.error({ err, channelName }, "Failed to join channel");
}
return;
}
try {
const channels = await listChannels(this.client);
const channels = await listChannels(client);
if (!isCurrent()) return;
const channel = channels.find((ch) => ch.name === channelName);
if (!channel) {
@@ -351,13 +412,14 @@ export class TS3Client extends EventEmitter {
return;
}
await clientMove(this.client, this.clientId, channel.id, password);
await clientMove(client, clientId, channel.id, password);
if (!isCurrent()) return;
this.logger.info(
{ channelName, cid: channel.id.toString() },
"Joined channel"
);
} catch (err) {
this.logger.error({ err, channelName }, "Failed to join channel");
if (isCurrent()) this.logger.error({ err, channelName }, "Failed to join channel");
}
}
@@ -454,19 +516,68 @@ export class TS3Client extends EventEmitter {
private voiceFramesSent = 0;
sendVoiceData(opusFrame: Buffer): void {
if (!this.client || this.disconnecting) return;
sendVoiceData(opusFrame: Buffer): TS3VoiceSendResult {
const client = this.client;
if (!client || this.disconnecting) return "unavailable";
try {
this.client.sendVoice(opusFrame, 5);
this.voiceFramesSent++;
if (this.voiceFramesSent === 1) {
this.logger.info({ opusBytes: opusFrame.length, clientId: this.clientId }, "First voice packet sent to TeamSpeak");
}
client.sendVoice(opusFrame, 5);
} catch (err) {
if (this.voiceFramesSent === 0) {
this.logger.error({ err }, "Failed to send first voice packet");
if (this.voiceFailure) {
this.voiceFailure.consecutiveFailures++;
this.voiceFailure.code = safeSocketErrorCode(err) ?? this.voiceFailure.code;
return this.voiceFailureTimer ? "retrying" : "failed";
}
const code = safeSocketErrorCode(err);
const failure = this.voiceFailure = {
...(code ? { code } : {}), consecutiveFailures: 1, startedAt: Date.now(),
};
const generation = this.connectionGeneration;
this.voiceFailureTimer = setTimeout(() => {
if (this.client !== client || this.connectionGeneration !== generation ||
this.disconnecting || this.voiceFailure !== failure) return;
this.voiceFailureTimer = null;
const event = this.voiceFailureDetails(failure);
this.logger.error(event, "Voice sends have failed continuously; pausing playback is required");
this.emit("voiceSendFailed", event);
}, VOICE_SEND_FAILURE_TIMEOUT_MS);
this.voiceFailureTimer.unref?.();
const event = this.voiceFailureDetails(failure);
this.logger.warn(event, "Voice send failed");
this.emit("voiceSendFailure", event);
return "retrying";
}
this.voiceFramesSent++;
if (this.voiceFramesSent === 1) {
this.logger.info({ opusBytes: opusFrame.length, clientId: this.clientId }, "First voice packet accepted by TeamSpeak client");
}
if (this.voiceFailure) {
const event = this.voiceFailureDetails(this.voiceFailure);
this.clearVoiceFailure();
this.logger.info(event, "Voice send recovered");
this.emit("voiceSendRecovered", event);
}
return "accepted";
}
private voiceFailureDetails(failure: NonNullable<TS3Client["voiceFailure"]>): TS3VoiceSendFailure {
return {
...(failure.code ? { code: failure.code } : {}),
consecutiveFailures: failure.consecutiveFailures,
durationMs: Math.max(0, Date.now() - failure.startedAt),
};
}
private clearVoiceFailure(): void {
if (this.voiceFailureTimer) clearTimeout(this.voiceFailureTimer);
this.voiceFailureTimer = null;
this.voiceFailure = null;
}
private resetVoiceSendState(): void {
this.clearVoiceFailure();
this.voiceFramesSent = 0;
if (this.udpErrorTimer) clearTimeout(this.udpErrorTimer);
this.udpErrorTimer = null;
}
getIdentityExport(): string {
@@ -524,24 +635,20 @@ export class TS3Client extends EventEmitter {
}
disconnect(): void {
if (this.client && !this.disconnecting) {
const generation = ++this.connectionGeneration;
this.resetVoiceSendState();
const client = this.client;
this.client = null;
if (client && !this.disconnecting) {
this.disconnecting = true;
const client = this.client;
client.disconnect().catch(() => {}).finally(() => {
if (this.client === client) {
this.client = null;
}
this.disconnecting = false;
if (generation === this.connectionGeneration) this.disconnecting = false;
});
}
this.clientId = 0;
this.clearVisibleClientUids();
this.httpQuery = null;
this.detectedProtocol = "unknown";
if (this.udpErrorTimer) {
clearTimeout(this.udpErrorTimer);
this.udpErrorTimer = null;
}
this.logger.info("Disconnected from TeamSpeak server");
}
}