fix: isolate embedded music API credential logs

This commit is contained in:
TIANYAO ZHANG committed 2026-10-03 21:03:05 +08:00
1 parent a4c0239a59
commit 44a1457baa
5 files changed
+551 -290

No files matched your search

+160 -178
View File
@@ -1,16 +1,13 @@
import net from "node:net";
import { fork, type ChildProcess } from "node:child_process";
import type { Logger } from "../logger.js";
import type { Server } from "node:http";
import { getSafeApiStartupError, isApiPortFree, safeApiErrorCode, type ApiProvider, type SafeApiStartupError } from "./api-server-runtime.js";
export interface ApiServerOptions {
neteasePort: number;
qqMusicPort: number;
/** Provider gating (#enabledProviders): when false, the corresponding
* embedded sidecar API server is never started and its port never bound. */
neteaseEnabled?: boolean;
qqEnabled?: boolean;
}
export interface ApiServerManager {
start(): Promise<void>;
stop(): void;
@@ -18,196 +15,181 @@ export interface ApiServerManager {
getQQMusicBaseUrl(): string;
}
/**
* Classify a QQ Music API (@sansenjian/qq-music-api) startup failure into
* actionable operator guidance, or null when it isn't a recognised
* dependency/runtime mismatch. Exported for testing.
*
* Background: the package became ESM in 2.3.x. A loose `^` range could pull an
* ESM-only build (2.3.0/2.3.1) that throws ERR_REQUIRE_ESM, or a 2.4.x build
* that needs Node >=20.17 — either way the embedded server never binds, so
* every QQ request fails downstream with ECONNREFUSED on the API port.
*/
export function describeQqApiStartupError(err: unknown): string | null {
const e = (err ?? {}) as { code?: string; message?: string };
const code = String(e.code ?? "");
const msg = String(e.message ?? "");
if (code === "ERR_REQUIRE_ESM" || /ERR_REQUIRE_ESM|require\(\) of ES ?Module/i.test(msg)) {
return (
"an incompatible @sansenjian/qq-music-api build is installed (ERR_REQUIRE_ESM). " +
"Pin it to ~2.4.0 (needs Node >=20.17) or ~2.2.10 in package.json, then reinstall"
);
}
if (/Unsupported engine|EBADENGINE|requires Node|Node\.js version/i.test(msg)) {
return "@sansenjian/qq-music-api 2.4.x requires Node >=20.17 (or >=22.9) — upgrade Node, or pin the package to ~2.2.10";
}
const { category } = getSafeApiStartupError(err);
if (category === "esm") return "an incompatible @sansenjian/qq-music-api build is installed (ERR_REQUIRE_ESM). Pin it to ~2.4.0 (needs Node >=20.17) or ~2.2.10 in package.json, then reinstall";
if (category === "node-engine") return "@sansenjian/qq-music-api 2.4.x requires Node >=20.17 (or >=22.9) — upgrade Node, or pin the package to ~2.2.10";
return null;
}
function isPortFree(port: number): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
server.once("error", () => {
server.close(() => resolve(false));
});
server.once("listening", () => {
server.close(() => resolve(true));
});
server.listen(port, "127.0.0.1");
});
/** Carry only tsx loader arguments into a source child. CLI evaluation,
* inspector and test-runner flags have unrelated meanings in a fork. */
function childExecArgv(source: boolean): string[] {
if (!source) return [];
const args: string[] = [];
for (let i = 0; i < process.execArgv.length; i++) {
const arg = process.execArgv[i];
if (arg === "--import" || arg === "--require" || arg === "-r") {
const value = process.execArgv[++i];
if (value && (value === "tsx" || /[/\\]tsx[/\\]/.test(value))) args.push(arg, value);
} else if (arg.startsWith("--import=") && (arg === "--import=tsx" || /[/\\]tsx[/\\]/.test(arg))) args.push(arg);
}
return args.length ? args : ["--import", "tsx"];
}
export function createApiServerManager(
options: ApiServerOptions,
logger: Logger
): ApiServerManager {
let neteaseServer: Server | null = null;
let qqMusicServer: Server | null = null;
class StartupFailure extends Error {
constructor(readonly details: SafeApiStartupError) { super("Embedded music API startup failed"); }
}
interface ManagedChild {
child: ChildProcess;
stop(): Promise<void>;
}
const STARTUP_TIMEOUT_MS = 15000;
const ERROR_CATEGORIES = new Set(["esm", "node-engine", "port-in-use", "startup"]);
const neteaseBaseUrl = `http://127.0.0.1:${options.neteasePort}`;
const qqMusicBaseUrl = `http://127.0.0.1:${options.qqMusicPort}`;
export function createApiServerManager(options: ApiServerOptions, logger: Logger): ApiServerManager {
const children = new Map<ApiProvider, ManagedChild>();
let generation = 0;
let starting: Promise<void> | null = null;
let stopping: Promise<void> = Promise.resolve();
function launch(provider: ApiProvider, port: number, launchGeneration: number): Promise<void> {
const source = import.meta.url.endsWith(".ts");
const entry = new URL(source ? "./api-server-child.ts" : "./api-server-child.js", import.meta.url);
const child = fork(entry, [provider, String(port)], {
stdio: ["ignore", "ignore", "ignore", "ipc"],
execArgv: childExecArgv(source),
});
let ready = false;
let expectedExit = false;
let settled = false;
let hasExited = false;
let startupTimer: ReturnType<typeof setTimeout>;
let terminateTimer: ReturnType<typeof setTimeout> | undefined;
let killTimer: ReturnType<typeof setTimeout> | undefined;
let resolveExit!: () => void;
const exited = new Promise<void>((resolve) => { resolveExit = resolve; });
let resolveStart!: () => void;
let rejectStart!: (error: StartupFailure) => void;
const started = new Promise<void>((resolve, reject) => { resolveStart = resolve; rejectStart = reject; });
const settle = (error?: SafeApiStartupError) => {
if (settled) return;
settled = true;
clearTimeout(startupTimer);
if (error) rejectStart(new StartupFailure(error)); else resolveStart();
};
const record: ManagedChild = {
child,
stop() {
if (expectedExit) return exited;
expectedExit = true;
settle({ category: "cancelled" });
if (children.get(provider) === record) children.delete(provider);
stopping = Promise.all([stopping, exited]).then(() => {});
if (hasExited) return exited;
try {
if (child.connected) child.send({ type: "stop" }, (error) => { if (error) child.kill("SIGTERM"); });
else child.kill("SIGTERM");
} catch { child.kill("SIGTERM"); }
terminateTimer = setTimeout(() => child.kill("SIGTERM"), 1000);
killTimer = setTimeout(() => child.kill("SIGKILL"), 2000);
terminateTimer.unref(); killTimer.unref();
return exited;
},
};
children.set(provider, record);
child.on("message", (message: unknown) => {
if (!message || typeof message !== "object" || expectedExit || launchGeneration !== generation) return;
const data = message as Record<string, unknown>;
if (data.provider !== provider || data.port !== port) return;
if (data.type === "ready") { ready = true; settle(); }
else if (data.type === "error" && typeof data.category === "string" && ERROR_CATEGORIES.has(data.category)) {
const code = safeApiErrorCode(data.code);
const details: SafeApiStartupError = { category: data.category as SafeApiStartupError["category"], ...(code ? { code } : {}) };
if (!ready) settle(details);
else logger.error({ provider, port, ...details }, "Embedded music API reported a runtime failure");
void record.stop();
}
});
child.on("error", (error) => {
if (expectedExit) return;
const details = getSafeApiStartupError(error);
if (!ready) settle(details);
else logger.error({ provider, port, ...details }, "Embedded music API child failed");
void record.stop();
});
const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
if (hasExited) return;
hasExited = true;
clearTimeout(startupTimer); clearTimeout(terminateTimer); clearTimeout(killTimer);
if (children.get(provider) === record) children.delete(provider);
if (!expectedExit) {
if (ready) logger.error({ provider, port, code, signal }, "Embedded music API exited unexpectedly");
else settle({ category: "startup" });
}
resolveExit();
};
child.once("exit", onExit);
// A failed fork emits close without exit.
child.once("close", onExit);
startupTimer = setTimeout(() => { settle({ category: "timeout" }); void record.stop(); }, STARTUP_TIMEOUT_MS);
return started;
}
return {
async start(): Promise<void> {
// Provider gating: with the jellyfin-only default config neither legacy
// sidecar starts, so ports 3001/3200 are never opened.
if (options.neteaseEnabled === false && options.qqEnabled === false) {
logger.info("NetEase/QQ providers disabled — embedded music API servers not started");
return;
}
logger.info("Starting embedded music API servers...");
// Start NetEase Cloud Music API
if (options.neteaseEnabled !== false) {
try {
const portFree = await isPortFree(options.neteasePort);
if (!portFree) {
logger.info(
{ port: options.neteasePort },
"NetEase API port already in use — reusing existing instance"
);
} else {
const ncmModule = await import("NeteaseCloudMusicApi") as any;
const serverObj = ncmModule.server ?? ncmModule.default?.server;
const app = await serverObj.serveNcmApi({ port: options.neteasePort });
neteaseServer = app;
logger.info(
{ port: options.neteasePort },
"NetEase Cloud Music API started"
);
}
} catch (err) {
logger.error({ err }, "Failed to start NetEase Cloud Music API");
start(): Promise<void> {
if (starting) return starting;
const startGeneration = generation;
const run = async () => {
await stopping;
if (startGeneration !== generation) return;
if (options.neteaseEnabled === false && options.qqEnabled === false) {
logger.info("NetEase/QQ providers disabled — embedded music API servers not started"); return;
}
}
// Start QQ Music API. Older versions auto-started on import; the
// current fork (2.2.11+) only listens when run as `require.main`,
// so we explicitly call .listen() on the imported Koa app and keep
// the server handle for clean shutdown.
if (options.qqEnabled === false) return;
try {
const portFree = await isPortFree(options.qqMusicPort);
if (!portFree) {
logger.info(
{ port: options.qqMusicPort },
"QQ Music API port already in use — reusing existing instance"
);
} else {
// Pin the upstream server to the configured port before importing.
// The package derives its default port from process.env.PORT (falling
// back to 3200) and, in some historical versions, auto-started that
// server as an import side effect. Aligning PORT with qqMusicApiPort
// guarantees the sidecar can never bind a different port than the one
// the client base URL (getQQMusicBaseUrl) targets — the root cause of
// issue #122, where an old build listened on 3300 while the client
// requested 3200. Restore the previous value right after import so we
// never leak the override into the rest of the process (e.g. the web
// server or the NetEase sidecar, which also read PORT as a fallback).
const prevPortEnv = process.env.PORT;
process.env.PORT = String(options.qqMusicPort);
let qqModule: any;
logger.info("Starting embedded music API servers...");
const providers: Array<{ provider: ApiProvider; port: number; enabled: boolean; name: string }> = [
{ provider: "netease", port: options.neteasePort, enabled: options.neteaseEnabled !== false, name: "NetEase Cloud Music" },
{ provider: "qq", port: options.qqMusicPort, enabled: options.qqEnabled !== false, name: "QQ Music" },
];
for (const { provider, port, enabled, name } of providers) {
if (startGeneration !== generation) return;
if (!enabled || children.has(provider)) continue;
try {
qqModule = (await import("@sansenjian/qq-music-api")) as any;
} finally {
if (prevPortEnv === undefined) delete process.env.PORT;
else process.env.PORT = prevPortEnv;
}
// The module's export structure varies between versions:
// 2.2.11+: default → Koa app (has .listen)
// 2.2.10: default → wrapper object whose .default is the Koa app
// older: module itself may be the Koa app
const candidate = qqModule.default ?? qqModule;
const koaApp = typeof candidate.listen === "function"
? candidate
: candidate.default ?? null;
if (koaApp && typeof koaApp.listen === "function") {
// A version that auto-started on import has already bound the
// configured port (thanks to the PORT alignment above); reuse it
// rather than racing a second listen that would fail EADDRINUSE.
const stillFree = await isPortFree(options.qqMusicPort);
if (!stillFree) {
logger.info(
{ port: options.qqMusicPort },
"QQ Music API already listening on the configured port (auto-started on import) — reusing embedded instance"
);
} else {
qqMusicServer = await new Promise<Server>((resolve, reject) => {
const srv = koaApp.listen(options.qqMusicPort, "127.0.0.1", () =>
resolve(srv)
);
srv.on("error", reject);
});
// Log the port actually bound (read from the socket) rather than
// the requested one, so operators can spot a mismatch in the logs.
const addr = qqMusicServer.address();
const boundPort =
addr && typeof addr === "object" && addr !== null
? addr.port
: options.qqMusicPort;
logger.info(
{ port: boundPort },
"QQ Music API started"
);
const free = await isApiPortFree(port);
if (startGeneration !== generation) return;
if (!free) {
logger.info({ port }, `${provider === "netease" ? "NetEase" : "QQ Music"} API port already in use — reusing existing instance`);
continue;
}
} else {
logger.warn("QQ Music API module does not expose a Koa app");
await launch(provider, port, startGeneration);
if (startGeneration !== generation) return;
logger.info({ port }, `${name} API started`);
} catch (error) {
if (startGeneration !== generation) return;
const details = error instanceof StartupFailure ? error.details : getSafeApiStartupError(error);
if (details.category === "cancelled") return;
const hint = provider === "qq" ? describeQqApiStartupError(details.category === "esm" ? { code: "ERR_REQUIRE_ESM" } : details.category === "node-engine" ? { code: "EBADENGINE" } : {}) : null;
logger.error({ provider, port, ...details }, hint ? `QQ Music API failed to start — ${hint}. QQ features (search/play/login) will be unavailable until fixed; port ${port} is down.` : `Failed to start ${name} API`);
}
}
} catch (err) {
const hint = describeQqApiStartupError(err);
if (hint) {
logger.error(
{ err },
`QQ Music API failed to start — ${hint}. QQ features (search/play/login) will be unavailable until fixed; port ${options.qqMusicPort} is down.`
);
} else {
logger.warn(
{ err },
"QQ Music API not available — QQ Music features may be limited"
);
}
}
};
const promise = run();
starting = promise;
void promise.finally(() => { if (starting === promise) starting = null; });
return promise;
},
stop(): void {
generation++;
const pendingStart = starting;
starting = null;
logger.info("Stopping music API servers");
if (neteaseServer && typeof (neteaseServer as any).close === "function") {
(neteaseServer as any).close();
}
neteaseServer = null;
if (qqMusicServer && typeof (qqMusicServer as any).close === "function") {
(qqMusicServer as any).close();
}
qqMusicServer = null;
},
getNeteaseBaseUrl(): string {
return neteaseBaseUrl;
},
getQQMusicBaseUrl(): string {
return qqMusicBaseUrl;
const retiring = [...children.values()];
children.clear();
// A cancelled preflight still owns a temporary listening socket until
// its callback closes it. Restart must wait for that work as well.
stopping = Promise.all([stopping, pendingStart, ...retiring.map((record) => record.stop())]).then(() => {});
},
getNeteaseBaseUrl: () => `http://127.0.0.1:${options.neteasePort}`,
getQQMusicBaseUrl: () => `http://127.0.0.1:${options.qqMusicPort}`,
};
}