mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-03 03:12:51 +08:00
fix(playback): back off properly when NetEase risk control answers -460
Measured directly against the sidecar on a cloud host, same song, same minute:
GET /song/url/v1?id=1827600686&level=exhigh → 400
{"code":-460,"message":"检测到您的网络环境存在风险,请稍后再试"}
GET …&cookie=<account cookie> → 200, 320k url
So the "无法播放(区域/版权限制)" everyone was chasing is NetEase rejecting
the host's IP, not a copyright or membership problem. It arrives as a 4xx,
which axios reports as ERR_BAD_REQUEST — indistinguishable from a malformed
request without reading the body — and that is why it looked like a dead end in
the logs.
The previous commit retried everything on a flat 250ms backoff. For -460 that
is useless: the risk window lasts a few seconds, so three re-pokes inside 750ms
all land in it and the budget is spent without ever giving the upstream time to
relax. It also spent the 120ms level-switch delay on it, but -460 ignores which
quality we ask for.
Now:
- `netease.getSongUrl` recognises 400 + `code: -460` and rethrows
`RiskControlError` (provider.ts), so the retry layer can tell "wait this out"
from "this track will never play".
- `resolveUrlWithRetry` waits `RISK_CONTROL_BACKOFF_MS * attempt` (800ms,
1600ms, …) instead of 250ms, and never uses the fast level-switch delay while
risk controlled.
- The failure log now says what actually happened
(`hit NetEase risk control (-460) — backing off`) instead of dumping an axios
error that reads like a broken request.
Everything else keeps the old timing: a plain thrown error still retries at
250ms, a genuine 400 (`code: 400`) is not reclassified, and a 200 with `url:null`
still falls through to the quality ladder.
11 new tests: -460 → RiskControlError, genuine 400 untouched, HTML 400
untouched, message preserved, exponential wait, no 120ms switch under risk
control, recovery stops spending, cancellation during a wait.
This commit is contained in:
1 parent
c2771ab9a7
commit
e9995c1e30
6 files changed
+253
-5
No files matched your search
+10
-1
@@ -8,6 +8,7 @@ import {
|
||||
} from "../ts-protocol/client.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { resolveUrlWithRetry } from "./url-retry.js";
|
||||
import { RISK_CONTROL_CODE, RiskControlError } from "../music/provider.js";
|
||||
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
|
||||
import type { MusicProvider, Platform, Song, SongUrlResult } from "../music/provider.js";
|
||||
import {
|
||||
@@ -1064,7 +1065,15 @@ export class BotInstance extends EventEmitter {
|
||||
isCancelled: () => !this.connected,
|
||||
onAttemptFailed: ({ attempt, total, quality, error }) => {
|
||||
const fields = { songId: song.id, name: song.name, attempt, total, quality };
|
||||
if (error) {
|
||||
if (error instanceof RiskControlError) {
|
||||
// -460 is NetEase refusing the IP, not this track. Say so, otherwise
|
||||
// the log reads like the song is unavailable and people go hunting
|
||||
// for a copyright problem that does not exist.
|
||||
this.logger.warn(
|
||||
{ ...fields, code: RISK_CONTROL_CODE, reason: error.message },
|
||||
"URL resolve hit NetEase risk control (-460) — backing off",
|
||||
);
|
||||
} else 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");
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { RiskControlError } from "../music/provider.js";
|
||||
import type { SongUrlResult } from "../music/provider.js";
|
||||
import {
|
||||
MAX_URL_RETRIES,
|
||||
DEFAULT_URL_RETRY_BACKOFF_MS,
|
||||
QUALITY_SWITCH_BACKOFF_MS,
|
||||
RISK_CONTROL_BACKOFF_MS,
|
||||
normalizeRetryCount,
|
||||
resolveUrlWithRetry,
|
||||
} from "./url-retry.js";
|
||||
@@ -309,3 +311,94 @@ describe("resolveUrlWithRetry — quality fallback", () => {
|
||||
expect(resolve).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// NetEase risk control (-460)
|
||||
//
|
||||
// Measured against a live host: `GET /song/url/v1?id=…&level=exhigh` without
|
||||
// the account cookie answers 400 `{"code":-460,"message":"检测到您的网络环境存在
|
||||
// 风险,请稍后再试"}` every single time, while the same call WITH the cookie
|
||||
// answers 200. Intermittently it also rejects the cookie call — that is the
|
||||
// "click play five times until it works" report.
|
||||
//
|
||||
// Because -460 is a 400, the normal 250ms re-poke lands inside the same risk
|
||||
// window and the whole budget is wasted. These tests pin the longer wait.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("resolveUrlWithRetry — risk control backoff", () => {
|
||||
it("grows the wait from RISK_CONTROL_BACKOFF_MS instead of 250ms", async () => {
|
||||
const { sleep, delays } = recordingSleep();
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 2,
|
||||
resolve: async () => {
|
||||
throw new RiskControlError("网络环境风险 (-460)");
|
||||
},
|
||||
sleep,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS, RISK_CONTROL_BACKOFF_MS * 2]);
|
||||
// Every one of them is longer than a plain transient retry would have been.
|
||||
for (const d of delays) expect(d).toBeGreaterThan(DEFAULT_URL_RETRY_BACKOFF_MS);
|
||||
});
|
||||
|
||||
it("does not fall back to the fast level-switch delay while risk controlled", async () => {
|
||||
const { sleep, delays } = recordingSleep();
|
||||
await resolveUrlWithRetry({
|
||||
retries: 0,
|
||||
resolve: async () => {
|
||||
throw new RiskControlError("网络环境风险 (-460)");
|
||||
},
|
||||
fallbacks: ["higher", "standard"],
|
||||
sleep,
|
||||
});
|
||||
|
||||
// -460 ignores which quality we ask for, so 120ms would just burn attempts.
|
||||
expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS, RISK_CONTROL_BACKOFF_MS]);
|
||||
expect(delays).not.toContain(QUALITY_SWITCH_BACKOFF_MS);
|
||||
});
|
||||
|
||||
it("recovers as soon as the window passes, and stops spending", async () => {
|
||||
let attempts = 0;
|
||||
const { sleep, delays } = recordingSleep();
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 3,
|
||||
resolve: async () => {
|
||||
attempts += 1;
|
||||
if (attempts < 3) throw new RiskControlError("网络环境风险 (-460)");
|
||||
return ok("https://cdn.example/after-window.mp3");
|
||||
},
|
||||
sleep,
|
||||
});
|
||||
|
||||
expect(result?.url).toBe("https://cdn.example/after-window.mp3");
|
||||
expect(attempts).toBe(3);
|
||||
expect(delays).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("still uses the short delay for a plain error", async () => {
|
||||
const { sleep, delays } = recordingSleep();
|
||||
await resolveUrlWithRetry({
|
||||
retries: 1,
|
||||
resolve: async () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
sleep,
|
||||
});
|
||||
expect(delays).toEqual([DEFAULT_URL_RETRY_BACKOFF_MS]);
|
||||
});
|
||||
|
||||
it("cancels during a risk-control wait", async () => {
|
||||
let cancelled = false;
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 3,
|
||||
resolve: async () => {
|
||||
throw new RiskControlError("网络环境风险 (-460)");
|
||||
},
|
||||
isCancelled: () => cancelled,
|
||||
sleep: async () => {
|
||||
cancelled = true;
|
||||
},
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
+21
-1
@@ -1,3 +1,4 @@
|
||||
import { RiskControlError } from "../music/provider.js";
|
||||
import type { SongUrlResult } from "../music/provider.js";
|
||||
|
||||
/**
|
||||
@@ -35,6 +36,17 @@ export const DEFAULT_URL_RETRY_BACKOFF_MS = 250;
|
||||
*/
|
||||
export const QUALITY_SWITCH_BACKOFF_MS = 120;
|
||||
|
||||
/**
|
||||
* Delay after a -460 (NetEase IP risk control) failure.
|
||||
*
|
||||
* This is the one failure mode where the delay is NOT cosmetic: the upstream
|
||||
* has decided the caller's address looks risky and will keep answering 400 for
|
||||
* a few seconds no matter what we ask. Re-poking after 250ms just burns the
|
||||
* budget. 800ms × attempt (800, 1600, …) covers roughly the window users
|
||||
* reported clicking through by hand, without stalling the queue for long.
|
||||
*/
|
||||
export const RISK_CONTROL_BACKOFF_MS = 800;
|
||||
|
||||
/**
|
||||
* Normalise a config value into a usable retry count.
|
||||
* Anything non-numeric (legacy config, `"3"`, `null`) means "no retries", which
|
||||
@@ -91,13 +103,20 @@ export async function resolveUrlWithRetry(
|
||||
for (const quality of opts.fallbacks ?? []) plan.push({ quality, fallback: true });
|
||||
|
||||
let sameQualityAttempt = 0;
|
||||
// Set when the previous attempt failed with -460. Risk control ignores the
|
||||
// quality we ask for, so a level switch does not get to use its short delay.
|
||||
let riskControlled = false;
|
||||
|
||||
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;
|
||||
const wait = riskControlled
|
||||
? RISK_CONTROL_BACKOFF_MS * Math.max(1, sameQualityAttempt)
|
||||
: 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;
|
||||
@@ -110,6 +129,7 @@ export async function resolveUrlWithRetry(
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
riskControlled = error instanceof RiskControlError;
|
||||
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;
|
||||
|
||||
Reference in new issue
Block a user