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
This commit is contained in:
NoLogicAlan committed 2026-05-12 16:38:24 +03:00
1 parent 0d23d1bd50
commit 7b2d29e229
6 files changed
+488 -666

No files matched your search

+19 -31
View File
@@ -168,11 +168,15 @@ export class Remix {
this._announcementChannelCache = new Map(); this._announcementChannelCache = new Map();
this.intentionalLeaves = new Map(); this.intentionalLeaves = new Map();
// ── Recovery Manager ──────────────────────────────────────────────────── // ── Recovery Manager (24/7 auto-join + spawn) ──────────────────────────
// Handles session persistence, boot recovery, 24/7 auto-join, and player // Handles 24/7 auto-join on boot and player spawning.
// spawning with concurrency control. // The boot-time session recovery system has been removed.
this.recoveryManager = new RecoveryManager(this); 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 ───────────────────────────────────────────────────── // ── Gateway Handler ─────────────────────────────────────────────────────
// Handles raw WS gateway events, voice-state tracking, presence rotation, // Handles raw WS gateway events, voice-state tracking, presence rotation,
// and high-level Fluxer event handlers (GuildCreate, GuildDelete, // and high-level Fluxer event handlers (GuildCreate, GuildDelete,
@@ -327,7 +331,7 @@ export class Remix {
const guildId = player._guildId; const guildId = player._guildId;
if (!guildId) continue; if (!guildId) continue;
if (player._isJoining || player._isRecovering) continue; if (player._isJoining) continue;
const channelId = player._channelId ?? mapKey; const channelId = player._channelId ?? mapKey;
const cleanChanId = String(channelId).replace(/\D/g, ""); const cleanChanId = String(channelId).replace(/\D/g, "");
@@ -426,16 +430,16 @@ export class Remix {
this.players.checkVoiceChannels = function (message) { this.players.checkVoiceChannels = function (message) {
const userId = message?.author?.id ?? message?.message?.author?.id; const userId = message?.author?.id ?? message?.message?.author?.id;
const guildId = const guildId =
message?.channel?.server_id ?? message?.channel?.guildId ??
message?.channel?.serverId ?? message?.channel?.guild?.id ??
message?.channel?.guild?.id ?? message?.channel?.server_id ??
message?.channel?.guildId ?? message?.channel?.serverId ??
message?.message?.server_id ?? message?.message?.guildId ??
message?.message?.serverId ?? message?.message?.guild?.id ??
message?.message?.guildId ?? message?.message?.channel?.guildId ??
message?.message?.channel?.guild?.id ??
message?.message?.channel?.server_id ?? message?.message?.channel?.server_id ??
message?.message?.channel?.serverId ?? message?.message?.channel?.serverId;
message?.message?.channel?.guildId;
logger.voice(`[checkVC] userId=${userId} guildId=${guildId}`); logger.voice(`[checkVC] userId=${userId} guildId=${guildId}`);
logger.voice(`[checkVC] channel keys: ${Object.keys(message?.channel ?? {}).join(",")}`); 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 ────────────────────────────────────────────────────────────────────── // ── Boot ──────────────────────────────────────────────────────────────────────
@@ -879,10 +877,6 @@ process.on("uncaughtException", (err, origin) => {
} }
logger.error("[Error_Handling] Uncaught Exception/Catch"); logger.error("[Error_Handling] Uncaught Exception/Catch");
logger.error("Error:", err, origin); logger.error("Error:", err, origin);
try {
const state = remix.buildRecoveryState();
remix.writeRecoveryState(state, "Shutdown/Crash");
} catch (_) {}
process.exit(1); process.exit(1);
}); });
process.on("uncaughtExceptionMonitor", (err, origin) => { process.on("uncaughtExceptionMonitor", (err, origin) => {
@@ -890,15 +884,9 @@ process.on("uncaughtExceptionMonitor", (err, origin) => {
logger.error("Error:", err, origin); logger.error("Error:", err, origin);
}); });
// ── Session Reboot Recovery Hooks ─────────────────────────────────────────── // ── Shutdown Hooks ──────────────────────────────────────────────────────────
const saveAndExit = async () => { const saveAndExit = async () => {
logger.recovery("\n[Shutdown] Saving active sessions for reboot recovery..."); logger.recovery("\n[Shutdown] Cleaning up before exit...");
try {
const state = remix.buildRecoveryState();
remix.writeRecoveryState(state, "Shutdown");
} catch (e) {
logger.error("[Shutdown] Failed to save recovery state:", e.message);
}
try { try {
if (remix.dashboard?.redis?.destroy) { if (remix.dashboard?.redis?.destroy) {
await remix.dashboard.redis.destroy(); await remix.dashboard.redis.destroy();
+172 -39
View File
@@ -15,7 +15,7 @@ import mysql from "mysql2";
export class GatewayHandler { export class GatewayHandler {
/** /**
* @param {import('../../index.mjs').Remix} remix The running bot instance. * @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) { constructor(remix, recoveryManager) {
this.remix = remix; this.remix = remix;
@@ -59,6 +59,28 @@ export class GatewayHandler {
// where recovery rejoins → gateway disconnects again → recovery again. // where recovery rejoins → gateway disconnects again → recovery again.
/** @type {Map<string, number>} guildId → timestamp when cooldown expires */ /** @type {Map<string, number>} guildId → timestamp when cooldown expires */
this._gatewayDisconnectCooldown = new Map(); 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<string, {guild, timer}>} 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 ────────────────────────────────────────────────── // ── Voice-state key helpers ──────────────────────────────────────────────────
@@ -578,6 +600,20 @@ export class GatewayHandler {
const guildId = guild?.id ?? guild?._id; const guildId = guild?.id ?? guild?._id;
if (!guildId) return; 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 // Part 1: Voice state population
// Only purge stale entries if the GUILD_CREATE actually contains // Only purge stale entries if the GUILD_CREATE actually contains
// voice_states data. If voice_states is empty, the guild may just // 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]) { for (const [uid, info] of [...remix.observedVoiceUsers]) {
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "") if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")
&& newUserIds.has(uid)) { && newUserIds.has(uid)) {
@@ -617,9 +657,13 @@ export class GatewayHandler {
} }
for (const [uid, info] of [...remix.observedVoiceBots]) { for (const [uid, info] of [...remix.observedVoiceBots]) {
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) { if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) {
const botKey = uid; // observedVoiceBots keys are "guildId:userId" // Only delete if this bot's user ID appears in the new voice_states
// Check if this bot entry is for the current guild // data — i.e., it's being replaced by fresh data. This prevents
remix.observedVoiceBots.delete(uid); // 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( logger.voice247(
`[GuildCreate] Late-arriving guild ${guildId} — scheduling 24/7 spawn for channel ${chId} (mode ${mode})` `[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; const guildId = guild?.id ?? guild?._id;
if (!guildId) return; 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.`); logger.guild(`[GuildDelete] Removed from server ${guildId} — cleaning up.`);
this._processGuildDelete(guildId);
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}.`);
}); });
// ── VOICE_STATE_UPDATE ────────────────────────────────────────────────── // ── VOICE_STATE_UPDATE ──────────────────────────────────────────────────
@@ -1080,17 +1127,28 @@ export class GatewayHandler {
// Also check if there was a recent bot join in this guild — if so, // 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 // the disconnect is likely a side-effect of the channel move, not a
// real disconnect that needs recovery. // 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 recentJoin = this._recentBotJoins.get(cleanGuild) ?? 0;
const timeSinceJoin = Date.now() - recentJoin; 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 // Also check if there are pending spawns for this guild — if a
// spawnPlayer is in progress, the disconnect is expected. // spawnPlayer is in progress, the disconnect is expected.
const hasPendingSpawn = [...this.recoveryManager.pendingSpawns].some(([, entry]) => // pendingSpawns is a Set<string> (channel IDs), not a Map — we
String(entry.guildId).replace(/\D/g, "") === cleanGuild // cross-reference with scheduledSpawns to check the guild.
) || [...this.recoveryManager.scheduledSpawns].some(([, entry]) => const hasPendingSpawn = (() => {
String(entry.guildId).replace(/\D/g, "") === cleanGuild 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 // Check gateway disconnect cooldown — if the gateway recently
// force-disconnected us, don't attempt recovery again immediately. // force-disconnected us, don't attempt recovery again immediately.
@@ -1121,6 +1179,13 @@ export class GatewayHandler {
); );
} else { } else {
const set = remix.settingsMgr.getServer(guildId); 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"); const raw = set.get("stay_247");
if (raw && raw !== "none") { if (raw && raw !== "none") {
const channels = Array.isArray(raw) const channels = Array.isArray(raw)
@@ -1130,6 +1195,20 @@ export class GatewayHandler {
// Per-channel mode: check the mode for this specific channel // Per-channel mode: check the mode for this specific channel
const mode = get247ChannelMode(set, cleanOld); const mode = get247ChannelMode(set, cleanOld);
if (mode === "on" || mode === "auto") { 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 // Match the specific player by channel ID
const player = remix.players.playerMap.get(cleanOld); const player = remix.players.playerMap.get(cleanOld);
if (player && !player.leaving) { if (player && !player.leaving) {
@@ -1152,10 +1231,10 @@ export class GatewayHandler {
} else { } else {
remix.players.playerMap.delete(cleanOld); remix.players.playerMap.delete(cleanOld);
try { player.destroy(); } catch (_) {} 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 { } else {
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, null, "gateway-disconnect"); this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect");
} }
} else { } else {
logger.voice247(`[247] Channel ${cleanOld} mode='${mode}' — not rejoining.`); logger.voice247(`[247] Channel ${cleanOld} mode='${mode}' — not rejoining.`);
@@ -1198,5 +1277,59 @@ export class GatewayHandler {
this.recoveryManager.tryAutoJoin(); this.recoveryManager.tryAutoJoin();
this.setupPresenceRotation(); 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}.`);
} }
} }
+1 -3
View File
@@ -541,12 +541,10 @@ export default class Player extends EventEmitter {
// keep retrying — 401 is a permission problem, not a transient failure. // keep retrying — 401 is a permission problem, not a transient failure.
// Retrying just creates more 401 errors and recovery loops. // Retrying just creates more 401 errors and recovery loops.
// Instead, give up on recovery and let the 24/7 system schedule a // Instead, give up on recovery and let the 24/7 system schedule a
// delayed respawn with proper cooldown. // delayed respawn.
if (this._lastDisconnectReason === "401") { if (this._lastDisconnectReason === "401") {
const timeSinceDisconnect = Date.now() - this._lastDisconnectTime; const timeSinceDisconnect = Date.now() - this._lastDisconnectTime;
if (timeSinceDisconnect < 60_000) { 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( logger.warn(
`[Player] Skipping recovery for guild ${this._guildId} — ` + `[Player] Skipping recovery for guild ${this._guildId} — ` +
`last disconnect was 401 Unauthorized (${timeSinceDisconnect / 1000}s ago). ` + `last disconnect was 401 Unauthorized (${timeSinceDisconnect / 1000}s ago). ` +
+2 -2
View File
@@ -113,7 +113,7 @@ export class PlayerManager {
this.playerConfig = config.player; this.playerConfig = config.player;
this.dashboard = config.dashboard ?? null; this.dashboard = config.dashboard ?? null;
this.locale = config.locale ?? 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.timers = config.timers ?? {};
this._lastfm = null; // Set later by Remix class after init this._lastfm = null; // Set later by Remix class after init
} }
@@ -760,7 +760,7 @@ export class PlayerManager {
if (this.spawnPlayer) { if (this.spawnPlayer) {
logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} (mode ${mode247}) in ${delay}ms`); logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} (mode ${mode247}) in ${delay}ms`);
setTimeout(() => { 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) logger.warn("[AutoLeave] 24/7 rejoin failed for", homeChannelId, e.message)
); );
}, delay); }, delay);
+170 -539
View File
@@ -1,4 +1,3 @@
import * as fs from "fs";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "./MessageHandler.mjs"; import { getGlobalColor } from "./MessageHandler.mjs";
@@ -6,10 +5,17 @@ import Player from "./Player.mjs";
import { get247ChannelMode } from "./constants/Helpers247.mjs"; import { get247ChannelMode } from "./constants/Helpers247.mjs";
/** /**
* RecoveryManager — handles session persistence, boot recovery, 24/7 auto-join, * RecoveryManager — handles 24/7 auto-join on boot and player spawning.
* and player spawning with concurrency control.
* *
* 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 { export class RecoveryManager {
/** /**
@@ -21,50 +27,38 @@ export class RecoveryManager {
// ── Timers derived from config ──────────────────────────────────────────── // ── Timers derived from config ────────────────────────────────────────────
const timers = remix.config.timers ?? {}; const timers = remix.config.timers ?? {};
this.T = { this.T = {
aloneCheckInterval: timers.aloneCheckInterval ?? 30_000, aloneCheckInterval: timers.aloneCheckInterval ?? 30_000,
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
rejoin247Delay: timers.rejoin247Delay ?? 3_000, rejoin247Delay: timers.rejoin247Delay ?? 3_000,
recoveryStaggerMs: timers.recoveryStaggerMs ?? 3_000,
recoveryConcurrency: timers.recoveryConcurrency ?? 2,
}; };
// ── Internal state ──────────────────────────────────────────────────────── // ── Internal state ────────────────────────────────────────────────────────
/** @type {Set<string>} Per-channel spawn mutex */ /** @type {Set<string>} Per-channel spawn mutex */
this.pendingSpawns = new Set(); this.pendingSpawns = new Set();
/** @type {Map<string, {timer, guildId, recoveryData, reason, retryCount}>} Scheduled delayed spawns */ /** @type {Map<string, {timer, guildId, reason}>} Scheduled delayed spawns */
this.scheduledSpawns = new Map(); 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<string, number>} 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 ─────────────────────────────────────────────────────────── // ── Ready flags ───────────────────────────────────────────────────────────
this.botReady = false; this.botReady = false;
this.settingsReady = false; this.settingsReady = false;
// ── Auto-join guard ─────────────────────────────────────────────────────── // ── 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._autoJoinRunning = false;
this._autoJoinDone = false; this._autoJoinDone = false;
// ── 401 error tracking ──────────────────────────────────────────────────────
/** @type {Map<string, number>} 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<string, number>} 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 ────────────────────── // ── 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); remix._spawnPlayer = this.spawnPlayer.bind(this);
// ── GatewayHandler reference (set after construction) ──────────────────── // ── 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; this.gatewayHandler = null;
} }
@@ -74,126 +68,8 @@ export class RecoveryManager {
return String(value ?? "").replace(/\D/g, ""); 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. * 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} guildId
* @param {string} [reason="bot no longer in guild"] * @param {string} [reason="bot no longer in guild"]
@@ -201,11 +77,11 @@ export class RecoveryManager {
cleanStaleGuild(guildId, reason = "bot no longer in guild") { cleanStaleGuild(guildId, reason = "bot no longer in guild") {
const { remix } = this; const { remix } = this;
const cleanId = String(guildId).replace(/\D/g, ""); 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 // Destroy any active players for this guild
for (const [channelId, player] of remix.players.playerMap) { 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); remix.players.playerMap.delete(channelId);
try { player.leave().catch(() => {}); } catch (_) {} try { player.leave().catch(() => {}); } catch (_) {}
try { player.destroy(); } catch (_) {} try { player.destroy(); } catch (_) {}
@@ -242,51 +118,34 @@ export class RecoveryManager {
* @param {string} guildId * @param {string} guildId
* @param {string} channelId * @param {string} channelId
* @param {number} [delayMs=0] * @param {number} [delayMs=0]
* @param {Object|null} [recoveryData=null]
* @param {string} [reason="spawn"] * @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); const cleanChannelId = this.normalizeChannelId(channelId);
if (!cleanChannelId) return; if (!cleanChannelId) return;
const existing = this.scheduledSpawns.get(cleanChannelId); const existing = this.scheduledSpawns.get(cleanChannelId);
if (existing) clearTimeout(existing.timer); 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(() => { const timer = setTimeout(() => {
this.scheduledSpawns.delete(cleanChannelId); 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); logger.warn(`[PlayerSpawn] Scheduled ${reason} failed for ${cleanChannelId}:`, e?.message ?? e);
}); });
}, Math.max(0, delayMs)); }, Math.max(0, delayMs));
this.scheduledSpawns.set(cleanChannelId, { timer, guildId, recoveryData, reason, retryCount }); this.scheduledSpawns.set(cleanChannelId, { timer, guildId, reason });
}
/**
* 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
} }
// ── Player spawning ────────────────────────────────────────────────────────── // ── Player spawning ──────────────────────────────────────────────────────────
/** /**
* Create a new Player, join the target voice channel, and optionally restore * Create a new Player and join the target voice channel.
* recovery state. * 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; const { remix } = this;
if (delayMs > 0) await new Promise(r => setTimeout(r, delayMs));
const cleanChannelId = this.normalizeChannelId(channelId); const cleanChannelId = this.normalizeChannelId(channelId);
if (!cleanChannelId) return; if (!cleanChannelId) return;
@@ -297,60 +156,71 @@ export class RecoveryManager {
this.scheduledSpawns.delete(cleanChannelId); this.scheduledSpawns.delete(cleanChannelId);
} }
// Use the passed-in retryCount (from scheduleSpawn's closure) rather const cleanGuildId = String(guildId).replace(/\D/g, "");
// than reading from the now-deleted scheduledSpawns entry.
// Only enforce 24/7 check if we are NOT recovering from a reboot // ── Pre-flight: verify bot is still in the guild ─────────────────────
if (!recoveryData) { // During startup, the guild cache may not be populated yet because
// Try the guildId as-is first, then the cleaned version. // GuildCreate events haven't arrived. In that case, DON'T call
// The settingsMgr Map key might differ from the guildId format // cleanStaleGuild — it would nuke the in-memory settings cache for a
// passed in (e.g. string vs number, or cleaned vs raw). // guild the bot IS still in, causing unnecessary churn and scary log
let set = remix.settingsMgr.getServer(guildId); // messages. The GuildCreate handler will schedule the 24/7 spawn for
let raw = set.get("stay_247"); // late-arriving guilds. cleanStaleGuild is only appropriate when we
if ((!raw || raw === "none") && String(guildId).replace(/\D/g, "") !== String(guildId)) { // know for sure the bot was kicked (i.e. a GuildDelete was received).
const cleanGId = String(guildId).replace(/\D/g, ""); if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGuildId)) {
set = remix.settingsMgr.getServer(cleanGId); if (this._autoJoinRunning || !this._autoJoinDone) {
raw = set.get("stay_247"); // Startup phase — guild cache not populated yet, just skip
}
if (!raw || raw === "none") {
// Diagnostic: log why we're skipping
logger.recovery( logger.recovery(
`[PlayerSpawn] Skipping 24/7 channel ${cleanChannelId} in guild ${guildId}: ` + `[PlayerSpawn] Skipping channel ${cleanChannelId} in guild ${cleanGuildId} — ` +
`stay_247=${JSON.stringify(raw)}. ` + `guild cache not populated yet (startup race). GuildCreate will schedule spawn.`
`SettingsMgr has this guild: ${remix.settingsMgr.guilds.has(guildId)}`
); );
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) // ── 24/7 check ──────────────────────────────────────────────────────
? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)) // Only spawn if this channel is in the stay_247 list.
: new Set([String(raw).replace(/\D/g, "")]); let set = remix.settingsMgr.getServer(guildId);
if (!channels.has(cleanChannelId)) { let raw = set?.get("stay_247");
logger.recovery( if ((!raw || raw === "none") && String(guildId).replace(/\D/g, "") !== String(guildId)) {
`[PlayerSpawn] Skipping channel ${cleanChannelId}: not in stay_247 list [${[...channels].join(", ")}]` const cleanGId = String(guildId).replace(/\D/g, "");
); set = remix.settingsMgr.getServer(cleanGId);
return; 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. // Atomic mutex check — blocks concurrent spawns for the same channel.
if (remix.players.playerMap.has(cleanChannelId) || this.pendingSpawns.has(cleanChannelId)) return; if (remix.players.playerMap.has(cleanChannelId) || this.pendingSpawns.has(cleanChannelId)) return;
// ── Duplicate player cleanup for same guild ────────────────────────── // ── 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) { for (const [mapKey, existingPlayer] of remix.players.playerMap) {
if (existingPlayer._destroyed || existingPlayer.leaving) { if (existingPlayer._destroyed || existingPlayer.leaving) {
remix.players.playerMap.delete(mapKey); remix.players.playerMap.delete(mapKey);
try { existingPlayer.destroy(); } catch (_) {} try { existingPlayer.destroy(); } catch (_) {}
continue; 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 existingChannelId = String(existingPlayer._channelId ?? mapKey).replace(/\D/g, "");
const existingGuildId = String(existingPlayer._guildId ?? "").replace(/\D/g, ""); const existingGuildId = String(existingPlayer._guildId ?? "").replace(/\D/g, "");
if (existingGuildId === cleanGuildId && existingChannelId === cleanChannelId) { if (existingGuildId === cleanGuildId && existingChannelId === cleanChannelId) {
@@ -363,7 +233,7 @@ export class RecoveryManager {
try { existingPlayer.destroy(); } catch (_) {} try { existingPlayer.destroy(); } catch (_) {}
} }
} }
this.pendingSpawns.add(cleanChannelId); this.pendingSpawns.add(cleanChannelId);
try { try {
@@ -415,7 +285,7 @@ export class RecoveryManager {
p.destroy(); p.destroy();
if (matchChannel && (mode2 === "on" || mode2 === "auto")) { 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 { } else {
// 24/7 is off — send inactivity message with hint to enable 247 // 24/7 is off — send inactivity message with hint to enable 247
try { try {
@@ -431,7 +301,7 @@ export class RecoveryManager {
.setDescription( .setDescription(
`Left channel <#${activeChannelId}> because of inactivity.\n` + `Left channel <#${activeChannelId}> because of inactivity.\n` +
`If you want me to stay in voice, use \`${prefix}247 on\` or \`${prefix}247 auto\`\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(); .toJSON();
if (typeof ch?.send === "function") ch.send({ embeds: [embed] }).catch(() => {}); if (typeof ch?.send === "function") ch.send({ embeds: [embed] }).catch(() => {});
@@ -472,8 +342,6 @@ export class RecoveryManager {
}); });
// ── Join channel ─────────────────────────────────────────────────────── // ── 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 { try {
await p.join(cleanChannelId); await p.join(cleanChannelId);
@@ -484,20 +352,13 @@ export class RecoveryManager {
p._home247Channel = cleanChannelId; p._home247Channel = cleanChannelId;
// ── Re-seed voice states for this channel ──────────────────────────── // ── 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 { try {
const humansFound = this.gatewayHandler.reseedVoiceStatesForChannel(guildId, cleanChannelId); const humansFound = this.gatewayHandler.reseedVoiceStatesForChannel(guildId, cleanChannelId);
if (humansFound > 0) { if (humansFound > 0) {
logger.recovery( logger.recovery(
`[Recovery] Re-seeded voice states for ${cleanChannelId}: ` + `[Spawn] Re-seeded voice states for ${cleanChannelId}: ` +
`${humansFound} human(s) already present — cancelling inactivity timer.` `${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") { if (typeof p._stopInactivityTimer === "function") {
p._stopInactivityTimer(); p._stopInactivityTimer();
} }
@@ -506,148 +367,88 @@ export class RecoveryManager {
logger.warn("[PlayerSpawn] Voice state reseed failed:", reseedErr?.message); logger.warn("[PlayerSpawn] Voice state reseed failed:", reseedErr?.message);
} }
// ── Restore recovery state ─────────────────────────────────────────── // ── Restore saved volume from guild settings ─────────────────────────
if (recoveryData) { try {
if (recoveryData.textChannelId) { const savedVol = remix.settingsMgr.getServer(guildId)?.get("volume");
p.textChannel = remix.client.channels.get(recoveryData.textChannelId); if (savedVol !== undefined && savedVol !== null) {
} const vol = Number(savedVol);
if (recoveryData.home247ChannelId) { if (!isNaN(vol)) p.preferredVolume = vol / 100;
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;
} }
} catch (_) {}
if (recoveryData.queue && recoveryData.queue.length > 0) { logger.recovery(`[Spawn] Joined 24/7 channel ${cleanChannelId} in guild ${cleanGuildId}.`);
p.queue.addMany(recoveryData.queue);
const startPlayback = () => p.playNext().catch(e => // Join succeeded — clear any 401 retry counters for this guild
logger.warn("[Recovery] playNext failed:", e?.message) this._guild401Retries.delete(cleanGuildId);
); this._guild401Ban.delete(cleanGuildId);
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)).`);
}
} catch (e) { } catch (e) {
remix.players.playerMap.delete(cleanChannelId); remix.players.playerMap.delete(cleanChannelId);
try { p.destroy(); } catch (_) {} try { p.destroy(); } catch (_) {}
logger.warn("[PlayerSpawn] Failed to join channel", cleanChannelId, "guild", guildId, e.message); logger.warn("[PlayerSpawn] Failed to join channel", cleanChannelId, "guild", guildId, e.message);
// ── Guild membership check for 401 errors ─────────────────────────── // ── 401 Unauthorized handling ─────────────────────────────────────
// If the bot was kicked while offline (or between retries), the 401 will const is401Error = /\b401\b/.test(e.message) ||
// keep repeating. Verify the bot is still in the guild — if not, clean e.message?.includes("Unauthorized") ||
// up all state and skip retries entirely. e.message?.includes("no permissions to access the room") ||
// ── 401 Unauthorized handling with circuit breaker ───────────────── e.message?.includes("signal failure: client error");
if (e.message?.includes("401 Unauthorized")) {
const cleanGId = String(guildId).replace(/\D/g, ""); if (is401Error) {
// Bot not in guild cache — but during startup, the cache might not
// Bot no longer in guild → clean up entirely // be populated yet. Same race as the pre-flight check.
if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGId)) { 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( logger.warn(
`[PlayerSpawn] 401 on guild ${guildId} — bot no longer in server. ` + `[PlayerSpawn] 401 on guild ${guildId} — bot no longer in server. Cleaning up.`
`Cleaning up and skipping retries.`
); );
this.cleanStaleGuild(guildId, "401 and bot not in guild"); this.cleanStaleGuild(guildId, "401 and bot not in guild");
return; return;
} }
// Guild-level circuit breaker: if this guild has hit the 401 threshold, // Bot IS still in the guild — the 401 may be transient (gateway slow
// stop retrying all channels in it during this recovery cycle. // to provision voice room). Retry with exponential backoff instead of
const prev401 = this._guild401Count.get(cleanGId) ?? 0; // permanently giving up on the first failure.
const new401 = prev401 + 1; const retryCount = (this._guild401Retries.get(cleanGuildId) ?? 0) + 1;
this._guild401Count.set(cleanGId, new401); 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( logger.warn(
`[PlayerSpawn] 401 circuit breaker tripped for guild ${cleanGId} ` + `[PlayerSpawn] 401 for guild ${cleanGuildId} — ` +
`(${new401} failures ≥ ${this._guild401Max}). Skipping all further ` + `${retryCount} consecutive failures. Banning for 5 minutes.`
`retries for this guild in the current recovery cycle.`
); );
// 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; return;
} }
// First 401 in guild — log with context but don't retry // Exponential backoff: 1st retry after 15s, 2nd after 45s
// (401 is permission-based, retrying immediately won't help) const backoffMs = retryCount === 1 ? 15_000 : 45_000;
logger.warn( logger.warn(
`[PlayerSpawn] 401 Unauthorized for channel ${cleanChannelId} in guild ${cleanGId} ` + `[PlayerSpawn] 401 for guild ${cleanGuildId} — ` +
`(${new401}/${this._guild401Max} before circuit breaker). ` + `transient? Retry ${retryCount}/3 in ${backoffMs / 1000}s.`
`Bot is still in guild — permissions may have been revoked. ` +
`Skipping retry (401 is persistent, not transient).`
); );
this.scheduleSpawn(guildId, cleanChannelId, backoffMs, `401-retry-${retryCount}`);
return; return;
} }
// Retry if the failure is a transient LiveKit race (with max retries + backoff) // Non-401 error — clear the 401 retry counter for this guild since
// IMPORTANT: 401 Unauthorized is NOT transient — it's a permission error // this was a different kind of failure.
// that will keep failing. It's already handled above with the circuit this._guild401Retries.delete(cleanGuildId);
// 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}`
);
}
} }
return p; return p;
@@ -657,226 +458,56 @@ export class RecoveryManager {
} }
} }
// ── Concurrency utility ────────────────────────────────────────────────────── // ── Auto-join on boot (24/7 only) ────────────────────────────────────────────
/**
* 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 ────────────────────────────────────────────────────────
/** /**
* Called when both `botReady` and `settingsReady` are true. * 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() { async tryAutoJoin() {
if (!this.botReady || !this.settingsReady) return; if (!this.botReady || !this.settingsReady) return;
if (this._autoJoinDone || this._autoJoinRunning) return; if (this._autoJoinRunning || this._autoJoinDone) return;
this._autoJoinRunning = true; this._autoJoinRunning = true;
const { remix } = this; const { remix } = this;
await new Promise(r => setTimeout(r, 2000));
// Build a unified join list: recovery sessions + 24/7 channels
const joinList = []; const joinList = [];
// 1. Recover standard reboot sessions // Collect all 24/7 channels from loaded guild settings
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));
for (const [guildId, serverSettings] of remix.settingsMgr.guilds) { for (const [guildId, serverSettings] of remix.settingsMgr.guilds) {
const raw = serverSettings.get("stay_247"); try {
if (!raw || raw === "none") continue; const raw = serverSettings.get("stay_247");
if (!raw || raw === "none") continue;
const channelIds = Array.isArray(raw) const channels = Array.isArray(raw)
? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean) ? raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)
: [String(raw).replace(/\D/g, "")].filter(Boolean); : [String(raw).replace(/\D/g, "")].filter(id => id.length >= 15);
for (const channelId of channelIds) { for (const chId of channels) {
const clean = String(channelId).replace(/\D/g, ""); const mode = get247ChannelMode(serverSettings, chId);
// Per-channel mode: only join if this specific channel is on/auto if (mode !== "on" && mode !== "auto") continue;
const mode = get247ChannelMode(serverSettings, clean); if (!remix.players.playerMap.has(chId) && !this.pendingSpawns.has(chId)) {
if (mode !== "auto" && mode !== "on") continue; joinList.push({ guildId, channelId: chId });
}
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`
);
} }
} } catch (_) {}
} }
logger.recovery( logger.recovery(
`[Recovery] Join list built: ${joinList.length} channel(s) ` + `[AutoJoin] Found ${joinList.length} 24/7 channel(s) to join.`
`(${joinList.filter(j => j.recoveryData).length} recovery, ` +
`${joinList.filter(j => !j.recoveryData).length} 24/7)`
); );
// ── Filter out guilds the bot is no longer a member of ──────────────── // Schedule all 24/7 spawns immediately (no stagger). The FluxerRevoice
const filteredList = []; // global join queue handles serialization — only one join is in-flight
for (const item of joinList) { // at a time across all guilds, with a 3s gap between each. Staggering
// Try both the raw guildId and the cleaned (digits-only) version. // here is no longer needed and just adds unnecessary delay before the
// The settings Map might use a different format than client.guilds // joins start queuing.
// (e.g. string vs number, or with/without non-digit chars). for (let i = 0; i < joinList.length; i++) {
const cleanGId = String(item.guildId).replace(/\D/g, ""); const { guildId, channelId } = joinList[i];
const hasRaw = remix.client.guilds.has(item.guildId); this.scheduleSpawn(guildId, channelId, 0, "247-autojoin");
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);
}
} }
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._autoJoinDone = true;
this._autoJoinRunning = false;
} }
} }
+124 -52
View File
@@ -168,22 +168,32 @@ export class FluxerRevoice extends EventEmitter {
connections = new Map(); connections = new Map();
users = new Map(); users = new Map();
// Guild-level join mutex: prevents concurrent joinVoiceChannel() calls // Guild-level join mutex: kept for per-guild cooldown tracking (401 cooldowns
// for the same guild. When the bot tries to join multiple channels in // and minimum join intervals), but actual join serialization is handled by
// the same guild simultaneously (e.g. during recovery), the Fluxer // the global queue above. The per-guild queue was insufficient because the
// voice server can return 401 Unauthorized because the previous // Fluxer gateway can't handle concurrent joins from DIFFERENT guilds either.
// session's token hasn't been fully cleaned up yet. Serializing joins
// per guild eliminates this race condition.
/** @type {Map<string, Promise>} */ /** @type {Map<string, Promise>} */
_guildJoinQueue = new 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 // ── Global join queue ──────────────────────────────────────────────────────
* before we request a new one. 3000ms was too short and caused 401 errors when // The per-guild queue serializes joins within the same guild, but the Fluxer
* multiple channels in the same guild were joined in quick succession. // gateway also struggles when many DIFFERENT guilds are joined simultaneously.
* The Fluxer gateway's Erlang backend needs time to process voice state // During boot recovery, 10+ channels can be spawned within seconds, each
* transitions, and concurrent joins within the cleanup window cause // triggering VOICE_STATE_UPDATE + VOICE_SERVER_UPDATE + LiveKit connect.
* the new LiveKit token to be rejected with 401 Unauthorized. */ // The gateway's Erlang backend can't process this flood fast enough, causing
_guildJoinDelay = 4000; // 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<string>} Channel IDs where disconnect is expected (bot-initiated) */ /** @type {Set<string>} Channel IDs where disconnect is expected (bot-initiated) */
_intentionalDisconnects = new Set(); _intentionalDisconnects = new Set();
@@ -197,10 +207,12 @@ export class FluxerRevoice extends EventEmitter {
/** @type {number} Minimum time between guild joins (ms) — enforced on top of /** @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 * 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 * wait the remaining time before proceeding. Increased from 7000 to 8000
* because 5000ms was insufficient to prevent 401 errors when the bot * because 7000ms was insufficient to prevent 401 errors when the bot
* re-joins a channel in the same guild quickly after a disconnect. */ * re-joins a channel in the same guild quickly after a disconnect,
_guildMinJoinInterval = 7000; * especially during boot recovery when multiple guilds compete for
* gateway attention. */
_guildMinJoinInterval = 8000;
/** @type {Map<string, number>} Guild IDs that recently had a 401 error. /** @type {Map<string, number>} Guild IDs that recently had a 401 error.
* Used to add an even longer backoff before retrying joins in that guild. */ * Used to add an even longer backoff before retrying joins in that guild. */
@@ -389,6 +401,53 @@ export class FluxerRevoice extends EventEmitter {
* @returns {Promise<FluxerVoiceConnection>} * @returns {Promise<FluxerVoiceConnection>}
*/ */
async join(channelId, _leaveIfEmpty = false) { 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<FluxerVoiceConnection>}
*/
async _joinInternal(channelId, _leaveIfEmpty = false) {
// Resolve the guild ID for this channel so we can serialize joins per guild. // Resolve the guild ID for this channel so we can serialize joins per guild.
// This prevents the 401 Unauthorized race condition that occurs when // This prevents the 401 Unauthorized race condition that occurs when
// multiple channels in the same guild are joined simultaneously. // 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; guildId = ch?.guildId ?? ch?.guild?.id ?? null;
} catch (_) {} } 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) { if (guildId) {
// Serialize: wait for any in-flight join for this guild to complete, // Additional safety: if this guild was joined very recently, wait
// then add a delay before starting our join. // until the minimum interval has elapsed. This prevents the rapid
const prev = this._guildJoinQueue.get(guildId) ?? Promise.resolve(); // rejoin that causes 401 Unauthorized errors.
const ourTurn = prev.then(async () => { const lastJoin = this._guildLastJoinTime.get(guildId) ?? 0;
// Wait the base guild join delay const elapsed = Date.now() - lastJoin;
await new Promise(r => setTimeout(r, this._guildJoinDelay)); 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 // If this guild recently had a 401 error, wait for the cooldown.
// until the minimum interval has elapsed. This prevents the rapid const cooldownExpiry = this._guild401Cooldown.get(guildId) ?? 0;
// rejoin that causes 401 Unauthorized errors. const cooldownRemaining = cooldownExpiry - Date.now();
const lastJoin = this._guildLastJoinTime.get(guildId) ?? 0; if (cooldownRemaining > 0) {
const elapsed = Date.now() - lastJoin; if (cooldownRemaining > 30_000) {
if (elapsed < this._guildMinJoinInterval) { throw new Error(
const extraWait = this._guildMinJoinInterval - elapsed; `Guild ${guildId} has active 401 cooldown (${Math.round(cooldownRemaining / 1000)}s remaining) — ` +
logger.player( `aborting join for channel ${channelId} to avoid guaranteed failure. `
`[FluxerRevoice] Guild ${guildId} was joined ${elapsed}ms ago — ` +
`waiting additional ${extraWait}ms to avoid 401 race`
); );
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 // Re-check cooldown after waiting
const cooldownExpiry = this._guild401Cooldown.get(guildId) ?? 0; const recheckExpiry = this._guild401Cooldown.get(guildId) ?? 0;
const cooldownRemaining = cooldownExpiry - Date.now(); const recheckRemaining = recheckExpiry - Date.now();
if (cooldownRemaining > 0) { if (recheckRemaining > 30_000) {
logger.player( throw new Error(
`[FluxerRevoice] Guild ${guildId} has 401 cooldown — ` + `Guild ${guildId} 401 cooldown re-activated during wait — ` +
`waiting ${cooldownRemaining}ms before attempting join` `aborting join for channel ${channelId}.`
); );
await new Promise(r => setTimeout(r, cooldownRemaining)); }
}
});
this._guildJoinQueue.set(guildId, ourTurn);
await ourTurn;
} }
if (this.connections.has(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 // Record the successful join time for this guild so future joins
// can enforce the minimum interval and avoid 401 races. // can enforce the minimum interval and avoid 401 races.
if (channelGuildId) { // Clear any 401 cooldown for this guild since the join succeeded.
this._guildLastJoinTime.set(channelGuildId, Date.now()); // Try both the resolved channelGuildId and the pre-resolved guildId
// Clear any 401 cooldown for this guild since the join succeeded // to ensure the cooldown is properly cleared even if channelGuildId
this._guild401Cooldown.delete(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 // Create our FluxerVoiceConnection wrapper