From 7b2d29e229611a55e5220db6712f0059ff594300 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Tue, 12 May 2026 16:38:24 +0300 Subject: [PATCH] refactor(recovery): remove session persistence, simplify 24/7 auto-join & fix gateway races - Remove boot-time recovery.json session persistence (RecoveryManager) - Replace 401 circuit-breaker with exponential backoff + 5-min guild ban - Add global voice join queue in FluxerRevoice (one join at a time, 3s gap) - Add 15s startup GuildDelete deferral to avoid wiping state during outages - Fix pendingSpawns Set/Map API mismatch in disconnect handler - Fix cross-guild join suppressing recovery for unrelated guild disconnects - Expose client._recoveryManager; remove shutdown recovery-save hooks - Increase guildMinJoinInterval from 7000ms to 8000ms --- index.mjs | 50 +-- src/GatewayHandler.mjs | 211 ++++++++-- src/Player.mjs | 4 +- src/PlayerManager.mjs | 4 +- src/RecoveryManager.mjs | 709 ++++++++------------------------ src/constants/FluxerRevoice.mjs | 176 +++++--- 6 files changed, 488 insertions(+), 666 deletions(-) diff --git a/index.mjs b/index.mjs index 312f23e..f0160b1 100644 --- a/index.mjs +++ b/index.mjs @@ -168,11 +168,15 @@ export class Remix { this._announcementChannelCache = new Map(); this.intentionalLeaves = new Map(); - // ── Recovery Manager ──────────────────────────────────────────────────── - // Handles session persistence, boot recovery, 24/7 auto-join, and player - // spawning with concurrency control. + // ── Recovery Manager (24/7 auto-join + spawn) ────────────────────────── + // Handles 24/7 auto-join on boot and player spawning. + // The boot-time session recovery system has been removed. this.recoveryManager = new RecoveryManager(this); + // Expose recoveryManager on the Fluxer client so that Player.mjs and + // other modules that only have a client reference can access it. + client._recoveryManager = this.recoveryManager; + // ── Gateway Handler ───────────────────────────────────────────────────── // Handles raw WS gateway events, voice-state tracking, presence rotation, // and high-level Fluxer event handlers (GuildCreate, GuildDelete, @@ -327,7 +331,7 @@ export class Remix { const guildId = player._guildId; if (!guildId) continue; - if (player._isJoining || player._isRecovering) continue; + if (player._isJoining) continue; const channelId = player._channelId ?? mapKey; const cleanChanId = String(channelId).replace(/\D/g, ""); @@ -426,16 +430,16 @@ export class Remix { this.players.checkVoiceChannels = function (message) { const userId = message?.author?.id ?? message?.message?.author?.id; const guildId = - message?.channel?.server_id ?? - message?.channel?.serverId ?? - message?.channel?.guild?.id ?? - message?.channel?.guildId ?? - message?.message?.server_id ?? - message?.message?.serverId ?? - message?.message?.guildId ?? + message?.channel?.guildId ?? + message?.channel?.guild?.id ?? + message?.channel?.server_id ?? + message?.channel?.serverId ?? + message?.message?.guildId ?? + message?.message?.guild?.id ?? + message?.message?.channel?.guildId ?? + message?.message?.channel?.guild?.id ?? message?.message?.channel?.server_id ?? - message?.message?.channel?.serverId ?? - message?.message?.channel?.guildId; + message?.message?.channel?.serverId; logger.voice(`[checkVC] userId=${userId} guildId=${guildId}`); logger.voice(`[checkVC] channel keys: ${Object.keys(message?.channel ?? {}).join(",")}`); @@ -836,13 +840,7 @@ export class Remix { ); } - buildRecoveryState() { - return this._buildRecoveryState?.() ?? []; - } - writeRecoveryState(state, sourceLabel = "Recovery") { - return this._writeRecoveryState?.(state, sourceLabel) ?? false; - } } // ── Boot ────────────────────────────────────────────────────────────────────── @@ -879,10 +877,6 @@ process.on("uncaughtException", (err, origin) => { } logger.error("[Error_Handling] Uncaught Exception/Catch"); logger.error("Error:", err, origin); - try { - const state = remix.buildRecoveryState(); - remix.writeRecoveryState(state, "Shutdown/Crash"); - } catch (_) {} process.exit(1); }); process.on("uncaughtExceptionMonitor", (err, origin) => { @@ -890,15 +884,9 @@ process.on("uncaughtExceptionMonitor", (err, origin) => { logger.error("Error:", err, origin); }); -// ── Session Reboot Recovery Hooks ─────────────────────────────────────────── +// ── Shutdown Hooks ────────────────────────────────────────────────────────── const saveAndExit = async () => { - logger.recovery("\n[Shutdown] Saving active sessions for reboot recovery..."); - try { - const state = remix.buildRecoveryState(); - remix.writeRecoveryState(state, "Shutdown"); - } catch (e) { - logger.error("[Shutdown] Failed to save recovery state:", e.message); - } + logger.recovery("\n[Shutdown] Cleaning up before exit..."); try { if (remix.dashboard?.redis?.destroy) { await remix.dashboard.redis.destroy(); diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index 9e9263b..053582a 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -15,7 +15,7 @@ import mysql from "mysql2"; export class GatewayHandler { /** * @param {import('../../index.mjs').Remix} remix The running bot instance. - * @param {import('./RecoveryManager.mjs').RecoveryManager} recoveryManager For scheduleSpawn / tryAutoJoin. + * @param {import('./RecoveryManager.mjs').RecoveryManager} recoveryManager For scheduleSpawn / 24/7 auto-join. */ constructor(remix, recoveryManager) { this.remix = remix; @@ -59,6 +59,28 @@ export class GatewayHandler { // where recovery rejoins → gateway disconnects again → recovery again. /** @type {Map} guildId → timestamp when cooldown expires */ this._gatewayDisconnectCooldown = new Map(); + + // ── Startup GuildDelete deferral ─────────────────────────────────────── + // Fluxer's GUILD_DELETE does NOT expose the `unavailable` flag, so we + // cannot distinguish "bot was kicked" from "guild is temporarily + // unavailable." During startup, the gateway sends GUILD_DELETE for + // guilds that went offline while the bot was down, followed immediately + // by GUILD_CREATE when they come back. If we process GuildDelete + // immediately, we wipe in-memory state (settings cache, player map, + // voice observations) for guilds the bot IS still in, then GuildCreate + // has to re-load everything from DB — wasting time and causing scary + // "bot removed from server" log messages for guilds that are fine. + // + // Solution: During a startup grace period, buffer GuildDelete events + // and only process them after the grace period expires. If a GuildCreate + // arrives for the same guild before the grace period ends, we cancel the + // deferred cleanup because the guild is still active. + /** @type {Map} guildId → deferred cleanup data */ + this._deferredGuildDeletes = new Map(); + /** @type {number} How long to defer GuildDelete processing during startup (ms) */ + this._startupDeleteGraceMs = 15_000; + /** @type {boolean} Whether we're still in the startup grace period */ + this._inStartupGrace = true; } // ── Voice-state key helpers ────────────────────────────────────────────────── @@ -578,6 +600,20 @@ export class GatewayHandler { const guildId = guild?.id ?? guild?._id; if (!guildId) return; + // ── Cancel any deferred GuildDelete for this guild ──────────────── + // If we got GuildDelete → GuildCreate for the same guild during the + // startup grace period, the guild was temporarily unavailable, not + // actually kicked. Cancel the deferred cleanup timer. + const deferred = this._deferredGuildDeletes.get(guildId); + if (deferred) { + clearTimeout(deferred.timer); + this._deferredGuildDeletes.delete(guildId); + logger.guild( + `[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` + + `guild came back (GuildCreate received during grace period).` + ); + } + // Part 1: Voice state population // Only purge stale entries if the GUILD_CREATE actually contains // voice_states data. If voice_states is empty, the guild may just @@ -608,7 +644,11 @@ export class GatewayHandler { } } - // Only purge entries for users that are being replaced by new data + // Only purge entries for users/bots that are being replaced by new data. + // Previously, ALL observedVoiceBots entries for the guild were deleted, + // which removed the bot's own entry that was set up during recovery. + // Now we only delete entries for bots whose user ID appears in the new + // voice_states data, matching the same logic used for observedVoiceUsers. for (const [uid, info] of [...remix.observedVoiceUsers]) { if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "") && newUserIds.has(uid)) { @@ -617,9 +657,13 @@ export class GatewayHandler { } for (const [uid, info] of [...remix.observedVoiceBots]) { if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) { - const botKey = uid; // observedVoiceBots keys are "guildId:userId" - // Check if this bot entry is for the current guild - remix.observedVoiceBots.delete(uid); + // Only delete if this bot's user ID appears in the new voice_states + // data — i.e., it's being replaced by fresh data. This prevents + // destroying the bot's own entry set up during recovery. + const botUserId = uid.split(":").pop(); // key is "guildId:userId" + if (botUserId && newUserIds.has(botUserId)) { + remix.observedVoiceBots.delete(uid); + } } } } @@ -706,7 +750,7 @@ export class GatewayHandler { logger.voice247( `[GuildCreate] Late-arriving guild ${guildId} — scheduling 24/7 spawn for channel ${chId} (mode ${mode})` ); - this.recoveryManager.scheduleSpawn(guildId, chId, this.T.rejoin247Delay, null, "guild-create-247"); + this.recoveryManager.scheduleSpawn(guildId, chId, this.T.rejoin247Delay, "guild-create-247"); } } } @@ -720,32 +764,35 @@ export class GatewayHandler { const guildId = guild?.id ?? guild?._id; if (!guildId) return; + // ── Startup deferral ────────────────────────────────────────────── + // During startup, the gateway may send GUILD_DELETE for guilds that + // are temporarily unavailable (not actually kicked). If we process + // these immediately, we wipe settings/players for guilds that will + // come back via GUILD_CREATE moments later. Defer cleanup during + // the startup grace period; if GuildCreate arrives first, cancel. + if (this._inStartupGrace) { + logger.guild( + `[GuildDelete] Deferring cleanup for server ${guildId} ` + + `(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).` + ); + // Cancel any existing deferred timer for this guild + const existing = this._deferredGuildDeletes.get(guildId); + if (existing) clearTimeout(existing.timer); + + const timer = setTimeout(() => { + this._deferredGuildDeletes.delete(guildId); + // Grace period expired without GuildCreate — this guild is really gone + logger.guild(`[GuildDelete] Confirmed removal from server ${guildId} — cleaning up.`); + this._processGuildDelete(guildId); + }, this._startupDeleteGraceMs); + + this._deferredGuildDeletes.set(guildId, { guild, timer }); + return; + } + + // ── Runtime (after startup grace) — process immediately ───────── logger.guild(`[GuildDelete] Removed from server ${guildId} — cleaning up.`); - - for (const [channelId, player] of remix.players.playerMap) { - if (!player._guildId || String(player._guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) { - remix.players.playerMap.delete(channelId); - try { player.leave().catch(() => {}); } catch (_) {} - try { player.destroy(); } catch (_) {} - logger.guild(`[GuildDelete] Destroyed player for channel ${channelId}.`); - } - } - - for (const [userId, info] of [...remix.observedVoiceUsers]) { - if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) remix.observedVoiceUsers.delete(userId); - } - for (const [userId, info] of [...remix.observedVoiceBots]) { - if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) remix.observedVoiceBots.delete(userId); - } - for (const [stateKey, info] of [...this._prevVoiceState]) { - if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) - this._prevVoiceState.delete(stateKey); - } - - remix.settingsMgr.removeServer(guildId); - remix._announcementChannelCache.delete(guildId); - - logger.guild(`[GuildDelete] Cleanup complete for server ${guildId}.`); + this._processGuildDelete(guildId); }); // ── VOICE_STATE_UPDATE ────────────────────────────────────────────────── @@ -1080,17 +1127,28 @@ export class GatewayHandler { // Also check if there was a recent bot join in this guild — if so, // the disconnect is likely a side-effect of the channel move, not a // real disconnect that needs recovery. + // IMPORTANT: We also verify that the bot is in another channel in + // THIS SAME guild. Cross-guild joins should NOT suppress recovery + // for this guild's disconnect — that was causing guilds to lose + // their 24/7 player silently when a different guild joined nearby. const recentJoin = this._recentBotJoins.get(cleanGuild) ?? 0; const timeSinceJoin = Date.now() - recentJoin; - const isLikelyMoveSideEffect = timeSinceJoin < this._moveDetectionWindow; + const isLikelyMoveSideEffect = timeSinceJoin < this._moveDetectionWindow && botInOtherChannel; // Also check if there are pending spawns for this guild — if a // spawnPlayer is in progress, the disconnect is expected. - const hasPendingSpawn = [...this.recoveryManager.pendingSpawns].some(([, entry]) => - String(entry.guildId).replace(/\D/g, "") === cleanGuild - ) || [...this.recoveryManager.scheduledSpawns].some(([, entry]) => - String(entry.guildId).replace(/\D/g, "") === cleanGuild - ); + // pendingSpawns is a Set (channel IDs), not a Map — we + // cross-reference with scheduledSpawns to check the guild. + const hasPendingSpawn = (() => { + for (const chId of this.recoveryManager.pendingSpawns) { + const entry = this.recoveryManager.scheduledSpawns.get(chId); + if (entry && String(entry.guildId).replace(/\D/g, "") === cleanGuild) return true; + } + for (const [, entry] of this.recoveryManager.scheduledSpawns) { + if (String(entry.guildId).replace(/\D/g, "") === cleanGuild) return true; + } + return false; + })(); // Check gateway disconnect cooldown — if the gateway recently // force-disconnected us, don't attempt recovery again immediately. @@ -1121,6 +1179,13 @@ export class GatewayHandler { ); } else { const set = remix.settingsMgr.getServer(guildId); + if (!set) { + logger.voice247( + `[247] Skipping recovery for ${cleanOld} in guild ${guildId} — ` + + `settings not loaded yet (race with GuildCreate).` + ); + return; + } const raw = set.get("stay_247"); if (raw && raw !== "none") { const channels = Array.isArray(raw) @@ -1130,6 +1195,20 @@ export class GatewayHandler { // Per-channel mode: check the mode for this specific channel const mode = get247ChannelMode(set, cleanOld); if (mode === "on" || mode === "auto") { + // Check persistent 401 ban — if this guild was recently + // 401-banned, don't attempt recovery (it will fail). + const banExpiry = this.recoveryManager._guild401Ban?.get(cleanGuild) ?? 0; + if (banExpiry > Date.now()) { + logger.voice247( + `[247] Skipping recovery for ${cleanOld} in guild ${guildId} — ` + + `guild is 401-banned (${Math.round((banExpiry - Date.now()) / 1000)}s remaining).` + ); + // Remove the old player entry and destroy it + remix.players.playerMap.delete(cleanOld); + try { remix.players.playerMap.get(cleanOld)?.destroy(); } catch (_) {} + return; + } + // Match the specific player by channel ID const player = remix.players.playerMap.get(cleanOld); if (player && !player.leaving) { @@ -1152,10 +1231,10 @@ export class GatewayHandler { } else { remix.players.playerMap.delete(cleanOld); try { player.destroy(); } catch (_) {} - this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, null, "gateway-disconnect"); + this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect"); } } else { - this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, null, "gateway-disconnect"); + this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect"); } } else { logger.voice247(`[247] Channel ${cleanOld} mode='${mode}' — not rejoining.`); @@ -1198,5 +1277,59 @@ export class GatewayHandler { this.recoveryManager.tryAutoJoin(); this.setupPresenceRotation(); + + // End the startup grace period after the configured delay. + // Any deferred GuildDelete events that weren't cancelled by a GuildCreate + // will be processed at this point. + setTimeout(() => { + this._inStartupGrace = false; + const pending = this._deferredGuildDeletes.size; + if (pending > 0) { + logger.guild( + `[GuildDelete] Startup grace period ended. ` + + `${pending} deferred deletion(s) will be processed by their timers.` + ); + } else { + logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`); + } + }, this._startupDeleteGraceMs); + } + + // ── GuildDelete cleanup (extracted for deferred processing) ──────────────── + + /** + * Perform the actual cleanup for a guild that the bot was removed from. + * Extracted from the GuildDelete handler so it can be called after the + * startup grace period expires. + * @param {string} guildId + */ + _processGuildDelete(guildId) { + const { remix } = this; + const cleanGuildId = String(guildId).replace(/\D/g, ""); + + for (const [channelId, player] of remix.players.playerMap) { + if (String(player._guildId ?? "").replace(/\D/g, "") === cleanGuildId) { + remix.players.playerMap.delete(channelId); + try { player.leave().catch(() => {}); } catch (_) {} + try { player.destroy(); } catch (_) {} + logger.guild(`[GuildDelete] Destroyed player for channel ${channelId}.`); + } + } + + for (const [userId, info] of [...remix.observedVoiceUsers]) { + if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceUsers.delete(userId); + } + for (const [userId, info] of [...remix.observedVoiceBots]) { + if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceBots.delete(userId); + } + for (const [stateKey, info] of [...this._prevVoiceState]) { + if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) + this._prevVoiceState.delete(stateKey); + } + + remix.settingsMgr.removeServer(guildId); + remix._announcementChannelCache.delete(guildId); + + logger.guild(`[GuildDelete] Cleanup complete for server ${guildId}.`); } } diff --git a/src/Player.mjs b/src/Player.mjs index 7fc5e3c..190a7a8 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -541,12 +541,10 @@ export default class Player extends EventEmitter { // keep retrying — 401 is a permission problem, not a transient failure. // Retrying just creates more 401 errors and recovery loops. // Instead, give up on recovery and let the 24/7 system schedule a - // delayed respawn with proper cooldown. + // delayed respawn. if (this._lastDisconnectReason === "401") { const timeSinceDisconnect = Date.now() - this._lastDisconnectTime; if (timeSinceDisconnect < 60_000) { - // Within 60 seconds of a 401 — don't attempt recovery. - // Let the 24/7 system handle reconnection with its own delay. logger.warn( `[Player] Skipping recovery for guild ${this._guildId} — ` + `last disconnect was 401 Unauthorized (${timeSinceDisconnect / 1000}s ago). ` + diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 5d9cf18..ee95295 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -113,7 +113,7 @@ export class PlayerManager { this.playerConfig = config.player; this.dashboard = config.dashboard ?? null; this.locale = config.locale ?? null; - this.spawnPlayer = config.spawnPlayer ?? null; // RecoveryManager.spawnPlayer — for 24/7 rejoin on autoleave + this.spawnPlayer = config.spawnPlayer ?? null; // RecoveryManager.spawnPlayer — for 24/7 rejoin this.timers = config.timers ?? {}; this._lastfm = null; // Set later by Remix class after init } @@ -760,7 +760,7 @@ export class PlayerManager { if (this.spawnPlayer) { logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} (mode ${mode247}) in ${delay}ms`); setTimeout(() => { - this.spawnPlayer(guildId, homeChannelId, 0, null, "initplayer-autoleave").catch(e => + this.spawnPlayer(guildId, homeChannelId).catch(e => logger.warn("[AutoLeave] 24/7 rejoin failed for", homeChannelId, e.message) ); }, delay); diff --git a/src/RecoveryManager.mjs b/src/RecoveryManager.mjs index 0ef5f51..665e385 100644 --- a/src/RecoveryManager.mjs +++ b/src/RecoveryManager.mjs @@ -1,4 +1,3 @@ -import * as fs from "fs"; import { logger } from "./constants/Logger.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "./MessageHandler.mjs"; @@ -6,10 +5,17 @@ import Player from "./Player.mjs"; import { get247ChannelMode } from "./constants/Helpers247.mjs"; /** - * RecoveryManager — handles session persistence, boot recovery, 24/7 auto-join, - * and player spawning with concurrency control. + * RecoveryManager — handles 24/7 auto-join on boot and player spawning. * - * Extracted from index.mjs to reduce the Remix constructor footprint. + * The boot-time recovery system (session persistence via recovery.json) has + * been removed. On restart the bot starts clean; only 24/7 channels configured + * in each guild's settings are automatically rejoined. + * + * This module still provides: + * - spawnPlayer() — create a Player, join a voice channel (used by 24/7) + * - scheduleSpawn() — delayed player spawn (used by 24/7 autoleave rejoin) + * - cleanStaleGuild() — purge all state for a guild the bot left + * - tryAutoJoin() — auto-join 24/7 channels when bot + settings are ready */ export class RecoveryManager { /** @@ -21,50 +27,38 @@ export class RecoveryManager { // ── Timers derived from config ──────────────────────────────────────────── const timers = remix.config.timers ?? {}; this.T = { - aloneCheckInterval: timers.aloneCheckInterval ?? 30_000, - aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, - rejoin247Delay: timers.rejoin247Delay ?? 3_000, - recoveryStaggerMs: timers.recoveryStaggerMs ?? 3_000, - recoveryConcurrency: timers.recoveryConcurrency ?? 2, + aloneCheckInterval: timers.aloneCheckInterval ?? 30_000, + aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, + rejoin247Delay: timers.rejoin247Delay ?? 3_000, }; // ── Internal state ──────────────────────────────────────────────────────── /** @type {Set} Per-channel spawn mutex */ this.pendingSpawns = new Set(); - /** @type {Map} Scheduled delayed spawns */ + /** @type {Map} Scheduled delayed spawns */ this.scheduledSpawns = new Map(); - /** @type {string} Path to the recovery JSON file */ - this.recoveryPath = "./storage/recovery.json"; - /** @type {number} Maximum transient retry attempts per channel before giving up */ - this.maxTransientRetries = remix.config.timers?.maxTransientRetries ?? 5; - /** @type {number} Base delay multiplier for exponential backoff (ms) */ - this.retryBaseDelay = remix.config.timers?.retryBaseDelay ?? 15_000; - /** @type {Map} Per-guild 401 failure count for circuit breaker */ - this._guild401Count = new Map(); - /** @type {number} Max 401 failures per guild before circuit breaker trips */ - this._guild401Max = 2; // ── Ready flags ─────────────────────────────────────────────────────────── this.botReady = false; this.settingsReady = false; // ── Auto-join guard ─────────────────────────────────────────────────────── - // Prevents concurrent tryAutoJoin() calls. Both settings "ready" and - // Events.Ready can trigger tryAutoJoin(); without this guard, two calls - // could overlap and attempt to spawn duplicate players. this._autoJoinRunning = false; this._autoJoinDone = false; + // ── 401 error tracking ────────────────────────────────────────────────────── + /** @type {Map} Guild ID → timestamp when 401 ban expires. + * After 3 consecutive 401s, the guild is banned from further retries for + * 5 minutes to avoid infinite retry loops. */ + this._guild401Ban = new Map(); + /** @type {Map} Guild ID → consecutive 401 retry count. + * Used for exponential backoff: 1st retry after 15s, 2nd after 45s, 3rd = ban. */ + this._guild401Retries = new Map(); + // ── Expose convenience methods on the Remix instance ────────────────────── - // These are referenced by the shutdown hooks and dashboard. - remix._buildRecoveryState = () => this.buildRecoveryState(); - remix._writeRecoveryState = (state, label) => this.writeRecoveryState(state, label); remix._spawnPlayer = this.spawnPlayer.bind(this); // ── GatewayHandler reference (set after construction) ──────────────────── - // RecoveryManager is created before GatewayHandler, so we can't pass it - // in the constructor. Instead, index.mjs sets this reference after both - // objects are constructed. this.gatewayHandler = null; } @@ -74,126 +68,8 @@ export class RecoveryManager { return String(value ?? "").replace(/\D/g, ""); } - cloneRecoveryTrack(track) { - try { return JSON.parse(JSON.stringify(track)); } catch { return track; } - } - - // ── Recovery state persistence ─────────────────────────────────────────────── - - buildRecoveryState() { - const sessions = []; - const seen = new Set(); - const { remix } = this; - - for (const [channelKey, player] of remix.players.playerMap.entries()) { - try { - if (!player || player._destroyed || player.leaving) continue; - - const guildId = this.normalizeChannelId(player._guildId); - const channelId = this.normalizeChannelId(player._channelId ?? channelKey); - if (!guildId || !channelId) continue; - - // ── Save ALL active sessions including 24/7 ────────────────────── - // Previously, 24/7 channels were skipped because tryAutoJoin() - // handles reconnection on boot. However, this meant queue data - // (current track, queue, loop state) was lost on restart. - // Now we save 24/7 channels too, with their mode stored in the - // recovery data so tryAutoJoin() can restore both the connection - // and the music state. - - const dedupeKey = `${guildId}:${channelId}`; - if (seen.has(dedupeKey)) continue; - seen.add(dedupeKey); - - // Determine if this is a 24/7 channel and get its per-channel mode - let is247 = false; - let mode247 = null; - try { - const set = remix.settingsMgr.getServer(guildId); - if (set) { - const raw247 = set.get("stay_247"); - if (raw247 && raw247 !== "none") { - const homeChannel = this.normalizeChannelId(player._home247Channel) || channelId; - const channels247 = Array.isArray(raw247) - ? raw247.map(id => this.normalizeChannelId(id)).filter(Boolean) - : [this.normalizeChannelId(raw247)].filter(Boolean); - if (channels247.includes(channelId) || channels247.includes(homeChannel)) { - is247 = true; - mode247 = get247ChannelMode(set, homeChannel || channelId); - } - } - } - } catch (_) {} - - const current = player.queue.getCurrent(); - const queueData = player.queue.getQueue(); - const tracksToSave = []; - if (current) tracksToSave.push(this.cloneRecoveryTrack(current)); - for (const track of queueData) tracksToSave.push(this.cloneRecoveryTrack(track)); - - sessions.push({ - guildId, - channelId, - home247ChannelId: this.normalizeChannelId(player._home247Channel) || channelId, - textChannelId: player.textChannel?.id ?? player.textChannel?._id ?? null, - queue: tracksToSave, - loopQueue: !!player.queue.loop, - loopSong: !!player.queue.songLoop, - preferredVolume: player.preferredVolume ?? 1, - is247, - mode247, // "on" | "auto" | null - savedAt: Date.now(), - }); - } catch (e) { - logger.warn(`[Recovery] Failed to serialize session for channel ${channelKey}:`, e?.message ?? e); - } - } - - return sessions; - } - - writeRecoveryState(state, sourceLabel) { - if (!Array.isArray(state) || state.length === 0) { - logger.recovery(`[${sourceLabel}] No active sessions to save.`); - return false; - } - - const tmpPath = `${this.recoveryPath}.tmp`; - fs.writeFileSync(tmpPath, JSON.stringify(state, null, 2)); - fs.renameSync(tmpPath, this.recoveryPath); - logger.recovery(`[${sourceLabel}] Saved ${state.length} active session(s) to ${this.recoveryPath}`); - return true; - } - - normalizeRecoverySessions(rawSessions) { - if (!Array.isArray(rawSessions)) return []; - - const deduped = new Map(); - for (const session of rawSessions) { - const guildId = this.normalizeChannelId(session?.guildId); - const channelId = this.normalizeChannelId(session?.channelId ?? session?.home247ChannelId); - if (!guildId || !channelId) continue; - - deduped.set(`${guildId}:${channelId}`, { - ...session, - guildId, - channelId, - home247ChannelId: this.normalizeChannelId(session?.home247ChannelId) || channelId, - queue: Array.isArray(session?.queue) - ? session.queue.filter(t => t && (t.encoded || t.uri || t.url)) - : [], - loopQueue: !!session?.loopQueue, - loopSong: !!session?.loopSong, - }); - } - - return [...deduped.values()]; - } - /** * Clean up all state for a guild the bot is no longer a member of. - * Mirrors the GUILD_DELETE handler in GatewayHandler so that servers - * kicked while offline are fully purged on the next boot. * * @param {string} guildId * @param {string} [reason="bot no longer in guild"] @@ -201,11 +77,11 @@ export class RecoveryManager { cleanStaleGuild(guildId, reason = "bot no longer in guild") { const { remix } = this; const cleanId = String(guildId).replace(/\D/g, ""); - logger.recovery(`[Recovery] Cleaning stale guild ${cleanId} (${reason}).`); + logger.recovery(`[SpawnManager] Cleaning stale guild ${cleanId} (${reason}).`); // Destroy any active players for this guild for (const [channelId, player] of remix.players.playerMap) { - if (!player._guildId || String(player._guildId).replace(/\D/g, "") === cleanId) { + if (String(player._guildId ?? "").replace(/\D/g, "") === cleanId) { remix.players.playerMap.delete(channelId); try { player.leave().catch(() => {}); } catch (_) {} try { player.destroy(); } catch (_) {} @@ -242,51 +118,34 @@ export class RecoveryManager { * @param {string} guildId * @param {string} channelId * @param {number} [delayMs=0] - * @param {Object|null} [recoveryData=null] * @param {string} [reason="spawn"] - * @param {number} [retryCount=0] Current retry attempt number (0 = first try). */ - scheduleSpawn(guildId, channelId, delayMs = 0, recoveryData = null, reason = "spawn", retryCount = 0) { + scheduleSpawn(guildId, channelId, delayMs = 0, reason = "spawn") { const cleanChannelId = this.normalizeChannelId(channelId); if (!cleanChannelId) return; const existing = this.scheduledSpawns.get(cleanChannelId); if (existing) clearTimeout(existing.timer); - // Capture retryCount in the closure BEFORE the entry is deleted, - // so spawnPlayer receives the correct count for exponential backoff. - const capturedRetryCount = retryCount; const timer = setTimeout(() => { this.scheduledSpawns.delete(cleanChannelId); - this.spawnPlayer(guildId, cleanChannelId, 0, recoveryData, capturedRetryCount).catch(e => { + this.spawnPlayer(guildId, cleanChannelId).catch(e => { logger.warn(`[PlayerSpawn] Scheduled ${reason} failed for ${cleanChannelId}:`, e?.message ?? e); }); }, Math.max(0, delayMs)); - this.scheduledSpawns.set(cleanChannelId, { timer, guildId, recoveryData, reason, retryCount }); - } - - /** - * Calculate the exponential backoff delay for a given retry attempt. - * Delay doubles each attempt: base, base*2, base*4, base*8, … - * Capped at 5 minutes to avoid excessive waits. - */ - getRetryDelay(retryCount) { - const delay = this.retryBaseDelay * Math.pow(2, retryCount); - return Math.min(delay, 300_000); // cap at 5 minutes + this.scheduledSpawns.set(cleanChannelId, { timer, guildId, reason }); } // ── Player spawning ────────────────────────────────────────────────────────── /** - * Create a new Player, join the target voice channel, and optionally restore - * recovery state. + * Create a new Player and join the target voice channel. + * Used primarily for 24/7 auto-join (boot + autoleave rejoin). */ - async spawnPlayer(guildId, channelId, delayMs = 0, recoveryData = null, retryCount = 0) { + async spawnPlayer(guildId, channelId) { const { remix } = this; - if (delayMs > 0) await new Promise(r => setTimeout(r, delayMs)); - const cleanChannelId = this.normalizeChannelId(channelId); if (!cleanChannelId) return; @@ -297,60 +156,71 @@ export class RecoveryManager { this.scheduledSpawns.delete(cleanChannelId); } - // Use the passed-in retryCount (from scheduleSpawn's closure) rather - // than reading from the now-deleted scheduledSpawns entry. + const cleanGuildId = String(guildId).replace(/\D/g, ""); - // Only enforce 24/7 check if we are NOT recovering from a reboot - if (!recoveryData) { - // Try the guildId as-is first, then the cleaned version. - // The settingsMgr Map key might differ from the guildId format - // passed in (e.g. string vs number, or cleaned vs raw). - let set = remix.settingsMgr.getServer(guildId); - let raw = set.get("stay_247"); - if ((!raw || raw === "none") && String(guildId).replace(/\D/g, "") !== String(guildId)) { - const cleanGId = String(guildId).replace(/\D/g, ""); - set = remix.settingsMgr.getServer(cleanGId); - raw = set.get("stay_247"); - } - if (!raw || raw === "none") { - // Diagnostic: log why we're skipping + // ── Pre-flight: verify bot is still in the guild ───────────────────── + // During startup, the guild cache may not be populated yet because + // GuildCreate events haven't arrived. In that case, DON'T call + // cleanStaleGuild — it would nuke the in-memory settings cache for a + // guild the bot IS still in, causing unnecessary churn and scary log + // messages. The GuildCreate handler will schedule the 24/7 spawn for + // late-arriving guilds. cleanStaleGuild is only appropriate when we + // know for sure the bot was kicked (i.e. a GuildDelete was received). + if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGuildId)) { + if (this._autoJoinRunning || !this._autoJoinDone) { + // Startup phase — guild cache not populated yet, just skip logger.recovery( - `[PlayerSpawn] Skipping 24/7 channel ${cleanChannelId} in guild ${guildId}: ` + - `stay_247=${JSON.stringify(raw)}. ` + - `SettingsMgr has this guild: ${remix.settingsMgr.guilds.has(guildId)}` + `[PlayerSpawn] Skipping channel ${cleanChannelId} in guild ${cleanGuildId} — ` + + `guild cache not populated yet (startup race). GuildCreate will schedule spawn.` ); - return; + } else { + // Runtime — bot was actually removed from the guild + logger.recovery( + `[PlayerSpawn] Skipping channel ${cleanChannelId} in guild ${cleanGuildId} — ` + + `bot is no longer in this guild.` + ); + this.cleanStaleGuild(guildId, "bot removed before spawn attempt"); } + return; + } - const channels = Array.isArray(raw) - ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)) - : new Set([String(raw).replace(/\D/g, "")]); - if (!channels.has(cleanChannelId)) { - logger.recovery( - `[PlayerSpawn] Skipping channel ${cleanChannelId}: not in stay_247 list [${[...channels].join(", ")}]` - ); - return; - } + // ── 24/7 check ────────────────────────────────────────────────────── + // Only spawn if this channel is in the stay_247 list. + let set = remix.settingsMgr.getServer(guildId); + let raw = set?.get("stay_247"); + if ((!raw || raw === "none") && String(guildId).replace(/\D/g, "") !== String(guildId)) { + const cleanGId = String(guildId).replace(/\D/g, ""); + set = remix.settingsMgr.getServer(cleanGId); + raw = set?.get("stay_247"); + } + if (!raw || raw === "none") { + logger.recovery( + `[PlayerSpawn] Skipping channel ${cleanChannelId} in guild ${guildId}: ` + + `stay_247=${JSON.stringify(raw)}.` + ); + return; + } + + const channels = Array.isArray(raw) + ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)) + : new Set([String(raw).replace(/\D/g, "")]); + if (!channels.has(cleanChannelId)) { + logger.recovery( + `[PlayerSpawn] Skipping channel ${cleanChannelId}: not in stay_247 list [${[...channels].join(", ")}]` + ); + return; } // Atomic mutex check — blocks concurrent spawns for the same channel. if (remix.players.playerMap.has(cleanChannelId) || this.pendingSpawns.has(cleanChannelId)) return; - + // ── Duplicate player cleanup for same guild ────────────────────────── - // If there's already a player for a different channel in this guild - // that has the SAME _channelId (e.g. due to a stale playerMap entry - // from a previous failed recovery), clean it up before spawning. - // This prevents the "multiple players per guild" conflict that causes - // "skipped re-key" and gateway force-disconnects. - const cleanGuildId = String(guildId).replace(/\D/g, ""); for (const [mapKey, existingPlayer] of remix.players.playerMap) { if (existingPlayer._destroyed || existingPlayer.leaving) { remix.players.playerMap.delete(mapKey); try { existingPlayer.destroy(); } catch (_) {} continue; } - // Check if an existing player in this guild has the same channel ID - // as the one we're about to spawn (stale state from a move/recovery) const existingChannelId = String(existingPlayer._channelId ?? mapKey).replace(/\D/g, ""); const existingGuildId = String(existingPlayer._guildId ?? "").replace(/\D/g, ""); if (existingGuildId === cleanGuildId && existingChannelId === cleanChannelId) { @@ -363,7 +233,7 @@ export class RecoveryManager { try { existingPlayer.destroy(); } catch (_) {} } } - + this.pendingSpawns.add(cleanChannelId); try { @@ -415,7 +285,7 @@ export class RecoveryManager { p.destroy(); if (matchChannel && (mode2 === "on" || mode2 === "auto")) { - this.scheduleSpawn(guildId, homeChannelId, this.T.rejoin247Delay, null, "247-autoleave"); + this.scheduleSpawn(guildId, homeChannelId, this.T.rejoin247Delay, "247-autoleave"); } else { // 24/7 is off — send inactivity message with hint to enable 247 try { @@ -431,7 +301,7 @@ export class RecoveryManager { .setDescription( `Left channel <#${activeChannelId}> because of inactivity.\n` + `If you want me to stay in voice, use \`${prefix}247 on\` or \`${prefix}247 auto\`\n` + - `💡 Use \`${prefix}247\` to view and manage all saved channels.` + `Use \`${prefix}247\` to view and manage all saved channels.` ) .toJSON(); if (typeof ch?.send === "function") ch.send({ embeds: [embed] }).catch(() => {}); @@ -472,8 +342,6 @@ export class RecoveryManager { }); // ── Join channel ─────────────────────────────────────────────────────── - // NOTE: playerMap.set happens AFTER join() succeeds so that other code - // (alone-check, voice state handlers) never sees a non-connected player. try { await p.join(cleanChannelId); @@ -484,20 +352,13 @@ export class RecoveryManager { p._home247Channel = cleanChannelId; // ── Re-seed voice states for this channel ──────────────────────────── - // After joining, the bot needs to know who's already in the channel. - // The initial seedVoiceStatesFromGuilds() may have missed users because - // sends voice states during GUILD_CREATE before the bot processes them. - // This re-reads the guild's voice_states cache and updates the - // observedVoiceUsers map so the bot detects humans already present. try { const humansFound = this.gatewayHandler.reseedVoiceStatesForChannel(guildId, cleanChannelId); if (humansFound > 0) { logger.recovery( - `[Recovery] Re-seeded voice states for ${cleanChannelId}: ` + + `[Spawn] Re-seeded voice states for ${cleanChannelId}: ` + `${humansFound} human(s) already present — cancelling inactivity timer.` ); - // Humans are present — stop any inactivity timer that Player.join() - // may have started (it starts one if the queue is empty). if (typeof p._stopInactivityTimer === "function") { p._stopInactivityTimer(); } @@ -506,148 +367,88 @@ export class RecoveryManager { logger.warn("[PlayerSpawn] Voice state reseed failed:", reseedErr?.message); } - // ── Restore recovery state ─────────────────────────────────────────── - if (recoveryData) { - if (recoveryData.textChannelId) { - p.textChannel = remix.client.channels.get(recoveryData.textChannelId); - } - if (recoveryData.home247ChannelId) { - p._home247Channel = this.normalizeChannelId(recoveryData.home247ChannelId) || cleanChannelId; - } - if (recoveryData.loopQueue) p.queue.setLoop(true); - if (recoveryData.loopSong) p.queue.setSongLoop(true); - if (typeof recoveryData.preferredVolume === "number") { - p.preferredVolume = recoveryData.preferredVolume; + // ── Restore saved volume from guild settings ───────────────────────── + try { + const savedVol = remix.settingsMgr.getServer(guildId)?.get("volume"); + if (savedVol !== undefined && savedVol !== null) { + const vol = Number(savedVol); + if (!isNaN(vol)) p.preferredVolume = vol / 100; } + } catch (_) {} - if (recoveryData.queue && recoveryData.queue.length > 0) { - p.queue.addMany(recoveryData.queue); + logger.recovery(`[Spawn] Joined 24/7 channel ${cleanChannelId} in guild ${cleanGuildId}.`); - const startPlayback = () => p.playNext().catch(e => - logger.warn("[Recovery] playNext failed:", e?.message) - ); - - if (remix.moonlink?._sessionId || remix.moonlink?.sessionId) { - startPlayback(); - } else if (remix.moonlink) { - remix.moonlink.once("ready", () => startPlayback()); - } else { - startPlayback(); - } - } - logger.recovery(`[Recovery] Restored session in ${cleanChannelId} (${recoveryData.queue?.length ?? 0} track(s)).`); - } + // Join succeeded — clear any 401 retry counters for this guild + this._guild401Retries.delete(cleanGuildId); + this._guild401Ban.delete(cleanGuildId); } catch (e) { remix.players.playerMap.delete(cleanChannelId); try { p.destroy(); } catch (_) {} logger.warn("[PlayerSpawn] Failed to join channel", cleanChannelId, "guild", guildId, e.message); - // ── Guild membership check for 401 errors ─────────────────────────── - // If the bot was kicked while offline (or between retries), the 401 will - // keep repeating. Verify the bot is still in the guild — if not, clean - // up all state and skip retries entirely. - // ── 401 Unauthorized handling with circuit breaker ───────────────── - if (e.message?.includes("401 Unauthorized")) { - const cleanGId = String(guildId).replace(/\D/g, ""); - - // Bot no longer in guild → clean up entirely - if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGId)) { + // ── 401 Unauthorized handling ───────────────────────────────────── + const is401Error = /\b401\b/.test(e.message) || + e.message?.includes("Unauthorized") || + e.message?.includes("no permissions to access the room") || + e.message?.includes("signal failure: client error"); + + if (is401Error) { + // Bot not in guild cache — but during startup, the cache might not + // be populated yet. Same race as the pre-flight check. + if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGuildId)) { + if (this._autoJoinRunning || !this._autoJoinDone) { + logger.warn( + `[PlayerSpawn] 401 on guild ${guildId} — guild cache not populated yet (startup race). Will retry.` + ); + // Schedule a retry — don't clean up + const retryCount = (this._guild401Retries.get(cleanGuildId) ?? 0) + 1; + this._guild401Retries.set(cleanGuildId, retryCount); + if (retryCount < 3) { + this.scheduleSpawn(guildId, cleanChannelId, 15_000, `401-startup-retry-${retryCount}`); + } + return; + } + // Runtime — bot was actually removed logger.warn( - `[PlayerSpawn] 401 on guild ${guildId} — bot no longer in server. ` + - `Cleaning up and skipping retries.` + `[PlayerSpawn] 401 on guild ${guildId} — bot no longer in server. Cleaning up.` ); this.cleanStaleGuild(guildId, "401 and bot not in guild"); return; } - // Guild-level circuit breaker: if this guild has hit the 401 threshold, - // stop retrying all channels in it during this recovery cycle. - const prev401 = this._guild401Count.get(cleanGId) ?? 0; - const new401 = prev401 + 1; - this._guild401Count.set(cleanGId, new401); + // Bot IS still in the guild — the 401 may be transient (gateway slow + // to provision voice room). Retry with exponential backoff instead of + // permanently giving up on the first failure. + const retryCount = (this._guild401Retries.get(cleanGuildId) ?? 0) + 1; + this._guild401Retries.set(cleanGuildId, retryCount); - if (new401 >= this._guild401Max) { + if (retryCount >= 3) { + // After 3 consecutive 401s, ban this guild for 5 minutes to avoid + // infinite retry loops. The FluxerRevoice 45s cooldown + this ban + // prevent wasting resources on guilds where voice is truly broken. + const banDuration = 5 * 60 * 1000; // 5 minutes + this._guild401Ban.set(cleanGuildId, Date.now() + banDuration); + this._guild401Retries.delete(cleanGuildId); logger.warn( - `[PlayerSpawn] 401 circuit breaker tripped for guild ${cleanGId} ` + - `(${new401} failures ≥ ${this._guild401Max}). Skipping all further ` + - `retries for this guild in the current recovery cycle.` + `[PlayerSpawn] 401 for guild ${cleanGuildId} — ` + + `${retryCount} consecutive failures. Banning for 5 minutes.` ); - // Cancel any other scheduled spawns for this guild - for (const [chId, entry] of this.scheduledSpawns) { - if (String(entry.guildId).replace(/\D/g, "") === cleanGId) { - clearTimeout(entry.timer); - this.scheduledSpawns.delete(chId); - logger.warn(`[PlayerSpawn] Circuit breaker cancelled spawn for channel ${chId}`); - } - } return; } - // First 401 in guild — log with context but don't retry - // (401 is permission-based, retrying immediately won't help) + // Exponential backoff: 1st retry after 15s, 2nd after 45s + const backoffMs = retryCount === 1 ? 15_000 : 45_000; logger.warn( - `[PlayerSpawn] 401 Unauthorized for channel ${cleanChannelId} in guild ${cleanGId} ` + - `(${new401}/${this._guild401Max} before circuit breaker). ` + - `Bot is still in guild — permissions may have been revoked. ` + - `Skipping retry (401 is persistent, not transient).` + `[PlayerSpawn] 401 for guild ${cleanGuildId} — ` + + `transient? Retry ${retryCount}/3 in ${backoffMs / 1000}s.` ); + this.scheduleSpawn(guildId, cleanChannelId, backoffMs, `401-retry-${retryCount}`); return; } - // Retry if the failure is a transient LiveKit race (with max retries + backoff) - // IMPORTANT: 401 Unauthorized is NOT transient — it's a permission error - // that will keep failing. It's already handled above with the circuit - // breaker. The "signal failure" pattern is excluded here because it - // includes 401 errors (e.g. "engine: signal failure: client error: 401 - // Unauthorized") — retrying those just creates more 401 errors. - const isTransient = (e.message?.includes("engine is closed") || - e.message?.includes("MediaPlayer after retry") || - e.message?.includes("LiveKit connection timeout") || - e.message?.includes("LiveKit failed") || - e.message?.includes("No room available")) && - !e.message?.includes("401") && - !e.message?.includes("Unauthorized"); - - // Use the retryCount passed into spawnPlayer from scheduleSpawn's closure. - const prevRetryCount = retryCount; - - // Determine if this channel should be retried. - // A channel is retry-eligible if: - // 1. It has recovery data (boot recovery session) — always retry. - // 2. It was a 24/7 auto-join — retry if 24/7 is still enabled. - // 3. Fallback: if the guild still exists, give at least 1 retry - // even when settings lookup fails (handles the race where the bot - // was in the guild when the join list was built but settings cache - // is momentarily unavailable). - const isRetryEligible = (() => { - if (recoveryData) return true; // boot recovery — always retry - try { - const raw = remix.settingsMgr.getServer(guildId)?.get("stay_247"); - if (raw && raw !== "none") return true; // 24/7 enabled - } catch (_) {} - // Fallback: if the bot is still in the guild, the channel is likely - // a legitimate 24/7 or recovery channel — give it at least 1 retry. - // This fixes the "Giving up after 0 retries" bug that occurs when - // settingsMgr.getServer returns null during transient failures. - if (prevRetryCount === 0 && remix.client.guilds.has(guildId)) return true; - return false; - })(); - - const shouldRetry = isTransient && prevRetryCount < this.maxTransientRetries && isRetryEligible; - if (shouldRetry) { - const nextRetry = prevRetryCount + 1; - const retryDelay = this.getRetryDelay(prevRetryCount); - logger.warn( - `[PlayerSpawn] Transient join failure — retry ${nextRetry}/${this.maxTransientRetries} ` + - `in ${retryDelay}ms (channel=${cleanChannelId})` - ); - this.scheduleSpawn(guildId, cleanChannelId, retryDelay, recoveryData ?? null, "transient-join-retry", nextRetry); - } else if (isTransient) { - logger.error( - `[PlayerSpawn] Giving up on channel ${cleanChannelId} after ${prevRetryCount} retry(es). ` + - `Last error: ${e.message}` - ); - } + // Non-401 error — clear the 401 retry counter for this guild since + // this was a different kind of failure. + this._guild401Retries.delete(cleanGuildId); } return p; @@ -657,226 +458,56 @@ export class RecoveryManager { } } - // ── Concurrency utility ────────────────────────────────────────────────────── - - /** - * Run async tasks with bounded concurrency and staggered dispatch. - * - * Guarantees: - * - At most `concurrency` tasks in-flight at any time. - * - Minimum `staggerMs` gap between dispatching two consecutive tasks. - * - When a task finishes and a slot opens, the next dispatch happens - * after the remaining stagger time elapses (not immediately). - * - * @param {Array} items - * @param {number} concurrency - * @param {number} staggerMs - * @param {(item) => Promise} fn - */ - runWithConcurrency(items, concurrency, staggerMs, fn) { - const errors = []; - let idx = 0; - let active = 0; - let lastDispatchTime = -Infinity; - let dispatchTimer = null; - const total = items.length; - - if (total === 0) return Promise.resolve(errors); - - return new Promise((resolve) => { - const tryDispatch = () => { - if (dispatchTimer) { clearTimeout(dispatchTimer); dispatchTimer = null; } - - while (active < concurrency && idx < total) { - const now = Date.now(); - const elapsed = now - lastDispatchTime; - - if (elapsed < staggerMs) { - dispatchTimer = setTimeout(tryDispatch, staggerMs - elapsed); - return; - } - - const item = items[idx++]; - lastDispatchTime = Date.now(); - active++; - - fn(item) - .catch((e) => errors.push({ ...item, error: e.message })) - .finally(() => { - active--; - tryDispatch(); - }); - } - - if (idx >= total && active === 0) resolve(errors); - }; - - tryDispatch(); - }); - } - - // ── Auto-join on boot ──────────────────────────────────────────────────────── + // ── Auto-join on boot (24/7 only) ──────────────────────────────────────────── /** * Called when both `botReady` and `settingsReady` are true. - * Restores recovery sessions and auto-joins 24/7 channels. + * Auto-joins all 24/7 channels based on current guild settings. + * No session persistence or recovery from previous boot. */ async tryAutoJoin() { if (!this.botReady || !this.settingsReady) return; - if (this._autoJoinDone || this._autoJoinRunning) return; + if (this._autoJoinRunning || this._autoJoinDone) return; this._autoJoinRunning = true; + const { remix } = this; - - await new Promise(r => setTimeout(r, 2000)); - - // Build a unified join list: recovery sessions + 24/7 channels const joinList = []; - // 1. Recover standard reboot sessions - let recoveryFileExisted = false; - if (fs.existsSync(this.recoveryPath)) { - logger.recovery("[Recovery] Found previous session data, restoring..."); - recoveryFileExisted = true; - let data = null; - try { - data = JSON.parse(fs.readFileSync(this.recoveryPath, "utf8")); - } catch (e) { - logger.error("[Recovery] Failed to read/parse recovery file:", e); - } - // NOTE: File is deleted AFTER all spawns complete (see below). - // This prevents data loss if the process crashes mid-recovery. - const sessions = this.normalizeRecoverySessions(data); - for (const session of sessions) { - joinList.push({ - guildId: session.guildId, - channelId: session.channelId, - recoveryData: session, - }); - } - } - - // 2. Collect 24/7 channels (skip channels already covered by recovery) - const recoveryChannels = new Set(joinList.map(j => j.channelId)); + // Collect all 24/7 channels from loaded guild settings for (const [guildId, serverSettings] of remix.settingsMgr.guilds) { - const raw = serverSettings.get("stay_247"); - if (!raw || raw === "none") continue; + try { + const raw = serverSettings.get("stay_247"); + if (!raw || raw === "none") continue; - const channelIds = Array.isArray(raw) - ? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean) - : [String(raw).replace(/\D/g, "")].filter(Boolean); + const channels = Array.isArray(raw) + ? raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15) + : [String(raw).replace(/\D/g, "")].filter(id => id.length >= 15); - for (const channelId of channelIds) { - const clean = String(channelId).replace(/\D/g, ""); - // Per-channel mode: only join if this specific channel is on/auto - const mode = get247ChannelMode(serverSettings, clean); - if (mode !== "auto" && mode !== "on") continue; - - if (clean && !recoveryChannels.has(clean)) { - joinList.push({ guildId, channelId: clean, recoveryData: null }); - logger.recovery( - `[Recovery] Added 24/7 channel ${clean} (guild ${guildId}, mode ${mode}) to join list` - ); + for (const chId of channels) { + const mode = get247ChannelMode(serverSettings, chId); + if (mode !== "on" && mode !== "auto") continue; + if (!remix.players.playerMap.has(chId) && !this.pendingSpawns.has(chId)) { + joinList.push({ guildId, channelId: chId }); + } } - } + } catch (_) {} } logger.recovery( - `[Recovery] Join list built: ${joinList.length} channel(s) ` + - `(${joinList.filter(j => j.recoveryData).length} recovery, ` + - `${joinList.filter(j => !j.recoveryData).length} 24/7)` + `[AutoJoin] Found ${joinList.length} 24/7 channel(s) to join.` ); - // ── Filter out guilds the bot is no longer a member of ──────────────── - const filteredList = []; - for (const item of joinList) { - // Try both the raw guildId and the cleaned (digits-only) version. - // The settings Map might use a different format than client.guilds - // (e.g. string vs number, or with/without non-digit chars). - const cleanGId = String(item.guildId).replace(/\D/g, ""); - const hasRaw = remix.client.guilds.has(item.guildId); - const hasClean = cleanGId && cleanGId !== String(item.guildId) && remix.client.guilds.has(cleanGId); - - if (!hasRaw && !hasClean) { - logger.recovery( - `[Recovery] Skipping guild ${item.guildId} channel ${item.channelId} — bot is no longer in the server. ` + - `(hasRaw=${hasRaw}, hasClean=${hasClean}, cleanGId=${cleanGId}, ` + - `clientGuildsSample=[${[...remix.client.guilds.keys()].slice(0, 3).join(", ")}])` - ); - this.cleanStaleGuild(item.guildId); - } else { - if (hasClean && !hasRaw) { - item.guildId = cleanGId; - } - filteredList.push(item); - } + // Schedule all 24/7 spawns immediately (no stagger). The FluxerRevoice + // global join queue handles serialization — only one join is in-flight + // at a time across all guilds, with a 3s gap between each. Staggering + // here is no longer needed and just adds unnecessary delay before the + // joins start queuing. + for (let i = 0; i < joinList.length; i++) { + const { guildId, channelId } = joinList[i]; + this.scheduleSpawn(guildId, channelId, 0, "247-autojoin"); } - if (filteredList.length === 0) return; - - // ── Sort join list by guild ID ────────────────────────────────────────── - // Group channels by guild so that same-guild joins are dispatched - // sequentially rather than concurrently. This is critical because the - // Fluxer gateway needs time to process each voice state transition - // before the next one — concurrent same-guild joins cause 401 errors. - filteredList.sort((a, b) => { - const ga = String(a.guildId).replace(/\D/g, ""); - const gb = String(b.guildId).replace(/\D/g, ""); - if (ga !== gb) return ga.localeCompare(gb); - // Within the same guild, maintain original order - return 0; - }); - - const startTime = Date.now(); - logger.recovery( - `[Recovery] Joining ${filteredList.length} session(s) ` + - `(concurrency: ${this.T.recoveryConcurrency}, stagger: ${this.T.recoveryStaggerMs}ms)...` - ); - - const errors = await this.runWithConcurrency( - filteredList, - this.T.recoveryConcurrency, - this.T.recoveryStaggerMs, - async (item) => { - await this.spawnPlayer( - item.guildId, - item.channelId, - 0, // stagger is handled by runWithConcurrency - item.recoveryData, - ); - }, - ); - - const elapsed = ((Date.now() - startTime) / 1000).toFixed(1); - // Count how many sessions are currently active (joined successfully on first - // attempt or after transient retry). Transient failures are retried - // asynchronously by scheduleSpawn, so they don't appear here — log them - // separately instead of claiming 0 failures. - const immediateOk = [...remix.players.playerMap.values()].filter(p => - filteredList.some(item => this.normalizeChannelId(item.channelId) === this.normalizeChannelId(p._channelId ?? p._home247Channel)) - ).length; - const immediateFail = filteredList.length - immediateOk; - const retryPending = this.scheduledSpawns.size; - - if (errors.length > 0) { - for (const err of errors) { - logger.error("[Recovery] Failed to join channel", err.channelId, "guild", err.guildId, err.error); - } - } - logger.recovery( - `[Recovery] Processed ${filteredList.length} session(s) in ${elapsed}s ` + - `(${immediateOk} joined, ${immediateFail} pending/failed` + - (retryPending > 0 ? `, ${retryPending} retry scheduled` : "") + `).` - ); - - // Delete recovery file AFTER all spawns have been attempted (success or fail). - // If the process crashes mid-recovery, the file still exists for next boot. - if (recoveryFileExisted) { - try { fs.unlinkSync(this.recoveryPath); } catch (_) {} - } - - // Reset 401 circuit breaker for next boot cycle - this._guild401Count.clear(); - this._autoJoinRunning = false; this._autoJoinDone = true; + this._autoJoinRunning = false; } } diff --git a/src/constants/FluxerRevoice.mjs b/src/constants/FluxerRevoice.mjs index d9033f1..dd28880 100644 --- a/src/constants/FluxerRevoice.mjs +++ b/src/constants/FluxerRevoice.mjs @@ -168,22 +168,32 @@ export class FluxerRevoice extends EventEmitter { connections = new Map(); users = new Map(); - // Guild-level join mutex: prevents concurrent joinVoiceChannel() calls - // for the same guild. When the bot tries to join multiple channels in - // the same guild simultaneously (e.g. during recovery), the Fluxer - // voice server can return 401 Unauthorized because the previous - // session's token hasn't been fully cleaned up yet. Serializing joins - // per guild eliminates this race condition. + // Guild-level join mutex: kept for per-guild cooldown tracking (401 cooldowns + // and minimum join intervals), but actual join serialization is handled by + // the global queue above. The per-guild queue was insufficient because the + // Fluxer gateway can't handle concurrent joins from DIFFERENT guilds either. /** @type {Map} */ _guildJoinQueue = new Map(); - /** @type {number} Delay between consecutive guild joins (ms) — increased from 3000 to 4000 - * to give the Fluxer gateway more time to clean up the previous voice session - * before we request a new one. 3000ms was too short and caused 401 errors when - * multiple channels in the same guild were joined in quick succession. - * The Fluxer gateway's Erlang backend needs time to process voice state - * transitions, and concurrent joins within the cleanup window cause - * the new LiveKit token to be rejected with 401 Unauthorized. */ - _guildJoinDelay = 4000; + + // ── Global join queue ────────────────────────────────────────────────────── + // The per-guild queue serializes joins within the same guild, but the Fluxer + // gateway also struggles when many DIFFERENT guilds are joined simultaneously. + // During boot recovery, 10+ channels can be spawned within seconds, each + // triggering VOICE_STATE_UPDATE + VOICE_SERVER_UPDATE + LiveKit connect. + // The gateway's Erlang backend can't process this flood fast enough, causing + // 401 Unauthorized errors on guilds that were scheduled later. + // + // The global queue ensures that only ONE join is in-flight at a time across + // ALL guilds, with a delay between each to let the gateway catch up. + /** @type {Promise} Global join serializer — only one join at a time across all guilds */ + _globalJoinQueue = Promise.resolve(); + /** @type {number} Minimum delay between ANY two joins (ms), even across guilds. + * This delay runs AFTER the previous join completes and BEFORE the next + * one starts, giving the Fluxer gateway time to clean up the previous + * voice session. 3 seconds is needed because the gateway's Erlang backend + * needs time to process the voice state transition before a new join + * can succeed without 401 errors. */ + _globalJoinDelay = 3_000; /** @type {Set} Channel IDs where disconnect is expected (bot-initiated) */ _intentionalDisconnects = new Set(); @@ -197,10 +207,12 @@ export class FluxerRevoice extends EventEmitter { /** @type {number} Minimum time between guild joins (ms) — enforced on top of * the per-join delay. If a new join is requested within this window, we - * wait the remaining time before proceeding. Increased from 5000 to 7000 - * because 5000ms was insufficient to prevent 401 errors when the bot - * re-joins a channel in the same guild quickly after a disconnect. */ - _guildMinJoinInterval = 7000; + * wait the remaining time before proceeding. Increased from 7000 to 8000 + * because 7000ms was insufficient to prevent 401 errors when the bot + * re-joins a channel in the same guild quickly after a disconnect, + * especially during boot recovery when multiple guilds compete for + * gateway attention. */ + _guildMinJoinInterval = 8000; /** @type {Map} Guild IDs that recently had a 401 error. * Used to add an even longer backoff before retrying joins in that guild. */ @@ -389,6 +401,53 @@ export class FluxerRevoice extends EventEmitter { * @returns {Promise} */ async join(channelId, _leaveIfEmpty = false) { + // ── Global join queue (TRUE serialization) ─────────────────────────── + // Serialize ALL joins so that only ONE join is in-flight at a time across + // the entire bot. The Fluxer gateway's Erlang backend cannot handle + // concurrent VOICE_STATE_UPDATE + VOICE_SERVER_UPDATE flows — it returns + // 401 Unauthorized when LiveKit tokens haven't propagated for the previous + // join yet. + // + // PREVIOUS APPROACH (broken): Add a 2s delay between starts, but don't + // wait for the previous join to complete. Multiple joins were in-flight + // simultaneously, causing 401 errors. + // + // NEW APPROACH: The global queue wraps the ENTIRE join() call. Each join + // must FULLY COMPLETE (including LiveKit room connection) before the next + // one starts, plus a 3-second gap between joins to give the gateway time + // to clean up the previous voice session. + // + // The promise chain works like this: + // _globalJoinQueue = Promise.resolve() // initial + // _globalJoinQueue = prev.then(() => joinA()) // joinA runs after prev + // _globalJoinQueue = prev.then(() => joinB()) // joinB runs after joinA completes + // + // Each caller awaits its own turn, which only resolves after the full + // join operation completes (or throws). + const joinOperation = async () => { + // Small gap between joins to let the gateway process the previous + // session's cleanup. This runs BEFORE the actual join logic. + await new Promise(r => setTimeout(r, this._globalJoinDelay)); + return await this._joinInternal(channelId, _leaveIfEmpty); + }; + + // Chain onto the global queue: our join only starts after the previous + // one has fully completed (or failed). We store the new tail of the chain. + const prevQueue = this._globalJoinQueue; + const ourResult = prevQueue.then(() => joinOperation()); + this._globalJoinQueue = ourResult.catch(() => {}); // don't break chain on error + return await ourResult; + } + + /** + * Internal join implementation — called by join() through the global queue. + * Do NOT call this directly; always use join() to ensure serialization. + * + * @param {string} channelId + * @param {boolean} _leaveIfEmpty + * @returns {Promise} + */ + async _joinInternal(channelId, _leaveIfEmpty = false) { // Resolve the guild ID for this channel so we can serialize joins per guild. // This prevents the 401 Unauthorized race condition that occurs when // multiple channels in the same guild are joined simultaneously. @@ -398,41 +457,50 @@ export class FluxerRevoice extends EventEmitter { guildId = ch?.guildId ?? ch?.guild?.id ?? null; } catch (_) {} + // Per-guild cooldown checks (still useful for same-guild rapid rejoins + // from recovery or user commands, even though the global queue prevents + // concurrent joins) if (guildId) { - // Serialize: wait for any in-flight join for this guild to complete, - // then add a delay before starting our join. - const prev = this._guildJoinQueue.get(guildId) ?? Promise.resolve(); - const ourTurn = prev.then(async () => { - // Wait the base guild join delay - await new Promise(r => setTimeout(r, this._guildJoinDelay)); + // Additional safety: if this guild was joined very recently, wait + // until the minimum interval has elapsed. This prevents the rapid + // rejoin that causes 401 Unauthorized errors. + const lastJoin = this._guildLastJoinTime.get(guildId) ?? 0; + const elapsed = Date.now() - lastJoin; + if (elapsed < this._guildMinJoinInterval) { + const extraWait = this._guildMinJoinInterval - elapsed; + logger.player( + `[FluxerRevoice] Guild ${guildId} was joined ${elapsed}ms ago — ` + + `waiting additional ${extraWait}ms to avoid 401 race` + ); + await new Promise(r => setTimeout(r, extraWait)); + } - // Additional safety: if this guild was joined very recently, wait - // until the minimum interval has elapsed. This prevents the rapid - // rejoin that causes 401 Unauthorized errors. - const lastJoin = this._guildLastJoinTime.get(guildId) ?? 0; - const elapsed = Date.now() - lastJoin; - if (elapsed < this._guildMinJoinInterval) { - const extraWait = this._guildMinJoinInterval - elapsed; - logger.player( - `[FluxerRevoice] Guild ${guildId} was joined ${elapsed}ms ago — ` + - `waiting additional ${extraWait}ms to avoid 401 race` + // If this guild recently had a 401 error, wait for the cooldown. + const cooldownExpiry = this._guild401Cooldown.get(guildId) ?? 0; + const cooldownRemaining = cooldownExpiry - Date.now(); + if (cooldownRemaining > 0) { + if (cooldownRemaining > 30_000) { + throw new Error( + `Guild ${guildId} has active 401 cooldown (${Math.round(cooldownRemaining / 1000)}s remaining) — ` + + `aborting join for channel ${channelId} to avoid guaranteed failure. ` ); - await new Promise(r => setTimeout(r, extraWait)); } + logger.player( + `[FluxerRevoice] Guild ${guildId} has 401 cooldown — ` + + `waiting ${Math.round(cooldownRemaining / 1000)}s before attempting join` + ); + await new Promise(r => setTimeout(r, cooldownRemaining)); + } - // If this guild recently had a 401 error, wait for the cooldown - const cooldownExpiry = this._guild401Cooldown.get(guildId) ?? 0; - const cooldownRemaining = cooldownExpiry - Date.now(); - if (cooldownRemaining > 0) { - logger.player( - `[FluxerRevoice] Guild ${guildId} has 401 cooldown — ` + - `waiting ${cooldownRemaining}ms before attempting join` - ); - await new Promise(r => setTimeout(r, cooldownRemaining)); - } - }); - this._guildJoinQueue.set(guildId, ourTurn); - await ourTurn; + // Re-check cooldown after waiting + const recheckExpiry = this._guild401Cooldown.get(guildId) ?? 0; + const recheckRemaining = recheckExpiry - Date.now(); + if (recheckRemaining > 30_000) { + throw new Error( + `Guild ${guildId} 401 cooldown re-activated during wait — ` + + `aborting join for channel ${channelId}.` + ); + } } if (this.connections.has(channelId)) { @@ -576,10 +644,14 @@ export class FluxerRevoice extends EventEmitter { // Record the successful join time for this guild so future joins // can enforce the minimum interval and avoid 401 races. - if (channelGuildId) { - this._guildLastJoinTime.set(channelGuildId, Date.now()); - // Clear any 401 cooldown for this guild since the join succeeded - this._guild401Cooldown.delete(channelGuildId); + // Clear any 401 cooldown for this guild since the join succeeded. + // Try both the resolved channelGuildId and the pre-resolved guildId + // to ensure the cooldown is properly cleared even if channelGuildId + // couldn't be resolved from the channel object. + const clearIds = new Set([channelGuildId, guildId].filter(Boolean)); + for (const gId of clearIds) { + this._guildLastJoinTime.set(gId, Date.now()); + this._guild401Cooldown.delete(gId); } // Create our FluxerVoiceConnection wrapper