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
@@ -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");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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 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);
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<object>} @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) {
|
||||
|
||||
Reference in new issue
Block a user