mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-03 11:22: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
@@ -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=<account 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<unknown>) {
|
||||
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, "<html>Bad Request</html>");
|
||||
});
|
||||
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);
|
||||
});
|
||||
});
|
||||
+29
-3
@@ -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<SongUrlResult | null> {
|
||||
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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user