From 0f3bc0f54d25ba2bf71c9b828421c7dbdc00a7ff Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Tue, 22 Sep 2026 01:24:13 +0300 Subject: [PATCH] hotfix(better) --- index.mjs | 40 ++++++++++ src/db/DatabaseManager.mjs | 6 +- src/db/MysqlGuard.mjs | 93 ++++++++++++++++++++++++ src/db/Settings.mjs | 4 +- src/music/bilibili/BilibiliProxy.mjs | 3 + src/services/FluxerListManager.mjs | 1 + src/services/TrackOptionsManager.mjs | 4 +- src/services/lastfm/LastFmManager.mjs | 3 + src/services/lastfm/UserQueriesMixin.mjs | 2 + src/services/lastfm/constants.mjs | 6 +- 10 files changed, 156 insertions(+), 6 deletions(-) create mode 100644 src/db/MysqlGuard.mjs diff --git a/index.mjs b/index.mjs index 1755d09..5992b26 100644 --- a/index.mjs +++ b/index.mjs @@ -45,8 +45,39 @@ const isBenignAudioStopRace = (err) => const isBenignStreamAbortRace = (err) => err?.code === "ECONNRESET" && String(err?.message ?? "").includes("aborted"); +/** + * Socket error codes that represent transient transport failures of a single + * connection (NAT/firewall idle drops, dead upstreams, restarts). Losing one + * TCP connection is never a reason to take the whole bot down. + * @type {Set} + */ +const TRANSIENT_SOCKET_CODES = new Set([ + "ETIMEDOUT", "ECONNRESET", "EPIPE", "ECONNABORTED", + "EHOSTUNREACH", "ENETUNREACH", "ENETDOWN", "EAI_AGAIN", +]); + +/** + * Check whether an error is a raw transport-level socket failure that bubbled + * out of a library's internals (mysql2 pooled connections, undici, ws, etc.) + * with no user stack frames involved. The owning library has already recorded + * the failure in its own state machine (marked the connection dead, destroyed + * the request...), so continuing to run is safe — crashing is not. + * Signature example: { errno: -110, code: 'ETIMEDOUT', syscall: 'read', + * fatal: true } at TCP.onStreamRead. + * @param {Error} err - The error to check. + * @returns {boolean} True if the error is a recoverable socket transport error. + */ +const isBenignTransportError = (err) => { + if (!err || typeof err !== "object") return false; + if (!TRANSIENT_SOCKET_CODES.has(err.code)) return false; + if (!err.syscall || !["read", "write", "connect", "getaddrinfo"].includes(err.syscall)) return false; + const stack = String(err.stack ?? ""); + return !stack.includes("/src/") && !stack.includes("/commands/") && !stack.includes("index.mjs"); +}; + let _lastWsCrashLog = 0; let _lastAudioRaceLog = 0; +let _lastTransportLog = 0; const WS_CRASH_LOG_COOLDOWN = 30_000; process.on("unhandledRejection", (reason, p) => { @@ -80,6 +111,14 @@ process.on("uncaughtException", (err, origin) => { } return; } + if (isBenignTransportError(err)) { + const now = Date.now(); + if (now - _lastTransportLog > WS_CRASH_LOG_COOLDOWN) { + _lastTransportLog = now; + logger.warn("[Error_Handling] Recovered from transient socket transport error (" + (err.code ?? "?") + " on " + (err.syscall ?? "?") + ") — connection-level failure, bot continues running (will not re-log for 30s)."); + } + return; + } logger.error("[Error_Handling] Uncaught Exception/Catch"); logger.error("Error:", err, origin); process.exit(1); @@ -89,6 +128,7 @@ process.on("uncaughtExceptionMonitor", (err, origin) => { if (isIgnorableWsCrash(err)) return; if (isBenignAudioStopRace(err)) return; if (isBenignStreamAbortRace(err)) return; + if (isBenignTransportError(err)) return; logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)"); logger.error("Error:", err, origin); }); diff --git a/src/db/DatabaseManager.mjs b/src/db/DatabaseManager.mjs index 66e7f24..358829c 100644 --- a/src/db/DatabaseManager.mjs +++ b/src/db/DatabaseManager.mjs @@ -7,6 +7,7 @@ import { compare, genSalt, hash } from "bcryptjs"; import { createPool } from "mysql2/promise"; import { logger } from "../core/Logger.mjs"; +import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs"; /** * @class @@ -20,12 +21,11 @@ export class DatabaseManager { */ constructor(config) { this.db = createPool({ + ...MYSQL_POOL_DEFAULTS, connectionLimit: 15, ...config, }); - this.db.on("error", (err) => { - logger.error("[DashboardDB] MySQL pool error:", err.code ?? err.message); - }); + attachMysqlPoolGuard(this.db, "DashboardDB"); } /** diff --git a/src/db/MysqlGuard.mjs b/src/db/MysqlGuard.mjs new file mode 100644 index 0000000..0ea54af --- /dev/null +++ b/src/db/MysqlGuard.mjs @@ -0,0 +1,93 @@ +/** + * @module src/db/MysqlGuard + * @description Hardening for mysql2 connection pools against fatal socket + * errors (read ETIMEDOUT / ECONNRESET / EPIPE) escaping as uncaughtException. + * + * ## The problem this solves + * + * mysql2's `PoolConnection` registers only `once("error")`. The FIRST error + * event on a pooled connection is silently consumed (the connection is removed + * from the pool) — but any SUBSEQUENT `"error"` emission on that same + * connection object has zero listeners and crashes the whole process with an + * uncaughtException. This is a real-world scenario: when a NAT/firewall + * silently drops an idle pooled connection, the next I/O attempt produces a + * raw `read ETIMEDOUT` (errno -110, fatal: true) that surfaces exactly this + * way. mysql2's `Pool` itself NEVER emits `"error"`, so pool-level + * `pool.on("error", ...)` handlers (as used elsewhere in this codebase) do not + * and cannot catch connection-level socket errors. + * + * ## The fix + * + * 1. `MYSQL_POOL_DEFAULTS` — spread into every `createPool()` call. + * `enableKeepAlive` sends TCP keepalive probes so idle connections survive + * NAT/firewall idle timeouts instead of dying silently. + * 2. `attachMysqlPoolGuard(pool)` — listens on the core pool's + * `"connection"` event and attaches a persistent (non-`once`) error + * listener to every newly created pooled connection. After mysql2's + * internal `once("error")` has done its job (removing the dead connection + * from the pool), any further emissions are swallowed instead of crashing + * the process. In-flight queries still receive their rejections normally. + * + * Both helpers are idempotent (guarded by WeakSets) so they can safely be + * called twice on the same pool. + */ + +import { logger } from "../core/Logger.mjs"; + +/** + * @type {object} + * @description Pool config defaults that prevent idle-connection death. + * `enableKeepAlive` is the critical one — without TCP keepalive probes, a + * connection parked in the pool behind a NAT/firewall is silently dropped and + * the next query on it dies with read ETIMEDOUT. + */ +const MYSQL_POOL_DEFAULTS = { + enableKeepAlive: true, + keepAliveInitialDelay: 10_000, +}; + +/** + * @type {WeakSet} + * @description Pools already guarded (core callback pools). + */ +const _guardedPools = new WeakSet(); + +/** + * Attach the persistent connection-level error guard to a mysql2 pool. + * Accepts either a callback-API `Pool` (from `mysql2`) or a `PromisePool` + * (from `mysql2/promise`) — the core pool is resolved automatically. + * Idempotent: calling twice on the same pool is a no-op. + * @param {object} pool - mysql2 Pool or PromisePool instance. + * @param {string} [label="MySQL"] - Label used in log lines. + * @returns {object} The core (callback-API) pool that was guarded. + */ +function attachMysqlPoolGuard(pool, label = "MySQL") { + if (!pool) return pool; + const corePool = typeof pool.getConnection === "function" && pool.pool && pool.pool.getConnection + ? pool.pool + : pool; + if (!corePool || typeof corePool.on !== "function" || _guardedPools.has(corePool)) { + return corePool ?? pool; + } + _guardedPools.add(corePool); + + corePool.on("connection", (connection) => { + if (!connection || connection.__mysqlGuardAttached) return; + connection.__mysqlGuardAttached = true; + connection.on("error", (err) => { + logger.warn( + `[${label}] Pooled MySQL connection error (handled, pool will recycle):`, + err?.code ?? err?.message ?? err + ); + }); + }); + + corePool.on("error", (err) => { + logger.error(`[${label}] MySQL pool error:`, err?.code ?? err?.message ?? err); + }); + + return corePool; +} + +export { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard }; +export default { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard }; diff --git a/src/db/Settings.mjs b/src/db/Settings.mjs index 7523b62..c9d1547 100644 --- a/src/db/Settings.mjs +++ b/src/db/Settings.mjs @@ -8,6 +8,7 @@ import fs from "node:fs"; import mysql from "mysql2"; import { EventEmitter } from "node:events"; +import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs"; import { logger } from "../core/Logger.mjs"; /** @@ -183,7 +184,8 @@ export class RemoteSettingsManager extends SettingsManager { constructor(config, defaultsPath, botId = null) { super(); this.botId = botId; - this.db = mysql.createPool({ connectionLimit: 15, ...config }); + this.db = mysql.createPool({ ...MYSQL_POOL_DEFAULTS, connectionLimit: 15, ...config }); + attachMysqlPoolGuard(this.db, "DB"); this.db.on('error', (err) => { logger.error('[DB] MySQL pool error:', err.code ?? err.message); }); diff --git a/src/music/bilibili/BilibiliProxy.mjs b/src/music/bilibili/BilibiliProxy.mjs index 64b43ea..c8453e1 100644 --- a/src/music/bilibili/BilibiliProxy.mjs +++ b/src/music/bilibili/BilibiliProxy.mjs @@ -235,6 +235,9 @@ export function ensureBilibiliProxy() { _starting = null; reject(new Error("bilibili proxy failed to listen on " + _cfg.bind + ":" + _cfg.port + ": " + err.message)); }); + server.on("error", (err) => { + logger.warn("[BilibiliProxy] server error: " + (err?.message || err)); + }); server.unref?.(); } catch (e) { _starting = null; diff --git a/src/services/FluxerListManager.mjs b/src/services/FluxerListManager.mjs index 888db11..3a919e6 100644 --- a/src/services/FluxerListManager.mjs +++ b/src/services/FluxerListManager.mjs @@ -93,6 +93,7 @@ export class FluxerListManager { "Accept": "application/json", "User-Agent": "RemixBot/1.0 (FluxerList Integration)", }, + signal: AbortSignal.timeout(15_000), }); if (res.status === 401) { diff --git a/src/services/TrackOptionsManager.mjs b/src/services/TrackOptionsManager.mjs index 50d08b6..f26cba4 100644 --- a/src/services/TrackOptionsManager.mjs +++ b/src/services/TrackOptionsManager.mjs @@ -1,6 +1,7 @@ /** @module src/services/TrackOptionsManager @description Per-user track options (start/end timestamps) stored in MySQL. Provides caching, matching, and CRUD for track segments. */ import mysql from "mysql2"; import { logger } from "../core/Logger.mjs"; +import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "../db/MysqlGuard.mjs"; const DEFAULT_ALIAS = "default"; const MAX_ALIAS_LEN = 32; @@ -24,7 +25,8 @@ export class TrackOptionsManager { /** @param {object} mysqlConfig - MySQL connection config. */ constructor(mysqlConfig) { - this.db = mysql.createPool({ connectionLimit: 10, ...mysqlConfig }); + this.db = mysql.createPool({ ...MYSQL_POOL_DEFAULTS, connectionLimit: 10, ...mysqlConfig }); + attachMysqlPoolGuard(this.db, "TrackOptions"); this.db.on("error", (err) => { logger.error("[TrackOptions] MySQL pool error:", err.code ?? err.message); }); diff --git a/src/services/lastfm/LastFmManager.mjs b/src/services/lastfm/LastFmManager.mjs index c885886..cb36248 100644 --- a/src/services/lastfm/LastFmManager.mjs +++ b/src/services/lastfm/LastFmManager.mjs @@ -14,6 +14,7 @@ import { logger } from "../../core/Logger.mjs"; import { normalizeTrackText } from "./constants.mjs"; import { applyMixins } from "../../utils/mixins.mjs"; import { parseLastFmUrl, isLastFmUrl } from "./urlUtils.mjs"; +import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "../../db/MysqlGuard.mjs"; import UserStoreMixin from "./UserStoreMixin.mjs"; import ScrobblingMixin from "./ScrobblingMixin.mjs"; import TrackQueriesMixin from "./TrackQueriesMixin.mjs"; @@ -140,12 +141,14 @@ export class LastFmManager { if (this._pool) return this._pool; const mysql = await import("mysql2/promise"); this._pool = mysql.createPool({ + ...MYSQL_POOL_DEFAULTS, host: this._mysqlConfig.host, port: this._mysqlConfig.port ?? 3306, user: this._mysqlConfig.user, password: this._mysqlConfig.password, database: this._mysqlConfig.database, }); + attachMysqlPoolGuard(this._pool, "LastFm"); await this._initTable(); return this._pool; } diff --git a/src/services/lastfm/UserQueriesMixin.mjs b/src/services/lastfm/UserQueriesMixin.mjs index 53fefe4..94b2772 100644 --- a/src/services/lastfm/UserQueriesMixin.mjs +++ b/src/services/lastfm/UserQueriesMixin.mjs @@ -184,6 +184,7 @@ const UserQueriesMixin = { const profileUrl = `https://www.last.fm/user/${encodeURIComponent(user.username)}/playlists`; const res = await fetch(profileUrl, { headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" }, + signal: AbortSignal.timeout(15_000), }); if (!res.ok) { @@ -250,6 +251,7 @@ const UserQueriesMixin = { const res = await fetch(playlistUrl, { headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" }, + signal: AbortSignal.timeout(15_000), }); if (!res.ok) { diff --git a/src/services/lastfm/constants.mjs b/src/services/lastfm/constants.mjs index 5516492..14003ce 100644 --- a/src/services/lastfm/constants.mjs +++ b/src/services/lastfm/constants.mjs @@ -23,6 +23,9 @@ function buildSignature(params, apiSecret) { return crypto.createHash("md5").update(str + apiSecret).digest("hex"); } +/** @private @type {number} @description AbortSignal timeout (ms) for Last.fm API calls — prevents stalled TCP connections from hanging for the OS-level timeout (~15 min). */ +const LASTFM_FETCH_TIMEOUT_MS = 15_000; + /** @private Make an authenticated Last.fm API call. @async @param {object} params @param {string} apiSecret @param {boolean} [post=false] @returns {Promise} @throws {Error} On HTTP or Last.fm API error. */ async function apiCall(params, apiSecret, post = false) { const allParams = { ...params }; @@ -36,8 +39,9 @@ async function apiCall(params, apiSecret, post = false) { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(allParams).toString(), + signal: AbortSignal.timeout(LASTFM_FETCH_TIMEOUT_MS), } - : {}; + : { signal: AbortSignal.timeout(LASTFM_FETCH_TIMEOUT_MS) }; const res = await fetch(url, opts); if (!res.ok) {