leave/247 flows behave correctly end-to-end — channel mentions render as proper #channel links

This commit is contained in:
NoLogicAlan committed 2026-09-10 02:43:55 +03:00
1 parent 774d188757
commit 35aab94a53
9 files changed
+274 -73

No files matched your search

+1 -1
View File
@@ -154,4 +154,4 @@ manager.spawn().then((shards) => {
}).catch((e) => {
logger.error("[Sharding] Spawn failed:", e?.message ?? e);
process.exit(1);
});
});
+2
View File
@@ -218,6 +218,8 @@ class Remix {
}
}, 60_000);
this.intentionalLeaves = new Map();
/** Bot-level 24/7 rejoin timers (channelId → Timeout). Owned by Remix, not by Players. */
this._247RejoinTimers = new Map();
this.gatewayHandler = new GatewayHandler(this);
this.gatewayHandler.setupEventHandlers();
+77 -2
View File
@@ -13,7 +13,7 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice";
import { getGlobalColor, PageBuilder } from "../ui/index.mjs";
import { cleanId } from "../utils/Utils.mjs";
import { remove247ChannelMode } from "../utils/Helpers247.mjs";
import { remove247ChannelMode, isPlayerConnectionDead, detachPlayerFromManager } from "../utils/Helpers247.mjs";
import { logger } from "./Logger.mjs";
import { Dashboard } from "../dashboard/Dashboard.mjs";
@@ -158,6 +158,9 @@ const BotVoiceMixin = {
markIntentionalLeave(channelId, ttlMs = null) {
const cleanChId = cleanId(channelId);
if (!cleanChId) return;
// A user-initiated leave must also cancel any rejoin already armed for
// this channel — otherwise the bot would come back 3s after !leave.
this.cancel247Rejoin?.(cleanChId);
if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000;
const existing = this.intentionalLeaves.get(cleanChId);
if (existing) clearTimeout(existing);
@@ -166,6 +169,68 @@ const BotVoiceMixin = {
}, ttlMs));
},
/**
* Arm a BOT-LEVEL 24/7 rejoin timer for a channel. The timer lives on the
* Remix context (not on any Player instance), so it survives player
* destruction — the previous per-player timer was cancelled by the very
* destroy() that the recovery required. Deduplicates per channel and
* respects intentional leaves at arm-time and at fire-time.
* @this {import('./Bot.mjs').Remix}
* @param {string} channelId - The channel to rejoin.
* @param {string} guildId - The guild ID (for the rejoin call).
* @param {number|null} [delayMs=null] - Delay override (default: config.timers.rejoin247Delay or 3s).
*/
schedule247Rejoin(channelId, guildId, delayMs = null) {
const cleanCh = cleanId(channelId);
const cleanG = cleanId(guildId);
if (!cleanCh || !cleanG) return;
if (this.intentionalLeaves.has(cleanCh)) {
logger.voice247(`[247] Rejoin for ${cleanCh} not armed — intentional leave registered`);
return;
}
if (!this._247RejoinTimers) this._247RejoinTimers = new Map();
if (this._247RejoinTimers.has(cleanCh)) return; // already armed — keep the earliest
const delay = delayMs ?? this.config?.timers?.rejoin247Delay ?? 3_000;
logger.voice247(`[247] Arming bot-level rejoin for ${cleanCh} (guild ${cleanG}) in ${delay / 1000}s`);
const timer = setTimeout(() => {
this._247RejoinTimers?.delete(cleanCh);
if (this.intentionalLeaves.has(cleanCh)) {
logger.voice247(`[247] Rejoin for ${cleanCh} cancelled — intentional leave registered`);
return;
}
try {
const p = this.gatewayHandler?._rejoinChannel?.(cleanG, cleanCh);
if (p && typeof p.catch === "function") {
p.catch(err => logger.warn(`[247] Rejoin failed for channel ${cleanCh}:`, err?.message ?? err));
}
} catch (err) {
logger.warn(`[247] Rejoin failed for channel ${cleanCh}:`, err?.message ?? err);
}
}, delay);
this._247RejoinTimers.set(cleanCh, timer);
},
/**
* Cancel a pending bot-level 24/7 rejoin timer for a channel.
* @this {import('./Bot.mjs').Remix}
* @param {string} channelId - The channel ID.
*/
cancel247Rejoin(channelId) {
const cleanCh = cleanId(channelId);
if (!cleanCh || !this._247RejoinTimers) return;
const timer = this._247RejoinTimers.get(cleanCh);
if (timer) {
clearTimeout(timer);
this._247RejoinTimers.delete(cleanCh);
logger.voice247(`[247] Cancelled pending rejoin for ${cleanCh}`);
}
},
/**
* Spawn a new Player for a channel. Used by 24/7 boot recovery and
* enable247. Guards against duplicate players, missing channels, and
@@ -184,7 +249,17 @@ const BotVoiceMixin = {
const existing = this.players.playerMap.get(cleanChannelId)
?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId);
if (existing) return existing;
if (existing) {
if (!isPlayerConnectionDead(existing)) return existing;
// A connection-less zombie (e.g. a 24/7 player whose LiveKit session
// died without a serverLeave reaching us) is worse than useless: it
// blocks rejoins AND swallows !play. Evict it and spawn a live one.
logger.voice247(
`[_spawnPlayer] Existing player for ${cleanChannelId} has a dead connection — evicting and respawning.`
);
detachPlayerFromManager(this, existing, cleanChannelId);
try { existing.destroy(); } catch (_) {}
}
if (!this.lavalink) throw new Error("Audio node not ready yet — try again in a moment");
+23 -11
View File
@@ -14,7 +14,7 @@
import Player from "./player/index.mjs";
import { cleanId } from "../utils/Utils.mjs";
import { logger } from "../core/Logger.mjs";
import { get247ChannelMode } from "../utils/Helpers247.mjs";
import { get247ChannelMode, isPlayerConnectionDead, detachPlayerFromManager } from "../utils/Helpers247.mjs";
import { EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice";
import { getGlobalColor, getMessageGuildId } from "../ui/index.mjs";
@@ -296,18 +296,30 @@ const PlayerLifecycleMixin = {
const existing = this.playerMap.get(cleanChannelId)
?? this.getPlayerByChannelId(cleanChannelId);
if (existing) {
existing.textChannel = message.channel?.channel ?? message.channel;
try {
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
const existingGuildId = getMessageGuildId(message);
if (existingGuildId && textChannelId) {
this.settings.getServer(existingGuildId)?.set("announcementChannelId", textChannelId);
if (isPlayerConnectionDead(existing)) {
// Zombie in the map (e.g. 24/7 player whose voice session died):
// returning it would make !play silently do nothing. Evict it and
// fall through to spawn a fresh live player.
logger.voice247(
`[PlayerManager] Existing player for ${cleanChannelId} has a dead connection — evicting before initPlayer.`
);
const remix = this.commands?.client?._remix ?? null;
detachPlayerFromManager(remix ?? { players: this }, existing, cleanChannelId);
try { existing.destroy(); } catch (_) {}
} else {
existing.textChannel = message.channel?.channel ?? message.channel;
try {
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
const existingGuildId = getMessageGuildId(message);
if (existingGuildId && textChannelId) {
this.settings.getServer(existingGuildId)?.set("announcementChannelId", textChannelId);
}
} catch(e) {
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
}
} catch(e) {
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
message.reply(this._t(message, "responses.join.alreadyJoined", { channel: cid }));
return existing;
}
message.reply(this._t(message, "responses.join.alreadyJoined", { channel: cid }));
return existing;
}
if (this._pendingJoins.has(cleanChannelId)) {
message.reply(this._t(message, "responses.join.joining"));
+38 -43
View File
@@ -15,7 +15,7 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../../ui/index.mjs";
import { Utils, cleanId } from "../../utils/Utils.mjs";
import { logger } from "../../core/Logger.mjs";
import { get247ChannelMode } from "../../utils/Helpers247.mjs";
import { get247ChannelMode, detachPlayerFromManager } from "../../utils/Helpers247.mjs";
import { hasHumansInChannel } from "../../voice/VoiceStateResolver.mjs";
import { FluxerAudioBridge } from "../audio/FluxerAudioBridge.mjs";
import { applyMixins } from "../../utils/mixins.mjs";
@@ -108,8 +108,6 @@ class Player extends EventEmitter {
_isJoining = false;
/** @private @type {boolean} */
_destroyed = false;
/** @private @type {Timeout|null} */
_rejoinTimer = null;
/**
* @param {string} token - Bot authentication token (used internally).
@@ -317,51 +315,45 @@ class Player extends EventEmitter {
}
/**
* Schedule a 24/7 rejoin after a delay. Guards against destroyed players,
* registered intentional leaves, and pending/duplicate joins.
* @param {string} channelId - The channel to rejoin.
* 24/7 serverLeave recovery: remove this (now connection-less) player
* from every manager index, schedule a BOT-LEVEL rejoin, notify listeners,
* and destroy the player.
*
* Why bot-level: the old design kept the rejoin timer on the dying player
* (`this._rejoinTimer`), so `destroy()` — which cleared that timer — and
* the rejoin scheduler fought each other; and when the player survived,
* `_rejoinChannel` skipped the rejoin because the zombie was still in the
* playerMap. Either way the channel never came back. The rejoin now lives
* on the Remix context (`ctx.schedule247Rejoin`), which survives this
* instance's destruction.
*
* @param {string} channelId - The 24/7 channel to rejoin.
* @param {string} guildId - The guild ID.
* @param {string} mode - The 24/7 mode ("on").
* @private
*/
_schedule247Rejoin(channelId, guildId, mode) {
_detachAndSchedule247Rejoin(channelId, guildId) {
const ctx = this.client?._remix;
if (!ctx) {
logger.warn(`[Player] Cannot schedule 24/7 rejoin for ${channelId} — no bot context`);
if (typeof ctx?.schedule247Rejoin !== "function") {
logger.warn(`[Player] No bot-level rejoin scheduler for ${channelId} — falling back to autoleave`);
this.emit("autoleave");
return;
}
if (ctx.players?._pendingJoins?.has?.(channelId)) {
logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — join already pending`);
return;
}
// 1) Detach from playerMap (active + home keys) so rejoin paths no
// longer see a "player already here" and skip.
detachPlayerFromManager(ctx, this, channelId);
if (ctx.players?.playerMap?.has(channelId)) {
const existing = ctx.players.playerMap.get(channelId);
if (existing && !existing._destroyed && existing !== this) {
logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — another player already exists`);
return;
}
}
// 2) Arm the ctx-level rejoin BEFORE destroying ourselves — the timer
// must outlive this instance.
ctx.schedule247Rejoin(channelId, guildId);
const rejoinDelay = ctx.config?.timers?.rejoin247Delay ?? 3_000;
logger.voice247(`[Player] Scheduling 24/7 ${mode} rejoin for channel ${channelId} (guild ${guildId}) in ${rejoinDelay / 1000}s`);
// 3) Notify (dashboard close/stopplay); the manager-level autoleave
// listeners suppress the actual leave for 24/7 channels, so this is
// notification-only.
this.emit("autoleave");
this._rejoinTimer = setTimeout(() => {
this._rejoinTimer = null;
if (this._destroyed) {
logger.voice247(`[Player] 24/7 rejoin cancelled — player destroyed`);
return;
}
if (ctx.intentionalLeaves?.has(channelId)) {
logger.voice247(`[Player] 24/7 rejoin cancelled — intentional leave registered`);
return;
}
ctx.gatewayHandler?._rejoinChannel?.(guildId, channelId).catch(err => {
logger.warn(`[Player] 24/7 rejoin failed for channel ${channelId}:`, err?.message);
});
}, rejoinDelay);
// 4) Finally destroy the dead instance.
this.destroy();
}
/**
@@ -543,10 +535,14 @@ class Player extends EventEmitter {
const cId = cleanId(this._channelId ?? this._home247Channel ?? "");
const gId = cleanId(this._guildId ?? "");
if (mode === "on") {
logger.player("[Player] serverLeave in 24/7 mode — scheduling rejoin");
this.emit("autoleave");
if (cId && gId) this._schedule247Rejoin(cId, gId, mode);
if (mode === "on" && cId && gId) {
// 24/7: the voice session is gone but the commitment stands.
// Detach this now-dead player (a zombie in the map makes every
// rejoin path bail with "already has a player"), arm a
// bot-level rejoin that survives our own destroy, notify, then
// destroy ourselves.
logger.player("[Player] serverLeave in 24/7 mode — detaching and scheduling rejoin");
this._detachAndSchedule247Rejoin(cId, gId);
} else {
logger.player("[Player] Unexpected serverLeave");
this.emit("autoleave");
@@ -666,7 +662,6 @@ class Player extends EventEmitter {
}
this.leaving = true;
this._stopInactivityTimer();
if (this._rejoinTimer) { clearTimeout(this._rejoinTimer); this._rejoinTimer = null; }
this._autoplay = false;
if (this._autoplayHandler) {
this.removeListener("queueEnd", this._autoplayHandler);
+76
View File
@@ -1,5 +1,42 @@
/** @module src/utils/Helpers247 */
import { cleanId } from "./Utils.mjs";
/**
* Runtime liveness check for a player's voice connection — the runtime
* counterpart of the debug command's isGhostConnection(). A player can sit
* in the playerMap with _destroyed === false while its LiveKit/voice session
* is long gone (serverLeave zeroes _voiceConn/connection). Such zombies
* historically blocked every 24/7 rejoin path ("already has a player —
* skipping"), which is why 24/7 silently died.
*
* Dead when: destroyed/leaving, or no connection objects at all, or the
* room reports disconnected. Alive while _isJoining (mid-join) — the
* connection may not exist yet.
*
* @param {object|null} player - Player instance (duck-typed; safe on stubs).
* @returns {boolean} True when the player cannot possibly be producing audio.
*/
export function isPlayerConnectionDead(player) {
if (!player) return true;
if (player._destroyed || player.leaving) return true;
if (player._isJoining) return false;
const conn = player._voiceConn ?? player.connection ?? null;
if (!conn) return true;
const room = conn.room ?? null;
if (!room) {
try { return conn.isConnected?.() === false; } catch (_) { return false; }
}
if (room.isConnected === false) return true;
const cs = room.connectionState;
if (cs === 0 || cs === "CONN_DISCONNECTED") return true;
return false;
}
/**
* Simplified 24/7 helpers — single mode (on/off), no per-channel modes.
* get247ChannelMode is used by Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, leave.mjs.
@@ -36,4 +73,43 @@ export function remove247ChannelMode(set, channelId, currentChannels) {
*/
export function set247ChannelMode(set, channelId, mode) {
// No-op: modes no longer exist.
}
/**
* Evict a player from every manager index (playerMap active + home keys,
* guild index, pending scrobble timers) WITHOUT destroying it. Shared by the
* serverLeave rejoin path, the rejoin self-healing path and _spawnPlayer's
* zombie replacement, so they all clean up identically.
*
* @param {object} remix - The bot (Remix) context.
* @param {object} player - The player to detach.
* @param {string} [fallbackChannelId] - Channel key to also clear if the
* player carries no ids.
* @returns {string|null} The primary channel key that was cleared.
*/
export function detachPlayerFromManager(remix, player, fallbackChannelId = null) {
if (!remix?.players?.playerMap || !player) return null;
const activeCh = cleanId(player._channelId ?? "") || cleanId(fallbackChannelId ?? "") || null;
const homeCh = cleanId(player._home247Channel ?? "") || null;
const guildId = cleanId(player._guildId ?? "");
const keys = new Set([activeCh, homeCh].filter(Boolean));
for (const key of keys) {
if (remix.players.playerMap.get(key) === player) remix.players.playerMap.delete(key);
}
for (const key of keys) {
try { remix.players._unindexPlayer?.(guildId, key); } catch (_) {}
}
for (const key of keys) {
const pendingScrobble = remix.players._pendingScrobbleTimers?.get(key);
if (pendingScrobble) {
clearTimeout(pendingScrobble.timer);
remix.players._pendingScrobbleTimers.delete(key);
}
}
return activeCh;
}
+1
View File
@@ -433,6 +433,7 @@ class GatewayHandler {
*/
onReady() {
this._lastReadyAt = Date.now();
this._graceStartedAt = Date.now();
this.seedVoiceStatesFromGuilds();
this.seedGuildsFromRest().catch(e => logger.warn("[onReady] seedGuildsFromRest error:", e.message));
this.attachRawListener();
+15 -3
View File
@@ -11,6 +11,7 @@
import { logger } from "../../core/Logger.mjs";
import { cleanId } from "../../utils/Utils.mjs";
import { isPlayerConnectionDead, detachPlayerFromManager } from "../../utils/Helpers247.mjs";
import { GatewayHandler } from "./GatewayHandler.mjs";
/**
@@ -85,9 +86,20 @@ const RejoinManager = {
const existing = remix.players.playerMap.get(cleanChannelId);
if (existing && !existing._destroyed) {
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a player — skipping.`);
this._rejoinAttempts.delete(cleanChannelId);
return;
if (!isPlayerConnectionDead(existing)) {
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a live player — skipping.`);
this._rejoinAttempts.delete(cleanChannelId);
return;
}
// Ghost/zombie player: object alive in the map but its voice session
// is long gone (serverLeave / dead socket). It used to block this
// rejoin with "already has a player" — the #1 reason 24/7 silently
// died. Evict it and respawn a live connection.
logger.voice247(
`[Rejoin] Existing player for ${cleanChannelId} has a dead connection — evicting before rejoin.`
);
detachPlayerFromManager(remix, existing, cleanChannelId);
try { existing.destroy(); } catch (_) {}
}
if (remix.players._pendingJoins?.has?.(cleanChannelId)) {
+41 -13
View File
@@ -11,7 +11,7 @@
*/
import { logger } from "../../core/Logger.mjs";
import { get247ChannelMode } from "../../utils/Helpers247.mjs";
import { get247ChannelMode, isPlayerConnectionDead } from "../../utils/Helpers247.mjs";
import { VoiceStateCache } from "../VoiceStateCache.mjs";
import { cleanId } from "../../utils/Utils.mjs";
@@ -313,12 +313,16 @@ const VoiceStateRouting = {
const homeCh = cleanId(existingPlayer._home247Channel ?? "");
if (homeCh && homeCh !== cleanOld) remix.players.playerMap.delete(homeCh);
try { existingPlayer.destroy(); } catch (_) {}
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
setTimeout(() => {
this._rejoinChannel(cleanId(guildId), cleanOld).catch(err => {
logger.warn(`[247] Failed to rejoin ${cleanOld} after move-away:`, err.message);
});
}, rejoinDelay);
if (typeof remix.schedule247Rejoin === "function") {
remix.schedule247Rejoin(cleanOld, cleanId(guildId));
} else {
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
setTimeout(() => {
this._rejoinChannel(cleanId(guildId), cleanOld).catch(err => {
logger.warn(`[247] Failed to rejoin ${cleanOld} after move-away:`, err.message);
});
}, rejoinDelay);
}
} else if (newChannelSaved || newChannelPendingSpawn) {
// New channel is already 24/7 or being spawned — keep both, don't rekey.
logger.voice247(
@@ -362,11 +366,31 @@ const VoiceStateRouting = {
if (this._inStartupGrace) {
const bootPlayer = remix.players.playerMap.get(cleanOld);
if (bootPlayer && !bootPlayer._destroyed) {
const playerAlive = !!bootPlayer && !bootPlayer._destroyed && !isPlayerConnectionDead(bootPlayer);
if (playerAlive) {
logger.voiceState(
`[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` +
`player still active, ignoring stale disconnect.`
);
return;
}
// Player missing or already dead. The old code just dropped the
// event ("deferring until grace period ends" — nothing ever
// replayed it), so a 24/7 channel killed during boot never came
// back. Arm a deferred bot-level rejoin for just after the grace
// window instead.
const graceSet = remix.settingsMgr.getServer(guildId);
const graceMode = graceSet ? get247ChannelMode(graceSet, cleanOld) : "off";
if (graceMode === "on" && typeof remix.schedule247Rejoin === "function") {
const graceStarted = this._graceStartedAt ?? Date.now();
const graceRemaining = Math.max(0, this._startupDeleteGraceMs - (Date.now() - graceStarted));
const rejoinDelay = remix.config?.timers?.rejoin247Delay ?? this.T.rejoin247Delay ?? 3_000;
logger.voice247(
`[VoiceState] Bot disconnected from ${cleanOld} during startup grace with a dead player — ` +
`arming deferred 24/7 rejoin in ${Math.round((graceRemaining + rejoinDelay) / 1000)}s.`
);
remix.schedule247Rejoin(cleanOld, cleanGuild, graceRemaining + rejoinDelay);
} else {
logger.voiceState(
`[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` +
@@ -409,11 +433,15 @@ const VoiceStateRouting = {
}
}
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
setTimeout(() => {
this._rejoinChannel(cleanGuild, cleanOld).catch(err => {
logger.warn(`[VoiceState] Failed to rejoin ${cleanOld} after disconnect:`, err.message);
});
}, rejoinDelay);
if (typeof remix.schedule247Rejoin === "function") {
remix.schedule247Rejoin(cleanOld, cleanGuild);
} else {
setTimeout(() => {
this._rejoinChannel(cleanGuild, cleanOld).catch(err => {
logger.warn(`[VoiceState] Failed to rejoin ${cleanOld} after disconnect:`, err.message);
});
}, rejoinDelay);
}
} else {
const leavePlayer = remix.players.playerMap.get(cleanOld);
if (leavePlayer && !leavePlayer.leaving && !leavePlayer._destroyed) {