fix(playback): retry and downgrade quality before reporting 无法播放

Two failure modes look identical to the user — 「无法播放(区域/版权限制)」 — but
need different handling, and both were hitting the same code path:

1. **Transient.** NetEase intermittently answers `url: null` for a song that
   resolves fine a moment later. Repeating the SAME request fixes it, but the
   user had to click play repeatedly to be that retry.

2. **Quality gap.** Measured against a real library: a track can be playable at
   192k ("higher") while BOTH 320k ("exhigh") and 128k ("standard") return
   `url: null`. So the ladder is not continuous and "just drop to the cheapest"
   would still fail — every level below the current one has to be tried.

`resolveAndPlay` now resolves through `bot/url-retry.ts`:

- Phase 1: `1 + config.playUrlRetries` attempts (default 2, clamped 0..5) at the
  configured quality, 250ms linear backoff between them.
- Phase 2: one attempt per lower level from `provider.getFallbackQualities()`
  (NetEase: exhigh → higher → standard), 120ms apart — switching level is a
  different request, not a re-poke of the same one.
- Cancel (stop / disconnect) is checked before every attempt, so the budget
  never retries into a dead connection.
- A thrown error is retried exactly like an empty result: a sidecar timeout
  looks identical to the user.
- Failure is logged once per track, not once per attempt.

Every queue path funnels into `resolveAndPlay` (web click, chat !play,
auto-advance, FM), so playlists and albums get the same budget for free — that
is where "click the playlist four times before it starts" came from.

`config.playUrlRetries` is exposed on GET/POST `/api/bot/settings`. A config
without the field falls back to 2 — retries are ON by default because the whole
point is to be invisible. Set it to 0 to restore the previous fail-fast path.
This commit is contained in:
jiayuLian committed 2026-11-08 17:30:02 +08:00
1 parent 17008ae52e
commit c2771ab9a7
8 files changed
+566 -5

No files matched your search

+32 -5
View File
@@ -7,8 +7,9 @@ import {
type TS3VoiceSendFailure,
} from "../ts-protocol/client.js";
import { AudioPlayer } from "../audio/player.js";
import { resolveUrlWithRetry } from "./url-retry.js";
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
import type { MusicProvider, Platform, Song } from "../music/provider.js";
import type { MusicProvider, Platform, Song, SongUrlResult } from "../music/provider.js";
import {
parseCommand,
canRunCommand,
@@ -1022,8 +1023,7 @@ export class BotInstance extends EventEmitter {
}
/** Resolve URL for a song and start playing it. Skips to next if URL fails. */
async resolveAndPlay(song: QueuedSong): Promise<boolean> {
if (!this.connected) {
async resolveAndPlay(song: QueuedSong): Promise<boolean> { if (!this.connected) {
this.logger.warn({ songId: song.id, name: song.name }, "resolveAndPlay called on disconnected bot — skipping");
return false;
}
@@ -1045,9 +1045,36 @@ export class BotInstance extends EventEmitter {
song.id = detail.id;
}
}
const result = await provider.getSongUrl(song.id);
// Retries live in resolveUrlWithRetry so the whole queue path (web click,
// chat !play, auto-advance, FM) benefits from the same budget, and the
// failure is logged once there instead of once per attempt.
// Retries happen here (not in the provider) so every queue path — web
// click, chat !play, auto-advance, FM — shares the same budget. The
// policy lives in url-retry.ts so it is unit tested without a bot; a
// config without the field means 0 retries, i.e. the previous behaviour.
const result = await resolveUrlWithRetry({
retries: this.config?.playUrlRetries,
resolve: (quality) => provider.getSongUrl(song.id, quality),
// NetEase's quality ladder is not continuous: a track can play at 192k
// while both 320k and 128k return null, so every lower level is tried.
// Providers without a quality knob return [] and keep one attempt.
fallbacks: provider.getFallbackQualities?.() ?? [],
// Stop / disconnect must abort the budget: retrying into a dead
// connection only delays the queue.
isCancelled: () => !this.connected,
onAttemptFailed: ({ attempt, total, quality, error }) => {
const fields = { songId: song.id, name: song.name, attempt, total, quality };
if (error) {
this.logger.warn({ ...fields, err: error }, "URL resolve threw — retrying");
} else if (attempt < total) {
this.logger.debug(fields, "URL resolve returned no URL — retrying");
} else {
// Once per track, after the budget is spent — not once per attempt.
this.logger.warn(fields, "No URL available after retries, skipping");
}
},
});
if (!result?.url) {
this.logger.warn({ songId: song.id, name: song.name }, "No URL available, skipping");
return false;
}
// Re-check connection state AFTER the network round-trip — the URL
+311
View File
@@ -0,0 +1,311 @@
import { describe, expect, it, vi } from "vitest";
import type { SongUrlResult } from "../music/provider.js";
import {
MAX_URL_RETRIES,
DEFAULT_URL_RETRY_BACKOFF_MS,
QUALITY_SWITCH_BACKOFF_MS,
normalizeRetryCount,
resolveUrlWithRetry,
} from "./url-retry.js";
const ok = (url = "https://cdn.example/track.mp3"): SongUrlResult => ({ url });
/** Sleep stand-in that records the delays instead of waiting. */
function recordingSleep() {
const delays: number[] = [];
return { delays, sleep: async (ms: number) => void delays.push(ms) };
}
describe("normalizeRetryCount", () => {
it("accepts 0..MAX and truncates fractions", () => {
expect(normalizeRetryCount(0)).toBe(0);
expect(normalizeRetryCount(2)).toBe(2);
expect(normalizeRetryCount(2.9)).toBe(2);
});
it("clamps out-of-range numbers", () => {
expect(normalizeRetryCount(-3)).toBe(0);
expect(normalizeRetryCount(99)).toBe(MAX_URL_RETRIES);
});
// Garbage means "old behaviour" (fail fast), not "retry forever".
it("treats non-numeric values as zero", () => {
expect(normalizeRetryCount(undefined)).toBe(0);
expect(normalizeRetryCount(null)).toBe(0);
expect(normalizeRetryCount("3")).toBe(0);
expect(normalizeRetryCount(Number.NaN)).toBe(0);
expect(normalizeRetryCount(Number.POSITIVE_INFINITY)).toBe(0);
});
});
describe("resolveUrlWithRetry", () => {
it("makes exactly one attempt when retries is 0", async () => {
const resolve = vi.fn(async () => null);
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 0, resolve, sleep });
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(1);
});
// The reported bug: first click fails, third works. A retry inside one
// request turns that into a normal play.
it("succeeds on a later attempt and stops retrying", async () => {
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(ok());
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
expect(result).toEqual(ok());
expect(resolve).toHaveBeenCalledTimes(3);
});
it("gives up after 1 + retries attempts", async () => {
const resolve = vi.fn(async () => null);
const { sleep, delays } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(3);
// Linear backoff: one wait before attempt 2, two units before attempt 3.
expect(delays).toEqual([DEFAULT_URL_RETRY_BACKOFF_MS, DEFAULT_URL_RETRY_BACKOFF_MS * 2]);
});
// A timeout from the local API sidecar looks identical to the user, so a
// throw is retried exactly like an empty result.
it("retries after a thrown error", async () => {
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockRejectedValueOnce(new Error("ECONNRESET"))
.mockResolvedValueOnce(ok("https://cdn.example/retry.mp3"));
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 1, resolve, sleep });
expect(result?.url).toBe("https://cdn.example/retry.mp3");
expect(resolve).toHaveBeenCalledTimes(2);
});
it("returns null when every attempt throws", async () => {
const resolve = vi.fn(async () => {
throw new Error("boom");
});
const { sleep } = recordingSleep();
expect(await resolveUrlWithRetry({ retries: 2, resolve, sleep })).toBeNull();
expect(resolve).toHaveBeenCalledTimes(3);
});
it("does not start when already cancelled", async () => {
const resolve = vi.fn(async () => ok());
const result = await resolveUrlWithRetry({
retries: 3,
resolve,
isCancelled: () => true,
sleep: async () => {},
});
expect(result).toBeNull();
expect(resolve).not.toHaveBeenCalled();
});
// Stopping mid-budget must not keep hammering the API for a track nobody
// wants any more.
it("aborts after cancellation during the backoff", async () => {
const resolve = vi.fn(async () => null);
let cancelled = false;
const sleep = async () => {
cancelled = true; // user hit stop while we waited
};
const result = await resolveUrlWithRetry({
retries: 3,
resolve,
isCancelled: () => cancelled,
sleep,
});
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(1);
});
it("reports every failed attempt once, with the error when there was one", async () => {
const failures: Array<{ attempt: number; total: number; error?: unknown }> = [];
const boom = new Error("boom");
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockResolvedValueOnce(null)
.mockRejectedValueOnce(boom)
.mockResolvedValueOnce(null);
const { sleep } = recordingSleep();
await resolveUrlWithRetry({
retries: 2,
resolve,
sleep,
onAttemptFailed: (info) => failures.push(info),
});
expect(failures).toHaveLength(3);
expect(failures[0]).toEqual({ attempt: 1, total: 3, error: undefined });
expect(failures[1]).toEqual({ attempt: 2, total: 3, error: boom });
expect(failures[2]).toEqual({ attempt: 3, total: 3, error: undefined });
});
it("does not report a failure for the attempt that succeeded", async () => {
const onAttemptFailed = vi.fn();
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(ok());
const { sleep } = recordingSleep();
await resolveUrlWithRetry({ retries: 1, resolve, sleep, onAttemptFailed });
expect(onAttemptFailed).toHaveBeenCalledTimes(1);
});
it("honours a custom backoff", async () => {
const { sleep, delays } = recordingSleep();
await resolveUrlWithRetry({
retries: 2,
backoffMs: 10,
resolve: async () => null,
sleep,
});
expect(delays).toEqual([10, 20]);
});
// An empty-string URL is as useless as null: the player would fail later.
it("treats a result without a url as a failure", async () => {
const resolve = vi
.fn<() => Promise<SongUrlResult | null>>()
.mockResolvedValueOnce({ url: "" })
.mockResolvedValueOnce(ok());
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 1, resolve, sleep });
expect(result?.url).toBe(ok().url);
expect(resolve).toHaveBeenCalledTimes(2);
});
});
// ---------------------------------------------------------------------------
// Quality fallback
//
// Regression for «点四五次才能播»: NetEase's ladder is discontinuous, so a
// track that plays at 192k can return null at BOTH 320k (the default) and 128k.
// Retrying the same level can never fix that — the level has to change.
// ---------------------------------------------------------------------------
describe("resolveUrlWithRetry — quality fallback", () => {
it("sweeps the fallback levels after the primary budget is spent", async () => {
const seen: Array<string | undefined> = [];
const resolve = vi.fn(async (quality?: string) => {
seen.push(quality);
// Only "higher" ever works; the configured level never does.
return quality === "higher" ? ok("https://cdn.example/192.mp3") : null;
});
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({
retries: 1,
resolve,
fallbacks: ["higher", "standard"],
sleep,
});
expect(result?.url).toBe("https://cdn.example/192.mp3");
// primary, primary retry, then higher — and stops there.
expect(seen).toEqual([undefined, undefined, "higher"]);
});
it("tries every fallback in order when none of them work", async () => {
const seen: Array<string | undefined> = [];
const resolve = vi.fn(async (quality?: string) => {
seen.push(quality);
return null;
});
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({
retries: 1,
resolve,
fallbacks: ["higher", "standard"],
sleep,
});
expect(result).toBeNull();
expect(seen).toEqual([undefined, undefined, "higher", "standard"]);
});
it("does not touch fallbacks when the configured level succeeds", async () => {
const resolve = vi.fn(async () => ok());
const { sleep } = recordingSleep();
await resolveUrlWithRetry({ retries: 3, resolve, fallbacks: ["higher"], sleep });
expect(resolve).toHaveBeenCalledTimes(1);
});
// A level switch is a different request, so it must not wait out a full
// same-quality backoff — otherwise a broken 320k track stalls for seconds.
it("uses the short switch delay between levels", async () => {
const { sleep, delays } = recordingSleep();
await resolveUrlWithRetry({
retries: 1,
resolve: async () => null,
fallbacks: ["higher", "standard"],
sleep,
});
expect(delays).toEqual([
DEFAULT_URL_RETRY_BACKOFF_MS, // primary → primary retry
QUALITY_SWITCH_BACKOFF_MS, // retry → higher
QUALITY_SWITCH_BACKOFF_MS, // higher → standard
]);
});
it("reports which quality each failed attempt used", async () => {
const failures: Array<{ quality?: string }> = [];
const { sleep } = recordingSleep();
await resolveUrlWithRetry({
retries: 0,
resolve: async () => null,
fallbacks: ["higher", "standard"],
sleep,
onAttemptFailed: (info) => failures.push(info),
});
expect(failures.map((f) => f.quality)).toEqual([undefined, "higher", "standard"]);
});
it("still works when no fallbacks are supplied", async () => {
const resolve = vi.fn(async () => null);
const { sleep } = recordingSleep();
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(3);
});
it("aborts mid-sweep when the caller is cancelled", async () => {
const resolve = vi.fn(async () => null);
let cancelled = false;
const sleep = async () => {
cancelled = true;
};
const result = await resolveUrlWithRetry({
retries: 0,
resolve,
fallbacks: ["higher", "standard"],
isCancelled: () => cancelled,
sleep,
});
expect(result).toBeNull();
expect(resolve).toHaveBeenCalledTimes(1);
});
});
+119
View File
@@ -0,0 +1,119 @@
import type { SongUrlResult } from "../music/provider.js";
/**
* Silent re-resolve of a playable URL.
*
* Two different failure modes look identical to the user but need different
* treatment, so this handles both inside one request:
*
* 1. **Transient** — NetEase intermittently answers `url: null` for a song that
* resolves fine a moment later. Repeating the SAME request fixes it.
* 2. **Quality gap** — some tracks have no URL at the configured level while a
* different level works. Measured against a real library: a track can be
* playable at "higher" (192k) while BOTH "exhigh" (320k) and "standard"
* (128k) return null, so a single "drop to the cheapest" step is not enough
* — every level below the current one has to be tried.
*
* Without either, the user saw 「无法播放(区域/版权限制)」 and had to click play
* repeatedly until it happened to work.
*
* Kept as a standalone function (not a BotInstance method) so the behaviour is
* testable without booting a bot, and so every caller — web click, chat !play,
* auto-advance, FM — gets the same budget by construction.
*/
/** Upper bound on retries per quality level, whatever the config says. */
export const MAX_URL_RETRIES = 5;
/** Default delay before retrying the SAME quality; grows linearly (250, 500 …). */
export const DEFAULT_URL_RETRY_BACKOFF_MS = 250;
/**
* Delay before the first attempt at the next quality level. Much shorter than a
* same-quality retry: switching level is a different request, not a re-poke of
* the same one, so it does not need to wait out the same jitter window.
*/
export const QUALITY_SWITCH_BACKOFF_MS = 120;
/**
* Normalise a config value into a usable retry count.
* Anything non-numeric (legacy config, `"3"`, `null`) means "no retries", which
* keeps the pre-existing fail-fast behaviour for callers that pass garbage.
*/
export function normalizeRetryCount(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) return 0;
return Math.min(MAX_URL_RETRIES, Math.max(0, Math.trunc(value)));
}
export interface ResolveUrlWithRetryOptions {
/** Extra attempts per quality level after the first. 0 = one attempt each. */
retries: unknown;
/** Resolve one URL. `undefined` means "the provider's configured quality". */
resolve: (quality?: string) => Promise<SongUrlResult | null>;
/**
* Lower quality levels to sweep after the primary budget is spent, best→worst.
* Typically `provider.getFallbackQualities?.()`.
*/
fallbacks?: string[];
/** Checked before every attempt — stop / disconnect aborts the budget. */
isCancelled?: () => boolean;
backoffMs?: number;
/** Called once per failed attempt (logging hook). */
onAttemptFailed?: (info: {
attempt: number;
total: number;
quality?: string;
error?: unknown;
}) => void;
/** Injectable for tests. */
sleep?: (ms: number) => Promise<void>;
}
/**
* Returns the first successful result, or null once every level is exhausted.
*
* Request count: `(1 + retries)` at the configured quality, then one per
* fallback level. With the defaults (2 retries, exhigh, NetEase's two lower
* levels) that is at most 5 requests and ~1.1s of waiting.
*/
export async function resolveUrlWithRetry(
opts: ResolveUrlWithRetryOptions,
): Promise<SongUrlResult | null> {
const retries = normalizeRetryCount(opts.retries);
const backoffMs = opts.backoffMs ?? DEFAULT_URL_RETRY_BACKOFF_MS;
const sleep =
opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
// Phase 1: the configured quality (1 + retries attempts).
// Phase 2: every lower level, once each, so a discontinuous ladder is covered.
const plan: Array<{ quality?: string; fallback: boolean }> = [];
for (let i = 0; i <= retries; i++) plan.push({ quality: undefined, fallback: false });
for (const quality of opts.fallbacks ?? []) plan.push({ quality, fallback: true });
let sameQualityAttempt = 0;
for (let i = 0; i < plan.length; i++) {
const step = plan[i];
if (opts.isCancelled?.()) return null;
if (i > 0) {
const wait = step.fallback ? QUALITY_SWITCH_BACKOFF_MS : backoffMs * sameQualityAttempt;
if (wait > 0) await sleep(wait);
// The user may have stopped or switched tracks while we waited.
if (opts.isCancelled?.()) return null;
}
let error: unknown;
try {
const result = await opts.resolve(step.quality);
if (result?.url) return result;
} catch (err) {
error = err;
}
opts.onAttemptFailed?.({ attempt: i + 1, total: plan.length, quality: step.quality, error });
// Only same-quality attempts grow the backoff; a level switch resets it.
sameQualityAttempt = step.fallback ? 0 : sameQualityAttempt + 1;
}
return null;
}