hotfix for VoiceStateCache.mjs

This commit is contained in:
NoLogicAlan committed 2026-05-16 17:43:36 +03:00
1 parent 16e4f853a6
commit 68938e0d29
7 files changed
+832 -223

No files matched your search

+42 -44
View File
@@ -13,6 +13,7 @@ import { FluxerRevoice } from "./src/constants/FluxerRevoice.mjs";
import { MoonlinkManager } from "./src/MoonlinkManager.mjs"; import { MoonlinkManager } from "./src/MoonlinkManager.mjs";
import { Dashboard } from "./src/dashboard/Dashboard.mjs"; import { Dashboard } from "./src/dashboard/Dashboard.mjs";
import { Locale } from "./src/constants/Locale.mjs"; import { Locale } from "./src/constants/Locale.mjs";
import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs";
import { GatewayHandler } from "./src/GatewayHandler.mjs"; import { GatewayHandler } from "./src/GatewayHandler.mjs";
import { LastFmManager } from "./src/LastFmManager.mjs"; import { LastFmManager } from "./src/LastFmManager.mjs";
@@ -159,12 +160,21 @@ export class Remix {
this.moonlink = null; this.moonlink = null;
let moonlinkInitialised = false; let moonlinkInitialised = false;
// ── Voice state tracking maps (created early so all modules can reference) ── // ── Voice state tracking — indexed cache with LRU eviction ──────────
this.observedVoiceUsers = new Map(); // Replaces raw observedVoiceUsers/observedVoiceBots Maps with O(1)
this.observedVoiceBots = new Map(); // channel-member lookups, composite keys, and bounded memory.
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
// ── Backward-compat aliases (deprecated — use voiceCache directly) ───
// These expose the same .size / .get / .set / .has / .delete / iteration
// interface so existing code (dashboard, commands) continues to work.
this.observedVoiceUsers = this.voiceCache;
this.observedVoiceBots = this.voiceCache;
// ── Caches ─────────────────────────────────────────────────────────────── // ── Caches ───────────────────────────────────────────────────────────────
// _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries
this._announcementChannelCache = new Map(); this._announcementChannelCache = new Map();
this._announcementChannelTTL = 5 * 60 * 1000; // 5 min
this.intentionalLeaves = new Map(); this.intentionalLeaves = new Map();
// ── Gateway Handler ───────────────────────────────────────────────────── // ── Gateway Handler ─────────────────────────────────────────────────────
@@ -305,9 +315,12 @@ export class Remix {
timers: this.T, timers: this.T,
}); });
this.players.observedVoiceUsers = this.observedVoiceUsers; this.players.observedVoiceUsers = this.observedVoiceUsers;
this.players.voiceCache = this.voiceCache;
this.players._lastfm = this.lastfm; this.players._lastfm = this.lastfm;
// ── Periodic alone-check ─────────────────────────────────────────────────── // ── Periodic alone-check ───────────────────────────────────────────────────
// Uses VoiceStateCache.channelMembers index for O(1) per-player lookup
// instead of iterating ALL observedVoiceUsers (which was O(N×M)).
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval; const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
setInterval(() => { setInterval(() => {
for (const [mapKey, player] of this.players.playerMap) { for (const [mapKey, player] of this.players.playerMap) {
@@ -334,17 +347,10 @@ export class Remix {
if (player._is247Enabled()) continue; if (player._is247Enabled()) continue;
let hasHuman = false; // O(1) lookup via VoiceStateCache channelMembers index
for (const [, info] of this.observedVoiceUsers) { let hasHuman = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanChanId);
const infoChannel = String(info.channelId ?? "").replace(/\D/g, "");
const infoGuild = String(info.guildId ?? "").replace(/\D/g, "");
if (infoGuild === cleanGuildId && infoChannel === cleanChanId) {
hasHuman = true;
break;
}
}
// Fallback: check guild voice_states cache if observedVoiceUsers // Fallback: check guild voice_states cache if voiceCache
// didn't find anyone (can happen after bot restart before reseed). // didn't find anyone (can happen after bot restart before reseed).
if (!hasHuman) { if (!hasHuman) {
try { try {
@@ -364,9 +370,9 @@ export class Remix {
const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false; const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false;
if (!isBot) { if (!isBot) {
hasHuman = true; hasHuman = true;
// Also update observedVoiceUsers so future checks are fast // Also update voiceCache so future checks are O(1)
if (stateUserId) { if (stateUserId) {
this.observedVoiceUsers.set(stateUserId, { channelId: cleanChanId, guildId: cleanGuildId }); this.voiceCache.updateUser({ guildId: cleanGuildId, userId: stateUserId, channelId: cleanChanId, isBot: false });
} }
break; break;
} }
@@ -377,8 +383,6 @@ export class Remix {
} }
// Fallback: check LiveKit remote participants if guild cache is empty. // Fallback: check LiveKit remote participants if guild cache is empty.
// This is the most reliable source of truth — if the bot's LiveKit room
// has remote participants, those are real humans in the channel.
if (!hasHuman) { if (!hasHuman) {
try { try {
const room = player.connection?.room; const room = player.connection?.room;
@@ -427,10 +431,7 @@ export class Remix {
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(",")}`);
logger.voice(`[checkVC] observedVoiceUsers size=${self.observedVoiceUsers.size}`); logger.voice(`[checkVC] voiceCache humans=${self.voiceCache.observedVoiceUsersSize} bots=${self.voiceCache.observedVoiceBotsSize}`);
for (const [uid, info] of self.observedVoiceUsers) {
logger.voice(`[checkVC] stored: uid=${uid} channelId=${info.channelId} guildId=${info.guildId}`);
}
if (!userId || !guildId) { if (!userId || !guildId) {
logger.voice(`[checkVC] BAIL — missing userId or guildId`); logger.voice(`[checkVC] BAIL — missing userId or guildId`);
@@ -440,16 +441,16 @@ export class Remix {
const cleanGuild = String(guildId).replace(/\D/g, ""); const cleanGuild = String(guildId).replace(/\D/g, "");
const seed = (channelId) => { const seed = (channelId) => {
if (!self.observedVoiceUsers.has(userId)) { if (!self.voiceCache.hasHumanUser(userId, cleanGuild)) {
self.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuild }); self.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false });
} }
return self.observedVoiceUsers.get(userId)?.channelId ?? channelId; return self.voiceCache.getUserChannel(cleanGuild, userId) ?? channelId;
}; };
const observed = self.observedVoiceUsers.get(userId); const observed = self.voiceCache.getUserLocation(cleanGuild, userId);
logger.voice(`[checkVC] observed=${JSON.stringify(observed)} cleanGuild=${cleanGuild}`); logger.voice(`[checkVC] observed=${JSON.stringify(observed)} cleanGuild=${cleanGuild}`);
if (observed && String(observed.guildId).replace(/\D/g, "") === cleanGuild) { if (observed && observed.channelId) {
logger.voice(`[checkVC] HIT observedVoiceUsers → ${observed.channelId}`); logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`);
return observed.channelId; return observed.channelId;
} }
@@ -505,13 +506,10 @@ export class Remix {
} catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); } } catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); }
try { try {
for (const [uid, info] of self.observedVoiceUsers) { const loc = self.voiceCache.getHumanUser(userId); // scan all guilds
if (uid !== userId) continue; if (loc && String(loc.guildId ?? "").replace(/\D/g, "") === cleanGuild) {
logger.voice(`[checkVC] last-resort: uid=${uid} stored.guildId=${info.guildId} cleanGuild=${cleanGuild}`); logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`);
if (String(info.guildId).replace(/\D/g, "") === cleanGuild) { return loc.channelId;
logger.voice(`[checkVC] HIT last-resort → ${info.channelId}`);
return info.channelId;
}
} }
} catch (e) { logger.voice(`[checkVC] last-resort error: ${e.message}`); } } catch (e) { logger.voice(`[checkVC] last-resort error: ${e.message}`); }
@@ -673,10 +671,9 @@ export class Remix {
if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId"); if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId");
// Already have a player for this channel? // Already have a player for this channel?
// Use guild→player reverse index for O(1) lookup, fallback to playerMap.get()
const existing = this.players.playerMap.get(cleanChannelId) const existing = this.players.playerMap.get(cleanChannelId)
?? [...this.players.playerMap.values()].find(p => ?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId);
String(p?._channelId ?? "").replace(/\D/g, "") === cleanChannelId
);
if (existing) return existing; if (existing) return existing;
// Guard: moonlink must be ready // Guard: moonlink must be ready
@@ -702,6 +699,7 @@ export class Remix {
revoice: this.revoice ?? null, revoice: this.revoice ?? null,
settingsMgr: this.settingsMgr ?? this.settings ?? null, settingsMgr: this.settingsMgr ?? this.settings ?? null,
observedVoiceUsers: this.observedVoiceUsers ?? null, observedVoiceUsers: this.observedVoiceUsers ?? null,
voiceCache: this.voiceCache ?? null,
locale: this.locale ?? null, locale: this.locale ?? null,
}); });
@@ -739,6 +737,7 @@ export class Remix {
// Add to playerMap only after join succeeds // Add to playerMap only after join succeeds
this.players.playerMap.set(cleanChannelId, player); this.players.playerMap.set(cleanChannelId, player);
this.players._indexPlayer(cleanGuildId, cleanChannelId);
if (this.players._pendingJoins) { if (this.players._pendingJoins) {
this.players._pendingJoins.delete(cleanChannelId); this.players._pendingJoins.delete(cleanChannelId);
} }
@@ -865,15 +864,14 @@ export class Remix {
isMember = true; isMember = true;
} }
// 2. Fallback — observed voice users (REST-less) // 2. Fallback — check voiceCache for this guild (O(1) per guild)
if (!isMember) { if (!isMember) {
const cleanGuildId = String(guild.id).replace(/\D/g, ""); const cleanGuildId = String(guild.id).replace(/\D/g, "");
for (const [, info] of (this.observedVoiceUsers ?? [])) { // Check if any human users are tracked in this guild
if (String(info.guildId ?? "").replace(/\D/g, "") === cleanGuildId) { const hasVoiceUsers = [...this.voiceCache.userLocations.values()].some(
isMember = true; loc => loc.guildId === cleanGuildId
break; );
} if (hasVoiceUsers) isMember = true;
}
} }
// 3. Slow path — REST fetch for large guilds with incomplete caches // 3. Slow path — REST fetch for large guilds with incomplete caches
+100 -134
View File
@@ -3,6 +3,7 @@ import { getVoiceManager } from "@fluxerjs/voice";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
import { ServerSettings } from "./Settings.mjs"; import { ServerSettings } from "./Settings.mjs";
import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs"; import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs";
import { VoiceStateCache } from "./constants/VoiceStateCache.mjs";
import mysql from "mysql2"; import mysql from "mysql2";
/** /**
@@ -128,25 +129,23 @@ export class GatewayHandler {
// The bot's own ID is included in voiceStates — track it as a bot // The bot's own ID is included in voiceStates — track it as a bot
const botId = client.user?.id; const botId = client.user?.id;
if (userId === botId) { if (userId === botId) {
const botKey = this.getObservedVoiceBotKey(userId, cleanGuildId); remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true });
if (botKey) remix.observedVoiceBots.set(botKey, { channelId, guildId: cleanGuildId });
} else { } else {
// Check if this user is a bot via the members cache // Check if this user is a bot via the members cache
const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId); const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId);
const member = guild?.members?.get?.(userId); const member = guild?.members?.get?.(userId);
const isBot = member?.user?.bot ?? false; const isBot = member?.user?.bot ?? false;
if (isBot) { if (isBot) {
const botKey = this.getObservedVoiceBotKey(userId, cleanGuildId); remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true });
if (botKey) remix.observedVoiceBots.set(botKey, { channelId, guildId: cleanGuildId });
} else { } else {
remix.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuildId }); remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: false });
} }
} }
}); });
} }
logger.voiceState( logger.voiceState(
`[Seed] Seeded from VoiceManager.voiceStates — ` + `[Seed] Seeded from VoiceManager.voiceStates — ` +
`${remix.observedVoiceUsers.size} humans, ${remix.observedVoiceBots.size} bots tracked.` `${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots tracked.`
); );
return; // VoiceManager is the primary source — skip fallback return; // VoiceManager is the primary source — skip fallback
} }
@@ -170,8 +169,7 @@ export class GatewayHandler {
: val?.channelId ?? val?.channel_id ?? null; : val?.channelId ?? val?.channel_id ?? null;
if (!uid || !channelId) continue; if (!uid || !channelId) continue;
const isBot = val?.member?.user?.bot ?? false; const isBot = val?.member?.user?.bot ?? false;
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers; remix.voiceCache.updateUser({ guildId: gId, userId: uid, channelId, isBot });
target.set(uid, { channelId, guildId: gId });
} }
} else { } else {
const entries = Array.isArray(voiceStatesRaw) const entries = Array.isArray(voiceStatesRaw)
@@ -182,8 +180,7 @@ export class GatewayHandler {
const channelId = state?.channelId ?? state?.channel_id; const channelId = state?.channelId ?? state?.channel_id;
if (!userId || !channelId) continue; if (!userId || !channelId) continue;
const isBot = state?.member?.user?.bot ?? false; const isBot = state?.member?.user?.bot ?? false;
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers; remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
target.set(userId, { channelId, guildId: gId });
} }
} }
} }
@@ -228,20 +225,18 @@ export class GatewayHandler {
const userChannel = String(userChannelId).replace(/\D/g, ""); const userChannel = String(userChannelId).replace(/\D/g, "");
if (userChannel !== cleanChannel) return; if (userChannel !== cleanChannel) return;
if (userId === botId) { if (userId === botId) {
const botKey = this.getObservedVoiceBotKey(userId, cleanGuild); remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true });
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
} else { } else {
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
const member = guild?.members?.get?.(userId); const member = guild?.members?.get?.(userId);
const isBot = member?.user?.bot ?? false; const isBot = member?.user?.bot ?? false;
if (isBot) { if (isBot) {
const botKey = this.getObservedVoiceBotKey(userId, cleanGuild); remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true });
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
} else { } else {
remix.observedVoiceUsers.set(userId, { channelId: cleanChannel, guildId: cleanGuild }); remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false });
humansFound++; humansFound++;
logger.voiceState( logger.voiceState(
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceManager` `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceManager`
); );
} }
} }
@@ -249,13 +244,12 @@ export class GatewayHandler {
// Update the bot's own entry // Update the bot's own entry
if (botId) { if (botId) {
const botKey = this.getObservedVoiceBotKey(botId, cleanGuild); remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
} }
logger.voiceState( logger.voiceState(
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
`found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.observedVoiceUsers.size}` `found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
); );
// If VoiceManager found humans, skip fallbacks // If VoiceManager found humans, skip fallbacks
@@ -270,7 +264,7 @@ export class GatewayHandler {
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
if (!guild) { if (!guild) {
logger.voiceState( logger.voiceState(
`[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.` `[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.`
); );
} else { } else {
const voiceStatesRaw = const voiceStatesRaw =
@@ -288,10 +282,10 @@ export class GatewayHandler {
const isBot = val?.member?.user?.bot ?? false; const isBot = val?.member?.user?.bot ?? false;
if (isBot) continue; if (isBot) continue;
if (String(stateChannel).replace(/\D/g, "") === cleanChannel) { if (String(stateChannel).replace(/\D/g, "") === cleanChannel) {
remix.observedVoiceUsers.set(uid, { channelId: stateChannel, guildId: cleanGuild }); remix.voiceCache.updateUser({ guildId: cleanGuild, userId: uid, channelId: stateChannel, isBot: false });
humansFound++; humansFound++;
logger.voiceState( logger.voiceState(
`[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild})` `[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild})`
); );
} }
} }
@@ -306,10 +300,10 @@ export class GatewayHandler {
const isBot = state?.member?.user?.bot ?? false; const isBot = state?.member?.user?.bot ?? false;
if (isBot) continue; if (isBot) continue;
if (String(stateChannel).replace(/\D/g, "") === cleanChannel) { if (String(stateChannel).replace(/\D/g, "") === cleanChannel) {
remix.observedVoiceUsers.set(userId, { channelId: stateChannel, guildId: cleanGuild }); remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: stateChannel, isBot: false });
humansFound++; humansFound++;
logger.voiceState( logger.voiceState(
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild})` `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild})`
); );
} }
} }
@@ -317,14 +311,13 @@ export class GatewayHandler {
// Update bot's own entry // Update bot's own entry
if (botId) { if (botId) {
const botKey = this.getObservedVoiceBotKey(botId, cleanGuild); remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
} }
if (humansFound > 0) { if (humansFound > 0) {
logger.voiceState( logger.voiceState(
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
`found ${humansFound} human(s), observedVoiceUsers size now ${remix.observedVoiceUsers.size}` `found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
); );
return humansFound; return humansFound;
} }
@@ -339,15 +332,14 @@ export class GatewayHandler {
if (infoGuild === cleanGuild && infoChannel === cleanChannel) { if (infoGuild === cleanGuild && infoChannel === cleanChannel) {
humansFound++; humansFound++;
logger.voiceState( logger.voiceState(
`[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via observedVoiceUsers` `[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via observedVoiceUsers`
); );
} }
} }
// Update bot's own entry // Update bot's own entry
if (botId) { if (botId) {
const botKey = this.getObservedVoiceBotKey(botId, cleanGuild); remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
} }
} }
@@ -361,9 +353,9 @@ export class GatewayHandler {
const userId = participant?.identity ?? participant?.sid; const userId = participant?.identity ?? participant?.sid;
if (userId) { if (userId) {
humansFound++; humansFound++;
remix.observedVoiceUsers.set(userId, { channelId: cleanChannel, guildId: cleanGuild }); remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false });
logger.voiceState( logger.voiceState(
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via LiveKit participants` `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via LiveKit participants`
); );
} }
} }
@@ -374,8 +366,8 @@ export class GatewayHandler {
} }
logger.voiceState( logger.voiceState(
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
`found ${humansFound} human(s), observedVoiceUsers size now ${remix.observedVoiceUsers.size}` `found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
); );
return humansFound; return humansFound;
@@ -445,8 +437,7 @@ export class GatewayHandler {
const channelId = state.channel_id; const channelId = state.channel_id;
if (!userId || !channelId) continue; if (!userId || !channelId) continue;
const isBot = state.member?.user?.bot ?? false; const isBot = state.member?.user?.bot ?? false;
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers; remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
target.set(isBot ? this.getObservedVoiceBotKey(userId, gId) : userId, { channelId, guildId: gId });
} }
} }
} }
@@ -466,8 +457,7 @@ export class GatewayHandler {
const channelId = state.channel_id; const channelId = state.channel_id;
if (!userId || !channelId) continue; if (!userId || !channelId) continue;
const isBot = state.member?.user?.bot ?? false; const isBot = state.member?.user?.bot ?? false;
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers; remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
target.set(isBot ? this.getObservedVoiceBotKey(userId, gId) : userId, { channelId, guildId: gId });
} }
} }
} }
@@ -483,10 +473,11 @@ export class GatewayHandler {
const guildId = d?.guild_id; const guildId = d?.guild_id;
const isBot = d?.member?.user?.bot ?? false; const isBot = d?.member?.user?.bot ?? false;
if (!userId) return; if (!userId) return;
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers; if (channelId) {
const voiceKey = isBot ? this.getObservedVoiceBotKey(userId, guildId) : userId; remix.voiceCache.updateUser({ guildId, userId, channelId, isBot });
if (channelId) target.set(voiceKey, { channelId, guildId }); } else {
else if (voiceKey) target.delete(voiceKey); remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot });
}
} }
} catch (_) {} } catch (_) {}
}; };
@@ -590,8 +581,8 @@ export class GatewayHandler {
clearTimeout(deferred.timer); clearTimeout(deferred.timer);
this._deferredGuildDeletes.delete(guildId); this._deferredGuildDeletes.delete(guildId);
logger.guild( logger.guild(
`[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` + `[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` +
`guild came back (GuildCreate received during grace period).` `guild came back (GuildCreate received during grace period).`
); );
} }
@@ -606,7 +597,7 @@ export class GatewayHandler {
guild.voice_states ?? guild.voice_states ??
guild.voiceStates ?? guild.voiceStates ??
null; null;
if (voiceStatesRaw) { if (voiceStatesRaw) {
// Build a set of user IDs from the new voice_states data // Build a set of user IDs from the new voice_states data
const newUserIds = new Set(); const newUserIds = new Set();
@@ -624,29 +615,13 @@ export class GatewayHandler {
if (userId) newUserIds.add(userId); if (userId) newUserIds.add(userId);
} }
} }
// Only purge entries for users/bots 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, // Previously, ALL observedVoiceBots entries for the guild were deleted,
// which removed the bot's own entry that was set up during recovery. // 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 // Now we only delete entries for bots whose user ID appears in the new
// voice_states data, matching the same logic used for observedVoiceUsers. // voice_states data, matching the same logic used for observedVoiceUsers.
for (const [uid, info] of [...remix.observedVoiceUsers]) { remix.voiceCache.purgeUsersInGuild(guildId, newUserIds);
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")
&& newUserIds.has(uid)) {
remix.observedVoiceUsers.delete(uid);
}
}
for (const [uid, info] of [...remix.observedVoiceBots]) {
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) {
// Only delete if this bot's user ID appears in the new voice_states
// data — i.e., it's being replaced by fresh data. This prevents
// destroying the bot's own entry set up during recovery.
const botUserId = uid.split(":").pop(); // key is "guildId:userId"
if (botUserId && newUserIds.has(botUserId)) {
remix.observedVoiceBots.delete(uid);
}
}
}
} }
if (voiceStatesRaw) { if (voiceStatesRaw) {
if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object"
@@ -656,8 +631,7 @@ export class GatewayHandler {
: val?.channelId ?? val?.channel_id ?? null; : val?.channelId ?? val?.channel_id ?? null;
if (!uid || !channelId) continue; if (!uid || !channelId) continue;
const isBot = val?.member?.user?.bot ?? false; const isBot = val?.member?.user?.bot ?? false;
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers; remix.voiceCache.updateUser({ guildId, userId: uid, channelId, isBot });
target.set(isBot ? this.getObservedVoiceBotKey(uid, guildId) : uid, { channelId, guildId });
} }
} else { } else {
const entries = Array.isArray(voiceStatesRaw) const entries = Array.isArray(voiceStatesRaw)
@@ -670,8 +644,7 @@ export class GatewayHandler {
const sgid = state?.guildId ?? state?.guild_id ?? guildId; const sgid = state?.guildId ?? state?.guild_id ?? guildId;
const isBot = state?.member?.user?.bot ?? false; const isBot = state?.member?.user?.bot ?? false;
if (!channelId || !userId) continue; if (!channelId || !userId) continue;
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers; remix.voiceCache.updateUser({ guildId: sgid, userId, channelId, isBot });
target.set(isBot ? this.getObservedVoiceBotKey(userId, sgid) : userId, { channelId, guildId: sgid });
} }
} }
} }
@@ -725,8 +698,8 @@ export class GatewayHandler {
// Only log the first few deferrals individually, then suppress // Only log the first few deferrals individually, then suppress
if (this._deferredDeleteCount <= 3) { if (this._deferredDeleteCount <= 3) {
logger.guild( logger.guild(
`[GuildDelete] Deferring cleanup for server ${guildId} ` + `[GuildDelete] Deferring cleanup for server ${guildId} ` +
`(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).` `(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).`
); );
} }
// Cancel any existing deferred timer for this guild // Cancel any existing deferred timer for this guild
@@ -805,15 +778,13 @@ export class GatewayHandler {
} }
// Always update/delete the voice maps // Always update/delete the voice maps
const target = isBot === true ? remix.observedVoiceBots : remix.observedVoiceUsers;
const voiceKey = isBot === true ? this.getObservedVoiceBotKey(userId, guildId ?? prev?.guildId) : userId;
if (channelId) { if (channelId) {
if (voiceKey) target.set(voiceKey, { channelId, guildId }); remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId, isBot: isBot === true });
} else { } else {
remix.observedVoiceUsers.delete(userId); // User left voice — remove from both human and bot indexes
if (voiceKey) remix.observedVoiceBots.delete(voiceKey); const resolvedGuildId = guildId ?? prev?.guildId;
const fallbackBotKey = this.getObservedVoiceBotKey(userId, prev?.guildId); remix.voiceCache.deleteHumanUser(userId, resolvedGuildId);
if (fallbackBotKey && fallbackBotKey !== voiceKey) remix.observedVoiceBots.delete(fallbackBotKey); remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId));
} }
const isBotUser = isBot === true && userId === client.user?.id; const isBotUser = isBot === true && userId === client.user?.id;
@@ -910,7 +881,7 @@ export class GatewayHandler {
// ── Bot-only logic below ─────────────────────────────────────────────── // ── Bot-only logic below ───────────────────────────────────────────────
const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) => const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) =>
String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
); );
const multiVoiceGuild = activeGuildPlayers.length > 1; const multiVoiceGuild = activeGuildPlayers.length > 1;
@@ -932,9 +903,9 @@ export class GatewayHandler {
if (saved247Channels.length > 1) { if (saved247Channels.length > 1) {
logger.voice247( logger.voice247(
`[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanId} ` + `[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanId} ` +
`because guild ${guildId} already has multiple saved 24/7 channels ` + `because guild ${guildId} already has multiple saved 24/7 channels ` +
`[${saved247Channels.join(", ")}]` `[${saved247Channels.join(", ")}]`
); );
return; return;
} }
@@ -957,12 +928,12 @@ export class GatewayHandler {
remix.players?._pendingJoins?.has?.(cleanId) || remix.players?._pendingJoins?.has?.(cleanId) ||
false; false;
const targetChannel = client.channels.get(cleanId) const targetChannel = client.channels.get(cleanId)
?? client.channels.get?.(cleanId) ?? client.channels.get?.(cleanId)
?? null; ?? null;
const targetGuildId = String(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? "").replace(/\D/g, ""); const targetGuildId = String(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? "").replace(/\D/g, "");
const playerGuildId = String(existingPlayer?._guildId ?? "").replace(/\D/g, ""); const playerGuildId = String(existingPlayer?._guildId ?? "").replace(/\D/g, "");
const guildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) => const guildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) =>
String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
); );
const guildIsAmbiguous = guildPlayers.length > 1; const guildIsAmbiguous = guildPlayers.length > 1;
@@ -974,8 +945,8 @@ export class GatewayHandler {
// situation we must NOT re-key the old player or rewrite stay_247, // situation we must NOT re-key the old player or rewrite stay_247,
// otherwise one saved channel gets collapsed into the newer one. // otherwise one saved channel gets collapsed into the newer one.
logger.voice247( logger.voice247(
`[247] Keeping both channels ${cleanOld} and ${cleanId} ` + `[247] Keeping both channels ${cleanOld} and ${cleanId} ` +
`(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})` `(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
); );
rekeyed = false; rekeyed = false;
} else } else
@@ -992,9 +963,9 @@ export class GatewayHandler {
if (targetGuildId) existingPlayer._guildId = targetGuildId; if (targetGuildId) existingPlayer._guildId = targetGuildId;
rekeyed = false; rekeyed = false;
logger.voice247( logger.voice247(
`[247] Updated player channel ${cleanOld} → ${cleanId} ` + `[247] Updated player channel ${cleanOld} → ${cleanId} ` +
`(guild ${guildId} has ${guildPlayers.length} active players, ` + `(guild ${guildId} has ${guildPlayers.length} active players, ` +
`new key occupied by another player — skipped re-key)` `new key occupied by another player — skipped re-key)`
); );
} else { } else {
// Safe to re-key: no collision // Safe to re-key: no collision
@@ -1005,8 +976,8 @@ export class GatewayHandler {
if (targetGuildId) existingPlayer._guildId = targetGuildId; if (targetGuildId) existingPlayer._guildId = targetGuildId;
rekeyed = true; rekeyed = true;
logger.voice247( logger.voice247(
`[247] Re-keyed playerMap ${cleanOld} → ${cleanId} ` + `[247] Re-keyed playerMap ${cleanOld} → ${cleanId} ` +
`(guild ${guildId} has ${guildPlayers.length} active players)` `(guild ${guildId} has ${guildPlayers.length} active players)`
); );
} }
} else if (playerGuildId && targetGuildId && playerGuildId !== targetGuildId) { } else if (playerGuildId && targetGuildId && playerGuildId !== targetGuildId) {
@@ -1017,8 +988,8 @@ export class GatewayHandler {
// In this case, just update the observed bot state without re-keying. // In this case, just update the observed bot state without re-keying.
if (!existingPlayer) { if (!existingPlayer) {
logger.voice247( logger.voice247(
`[247] Stale cross-guild move ${cleanOld} → ${cleanId} ` + `[247] Stale cross-guild move ${cleanOld} → ${cleanId} ` +
`(no player in playerMap for old channel — updating bot state only)` `(no player in playerMap for old channel — updating bot state only)`
); );
} else { } else {
// There IS a player in the old channel but the guilds don't match. // There IS a player in the old channel but the guilds don't match.
@@ -1040,13 +1011,13 @@ export class GatewayHandler {
remix.players.playerMap.set(cleanId, existingPlayer); remix.players.playerMap.set(cleanId, existingPlayer);
rekeyed = true; rekeyed = true;
logger.voice247( logger.voice247(
`[247] Fixed stale guild during recovery: re-keyed ${cleanOld} → ${cleanId} ` + `[247] Fixed stale guild during recovery: re-keyed ${cleanOld} → ${cleanId} ` +
`(playerGuild ${playerGuildId} → ${targetGuildId})` `(playerGuild ${playerGuildId} → ${targetGuildId})`
); );
} else { } else {
logger.warn( logger.warn(
`[247] Refused cross-guild re-key ${cleanOld} → ${cleanId} ` + `[247] Refused cross-guild re-key ${cleanOld} → ${cleanId} ` +
`(playerGuild=${playerGuildId} targetGuild=${targetGuildId})` `(playerGuild=${playerGuildId} targetGuild=${targetGuildId})`
); );
} }
} }
@@ -1070,8 +1041,8 @@ export class GatewayHandler {
if (channels.has(cleanOld) && cleanOld !== cleanId && cleanId.length >= 15) { if (channels.has(cleanOld) && cleanOld !== cleanId && cleanId.length >= 15) {
if (channels.has(cleanId) || newChannelAlreadySaved || newChannelPendingSpawn) { if (channels.has(cleanId) || newChannelAlreadySaved || newChannelPendingSpawn) {
logger.voice247( logger.voice247(
`[247] Preserved stay_247 channels ${cleanOld} and ${cleanId} ` + `[247] Preserved stay_247 channels ${cleanOld} and ${cleanId} ` +
`(saved=${channels.has(cleanId) || newChannelAlreadySaved} pending=${newChannelPendingSpawn})` `(saved=${channels.has(cleanId) || newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
); );
return; return;
} }
@@ -1119,7 +1090,7 @@ export class GatewayHandler {
if (mode === "auto") { if (mode === "auto") {
logger.voice247( logger.voice247(
`[VoiceState] Bot unexpectedly disconnected from ${cleanOld} (24/7 auto) — cleaning up and scheduling rejoin.` `[VoiceState] Bot unexpectedly disconnected from ${cleanOld} (24/7 auto) — cleaning up and scheduling rejoin.`
); );
const player = remix.players.playerMap.get(cleanOld); const player = remix.players.playerMap.get(cleanOld);
if (player && !player._destroyed) { if (player && !player._destroyed) {
@@ -1153,7 +1124,7 @@ export class GatewayHandler {
const player = remix.players.playerMap.get(cleanOld); const player = remix.players.playerMap.get(cleanOld);
if (player && !player.leaving && !player._destroyed) { if (player && !player.leaving && !player._destroyed) {
logger.voiceState( logger.voiceState(
`[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.` `[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.`
); );
player.emit("autoleave"); player.emit("autoleave");
} }
@@ -1233,7 +1204,7 @@ export class GatewayHandler {
const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES; const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES;
logger.voice247( logger.voice247(
`[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId} (attempt ${attempt}/${maxRetries})...` `[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId} (attempt ${attempt}/${maxRetries})...`
); );
try { try {
@@ -1256,8 +1227,8 @@ export class GatewayHandler {
// Retry with exponential backoff: 5s, 10s, 20s // Retry with exponential backoff: 5s, 10s, 20s
const backoffMs = 5_000 * Math.pow(2, attempt - 1); const backoffMs = 5_000 * Math.pow(2, attempt - 1);
logger.voice247( logger.voice247(
`[Rejoin] Track publication failed for channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}) — ` + `[Rejoin] Track publication failed for channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}) — ` +
`retrying in ${backoffMs / 1000}s: ${errMsg}` `retrying in ${backoffMs / 1000}s: ${errMsg}`
); );
this._rejoinInProgress.delete(cleanChannelId); this._rejoinInProgress.delete(cleanChannelId);
@@ -1267,7 +1238,7 @@ export class GatewayHandler {
} }
logger.warn( logger.warn(
`[Rejoin] Failed to rejoin channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}): ${errMsg}` `[Rejoin] Failed to rejoin channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}): ${errMsg}`
); );
this._rejoinAttempts.delete(cleanChannelId); this._rejoinAttempts.delete(cleanChannelId);
@@ -1300,8 +1271,8 @@ export class GatewayHandler {
const pending = this._deferredGuildDeletes.size; const pending = this._deferredGuildDeletes.size;
if (pending > 0) { if (pending > 0) {
logger.guild( logger.guild(
`[GuildDelete] Startup grace period ended. ` + `[GuildDelete] Startup grace period ended. ` +
`${pending} deferred deletion(s) confirmed — cleaning up.` `${pending} deferred deletion(s) confirmed — cleaning up.`
); );
} else { } else {
logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`); logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`);
@@ -1309,7 +1280,7 @@ export class GatewayHandler {
// Log suppressed count if we had more than 3 deferred deletes // Log suppressed count if we had more than 3 deferred deletes
if (this._deferredDeleteCount > 3) { if (this._deferredDeleteCount > 3) {
logger.guild( logger.guild(
`[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)` `[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)`
); );
} }
}, this._startupDeleteGraceMs); }, this._startupDeleteGraceMs);
@@ -1357,8 +1328,8 @@ export class GatewayHandler {
} }
logger.voice247( logger.voice247(
`[BootRecovery] Found ${channelsToRejoin.length} 24/7 channel(s) to rejoin: ` + `[BootRecovery] Found ${channelsToRejoin.length} 24/7 channel(s) to rejoin: ` +
channelsToRejoin.map(c => `${c.channelId}(${c.mode})`).join(", ") channelsToRejoin.map(c => `${c.channelId}(${c.mode})`).join(", ")
); );
const baseStagger = remix.config?.timers?.bootRejoinStagger ?? 5_000; const baseStagger = remix.config?.timers?.bootRejoinStagger ?? 5_000;
@@ -1386,7 +1357,7 @@ export class GatewayHandler {
} }
logger.voice247( logger.voice247(
`[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` `[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]`
); );
const BOOT_MAX_RETRIES = 3; const BOOT_MAX_RETRIES = 3;
@@ -1401,8 +1372,8 @@ export class GatewayHandler {
this.reseedVoiceStatesForChannel(guildId, channelId); this.reseedVoiceStatesForChannel(guildId, channelId);
logger.voice247( logger.voice247(
`[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` + `[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` +
(bootRetries > 0 ? ` (after ${bootRetries} retry/retries)` : '') (bootRetries > 0 ? ` (after ${bootRetries} retry/retries)` : '')
); );
break; // success — move to next channel break; // success — move to next channel
} catch (err) { } catch (err) {
@@ -1416,16 +1387,16 @@ export class GatewayHandler {
if (isTrackTimeout && bootRetries < BOOT_MAX_RETRIES) { if (isTrackTimeout && bootRetries < BOOT_MAX_RETRIES) {
const backoffMs = BOOT_BASE_RETRY_MS * Math.pow(2, bootRetries - 1); const backoffMs = BOOT_BASE_RETRY_MS * Math.pow(2, bootRetries - 1);
logger.warn( logger.warn(
`[BootRecovery] Track publication failed for channel ${channelId} (attempt ${bootRetries}/${BOOT_MAX_RETRIES}) — ` + `[BootRecovery] Track publication failed for channel ${channelId} (attempt ${bootRetries}/${BOOT_MAX_RETRIES}) — ` +
`retrying in ${backoffMs / 1000}s: ${errMsg}` `retrying in ${backoffMs / 1000}s: ${errMsg}`
); );
await new Promise(resolve => setTimeout(resolve, backoffMs)); await new Promise(resolve => setTimeout(resolve, backoffMs));
continue; continue;
} }
logger.warn( logger.warn(
`[BootRecovery] Failed to rejoin channel ${channelId} (mode: ${mode}): ${errMsg}` + `[BootRecovery] Failed to rejoin channel ${channelId} (mode: ${mode}): ${errMsg}` +
(bootRetries > 1 ? ` (after ${bootRetries} attempts)` : '') (bootRetries > 1 ? ` (after ${bootRetries} attempts)` : '')
); );
// Auto-cleanup: if all retries exhausted due to track publication // Auto-cleanup: if all retries exhausted due to track publication
@@ -1437,20 +1408,20 @@ export class GatewayHandler {
if (set) { if (set) {
const raw = set.get("stay_247"); const raw = set.get("stay_247");
const channels = new Set( const channels = new Set(
(Array.isArray(raw) ? raw : [raw]) (Array.isArray(raw) ? raw : [raw])
.filter(id => id && id !== "none" && String(id).replace(/\D/g, "") !== channelId) .filter(id => id && id !== "none" && String(id).replace(/\D/g, "") !== channelId)
); );
set.set("stay_247", channels.size > 0 ? [...channels] : "none"); set.set("stay_247", channels.size > 0 ? [...channels] : "none");
remove247ChannelMode(set, channelId, channels); remove247ChannelMode(set, channelId, channels);
logger.warn( logger.warn(
`[BootRecovery] Auto-removed channel ${channelId} from 24/7 ` + `[BootRecovery] Auto-removed channel ${channelId} from 24/7 ` +
`in guild ${guildId} after persistent track publication failure` `in guild ${guildId} after persistent track publication failure`
); );
} }
} catch (cleanupErr) { } catch (cleanupErr) {
logger.error( logger.error(
`[BootRecovery] Failed to auto-remove channel ${channelId} from 24/7:`, `[BootRecovery] Failed to auto-remove channel ${channelId} from 24/7:`,
cleanupErr?.message ?? cleanupErr cleanupErr?.message ?? cleanupErr
); );
} }
} }
@@ -1461,7 +1432,7 @@ export class GatewayHandler {
} }
logger.voice247( logger.voice247(
`[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.` `[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.`
); );
} }
@@ -1499,8 +1470,8 @@ export class GatewayHandler {
// Keep the player alive — the guild will come back via GuildCreate. // Keep the player alive — the guild will come back via GuildCreate.
if (!batchMode) { if (!batchMode) {
logger.guild( logger.guild(
`[GuildDelete] Preserving 24/7 player for channel ${channelId} ` + `[GuildDelete] Preserving 24/7 player for channel ${channelId} ` +
`(LiveKit room still connected — guild ${cleanGuildId} likely temporarily unavailable).` `(LiveKit room still connected — guild ${cleanGuildId} likely temporarily unavailable).`
); );
} }
continue; continue;
@@ -1512,12 +1483,7 @@ export class GatewayHandler {
if (!batchMode) logger.guild(`[GuildDelete] Destroyed player for channel ${channelId}.`); if (!batchMode) logger.guild(`[GuildDelete] Destroyed player for channel ${channelId}.`);
} }
for (const [userId, info] of [...remix.observedVoiceUsers]) { remix.voiceCache.removeGuild(cleanGuildId);
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]) { for (const [stateKey, info] of [...this._prevVoiceState]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) if (String(info.guildId).replace(/\D/g, "") === cleanGuildId)
this._prevVoiceState.delete(stateKey); this._prevVoiceState.delete(stateKey);
+31 -18
View File
@@ -327,6 +327,7 @@ export default class Player extends EventEmitter {
// searches Map with max-size eviction to prevent memory leak on busy servers. // searches Map with max-size eviction to prevent memory leak on busy servers.
searches = new Map(); searches = new Map();
_searchMaxSize = 50; _searchMaxSize = 50;
_maxQueueSize = 10_000; // Max tracks in queue to prevent unbounded memory growth
resultLimit = 5; resultLimit = 5;
preferredVolume = 1; preferredVolume = 1;
@@ -370,6 +371,7 @@ export default class Player extends EventEmitter {
this.settings = opts.settings ?? null; this.settings = opts.settings ?? null;
this.settingsMgr = opts.settingsMgr ?? null; this.settingsMgr = opts.settingsMgr ?? null;
this._observedVoiceUsers = opts.observedVoiceUsers ?? null; this._observedVoiceUsers = opts.observedVoiceUsers ?? null;
this._voiceCache = opts.voiceCache ?? null;
this.locale = opts.locale ?? null; this.locale = opts.locale ?? null;
// Merge NodeLink config (for stream URL building) // Merge NodeLink config (for stream URL building)
@@ -524,25 +526,34 @@ export default class Player extends EventEmitter {
if (!this._channelId || !this._guildId) return false; if (!this._channelId || !this._guildId) return false;
const cleanChan = String(this._channelId).replace(/\D/g, ""); const cleanChan = String(this._channelId).replace(/\D/g, "");
const cleanGuild = String(this._guildId).replace(/\D/g, ""); const cleanGuild = String(this._guildId).replace(/\D/g, "");
// O(1) lookup via VoiceStateCache channelMembers index
if (this._voiceCache && this._voiceCache.hasHumansInChannel(cleanGuild, cleanChan)) {
return true;
}
// Legacy fallback: iterate observedVoiceUsers (O(n))
try { try {
const voiceUsers = this._observedVoiceUsers; const voiceUsers = this._observedVoiceUsers;
if (voiceUsers) { if (voiceUsers && typeof voiceUsers.iterateHumanUsers === "function") {
for ( const [, info] of voiceUsers) { for (const [, info] of voiceUsers.iterateHumanUsers()) {
if (
String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild &&
String(info.channelId ?? "").replace(/\D/g, "") === cleanChan
) return true;
}
} else if (voiceUsers) {
// Raw Map fallback (shouldn't happen with new code)
for (const [, info] of voiceUsers) {
if ( if (
String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild && String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild &&
String(info.channelId ?? "").replace(/\D/g, "") === cleanChan String(info.channelId ?? "").replace(/\D/g, "") === cleanChan
) return true; ) return true;
} }
// Don't return false here — fall through to guild voice_states
// fallback in case observedVoiceUsers hasn't been populated yet
// (e.g., right after bot restart before reseed completes).
} }
} catch (_) {} } catch (_) {}
try { try {
// @fluxerjs channels do NOT have a .members property.
// Use the guild's member manager and filter by voice state instead.
const guild = this.client?.guilds?.get?.(this._guildId); const guild = this.client?.guilds?.get?.(this._guildId);
// Iterate raw voice_states on the guild object.
const voiceStates = guild?.voice_states; const voiceStates = guild?.voice_states;
if (voiceStates) { if (voiceStates) {
const entries = Array.isArray(voiceStates) const entries = Array.isArray(voiceStates)
@@ -554,7 +565,6 @@ export default class Player extends EventEmitter {
const stateChannelId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, ""); const stateChannelId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
if (stateChannelId === cleanChan) { if (stateChannelId === cleanChan) {
const userId = String(state?.userId ?? state?.user_id ?? ""); const userId = String(state?.userId ?? state?.user_id ?? "");
// Check if user is a bot — look up via members or observedVoiceUsers
const member = guild?.members?.get?.(userId); const member = guild?.members?.get?.(userId);
const isBot = member?.user?.bot ?? false; const isBot = member?.user?.bot ?? false;
if (!isBot) return true; if (!isBot) return true;
@@ -563,19 +573,11 @@ export default class Player extends EventEmitter {
} }
} catch (_) {} } catch (_) {}
// ── LiveKit participant fallback ────────────────────────────────────── // LiveKit participant fallback
// If the above methods didn't find any humans (e.g., because
// voice_states cache is empty and observedVoiceUsers hasn't been
// populated yet after a restart), check the LiveKit room's remote
// participants. This is the most reliable source of truth for who's
// actually in the voice channel, since LiveKit knows about every
// connected participant regardless of gateway cache state.
try { try {
const room = this.connection?.room; const room = this.connection?.room;
if (room?.isConnected && room.remoteParticipants) { if (room?.isConnected && room.remoteParticipants) {
for (const [, participant] of room.remoteParticipants) { for (const [, participant] of room.remoteParticipants) {
// Remote participants in the LiveKit room are humans (the bot is
// the local participant). If there's at least one, humans are present.
if (participant?.identity || participant?.sid) { if (participant?.identity || participant?.sid) {
return true; return true;
} }
@@ -1590,6 +1592,11 @@ export default class Player extends EventEmitter {
isEmpty() { return this.queue.isEmpty(); } isEmpty() { return this.queue.isEmpty(); }
addToQueue(d, t) { addToQueue(d, t) {
// Enforce queue size cap to prevent unbounded memory growth
if (this.queue.data.length >= this._maxQueueSize) {
logger.warn(`[Player] Queue size cap reached (${this._maxQueueSize}) — dropping oldest track`);
this.queue.data.shift();
}
this.queue.add(d, t); this.queue.add(d, t);
this.emit("update", "queue"); this.emit("update", "queue");
this._stopInactivityTimer(); this._stopInactivityTimer();
@@ -1604,6 +1611,12 @@ export default class Player extends EventEmitter {
} }
addManyToQueue(t, top = false) { addManyToQueue(t, top = false) {
// Enforce queue size cap
const overflow = (this.queue.data.length + t.length) - this._maxQueueSize;
if (overflow > 0) {
logger.warn(`[Player] Queue size cap (${this._maxQueueSize}) — dropping ${overflow} oldest tracks`);
this.queue.data.splice(0, overflow);
}
const added = this.queue.addMany(t, top); const added = this.queue.addMany(t, top);
this.emit("update", "queue"); this.emit("update", "queue");
this._stopInactivityTimer(); this._stopInactivityTimer();
+114 -17
View File
@@ -81,9 +81,12 @@ export class PlayerManager {
/** @type {CommandHandler} */ /** @type {CommandHandler} */
commands; commands;
/** @type {Map<string, Player>} */ /** @type {Map<string, Player>} Keyed by cleaned channel ID */
playerMap = new Map(); playerMap = new Map();
/** @type {Map<string, Set<string>>} Reverse index: guildId → Set<channelId> for O(1) guild lookups */
_guildPlayerIndex = new Map();
/** @type {Set<string>} Channel IDs currently being joined (not yet in playerMap) */ /** @type {Set<string>} Channel IDs currently being joined (not yet in playerMap) */
_pendingJoins = new Set(); _pendingJoins = new Set();
@@ -121,6 +124,94 @@ export class PlayerManager {
this._lastfm = null; // Set later by Remix class after init this._lastfm = null; // Set later by Remix class after init
} }
// ═══════════════════════════════════════════════════════════════════════════
// Guild→Player Reverse Index — O(1) lookups instead of O(n) scans
// ═══════════════════════════════════════════════════════════════════════════
/**
* Add a channel to the guild→player reverse index.
* Called after a successful player join.
* @param {string} guildId
* @param {string} channelId
*/
_indexPlayer(guildId, channelId) {
const gId = cleanId(guildId);
const cId = cleanId(channelId);
if (!gId || !cId) return;
let set = this._guildPlayerIndex.get(gId);
if (!set) { set = new Set(); this._guildPlayerIndex.set(gId, set); }
set.add(cId);
}
/**
* Remove a channel from the guild→player reverse index.
* Called on player leave/destroy.
* @param {string} guildId
* @param {string} channelId
*/
_unindexPlayer(guildId, channelId) {
const gId = cleanId(guildId);
const cId = cleanId(channelId);
if (!gId) return;
const set = this._guildPlayerIndex.get(gId);
if (set) {
set.delete(cId);
if (set.size === 0) this._guildPlayerIndex.delete(gId);
}
}
/**
* Get all [channelId, Player] entries for a guild.
* Uses the reverse index for O(1) guild lookup instead of O(n) scan.
* @param {string} guildId
* @returns {Array<[string, Player]>}
*/
getGuildPlayers(guildId) {
const gId = cleanId(guildId);
const set = this._guildPlayerIndex.get(gId);
if (!set) return [];
const result = [];
for (const channelId of set) {
const player = this.playerMap.get(channelId);
if (player && !player._destroyed) {
result.push([channelId, player]);
}
}
return result;
}
/**
* Find a player by guildId and channelId using the reverse index.
* @param {string} guildId
* @param {string} channelId
* @returns {Player|null}
*/
getPlayerByGuildAndChannel(guildId, channelId) {
const cId = cleanId(channelId);
const players = this.getGuildPlayers(guildId);
for (const [mapChannelId, player] of players) {
if (getPlayerChannelId(player, mapChannelId) === cId) return player;
}
return null;
}
/**
* Find a player by channelId alone (scans guild index first, then fallback).
* @param {string} channelId
* @returns {Player|null}
*/
getPlayerByChannelId(channelId) {
const cId = cleanId(channelId);
// Try all guild indexes
for (const [, channelSet] of this._guildPlayerIndex) {
for (const mapChannelId of channelSet) {
const player = this.playerMap.get(mapChannelId);
if (player && getPlayerChannelId(player, mapChannelId) === cId) return player;
}
}
return null;
}
/** /**
* Forward player lifecycle/state events to the dashboard pub/sub channels. * Forward player lifecycle/state events to the dashboard pub/sub channels.
* *
@@ -502,9 +593,7 @@ export class PlayerManager {
if (cleanUserChannelId) { if (cleanUserChannelId) {
const player = this.playerMap.get(cleanUserChannelId) const player = this.playerMap.get(cleanUserChannelId)
?? [...this.playerMap.values()].find(p => ?? this.getPlayerByGuildAndChannel(cleanGuildId, cleanUserChannelId);
getPlayerChannelId(p) === cleanUserChannelId
);
if (player) { if (player) {
player.textChannel = message.channel; player.textChannel = message.channel;
try { try {
@@ -523,9 +612,7 @@ export class PlayerManager {
} }
const serverPlayers = cleanGuildId const serverPlayers = cleanGuildId
? [...this.playerMap.entries()].filter(([, player]) => { ? this.getGuildPlayers(cleanGuildId)
return getPlayerGuildId(player) === cleanGuildId;
})
: []; : [];
if (serverPlayers.length > 0) { if (serverPlayers.length > 0) {
@@ -544,7 +631,7 @@ export class PlayerManager {
} }
const match = serverPlayers.find(([, player]) => const match = serverPlayers.find(([, player]) =>
String(player?._channelId ?? "").replace(/\D/g, "") === cleanUserChannelId getPlayerChannelId(player) === cleanUserChannelId
); );
if (match) { if (match) {
match[1].textChannel = message.channel; match[1].textChannel = message.channel;
@@ -697,22 +784,24 @@ export class PlayerManager {
if (!cid) { if (!cid) {
const guildId = getMessageGuildId(msg); const guildId = getMessageGuildId(msg);
if (guildId) { if (guildId) {
const matchedEntry = [...this.playerMap.entries()].find(([, player]) => const guildPlayers = this.getGuildPlayers(cleanId(guildId));
getPlayerGuildId(player) === cleanId(guildId) if (guildPlayers.length > 0) {
); const [, firstPlayer] = guildPlayers[0];
cid = getPlayerChannelId(matchedEntry?.[1], matchedEntry?.[0]) || matchedEntry?.[0] || null; cid = getPlayerChannelId(firstPlayer, guildPlayers[0][0]) || guildPlayers[0][0];
}
} }
} }
const cleanChannelId = cleanId(cid); const cleanChannelId = cleanId(cid);
const player = cleanChannelId const player = cleanChannelId
? this.playerMap.get(cleanChannelId) ?? ? this.playerMap.get(cleanChannelId) ??
[...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId) this.getPlayerByChannelId(cleanChannelId)
: null; : null;
if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice"))); if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice")));
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
this.playerMap.delete(activeChannelId); this.playerMap.delete(activeChannelId);
this._unindexPlayer(player._guildId, activeChannelId);
// Clean up pending scrobble timer // Clean up pending scrobble timer
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId); const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); } if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
@@ -749,7 +838,7 @@ export class PlayerManager {
const cleanChannelId = cleanId(cid); const cleanChannelId = cleanId(cid);
const existing = this.playerMap.get(cleanChannelId) const existing = this.playerMap.get(cleanChannelId)
?? [...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId); ?? this.getPlayerByChannelId(cleanChannelId);
if (existing) { if (existing) {
existing.textChannel = message.channel; existing.textChannel = message.channel;
cb(existing); cb(existing);
@@ -769,6 +858,7 @@ export class PlayerManager {
revoice: this.playerConfig?.revoice ?? null, revoice: this.playerConfig?.revoice ?? null,
settingsMgr: this.settings, settingsMgr: this.settings,
observedVoiceUsers: this.observedVoiceUsers ?? null, observedVoiceUsers: this.observedVoiceUsers ?? null,
voiceCache: this.voiceCache ?? null,
locale: this.locale ?? null, locale: this.locale ?? null,
}); });
@@ -808,6 +898,7 @@ export class PlayerManager {
// Remove player from map and destroy // Remove player from map and destroy
this.playerMap.delete(activeChannelId); this.playerMap.delete(activeChannelId);
this._unindexPlayer(player._guildId, activeChannelId);
// Clean up pending scrobble timer // Clean up pending scrobble timer
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId); const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); } if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
@@ -862,6 +953,7 @@ export class PlayerManager {
// Only add to playerMap after join succeeds — this prevents phantom // Only add to playerMap after join succeeds — this prevents phantom
// entries from inflating the player count. // entries from inflating the player count.
this.playerMap.set(cleanChannelId, player); this.playerMap.set(cleanChannelId, player);
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
this._pendingJoins.delete(cleanChannelId); this._pendingJoins.delete(cleanChannelId);
await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid }))); await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid })));
@@ -892,6 +984,7 @@ export class PlayerManager {
} }
await statusMsg.edit(mkEmbed(errorMsg)).catch(() => {}); await statusMsg.edit(mkEmbed(errorMsg)).catch(() => {});
this.playerMap.delete(cleanChannelId); this.playerMap.delete(cleanChannelId);
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
player.destroy(); player.destroy();
} }
})(); })();
@@ -920,9 +1013,13 @@ export class PlayerManager {
const channelId = getPlayerChannelId(player); const channelId = getPlayerChannelId(player);
const humanUserIds = []; const humanUserIds = [];
// Check observedVoiceUsers first // Use VoiceStateCache O(1) channel index instead of iterating all users
if (this.observedVoiceUsers) { if (this.voiceCache) {
for (const [uid, info] of this.observedVoiceUsers) { const users = this.voiceCache.getHumansInChannel(guildId, channelId);
humanUserIds.push(...users);
} else if (this.observedVoiceUsers) {
// Legacy fallback
for (const [uid, info] of this.observedVoiceUsers.iterateHumanUsers()) {
if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) { if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) {
humanUserIds.push(uid); humanUserIds.push(uid);
} }
+24 -5
View File
@@ -123,12 +123,25 @@ export class FluxerVoiceConnection extends EventEmitter {
channelId = null; channelId = null;
_voice = null; // parent FluxerRevoice instance _voice = null; // parent FluxerRevoice instance
_connected = false; // internal flag, set by events _connected = false; // internal flag, set by events
users = []; _users = []; // internal, derived from parent FluxerRevoice.users
_destroyed = false; _destroyed = false;
// @fluxerjs/voice native connection reference (for proper disconnect) // @fluxerjs/voice native connection reference (for proper disconnect)
_nativeConn = null; _nativeConn = null;
/**
* Users currently in this voice channel.
* Derived from the parent FluxerRevoice's unified users map (single source of truth).
* This prevents the old divergence bug where the array and Map could get out of sync.
*/
get users() {
return this._users;
}
set users(val) {
this._users = Array.isArray(val) ? val : [];
}
constructor(channelId, voice, opts = {}) { constructor(channelId, voice, opts = {}) {
super(); super();
this.channelId = channelId; this.channelId = channelId;
@@ -223,6 +236,8 @@ export class FluxerRevoice extends EventEmitter {
/** @type {import("@fluxerjs/core").Client} */ /** @type {import("@fluxerjs/core").Client} */
client = null; client = null;
connections = new Map(); connections = new Map();
// Unified users map: keyed by "channelId:userId", value is { id, connectedTo }
// This is the single source of truth; connection.users is derived from it.
users = new Map(); users = new Map();
/** @type {Map<string, Promise>} */ /** @type {Map<string, Promise>} */
@@ -628,8 +643,10 @@ export class FluxerRevoice extends EventEmitter {
room.on(RoomEvent.ParticipantConnected, (participant) => { room.on(RoomEvent.ParticipantConnected, (participant) => {
const userId = participant?.identity ?? participant?.sid; const userId = participant?.identity ?? participant?.sid;
if (userId) { if (userId) {
connection.users.push({ id: userId, connectedTo: channelId }); const uKey = `${channelId}:${userId}`;
this.users.set(userId, { id: userId, connectedTo: channelId }); this.users.set(uKey, { id: userId, connectedTo: channelId });
// Derive connection.users from the unified map (single source of truth)
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
connection.emit("userjoin", userId); connection.emit("userjoin", userId);
} }
}); });
@@ -637,8 +654,10 @@ export class FluxerRevoice extends EventEmitter {
room.on(RoomEvent.ParticipantDisconnected, (participant) => { room.on(RoomEvent.ParticipantDisconnected, (participant) => {
const userId = participant?.identity ?? participant?.sid; const userId = participant?.identity ?? participant?.sid;
if (userId) { if (userId) {
connection.users = connection.users.filter(u => u.id !== userId); const uKey = `${channelId}:${userId}`;
this.users.delete(userId); this.users.delete(uKey);
// Derive connection.users from the unified map
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
connection.emit("userleave", userId); connection.emit("userleave", userId);
} }
}); });
+518
View File
@@ -0,0 +1,518 @@
/**
* VoiceStateCache — O(1) voice-state lookups with bounded memory.
*
* Replaces the raw `observedVoiceUsers` / `observedVoiceBots` Maps with a
* composite-keyed, indexed, LRU-evicted cache that supports:
*
* • O(1) lookup: "is anyone in channel X?" → channelMembers.get(guildId, channelId)
* • O(1) lookup: "what channel is user X in?" → userLocations.get(guildId, userId)
* • O(1) lookup: "how many humans in channel X?" → channelMembers.get(...).size
* • Bounded memory via LRU eviction (default 50 000 entries)
* • Composite keys (guildId:userId) so multi-guild users don't overwrite
* • Single update function used by both raw WS and high-level handlers
*
* Data structures:
* userLocations — Map<"guildId:userId", {channelId, guildId, userId}>
* channelMembers — Map<"guildId:channelId", Set<userId>>
* botLocations — Map<"guildId:userId", {channelId, guildId, userId}>
* botChannelMembers — Map<"guildId:channelId", Set<userId>>
* _lruOrder — String[] (most-recently-updated keys, for eviction)
*/
import { logger } from "./Logger.mjs";
export class VoiceStateCache {
/**
* @param {object} [opts]
* @param {number} [opts.maxUsers=50000] Max human entries before LRU eviction
* @param {number} [opts.maxBots=10000] Max bot entries before LRU eviction
*/
constructor(opts = {}) {
// ── Human users ──────────────────────────────────────────────────────
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
this.userLocations = new Map();
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
this.channelMembers = new Map();
// ── Bot users ────────────────────────────────────────────────────────
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
this.botLocations = new Map();
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
this.botChannelMembers = new Map();
// ── LRU tracking ─────────────────────────────────────────────────────
this._maxUsers = opts.maxUsers ?? 50_000;
this._maxBots = opts.maxBots ?? 10_000;
/** @type {string[]} MRU-first list of user location keys */
this._lruUserKeys = [];
/** @type {string[]} MRU-first list of bot location keys */
this._lruBotKeys = [];
}
// ── Key helpers ──────────────────────────────────────────────────────────
/** Build composite key "guildId:userId" (both cleaned to digits only) */
static userKey(guildId, userId) {
return `${String(guildId ?? "").replace(/\D/g, "")}:${String(userId ?? "").replace(/\D/g, "")}`;
}
/** Build composite key "guildId:channelId" (both cleaned to digits only) */
static channelKey(guildId, channelId) {
return `${String(guildId ?? "").replace(/\D/g, "")}:${String(channelId ?? "").replace(/\D/g, "")}`;
}
// ── Core update (unified — called by both raw WS and high-level handler) ─
/**
* Update voice state for a user.
*
* @param {object} params
* @param {string} params.guildId
* @param {string} params.userId
* @param {string|null} params.channelId null = user left voice
* @param {boolean} [params.isBot=false]
*/
updateUser({ guildId, userId, channelId, isBot = false }) {
const cleanGuild = String(guildId ?? "").replace(/\D/g, "");
const cleanUser = String(userId ?? "").replace(/\D/g, "");
const cleanChannel = channelId ? String(channelId).replace(/\D/g, "") : null;
if (!cleanGuild || !cleanUser) return;
const locations = isBot ? this.botLocations : this.userLocations;
const channelIdx = isBot ? this.botChannelMembers : this.channelMembers;
const maxEntries = isBot ? this._maxBots : this._maxUsers;
const lruKeys = isBot ? this._lruBotKeys : this._lruUserKeys;
const uKey = VoiceStateCache.userKey(cleanGuild, cleanUser);
// ── Remove from previous channel index ───────────────────────────────
const prev = locations.get(uKey);
if (prev) {
const prevCKey = VoiceStateCache.channelKey(prev.guildId, prev.channelId);
const prevSet = channelIdx.get(prevCKey);
if (prevSet) {
prevSet.delete(cleanUser);
if (prevSet.size === 0) channelIdx.delete(prevCKey);
}
}
if (cleanChannel) {
// ── Add to new channel index ───────────────────────────────────────
const cKey = VoiceStateCache.channelKey(cleanGuild, cleanChannel);
let set = channelIdx.get(cKey);
if (!set) { set = new Set(); channelIdx.set(cKey, set); }
set.add(cleanUser);
// ── Update location map ────────────────────────────────────────────
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
// ── LRU: move to front ─────────────────────────────────────────────
const idx = lruKeys.indexOf(uKey);
if (idx !== -1) lruKeys.splice(idx, 1);
lruKeys.unshift(uKey);
// ── Evict if over cap ──────────────────────────────────────────────
while (lruKeys.length > maxEntries) {
const evictKey = lruKeys.pop();
if (evictKey === uKey) continue; // don't evict the entry we just added
const evicted = locations.get(evictKey);
if (evicted) {
const evictCKey = VoiceStateCache.channelKey(evicted.guildId, evicted.channelId);
const evictSet = channelIdx.get(evictCKey);
if (evictSet) {
evictSet.delete(evicted.userId);
if (evictSet.size === 0) channelIdx.delete(evictCKey);
}
locations.delete(evictKey);
}
}
} else {
// ── User left voice — remove from location map ─────────────────────
locations.delete(uKey);
// Remove from LRU list
const idx = lruKeys.indexOf(uKey);
if (idx !== -1) lruKeys.splice(idx, 1);
}
}
// ── Query methods ────────────────────────────────────────────────────────
/**
* Check if there are any human users in a specific channel.
* O(1) via channelMembers index.
*
* @param {string} guildId
* @param {string} channelId
* @returns {boolean}
*/
hasHumansInChannel(guildId, channelId) {
const cKey = VoiceStateCache.channelKey(guildId, channelId);
const set = this.channelMembers.get(cKey);
return set ? set.size > 0 : false;
}
/**
* Get the number of human users in a specific channel.
* O(1) via channelMembers index.
*
* @param {string} guildId
* @param {string} channelId
* @returns {number}
*/
getHumanCount(guildId, channelId) {
const cKey = VoiceStateCache.channelKey(guildId, channelId);
const set = this.channelMembers.get(cKey);
return set ? set.size : 0;
}
/**
* Get all human userIds in a specific channel.
* O(1) lookup + Set iteration.
*
* @param {string} guildId
* @param {string} channelId
* @returns {string[]}
*/
getHumansInChannel(guildId, channelId) {
const cKey = VoiceStateCache.channelKey(guildId, channelId);
const set = this.channelMembers.get(cKey);
return set ? [...set] : [];
}
/**
* Get the channelId a human user is currently in (within a specific guild).
* O(1) via userLocations index.
*
* @param {string} guildId
* @param {string} userId
* @returns {string|null}
*/
getUserChannel(guildId, userId) {
const uKey = VoiceStateCache.userKey(guildId, userId);
const loc = this.userLocations.get(uKey);
return loc ? loc.channelId : null;
}
/**
* Check if a human user is tracked in a specific guild.
*
* @param {string} guildId
* @param {string} userId
* @returns {boolean}
*/
hasUser(guildId, userId) {
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
}
/**
* Get user location info (channelId, guildId) for a human user.
*
* @param {string} guildId
* @param {string} userId
* @returns {{channelId: string, guildId: string, userId: string}|undefined}
*/
getUserLocation(guildId, userId) {
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
}
/**
* Seed a user into the cache (only if not already present).
*
* @param {string} guildId
* @param {string} userId
* @param {string} channelId
* @param {boolean} [isBot=false]
*/
seedUser(guildId, userId, channelId, isBot = false) {
const uKey = VoiceStateCache.userKey(guildId, userId);
const locations = isBot ? this.botLocations : this.userLocations;
if (locations.has(uKey)) return; // already tracked — don't overwrite
this.updateUser({ guildId, userId, channelId, isBot });
}
// ── Bulk operations ──────────────────────────────────────────────────────
/**
* Remove all entries for a specific guild (used on GuildDelete).
*
* @param {string} guildId
*/
removeGuild(guildId) {
const cleanGuild = String(guildId).replace(/\D/g, "");
const prefix = cleanGuild + ":";
// Humans
for (const [uKey, loc] of this.userLocations) {
if (uKey.startsWith(prefix)) {
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
const set = this.channelMembers.get(cKey);
if (set) { set.delete(loc.userId); if (set.size === 0) this.channelMembers.delete(cKey); }
this.userLocations.delete(uKey);
}
}
// Clean up channel member sets for this guild
for (const [cKey, set] of this.channelMembers) {
if (cKey.startsWith(prefix)) this.channelMembers.delete(cKey);
}
// Clean LRU
this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix));
// Bots
for (const [uKey, loc] of this.botLocations) {
if (uKey.startsWith(prefix)) {
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
const set = this.botChannelMembers.get(cKey);
if (set) { set.delete(loc.userId); if (set.size === 0) this.botChannelMembers.delete(cKey); }
this.botLocations.delete(uKey);
}
}
for (const [cKey, set] of this.botChannelMembers) {
if (cKey.startsWith(prefix)) this.botChannelMembers.delete(cKey);
}
this._lruBotKeys = this._lruBotKeys.filter(k => !k.startsWith(prefix));
}
/**
* Remove a specific channel's index entries (used when a player leaves).
*
* @param {string} guildId
* @param {string} channelId
*/
removeChannel(guildId, channelId) {
const cKey = VoiceStateCache.channelKey(guildId, channelId);
// Humans
const humanSet = this.channelMembers.get(cKey);
if (humanSet) {
for (const userId of humanSet) {
const uKey = VoiceStateCache.userKey(guildId, userId);
const loc = this.userLocations.get(uKey);
// Only delete if the user is still in THIS channel (not moved)
if (loc && loc.channelId === String(channelId).replace(/\D/g, "")) {
this.userLocations.delete(uKey);
}
}
this.channelMembers.delete(cKey);
}
// Bots
const botSet = this.botChannelMembers.get(cKey);
if (botSet) {
for (const userId of botSet) {
const uKey = VoiceStateCache.userKey(guildId, userId);
const loc = this.botLocations.get(uKey);
if (loc && loc.channelId === String(channelId).replace(/\D/g, "")) {
this.botLocations.delete(uKey);
}
}
this.botChannelMembers.delete(cKey);
}
}
/**
* Selectively remove entries for users whose IDs appear in a given set
* (used during GuildCreate to purge stale entries being replaced).
*
* @param {string} guildId
* @param {Set<string>} userIds User IDs whose entries should be purged
* @param {boolean} [botsOnly=false] Only purge bot entries
*/
purgeUsersInGuild(guildId, userIds, botsOnly = false) {
const cleanGuild = String(guildId).replace(/\D/g, "");
if (!botsOnly) {
// Purge human entries
for (const userId of userIds) {
const uKey = VoiceStateCache.userKey(cleanGuild, userId);
const loc = this.userLocations.get(uKey);
if (loc) {
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
const set = this.channelMembers.get(cKey);
if (set) { set.delete(loc.userId); if (set.size === 0) this.channelMembers.delete(cKey); }
this.userLocations.delete(uKey);
}
}
}
// Purge bot entries
for (const userId of userIds) {
const uKey = VoiceStateCache.userKey(cleanGuild, userId);
const loc = this.botLocations.get(uKey);
if (loc) {
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
const set = this.botChannelMembers.get(cKey);
if (set) { set.delete(loc.userId); if (set.size === 0) this.botChannelMembers.delete(cKey); }
this.botLocations.delete(uKey);
}
}
}
// ── Backward-compatible accessors ────────────────────────────────────────
// These provide the same interface as the old raw Maps so that existing
// code (dashboard, commands) doesn't need to be rewritten immediately.
/**
* Get the "observedVoiceUsers" size (human count).
* Backward-compat with `this.observedVoiceUsers.size`
*/
get observedVoiceUsersSize() { return this.userLocations.size; }
/**
* Get the "observedVoiceBots" size.
* Backward-compat with `this.observedVoiceBots.size`
*/
get observedVoiceBotsSize() { return this.botLocations.size; }
/**
* Iterate over all human user locations.
* Yields [compositeKey, {channelId, guildId, userId}] — same shape as Map entries.
* Backward-compat with `for (const [uid, info] of this.observedVoiceUsers)`.
*/
*iterateHumanUsers() {
for (const [uKey, loc] of this.userLocations) {
// Yield the userId (not composite key) as first element for compat
yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }];
}
}
/**
* Iterate over all bot user locations.
* Yields [compositeKey, {channelId, guildId, userId}].
* Backward-compat with `for (const [uid, info] of this.observedVoiceBots)`.
*/
*iterateBotUsers() {
for (const [uKey, loc] of this.botLocations) {
yield [uKey, { channelId: loc.channelId, guildId: loc.guildId }];
}
}
/**
* Get a human user's location by userId and guildId.
* If guildId is provided, uses O(1) composite key.
* If guildId is null, falls back to O(n) scan (legacy compat).
*
* @param {string} userId
* @param {string|null} [guildId=null]
* @returns {{channelId: string, guildId: string}|undefined}
*/
getHumanUser(userId, guildId = null) {
if (guildId) {
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
}
// Legacy fallback: scan for first match
const cleanUser = String(userId).replace(/\D/g, "");
for (const [uKey, loc] of this.userLocations) {
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
}
return undefined;
}
/**
* Set a human user's location (backward-compat with observedVoiceUsers.set).
*
* @param {string} userId
* @param {{channelId: string, guildId: string}} info
*/
setHumanUser(userId, info) {
const guildId = info.guildId;
const channelId = info.channelId;
if (guildId && channelId) {
this.updateUser({ guildId, userId, channelId, isBot: false });
}
}
/**
* Set a bot user's location (backward-compat with observedVoiceBots.set).
*
* @param {string} compositeKey "guildId:userId" composite key
* @param {{channelId: string, guildId: string}} info
*/
setBotUser(compositeKey, info) {
const guildId = info.guildId;
const channelId = info.channelId;
// Extract userId from composite key (format: "guildId:userId")
const userId = compositeKey.split(":").pop();
if (guildId && channelId && userId) {
this.updateUser({ guildId, userId, channelId, isBot: true });
}
}
/**
* Delete a human user by userId (scans all guilds if no guildId given).
* Backward-compat with observedVoiceUsers.delete(userId).
*
* @param {string} userId
* @param {string|null} [guildId=null]
*/
deleteHumanUser(userId, guildId = null) {
if (guildId) {
this.updateUser({ guildId, userId, channelId: null, isBot: false });
} else {
// Legacy: remove from ALL guilds
const cleanUser = String(userId).replace(/\D/g, "");
for (const [uKey, loc] of this.userLocations) {
if (loc.userId === cleanUser) {
this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false });
}
}
}
}
/**
* Delete a bot user by composite key.
* Backward-compat with observedVoiceBots.delete(compositeKey).
*
* @param {string} compositeKey "guildId:userId"
*/
deleteBotUser(compositeKey) {
const parts = compositeKey.split(":");
const guildId = parts[0];
const userId = parts[1];
if (guildId && userId) {
this.updateUser({ guildId, userId, channelId: null, isBot: true });
}
}
/**
* Check if a human user exists in the cache.
* Backward-compat with observedVoiceUsers.has(userId).
*
* @param {string} userId
* @param {string|null} [guildId=null]
* @returns {boolean}
*/
hasHumanUser(userId, guildId = null) {
if (guildId) {
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
}
// Legacy: scan
const cleanUser = String(userId).replace(/\D/g, "");
for (const [uKey, loc] of this.userLocations) {
if (loc.userId === cleanUser) return true;
}
return false;
}
/**
* Check if a bot user exists in the cache.
* Backward-compat with observedVoiceBots.has(compositeKey).
*
* @param {string} compositeKey
* @returns {boolean}
*/
hasBotUser(compositeKey) {
return this.botLocations.has(compositeKey);
}
// ── Debug / stats ────────────────────────────────────────────────────────
get stats() {
return {
humanUsers: this.userLocations.size,
botUsers: this.botLocations.size,
humanChannels: this.channelMembers.size,
botChannels: this.botChannelMembers.size,
lruUserKeysLen: this._lruUserKeys.length,
lruBotKeysLen: this._lruBotKeys.length,
};
}
}
+3 -5
View File
@@ -48,19 +48,17 @@ export class Dashboard {
case "server": { case "server": {
try { try {
const guild = await this.remix.client.guilds.fetch(data.key); const guild = this.remix.client.guilds.get(data.key);
if (!guild) return { error: "Server not found" }; if (!guild) return { error: "Server not found" };
const member = await guild.members.fetch(data.accessor).catch(() => null); const member = await guild.members.fetch(data.accessor).catch(() => null);
const channels = await guild.fetchChannels(); // execute before converting the guild, see caching
const server = Dashboard.convertServer(guild); const server = Dashboard.convertServer(guild);
if (member) { if (member) {
server.channels = server.channels.filter(c => { server.channels = server.channels.filter(c => {
const ch = channels.find(cl => c.id === cl.id); const ch = guild.channels.get(c.id);
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true; return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
}); });
server.voiceChannels = server.voiceChannels.filter(c => { server.voiceChannels = server.voiceChannels.filter(c => {
if (c.type !== 2) return false; const ch = guild.channels.get(c.id);
const ch = channels.find(cl => c.id === cl.id);
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true; return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
}); });
} }