Merge pull request #35 from LainHE/fix/voice-session-connect-window-upstream

fix(voice): never swallow a TeamSpeak drop while the session is settling
This commit is contained in:
ILLUSIA authored and GitHub committed 2026-10-16 19:33:15 +08:00
commit a9f5a47163
2 files changed
+152 -13

No files matched your search

@@ -85,6 +85,26 @@ async function fixture(t: TestContext, overrides: {
return { bridge, sdk, socket, messages, entries, wss };
}
function messageTypes(messages: Array<{ data: Buffer; binary: boolean }>): string[] {
return messages
.filter(message => !message.binary)
.map(message => (JSON.parse(message.data.toString()) as { type: string }).type);
}
function waitForMessage<T extends Record<string, unknown>>(socket: WebSocket, type: string): Promise<T> {
return new Promise(resolve => {
socket.on("message", (data, binary) => {
if (binary) return;
const message = JSON.parse(data.toString()) as { type?: string };
if (message.type === type) resolve(message as unknown as T);
});
});
}
// The native Opus codec is unavailable in some environments. These tests only
// exercise gateway wiring, so the encoder is stubbed out.
const stubEncoder = () => ({ encode: () => Buffer.alloc(0), dispose: () => {} });
test("a TeamSpeak constructor failure releases the admitted gateway slot", { timeout: 5_000 }, async t => {
const f = await fixture(t, { createTeamSpeakClient() { throw new Error("Identity initialization failed"); } });
if (f.socket.readyState !== WebSocket.CLOSED) await once(f.socket, "close");
@@ -127,6 +147,77 @@ test("server identity lookup waits until the directory sync publishes the connec
assert.ok(f.bridge.getActiveCount() > 0);
});
test("a TeamSpeak drop before the directory sync fails the connection instead of stalling", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
waitForFirstMessage: false,
createEncoder: stubEncoder,
configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; },
});
while (!f.sdk.connectCalls) await nextTurn();
await nextTurn();
// The session is past authentication, but `connected` was never published.
assert.deepEqual(messageTypes(f.messages), []);
const failure = waitForMessage<{ code: string }>(f.socket, "connectionFailed");
f.sdk.emit("disconnected");
assert.ok((await failure).code.length > 0);
await nextTurn();
assert.equal(f.bridge.getActiveCount(), 0);
});
test("a kick before the directory sync is reported instead of leaving the session alive", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
waitForFirstMessage: false,
createEncoder: stubEncoder,
configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; },
});
while (!f.sdk.connectCalls) await nextTurn();
await nextTurn();
assert.deepEqual(messageTypes(f.messages), []);
const failure = waitForMessage<{ code: string; detail?: string }>(f.socket, "connectionFailed");
f.sdk.emit("kicked", normalizeTeamSpeakKickedReason("Removed by operator", 4));
const message = await failure;
assert.equal(message.code, "KICKED");
assert.match(message.detail ?? "", /Removed by operator/);
await nextTurn();
assert.equal(f.bridge.getActiveCount(), 0);
});
test("a drop during a reconnect handshake resumes recovery instead of stalling in syncing", { timeout: 15_000 }, async t => {
const f = await fixture(t, {
createEncoder: stubEncoder,
configureSdk(sdk) {
let connects = 0;
sdk.connect = async () => {
sdk.connectCalls += 1;
sdk.disconnected = false;
connects += 1;
// Only the first handshake publishes the directory, so the reconnect
// attempt parks in `syncing` the way a slow server would.
if (connects === 1) sdk.emit("directorySnapshot", sdk.directory);
};
},
});
assert.ok(messageTypes(f.messages).includes("connected"));
const firstReconnect = waitForMessage<{ attempt: number }>(f.socket, "reconnecting");
f.sdk.emit("disconnected");
assert.equal((await firstReconnect).attempt, 1);
// Wait for the retry handshake to reach `syncing` without republishing `connected`.
while (f.sdk.connectCalls < 2) await nextTurn();
await nextTurn();
await nextTurn();
assert.ok(!messageTypes(f.messages).includes("reconnected"));
const secondReconnect = waitForMessage<{ attempt: number }>(f.socket, "reconnecting");
f.sdk.emit("disconnected");
assert.equal((await secondReconnect).attempt, 2);
assert.ok(f.bridge.getActiveCount() > 0);
});
test("a codec disposal failure cannot abandon TeamSpeak or the browser socket", { timeout: 5_000 }, async t => {
const encoder = new OpusEncoder(48000, 1);
t.mock.method(encoder, "dispose", () => { throw new Error("Codec already disposed"); });
+61 -13
View File
@@ -251,6 +251,11 @@ export class VoiceBridge {
let initialStateSent = false;
let serverInfoGeneration = 0;
let hasConnectedOnce = false;
// `connected` is only published once the directory sync has landed (see
// `sendInitialState`), so the session can already be past authentication
// while `hasConnectedOnce` is still false. A transport drop inside that
// gap must be handled rather than swallowed.
const isSettling = () => session.state === "authenticating" || session.state === "syncing";
let reconnectStartedAt = 0;
let reconnectAttempt = 0;
const addServerEvent = (kind: ServerEvent["kind"], message: string) => {
@@ -350,6 +355,28 @@ export class VoiceBridge {
void this.teardown(entryId, "teamSpeak-connect-failed");
};
const failConnect = (normalized: ReturnType<typeof normalizeTeamSpeakError>) => {
// A dead transport can report itself twice -- once as a `disconnected`
// event and once as a rejected `connect()`. Report and tear down once.
if (session.state === "failed" || session.state === "disconnecting" || session.state === "idle") return;
if (entry!.reconnectTimer) {
clearTimeout(entry!.reconnectTimer);
entry!.reconnectTimer = null;
}
try {
session.transition("failed");
} catch { /* teardown below remains authoritative */ }
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
const failureDetail = publicFailureDetail(normalized);
entry!.connectionFailureCode = failureCode;
// Send the structured failure before closing. Some browsers and reverse
// proxies do not preserve a WebSocket close reason, which would
// otherwise collapse every failure into a generic message.
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode);
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)) {
@@ -397,7 +424,6 @@ export class VoiceBridge {
} catch (error: unknown) {
const normalized = normalizeTeamSpeakError(error);
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
const failureDetail = publicFailureDetail(normalized);
entry!.connectionFailureCode = failureCode;
this.logger.warn({
code: failureCode,
@@ -409,15 +435,7 @@ export class VoiceBridge {
attempt: reconnectAttempt,
}, "TS connect failed");
if (!isReconnect) {
try {
if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed");
} catch { /* teardown below remains authoritative */ }
// Send the structured failure before closing. Some browsers and
// reverse proxies do not preserve a WebSocket close reason, which
// would otherwise collapse every failure into a generic message.
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode);
void this.teardown(entryId, "teamSpeak-connect-failed");
failConnect(normalized);
return;
}
if (isReconnect && isRecoverable(normalized)) {
@@ -451,7 +469,11 @@ export class VoiceBridge {
onKick: kick => {
// A transport drop may arrive first and already start recovery. A
// subsequent kick is still terminal and must cancel that recovery.
if (!hasConnectedOnce) return;
// A kick that lands before the session ever settled in (during the
// first connect or a reconnect handshake) is terminal too: without
// this the client would sit on the connecting screen while the
// gateway kept the dead session alive.
if (!hasConnectedOnce && !isSettling()) return;
resetDirectoryForReconnect();
const failureCode = clientConnectionFailureCode(kick, serverPassword);
const failureDetail = publicFailureDetail(kick);
@@ -461,10 +483,36 @@ export class VoiceBridge {
void this.teardown(entryId, "teamSpeak-kicked");
},
onDisconnect: error => {
if (!hasConnectedOnce || session.state !== "connected") return;
const normalized = error ? normalizeTeamSpeakError(error) : null;
if (isSettling()) {
// `connected` was never published, so there is no live session to
// interrupt -- but staying in `syncing` would leave the client on
// the connecting screen with no recovery scheduled.
if (!hasConnectedOnce) {
this.logger.warn({
entryId,
normalizedCode: normalized?.code,
...(normalized ? { failureDetail: describeTeamSpeakError(normalized) } : {}),
}, "TeamSpeak connection lost before the session became usable");
failConnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection lost during startup")));
return;
}
// A reconnect attempt dropped mid-handshake. Detach the dead
// transport and fall back into the recovery loop rather than
// stalling in `syncing`.
resetDirectoryForReconnect();
try {
session.transition("reconnecting");
} catch {
failReconnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection lost during reconnect")));
return;
}
scheduleReconnect(normalized);
return;
}
if (session.state !== "connected") return;
this.screenShares.removePeer(entryId);
resetDirectoryForReconnect();
const normalized = error ? normalizeTeamSpeakError(error) : null;
sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) });
scheduleReconnect(normalized);
},