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
+302 -83

No files matched your search

+3 -2
View File
@@ -134,7 +134,7 @@ A few things worth knowing:
- **Dashboard backend** — optional Redis-RPC backend that an external web frontend uses to monitor players and control playback remotely - **Dashboard backend** — optional Redis-RPC backend that an external web frontend uses to monitor players and control playback remotely
- **Multi-language support** — English, Arabic, German, Kurdish (Sorani), Brazilian Portuguese, and Turkish - **Multi-language support** — English, Arabic, German, Kurdish (Sorani), Brazilian Portuguese, and Turkish
- **Configurable logging** — granular control over which log categories appear in the console - **Configurable logging** — granular control over which log categories appear in the console
- **Graceful shutdown** — destroys players and closes MySQL/Redis/NodeLink sessions cleanly on SIGINT/SIGTERM/SIGUSR2 - **Graceful shutdown & Queue Persistence** — flushes active player queues and playback positions into MySQL (`player_state`) before cleanly destroying players and closing MySQL/Redis/NodeLink sessions on SIGINT/SIGTERM/SIGUSR2
- **Module system** — pluggable module architecture for extending bot functionality (`storage/modules.json`) - **Module system** — pluggable module architecture for extending bot functionality (`storage/modules.json`)
--- ---
@@ -413,7 +413,7 @@ Key configuration options in `config.json`:
| `customStatsFooter` | string | — | Custom text shown in the `%stats` embed footer | | `customStatsFooter` | string | — | Custom text shown in the `%stats` embed footer |
| `presenceInterval` | number | `30000` | Interval in ms for rotating bot presence status | | `presenceInterval` | number | `30000` | Interval in ms for rotating bot presence status |
| `presenceContents` | array | `[]` | Presence status messages to cycle through (strings or objects with `text`/`emoji_name`/`emoji_id`/`activity`) | | `presenceContents` | array | `[]` | Presence status messages to cycle through (strings or objects with `text`/`emoji_name`/`emoji_id`/`activity`) |
| `mysql` | object | — | **Required.** MySQL connection settings | | `mysql` | object | — | **Required.** MySQL connection settings (`host`, `port`, `user`, `password`, `database`, `connectionLimit`) |
| `nodelink` | object | — | NodeLink connection (`host`, `port`, `password`, `requestTimeout`) | | `nodelink` | object | — | NodeLink connection (`host`, `port`, `password`, `requestTimeout`) |
| `audio` | object | — | Audio streaming options (`allowLoadstream: false` for zero-re-encode `/v4/trackstream`) | | `audio` | object | — | Audio streaming options (`allowLoadstream: false` for zero-re-encode `/v4/trackstream`) |
| `bilibili` | object | — | Anonymous Bilibili proxy (`enabled`, `bind`, `port`, `advertiseHost`, `remoteProxy`, `remoteSecret`) | | `bilibili` | object | — | Anonymous Bilibili proxy (`enabled`, `bind`, `port`, `advertiseHost`, `remoteProxy`, `remoteSecret`) |
@@ -518,6 +518,7 @@ fluxer/
│ ├── constants.mjs # Signed API-call plumbing │ ├── constants.mjs # Signed API-call plumbing
│ └── urlUtils.mjs # lastfm:// URL parsing │ └── urlUtils.mjs # lastfm:// URL parsing
├── db/ # Persistence ├── db/ # Persistence
│ ├── PoolManager.mjs # Unified MySQL pool manager (callback & promise APIs)
│ ├── Settings.mjs # SettingsManager / ServerSettings / RemoteSettingsManager │ ├── Settings.mjs # SettingsManager / ServerSettings / RemoteSettingsManager
│ │ # (MySQL-backed, debounced JSON_SET writes) │ │ # (MySQL-backed, debounced JSON_SET writes)
│ └── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers │ └── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers
+3 -1
View File
@@ -97,7 +97,9 @@
"port": 3306, "port": 3306,
"user": "youruser", "user": "youruser",
"password": "password of your user", "password": "password of your user",
"database": "name of the target database" "database": "name of the target database",
"connectionLimit": 15,
"connectionLimit-Comment": "Maximum simultaneous MySQL connections shared across all bot services (default: 15). Prevents connection pool exhaustion in multi-shard deployments."
}, },
"dashboard": { "dashboard": {
"enabled": false, "enabled": false,
+2 -2
View File
@@ -36,8 +36,8 @@ USER 10001:10001
EXPOSE 80 EXPOSE 80
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ HEALTHCHECK --interval=15s --timeout=5s --start-period=45s --retries=3 \
CMD pgrep -f "node .*index.mjs" >/dev/null 2>&1 || pgrep -f "node .*shard.mjs" >/dev/null 2>&1 || exit 1 CMD node -e "const fs = require('fs'); try { const diff = Date.now() - fs.statSync('/tmp/.remix-health').mtimeMs; process.exit(diff < 30000 ? 0 : 1); } catch { process.exit(1); }"
ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"] ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"]
+2 -1
View File
@@ -8,7 +8,8 @@
"port": 3306, "port": 3306,
"user": "remix", "user": "remix",
"password": "remix_pw", "password": "remix_pw",
"database": "remix" "database": "remix",
"connectionLimit": 15
}, },
"nodelink": { "nodelink": {
"host": "nodelink", "host": "nodelink",
+6
View File
@@ -20,6 +20,12 @@ services:
- TZ=${TZ:-UTC} - TZ=${TZ:-UTC}
ports: ports:
- "${WEB_PORT:-8080}:80" - "${WEB_PORT:-8080}:80"
healthcheck:
test: ["CMD", "node", "-e", "const fs = require('fs'); try { const diff = Date.now() - fs.statSync('/tmp/.remix-health').mtimeMs; process.exit(diff < 30000 ? 0 : 1); } catch { process.exit(1); }"]
interval: 15s
timeout: 5s
retries: 3
start_period: 45s
networks: networks:
- remix-net - remix-net
+5 -47
View File
@@ -140,60 +140,18 @@ process.on("uncaughtExceptionMonitor", (err, origin) => {
}); });
/** /**
* Graceful shutdown handler: destroys all active players, closes Lavalink, * Graceful shutdown handler: flushes player queue snapshots to MySQL,
* Redis, and Dashboard DB connections, then exits. * cleans up active players, services, and connections, then exits.
* @async * @async
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
const saveAndExit = async () => { const saveAndExit = async () => {
logger.recovery("\n[Shutdown] Cleaning up before exit...");
try { try {
await remix.playerState?.saveAllFrom?.(remix.players); if (remix?.gracefulShutdown) {
} catch (e) { await remix.gracefulShutdown();
logger.warn("[Shutdown] Player state save failed:", e?.message);
}
try {
if (remix.players?.playerMap) {
for (const [channelId, player] of remix.players.playerMap) {
try { player.destroy(); } catch (e) { logger.warn("[Shutdown] Player destroy error:", e?.message); }
}
remix.players.playerMap.clear();
} }
} catch (e) { } catch (e) {
logger.warn("[Shutdown] Player cleanup error:", e?.message); logger.error("[Shutdown] Error during graceful shutdown:", e?.message ?? e);
}
try {
if (remix.lavalink) {
remix.lavalink.destroy();
}
} catch (e) {
logger.warn("[Shutdown] Lavalink cleanup error:", e?.message);
}
try {
if (remix.dashboard?.redis?.destroy) {
await remix.dashboard.redis.destroy();
}
} catch (e) {
logger.error("[Shutdown] Failed to close Redis:", e.message);
}
try {
if (remix.dashboard?.db?.close) {
await remix.dashboard.db.close();
}
} catch (e) {
logger.error("[Shutdown] Failed to close Dashboard DB:", e.message);
}
try {
remix.gatewayHandler?.stop247Watchdog?.();
} catch (e) {
logger.warn("[Shutdown] Watchdog stop error:", e?.message);
}
try {
if (remix.settingsMgr?.shutdown) {
await remix.settingsMgr.shutdown();
}
} catch (e) {
logger.error("[Shutdown] Settings flush failed:", e.message);
} }
process.exit(0); process.exit(0);
}; };
+44 -2
View File
@@ -38,6 +38,8 @@
*/ */
import * as fs from "node:fs"; import * as fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { ShardingManager } from "@fluxerjs/sharding"; import { ShardingManager } from "@fluxerjs/sharding";
import { logger } from "./src/core/Logger.mjs"; import { logger } from "./src/core/Logger.mjs";
@@ -126,18 +128,58 @@ manager.on("error", (err) => {
logger.error("[Sharding] Manager error:", err?.message ?? err); logger.error("[Sharding] Manager error:", err?.message ?? err);
}); });
/** Graceful shutdown: destroy all children, then exit. // 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();
const healthInterval = setInterval(updateHealth, 10_000);
healthInterval.unref?.();
/** Graceful shutdown: signal shard children to flush queue snapshots, await exit, then destroy.
* @param {string} sig - The received signal name. */ * @param {string} sig - The received signal name. */
let shuttingDown = false; let shuttingDown = false;
const shutdown = async (sig) => { const shutdown = async (sig) => {
if (shuttingDown) return; if (shuttingDown) return;
shuttingDown = true; shuttingDown = true;
logger.recovery(`\n[Sharding] ${sig} received — destroying shard processes...`); manager.respawn = false;
logger.recovery(`\n[Sharding] ${sig} received — waiting for shard processes to flush queue snapshots and exit...`);
// Send SIGTERM to all child processes so their saveAndExit / Bot.gracefulShutdown runs
const exitPromises = [];
if (manager.shards) {
for (const shard of manager.shards.values()) {
const cp = shard.process;
if (cp && !cp.killed) {
exitPromises.push(new Promise((resolve) => {
cp.once("exit", resolve);
setTimeout(resolve, 8000);
}));
try {
cp.kill("SIGTERM");
} catch (_) {}
}
}
}
if (exitPromises.length > 0) {
await Promise.all(exitPromises);
}
try { try {
await manager.destroy(); await manager.destroy();
} catch (e) { } catch (e) {
logger.warn("[Sharding] destroy error:", e?.message); logger.warn("[Sharding] destroy error:", e?.message);
} }
try {
clearInterval(healthInterval);
fs.unlink(healthFile, () => {});
} catch (_) {}
process.exit(0); process.exit(0);
}; };
process.once("SIGINT", () => shutdown("SIGINT")); process.once("SIGINT", () => shutdown("SIGINT"));
+120 -5
View File
@@ -7,6 +7,7 @@
*/ */
import * as fs from "node:fs"; import * as fs from "node:fs";
import os from "node:os";
import path from "node:path"; import path from "node:path";
import childProcess from "node:child_process"; import childProcess from "node:child_process";
import { Client, Events } from "@fluxerjs/core"; import { Client, Events } from "@fluxerjs/core";
@@ -20,6 +21,7 @@ import { resolveIsBotUser } from "../voice/VoiceStateResolver.mjs";
import * as ShardingUtils from "../utils/ShardingUtils.mjs"; import * as ShardingUtils from "../utils/ShardingUtils.mjs";
import { RemoteSettingsManager } from "../db/Settings.mjs"; import { RemoteSettingsManager } from "../db/Settings.mjs";
import { PlayerStateStore } from "../db/PlayerStateStore.mjs"; import { PlayerStateStore } from "../db/PlayerStateStore.mjs";
import { getSharedMysqlPool, getSharedPromisePool, closeSharedMysqlPool } from "../db/PoolManager.mjs";
import { PlayerManager } from "../music/PlayerManager.mjs"; import { PlayerManager } from "../music/PlayerManager.mjs";
import { LavalinkManager } from "../music/LavalinkManager.mjs"; import { LavalinkManager } from "../music/LavalinkManager.mjs";
import { Dashboard } from "../dashboard/Dashboard.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 = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
this.locale.load(); this.locale.load();
// Centralized MySQL connection pool (Issue #21)
const sharedPool = getSharedMysqlPool(config.mysql);
const sharedPromisePool = getSharedPromisePool(config.mysql);
this.dashboard = new Dashboard(this, { this.dashboard = new Dashboard(this, {
enabled: config.dashboard?.enabled, enabled: config.dashboard?.enabled,
redis: config.dashboard?.redis, redis: config.dashboard?.redis,
mysql: config.mysql, mysql: sharedPromisePool,
}); });
const presenceContents = config.presenceContents ?? []; const presenceContents = config.presenceContents ?? [];
@@ -192,10 +198,10 @@ class Remix {
const messages = new MessageHandler(this.client); const messages = new MessageHandler(this.client);
this.messages = messages; this.messages = messages;
const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); const settings = new RemoteSettingsManager(sharedPool, "./storage/defaults.json");
this.settingsMgr = settings; this.settingsMgr = settings;
this.playerState = new PlayerStateStore(settings.db); this.playerState = new PlayerStateStore(sharedPool);
const configPrefix = config.prefix ?? null; const configPrefix = config.prefix ?? null;
if (configPrefix && settings.defaults) { if (configPrefix && settings.defaults) {
@@ -255,9 +261,28 @@ class Remix {
this.gatewayHandler = new GatewayHandler(this); this.gatewayHandler = new GatewayHandler(this);
this.gatewayHandler.setupEventHandlers(); 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.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()); settings.on("ready", () => this._onSettingsReady());
@@ -619,6 +644,96 @@ class Remix {
logger.warn("[WS] Failed to attach WS error handlers:", e.message); 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); applyMixins(Remix, BotVoiceMixin);
+16 -7
View File
@@ -8,6 +8,7 @@ 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"; import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
import { getSharedPromisePool } from "./PoolManager.mjs";
/** /**
* @class * @class
@@ -17,14 +18,19 @@ import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
export class DatabaseManager { export class DatabaseManager {
/** /**
* Create a new 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) { constructor(config) {
this.db = createPool({ if (config && typeof config.execute === "function") {
...MYSQL_POOL_DEFAULTS, this.db = config;
connectionLimit: 15, this._ownsPool = false;
...config, } 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"); 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>} * @returns {Promise<void>}
*/ */
close() { close() {
if (this._ownsPool && this.db?.end) {
return 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 mysql from "mysql2";
import { EventEmitter } from "node:events"; import { EventEmitter } from "node:events";
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs"; import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
import { getSharedMysqlPool } from "./PoolManager.mjs";
import { logger } from "../core/Logger.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. * 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} defaultsPath - Path to a JSON file with default values and descriptions.
* @param {string|null} [botId=null] - The bot user ID for multi-bot support. * @param {string|null} [botId=null] - The bot user ID for multi-bot support.
*/ */
constructor(config, defaultsPath, botId = null) { constructor(config, defaultsPath, botId = null) {
super(); super();
this.botId = botId; 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"); 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);
}); });
if (defaultsPath) this.loadDefaultsSync(defaultsPath); if (defaultsPath) this.loadDefaultsSync(defaultsPath);
@@ -219,7 +226,7 @@ export class RemoteSettingsManager extends SettingsManager {
} }
await Promise.allSettled(pendingServers.map(server => this._doSave(server))); await Promise.allSettled(pendingServers.map(server => this._doSave(server)));
try { try {
if (this.db?.end) { if (this._ownsPool && this.db?.end) {
await new Promise(r => this.db.end(() => r())); await new Promise(r => this.db.end(() => r()));
} }
} catch (_) {} } catch (_) {}
+8 -3
View File
@@ -2,6 +2,7 @@
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"; import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "../db/MysqlGuard.mjs";
import { getSharedMysqlPool } from "../db/PoolManager.mjs";
const DEFAULT_ALIAS = "default"; const DEFAULT_ALIAS = "default";
const MAX_ALIAS_LEN = 32; const MAX_ALIAS_LEN = 32;
@@ -23,11 +24,15 @@ export class TrackOptionsManager {
/** @private @type {number} */ /** @private @type {number} */
_cacheMaxSize = 2000; _cacheMaxSize = 2000;
/** @param {object} mysqlConfig - MySQL connection config. */ /** @param {object} mysqlConfig - MySQL connection config or shared Pool instance. */
constructor(mysqlConfig) { 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"); 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);
}); });
this._readyPromise = this._ensureTable(); this._readyPromise = this._ensureTable();
+8 -9
View File
@@ -15,6 +15,7 @@ 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 { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "../../db/MysqlGuard.mjs";
import { getSharedPromisePool } from "../../db/PoolManager.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";
@@ -139,15 +140,13 @@ export class LastFmManager {
/** @private @async Get or create the MySQL connection pool. @returns {Promise<object>} */ /** @private @async Get or create the MySQL connection pool. @returns {Promise<object>} */
async _getPool() { async _getPool() {
if (this._pool) return this._pool; if (this._pool) return this._pool;
const mysql = await import("mysql2/promise"); if (this._mysqlConfig && typeof this._mysqlConfig.execute === "function") {
this._pool = mysql.createPool({ this._pool = this._mysqlConfig;
...MYSQL_POOL_DEFAULTS, } else if (this._mysqlConfig && typeof this._mysqlConfig.promise === "function") {
host: this._mysqlConfig.host, this._pool = this._mysqlConfig.promise();
port: this._mysqlConfig.port ?? 3306, } else {
user: this._mysqlConfig.user, this._pool = getSharedPromisePool(this._mysqlConfig);
password: this._mysqlConfig.password, }
database: this._mysqlConfig.database,
});
attachMysqlPoolGuard(this._pool, "LastFm"); attachMysqlPoolGuard(this._pool, "LastFm");
await this._initTable(); await this._initTable();
return this._pool; return this._pool;