hotfix/added restore queue/added some good stuff to/removing some stuff to

This commit is contained in:
NoLogicAlan committed 2026-09-16 02:02:29 +03:00
1 parent ca98dc11aa
commit 8a8925653c
17 files changed
+429 -22

No files matched your search

+5 -1
View File
@@ -18,6 +18,7 @@ import { MessageHandler, HelpCommand, setGlobalColor } from "../ui/index.mjs";
import { cleanId } from "../utils/Utils.mjs";
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
import { RemoteSettingsManager } from "../db/Settings.mjs";
import { PlayerStateStore } from "../db/PlayerStateStore.mjs";
import { PlayerManager } from "../music/PlayerManager.mjs";
import { LavalinkManager } from "../music/LavalinkManager.mjs";
import { Dashboard } from "../dashboard/Dashboard.mjs";
@@ -176,6 +177,8 @@ class Remix {
const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
this.settingsMgr = settings;
this.playerState = new PlayerStateStore(settings.db);
const configPrefix = config.prefix ?? null;
if (configPrefix && settings.defaults) {
settings.defaults.prefix = configPrefix;
@@ -258,6 +261,7 @@ class Remix {
await this.settingsMgr.setBotId(botId);
await this.lastfm.setBotId(botId);
this.playerState?.setBotId?.(botId);
this.dashboard.setBotId(botId);
this.trackOptions.setBotId(botId);
@@ -493,7 +497,7 @@ class Remix {
player._startInactivityTimer?.();
} else {
player._stopInactivityTimer?.();
player.emit("autoleave");
if (!player._stayInVoice) player.emit("autoleave");
}
} else if (hasHuman) {
player._stopInactivityTimer?.();
+98
View File
@@ -413,6 +413,104 @@ const BotVoiceMixin = {
}
},
/**
* Restore music players saved before a restart/crash (PlayerStateStore).
* Called from GatewayHandler.onReady after the 24/7 boot recovery.
* @this {import('./Bot.mjs').Remix}
* @returns {Promise<void>}
*/
async restorePlayerState() {
const store = this.playerState;
if (!store) return;
let rows = [];
try {
rows = await store.loadAll();
} catch (e) {
logger.warn("[Restore] Could not load saved player state:", e?.message);
return;
}
if (!rows.length) return;
const lava = this.lavalink;
if (lava?.hasConnectedNode && !lava.hasConnectedNode() && lava.waitForNode) {
logger.player("[Restore] Waiting up to 90s for an audio node...");
await lava.waitForNode({ timeoutMs: 90_000, intervalMs: 2_000 }).catch(() => {});
}
const local = rows.filter((r) => {
try { return !!this.client?.guilds?.get?.(r.guildId); } catch (_) { return false; }
});
logger.player(`[Restore] ${rows.length} saved player(s) found — restoring ${local.length} on this shard.`);
if (!local.length) return;
for (let i = 0; i < local.length; i++) {
const { guildId, data: snap } = local[i];
if (i > 0) await new Promise((r) => setTimeout(r, 1_500));
try {
const channelId = cleanId(snap.channelId);
if (!channelId) { await store.clearSnapshot(guildId); continue; }
const channel = await resolveChannelCached(this.client, channelId);
if (!channel || channel.type !== 2) {
logger.player(`[Restore] Channel ${channelId} for guild ${guildId} is gone — dropping snapshot.`);
await store.clearSnapshot(guildId);
continue;
}
const player = await this._spawnPlayer(guildId, channelId);
const tcId = cleanId(snap.textChannelId);
if (tcId) {
const tc = this.client?.channels?.get?.(tcId);
if (tc) player.textChannel = tc;
}
if (Number.isFinite(snap.volume) && snap.volume > 0) {
try { player.setVolume(Math.min(Number(snap.volume), 2)); } catch (_) {}
}
player.queue.loop = !!snap.loop;
player.queue.songLoop = !!snap.songLoop;
const restoredQueue = (Array.isArray(snap.queue) ? snap.queue : [])
.filter((t) => t && (t.url || t.encoded));
let current = (snap.current && (snap.current.url || snap.current.encoded)) ? snap.current : null;
const pos = Math.max(0, Number(snap.positionMs) || 0);
const dur = Number(current?._durationMs) || 0;
if (current && dur > 0 && pos > dur * 0.9) current = null;
player.queue.data = [];
if (current) player.queue.data.push(current);
for (const t of restoredQueue) player.queue.data.push(t);
if (!player.queue.data.length) {
await store.clearSnapshot(guildId);
continue;
}
player.emit("message", {
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
player._t?.("responses._common.queueRestored", { count: player.queue.data.length })
?? `Bot restarted — restored **${player.queue.data.length}** song(s) to the queue.`)],
system: true,
});
await player.playNext();
if (current && pos > 0) {
await new Promise((r) => setTimeout(r, 800)); // let the bridge settle
try { await player.seekToPosition(pos); } catch (_) {}
}
logger.player(`[Restore] Guild ${guildId}: ${player.queue.data.length} track(s) restored, resuming at ${pos}ms.`);
} catch (e) {
logger.warn(`[Restore] Failed to restore guild ${guildId}:`, e?.message ?? e);
}
}
},
/**
* Leave a voice channel programmatically. Removes 24/7 if active, destroys
* the player, and optionally sends a confirmation message.
+266
View File
@@ -0,0 +1,266 @@
/**
* @module src/db/PlayerStateStore
* @description MySQL-backed persistence for music player state so queues
* survive bot reboots/crashes. One row per (bot_id, guild_id) holding a JSON
* snapshot of the player: voice channel, text channel, queue tracks, current
* track, resume position, volume and loop modes.
*
* WHY MySQL AND NOT REDIS/FILES:
* - The bot already owns a MySQL pool (RemoteSettingsManager) that is flushed
* on graceful shutdown; snapshots ride the same healthy connection and are
* durable across restarts of ANY component.
* - The project's Redis handle (dashboard RedisHandler) is a pub/sub cache
* whose client is closed on shutdown — it is the wrong place for state
* that must outlive a reboot.
* - Local JSON files were audited and removed from the hot path years ago
* (storage/stats.json has no writer left); adding file writes would make
* the bot slower, not faster.
*
* Write pattern:
* - Full snapshot: debounced 3s per player, triggered by queue/playback
* events (see Player.mjs).
* - Position heartbeat: single cheap UPDATE of the position_ms column every
* 15s while a track is playing, so resume-after-crash lands within ~15s
* of where the song actually was.
*/
import { logger } from "../core/Logger.mjs";
import { cleanId } from "../utils/Utils.mjs";
/** Maximum number of queued tracks persisted in one snapshot. */
const MAX_PERSISTED_TRACKS = 300;
/**
* Reduce a track object to the plain fields needed to rebuild and replay it.
* Track objects are plain data already, but the whitelist keeps the payload
* small and guarantees JSON-safety (no circular refs from richer sources).
* @param {object|null} t - Track object.
* @returns {object|null} Slim track or null.
*/
function slimTrack(t) {
if (!t || typeof t !== "object") return null;
return {
encoded: typeof t.encoded === "string" ? t.encoded : null,
title: t.title ?? "Unknown",
url: t.url ?? null,
thumbnail: t.thumbnail ?? null,
artworkUrl: t.artworkUrl ?? null,
_durationMs: Number(t._durationMs) || 0,
duration: t.duration ?? null,
author: t.author ?? null,
requester: t.requester ?? null,
type: t.type ?? null,
identifier: t.identifier ?? null,
isStream: !!t.isStream,
};
}
/**
* Compute the playback position of a player's current track in ms.
* `startedPlaying` is kept in sync across seeks and pauses by the player
* (resume folds pause duration back in), so:
* - playing → Date.now() - startedPlaying
* - paused → _pausedAt - startedPlaying (elapsed at the pause moment)
* @param {object} player - Player instance.
* @param {object|null} current - Current track.
* @returns {number} Position in ms (0 when unknown).
*/
function computePosition(player, current) {
if (!current) return 0;
try {
if (player._paused && player._pausedAt && player.startedPlaying) {
return Math.max(0, player._pausedAt - player.startedPlaying);
}
if (player.startedPlaying) {
return Math.max(0, Date.now() - player.startedPlaying);
}
} catch (_) { /* fallthrough */ }
return 0;
}
/**
* @class PlayerStateStore
* @description Persists and restores player snapshots in MySQL. Reuses the
* settings manager's mysql2 pool (callback API) — no extra connections.
*/
export class PlayerStateStore {
/** @private @type {object|null} mysql2 callback-style pool. */
db = null;
/** @private @type {string} Bot user id for multi-bot isolation. */
botId = "";
/** @private @type {Promise<void>|null} Memoized CREATE TABLE promise. */
_tableReady = null;
/**
* @param {object|null} pool - mysql2 callback pool (RemoteSettingsManager.db).
*/
constructor(pool) {
this.db = pool ?? null;
}
/**
* Set the bot id (called once the gateway client is ready).
* @param {string} id - Bot user id.
*/
setBotId(id) {
this.botId = id ? String(id) : "";
}
/**
* Promisified pool.query with parameter binding.
* @private
* @param {string} sql - SQL with ? placeholders.
* @param {Array} [params=[]] - Bind parameters.
* @returns {Promise<any>} Result set.
*/
_exec(sql, params = []) {
return new Promise((resolve, reject) => {
if (!this.db) return reject(new Error("PlayerStateStore: no MySQL pool"));
this.db.query(sql, params, (err, results) => (err ? reject(err) : resolve(results)));
});
}
/**
* Create the player_state table if needed (idempotent, memoized).
* @returns {Promise<void>}
*/
init() {
if (!this._tableReady) {
this._tableReady = this._exec(
`CREATE TABLE IF NOT EXISTS player_state (
bot_id VARCHAR(32) NOT NULL DEFAULT '',
guild_id VARCHAR(32) NOT NULL,
data MEDIUMTEXT NOT NULL,
position_ms BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (bot_id, guild_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
).catch((err) => {
this._tableReady = null; // allow retry on next call
throw err;
});
}
return this._tableReady;
}
/**
* Persist a full snapshot of a player (debounce happens on the caller side).
* Deletes the row instead when the player has neither a current track nor
* queued songs (nothing worth restoring).
* @param {object} player - Player instance (duck-typed).
* @returns {Promise<void>}
*/
async saveSnapshot(player) {
if (!player || player._destroyed || player.leaving) return;
const guildId = cleanId(player._guildId ?? "");
if (!guildId) return;
const current = player.queue?.getCurrent?.() ?? null;
const queued = Array.isArray(player.queue?.data) ? player.queue.data : [];
if (!current && queued.length === 0) {
return this.clearSnapshot(guildId);
}
await this.init();
const channelId = cleanId(player._channelId ?? player._home247Channel ?? "");
if (!channelId) return;
const positionMs = computePosition(player, current);
const textChannel = player.textChannel ?? null;
const payload = {
v: 1,
guildId,
channelId,
textChannelId: cleanId(textChannel?.id ?? textChannel?.channel?.id ?? ""),
volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume : null,
loop: !!player.queue?.loop,
songLoop: !!player.queue?.songLoop,
current: slimTrack(current),
positionMs,
queue: queued.slice(0, MAX_PERSISTED_TRACKS).map(slimTrack).filter(Boolean),
savedAt: Date.now(),
};
await this._exec(
`INSERT INTO player_state (bot_id, guild_id, data, position_ms)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE data = VALUES(data), position_ms = VALUES(position_ms)`,
[this.botId, guildId, JSON.stringify(payload), positionMs]
);
}
/**
* Cheap heartbeat: update only the resume position of a guild's snapshot.
* @param {string} guildId - Guild id.
* @param {number} positionMs - Position within the current track in ms.
* @returns {Promise<void>}
*/
async updatePosition(guildId, positionMs) {
const gId = cleanId(guildId);
if (!gId) return;
await this.init();
await this._exec(
`UPDATE player_state SET position_ms = ? WHERE bot_id = ? AND guild_id = ?`,
[Math.max(0, Math.round(Number(positionMs) || 0)), this.botId, gId]
);
}
/**
* Remove a guild's snapshot (intentional %leave, guild gone, empty queue).
* @param {string} guildId - Guild id.
* @returns {Promise<void>}
*/
async clearSnapshot(guildId) {
const gId = cleanId(guildId);
if (!gId || !this.db) return;
try {
await this.init();
await this._exec(`DELETE FROM player_state WHERE bot_id = ? AND guild_id = ?`, [this.botId, gId]);
} catch (e) {
logger.warn("[PlayerState] clearSnapshot failed:", e?.message);
}
}
/**
* Load every snapshot belonging to this bot.
* @returns {Promise<Array<{guildId: string, data: object, positionMs: number}>>}
*/
async loadAll() {
await this.init();
const rows = await this._exec(
`SELECT guild_id, data, position_ms FROM player_state WHERE bot_id = ?`,
[this.botId]
);
const out = [];
for (const row of Array.isArray(rows) ? rows : []) {
try {
const parsed = typeof row.data === "string" ? JSON.parse(row.data) : row.data;
if (parsed && parsed.channelId) {
out.push({ guildId: String(row.guild_id), data: parsed, positionMs: Number(row.position_ms) || 0 });
}
} catch (e) {
logger.warn("[PlayerState] Skipping malformed snapshot for guild", row.guild_id, ":", e?.message);
}
}
return out;
}
/**
* Snapshot every live player of a manager immediately (shutdown path).
* @param {object} playerManager - Object exposing playerMap (channelId → Player).
* @returns {Promise<void>}
*/
async saveAllFrom(playerManager) {
const players = [...(playerManager?.playerMap?.values?.() ?? [])];
const alive = players.filter((p) => p && !p._destroyed && !p.leaving);
if (alive.length === 0) return;
logger.recovery(`[PlayerState] Saving ${alive.length} player snapshot(s) before shutdown...`);
await Promise.allSettled(alive.map((p) => this.saveSnapshot(p)));
}
}
export default PlayerStateStore;
-2
View File
@@ -146,8 +146,6 @@ const PlayerLifecycleMixin = {
const guildId = getMessageGuildId(msg);
const cleanGuildId = cleanId(guildId);
/* DMs have no voice channels — prompting for a channel selection would
be pointless (and hang until timeout). Tell the user directly. */
if (!cleanGuildId) {
await msg.reply(this._t(msg, "responses._common.serverOnlyForMusic")).catch(() => {});
return false;
+39
View File
@@ -156,6 +156,32 @@ class Player extends EventEmitter {
}
}
this._stayInVoice = this.config?.timers?.stayInVoice ?? this.config?.stayInVoice ?? true;
this._snapSaveTimer = null;
this._scheduleStateSave = () => {
if (this._snapSaveTimer || this._destroyed || this.leaving) return;
this._snapSaveTimer = setTimeout(() => {
this._snapSaveTimer = null;
try {
this.client?._remix?.playerState?.saveSnapshot(this)?.catch?.(() => {});
} catch (_) { /* persistence must never break playback */ }
}, 3_000);
};
for (const evt of ["queue", "startplay", "stopplay", "playback"]) {
try { this.on(evt, this._scheduleStateSave); } catch (_) {}
}
this._stateHeartbeat = setInterval(() => {
try {
const current = this.queue?.getCurrent?.();
if (!current || this._destroyed || this.leaving || this._paused) return;
if (!this.startedPlaying) return;
const pos = Math.max(0, Date.now() - this.startedPlaying);
this.client?._remix?.playerState?.updatePosition?.(this._guildId, pos)?.catch?.(() => {});
} catch (_) { /* best effort */ }
}, 15_000);
this._stateHeartbeat.unref?.();
if (this._lavalink) {
this._onLavalinkPlayerDisconnect = (lavaPlayer) => {
if (!lavaPlayer || String(lavaPlayer.guildId) !== String(this._guildId)) return;
@@ -269,6 +295,11 @@ class Player extends EventEmitter {
this._stopInactivityTimer();
if (this._inactivityLimit <= 0) return;
if (this._stayInVoice) {
logger.inactivity(`[Player] stay-in-voice active for guild ${this._guildId} — skipping inactivity auto-leave`);
return;
}
const mode = this._get247Mode();
logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`);
@@ -614,6 +645,10 @@ class Player extends EventEmitter {
this.removeListener("queueEnd", this._autoplayHandler);
this._autoplayHandler = null;
}
try {
this.client?._remix?.playerState?.clearSnapshot?.(this._guildId)?.catch?.(() => {});
} catch (_) { /* best effort */ }
} catch (e) {
logger.error("[Player] leave error:", e.message);
this.leaving = false;
@@ -632,6 +667,10 @@ class Player extends EventEmitter {
if (this._destroyed) return;
this._destroyed = true;
this._scheduleStateSave = null;
if (this._snapSaveTimer) { clearTimeout(this._snapSaveTimer); this._snapSaveTimer = null; }
if (this._stateHeartbeat) { clearInterval(this._stateHeartbeat); this._stateHeartbeat = null; }
this._clearTrackEndTimer();
this._activeTrackOpt = null;
+1 -15
View File
@@ -321,11 +321,6 @@ const ServerStatsMixin = {
async getLeaderboard(page = 0, perPage = 10) {
if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 };
/* Sync scrobble counts from Last.fm before ranking. The local counter
only advances on bot-made scrobbles, so listening done outside the
bot (phone/desktop clients) would never show up. getTotalScrobbles()
syncs every linked user, is deduped while in-flight, cached for 10
minutes, and resolves (never throws) even if the API is down. */
try {
await this.getTotalScrobbles();
} catch (_) { /* stale counts are better than no leaderboard */ }
@@ -359,9 +354,6 @@ const ServerStatsMixin = {
/**
* Global rank (1-based) of one user on the all-time scrobble leaderboard.
* Returns null when the user is not linked or has no scrobbles recorded
* yet (they are not ranked). Used so anyone can check whether they are
* top 1, 2, 3 ... even when their row is not on the visible page.
* @async
* @param {string} userId - Platform user ID to look up.
* @returns {Promise<{rank: number, scrobbleCount: number}|null>} Rank info or null.
@@ -388,10 +380,7 @@ const ServerStatsMixin = {
},
/**
* Get the scrobble leaderboard scoped to a set of platform user IDs
* (typically the members of one guild), with pagination. Refreshes only
* these users' counts from Last.fm first (5-minute TTL, deduped while
* in-flight) so pagination turns don't hammer the API.
* Get the scrobble leaderboard scoped to a set of platform user IDs, with pagination.
* @async
* @param {Array<string>} userIds - Platform user IDs to include.
* @param {number} [page=0] - Zero-based page index.
@@ -407,9 +396,6 @@ const ServerStatsMixin = {
.filter(id => /^\d{5,25}$/.test(id)))];
if (!ids.length) return empty;
/* Refresh just these users' counts from Last.fm before ranking.
The local counter only advances on bot-made scrobbles, so listening
done outside the bot would never show up. TTL-gated + deduped. */
try {
if (!this._lbServerSyncAt || Date.now() - this._lbServerSyncAt > 5 * 60 * 1000) {
if (!this._lbServerSyncInflight) {
+7
View File
@@ -448,6 +448,13 @@ class GatewayHandler {
this.rejoin247Channels();
this.start247Watchdog();
try {
this.remix.restorePlayerState?.().catch?.((e) =>
logger.warn("[Restore] Player state restore failed:", e?.message));
} catch (e) {
logger.warn("[Restore] Player state restore could not start:", e?.message);
}
}
/**