mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-03 11:22:51 +08:00
fix: harden long-video recovery and voice transport handling (#161)
This commit is contained in:
1 parent
e5879ea106
commit
28c128d0c9
9 files changed
+1298
-114
No files matched your search
@@ -0,0 +1,393 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { BotInstance } from "./instance.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { PlayQueue } from "../audio/queue.js";
|
||||
import { ManagedVoiceClientRegistry } from "./managed-voice-clients.js";
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>(done => { resolve = done; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
async function flush() {
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
}
|
||||
|
||||
function makeBot() {
|
||||
const queue = new PlayQueue();
|
||||
queue.add({ id: "BV1example", name: "Long", artist: "A", album: "", coverUrl: "", platform: "bilibili", duration: 10_000, url: "old" });
|
||||
queue.playAt(0);
|
||||
const player = new EventEmitter() as any;
|
||||
player.state = "idle";
|
||||
player.sessionId = 1;
|
||||
player.elapsed = 1000;
|
||||
player.getState = AudioPlayer.prototype.getState;
|
||||
player.getPlaybackSessionId = AudioPlayer.prototype.getPlaybackSessionId;
|
||||
player.getElapsed = () => player.elapsed;
|
||||
player.getVolume = () => 50;
|
||||
player.pause = AudioPlayer.prototype.pause;
|
||||
player.resume = AudioPlayer.prototype.resume;
|
||||
player.play = vi.fn((_url: string, position: number) => { player.sessionId++; player.elapsed = position; player.state = "playing"; });
|
||||
player.stop = vi.fn(() => { player.sessionId++; player.state = "idle"; });
|
||||
const provider = { getSongUrl: vi.fn(async (): Promise<{ url: string } | null> => ({ url: "fresh" })) };
|
||||
const tsClient = new EventEmitter() as any;
|
||||
tsClient.getClientsInChannel = vi.fn(async () => [{ id: 1 }, { id: 2 }]);
|
||||
tsClient.getClientId = () => 1;
|
||||
tsClient.sendVoiceData = vi.fn();
|
||||
tsClient.connect = vi.fn(async () => { tsClient.emit("connected"); });
|
||||
tsClient.disconnect = vi.fn(() => { tsClient.emit("disconnected"); });
|
||||
tsClient.getResolvedVoiceEndpoint = () => null;
|
||||
const spotifyController = new EventEmitter() as any;
|
||||
spotifyController.stop = vi.fn();
|
||||
const bot = Object.assign(Object.create(BotInstance.prototype), {
|
||||
id: "bot", name: "Bot", queue, player, tsClient, provider, spotifyController,
|
||||
connected: true, disconnectEmitted: false, effectiveDuration: 10_000,
|
||||
streamRecovery: null, lifecycleGeneration: 0, occupancyRequest: 0,
|
||||
config: { autoPauseOnEmpty: true, idleTimeoutMinutes: 1 }, autoPaused: false,
|
||||
idleTimer: null, snapshotTimer: null, currentSourceIsSpotify: false,
|
||||
localProvider: {}, voiceDucking: { reset: vi.fn(), removeSpeaker: vi.fn() },
|
||||
managedVoiceClients: new ManagedVoiceClientRegistry(),
|
||||
configuredVoiceServerScope: { host: "localhost", voicePort: 9987 },
|
||||
profileManager: { onConnect: vi.fn(), onChannelMoved: vi.fn(async () => {}) },
|
||||
unregisterManagedVoiceClient: vi.fn(), registerManagedVoiceClient: vi.fn(),
|
||||
restoreQueueFromSnapshot: vi.fn(async () => {}), _startJellyfinReportPoller: vi.fn(),
|
||||
logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||||
emit: vi.fn(), getProviderFor: () => provider,
|
||||
playNext: vi.fn(async () => { const next = queue.next(); if (!next) queue.clear(); return !!next; }),
|
||||
}) as any;
|
||||
bot.setupPlayerEvents();
|
||||
bot.setupTsEvents();
|
||||
return bot;
|
||||
}
|
||||
|
||||
function cancel(bot: any, action: string) {
|
||||
if (action === "disconnect") bot.disconnect();
|
||||
else if (action === "stop") { bot.queue.clear(); bot.player.stop(); }
|
||||
else if (action === "skip") { if (!bot.queue.next()) bot.queue.clear(); bot.player.stop(); }
|
||||
else if (action === "replace") {
|
||||
bot.queue.clear();
|
||||
bot.queue.add({ id: "other", name: "Other", artist: "A", album: "", coverUrl: "", platform: "bilibili", duration: 10_000 });
|
||||
bot.queue.playAt(0);
|
||||
bot.player.play("replacement", 0);
|
||||
} else { bot.player.sessionId++; bot.player.state = "idle"; }
|
||||
}
|
||||
|
||||
beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }));
|
||||
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
|
||||
|
||||
describe("Bilibili recovery retries transient URL failures", () => {
|
||||
it("keeps the same queue and seek through a null lookup, then resumes after one second", async () => {
|
||||
const bot = makeBot();
|
||||
const song = bot.queue.current();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.queue.current()).toBe(song);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(999);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(bot.player.play).toHaveBeenCalledWith("fresh", 1000, 10_000);
|
||||
expect(bot.queue.current()).toBe(song);
|
||||
expect(bot.provider.getSongUrl.mock.calls.map((args: unknown[]) => args[0])).toEqual(["BV1example", "BV1example"]);
|
||||
expect(bot.streamRecovery.attempts).toBe(1);
|
||||
});
|
||||
|
||||
it("retries a throw and null at one and two seconds without logging the sensitive exception", async () => {
|
||||
const bot = makeBot();
|
||||
const secret = "SYNTHETIC_SIGNED_URL_AND_COOKIE";
|
||||
bot.provider.getSongUrl.mockRejectedValueOnce(new Error(`https://cdn.invalid/?token=${secret}`))
|
||||
.mockResolvedValueOnce(null).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1999);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(2);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(bot.player.play).toHaveBeenCalledWith("fresh", 1000, 10_000);
|
||||
const logs = JSON.stringify(bot.logger.warn.mock.calls, (_key, value) => value instanceof Error ? { message: value.message, stack: value.stack } : value);
|
||||
expect(logs).not.toContain(secret);
|
||||
expect(bot.logger.warn.mock.calls.map((args: any[]) => args[0])).toContainEqual(expect.objectContaining({
|
||||
platform: "bilibili", sessionId: 1, lookupAttempt: 1, reason: "lookup-error",
|
||||
}));
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["null", "throw"])("advances only after three exhausted %s lookups", async failure => {
|
||||
const bot = makeBot();
|
||||
if (failure === "null") bot.provider.getSongUrl.mockResolvedValue(null);
|
||||
else bot.provider.getSongUrl.mockRejectedValue(new Error("temporary"));
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(2999);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(3);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).toHaveBeenCalledTimes(1);
|
||||
expect(bot.queue.current()).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["skip", "stop", "replace", "restart", "disconnect"])("does not retry or advance after %s during backoff", async action => {
|
||||
const bot = makeBot();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
cancel(bot, action);
|
||||
bot.player.play.mockClear();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["skip", "stop", "replace", "restart", "disconnect"])("does not write a late retry result after %s", async action => {
|
||||
const bot = makeBot();
|
||||
const retry = deferred<{ url: string }>();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockReturnValueOnce(retry.promise);
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(2);
|
||||
cancel(bot, action);
|
||||
bot.player.play.mockClear();
|
||||
retry.resolve({ url: "stale" });
|
||||
await flush();
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels a backoff when a new connection lifecycle begins", async () => {
|
||||
const bot = makeBot();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValue({ url: "stale" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
await bot.connect();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
|
||||
expect(bot.player.play).not.toHaveBeenCalled();
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows pause intent in the snapshot during backoff and pauses the recovered stream", async () => {
|
||||
const bot = makeBot();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
bot.cmdPause();
|
||||
expect(bot.getStatus().paused).toBe(true);
|
||||
expect(bot.player.getState()).toBe("idle");
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.player.getState()).toBe("paused");
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
bot.cmdResume();
|
||||
expect(bot.getStatus().paused).toBe(false);
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.player.play).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("retains a paused exhausted recovery until explicit resume retries", async () => {
|
||||
const bot = makeBot();
|
||||
bot.provider.getSongUrl.mockResolvedValue(null);
|
||||
bot.player.emit("trackEnd");
|
||||
bot.cmdPause();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
expect(bot.getStatus().paused).toBe(true);
|
||||
bot.provider.getSongUrl.mockResolvedValue({ url: "fresh" });
|
||||
bot.cmdResume();
|
||||
await flush();
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.player.play).toHaveBeenCalledWith("fresh", 1000, 10_000);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("coalesces duplicate ends throughout a lookup and its backoff", async () => {
|
||||
const bot = makeBot();
|
||||
const lookup = deferred<{ url: string } | null>();
|
||||
bot.provider.getSongUrl.mockReturnValueOnce(lookup.promise).mockResolvedValue({ url: "fresh" });
|
||||
bot.player.emit("trackEnd");
|
||||
bot.player.emit("trackEnd");
|
||||
lookup.resolve(null);
|
||||
await flush();
|
||||
bot.player.emit("trackEnd");
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(2);
|
||||
expect(bot.player.play).toHaveBeenCalledTimes(1);
|
||||
expect(bot.streamRecovery.attempts).toBe(1);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("an exhausted end cannot advance over an explicit paused-recovery retry already started", async () => {
|
||||
const bot = makeBot();
|
||||
const song = bot.queue.current();
|
||||
const retry = deferred<{ url: string }>();
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(null).mockReturnValueOnce(retry.promise);
|
||||
const recover = bot.resumeInterruptedStream.bind(bot);
|
||||
let first = true;
|
||||
bot.resumeInterruptedStream = () => {
|
||||
const result = recover();
|
||||
if (first) { first = false; result.then(() => bot.cmdResume()); }
|
||||
return result;
|
||||
};
|
||||
bot.player.emit("trackEnd");
|
||||
bot.cmdPause();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(4);
|
||||
expect(bot.queue.current()).toBe(song);
|
||||
expect(bot.playNext).not.toHaveBeenCalled();
|
||||
retry.resolve({ url: "fresh" });
|
||||
await flush();
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
});
|
||||
|
||||
it("lookup retries do not consume the three actual decoder resume attempts", async () => {
|
||||
const bot = makeBot();
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
bot.provider.getSongUrl.mockResolvedValueOnce(null).mockResolvedValueOnce({ url: `fresh-${attempt}` });
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(bot.queue.current()?.id).toBe("BV1example");
|
||||
}
|
||||
bot.player.state = "idle";
|
||||
bot.player.emit("trackEnd");
|
||||
await flush();
|
||||
expect(bot.player.play).toHaveBeenCalledTimes(3);
|
||||
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(6);
|
||||
expect(bot.playNext).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("occupancy responses belong to the current request and connection", () => {
|
||||
it("ignores an older alone response after a newer occupied response", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "playing";
|
||||
const older = deferred<any[]>(), newer = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise);
|
||||
const first = bot.refreshOccupancy(), second = bot.refreshOccupancy();
|
||||
newer.resolve([{ id: 1 }, { id: 2 }]);
|
||||
await second;
|
||||
older.resolve([{ id: 1 }]);
|
||||
await first;
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.autoPaused).toBe(false);
|
||||
expect(bot.idleTimer).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["clientEnter", "clientLeave", "clientMoved"])("a newer %s event invalidates a pending response even if its new query fails", async event => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "playing";
|
||||
const older = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise).mockResolvedValueOnce([]);
|
||||
const first = bot.refreshOccupancy();
|
||||
bot.tsClient.emit(event, { id: 2, targetChannelID: 3n });
|
||||
await flush();
|
||||
older.resolve([{ id: 1 }]);
|
||||
await first;
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.autoPaused).toBe(false);
|
||||
expect(bot.idleTimer).toBeNull();
|
||||
});
|
||||
|
||||
it("a listener's return cannot be undone by an earlier alone response", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "paused";
|
||||
bot.autoPaused = true;
|
||||
const older = deferred<any[]>(), newer = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise);
|
||||
const first = bot.refreshOccupancy();
|
||||
bot.tsClient.emit("clientEnter");
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
older.resolve([{ id: 1 }]);
|
||||
await first;
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
expect(bot.autoPaused).toBe(false);
|
||||
newer.resolve([]);
|
||||
await flush();
|
||||
});
|
||||
|
||||
it.each([false, true])("ignores a response from before disconnect (reconnected=%s)", async reconnect => {
|
||||
const bot = makeBot();
|
||||
const older = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise);
|
||||
const first = bot.refreshOccupancy();
|
||||
bot.disconnect();
|
||||
if (reconnect) { await bot.connect(); bot.player.state = "playing"; }
|
||||
older.resolve([{ id: 1 }]);
|
||||
await first;
|
||||
expect(bot.idleTimer).toBeNull();
|
||||
expect(bot.autoPaused).toBe(false);
|
||||
expect(bot.player.getState()).toBe(reconnect ? "playing" : "idle");
|
||||
});
|
||||
|
||||
it("does not let an old lifecycle's poll timer query after reconnect", async () => {
|
||||
const bot = makeBot();
|
||||
bot._startIdlePoller();
|
||||
bot.disconnect();
|
||||
await bot.connect();
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(bot.tsClient.getClientsInChannel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not apply or reschedule an old pending poll after reconnect", async () => {
|
||||
const bot = makeBot();
|
||||
const oldPoll = deferred<any[]>();
|
||||
bot.tsClient.getClientsInChannel.mockReturnValueOnce(oldPoll.promise);
|
||||
bot._startIdlePoller();
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
bot.disconnect();
|
||||
await bot.connect();
|
||||
bot.player.state = "playing";
|
||||
oldPoll.resolve([{ id: 1 }]);
|
||||
await flush();
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(bot.tsClient.getClientsInChannel).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not disconnect a new connection when an old idle deadline expires", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "playing";
|
||||
bot.tsClient.getClientsInChannel.mockResolvedValueOnce([{ id: 1 }]).mockResolvedValue([]);
|
||||
await bot.refreshOccupancy();
|
||||
bot.tsClient.emit("disconnected");
|
||||
await bot.connect();
|
||||
bot.player.state = "playing";
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(bot.connected).toBe(true);
|
||||
expect(bot.tsClient.disconnect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels an old idle deadline before awaiting a new handshake", async () => {
|
||||
const bot = makeBot();
|
||||
const handshake = deferred<void>();
|
||||
bot.tsClient.getClientsInChannel.mockResolvedValue([{ id: 1 }]);
|
||||
await bot.refreshOccupancy();
|
||||
bot.tsClient.connect.mockReturnValue(handshake.promise);
|
||||
const connecting = bot.connect();
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
handshake.resolve(undefined);
|
||||
await expect(connecting).resolves.toBeUndefined();
|
||||
expect(bot.connected).toBe(true);
|
||||
expect(bot.tsClient.disconnect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still pauses for a fresh authoritative alone response and ignores unknown occupancy", async () => {
|
||||
const bot = makeBot();
|
||||
bot.player.state = "playing";
|
||||
bot.tsClient.getClientsInChannel.mockResolvedValueOnce([]).mockResolvedValueOnce([{ id: 1 }]);
|
||||
await bot.refreshOccupancy();
|
||||
expect(bot.player.getState()).toBe("playing");
|
||||
await bot.refreshOccupancy();
|
||||
expect(bot.player.getState()).toBe("paused");
|
||||
expect(bot.autoPaused).toBe(true);
|
||||
expect(bot.idleTimer).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { BotInstance, COMMAND_DENIED_MESSAGE, spotifyPortsForBotId } from "./instance.js";
|
||||
import type { BotInstanceOptions } from "./instance.js";
|
||||
@@ -134,6 +134,9 @@ describe("BotInstance voice-ducking lifecycle integration", () => {
|
||||
return {
|
||||
disconnectEmitted: false,
|
||||
connected: false,
|
||||
lifecycleGeneration: 0,
|
||||
idleTimer: null,
|
||||
_cancelIdleTimer: (BotInstance.prototype as any)._cancelIdleTimer,
|
||||
tsClient: {
|
||||
connect: vi.fn(() => connectPromise),
|
||||
getResolvedVoiceEndpoint: vi.fn(() => ({ host: "203.0.113.20", port: 12000 })),
|
||||
@@ -1660,6 +1663,8 @@ describe("cmdPlaylist with a playlist link (#160)", () => {
|
||||
});
|
||||
|
||||
describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)", () => {
|
||||
beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }));
|
||||
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
|
||||
const resumeInterruptedStream = (BotInstance.prototype as any).resumeInterruptedStream as (
|
||||
this: unknown,
|
||||
) => Promise<boolean>;
|
||||
@@ -1678,6 +1683,7 @@ describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)",
|
||||
song,
|
||||
provider,
|
||||
connected: true,
|
||||
lifecycleGeneration: 0,
|
||||
effectiveDuration: song.duration,
|
||||
streamRecovery: null,
|
||||
queue: { current: vi.fn(() => song) },
|
||||
@@ -1739,7 +1745,10 @@ describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)",
|
||||
|
||||
it("falls through to advancing when no fresh URL can be fetched", async () => {
|
||||
const ctx = makeCtx({ url: null });
|
||||
expect(await resumeInterruptedStream.call(ctx)).toBe(false);
|
||||
const recovery = resumeInterruptedStream.call(ctx);
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(await recovery).toBe(false);
|
||||
expect(ctx.provider.getSongUrl).toHaveBeenCalledTimes(3);
|
||||
expect(ctx.player.play).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -1755,6 +1764,8 @@ describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)",
|
||||
});
|
||||
|
||||
describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }));
|
||||
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
|
||||
function makeEndedCtx(platform = "bilibili", duration = 10_000) {
|
||||
const song = {
|
||||
id: "ended", name: "Ended", artist: "A", album: "", coverUrl: "",
|
||||
@@ -1774,6 +1785,7 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
const advances: string[] = [];
|
||||
const ctx: any = {
|
||||
song, provider, player, connected: true, effectiveDuration: duration,
|
||||
lifecycleGeneration: 0,
|
||||
streamRecovery: null, queue: { current: () => current },
|
||||
spotifyController: new EventEmitter(), tsClient: { sendVoiceData: vi.fn() },
|
||||
logger: { warn: vi.fn(), debug: vi.fn(), error: vi.fn() }, emit: vi.fn(),
|
||||
@@ -1893,7 +1905,7 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
|
||||
it("resume after a paused failed lookup retries recovery instead of remaining idle", async () => {
|
||||
it("resume while a paused failed lookup waits for retry continues after its backoff", async () => {
|
||||
const ctx = makeEndedCtx();
|
||||
const lookup = deferred<{ url: string }>();
|
||||
ctx.provider.getSongUrl.mockReturnValue(lookup.promise);
|
||||
@@ -1903,7 +1915,7 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
await flushEvents();
|
||||
ctx.provider.getSongUrl.mockResolvedValue({ url: "recovered" });
|
||||
ctx.resume();
|
||||
await flushEvents();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(ctx.player.getState()).toBe("playing");
|
||||
expect(ctx.player.play).toHaveBeenCalledWith("recovered", 1000, 10_000);
|
||||
expect(ctx.advances).toEqual([]);
|
||||
|
||||
+102
-42
@@ -4,6 +4,7 @@ import {
|
||||
type TS3ClientOptions,
|
||||
type TS3TextMessage,
|
||||
type TS3VoiceActivity,
|
||||
type TS3VoiceSendFailure,
|
||||
} from "../ts-protocol/client.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
|
||||
@@ -182,6 +183,9 @@ export class BotInstance extends EventEmitter {
|
||||
private logger: Logger;
|
||||
private avatarStore: AvatarStore;
|
||||
private connected = false;
|
||||
/** Fences async work and timers from earlier TeamSpeak connections. */
|
||||
private lifecycleGeneration = 0;
|
||||
private occupancyRequest = 0;
|
||||
private disconnectEmitted = false;
|
||||
private voteSkipUsers = new Set<string>();
|
||||
private isAdvancing = false;
|
||||
@@ -200,7 +204,7 @@ export class BotInstance extends EventEmitter {
|
||||
/** 当前曲实际播放时长(试听片段秒数或完整 duration);resolveAndPlay 赋值。 */
|
||||
private effectiveDuration: number | undefined;
|
||||
/** Resume attempts for the current song's stream (#161); see resumeInterruptedStream. */
|
||||
private streamRecovery: { song: QueuedSong; attempts: number; position: number; session: number; pauseRequested: boolean; inFlight: boolean } | null = null;
|
||||
private streamRecovery: { song: QueuedSong; attempts: number; position: number; session: number; generation: number; pauseRequested: boolean; inFlight: boolean } | null = null;
|
||||
private playGate: Promise<unknown> = Promise.resolve();
|
||||
/** Per-bot Jellyfin playback-report session (start / ~10s progress / stop).
|
||||
* null when the wired provider has no reporting capability. */
|
||||
@@ -326,15 +330,21 @@ export class BotInstance extends EventEmitter {
|
||||
|
||||
private setupPlayerEvents(): void {
|
||||
this.player.on("frame", (opusFrame: Buffer) => {
|
||||
this.tsClient.sendVoiceData(opusFrame);
|
||||
const result = this.tsClient.sendVoiceData(opusFrame);
|
||||
// A terminal fault can outlive a pause, queue change, or URL recovery.
|
||||
// Retry the actual send first so a repaired transport can clear it.
|
||||
if (result === "failed" && this.connected && this.player.getState() === "playing") {
|
||||
this.logger.warn("Voice transport is still failing; playback paused");
|
||||
this.cmdPause();
|
||||
}
|
||||
});
|
||||
|
||||
this.player.on("trackEnd", () => {
|
||||
const endedSong = this.queue.current();
|
||||
const endedSession = this.player.getPlaybackSessionId();
|
||||
this.resumeInterruptedStream()
|
||||
.catch((err) => {
|
||||
this.logger.warn({ err }, "Stream resume failed");
|
||||
.catch(() => {
|
||||
this.logger.warn({ sessionId: endedSession, reason: "recovery-error" }, "Stream resume failed");
|
||||
return false;
|
||||
})
|
||||
.then((resumed) => {
|
||||
@@ -346,7 +356,8 @@ export class BotInstance extends EventEmitter {
|
||||
this.queue.current() !== endedSong ||
|
||||
this.player.getPlaybackSessionId() !== endedSession ||
|
||||
this.player.getState() !== "idle" ||
|
||||
(this.streamRecovery?.song === endedSong && this.streamRecovery.pauseRequested)
|
||||
(this.streamRecovery?.song === endedSong && this.streamRecovery.session === endedSession &&
|
||||
(this.streamRecovery.pauseRequested || this.streamRecovery.inFlight))
|
||||
) return;
|
||||
this.logger.debug("Track ended, advancing queue");
|
||||
return this.playNext();
|
||||
@@ -413,6 +424,22 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
private setupTsEvents(): void {
|
||||
this.tsClient.on("voiceSendFailed", (failure: TS3VoiceSendFailure) => {
|
||||
if (!this.connected) return;
|
||||
const recovery = this.streamRecovery;
|
||||
const pendingRecovery = this.player.getState() === "idle" && recovery &&
|
||||
recovery.song === this.queue.current() && recovery.generation === this.lifecycleGeneration &&
|
||||
recovery.session === this.player.getPlaybackSessionId();
|
||||
if (this.player.getState() !== "playing" && !pendingRecovery) return;
|
||||
this.logger.warn(
|
||||
{ code: failure.code, consecutiveFailures: failure.consecutiveFailures, durationMs: failure.durationMs },
|
||||
"Voice transmission failed; playback paused. Restore the connection before resuming",
|
||||
);
|
||||
// Preserve the queue and seek position. Use the normal pause path so
|
||||
// Spotify also pauses and occupancy cannot resume a broken transport.
|
||||
this.cmdPause();
|
||||
});
|
||||
|
||||
this.tsClient.on("textMessage", (msg: TS3TextMessage) => {
|
||||
this.handleTextMessage(msg).catch((err) => {
|
||||
this.logger.error({ err }, "Unhandled error in text message handler");
|
||||
@@ -424,7 +451,9 @@ export class BotInstance extends EventEmitter {
|
||||
// completed (hanging handshake → 60s library idle timeout) and
|
||||
// this.connected was never flipped to true. Previously this handler
|
||||
// short-circuited on !this.connected, leaving player stuck as "playing".
|
||||
this.lifecycleGeneration++;
|
||||
this.connected = false;
|
||||
this._cancelIdleTimer();
|
||||
this.unregisterManagedVoiceClient(MANAGED_VOICE_CLIENT_RELEASE_GRACE_MS);
|
||||
this.voiceDucking.reset(true);
|
||||
// Cancel any pending live-queue snapshot BEFORE clearing the queue: a
|
||||
@@ -452,6 +481,8 @@ export class BotInstance extends EventEmitter {
|
||||
});
|
||||
|
||||
this.tsClient.on("connected", () => {
|
||||
this.lifecycleGeneration++;
|
||||
this._cancelIdleTimer();
|
||||
// Fresh connection — clear any stale auto-pause flag from a prior session.
|
||||
this.autoPaused = false;
|
||||
this._startIdlePoller();
|
||||
@@ -562,8 +593,13 @@ export class BotInstance extends EventEmitter {
|
||||
|
||||
private async refreshOccupancy(): Promise<void> {
|
||||
if (!this.connected) return;
|
||||
const request = ++this.occupancyRequest;
|
||||
const generation = this.lifecycleGeneration;
|
||||
const client = this.tsClient;
|
||||
try {
|
||||
const clients = await this.tsClient.getClientsInChannel();
|
||||
const clients = await client.getClientsInChannel();
|
||||
if (!this.connected || this.lifecycleGeneration !== generation ||
|
||||
this.occupancyRequest !== request || this.tsClient !== client) return;
|
||||
// A 0-length result means the clientlist query failed (the bot is always
|
||||
// in its own channel) — occupancy is unknown, so don't act. Acting on it
|
||||
// would mis-read it as "empty" and falsely auto-pause / idle-disconnect.
|
||||
@@ -575,6 +611,8 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.lifecycleGeneration++;
|
||||
this._cancelIdleTimer();
|
||||
this.disconnectEmitted = false;
|
||||
await this.tsClient.connect();
|
||||
const resolvedEndpoint = this.tsClient.getResolvedVoiceEndpoint();
|
||||
@@ -607,6 +645,7 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.lifecycleGeneration++;
|
||||
this._cancelIdleTimer();
|
||||
this.voiceDucking.reset(true);
|
||||
// Cancel any pending live-queue snapshot before clearing so it can't fire
|
||||
@@ -662,16 +701,12 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
private _startIdlePoller(): void {
|
||||
const generation = this.lifecycleGeneration;
|
||||
// 每 30 秒检查一次频道人数
|
||||
const poll = async () => {
|
||||
if (!this.connected) return;
|
||||
try {
|
||||
const clients = await this.tsClient.getClientsInChannel();
|
||||
// null = clientlist query failed (occupancy unknown) → don't act.
|
||||
const userCount = occupancyFromClientList(clients.length);
|
||||
if (userCount !== null) this.handleOccupancy(userCount);
|
||||
} catch { /* ignore */ }
|
||||
setTimeout(poll, 30_000);
|
||||
if (!this.connected || this.lifecycleGeneration !== generation) return;
|
||||
await this.refreshOccupancy();
|
||||
if (this.connected && this.lifecycleGeneration === generation) setTimeout(poll, 30_000);
|
||||
};
|
||||
setTimeout(poll, 30_000);
|
||||
}
|
||||
@@ -736,8 +771,9 @@ export class BotInstance extends EventEmitter {
|
||||
if (this.idleTimer !== null) return; // 已经在倒计时,不重复创建
|
||||
const minutes = this.config.idleTimeoutMinutes ?? 0;
|
||||
if (!this.connected || minutes <= 0) return;
|
||||
const generation = this.lifecycleGeneration;
|
||||
this.idleTimer = setTimeout(() => {
|
||||
if (!this.connected) return;
|
||||
if (!this.connected || this.lifecycleGeneration !== generation) return;
|
||||
this.logger.info({ idleMinutes: minutes }, "Channel empty, disconnecting due to idle timeout");
|
||||
this.disconnect();
|
||||
}, minutes * 60 * 1000);
|
||||
@@ -1154,6 +1190,7 @@ export class BotInstance extends EventEmitter {
|
||||
/** A track that ends within this many seconds of its duration ended normally. */
|
||||
private static readonly STREAM_END_TOLERANCE_S = 30;
|
||||
private static readonly MAX_STREAM_RESUMES = 3;
|
||||
private static readonly MAX_STREAM_URL_LOOKUPS = 3;
|
||||
|
||||
/**
|
||||
* Called when the player reports a track end. If a B站 stream ended long
|
||||
@@ -1176,15 +1213,18 @@ export class BotInstance extends EventEmitter {
|
||||
if (!(duration > 0) || duration - position <= BotInstance.STREAM_END_TOLERANCE_S) {
|
||||
return false;
|
||||
}
|
||||
if (this.player.getState() !== "idle") return true;
|
||||
const generation = this.lifecycleGeneration;
|
||||
|
||||
const recovery = this.streamRecovery;
|
||||
if (
|
||||
!recovery ||
|
||||
recovery.song !== song ||
|
||||
recovery.session !== endedSession ||
|
||||
recovery.generation !== generation ||
|
||||
position - recovery.position > BotInstance.STREAM_END_TOLERANCE_S
|
||||
) {
|
||||
this.streamRecovery = { song, attempts: 0, position, session: endedSession, pauseRequested: false, inFlight: false };
|
||||
this.streamRecovery = { song, attempts: 0, position, session: endedSession, generation, pauseRequested: false, inFlight: false };
|
||||
}
|
||||
const state = this.streamRecovery!;
|
||||
if (state.inFlight) return true;
|
||||
@@ -1196,40 +1236,55 @@ export class BotInstance extends EventEmitter {
|
||||
this.streamRecovery = null;
|
||||
return false;
|
||||
}
|
||||
state.attempts++;
|
||||
state.position = position;
|
||||
|
||||
this.logger.warn(
|
||||
{ songId: song.id, position, duration, attempt: state.attempts },
|
||||
{ songId: song.id, position, duration, attempt: state.attempts + 1 },
|
||||
"Stream ended before the track did — resuming with a fresh URL",
|
||||
);
|
||||
state.inFlight = true;
|
||||
let result: Awaited<ReturnType<MusicProvider["getSongUrl"]>>;
|
||||
const isCurrent = () => this.connected && this.lifecycleGeneration === generation &&
|
||||
this.streamRecovery === state && this.queue.current() === song &&
|
||||
this.player.getPlaybackSessionId() === endedSession && this.player.getState() === "idle";
|
||||
const cancelled = () => {
|
||||
if (this.streamRecovery === state) this.streamRecovery = null;
|
||||
return true;
|
||||
};
|
||||
try {
|
||||
result = await this.getProviderFor(song.platform).getSongUrl(song.id);
|
||||
for (let lookup = 0; lookup < BotInstance.MAX_STREAM_URL_LOOKUPS; lookup++) {
|
||||
if (!isCurrent()) return cancelled();
|
||||
if (lookup > 0) {
|
||||
await new Promise<void>(resolve => setTimeout(resolve, lookup * 1000));
|
||||
if (!isCurrent()) return cancelled();
|
||||
}
|
||||
let result: Awaited<ReturnType<MusicProvider["getSongUrl"]>> = null;
|
||||
let reason = "no-url";
|
||||
try {
|
||||
result = await this.getProviderFor(song.platform).getSongUrl(song.id);
|
||||
} catch {
|
||||
reason = "lookup-error";
|
||||
}
|
||||
// Skip, stop, reconnect, or a new playback session supersedes the lookup.
|
||||
if (!isCurrent()) return cancelled();
|
||||
if (result?.url) {
|
||||
// Lookup retries do not consume the actual decoder resume budget.
|
||||
state.attempts++;
|
||||
song.url = result.url;
|
||||
this.player.play(result.url, position, duration);
|
||||
state.session = this.player.getPlaybackSessionId();
|
||||
if (state.pauseRequested) this.player.pause();
|
||||
this.emit("stateChange");
|
||||
return true;
|
||||
}
|
||||
this.logger.warn(
|
||||
{ platform: "bilibili", sessionId: endedSession, position, duration, lookupAttempt: lookup + 1, reason },
|
||||
"Fresh stream URL lookup failed",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
state.inFlight = false;
|
||||
}
|
||||
// The user may have skipped/stopped while we were resolving; never
|
||||
// clobber whatever is playing now.
|
||||
if (
|
||||
this.queue.current() !== song ||
|
||||
this.player.getPlaybackSessionId() !== endedSession ||
|
||||
this.player.getState() !== "idle"
|
||||
) {
|
||||
if (this.streamRecovery === state) this.streamRecovery = null;
|
||||
return true;
|
||||
}
|
||||
if (!result?.url || !this.connected) return false;
|
||||
|
||||
song.url = result.url;
|
||||
this.player.play(result.url, position, duration);
|
||||
state.session = this.player.getPlaybackSessionId();
|
||||
// During the lookup the ended player is idle, so pause() alone cannot
|
||||
// remember the user's intent. Pause the recovered stream before it emits frames.
|
||||
if (state.pauseRequested) this.player.pause();
|
||||
this.emit("stateChange");
|
||||
return true;
|
||||
}
|
||||
|
||||
private async syncProfileToSong(song: QueuedSong | null): Promise<void> {
|
||||
@@ -2135,12 +2190,17 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
getStatus(): BotStatus {
|
||||
const playerState = this.player.getState();
|
||||
const recovery = this.streamRecovery;
|
||||
const recoveryPaused = playerState === "idle" && recovery?.pauseRequested &&
|
||||
recovery.song === this.queue.current() && recovery.generation === this.lifecycleGeneration &&
|
||||
recovery.session === this.player.getPlaybackSessionId();
|
||||
return {
|
||||
id: this.id,
|
||||
name: this.name,
|
||||
connected: this.connected,
|
||||
playing: this.player.getState() === "playing",
|
||||
paused: this.player.getState() === "paused",
|
||||
playing: playerState === "playing",
|
||||
paused: playerState === "paused" || !!recoveryPaused,
|
||||
currentSong: this.queue.current(),
|
||||
queueSize: this.queue.size(),
|
||||
volume: this.player.getVolume(),
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EventEmitter } from "node:events";
|
||||
import pino from "pino";
|
||||
import { BotInstance } from "./instance.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { PlayQueue } from "../audio/queue.js";
|
||||
import { PCM_FRAME_BYTES } from "../audio/encoder.js";
|
||||
import { TS3Client } from "../ts-protocol/client.js";
|
||||
|
||||
function makeHarness(platform: "bilibili" | "spotify" = "bilibili") {
|
||||
const logger = pino({ level: "silent" });
|
||||
const player = new AudioPlayer(logger);
|
||||
const queue = new PlayQueue();
|
||||
queue.add({ id: "offline-fixture", name: "67-minute fixture", artist: "fixture", album: "", coverUrl: "", platform, duration: 4020 });
|
||||
queue.play();
|
||||
Object.assign(player, { state: "playing", framesPlayed: 111000 });
|
||||
const tsClient = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "OfflineFixture" }, logger);
|
||||
let sidecarPauses = 0;
|
||||
const bot = Object.assign(new EventEmitter(), {
|
||||
logger, player, queue, tsClient, connected: true, autoPaused: true,
|
||||
streamRecovery: null, lifecycleGeneration: 0,
|
||||
spotifyController: Object.assign(new EventEmitter(), { pause: async () => { sidecarPauses++; } }),
|
||||
});
|
||||
const methods = BotInstance.prototype as unknown as {
|
||||
setupTsEvents(this: typeof bot): void;
|
||||
cmdPause(this: typeof bot): string;
|
||||
};
|
||||
Object.assign(bot, { cmdPause: methods.cmdPause });
|
||||
methods.setupTsEvents.call(bot);
|
||||
return { bot, player, queue, tsClient, sidecarPauses: () => sidecarPauses };
|
||||
}
|
||||
|
||||
afterEach(() => { vi.clearAllTimers(); vi.restoreAllMocks(); vi.useRealTimers(); });
|
||||
|
||||
describe("BotInstance persistent voice send failure", () => {
|
||||
it.each(["bilibili", "spotify"] as const)("pauses %s while retaining the song and playback position", platform => {
|
||||
const h = makeHarness(platform);
|
||||
const song = h.queue.current();
|
||||
let changes = 0;
|
||||
h.bot.on("stateChange", () => changes++);
|
||||
try {
|
||||
h.tsClient.emit("voiceSendFailed", { code: "ERR_SOCKET_DGRAM_NOT_RUNNING", consecutiveFailures: 100, durationMs: 2000 });
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
expect(h.player.getElapsed()).toBe(2220);
|
||||
expect(h.queue.current()).toBe(song);
|
||||
expect(h.queue.size()).toBe(1);
|
||||
expect(h.bot.autoPaused).toBe(false);
|
||||
expect(changes).toBe(1);
|
||||
expect(h.sidecarPauses()).toBe(platform === "spotify" ? 1 : 0);
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 200, durationMs: 4000 });
|
||||
expect(changes).toBe(1);
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
it("stops the actual audio scheduler from advancing elapsed after terminal transmission failure", () => {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
|
||||
const h = makeHarness();
|
||||
const internal = h.player as unknown as { startFrameLoop(): void };
|
||||
let frames = 0;
|
||||
h.player.on("frame", () => frames++);
|
||||
Object.assign(h.player, { framesPlayed: 0, ffmpeg: { pid: undefined }, pcmBuffer: Buffer.alloc(PCM_FRAME_BYTES * 250), currentSongDuration: 4020 });
|
||||
try {
|
||||
internal.startFrameLoop();
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(frames).toBe(50);
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
|
||||
vi.advanceTimersByTime(3000);
|
||||
expect(frames).toBe(50);
|
||||
expect(h.player.getElapsed()).toBe(1);
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
it("lets transient failure recover without pausing and does not auto-resume a user pause", () => {
|
||||
const h = makeHarness();
|
||||
try {
|
||||
h.tsClient.emit("voiceSendFailure", { consecutiveFailures: 1, durationMs: 0 });
|
||||
h.tsClient.emit("voiceSendRecovered", { consecutiveFailures: 1, durationMs: 20 });
|
||||
expect(h.player.getState()).toBe("playing");
|
||||
h.player.pause();
|
||||
h.tsClient.emit("voiceSendRecovered", { consecutiveFailures: 1, durationMs: 20 });
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
it("preserves pause intent when terminal failure occurs during a pending fresh URL lookup", async () => {
|
||||
const h = makeHarness();
|
||||
Object.assign(h.player, { state: "idle" });
|
||||
let resolve!: (result: { url: string }) => void;
|
||||
const lookup = new Promise<{ url: string }>(done => { resolve = done; });
|
||||
Object.assign(h.bot, { getProviderFor: () => ({ getSongUrl: () => lookup }) });
|
||||
// Isolate only process creation; the actual stop, seek, state, session,
|
||||
// recovery method and pause method remain in use.
|
||||
vi.spyOn(h.player, "play").mockImplementation((_url, seek, duration) => {
|
||||
h.player.stop();
|
||||
Object.assign(h.player, { state: "playing", seekOffset: seek, currentSongDuration: duration });
|
||||
});
|
||||
const resume = (BotInstance.prototype as unknown as { resumeInterruptedStream(this: typeof h.bot): Promise<boolean> }).resumeInterruptedStream;
|
||||
const recovery = resume.call(h.bot);
|
||||
try {
|
||||
h.tsClient.emit("voiceSendFailed", { code: "EPIPE", consecutiveFailures: 100, durationMs: 2000 });
|
||||
resolve({ url: "https://offline.invalid/fresh.m4s" });
|
||||
expect(await recovery).toBe(true);
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
expect(h.player.getElapsed()).toBe(2220);
|
||||
expect(h.queue.current()?.id).toBe("offline-fixture");
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
it("pauses again if manual resume encounters the same persistent voice fault", () => {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance", "Date"] });
|
||||
const h = makeHarness();
|
||||
let accepted = 0;
|
||||
Object.assign(h.tsClient, { client: { sendVoice() {
|
||||
if (accepted++ > 0) throw Object.assign(new Error("offline fixture"), { code: "EPIPE" });
|
||||
} } });
|
||||
const setupPlayerEvents = (BotInstance.prototype as unknown as { setupPlayerEvents(this: typeof h.bot): void }).setupPlayerEvents;
|
||||
setupPlayerEvents.call(h.bot);
|
||||
Object.assign(h.player, { framesPlayed: 0, ffmpeg: { pid: undefined }, pcmBuffer: Buffer.alloc(PCM_FRAME_BYTES * 250), currentSongDuration: 4020 });
|
||||
try {
|
||||
(h.player as unknown as { startFrameLoop(): void }).startFrameLoop();
|
||||
vi.advanceTimersByTime(2100);
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
const pausedAt = h.player.getElapsed();
|
||||
h.player.resume();
|
||||
vi.advanceTimersByTime(40);
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
expect(h.player.getElapsed()).toBeLessThanOrEqual(pausedAt + 0.02);
|
||||
expect(h.queue.current()?.id).toBe("offline-fixture");
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
it("ignores terminal notifications when disconnected or already idle", () => {
|
||||
const h = makeHarness();
|
||||
try {
|
||||
h.bot.connected = false;
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
|
||||
expect(h.player.getState()).toBe("playing");
|
||||
h.bot.connected = true;
|
||||
h.player.stop();
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
|
||||
expect(h.player.getState()).toBe("idle");
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user