diff --git a/commands/filter.mjs b/commands/filter.mjs index a159465..29d4f6d 100644 --- a/commands/filter.mjs +++ b/commands/filter.mjs @@ -273,7 +273,7 @@ export async function run(msg) { for (const emoji of allEmojisForPage(p)) { try { await menuMsg.message.react(emoji); - await Utils.sleep(150); + await Utils.sleep(25); } catch (_) {} } }; @@ -389,7 +389,7 @@ export async function run(msg) { .setDescription(this.t(msg, "responses.filter.nothingPlaying")) ; await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {}); - await Utils.sleep(2000); + await Utils.sleep(500); await menuMsg.edit({ embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)] }).catch(() => {}); @@ -430,7 +430,7 @@ export async function run(msg) { ) ; await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {}); - await Utils.sleep(3000); + await Utils.sleep(900); await menuMsg.edit({ embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, track)] }).catch(() => {}); @@ -462,7 +462,7 @@ export async function run(msg) { ; await menuMsg.edit({ embeds: [confirmEmbed] }).catch(() => {}); - await Utils.sleep(2500); + await Utils.sleep(700); // Restore picker (session stays open) if (!settled) { @@ -473,4 +473,4 @@ export async function run(msg) { }); resetTimer(); -} \ No newline at end of file +} diff --git a/commands/stats.mjs b/commands/stats.mjs index f5ef075..74d559c 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -12,11 +12,19 @@ export const command = new CommandBuilder() // ── Stats cache ─────────────────────────────────────────────────────────────── const CACHE_TTL_MS = 5 * 60 * 1000; // refresh every 5 minutes +const FAST_WAIT_MS = 1_500; let cachedStats = null; // { guildCount, userCount } or null let cacheExpiresAt = 0; let inflightPromise = null; +function withTimeout(promise, ms, fallback) { + return Promise.race([ + promise, + new Promise((resolve) => setTimeout(() => resolve(fallback), ms)), + ]); +} + /** * Accurate guild count — same multi-layer strategy as ErinJS: * 1. Try client.fetchTotalGuildCount() (shard-aware, if available) @@ -46,16 +54,17 @@ async function fetchAccurateGuildCount(client) { try { let total = 0; let after = undefined; - for (let page = 0; page < 500; page++) { + for (let page = 0; page < 25; page++) { const route = `/users/@me/guilds?limit=200${after ? `&after=${after}` : ""}`; - const response = await client.rest.get(route); + const response = await withTimeout(client.rest.get(route), 800, null); + if (!response) break; const batch = Array.isArray(response) ? response : (response?.guilds ?? []); total += batch.length; if (batch.length < 200) break; after = batch[batch.length - 1]?.id; if (!after) break; } - return total; + if (total > 0) return total; } catch {} } @@ -104,6 +113,13 @@ function getStats(client) { return inflightPromise; } +function getLastfmSnapshot(lastfm) { + return { + scrobbleCount: Number(lastfm?._totalScrobblesCache ?? 0), + linkedUsers: Number(lastfm?._linkedUsersCache ?? 0), + }; +} + function getLivePlayerCount(playerMap) { let live = 0; @@ -172,12 +188,13 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, export async function run(message) { const lastfm = this.lastfm; const lastfmEnabled = lastfm?.enabled ?? false; + const lastfmSnapshot = getLastfmSnapshot(lastfm); const shared = { guildCount: this.client.guilds.size, playerCount: getLivePlayerCount(this.players.playerMap), - scrobbleCount: 0, - linkedUsers: 0, + scrobbleCount: lastfmSnapshot.scrobbleCount, + linkedUsers: lastfmSnapshot.linkedUsers, lastfmEnabled, uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000), comHash: this.comHash, @@ -187,8 +204,12 @@ export async function run(message) { }; // Fetch Last.fm stats (non-blocking for initial reply) - const scrobblePromise = lastfmEnabled ? lastfm.getTotalScrobbles() : Promise.resolve(0); - const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0); + const scrobblePromise = lastfmEnabled + ? withTimeout(lastfm.getStoredTotalScrobbles?.() ?? Promise.resolve(lastfmSnapshot.scrobbleCount), FAST_WAIT_MS, lastfmSnapshot.scrobbleCount) + : Promise.resolve(0); + const linkedPromise = lastfmEnabled + ? withTimeout(lastfm.getLinkedUsersCount(), FAST_WAIT_MS, lastfmSnapshot.linkedUsers) + : Promise.resolve(0); const hasCached = cachedStats !== null; @@ -206,7 +227,10 @@ export async function run(message) { const ping = Date.now() - start; const [stats, scrobbleCount, linkedUsers] = await Promise.all([ - getStats(this.client), + withTimeout(getStats(this.client), FAST_WAIT_MS, cachedStats ?? { + guildCount: shared.guildCount, + userCount: 0, + }), scrobblePromise, linkedPromise, ]); @@ -222,4 +246,4 @@ export async function run(message) { loading: false, })] }).catch((err) => console.error("[stats] editEmbed failed:", err)); -} \ No newline at end of file +} diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index e877dec..affc04a 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -866,9 +866,27 @@ export class LastFmManager { const [rows] = await pool.execute( "SELECT linked_users FROM lastfm_stats WHERE id = 1" ); - return Number(rows[0]?.linked_users ?? 0); + const count = Number(rows[0]?.linked_users ?? 0); + this._linkedUsersCache = count; + return count; } catch { - return 0; + return this._linkedUsersCache ?? 0; + } + } + + async getStoredTotalScrobbles() { + if (!this.enabled) return 0; + try { + const pool = await this._getPool(); + const [rows] = await pool.execute( + "SELECT stored_scrobbles FROM lastfm_stats WHERE id = 1" + ); + const total = Number(rows[0]?.stored_scrobbles ?? this._totalScrobblesCache ?? 0); + this._totalScrobblesCache = total; + this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000; + return total; + } catch { + return this._totalScrobblesCache ?? 0; } } diff --git a/src/Player.mjs b/src/Player.mjs index 0f070bc..50784db 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -521,191 +521,19 @@ export default class Player extends EventEmitter { // ═══════════════════════════════════════════════════════════════════════════ async _recoverConnection() { - // bail immediately if the player has been destroyed or a recovery is - // already in-flight or scheduled (covers the gap between attempts). - if (this._isRecovering || this._recoveryPending || this._destroyed) return; - const targetChannelId = this._getRecoveryChannelId(); - if (!targetChannelId) { - logger.warn(`[Player] Recovery aborted for guild ${this._guildId} - no channel target available.`); - this.emit("autoleave"); - return; - } - - // ── 401 Permission-based recovery guard ────────────────────────────── - // If the last disconnect was due to a 401 Unauthorized error, don't - // 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. - if (this._lastDisconnectReason === "401") { - const timeSinceDisconnect = Date.now() - this._lastDisconnectTime; - if (timeSinceDisconnect < 60_000) { - logger.warn( - `[Player] Skipping recovery for guild ${this._guildId} — ` + - `last disconnect was 401 Unauthorized (${timeSinceDisconnect / 1000}s ago). ` + - `Delegating to 24/7 respawn system.` - ); - this._isRecovering = false; - this._recoveryPending = false; - this.emit("autoleave"); - return; - } - // If more than 60s have passed since the 401, try again — permissions - // may have been restored. - logger.player( - `[Player] 401 was ${timeSinceDisconnect / 1000}s ago — retrying recovery ` + - `(permissions may have been restored).` - ); - } - - this._isRecovering = true; + if (this._destroyed || this.leaving || this._recoveryPending) return; + this._isRecovering = false; this._recoveryPending = true; - - this._recoveryAttempts = (this._recoveryAttempts ?? 0) + 1; - const MAX_RECOVERY = 5; - if (this._recoveryAttempts > MAX_RECOVERY) { - logger.error(`[Player] Recovery failed after ${MAX_RECOVERY} attempts for guild ${this._guildId} — giving up.`); - this._isRecovering = false; - this._recoveryPending = false; - this._recoveryAttempts = 0; - this.emit("autoleave"); - return; - } - // Exponential backoff: 2s, 4s, 8s, 16s, 32s (was linear: 2s, 4s, 6s, 8s, 10s) - // If last disconnect was a gateway force-disconnect, use longer backoff - // to avoid the recovery cascade where rejoining causes another disconnect. - let backoffMs; - if (this._lastDisconnectReason === "gateway") { - // Gateway force-disconnects need longer recovery time to avoid cascading - backoffMs = Math.min(5000 * Math.pow(2, this._recoveryAttempts - 1), 60_000); - } else { - backoffMs = Math.min(2000 * Math.pow(2, this._recoveryAttempts - 1), 30_000); - } - logger.mediaplayer(`[Player] Recovery attempt ${this._recoveryAttempts}/${MAX_RECOVERY} for ${this._guildId} (backoff ${backoffMs}ms, reason: ${this._lastDisconnectReason ?? "unknown"})`); - await Utils.sleep(backoffMs); - - // re-check after await — player may have been destroyed during backoff - if (this._destroyed) { - this._isRecovering = false; - return; - } - - // Wait for _isJoining to clear — if another operation (e.g. spawnPlayer or - // a concurrent _recoverConnection from a different event path) is currently - // calling join(), we must not race against it. Poll every 500ms for up to - // 15s, then give up on this attempt and schedule a retry. - let waited = 0; - while (this._isJoining && waited < 15_000) { - logger.mediaplayer(`[Player] Waiting for _isJoining to clear before recovery attempt...`); - await Utils.sleep(500); - waited += 500; - } - if (this._isJoining) { - logger.warn("[Player] _isJoining still busy after 15s — deferring recovery attempt."); - this._isRecovering = false; - this._recoveryPending = false; - // Schedule a retry via setTimeout so we don't stack synchronous calls - this._recoveryTimer = setTimeout(() => { - this._recoveryTimer = null; - this._recoverConnection().catch(() => {}); - }, 2000); - return; - } - - logger.mediaplayer(`[Player] Attempting to recover voice connection for ${this._guildId}`); - - try { - if (this.connection) { - // Clean up the old connection. FluxerVoiceConnection.disconnect() - // handles native @fluxerjs/voice disconnect + LiveKit room close. - // We also need to send a gateway leave signal so the gateway - // processes the leave before we attempt to rejoin. - try { await this.connection.disconnect(); } catch (_) {} - - // Explicitly send a gateway leave signal via @fluxerjs/voice so - // the gateway knows the bot left the channel. Without this, the - // gateway may still think the bot is in the channel and won't - // send a fresh VOICE_SERVER_UPDATE on the next joinVoiceChannel(). - try { - const vm = getVoiceManager(this.client); - if (vm && typeof vm.updateVoiceState === "function") { - // IMPORTANT: Always use guild-scoped leave. An unscoped - // updateVoiceState(null, opts) disconnects ALL guilds' voice - // connections, causing cascading failures. - const guildIdForLeave = this._guildId ?? this._resolveGuildId(); - if (guildIdForLeave) { - try { - vm.updateVoiceState(guildIdForLeave, null, { self_deaf: false, self_mute: false }); - } catch (e1) { - // Older @fluxerjs/voice may not accept 3-arg form - try { vm.updateVoiceState(guildIdForLeave, null); } catch (e2) {} - } - logger.mediaplayer(`[Player] Sent guild-scoped gateway leave signal for guild ${guildIdForLeave} before recovery rejoin`); - } else { - logger.warn(`[Player] Cannot send guild-scoped leave — no guildId available. Skipping to avoid disconnecting all guilds.`); - } - } - } catch (e) { - logger.warn(`[Player] Gateway leave signal failed: ${e?.message}`); - } - - // Also remove the stale connection from FluxerRevoice's map - // so the next _revoice.join() doesn't return the dead connection. - if (this._revoice && this._channelId) { - try { this._revoice.deleteConnection(this._channelId); } catch (_) {} - } - } - - await Utils.sleep(3000); - if (this.leaving || this._destroyed) return; - - logger.mediaplayer(`[Player] Rejoining channel ${targetChannelId}`); - await this.join(targetChannelId); - - // Do NOT re-read room.isConnected/room.connectionState here — - // join() already awaited ConnectionStateChanged and only resolved when - // the room was truly connected, so reaching this line means success. - // The old check using room.state (which doesn't exist in @livekit/rtc-node) - // always threw "unexpected state: undefined" and emitted autoleave, - // causing the infinite reconnect storm in the logs. - this._isRecovering = false; - this._recoveryPending = false; - this._recoveryAttempts = 0; - if (this._recoveryTimer) { - clearTimeout(this._recoveryTimer); - this._recoveryTimer = null; - } - // Keep _home247Channel in sync with the channel we successfully recovered to. - if (this._channelId) this._home247Channel = this._channelId; - - const current = this.queue.getCurrent(); - if (current) { - logger.player(`[Player] Resuming track after recovery: ${current.title}`); - this.queue.data.unshift(current); - this.queue.current = null; - this._playingNext = false; - await this.playNext(); - } else if (!this.queue.isEmpty()) { - this._playingNext = false; - await this.playNext(); - } - } catch (e) { - logger.error("[Player] Recovery failed:", e.message); - this._isRecovering = false; - // _recoveryPending stays true during the retry delay to block duplicate - // calls from stacking up (e.g. two rapid disconnect events). - if (!this._destroyed && !this.leaving) { - const delay = Math.min(2000 * (this._recoveryAttempts ?? 1), 30_000); - if (this._recoveryTimer) clearTimeout(this._recoveryTimer); - this._recoveryTimer = setTimeout(() => { - this._recoveryTimer = null; - this._recoveryPending = false; - if (!this._destroyed && !this.leaving) this._recoverConnection(); - }, delay); - } else { - this._recoveryPending = false; - } + this._recoveryAttempts = 0; + if (this._recoveryTimer) { + clearTimeout(this._recoveryTimer); + this._recoveryTimer = null; } + logger.warn( + `[Player] Voice connection lost for guild ${this._guildId} ` + + `(reason: ${this._lastDisconnectReason ?? "unknown"}). Recovery is disabled; leaving player stopped.` + ); + this.emit("autoleave"); } // ═══════════════════════════════════════════════════════════════════════════ @@ -1362,7 +1190,7 @@ export default class Player extends EventEmitter { settled = true; resolve(); } - }, 3_000); + }, 1_200); const onStateChange = (cs) => { if (settled) return; @@ -1391,7 +1219,7 @@ export default class Player extends EventEmitter { cleanup(); reject(new Error(`LiveKit disconnected (connectionState: ${room.connectionState})`)); } - }, 500); + }, 150); // Immediate check using correct API if (room.isConnected) { @@ -1474,8 +1302,8 @@ export default class Player extends EventEmitter { const playerReady = await this._ensureMediaPlayer(); if (!playerReady) { - logger.mediaplayer("[Player] First MediaPlayer attempt failed, retrying after delay..."); - await Utils.sleep(3000); + logger.mediaplayer("[Player] First MediaPlayer attempt failed, retrying after short delay..."); + await Utils.sleep(750); if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry"); const roomAlive = this.connection?.room?.isConnected ?? false; if (!roomAlive) { diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 78ee356..c2ca262 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -519,7 +519,12 @@ export class PlayerManager { } // Also check if a join is in-progress for this channel if (this._pendingJoins.has(cleanUserChannelId)) { - return null; // A player is being created — caller should retry + const pendingPlayer = await this._waitForPendingJoin(cleanUserChannelId); + if (pendingPlayer) { + pendingPlayer.textChannel = message.channel; + return pendingPlayer; + } + return null; } } @@ -592,6 +597,22 @@ export class PlayerManager { return null; } + async _waitForPendingJoin(channelId, timeoutMs = 5_000) { + const cleanChannelId = cleanId(channelId); + const startedAt = Date.now(); + + while (this._pendingJoins.has(cleanChannelId) && (Date.now() - startedAt) < timeoutMs) { + const player = this.playerMap.get(cleanChannelId) + ?? [...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId); + if (player) return player; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + + return this.playerMap.get(cleanChannelId) + ?? [...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId) + ?? null; + } + // ═══════════════════════════════════════════════════════════════════════════ // Channel Selection Prompt // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/RecoveryManager.mjs b/src/RecoveryManager.mjs index 1ea10d2..08a827b 100644 --- a/src/RecoveryManager.mjs +++ b/src/RecoveryManager.mjs @@ -5,17 +5,15 @@ import Player from "./Player.mjs"; import { get247ChannelMode } from "./constants/Helpers247.mjs"; /** - * RecoveryManager — handles 24/7 auto-join on boot and player spawning. + * RecoveryManager — handles player spawning without background recovery loops. * * 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) + * - spawnPlayer() — create a Player and join a voice channel when explicitly requested * - cleanStaleGuild() — purge all state for a guild the bot left - * - tryAutoJoin() — auto-join 24/7 channels when bot + settings are ready */ export class RecoveryManager { /** @@ -316,7 +314,6 @@ export class RecoveryManager { if (matchChannel && (mode2 === "on" || mode2 === "auto")) { this.scheduleSpawn(guildId, homeChannelId, this.T.rejoin247Delay, "247-autoleave"); } else { - // 24/7 is off — send inactivity message with hint to enable 247 try { const prefix = remix.handler?.getPrefix?.(guildId) ?? "%"; const guild = remix.client.guilds.get(guildId); @@ -430,56 +427,10 @@ export class RecoveryManager { 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.` - ); - this.cleanStaleGuild(guildId, "401 and bot not in guild"); - return; - } - - // 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 (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 for guild ${cleanGuildId} — ` + - `${retryCount} consecutive failures. Banning for 5 minutes.` - ); - return; - } - - // Exponential backoff: 1st retry after 15s, 2nd after 45s - const backoffMs = retryCount === 1 ? 15_000 : 45_000; logger.warn( - `[PlayerSpawn] 401 for guild ${cleanGuildId} — ` + - `transient? Retry ${retryCount}/3 in ${backoffMs / 1000}s.` + `[PlayerSpawn] 401 for guild ${cleanGuildId} on channel ${cleanChannelId}. ` + + "Recovery retries are disabled; leaving this channel disconnected." ); - this.scheduleSpawn(guildId, cleanChannelId, backoffMs, `401-retry-${retryCount}`); return; } @@ -510,7 +461,6 @@ export class RecoveryManager { const { remix } = this; const joinList = []; - // Collect all 24/7 channels from loaded guild settings for (const [guildId, serverSettings] of remix.settingsMgr.guilds) { try { const raw = serverSettings.get("stay_247"); @@ -534,11 +484,6 @@ export class RecoveryManager { `[AutoJoin] Found ${joinList.length} 24/7 channel(s) to join.` ); - // 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"); diff --git a/src/constants/FluxerRevoice.mjs b/src/constants/FluxerRevoice.mjs index cb312e8..bc3ebd3 100644 --- a/src/constants/FluxerRevoice.mjs +++ b/src/constants/FluxerRevoice.mjs @@ -194,10 +194,9 @@ export class FluxerRevoice extends EventEmitter { /** @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; + * voice session. Keep this short for snappy manual joins while still + * preserving serialization across the whole bot. */ + _globalJoinDelay = 1_000; /** @type {Set} Channel IDs where disconnect is expected (bot-initiated) */ _intentionalDisconnects = new Set(); @@ -211,12 +210,9 @@ 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 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; + * wait the remaining time before proceeding. Keep this lower than the old + * recovery-focused value so user-triggered joins don't feel sluggish. */ + _guildMinJoinInterval = 3_000; /** @type {Map} Guild IDs that recently had a 401 error. * Used to add an even longer backoff before retrying joins in that guild. */ @@ -390,10 +386,8 @@ export class FluxerRevoice extends EventEmitter { existing._connected = false; try { existing.removeAllListeners(); } catch (_) {} - // 4. Brief delay to let the gateway process the leave before we rejoin. - // Increased from 1500ms to 2000ms to give the Erlang gateway backend - // more time to clean up the previous voice session. - await new Promise(r => setTimeout(r, 2000)); + // Brief delay to let the gateway process the leave before we rejoin. + await new Promise(r => setTimeout(r, 750)); } /**