From db0ca569eeca121b6f1fce23ae075581ce7a9669 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Sat, 16 May 2026 23:20:05 +0300 Subject: [PATCH] hotfix --- index.mjs | 25 ++++++- settings/Settings.mjs | 101 ++++++++++++++++++++++++-- settings/migrate-add-bot-id.sql | 65 +++++++++++++++++ settings/migrate.mjs | 8 ++- src/CommandHandler.mjs | 9 ++- src/GatewayHandler.mjs | 6 +- src/LastFmManager.mjs | 116 ++++++++++++++++++++++++------ src/Settings.mjs | 124 ++++++++++++++++++++++++++++++-- src/dashboard/Dashboard.mjs | 14 ++++ 9 files changed, 426 insertions(+), 42 deletions(-) create mode 100644 settings/migrate-add-bot-id.sql diff --git a/index.mjs b/index.mjs index a844c49..46a8b5d 100644 --- a/index.mjs +++ b/index.mjs @@ -151,13 +151,27 @@ export class Remix { const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); this.settingsMgr = settings; + // Override the default prefix with config.json value if set. + // This ensures that when the bot joins a NEW server (no DB row yet), it uses + // the config prefix instead of the hardcoded "%" from defaults.json. + // Existing servers keep whatever prefix they already have in the DB. + const configPrefix = config.prefix ?? null; + if (configPrefix && settings.defaults) { + settings.defaults.prefix = configPrefix; + } + this.locale.bind(this.settingsMgr); // ── Command handler ────────────────────────────────────────────────────── - const commands = new CommandHandler(messages); + // config.prefix from config.json overrides the defaults.json prefix. + // This way, if you run multiple bots in the same server (e.g. Remix + test bot), + // each can have its own default prefix (Remix=%, test bot=!) without needing + // a separate database or manual %prefix per server. + const commands = new CommandHandler(messages, configPrefix); this.handler = commands; - commands.setPrefixManager(new PrefixManager(settings)); + const prefixMgr = new PrefixManager(settings, configPrefix); + commands.setPrefixManager(prefixMgr); commands.setLocale(this.locale); messages.setLocale(this.locale); @@ -285,6 +299,13 @@ export class Remix { const botId = client.user?.id ?? "0"; + // Set the bot ID on all managers that use the shared MySQL database. + // This isolates each bot's data (settings, Last.fm users, Redis channels) + // so multiple bots can share the same database without conflicts. + await this.settingsMgr.setBotId(botId); + await this.lastfm.setBotId(botId); + this.dashboard.setBotId(botId); + // MoonlinkManager initialisation — stays here because it's audio // infrastructure, not gateway handling. The guard prevents stacking // listeners on reconnect. diff --git a/settings/Settings.mjs b/settings/Settings.mjs index 37ee8b6..ee351ec 100644 --- a/settings/Settings.mjs +++ b/settings/Settings.mjs @@ -44,11 +44,18 @@ export class MySqlSettingsManager extends SettingsManager { descriptions = {}; defaults = {}; db = null; + /** @type {string|null} Bot user ID — used to isolate rows per-bot in shared databases */ + botId = null; + /** @type {boolean} Whether the bot_id column exists in the settings table */ + _hasBotIdColumn = false; + /** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */ + _loadPromise = null; // Per-server debounce timers — collapses rapid set() calls into one remoteSave() _debounceTimers = new Map(); - constructor(config, defaultsPath) { + constructor(config, defaultsPath, botId = null) { super(); + this.botId = botId; this.db = mysql.createPool({ connectionLimit: 15, ...config }); // Without this listener, any pool-level error (connection drop, timeout, protocol error) // fires an unhandled 'error' event which crashes the entire process with no log output. @@ -56,7 +63,88 @@ export class MySqlSettingsManager extends SettingsManager { logger.error("[DB] MySQL pool error:", err.code ?? err.message); }); if (defaultsPath) this.loadDefaultsSync(defaultsPath); - this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err)); + this._loadPromise = this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err)); + } + + /** + * Check whether the `bot_id` column exists in the settings table. + * If it doesn't, auto-migrate by adding the column and updating the primary key. + */ + async _ensureBotIdColumn() { + if (this._hasBotIdColumn) return; + + const res = await this.query( + `SELECT COLUMN_NAME FROM information_schema.COLUMNS ` + + `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'` + ); + + if (res.error) { + logger.error("[Settings] Failed to check bot_id column:", res.error); + return; + } + + if (res.results.length > 0) { + this._hasBotIdColumn = true; + return; + } + + // Auto-migrate + logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); + + const alterRes = await this.query( + `ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) DEFAULT NULL` + ); + if (alterRes.error) { + logger.error("[Settings] Failed to add bot_id column:", alterRes.error); + return; + } + + const pkRes = await this.query( + `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` + ); + if (pkRes.error) { + logger.error("[Settings] Failed to update primary key:", pkRes.error); + } + + this._hasBotIdColumn = true; + logger.settings("[Settings] Auto-migration complete: bot_id column added."); + } + + /** + * Set or update the bot ID used for database row isolation. + * Ensures the bot_id column exists (auto-migrates if needed), then reloads. + * @param {string} id + */ + async setBotId(id) { + const changed = this.botId !== id; + this.botId = id; + if (changed) { + if (this._loadPromise) await this._loadPromise; + await this._ensureBotIdColumn(); + this.guilds.clear(); + this._loadPromise = this.load(); + await this._loadPromise; + } + } + + _botIdWhere() { + if (!this.botId || !this._hasBotIdColumn) return ""; + return ` AND bot_id = ${mysql.escape(String(this.botId))}`; + } + + _botIdInsert() { + if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" }; + return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` }; + } + + /** + * Fetch a single guild's settings row from the database, filtered by bot_id. + * @param {string} guildId + * @returns {Promise<{error: object|null, results: Array, fields: Array}>} + */ + selectGuild(guildId) { + const escapedId = mysql.escape(String(guildId)); + return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`); } query(query) { return new Promise(res => { @@ -64,7 +152,7 @@ export class MySqlSettingsManager extends SettingsManager { }); } async load() { - const res = await this.query("SELECT * FROM settings"); + const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`); if (res.error) { this._loadAttempts = (this._loadAttempts || 0) + 1; const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000); @@ -103,7 +191,7 @@ export class MySqlSettingsManager extends SettingsManager { : mysql.escape(String(val)); const escapedId = mysql.escape(server.id); const r = await this.query( - `UPDATE settings SET data = JSON_SET(data, ${escapedKey}, ${escapedVal}) WHERE id=${escapedId}` + `UPDATE settings SET data = JSON_SET(data, ${escapedKey}, ${escapedVal}) WHERE id=${escapedId}${this._botIdWhere()}` ); if (r.error) logger.error("[Settings] remoteUpdate error:", r.error); } @@ -111,7 +199,7 @@ export class MySqlSettingsManager extends SettingsManager { const escapedData = mysql.escape(JSON.stringify(server.data)); const escapedId = mysql.escape(server.id); const r = await this.query( - `UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}` + `UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}` ); if (r.error) logger.error("[Settings] remoteSave error:", r.error); } @@ -133,8 +221,9 @@ export class MySqlSettingsManager extends SettingsManager { async create(id, server) { const escapedId = mysql.escape(id); const escapedData = mysql.escape(JSON.stringify(server.data)); + const bi = this._botIdInsert(); const r = await this.query( - `INSERT INTO settings (id, data) VALUES (${escapedId}, ${escapedData})` + `INSERT INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})` ); if (r.error) logger.error("[Settings] create error:", r.error); } diff --git a/settings/migrate-add-bot-id.sql b/settings/migrate-add-bot-id.sql new file mode 100644 index 0000000..a28b306 --- /dev/null +++ b/settings/migrate-add-bot-id.sql @@ -0,0 +1,65 @@ +-- Migration: Add bot_id column to the settings table +-- This allows multiple bots to share the same MySQL database while keeping +-- their settings (prefix, volume, etc.) completely separate. +-- +-- NOTE: The bot now auto-migrates on startup! You do NOT need to run this +-- file manually. It is kept here as a reference / manual fallback. +-- +-- The auto-migration happens when setBotId() is called after Discord login: +-- 1. Checks if bot_id column exists (via information_schema) +-- 2. If not, adds the column and updates the primary key automatically +-- +-- If you prefer to run it manually instead: +-- mysql -u -p < settings/migrate-add-bot-id.sql +-- +-- After migration: +-- - Existing rows have bot_id = NULL (legacy, works with both old and new code) +-- - New rows created by bots will have bot_id set to the bot's user ID +-- - The composite primary key (id, bot_id) allows the same guild to have +-- separate settings per bot + +-- Step 1: Add bot_id column if it doesn't exist +ALTER TABLE settings + ADD COLUMN IF NOT EXISTS bot_id VARCHAR(32) DEFAULT NULL; + +-- Step 2: Drop the old primary key (id) and create a composite one (id, bot_id) +-- This allows the same guild ID to exist with different bot_id values. +-- We use a procedure because MySQL doesn't support IF EXISTS on ALTER TABLE ... DROP PRIMARY KEY +-- and we want this migration to be idempotent (safe to run multiple times). + +DELIMITER // + +DROP PROCEDURE IF EXISTS migrate_add_bot_id_pk // + +CREATE PROCEDURE migrate_add_bot_id_pk() +BEGIN + DECLARE pk_has_bot_id INT DEFAULT 0; + + -- Check if the current primary key already includes bot_id + SELECT COUNT(*) INTO pk_has_bot_id + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'settings' + AND COLUMN_KEY = 'PRI' + AND COLUMN_NAME = 'bot_id'; + + IF pk_has_bot_id = 0 THEN + -- bot_id is not part of the primary key yet; safe to alter + ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id); + END IF; +END // + +CALL migrate_add_bot_id_pk() // + +DROP PROCEDURE IF EXISTS migrate_add_bot_id_pk // + +DELIMITER ; + +-- Step 3 (Optional): If you already know which bot owns which rows, +-- you can set bot_id manually. For example, if the existing rows belong +-- to a bot with ID "123456789012345678": +-- UPDATE settings SET bot_id = '123456789012345678' WHERE bot_id IS NULL; +-- +-- If you leave bot_id as NULL, those rows are treated as "shared" by the +-- legacy code path (no bot_id filter applied). Once each bot starts up +-- with the new code, it will create its own rows with bot_id set. diff --git a/settings/migrate.mjs b/settings/migrate.mjs index fd0ae6f..241bae3 100644 --- a/settings/migrate.mjs +++ b/settings/migrate.mjs @@ -4,11 +4,15 @@ import { logger } from "../src/constants/Logger.mjs"; const config = JSON.parse(fs.readFileSync(new URL("../config.json", import.meta.url))); +// Pass bot ID from config if available, so migrations are bot-isolated. +// If no botId in config, all rows are migrated (legacy behavior). +const botId = config.botId ?? null; + // Both source and destination use RemoteSettingsManager to ensure the // `guilds` Map is populated from MySQL. The abstract SettingsManager base // class has no implementation (no guilds, no load, no defaults). -const sm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); -const rsm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); +const sm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json", botId); +const rsm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json", botId); // Ensure source manager is fully loaded BEFORE starting migration. // Previously, rsm's "ready" could fire before sm finished loading, diff --git a/src/CommandHandler.mjs b/src/CommandHandler.mjs index c480811..7058e93 100644 --- a/src/CommandHandler.mjs +++ b/src/CommandHandler.mjs @@ -217,8 +217,13 @@ export class Flag extends Option { export class PrefixManager { /** @type {SettingsManager} */ settings; - constructor(settings) { this.settings = settings; } - getPrefix(guildId) { return this.settings.getServer(guildId).get("prefix"); } + /** @type {string|null} Prefix from config.json — used as fallback when DB has no value */ + configPrefix; + constructor(settings, configPrefix = null) { this.settings = settings; this.configPrefix = configPrefix; } + getPrefix(guildId) { + const serverPrefix = this.settings.getServer(guildId).get("prefix"); + return serverPrefix ?? this.configPrefix ?? "%"; + } } export class HelpHandler { diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index d407ada..ec9d9dc 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -5,7 +5,7 @@ import { ServerSettings } from "./Settings.mjs"; import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs"; import { VoiceStateCache } from "./constants/VoiceStateCache.mjs"; import { REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs"; -import mysql from "mysql2"; + /** * GatewayHandler — manages raw WebSocket gateway events, voice-state tracking, @@ -732,9 +732,7 @@ export class GatewayHandler { try { const cleanGuildId = String(guildId).replace(/\D/g, ""); if (!cleanGuildId) throw new Error("Invalid guildId: " + guildId); - const res = await remix.settingsMgr.query( - `SELECT * FROM settings WHERE id=${mysql.escape(cleanGuildId)}` - ); + const res = await remix.settingsMgr.selectGuild(cleanGuildId); if (res?.results?.length) { const row = res.results[0]; const server = new ServerSettings(guildId, remix.settingsMgr); diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index e877dec..2a84b26 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -95,6 +95,11 @@ export class LastFmManager { this._mysqlConfig = mysqlConfig; this._pool = null; + /** @type {string|null} Bot user ID — used to isolate rows per-bot in shared databases */ + this.botId = null; + /** @type {boolean} Whether the bot_id column exists in the lastfm tables */ + this._hasBotIdColumn = false; + // In-memory user cache: Map this._userCache = new Map(); @@ -108,6 +113,64 @@ export class LastFmManager { } } + // ── Bot ID isolation ───────────────────────────────────────────────────── + + /** + * Set the bot ID for multi-bot database isolation. + * Ensures bot_id column exists in lastfm tables, then clears caches. + * @param {string} id - The bot's Discord user ID + */ + async setBotId(id) { + const changed = this.botId !== id; + this.botId = id; + if (changed) { + await this._ensureBotIdColumn(); + this._userCache.clear(); + } + } + + /** + * Auto-migrate: add bot_id column to lastfm_users and lastfm_stats if missing. + */ + async _ensureBotIdColumn() { + if (this._hasBotIdColumn) return; + const pool = await this._getPool(); + + // Check lastfm_users + const [cols] = await pool.execute( + `SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_users' AND COLUMN_NAME = 'bot_id'` + ); + if (cols.length === 0) { + logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_users..."); + await pool.execute("ALTER TABLE `lastfm_users` ADD COLUMN `bot_id` VARCHAR(32) DEFAULT NULL"); + await pool.execute("ALTER TABLE `lastfm_users` DROP PRIMARY KEY, ADD PRIMARY KEY (user_id, bot_id)"); + logger.settings("[LastFm] Auto-migration complete: lastfm_users.bot_id added."); + } + + // Check lastfm_stats + const [statsCols] = await pool.execute( + `SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_stats' AND COLUMN_NAME = 'bot_id'` + ); + if (statsCols.length === 0) { + logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_stats..."); + await pool.execute("ALTER TABLE `lastfm_stats` ADD COLUMN `bot_id` VARCHAR(32) DEFAULT NULL"); + await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)"); + logger.settings("[LastFm] Auto-migration complete: lastfm_stats.bot_id added."); + } + + this._hasBotIdColumn = true; + } + + /** + * Returns SQL WHERE fragment for bot_id filtering. + * Uses prepared statement placeholder (?) for safety. + * @returns {{ where: string, params: string[] }} + */ + _botIdFilter() { + if (!this.botId || !this._hasBotIdColumn) return { where: "", params: [] }; + return { where: " AND bot_id = ?", params: [String(this.botId)] }; + } + // ── MySQL ────────────────────────────────────────────────────────────────── async _getPool() { @@ -166,9 +229,10 @@ export class LastFmManager { if (cached) return cached; const pool = await this._getPool(); + const f = this._botIdFilter(); const [rows] = await pool.execute( - "SELECT session_key, username, scrobble FROM lastfm_users WHERE user_id = ?", - [String(userId)] + `SELECT session_key, username, scrobble FROM lastfm_users WHERE user_id = ?${f.where}`, + [String(userId), ...f.params] ); if (!rows.length) return null; @@ -185,11 +249,12 @@ export class LastFmManager { async saveUser(userId, sessionKey, username) { const pool = await this._getPool(); + const f = this._botIdFilter(); await pool.execute( - `INSERT INTO lastfm_users (user_id, session_key, username, scrobble) - VALUES (?, ?, ?, 1) + `INSERT INTO lastfm_users (user_id, session_key, username, scrobble${f.where ? ', bot_id' : ''}) + VALUES (?, ?, ?, 1${f.where ? ', ?' : ''}) ON DUPLICATE KEY UPDATE session_key = VALUES(session_key), username = VALUES(username)`, - [String(userId), sessionKey, username ?? ""] + [String(userId), sessionKey, username ?? "", ...f.params] ); const data = { sessionKey, username: username ?? "", scrobbleEnabled: true }; this._userCache.set(userId, data); @@ -197,8 +262,8 @@ export class LastFmManager { // Increment linked_users counter (only on new links, not re-links) try { await pool.execute( - "UPDATE lastfm_stats SET linked_users = linked_users + 1 WHERE id = 1 AND NOT EXISTS (SELECT 1 FROM (SELECT 1 FROM lastfm_users WHERE user_id = ? AND linked_at < NOW()) AS tmp)", - [String(userId)] + `UPDATE lastfm_stats SET linked_users = linked_users + 1 WHERE id = 1${f.where} AND NOT EXISTS (SELECT 1 FROM (SELECT 1 FROM lastfm_users WHERE user_id = ?${f.where} AND linked_at < NOW()) AS tmp)`, + [...f.params, String(userId), ...f.params] ); } catch { // Non-critical — don't fail the save @@ -209,15 +274,17 @@ export class LastFmManager { async removeUser(userId) { const pool = await this._getPool(); - await pool.execute("DELETE FROM lastfm_users WHERE user_id = ?", [String(userId)]); + const f = this._botIdFilter(); + await pool.execute(`DELETE FROM lastfm_users WHERE user_id = ?${f.where}`, [String(userId), ...f.params]); this._userCache.delete(userId); } async setScrobble(userId, enabled) { const pool = await this._getPool(); + const f = this._botIdFilter(); await pool.execute( - "UPDATE lastfm_users SET scrobble = ? WHERE user_id = ?", - [enabled ? 1 : 0, String(userId)] + `UPDATE lastfm_users SET scrobble = ? WHERE user_id = ?${f.where}`, + [enabled ? 1 : 0, String(userId), ...f.params] ); const cached = this._userCache.get(userId); if (cached) cached.scrobbleEnabled = enabled; @@ -818,8 +885,10 @@ export class LastFmManager { const pool = await this._getPool(); // Get all linked user IDs + const f = this._botIdFilter(); const [rows] = await pool.execute( - "SELECT user_id FROM lastfm_users" + `SELECT user_id FROM lastfm_users WHERE 1=1${f.where}`, + [...f.params] ); if (!rows.length) { @@ -839,7 +908,8 @@ export class LastFmManager { // Now sum up all scrobble_count values from the DB const [sumRows] = await pool.execute( - "SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users" + `SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users WHERE 1=1${f.where}`, + [...f.params] ); const total = Number(sumRows[0]?.total ?? 0); @@ -863,8 +933,10 @@ export class LastFmManager { if (!this.enabled) return 0; try { const pool = await this._getPool(); + const f = this._botIdFilter(); const [rows] = await pool.execute( - "SELECT linked_users FROM lastfm_stats WHERE id = 1" + `SELECT linked_users FROM lastfm_stats WHERE id = 1${f.where}`, + [...f.params] ); return Number(rows[0]?.linked_users ?? 0); } catch { @@ -882,10 +954,12 @@ export class LastFmManager { if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 }; const pool = await this._getPool(); + const f = this._botIdFilter(); // Get total count const [countRows] = await pool.execute( - "SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0" + `SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0${f.where}`, + [...f.params] ); const totalUsers = Number(countRows[0]?.total ?? 0); const totalPages = Math.max(1, Math.ceil(totalUsers / perPage)); @@ -895,8 +969,8 @@ export class LastFmManager { const offset = page * perPage; const [rows] = await pool.execute( - "SELECT user_id, username, scrobble_count FROM lastfm_users WHERE scrobble_count > 0 ORDER BY scrobble_count DESC LIMIT ? OFFSET ?", - [String(perPage), String(offset)] + `SELECT user_id, username, scrobble_count FROM lastfm_users WHERE scrobble_count > 0${f.where} ORDER BY scrobble_count DESC LIMIT ? OFFSET ?`, + [...f.params, String(perPage), String(offset)] ); const entries = rows.map(r => ({ @@ -921,9 +995,10 @@ export class LastFmManager { const info = await this.getUserInfo(userId); const playcount = Number(info.playcount ?? 0); const pool = await this._getPool(); + const f = this._botIdFilter(); await pool.execute( - "UPDATE lastfm_users SET scrobble_count = ? WHERE user_id = ?", - [String(playcount), String(userId)] + `UPDATE lastfm_users SET scrobble_count = ? WHERE user_id = ?${f.where}`, + [String(playcount), String(userId), ...f.params] ); return playcount; } catch { @@ -943,10 +1018,11 @@ export class LastFmManager { */ _incrementScrobbleCount(userId) { if (!userId) return; + const f = this._botIdFilter(); this._getPool().then(pool => { pool.execute( - "UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?", - [String(userId)] + `UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?${f.where}`, + [String(userId), ...f.params] ).catch(() => {}); }).catch(() => {}); } diff --git a/src/Settings.mjs b/src/Settings.mjs index 69fdf36..3bc4650 100644 --- a/src/Settings.mjs +++ b/src/Settings.mjs @@ -37,17 +37,24 @@ export class RemoteSettingsManager extends EventEmitter { descriptions = {}; defaults = {}; db = null; + /** @type {string|null} Bot user ID — used to isolate rows per-bot in shared databases */ + botId = null; + /** @type {boolean} Whether the bot_id column exists in the settings table */ + _hasBotIdColumn = false; // track retry count and apply exponential backoff on load failures _loadAttempts = 0; + /** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */ + _loadPromise = null; // Per-server debounce timers: serverId → NodeJS.Timeout // Batches rapid set() calls (e.g. 24/7 mode changes that write stay_247 + stay_247_mode) // into a single remoteSave() 80ms after the last write, rather than firing one UPDATE // per key. _debounceTimers = new Map(); - constructor(config, defaultsPath) { + constructor(config, defaultsPath, botId = null) { super(); + this.botId = botId; this.db = mysql.createPool({ connectionLimit: 15, ...config }); // Without this listener, any pool-level error (connection drop, timeout, protocol error) // fires an unhandled 'error' event which crashes the entire process with no log output. @@ -55,7 +62,111 @@ export class RemoteSettingsManager extends EventEmitter { logger.error("[DB] MySQL pool error:", err.code ?? err.message); }); if (defaultsPath) this.loadDefaultsSync(defaultsPath); - this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err)); + this._loadPromise = this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err)); + } + + /** + * Check whether the `bot_id` column exists in the settings table. + * If it doesn't, auto-migrate by adding the column and updating the primary key. + * This ensures old databases work seamlessly with the new multi-bot code. + */ + async _ensureBotIdColumn() { + if (this._hasBotIdColumn) return; // already checked, column exists + + const res = await this.query( + `SELECT COLUMN_NAME FROM information_schema.COLUMNS ` + + `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'` + ); + + if (res.error) { + logger.error("[Settings] Failed to check bot_id column:", res.error); + return; + } + + if (res.results.length > 0) { + // Column already exists + this._hasBotIdColumn = true; + return; + } + + // Auto-migrate: add bot_id column and update primary key + logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); + + const alterRes = await this.query( + `ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) DEFAULT NULL` + ); + if (alterRes.error) { + logger.error("[Settings] Failed to add bot_id column:", alterRes.error); + return; + } + + // Update primary key from (id) to (id, bot_id) + const pkRes = await this.query( + `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` + ); + if (pkRes.error) { + logger.error("[Settings] Failed to update primary key:", pkRes.error); + // Column was added but PK update failed — still mark as available + // since the column exists and queries will work + } + + this._hasBotIdColumn = true; + logger.settings("[Settings] Auto-migration complete: bot_id column added."); + } + + /** + * Set or update the bot ID used for database row isolation. + * Called after login when the bot user ID becomes available. + * Ensures the bot_id column exists (auto-migrates if needed), then + * reloads guild data filtered by the bot's ID. + * @param {string} id + */ + async setBotId(id) { + const changed = this.botId !== id; + this.botId = id; + if (changed) { + // Wait for the initial load to finish before clearing and reloading + if (this._loadPromise) await this._loadPromise; + // Ensure the DB schema supports bot_id before querying with it + await this._ensureBotIdColumn(); + // Reload with the new botId so we pick up this bot's rows + this.guilds.clear(); + this._loadPromise = this.load(); + await this._loadPromise; + } + } + + /** + * Returns the SQL WHERE clause fragment for bot_id filtering. + * When botId is set AND the bot_id column exists in the table, + * includes "AND bot_id = " in queries. + * Otherwise no filter is applied (backward-compatible with old schemas). + * @returns {string} + */ + _botIdWhere() { + if (!this.botId || !this._hasBotIdColumn) return ""; + return ` AND bot_id = ${mysql.escape(String(this.botId))}`; + } + + /** + * Returns the bot_id column + value for INSERT statements. + * Only includes bot_id when both the botId is set AND the column exists. + * @returns {{ col: string, val: string }} + */ + _botIdInsert() { + if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" }; + return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` }; + } + + /** + * Fetch a single guild's settings row from the database, filtered by bot_id. + * Used by GatewayHandler when a guild is (re-)joined and not in the cache. + * @param {string} guildId + * @returns {Promise<{error: object|null, results: Array, fields: Array}>} + */ + selectGuild(guildId) { + const escapedId = mysql.escape(String(guildId)); + return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`); } query(q) { @@ -65,7 +176,7 @@ export class RemoteSettingsManager extends EventEmitter { } async load() { - const res = await this.query("SELECT * FROM settings"); + const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`); if (res.error) { this._loadAttempts++; // exponential backoff with a cap of 30s instead of forever-at-2s @@ -105,14 +216,14 @@ export class RemoteSettingsManager extends EventEmitter { ? mysql.escape(val) : mysql.escape(String(val)); const escapedId = mysql.escape(server.id); - const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, ${escapedVal}) WHERE id=${escapedId}`); + const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, ${escapedVal}) WHERE id=${escapedId}${this._botIdWhere()}`); if (r.error) logger.error("[Settings] remoteUpdate error:", r.error); } async remoteSave(server) { const escapedData = mysql.escape(JSON.stringify(server.data)); const escapedId = mysql.escape(server.id); - const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}`); + const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}`); if (r.error) logger.error("[Settings] remoteSave error:", r.error); } @@ -136,7 +247,8 @@ export class RemoteSettingsManager extends EventEmitter { async create(id, server) { const escapedId = mysql.escape(id); const escapedData = mysql.escape(JSON.stringify(server.data)); - const r = await this.query(`INSERT INTO settings (id, data) VALUES (${escapedId}, ${escapedData})`); + const bi = this._botIdInsert(); + const r = await this.query(`INSERT INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})`); if (r.error) logger.error("[Settings] create error:", r.error); } diff --git a/src/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index 7fbad0d..41c6ceb 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -92,6 +92,20 @@ export class Dashboard { } // ═══════════════════════════════════════════════════════════════════════════ + // ── Bot ID isolation ────────────────────────────────────────────────────── + + /** + * Set the bot ID for multi-bot Redis namespace isolation. + * Updates the Redis platform string so each bot uses its own channel namespace. + * @param {string} botId - The bot's Discord user ID + */ + setBotId(botId) { + if (!this.enabled || !this.redis) return; + // Use "fluxer_" as the platform so each bot's Redis messages + // are isolated. The dashboard backend must also be configured to match. + this.redis.platform = `fluxer_${botId}`; + } + // Dashboard Function Dispatch // ═══════════════════════════════════════════════════════════════════════════