mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
- 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:
1 parent
665be29a16
commit
90a53f047f
13 files changed
+303
-84
No files matched your search
@@ -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
|
||||
- **Multi-language support** — English, Arabic, German, Kurdish (Sorani), Brazilian Portuguese, and Turkish
|
||||
- **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`)
|
||||
|
||||
---
|
||||
@@ -413,7 +413,7 @@ Key configuration options in `config.json`:
|
||||
| `customStatsFooter` | string | — | Custom text shown in the `%stats` embed footer |
|
||||
| `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`) |
|
||||
| `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`) |
|
||||
| `audio` | object | — | Audio streaming options (`allowLoadstream: false` for zero-re-encode `/v4/trackstream`) |
|
||||
| `bilibili` | object | — | Anonymous Bilibili proxy (`enabled`, `bind`, `port`, `advertiseHost`, `remoteProxy`, `remoteSecret`) |
|
||||
@@ -518,6 +518,7 @@ fluxer/
|
||||
│ ├── constants.mjs # Signed API-call plumbing
|
||||
│ └── urlUtils.mjs # lastfm:// URL parsing
|
||||
├── db/ # Persistence
|
||||
│ ├── PoolManager.mjs # Unified MySQL pool manager (callback & promise APIs)
|
||||
│ ├── Settings.mjs # SettingsManager / ServerSettings / RemoteSettingsManager
|
||||
│ │ # (MySQL-backed, debounced JSON_SET writes)
|
||||
│ └── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers
|
||||
|
||||
+3
-1
@@ -97,7 +97,9 @@
|
||||
"port": 3306,
|
||||
"user": "youruser",
|
||||
"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": {
|
||||
"enabled": false,
|
||||
|
||||
+2
-2
@@ -36,8 +36,8 @@ USER 10001:10001
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||
CMD pgrep -f "node .*index.mjs" >/dev/null 2>&1 || pgrep -f "node .*shard.mjs" >/dev/null 2>&1 || exit 1
|
||||
HEALTHCHECK --interval=15s --timeout=5s --start-period=45s --retries=3 \
|
||||
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"]
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
"port": 3306,
|
||||
"user": "remix",
|
||||
"password": "remix_pw",
|
||||
"database": "remix"
|
||||
"database": "remix",
|
||||
"connectionLimit": 15
|
||||
},
|
||||
"nodelink": {
|
||||
"host": "nodelink",
|
||||
|
||||
@@ -20,6 +20,12 @@ services:
|
||||
- TZ=${TZ:-UTC}
|
||||
ports:
|
||||
- "${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:
|
||||
- remix-net
|
||||
|
||||
|
||||
@@ -140,60 +140,18 @@ process.on("uncaughtExceptionMonitor", (err, origin) => {
|
||||
});
|
||||
|
||||
/**
|
||||
* Graceful shutdown handler: destroys all active players, closes Lavalink,
|
||||
* Redis, and Dashboard DB connections, then exits.
|
||||
* Graceful shutdown handler: flushes player queue snapshots to MySQL,
|
||||
* cleans up active players, services, and connections, then exits.
|
||||
* @async
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const saveAndExit = async () => {
|
||||
logger.recovery("\n[Shutdown] Cleaning up before exit...");
|
||||
try {
|
||||
await remix.playerState?.saveAllFrom?.(remix.players);
|
||||
} catch (e) {
|
||||
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();
|
||||
if (remix?.gracefulShutdown) {
|
||||
await remix.gracefulShutdown();
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[Shutdown] Player cleanup error:", e?.message);
|
||||
}
|
||||
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);
|
||||
logger.error("[Shutdown] Error during graceful shutdown:", e?.message ?? e);
|
||||
}
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
@@ -38,6 +38,8 @@
|
||||
*/
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ShardingManager } from "@fluxerjs/sharding";
|
||||
import { logger } from "./src/core/Logger.mjs";
|
||||
@@ -126,18 +128,58 @@ manager.on("error", (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. */
|
||||
let shuttingDown = false;
|
||||
const shutdown = async (sig) => {
|
||||
if (shuttingDown) return;
|
||||
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 {
|
||||
await manager.destroy();
|
||||
} catch (e) {
|
||||
logger.warn("[Sharding] destroy error:", e?.message);
|
||||
}
|
||||
|
||||
try {
|
||||
clearInterval(healthInterval);
|
||||
fs.unlink(healthFile, () => {});
|
||||
} catch (_) {}
|
||||
|
||||
process.exit(0);
|
||||
};
|
||||
process.once("SIGINT", () => shutdown("SIGINT"));
|
||||
|
||||
+120
-5
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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 (_) {}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user