diff --git a/config_example.json b/config_example.json index ad30dbe..037e29f 100644 --- a/config_example.json +++ b/config_example.json @@ -110,6 +110,13 @@ "connectionLimit": 15, "connectionLimit-Comment": "Maximum simultaneous MySQL connections shared across all bot services (default: 15). Prevents connection pool exhaustion in multi-shard deployments." }, + "redis": { + "enabled": false, + "url": "redis://127.0.0.1:6379", + "password": null, + "searchTtlSeconds": 86400, + "Comment": "Centralized Redis service for ultra-fast track search caching (<1ms repeat lookups), 24/7 session restoration across bot reboots, and cross-shard atomic playback statistics. If disabled or omitted, searches fall back to direct Lavalink/NodeLink queries and sessions fall back to MySQL." + }, "dashboard": { "enabled": false, "redis": { diff --git a/src/core/Bot.mjs b/src/core/Bot.mjs index edb89f6..2b875db 100644 --- a/src/core/Bot.mjs +++ b/src/core/Bot.mjs @@ -21,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 { RedisManager } from "../db/RedisManager.mjs"; import { getSharedMysqlPool, getSharedPromisePool, closeSharedMysqlPool } from "../db/PoolManager.mjs"; import { PlayerManager } from "../music/PlayerManager.mjs"; import { LavalinkManager } from "../music/LavalinkManager.mjs"; @@ -144,12 +145,21 @@ class Remix { TrackStats.setPool(sharedPromisePool); + const redisConfig = config.redis ?? (config.dashboard?.enabled ? config.dashboard?.redis : null); + this.redis = new RedisManager(this, redisConfig); + if (this.redis.enabled) { + this.redis.connect().catch((err) => { + logger.warn("[Redis] Startup connection error:", err?.message); + }); + TrackStats.setRedis(this.redis); + } + this.dashboard = new Dashboard(this, { enabled: config.dashboard?.enabled, - redis: config.dashboard?.redis, + redis: config.dashboard?.redis ?? (this.redis.enabled ? this.redis.config : null), mysql: sharedPromisePool, }); - if (this.dashboard?.redis) { + if (!this.redis.enabled && this.dashboard?.redis) { TrackStats.setRedis(this.dashboard.redis); } @@ -209,6 +219,9 @@ class Remix { this.settingsMgr = settings; this.playerState = new PlayerStateStore(sharedPool); + if (this.redis?.enabled) { + this.playerState.setRedis(this.redis); + } const configPrefix = config.prefix ?? null; if (configPrefix && settings.defaults) { @@ -373,6 +386,7 @@ class Remix { if (!lavalinkInitialised) { lavalinkInitialised = true; this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" }); + this.lavalink.remix = this; this.lavalink.on("ready", () => { logger.lavalink("[Lavalink] Session ready"); this.statusChannel?.resolveIncident("audioNode"); @@ -431,6 +445,7 @@ class Remix { config, player: this.playerContext, dashboard: this.dashboard, + redis: this.redis, locale: this.locale, timers: this.T, trackOptions: this.trackOptions, @@ -796,9 +811,11 @@ class Remix { TrackStats.save(); } catch (_) {} - // 4. Close Redis if dashboard enabled + /* 4. Close Redis */ try { - if (this.dashboard?.redis?.destroy) { + if (this.redis?.destroy) { + await this.redis.destroy(); + } else if (this.dashboard?.redis?.destroy) { await this.dashboard.redis.destroy(); } } catch (e) { diff --git a/src/db/PlayerStateStore.mjs b/src/db/PlayerStateStore.mjs index e4ccec3..0d0f263 100644 --- a/src/db/PlayerStateStore.mjs +++ b/src/db/PlayerStateStore.mjs @@ -75,6 +75,9 @@ export class PlayerStateStore { /** @private @type {Promise|null} Memoized CREATE TABLE promise. */ _tableReady = null; + /** @private @type {object|null} Optional Redis manager for caching player sessions. */ + redis = null; + /** * @param {object|null} pool - mysql2 callback pool (RemoteSettingsManager.db). */ @@ -82,6 +85,14 @@ export class PlayerStateStore { this.db = pool ?? null; } + /** + * Attach the Redis manager for ultra-fast session cache and recovery. + * @param {object|null} redisManager - RedisManager instance. + */ + setRedis(redisManager) { + this.redis = redisManager ?? null; + } + /** * Set the bot id (called once the gateway client is ready). * @param {string} id - Bot user id. @@ -173,6 +184,10 @@ export class PlayerStateStore { ON DUPLICATE KEY UPDATE data = VALUES(data), position_ms = VALUES(position_ms)`, [this.botId, guildId, JSON.stringify(payload), positionMs] ); + + if (this.redis?.isReady()) { + this.redis.savePlayerSession(guildId, payload).catch(() => {}); + } } /** @@ -198,7 +213,11 @@ export class PlayerStateStore { */ async clearSnapshot(guildId) { const gId = cleanId(guildId); - if (!gId || !this.db) return; + if (!gId) return; + if (this.redis?.isReady()) { + this.redis.deletePlayerSession(gId).catch(() => {}); + } + if (!this.db) return; try { await this.init(); await this._exec(`DELETE FROM player_state WHERE bot_id = ? AND guild_id = ?`, [this.botId, gId]); @@ -210,6 +229,16 @@ export class PlayerStateStore { async load(guildId) { const gId = cleanId(guildId); if (!gId) return null; + + if (this.redis?.isReady()) { + try { + const cached = await this.redis.getPlayerSession(gId); + if (cached && cached.channelId) { + return { guildId: gId, data: cached, positionMs: Number(cached.positionMs) || 0 }; + } + } catch (_) { /* fallback to database lookup */ } + } + await this.init(); const rows = await this._exec( `SELECT guild_id, data, position_ms FROM player_state WHERE bot_id = ? AND guild_id = ?`, diff --git a/src/db/RedisManager.mjs b/src/db/RedisManager.mjs new file mode 100644 index 0000000..2856d20 --- /dev/null +++ b/src/db/RedisManager.mjs @@ -0,0 +1,223 @@ +/** + * @module src/db/RedisManager + * @description Centralized Redis service for caching, atomic counters, + * track search optimization, and 24/7 session restoration. + */ + +import { createClient } from "redis"; +import { logger } from "../core/Logger.mjs"; + +/** + * Default linear-ramp reconnection strategy. + * @param {number} retries - Number of reconnection attempts made so far. + * @returns {number} Delay in milliseconds before next attempt. + */ +const DEFAULT_RETRY_STRATEGY = (retries) => { + if (!Number.isFinite(retries)) return 15_000; + return retries < 10 ? Math.min(retries * 500, 5_000) : 15_000; +}; + +/** + * @class RedisManager + * @description Oversees Redis connection lifecycle, search caching, and player session checkpoints. + */ +export class RedisManager { + /** + * @param {object} remix - The main Bot instance. + * @param {object} [config] - Redis configuration object. + */ + constructor(remix, config = {}) { + this.remix = remix; + this.config = config || {}; + this.enabled = this.config.enabled === true; + this.platform = "fluxer"; + + this.client = null; + this._isReady = false; + this._destroyed = false; + this.searchTtlSeconds = Number(this.config.searchTtlSeconds ?? 86400); + } + + /** + * Connect to the Redis server if enabled. + * @returns {Promise} + */ + async connect() { + if (!this.enabled || !this.config.url) { + logger.redis("[Redis] Disabled or missing URL in configuration."); + return false; + } + + try { + const clientOpts = { + url: this.config.url, + socket: { + connectTimeout: 5_000, + reconnectStrategy: DEFAULT_RETRY_STRATEGY, + }, + }; + + if (this.config.password) { + clientOpts.password = this.config.password; + } + + this.client = createClient(clientOpts); + + this.client.on("error", (err) => { + logger.warn("[Redis] Client error:", err.message); + }); + + this.client.on("ready", () => { + this._isReady = true; + logger.redis("[Redis] Connected and operational."); + }); + + this.client.on("reconnecting", () => { + this._isReady = false; + logger.redis("[Redis] Reconnecting to server..."); + }); + + this.client.on("end", () => { + this._isReady = false; + }); + + await this.client.connect(); + return true; + } catch (err) { + logger.warn("[Redis] Initial connection attempt failed:", err.message); + this._isReady = false; + return false; + } + } + + /** + * Check if the Redis client is connected and ready for commands. + * @returns {boolean} + */ + isReady() { + return this._isReady && Boolean(this.client?.isOpen); + } + + /** + * Get a cached track search result. + * @param {string} query - The search query or URL. + * @param {string} [source=""] - The Lavalink source prefix (e.g. ytmsearch). + * @returns {Promise} + */ + async getCachedSearch(query, source = "") { + if (!this.isReady() || !query) return null; + try { + const key = this.getSearchCacheKey(query, source); + const data = await this.client.get(key); + if (!data) return null; + return JSON.parse(data); + } catch (err) { + logger.warn("[Redis] Error reading search cache:", err?.message); + return null; + } + } + + /** + * Cache a track search result in Redis. + * @param {string} query - The search query or URL. + * @param {string} source - The Lavalink source prefix. + * @param {object} result - The search result object. + * @param {number} [ttlSeconds] - Custom TTL in seconds. + * @returns {Promise} + */ + async cacheSearch(query, source, result, ttlSeconds = this.searchTtlSeconds) { + if (!this.isReady() || !query || !result) return; + try { + const key = this.getSearchCacheKey(query, source); + await this.client.set(key, JSON.stringify(result), { + EX: ttlSeconds, + }); + } catch (err) { + logger.warn("[Redis] Error storing search cache:", err?.message); + } + } + + /** + * Build a standardized cache key for audio searches. + * @param {string} query - The search query or URL. + * @param {string} [source=""] - The source prefix. + * @returns {string} + */ + getSearchCacheKey(query, source = "") { + const cleanQuery = String(query).trim().toLowerCase().replace(/\s+/g, " "); + const cleanSource = String(source).trim().toLowerCase(); + return `${this.platform}:cache:search:${cleanSource}:${cleanQuery}`; + } + + /** + * Save a player session snapshot for 24/7 recovery across bot restarts. + * @param {string} guildId - The guild snowflake ID. + * @param {object} sessionData - Session payload (queue, currentTrack, volume, mode). + * @param {number} [ttlSeconds=604800] - 7 days default retention. + * @returns {Promise} + */ + async savePlayerSession(guildId, sessionData, ttlSeconds = 604800) { + if (!this.isReady() || !guildId || !sessionData) return; + try { + const key = `${this.platform}:player:session:${guildId}`; + await this.client.set(key, JSON.stringify(sessionData), { + EX: ttlSeconds, + }); + } catch (err) { + logger.warn(`[Redis] Failed to save player session for guild ${guildId}:`, err?.message); + } + } + + /** + * Retrieve a saved player session snapshot. + * @param {string} guildId - The guild snowflake ID. + * @returns {Promise} + */ + async getPlayerSession(guildId) { + if (!this.isReady() || !guildId) return null; + try { + const key = `${this.platform}:player:session:${guildId}`; + const data = await this.client.get(key); + if (!data) return null; + return JSON.parse(data); + } catch (err) { + logger.warn(`[Redis] Failed to load player session for guild ${guildId}:`, err?.message); + return null; + } + } + + /** + * Delete a saved player session snapshot. + * @param {string} guildId - The guild snowflake ID. + * @returns {Promise} + */ + async deletePlayerSession(guildId) { + if (!this.isReady() || !guildId) return; + try { + const key = `${this.platform}:player:session:${guildId}`; + await this.client.del(key); + } catch (err) { + logger.warn(`[Redis] Failed to delete player session for guild ${guildId}:`, err?.message); + } + } + + /** + * Gracefully close Redis connection. + * @returns {Promise} + */ + async destroy() { + if (this._destroyed) return; + this._destroyed = true; + this._isReady = false; + try { + if (this.client?.isOpen) { + await this.client.quit(); + } + } catch (e) { + logger.warn("[Redis] Quit error:", e?.message); + } + logger.redis("[Redis] Connection closed gracefully."); + } +} + +export default RedisManager; diff --git a/src/music/LavalinkManager.mjs b/src/music/LavalinkManager.mjs index 01fd59b..5232133 100644 --- a/src/music/LavalinkManager.mjs +++ b/src/music/LavalinkManager.mjs @@ -451,43 +451,59 @@ export class LavalinkManager extends EventEmitter { } /** @async Search for tracks on the Lavalink node. Tries player-based search first, then falls back to direct node lookup. @param {string} query - The search query string or URL. @param {object} [options] - Search options. @param {string} [options.source] - Lavalink source identifier (e.g. 'ytmsearch'). @param {string} [options.requester] - Requester identifier. @returns {Promise} Lavalink search result with tracks array. @throws {Error} If no connected node is available. */ async search(query, options = {}) { - try { - const players = this.lavalink?.players; - if (players?.size > 0) { - const firstPlayer = players.values?.().next?.().value; - if (firstPlayer?.node) { - logger.lavalink("[Lavalink] search via player.node for guild " + firstPlayer.guildId); - if (options.source) { - return firstPlayer.node.search({ query, source: options.source }); - } - return firstPlayer.node.search(query); - } + const redis = this.remix?.redis; + if (redis?.isReady() && typeof query === "string") { + const cached = await redis.getCachedSearch(query, options?.source); + if (cached && (cached.tracks?.length > 0 || cached.loadType === "track" || cached.loadType === "playlist" || cached.loadType === "search")) { + return cached; } - } catch (_) { /* fall through to node-based search */ } - - const node = this._getConnectedNode(); - if (node) { - logger.lavalink("[Lavalink] search via _getConnectedNode()"); - if (options.source) { - return node.search({ query, source: options.source }); - } - return node.search(query); } - try { - const nodes = this.lavalink?.nodes; - const nodeId = this._nodeCfg?.id ?? "main"; - const node = nodes?.get?.(nodeId) ?? nodes?.cache?.get?.(nodeId); - if (node) { - logger.lavalink("[Lavalink] search via fallback node.get()"); - if (options.source) { - return node.search({ query, source: options.source }); + const executeSearch = async () => { + try { + const players = this.lavalink?.players; + if (players?.size > 0) { + const firstPlayer = players.values?.().next?.().value; + if (firstPlayer?.node) { + logger.lavalink("[Lavalink] search via player.node for guild " + firstPlayer.guildId); + if (options.source) { + return await firstPlayer.node.search({ query, source: options.source }); + } + return await firstPlayer.node.search(query); + } } - return node.search(query); - } - } catch (_) {} + } catch (_) { /* fall through to node-based search */ } - throw new Error("No connected Lavalink node available for search"); + const node = this._getConnectedNode(); + if (node) { + logger.lavalink("[Lavalink] search via _getConnectedNode()"); + if (options.source) { + return await node.search({ query, source: options.source }); + } + return await node.search(query); + } + + try { + const nodes = this.lavalink?.nodes; + const nodeId = this._nodeCfg?.id ?? "main"; + const fallbackNode = nodes?.get?.(nodeId) ?? nodes?.cache?.get?.(nodeId); + if (fallbackNode) { + logger.lavalink("[Lavalink] search via fallback node.get()"); + if (options.source) { + return await fallbackNode.search({ query, source: options.source }); + } + return await fallbackNode.search(query); + } + } catch (_) {} + + throw new Error("No connected Lavalink node available for search"); + }; + + const result = await executeSearch(); + if (redis?.isReady() && result && (result.tracks?.length > 0 || result.loadType === "track" || result.loadType === "playlist")) { + redis.cacheSearch(query, options?.source, result).catch(() => {}); + } + return result; } /** Get the Lavalink player for a guild. @param {string} guildId - The guild ID. @returns {object|null} The Lavalink player, or null if not found. */