From 5a1b137805029da5be32cee510118e1e1e19d203 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Mon, 11 May 2026 22:26:55 +0300 Subject: [PATCH] no more random error --- src/GatewayHandler.mjs | 145 ++++++++++++++++++++++---------- src/RecoveryManager.mjs | 48 ++++++++--- src/constants/FluxerRevoice.mjs | 29 +++++++ 3 files changed, 165 insertions(+), 57 deletions(-) diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index aecbbab..421b30f 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -161,10 +161,37 @@ export class GatewayHandler { null; if (!voiceStatesRaw) { + // Fallback: use observedVoiceUsers as a data source when the guild's + // voice_states cache is not populated by @fluxerjs/core. This is common + // because the raw WS listener populates observedVoiceUsers from READY, + // GUILD_CREATE, and VOICE_STATE_UPDATE events, but the Guild object + // itself may not have a voice_states property. logger.voiceState( - `[Reseed] Guild ${cleanGuild} has no voice_states cache — cannot reseed.` + `[Reseed] Guild ${cleanGuild} has no voice_states cache — falling back to observedVoiceUsers.` ); - return 0; + for (const [uid, info] of remix.observedVoiceUsers) { + const infoGuild = String(info.guildId ?? "").replace(/\D/g, ""); + const infoChannel = String(info.channelId ?? "").replace(/\D/g, ""); + if (infoGuild === cleanGuild && infoChannel === cleanChannel) { + humansFound++; + logger.voiceState( + `[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via observedVoiceUsers` + ); + } + } + // Also update the bot's own entry + const botId = client.user?.id; + if (botId) { + const botKey = this.getObservedVoiceBotKey(botId, cleanGuild); + if (botKey) { + remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild }); + } + } + logger.voiceState( + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + + `found ${humansFound} human(s) via fallback, observedVoiceUsers size now ${remix.observedVoiceUsers.size}` + ); + return humansFound; } // Process object-style voice_states (keyed by userId) @@ -822,20 +849,26 @@ export class GatewayHandler { ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)) : new Set(); if (channels.has(cleanOld) && cleanOld !== cleanId && cleanId.length >= 15) { - // Keep the old channel saved AND add the new one. - // The bot moved from one 24/7 channel to another — both should - // remain in the saved list so the bot can auto-rejoin either one. + // Replace the old channel with the new one in stay_247. + // Previously this kept BOTH channels, causing unbounded growth + // in the stay_247 list (e.g. guild 1480202154270605526 ended up + // with 5+ channels). Now we remove the old channel and add the + // new one so the list stays at the correct size. + channels.delete(cleanOld); channels.add(cleanId); set.set("stay_247", [...channels]); - // Copy the per-channel mode from old → new channel (keep old too) + // Move the per-channel mode from old → new channel const modes = set.get("stay_247_modes"); - if (modes && typeof modes === "object" && !Array.isArray(modes) && modes[cleanOld]) { - if (!modes[cleanId]) modes[cleanId] = modes[cleanOld]; + if (modes && typeof modes === "object" && !Array.isArray(modes)) { + if (modes[cleanOld] && !modes[cleanId]) { + modes[cleanId] = modes[cleanOld]; + } + delete modes[cleanOld]; set.set("stay_247_modes", modes); } - logger.voice247(`[247] Added to stay_247: ${cleanId} (kept ${cleanOld})`); + logger.voice247(`[247] Updated stay_247: ${cleanOld} → ${cleanId}`); } } } catch (e) { @@ -850,45 +883,69 @@ export class GatewayHandler { if (remix.intentionalLeaves.has(cleanOld)) { logger.voice247(`[247] Skipping rejoin for ${cleanOld} — intentional leave.`); } else { - const set = remix.settingsMgr.getServer(guildId); - const raw = set.get("stay_247"); - if (raw && raw !== "none") { - const channels = Array.isArray(raw) - ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)) - : new Set(); - if (channels.has(cleanOld)) { - // Per-channel mode: check the mode for this specific channel - const mode = get247ChannelMode(set, cleanOld); - if (mode === "on" || mode === "auto") { - // For multi-voice guilds, match the specific player by channel ID - // instead of skipping recovery entirely (was: if multiVoiceGuild return) - const player = remix.players.playerMap.get(cleanOld); - if (player && !player.leaving) { - logger.voice247("[247] Fluxer gateway disconnected us. Forcing player recovery..."); - if (typeof player._recoverConnection === "function") { - player._recoverConnection(); + // Check if the bot is still in another voice channel in this guild. + // During multi-voice recovery, the bot may be moved from one channel + // to another, which triggers a disconnect event for the old channel. + // This is NOT a real disconnect — it's a side effect of joining a + // new channel in the same guild. Skip recovery in this case to + // prevent the recovery loop (Bug #5). + const botInOtherChannel = [...remix.players.playerMap.entries()].some(([mapKey, p]) => { + if (String(p?._guildId ?? "").replace(/\D/g, "") !== String(guildId ?? "").replace(/\D/g, "")) return false; + const pChannel = String(p?._channelId ?? mapKey).replace(/\D/g, ""); + return pChannel !== cleanOld && !p.leaving && !p._destroyed; + }); + + if (botInOtherChannel) { + logger.voice247( + `[247] Bot disconnected from ${cleanOld} but is still in another channel ` + + `in guild ${guildId} — skipping recovery (likely a channel move).` + ); + // Clean up the old player entry if it wasn't already removed + const oldPlayer = remix.players.playerMap.get(cleanOld); + if (oldPlayer && !oldPlayer._destroyed) { + remix.players.playerMap.delete(cleanOld); + try { oldPlayer.destroy(); } catch (_) {} + } + } else { + const set = remix.settingsMgr.getServer(guildId); + const raw = set.get("stay_247"); + if (raw && raw !== "none") { + const channels = Array.isArray(raw) + ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)) + : new Set(); + if (channels.has(cleanOld)) { + // Per-channel mode: check the mode for this specific channel + const mode = get247ChannelMode(set, cleanOld); + if (mode === "on" || mode === "auto") { + // Match the specific player by channel ID + const player = remix.players.playerMap.get(cleanOld); + if (player && !player.leaving) { + logger.voice247("[247] Fluxer gateway disconnected us. Forcing player recovery..."); + if (typeof player._recoverConnection === "function") { + player._recoverConnection(); + } else { + remix.players.playerMap.delete(cleanOld); + try { player.destroy(); } catch (_) {} + this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, null, "gateway-disconnect"); + } } else { - remix.players.playerMap.delete(cleanOld); - try { player.destroy(); } catch (_) {} this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, null, "gateway-disconnect"); } } else { - this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, null, "gateway-disconnect"); - } - } else { - logger.voice247(`[247] Channel ${cleanOld} mode='${mode}' — not rejoining.`); - channels.delete(cleanOld); - set.set("stay_247", channels.size > 0 ? [...channels] : "none"); - // Also clean up the per-channel mode entry - const modes = set.get("stay_247_modes"); - if (modes && typeof modes === "object" && !Array.isArray(modes)) { - delete modes[cleanOld]; - set.set("stay_247_modes", modes); - } - if (channels.size === 0) set.set("stay_247_mode", "off"); - else { - const first = [...channels][0]; - set.set("stay_247_mode", modes?.[first] ?? "auto"); + logger.voice247(`[247] Channel ${cleanOld} mode='${mode}' — not rejoining.`); + channels.delete(cleanOld); + set.set("stay_247", channels.size > 0 ? [...channels] : "none"); + // Also clean up the per-channel mode entry + const modes = set.get("stay_247_modes"); + if (modes && typeof modes === "object" && !Array.isArray(modes)) { + delete modes[cleanOld]; + set.set("stay_247_modes", modes); + } + if (channels.size === 0) set.set("stay_247_mode", "off"); + else { + const first = [...channels][0]; + set.set("stay_247_mode", modes?.[first] ?? "auto"); + } } } } diff --git a/src/RecoveryManager.mjs b/src/RecoveryManager.mjs index 326bde4..28fe576 100644 --- a/src/RecoveryManager.mjs +++ b/src/RecoveryManager.mjs @@ -536,17 +536,29 @@ export class RecoveryManager { // Use the retryCount passed into spawnPlayer from scheduleSpawn's closure. const prevRetryCount = retryCount; - const shouldRetry = isTransient && prevRetryCount < this.maxTransientRetries - && ( - !recoveryData?.queue?.length - ? (() => { - try { - const raw = remix.settingsMgr.getServer(guildId)?.get("stay_247"); - return raw && raw !== "none"; - } catch (_) { return false; } - })() - : !!recoveryData - ); + // 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); @@ -747,7 +759,16 @@ export class RecoveryManager { ); const elapsed = ((Date.now() - startTime) / 1000).toFixed(1); - const ok = filteredList.length - errors.length; + // 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); @@ -755,7 +776,8 @@ export class RecoveryManager { } logger.recovery( `[Recovery] Processed ${filteredList.length} session(s) in ${elapsed}s ` + - `(${ok} ok, ${errors.length} failed).` + `(${immediateOk} joined, ${immediateFail} pending/failed` + + (retryPending > 0 ? `, ${retryPending} retry scheduled` : "") + `).` ); // Delete recovery file AFTER all spawns have been attempted (success or fail). diff --git a/src/constants/FluxerRevoice.mjs b/src/constants/FluxerRevoice.mjs index a06898b..b19c727 100644 --- a/src/constants/FluxerRevoice.mjs +++ b/src/constants/FluxerRevoice.mjs @@ -163,6 +163,17 @@ 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. + /** @type {Map} */ + _guildJoinQueue = new Map(); + /** @type {number} Delay between consecutive guild joins (ms) */ + _guildJoinDelay = 1500; + constructor(client) { super(); if (!client) throw new Error("FluxerRevoice requires a Fluxer client instance"); @@ -251,6 +262,24 @@ export class FluxerRevoice extends EventEmitter { * @returns {Promise} */ async join(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. + let guildId = null; + try { + const ch = this.client.channels?.get?.(channelId); + guildId = ch?.guildId ?? ch?.guild?.id ?? null; + } catch (_) {} + + if (guildId) { + // Serialize: wait for any in-flight join for this guild to complete, + // then add a short delay before starting our join. + const prev = this._guildJoinQueue.get(guildId) ?? Promise.resolve(); + const ourTurn = prev.then(() => new Promise(r => setTimeout(r, this._guildJoinDelay))); + this._guildJoinQueue.set(guildId, ourTurn); + await ourTurn; + } + if (this.connections.has(channelId)) { const existing = this.connections.get(channelId); // If the existing connection is still alive, reuse it.