M003: add TeamSpeak reconnect recovery

This commit is contained in:
illusia committed 2026-09-01 16:59:48 +08:00
1 parent 8c7a940de5
commit 3cca211ae9
10 files changed
+362 -98

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
import type { WebSpeakError } from "../errors.js";
export const RECONNECT_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000, 30_000] as const;
export const RECONNECT_WINDOW_MS = 5 * 60_000;
export function reconnectDelayMs(attempt: number, random = Math.random): number {
const safeAttempt = Math.max(1, Math.floor(attempt));
const base = RECONNECT_DELAYS_MS[Math.min(safeAttempt, RECONNECT_DELAYS_MS.length) - 1] ?? RECONNECT_DELAYS_MS.at(-1)!;
const jitter = Math.round(base * ((random() * 0.2) - 0.1));
return Math.max(250, base + jitter);
}
export function reconnectWindowOpen(startedAt: number, now = Date.now()): boolean {
return now - startedAt < RECONNECT_WINDOW_MS;
}
export function isRecoverable(error: WebSpeakError | null): boolean {
return error?.retryable ?? true;
}
+3 -3
View File
@@ -23,9 +23,9 @@ export type SessionTeardownReason =
const ALLOWED_TRANSITIONS: Record<ConnectionState, readonly ConnectionState[]> = {
idle: ["connecting", "disconnecting"],
connecting: ["authenticating", "failed", "disconnecting"],
authenticating: ["syncing", "failed", "disconnecting"],
syncing: ["connected", "failed", "disconnecting"],
connecting: ["authenticating", "reconnecting", "failed", "disconnecting"],
authenticating: ["syncing", "reconnecting", "failed", "disconnecting"],
syncing: ["connected", "reconnecting", "failed", "disconnecting"],
connected: ["interrupted", "failed", "disconnecting"],
interrupted: ["reconnecting", "failed", "disconnecting"],
reconnecting: ["connecting", "failed", "disconnecting"],
+3 -1
View File
@@ -73,6 +73,7 @@ export interface TeamSpeakAdapterOptions {
*/
export class TeamSpeakAdapter {
readonly client: TeamSpeakClient;
readonly identity: Identity;
private detectedProtocol: TeamSpeakProtocol | null = null;
constructor(
@@ -80,6 +81,7 @@ export class TeamSpeakAdapter {
private readonly logger: Logger,
private readonly protocolCache: EndpointProtocolCache = endpointProtocolCache,
) {
this.identity = options.identity ?? generateIdentity(8);
const clientOptions: ClientOptions = {
serverPassword: options.serverPassword,
defaultChannel: options.defaultChannel,
@@ -92,7 +94,7 @@ export class TeamSpeakAdapter {
},
};
this.client = new TeamSpeakClient(
options.identity ?? generateIdentity(8),
this.identity,
formatTeamSpeakTarget(options.target),
options.nickname,
clientOptions,
+96 -58
View File
@@ -2,6 +2,8 @@ import { EventEmitter } from "node:events";
import {
Client as TS3FullClient,
clientMove as tsClientMove,
generateIdentity,
type Identity,
type VoiceData,
type ChannelInfo,
type ClientInfo,
@@ -16,6 +18,7 @@ export interface TSClientOptions {
serverPassword?: string;
defaultChannel?: string;
channelPassword?: string;
identity?: Identity;
}
export interface TSVoiceData {
@@ -33,79 +36,42 @@ export class TSClient extends EventEmitter {
private client: TS3FullClient | null = null;
private adapter: TeamSpeakAdapter | null = null;
private logger: Logger;
private readonly identity: Identity;
private clientId = 0;
private connected = false;
private preferredChannelId = 0n;
constructor(private options: TSClientOptions, logger: Logger) {
super();
this.logger = logger.child({ nickname: options.nickname });
this.identity = options.identity ?? generateIdentity(8);
}
async connect(): Promise<void> {
this.adapter = new TeamSpeakAdapter({
target: this.options.target,
nickname: this.options.nickname,
serverPassword: this.options.serverPassword,
defaultChannel: this.options.defaultChannel,
channelPassword: this.options.channelPassword,
}, this.logger);
this.client = this.adapter.client;
if (!this.adapter || !this.client) {
this.adapter = new TeamSpeakAdapter({
target: this.options.target,
nickname: this.options.nickname,
identity: this.identity,
serverPassword: this.options.serverPassword,
defaultChannel: this.options.defaultChannel,
channelPassword: this.options.channelPassword,
}, this.logger);
this.client = this.adapter.client;
this.attachClientListeners(this.client);
}
const adapter = this.adapter;
const client = this.client;
this.client.on("voiceData", (data: VoiceData) => {
this.emit("voiceData", {
clientId: data.clientId,
codec: data.codec,
data: Buffer.from(data.data),
} as TSVoiceData);
});
await adapter.connect();
// The SDK patch exposes the directory that TeamSpeak sends during the
// normal client welcome sequence. This is the same data a native client
// receives and does not require channellist/clientlist permissions.
(this.client as unknown as {
on(event: "directorySnapshot", handler: (snapshot: TSDirectorySnapshot) => void): unknown;
}).on("directorySnapshot", (snapshot) => {
this.emit("directorySnapshot", snapshot);
});
this.client.on("textMessage", (msg) => {
this.emit("textMessage", {
invokerName: msg.invokerName,
invokerId: msg.invokerID,
invokerUid: msg.invokerUID,
message: msg.message,
targetMode: msg.targetMode,
});
});
this.client.on("disconnected", (err) => {
this.logger.warn({ err: err?.message }, "Disconnected from TS");
this.connected = false;
this.clientId = 0;
this.emit("disconnected");
});
this.client.on("clientEnter", (info) => {
this.emit("clientEnter", info);
});
this.client.on("clientLeave", (info) => {
this.emit("clientLeave", info);
});
this.client.on("clientMoved", (info) => {
this.emit("clientMoved", info);
});
await this.adapter.connect();
this.clientId = this.client.clientID();
this.clientId = client.clientID();
try {
// A native TeamSpeak client subscribes to the complete channel tree
// after the welcome sequence. Without this command the server only
// exposes members in the current channel, so users disappear as soon as
// they move elsewhere even though both clients are on the same server.
await this.client.execCommand("channelsubscribeall", 5000);
await client.execCommand("channelsubscribeall", 5000);
} catch (error: unknown) {
this.logger.warn({
err: error instanceof Error ? error.message : String(error),
@@ -116,12 +82,79 @@ export class TSClient extends EventEmitter {
// contains members from every subscribed channel.
await new Promise<void>((resolve) => setImmediate(resolve));
await new Promise<void>((resolve) => setImmediate(resolve));
const connectedChannelId = client.channelID();
if (this.preferredChannelId === 0n) {
this.preferredChannelId = connectedChannelId;
} else if (connectedChannelId !== this.preferredChannelId) {
try {
await tsClientMove(client, this.clientId, this.preferredChannelId);
} catch (error: unknown) {
// The old channel may have been deleted or become inaccessible. The
// SDK has already left us in the server/default channel, which is the
// safe fallback required by the reconnect contract.
this.logger.info({
channelId: this.preferredChannelId.toString(),
err: error instanceof Error ? error.message : String(error),
}, "Previous TeamSpeak channel could not be restored");
this.preferredChannelId = client.channelID();
}
}
this.connected = true;
this.logger.info({ clientId: this.clientId }, "Connected to TeamSpeak");
this.emit("connected", this.clientId);
}
private attachClientListeners(client: TS3FullClient): void {
client.on("voiceData", (data: VoiceData) => {
this.emit("voiceData", {
clientId: data.clientId,
codec: data.codec,
data: Buffer.from(data.data),
} as TSVoiceData);
});
// The SDK patch exposes the directory that TeamSpeak sends during the
// normal client welcome sequence. This is the same data a native client
// receives and does not require channellist/clientlist permissions.
(client as unknown as {
on(event: "directorySnapshot", handler: (snapshot: TSDirectorySnapshot) => void): unknown;
}).on("directorySnapshot", (snapshot) => {
this.emit("directorySnapshot", snapshot);
});
client.on("textMessage", (msg) => {
this.emit("textMessage", {
invokerName: msg.invokerName,
invokerId: msg.invokerID,
invokerUid: msg.invokerUID,
message: msg.message,
targetMode: msg.targetMode,
});
});
client.on("disconnected", (err) => {
this.logger.warn({ err: err?.message }, "Disconnected from TS");
this.connected = false;
this.clientId = 0;
this.emit("disconnected", err);
});
client.on("clientEnter", (info) => {
this.emit("clientEnter", info);
});
client.on("clientLeave", (info) => {
this.emit("clientLeave", info);
});
client.on("clientMoved", (info) => {
if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID;
this.emit("clientMoved", info);
});
}
sendVoice(data: Buffer, codec: number = 4): void {
if (!this.client || !this.connected) return;
this.client.sendVoice(data, codec);
@@ -139,8 +172,9 @@ export class TSClient extends EventEmitter {
}
async switchChannel(channelId: bigint, password?: string): Promise<void> {
if (!this.client) return;
if (!this.client || !this.connected) return;
await tsClientMove(this.client, this.clientId, channelId, password);
this.preferredChannelId = channelId;
}
getClientId(): number {
@@ -154,6 +188,10 @@ export class TSClient extends EventEmitter {
return this.adapter?.protocol ?? null;
}
getIdentityString(): string {
return this.identity.toString();
}
getChannelId(): bigint {
if (!this.client) return 0n;
const sdkClient = this.client as unknown as { channelID?: () => bigint };
+114 -28
View File
@@ -9,6 +9,7 @@ import { formatTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak
import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js";
import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js";
import { parseClientCommand, type ClientCommand } from "./voice-protocol.js";
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
@@ -38,6 +39,7 @@ interface WebClientEntry {
members: Map<number, ChannelMember>;
opusEncoder: { encode(pcm: Buffer): Buffer } | null;
isAlive: boolean;
reconnectTimer: ReturnType<typeof setTimeout> | null;
}
export class VoiceBridge {
@@ -100,6 +102,7 @@ export class VoiceBridge {
members: new Map(),
opusEncoder: null,
isAlive: true,
reconnectTimer: null,
};
this.entries.set(entryId, entry);
try {
@@ -116,6 +119,9 @@ export class VoiceBridge {
let initialStateSent = false;
let audioReady = true;
let realtimeReady = false;
let hasConnectedOnce = false;
let reconnectStartedAt = 0;
let reconnectAttempt = 0;
const directory = new DirectorySynchronizer();
const sendJson = (message: Record<string, unknown>) => {
@@ -137,9 +143,106 @@ export class VoiceBridge {
const sendInitialState = () => {
if (initialStateSent || !tsReady || !directory.ready || !realtimeReady || !audioReady || session.state !== "syncing") return;
initialStateSent = true;
const wasReconnecting = hasConnectedOnce;
hasConnectedOnce = true;
reconnectAttempt = 0;
reconnectStartedAt = 0;
session.transition("connected");
sendJson({ type: "connected", tsClientId: selfId, members: Array.from(entry!.members.values()) });
sendJson({ type: "channelList", channels: entry!.channelTree });
if (wasReconnecting) sendJson({ type: "reconnected" });
};
const resetDirectoryForReconnect = () => {
tsReady = false;
initialStateSent = false;
selfId = 0;
selfChannelId = 0n;
directory.clear();
entry!.channelTree = [];
entry!.members.clear();
};
const failReconnect = (normalized: ReturnType<typeof normalizeTeamSpeakError>) => {
if (entry!.reconnectTimer) {
clearTimeout(entry!.reconnectTimer);
entry!.reconnectTimer = null;
}
try {
if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed");
} catch { /* teardown below remains authoritative */ }
sendJson({ type: "reconnectFailed", code: normalized.code });
void this.teardown(entryId, "teamSpeak-connect-failed");
};
const scheduleReconnect = (normalized: ReturnType<typeof normalizeTeamSpeakError> | null) => {
if (session.state === "disconnecting" || session.state === "idle" || session.state === "failed") return;
if (!isRecoverable(normalized)) {
failReconnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection failed")));
return;
}
const now = Date.now();
if (!reconnectStartedAt) reconnectStartedAt = now;
reconnectAttempt += 1;
if (!reconnectWindowOpen(reconnectStartedAt, now)) {
failReconnect(normalized ?? normalizeTeamSpeakError(new Error("Reconnect window expired")));
return;
}
if (session.state === "connected") session.transition("interrupted");
if (session.state === "interrupted") session.transition("reconnecting");
if (entry!.reconnectTimer) return;
const delayMs = reconnectDelayMs(reconnectAttempt);
sendJson({ type: "reconnecting", attempt: reconnectAttempt, delayMs });
entry!.reconnectTimer = setTimeout(() => {
entry!.reconnectTimer = null;
if (session.state !== "reconnecting") return;
try {
session.transition("connecting");
session.transition("authenticating");
} catch {
failReconnect(normalizeTeamSpeakError(new Error("Reconnect state initialization failed")));
return;
}
void connectTeamSpeak(true);
}, delayMs);
entry!.reconnectTimer.unref?.();
};
const connectTeamSpeak = async (isReconnect: boolean): Promise<void> => {
try {
await tsClient.connect();
if (session.state !== "authenticating") return;
session.transition("syncing");
tsReady = true;
selfId = tsClient.getClientId();
const sdkChannelId = tsClient.getChannelId();
if (sdkChannelId !== 0n) selfChannelId = sdkChannelId;
refreshDirectory();
if (selfId > 0 && !entry!.members.has(selfId)) {
directory.applyClientEnter({ id: selfId, nickname, channelID: selfChannelId, uid: "", type: 1, serverGroups: [] });
refreshDirectory();
}
sendInitialState();
} catch (error: unknown) {
const normalized = normalizeTeamSpeakError(error);
this.logger.error({ code: normalized.code, entryId, reconnect: isReconnect, attempt: reconnectAttempt }, "TS connect failed");
if (!isReconnect) {
try {
if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed");
} catch { /* teardown below remains authoritative */ }
if (ws.readyState === WebSocket.OPEN) ws.close(4003, normalized.code);
void this.teardown(entryId, "teamSpeak-connect-failed");
return;
}
if (isReconnect && isRecoverable(normalized)) {
try {
if (session.state !== "disconnecting" && session.state !== "idle") session.transition("reconnecting");
} catch { /* teardown below remains authoritative */ }
scheduleReconnect(normalized);
return;
}
failReconnect(normalized);
}
};
// Register every directory listener before connect(). Events emitted by
@@ -204,12 +307,12 @@ export class VoiceBridge {
});
});
tsClient.on("disconnected", () => {
if (session.state !== "disconnecting" && session.state !== "idle") {
try { session.transition("interrupted"); } catch { /* teardown below is authoritative */ }
sendJson({ type: "disconnected" });
void this.teardown(entryId, "teamSpeak-disconnect");
}
tsClient.on("disconnected", (error?: Error) => {
if (!hasConnectedOnce || session.state !== "connected") return;
resetDirectoryForReconnect();
const normalized = error ? normalizeTeamSpeakError(error) : null;
sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) });
scheduleReconnect(normalized);
});
ws.on("pong", () => { if (entry) entry.isAlive = true; });
@@ -259,28 +362,7 @@ export class VoiceBridge {
return;
}
tsClient.connect()
.then(() => {
if (session.state !== "authenticating") return;
session.transition("syncing");
tsReady = true;
selfId = tsClient.getClientId();
const sdkChannelId = tsClient.getChannelId();
if (sdkChannelId !== 0n) selfChannelId = sdkChannelId;
refreshDirectory();
if (selfId > 0 && !entry!.members.has(selfId)) {
directory.applyClientEnter({ id: selfId, nickname, channelID: selfChannelId, uid: "", type: 1, serverGroups: [] });
refreshDirectory();
}
sendInitialState();
})
.catch((error: Error) => {
const normalized = normalizeTeamSpeakError(error);
this.logger.error({ code: normalized.code, entryId }, "TS connect failed");
try { if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed"); } catch { /* cleanup below */ }
if (ws.readyState === WebSocket.OPEN) ws.close(4003, normalized.code);
void this.teardown(entryId, "teamSpeak-connect-failed");
});
void connectTeamSpeak(false);
});
this.wss.on("error", (error) => {
@@ -321,6 +403,10 @@ export class VoiceBridge {
private async cleanupEntry(entry: WebClientEntry, reason: SessionTeardownReason): Promise<void> {
if (this.entries.get(entry.id) === entry) this.entries.delete(entry.id);
if (entry.reconnectTimer) {
clearTimeout(entry.reconnectTimer);
entry.reconnectTimer = null;
}
entry.opusEncoder = null;
entry.channelTree = [];
entry.members.clear();