Optimize MySQL connection pools & add Docker healthcheck with graceful queue flush (#21, #12)

- Unify MySQL pools in src/db/PoolManager.mjs shared across Settings, TrackOptions, LastFm, Dashboard, and PlayerStateStore
- Support global config.mysql.connectionLimit (default 15), preventing connection starvation
- Add gracefulShutdown() in Bot.mjs to flush active player queues and playback positions to MySQL on SIGTERM/SIGINT
- Update shard.mjs to forward SIGTERM and await shard worker queue flushes before exit
- Add event-loop responsiveness healthcheck in docker-compose.yml and Dockerfile via heartbeat probe
- Document connectionLimit and queue persistence in README and config templates
This commit is contained in:
NoLogicAlan committed 2026-10-22 01:37:42 +03:00
1 parent 665be29a16
commit 90a53f047f
13 files changed
+303 -84

No files matched your search

+120 -5
View File
@@ -7,6 +7,7 @@
*/
import * as fs from "node:fs";
import os from "node:os";
import path from "node:path";
import childProcess from "node:child_process";
import { Client, Events } from "@fluxerjs/core";
@@ -20,6 +21,7 @@ import { resolveIsBotUser } from "../voice/VoiceStateResolver.mjs";
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
import { RemoteSettingsManager } from "../db/Settings.mjs";
import { PlayerStateStore } from "../db/PlayerStateStore.mjs";
import { getSharedMysqlPool, getSharedPromisePool, closeSharedMysqlPool } from "../db/PoolManager.mjs";
import { PlayerManager } from "../music/PlayerManager.mjs";
import { LavalinkManager } from "../music/LavalinkManager.mjs";
import { Dashboard } from "../dashboard/Dashboard.mjs";
@@ -134,10 +136,14 @@ class Remix {
this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
this.locale.load();
// Centralized MySQL connection pool (Issue #21)
const sharedPool = getSharedMysqlPool(config.mysql);
const sharedPromisePool = getSharedPromisePool(config.mysql);
this.dashboard = new Dashboard(this, {
enabled: config.dashboard?.enabled,
redis: config.dashboard?.redis,
mysql: config.mysql,
mysql: sharedPromisePool,
});
const presenceContents = config.presenceContents ?? [];
@@ -192,10 +198,10 @@ class Remix {
const messages = new MessageHandler(this.client);
this.messages = messages;
const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
const settings = new RemoteSettingsManager(sharedPool, "./storage/defaults.json");
this.settingsMgr = settings;
this.playerState = new PlayerStateStore(settings.db);
this.playerState = new PlayerStateStore(sharedPool);
const configPrefix = config.prefix ?? null;
if (configPrefix && settings.defaults) {
@@ -255,9 +261,28 @@ class Remix {
this.gatewayHandler = new GatewayHandler(this);
this.gatewayHandler.setupEventHandlers();
this.lastfm = new LastFmManager(config.lastfm, config.mysql);
this.lastfm = new LastFmManager(config.lastfm, sharedPromisePool);
this.fluxerlist = new FluxerListManager(config.fluxerlist);
this.trackOptions = new TrackOptionsManager(config.mysql);
this.trackOptions = new TrackOptionsManager(sharedPool);
// Event loop health heartbeat for Docker container healthcheck (Issue #12)
const healthFile = path.join(os.tmpdir(), ".remix-health");
const updateHealth = () => {
try {
fs.writeFile(healthFile, Date.now().toString(), () => {});
} catch (_) {}
};
updateHealth();
this._healthInterval = setInterval(updateHealth, 10_000);
this._healthInterval.unref?.();
// Direct process signal fallback handlers
process.once("SIGINT", () => {
this.gracefulShutdown().then(() => process.exit(0)).catch(() => process.exit(1));
});
process.once("SIGTERM", () => {
this.gracefulShutdown().then(() => process.exit(0)).catch(() => process.exit(1));
});
settings.on("ready", () => this._onSettingsReady());
@@ -619,6 +644,96 @@ class Remix {
logger.warn("[WS] Failed to attach WS error handlers:", e.message);
}
}
/**
* Graceful shutdown: flush player queue snapshots to MySQL (Issue #12),
* destroy players, close Lavalink, Redis, dashboard DB, settings, and pool.
* @async
* @returns {Promise<void>}
*/
async gracefulShutdown() {
if (this._shuttingDown) return;
this._shuttingDown = true;
logger.recovery("\n[Shutdown] Cleaning up before exit...");
// 1. Flush active player queue snapshots to MySQL (Issue #12)
try {
if (this.playerState && this.players) {
await this.playerState.saveAllFrom(this.players);
}
} catch (e) {
logger.warn("[Shutdown] Player state save failed:", e?.message);
}
// 2. Destroy live players
try {
if (this.players?.playerMap) {
for (const [channelId, player] of this.players.playerMap) {
try { player.destroy(); } catch (e) { logger.warn("[Shutdown] Player destroy error:", e?.message); }
}
this.players.playerMap.clear();
}
} catch (e) {
logger.warn("[Shutdown] Player cleanup error:", e?.message);
}
// 3. Destroy Lavalink
try {
if (this.lavalink) {
this.lavalink.destroy();
}
} catch (e) {
logger.warn("[Shutdown] Lavalink cleanup error:", e?.message);
}
// 4. Close Redis if dashboard enabled
try {
if (this.dashboard?.redis?.destroy) {
await this.dashboard.redis.destroy();
}
} catch (e) {
logger.error("[Shutdown] Failed to close Redis:", e.message);
}
// 5. Close Dashboard DB if present
try {
if (this.dashboard?.db?.close) {
await this.dashboard.db.close();
}
} catch (e) {
logger.error("[Shutdown] Failed to close Dashboard DB:", e.message);
}
// 6. Stop 24/7 watchdog
try {
this.gatewayHandler?.stop247Watchdog?.();
} catch (e) {
logger.warn("[Shutdown] Watchdog stop error:", e?.message);
}
// 7. Flush pending settings writes
try {
if (this.settingsMgr?.shutdown) {
await this.settingsMgr.shutdown();
}
} catch (e) {
logger.error("[Shutdown] Settings flush failed:", e.message);
}
// 8. Close unified shared MySQL pool (Issue #21)
try {
await closeSharedMysqlPool();
} catch (e) {
logger.warn("[Shutdown] MySQL pool close failed:", e?.message);
}
// 9. Clean up event-loop health heartbeat
try {
if (this._healthInterval) clearInterval(this._healthInterval);
const healthFile = path.join(os.tmpdir(), ".remix-health");
fs.unlink(healthFile, () => {});
} catch (_) {}
}
}
applyMixins(Remix, BotVoiceMixin);
+17 -8
View File
@@ -8,6 +8,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";
import { getSharedPromisePool } from "./PoolManager.mjs";
/**
* @class
@@ -17,14 +18,19 @@ import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
export class DatabaseManager {
/**
* Create a new DatabaseManager.
* @param {object} config - mysql2 pool configuration (host, user, password, database, etc.).
* @param {object} config - mysql2 pool configuration or shared PromisePool instance.
*/
constructor(config) {
this.db = createPool({
...MYSQL_POOL_DEFAULTS,
connectionLimit: 15,
...config,
});
if (config && typeof config.execute === "function") {
this.db = config;
this._ownsPool = false;
} else if (config && typeof config.promise === "function") {
this.db = config.promise();
this._ownsPool = false;
} else {
this.db = getSharedPromisePool(config);
this._ownsPool = false;
}
attachMysqlPoolGuard(this.db, "DashboardDB");
}
@@ -73,10 +79,13 @@ export class DatabaseManager {
}
/**
* Close the underlying MySQL connection pool.
* Close the underlying MySQL connection pool (no-op if using a shared pool).
* @returns {Promise<void>}
*/
close() {
return this.db.end();
if (this._ownsPool && this.db?.end) {
return this.db.end();
}
return Promise.resolve();
}
}
+74
View File
@@ -0,0 +1,74 @@
/**
* @module src/db/PoolManager
* @description Centralized MySQL connection pool manager for the Remix bot.
* Provides a single shared connection pool instance across all services (Settings,
* TrackOptions, Last.fm, Dashboard, PlayerStateStore), preventing connection exhaustion.
* Supports both callback-style queries and Promise-based execution via `pool.promise()`.
*/
import mysql from "mysql2";
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
import { logger } from "../core/Logger.mjs";
/** @type {import('mysql2').Pool|null} */
let _sharedPool = null;
/** @type {import('mysql2/promise').Pool|null} */
let _sharedPromisePool = null;
/**
* Get or create the shared MySQL callback-style pool.
* If config is omitted, returns the existing pool if one was already initialized.
* @param {object} [config] - MySQL configuration (host, user, password, database, connectionLimit, etc.)
* @returns {import('mysql2').Pool}
*/
export function getSharedMysqlPool(config = null) {
if (_sharedPool) return _sharedPool;
if (!config || !config.host) {
throw new Error("[PoolManager] Cannot initialize MySQL pool: missing host or config.");
}
const connectionLimit = Number(config.connectionLimit) > 0 ? Number(config.connectionLimit) : 15;
const poolConfig = {
...MYSQL_POOL_DEFAULTS,
...config,
connectionLimit,
};
_sharedPool = mysql.createPool(poolConfig);
attachMysqlPoolGuard(_sharedPool, "SharedMySQL");
_sharedPool.on("error", (err) => {
logger.error("[MySQL] Shared pool error:", err.code ?? err.message);
});
logger.db?.(`[PoolManager] Initialized shared MySQL pool (connectionLimit=${connectionLimit}).`);
return _sharedPool;
}
/**
* Get the Promise-based wrapper around the shared MySQL pool (`pool.promise()`).
* Shares the exact same underlying connections as the callback pool.
* @param {object} [config] - MySQL configuration if not yet initialized.
* @returns {import('mysql2/promise').Pool}
*/
export function getSharedPromisePool(config = null) {
if (_sharedPromisePool) return _sharedPromisePool;
const pool = getSharedMysqlPool(config);
_sharedPromisePool = pool.promise();
return _sharedPromisePool;
}
/**
* Gracefully close the shared MySQL pool on shutdown.
* @returns {Promise<void>}
*/
export async function closeSharedMysqlPool() {
if (_sharedPool) {
try {
await new Promise((resolve) => _sharedPool.end(() => resolve()));
logger.recovery?.("[PoolManager] Shared MySQL pool closed.");
} catch (e) {
logger.warn?.("[PoolManager] Error closing shared MySQL pool:", e?.message);
}
_sharedPool = null;
_sharedPromisePool = null;
}
}
+11 -4
View File
@@ -9,6 +9,7 @@ import fs from "node:fs";
import mysql from "mysql2";
import { EventEmitter } from "node:events";
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
import { getSharedMysqlPool } from "./PoolManager.mjs";
import { logger } from "../core/Logger.mjs";
/**
@@ -180,16 +181,22 @@ export class RemoteSettingsManager extends SettingsManager {
/**
* Create a new RemoteSettingsManager backed by a MySQL pool.
* @param {object} config - mysql2 pool configuration (host, user, password, database).
* @param {object} config - mysql2 pool or configuration (host, user, password, database).
* @param {string} defaultsPath - Path to a JSON file with default values and descriptions.
* @param {string|null} [botId=null] - The bot user ID for multi-bot support.
*/
constructor(config, defaultsPath, botId = null) {
super();
this.botId = botId;
this.db = mysql.createPool({ ...MYSQL_POOL_DEFAULTS, connectionLimit: 15, ...config });
if (config && typeof config.query === "function") {
this.db = config;
this._ownsPool = false;
} else {
this.db = getSharedMysqlPool(config);
this._ownsPool = false;
}
attachMysqlPoolGuard(this.db, "DB");
this.db.on('error', (err) => {
this.db.on?.('error', (err) => {
logger.error('[DB] MySQL pool error:', err.code ?? err.message);
});
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
@@ -219,7 +226,7 @@ export class RemoteSettingsManager extends SettingsManager {
}
await Promise.allSettled(pendingServers.map(server => this._doSave(server)));
try {
if (this.db?.end) {
if (this._ownsPool && this.db?.end) {
await new Promise(r => this.db.end(() => r()));
}
} catch (_) {}
+8 -3
View File
@@ -2,6 +2,7 @@
import mysql from "mysql2";
import { logger } from "../core/Logger.mjs";
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "../db/MysqlGuard.mjs";
import { getSharedMysqlPool } from "../db/PoolManager.mjs";
const DEFAULT_ALIAS = "default";
const MAX_ALIAS_LEN = 32;
@@ -23,11 +24,15 @@ export class TrackOptionsManager {
/** @private @type {number} */
_cacheMaxSize = 2000;
/** @param {object} mysqlConfig - MySQL connection config. */
/** @param {object} mysqlConfig - MySQL connection config or shared Pool instance. */
constructor(mysqlConfig) {
this.db = mysql.createPool({ ...MYSQL_POOL_DEFAULTS, connectionLimit: 10, ...mysqlConfig });
if (mysqlConfig && typeof mysqlConfig.query === "function") {
this.db = mysqlConfig;
} else {
this.db = getSharedMysqlPool(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);
});
this._readyPromise = this._ensureTable();
+8 -9
View File
@@ -15,6 +15,7 @@ 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 { getSharedPromisePool } from "../../db/PoolManager.mjs";
import UserStoreMixin from "./UserStoreMixin.mjs";
import ScrobblingMixin from "./ScrobblingMixin.mjs";
import TrackQueriesMixin from "./TrackQueriesMixin.mjs";
@@ -139,15 +140,13 @@ export class LastFmManager {
/** @private @async Get or create the MySQL connection pool. @returns {Promise<object>} */
async _getPool() {
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,
});
if (this._mysqlConfig && typeof this._mysqlConfig.execute === "function") {
this._pool = this._mysqlConfig;
} else if (this._mysqlConfig && typeof this._mysqlConfig.promise === "function") {
this._pool = this._mysqlConfig.promise();
} else {
this._pool = getSharedPromisePool(this._mysqlConfig);
}
attachMysqlPoolGuard(this._pool, "LastFm");
await this._initTable();
return this._pool;