mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
hotfix(better)
This commit is contained in:
1 parent
3ea34c7f19
commit
0f3bc0f54d
10 files changed
+156
-6
No files matched your search
@@ -45,8 +45,39 @@ const isBenignAudioStopRace = (err) =>
|
|||||||
const isBenignStreamAbortRace = (err) =>
|
const isBenignStreamAbortRace = (err) =>
|
||||||
err?.code === "ECONNRESET" && String(err?.message ?? "").includes("aborted");
|
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<string>}
|
||||||
|
*/
|
||||||
|
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 _lastWsCrashLog = 0;
|
||||||
let _lastAudioRaceLog = 0;
|
let _lastAudioRaceLog = 0;
|
||||||
|
let _lastTransportLog = 0;
|
||||||
const WS_CRASH_LOG_COOLDOWN = 30_000;
|
const WS_CRASH_LOG_COOLDOWN = 30_000;
|
||||||
|
|
||||||
process.on("unhandledRejection", (reason, p) => {
|
process.on("unhandledRejection", (reason, p) => {
|
||||||
@@ -80,6 +111,14 @@ process.on("uncaughtException", (err, origin) => {
|
|||||||
}
|
}
|
||||||
return;
|
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_Handling] Uncaught Exception/Catch");
|
||||||
logger.error("Error:", err, origin);
|
logger.error("Error:", err, origin);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@@ -89,6 +128,7 @@ process.on("uncaughtExceptionMonitor", (err, origin) => {
|
|||||||
if (isIgnorableWsCrash(err)) return;
|
if (isIgnorableWsCrash(err)) return;
|
||||||
if (isBenignAudioStopRace(err)) return;
|
if (isBenignAudioStopRace(err)) return;
|
||||||
if (isBenignStreamAbortRace(err)) return;
|
if (isBenignStreamAbortRace(err)) return;
|
||||||
|
if (isBenignTransportError(err)) return;
|
||||||
logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)");
|
logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)");
|
||||||
logger.error("Error:", err, origin);
|
logger.error("Error:", err, origin);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import { compare, genSalt, hash } from "bcryptjs";
|
import { compare, genSalt, hash } from "bcryptjs";
|
||||||
import { createPool } from "mysql2/promise";
|
import { createPool } from "mysql2/promise";
|
||||||
import { logger } from "../core/Logger.mjs";
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @class
|
* @class
|
||||||
@@ -20,12 +21,11 @@ export class DatabaseManager {
|
|||||||
*/
|
*/
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
this.db = createPool({
|
this.db = createPool({
|
||||||
|
...MYSQL_POOL_DEFAULTS,
|
||||||
connectionLimit: 15,
|
connectionLimit: 15,
|
||||||
...config,
|
...config,
|
||||||
});
|
});
|
||||||
this.db.on("error", (err) => {
|
attachMysqlPoolGuard(this.db, "DashboardDB");
|
||||||
logger.error("[DashboardDB] MySQL pool error:", err.code ?? err.message);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -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<object>}
|
||||||
|
* @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 };
|
||||||
+3
-1
@@ -8,6 +8,7 @@
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import mysql from "mysql2";
|
import mysql from "mysql2";
|
||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
|
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
|
||||||
import { logger } from "../core/Logger.mjs";
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -183,7 +184,8 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
constructor(config, defaultsPath, botId = null) {
|
constructor(config, defaultsPath, botId = null) {
|
||||||
super();
|
super();
|
||||||
this.botId = botId;
|
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) => {
|
this.db.on('error', (err) => {
|
||||||
logger.error('[DB] MySQL pool error:', err.code ?? err.message);
|
logger.error('[DB] MySQL pool error:', err.code ?? err.message);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -235,6 +235,9 @@ export function ensureBilibiliProxy() {
|
|||||||
_starting = null;
|
_starting = null;
|
||||||
reject(new Error("bilibili proxy failed to listen on " + _cfg.bind + ":" + _cfg.port + ": " + err.message));
|
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?.();
|
server.unref?.();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
_starting = null;
|
_starting = null;
|
||||||
|
|||||||
@@ -93,6 +93,7 @@ export class FluxerListManager {
|
|||||||
"Accept": "application/json",
|
"Accept": "application/json",
|
||||||
"User-Agent": "RemixBot/1.0 (FluxerList Integration)",
|
"User-Agent": "RemixBot/1.0 (FluxerList Integration)",
|
||||||
},
|
},
|
||||||
|
signal: AbortSignal.timeout(15_000),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
|
|||||||
@@ -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. */
|
/** @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 mysql from "mysql2";
|
||||||
import { logger } from "../core/Logger.mjs";
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "../db/MysqlGuard.mjs";
|
||||||
|
|
||||||
const DEFAULT_ALIAS = "default";
|
const DEFAULT_ALIAS = "default";
|
||||||
const MAX_ALIAS_LEN = 32;
|
const MAX_ALIAS_LEN = 32;
|
||||||
@@ -24,7 +25,8 @@ export class TrackOptionsManager {
|
|||||||
|
|
||||||
/** @param {object} mysqlConfig - MySQL connection config. */
|
/** @param {object} mysqlConfig - MySQL connection config. */
|
||||||
constructor(mysqlConfig) {
|
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) => {
|
this.db.on("error", (err) => {
|
||||||
logger.error("[TrackOptions] MySQL pool error:", err.code ?? err.message);
|
logger.error("[TrackOptions] MySQL pool error:", err.code ?? err.message);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { logger } from "../../core/Logger.mjs";
|
|||||||
import { normalizeTrackText } from "./constants.mjs";
|
import { normalizeTrackText } from "./constants.mjs";
|
||||||
import { applyMixins } from "../../utils/mixins.mjs";
|
import { applyMixins } from "../../utils/mixins.mjs";
|
||||||
import { parseLastFmUrl, isLastFmUrl } from "./urlUtils.mjs";
|
import { parseLastFmUrl, isLastFmUrl } from "./urlUtils.mjs";
|
||||||
|
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "../../db/MysqlGuard.mjs";
|
||||||
import UserStoreMixin from "./UserStoreMixin.mjs";
|
import UserStoreMixin from "./UserStoreMixin.mjs";
|
||||||
import ScrobblingMixin from "./ScrobblingMixin.mjs";
|
import ScrobblingMixin from "./ScrobblingMixin.mjs";
|
||||||
import TrackQueriesMixin from "./TrackQueriesMixin.mjs";
|
import TrackQueriesMixin from "./TrackQueriesMixin.mjs";
|
||||||
@@ -140,12 +141,14 @@ export class LastFmManager {
|
|||||||
if (this._pool) return this._pool;
|
if (this._pool) return this._pool;
|
||||||
const mysql = await import("mysql2/promise");
|
const mysql = await import("mysql2/promise");
|
||||||
this._pool = mysql.createPool({
|
this._pool = mysql.createPool({
|
||||||
|
...MYSQL_POOL_DEFAULTS,
|
||||||
host: this._mysqlConfig.host,
|
host: this._mysqlConfig.host,
|
||||||
port: this._mysqlConfig.port ?? 3306,
|
port: this._mysqlConfig.port ?? 3306,
|
||||||
user: this._mysqlConfig.user,
|
user: this._mysqlConfig.user,
|
||||||
password: this._mysqlConfig.password,
|
password: this._mysqlConfig.password,
|
||||||
database: this._mysqlConfig.database,
|
database: this._mysqlConfig.database,
|
||||||
});
|
});
|
||||||
|
attachMysqlPoolGuard(this._pool, "LastFm");
|
||||||
await this._initTable();
|
await this._initTable();
|
||||||
return this._pool;
|
return this._pool;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -184,6 +184,7 @@ const UserQueriesMixin = {
|
|||||||
const profileUrl = `https://www.last.fm/user/${encodeURIComponent(user.username)}/playlists`;
|
const profileUrl = `https://www.last.fm/user/${encodeURIComponent(user.username)}/playlists`;
|
||||||
const res = await fetch(profileUrl, {
|
const res = await fetch(profileUrl, {
|
||||||
headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" },
|
headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" },
|
||||||
|
signal: AbortSignal.timeout(15_000),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -250,6 +251,7 @@ const UserQueriesMixin = {
|
|||||||
|
|
||||||
const res = await fetch(playlistUrl, {
|
const res = await fetch(playlistUrl, {
|
||||||
headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" },
|
headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" },
|
||||||
|
signal: AbortSignal.timeout(15_000),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
|
|||||||
@@ -23,6 +23,9 @@ function buildSignature(params, apiSecret) {
|
|||||||
return crypto.createHash("md5").update(str + apiSecret).digest("hex");
|
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<object>} @throws {Error} On HTTP or Last.fm API error. */
|
/** @private Make an authenticated Last.fm API call. @async @param {object} params @param {string} apiSecret @param {boolean} [post=false] @returns {Promise<object>} @throws {Error} On HTTP or Last.fm API error. */
|
||||||
async function apiCall(params, apiSecret, post = false) {
|
async function apiCall(params, apiSecret, post = false) {
|
||||||
const allParams = { ...params };
|
const allParams = { ...params };
|
||||||
@@ -36,8 +39,9 @@ async function apiCall(params, apiSecret, post = false) {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
body: new URLSearchParams(allParams).toString(),
|
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);
|
const res = await fetch(url, opts);
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
|
|||||||
Reference in new issue
Block a user