From e9995c1e303857cd072d4f178443da9afcc28883 Mon Sep 17 00:00:00 2001 From: jiayuLian Date: Sun, 8 Nov 2026 17:53:43 +0800 Subject: [PATCH] fix(playback): back off properly when NetEase risk control answers -460 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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= → 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. --- src/bot/instance.ts | 11 ++++- src/bot/url-retry.test.ts | 93 +++++++++++++++++++++++++++++++++++++++ src/bot/url-retry.ts | 22 ++++++++- src/music/netease.test.ts | 72 ++++++++++++++++++++++++++++++ src/music/netease.ts | 32 ++++++++++++-- src/music/provider.ts | 28 ++++++++++++ 6 files changed, 253 insertions(+), 5 deletions(-) diff --git a/src/bot/instance.ts b/src/bot/instance.ts index e87cddb..b16ba79 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -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"); diff --git a/src/bot/url-retry.test.ts b/src/bot/url-retry.test.ts index b4cfef3..565b422 100644 --- a/src/bot/url-retry.test.ts +++ b/src/bot/url-retry.test.ts @@ -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(); + }); +}); diff --git a/src/bot/url-retry.ts b/src/bot/url-retry.ts index 58ebf41..2250eec 100644 --- a/src/bot/url-retry.ts +++ b/src/bot/url-retry.ts @@ -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; diff --git a/src/music/netease.test.ts b/src/music/netease.test.ts index bffd55c..587f7eb 100644 --- a/src/music/netease.test.ts +++ b/src/music/netease.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi } from "vitest"; +import { RiskControlError } from "./provider.js"; import { parseLyrics, mapNeteaseAlbums, @@ -343,3 +344,74 @@ describe("NetEase quality fallback ladder", () => { expect(p.getFallbackQualities()).toEqual(["standard"]); }); }); + +// --------------------------------------------------------------------------- +// Risk control (-460) +// +// Live measurement on a cloud host, same song, same second: +// GET /song/url/v1?id=1827600686&level=exhigh → 400 {"code":-460} +// GET …&cookie= → 200, 320k url +// axios reports both 400s and 200s alike as ERR_BAD_REQUEST when it fails, so +// the body has to be inspected to know whether retrying is worthwhile. +// --------------------------------------------------------------------------- +describe("NetEase risk control (-460)", () => { + /** Swap the axios instance for a stub — no module mocking needed. */ + function providerWithApi(get: (url: string, cfg: unknown) => Promise) { + const p = new NeteaseProvider("http://127.0.0.1:3001"); + (p as unknown as { api: { get: typeof get } }).api = { get }; + return p; + } + + function httpError(status: number, data: unknown) { + const err = new Error(`Request failed with status code ${status}`) as Error & { + response: unknown; + }; + err.response = { status, data }; + return err; + } + + it("turns 400 + code -460 into a RiskControlError", async () => { + const p = providerWithApi(async () => { + throw httpError(400, { + code: -460, + message: "检测到您的网络环境存在风险,请稍后再试", + }); + }); + await expect(p.getSongUrl("1827600686")).rejects.toBeInstanceOf(RiskControlError); + }); + + it("keeps the upstream message so the log says what happened", async () => { + const p = providerWithApi(async () => { + throw httpError(400, { code: -460, message: "检测到您的网络环境存在风险,请稍后再试" }); + }); + await expect(p.getSongUrl("1827600686")).rejects.toThrow(/风险/); + }); + + it("does not disguise a genuine bad request", async () => { + const p = providerWithApi(async () => { + throw httpError(400, { code: 400, msg: "参数错误" }); + }); + await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError); + }); + + it("does not disguise an unrelated 400 without a body code", async () => { + const p = providerWithApi(async () => { + throw httpError(400, "Bad Request"); + }); + await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError); + }); + + it("still returns null for a 200 that carries no url", async () => { + const p = providerWithApi(async () => ({ data: { data: [{ url: null, code: 404 }] } })); + expect(await p.getSongUrl("1")).toBeNull(); + }); + + it("returns the url and the trial window on success", async () => { + const p = providerWithApi(async () => ({ + data: { data: [{ url: "http://cdn.example/x.mp3", freeTrialInfo: { start: 0, end: 60 } }] }, + })); + const r = await p.getSongUrl("1"); + expect(r?.url).toBe("http://cdn.example/x.mp3"); + expect(r?.trialDuration).toBe(60); + }); +}); diff --git a/src/music/netease.ts b/src/music/netease.ts index 07bc429..b513678 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -1,4 +1,5 @@ import axios, { type AxiosInstance } from "axios"; +import { RISK_CONTROL_CODE, RiskControlError } from "./provider.js"; import type { MusicProvider, Song, @@ -114,6 +115,21 @@ export function parseNeteaseTrial(item: any): number | undefined { return Math.round(secs); } +/** + * Recognise NetEase's IP risk control inside an axios error. The status alone + * is not enough — axios reports every 4xx as ERR_BAD_REQUEST — so the body has + * to be read. See RiskControlError for the measured behaviour. + */ +function riskControlFrom(err: unknown): RiskControlError | null { + const e = err as { + response?: { status?: number; data?: { code?: number; message?: string } }; + }; + if (e?.response?.status === 400 && e.response.data?.code === RISK_CONTROL_CODE) { + return new RiskControlError(e.response.data.message ?? "网络环境风险 (-460)"); + } + return null; +} + // NetEase quality levels: standard(128k) higher(192k) exhigh(320k) lossless(flac) hires(hi-res) jyeffect jymaster export const NETEASE_QUALITY_LEVELS = [ { value: "standard", label: "标准 (128kbps)", bitrate: 128 }, @@ -197,9 +213,19 @@ export class NeteaseProvider implements MusicProvider { async getSongUrl(songId: string, quality?: string): Promise { const level = quality ?? this.quality; - const res = await this.api.get("/song/url/v1", { - params: { id: songId, level, ...this.cookieParams }, - }); + let res; + try { + res = await this.api.get("/song/url/v1", { + params: { id: songId, level, ...this.cookieParams }, + }); + } catch (err) { + // -460 arrives as HTTP 400, and left as-is it looks like "this track is + // unavailable" to every caller. Surface it as its own error type so the + // retry layer can wait out the risk-control window instead of giving up. + const risk = riskControlFrom(err); + if (risk) throw risk; + throw err; + } const item = res.data?.data?.[0]; const url = item?.url; if (!url) return null; diff --git a/src/music/provider.ts b/src/music/provider.ts index 890b5ed..d7e6e5b 100644 --- a/src/music/provider.ts +++ b/src/music/provider.ts @@ -34,6 +34,34 @@ export interface SongUrlResult { trialDuration?: number; } +/** + * NetEase rate-limits by IP, not by request shape. When it decides the caller's + * network looks risky it answers **HTTP 400** with + * + * {"code":-460,"message":"检测到您的网络环境存在风险,请稍后再试"} + * + * Cloud-host IPs hit this constantly; it clears up on its own after a few + * seconds. Because it is a 4xx, axios reports `ERR_BAD_REQUEST` — identical to + * a genuinely malformed request — so the only way to tell them apart is to read + * the response body. The distinction matters: -460 is worth retrying, a bad + * request never is. + * + * Measured on a live host: the anonymous call `?id=…&level=exhigh` answered + * 400/-460 every time, while the same call with the account cookie answered 200 + * and returned a full 320k URL. Intermittently, the cookie version is also + * rejected — which is exactly the "click play five times until it works" + * behaviour users report. + */ +export const RISK_CONTROL_CODE = -460; + +export class RiskControlError extends Error { + readonly code: number = RISK_CONTROL_CODE; + constructor(message: string) { + super(message); + this.name = "RiskControlError"; + } +} + export interface Playlist { id: string; name: string;