From 85c4bf4e8da9aaf6417a16bcbb02d3dbeb86d648 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Fri, 11 Sep 2026 01:47:38 +0300 Subject: [PATCH] ... --- commands/settings.mjs | 3 +- commands/settings/channels247.mjs | 162 ++++++++++++++----- commands/settings/setters.mjs | 13 +- index.mjs | 12 ++ src/db/Settings.mjs | 42 ++++- src/music/audio/WebMOpusMuxer.mjs | 45 +++--- src/voice/gateway/GatewayHandler.mjs | 39 +++-- src/voice/gateway/Watchdog247.mjs | 234 +++++++++++++++++++++++++++ storage/locales/bot/en.json | 13 +- 9 files changed, 475 insertions(+), 88 deletions(-) create mode 100644 src/voice/gateway/Watchdog247.mjs diff --git a/commands/settings.mjs b/commands/settings.mjs index 4140ded..1755da8 100644 --- a/commands/settings.mjs +++ b/commands/settings.mjs @@ -176,8 +176,7 @@ export async function run(message, data) { if (cmd === "getSettings") { if (settingKey) { if (settingKey === "stay_247") { - const channels = get247Channels(set); - return message.reply(build247Panel(set, this, guildId, channels.size > 0)); + return message.reply(build247Panel(set, this, guildId, null)); } const val = set.get(settingKey); const desc = this.settingsMgr.descriptions?.[settingKey]; diff --git a/commands/settings/channels247.mjs b/commands/settings/channels247.mjs index ade11d0..af7d717 100644 --- a/commands/settings/channels247.mjs +++ b/commands/settings/channels247.mjs @@ -1,12 +1,19 @@ /** * @module commands/settings/channels247 - * @description 24/7 channel storage, panel - * rendering and enable/disable/toggle handling for the settings command. - * Bodies are verbatim from the original single-file command. + * @description 24/7 channel storage, live-status panel rendering and + * enable/disable/toggle handling for the settings command. + * + * The panel is localized (falls back to the default locale) and shows the + * LIVE state of every saved channel: + * Connected — a healthy player is attached + * Reconnecting — a bot-level rejoin is armed right now + * Offline — no player; the watchdog sweep will re-arm a rejoin + * plus the auto-recovery line so users can see the watchdog is watching. */ import { cleanId } from "../../src/ui/index.mjs"; +import { isPlayerConnectionDead } from "../../src/utils/Helpers247.mjs"; import { isValidFluxerId, MAX_247_CHANNELS, embed, tWrap } from "./utils.mjs"; /** @@ -28,7 +35,8 @@ export function get247Channels(set) { } /** * Save a Set of channel IDs back to the stay_247 setting. - * Writes 'none' if the set is empty. + * Writes 'none' if the set is empty. The settings manager persists + * stay_247 changes immediately (no debounce window) — see Settings.mjs. * @param {ServerSettings} set - The guild settings instance. * @param {Set} channels - The channel IDs to save. */ @@ -52,42 +60,116 @@ function resolveChannelName(client, channelId) { } /** - * Build an embed payload showing the current 24/7 status for the guild. + * @private + * Live status of one saved 24/7 channel. + * @param {object} ctx - The bot (Remix) context. + * @param {string} guildId - The guild ID. + * @param {string} channelId - The saved channel ID. + * @param {object} t - Panel translation function. + * @returns {{line: string, state: "connected"|"reconnecting"|"offline", order: number}} + */ +function channelStatus(ctx, guildId, channelId, t) { + const player = ctx.players?.playerMap?.get(channelId) + ?? [...(ctx.players?.playerMap?.values() ?? [])].find(p => + cleanId(p?._channelId ?? "") === channelId && + cleanId(p?._guildId ?? "") === cleanId(guildId) + ); + + const rejoinArmed = ctx._247RejoinTimers?.has?.(cleanId(channelId)) === true; + const name = resolveChannelName(ctx.client, channelId); + + if (player && !isPlayerConnectionDead(player)) { + return { + state: "connected", order: 0, + line: t("responses.settings.247Panel.statusConnected") + " " + + (name ? "**" + name + "** " : "") + "<#" + channelId + ">", + }; + } + if (rejoinArmed || player?._isJoining) { + return { + state: "reconnecting", order: 1, + line: t("responses.settings.247Panel.statusReconnecting") + " " + + (name ? "**" + name + "** " : "") + "<#" + channelId + ">", + }; + } + return { + state: "offline", order: 2, + line: t("responses.settings.247Panel.statusOffline") + " " + + (name ? "**" + name + "** " : "") + "<#" + channelId + ">", + }; +} + +/** + * @private + * Build the panel description text (localized, live status) without the + * embed wrapper so callers can compose confirmations around it. * @param {ServerSettings} set - The guild settings instance. * @param {object} ctx - The bot (Remix) context. * @param {string} guildId - The guild ID. - * @param {string|null} channelId - The channel ID (for active indicator), or null. - * @returns {object} Embed payload object for message.reply(). + * @param {string|null} [justToggledId=null] - Channel just toggled (marked ←). + * @returns {string} Description text for the panel embed. */ -export function build247Panel(set, ctx, guildId, channelId) { - const channels = [...get247Channels(set)]; +function build247PanelDescription(set, ctx, guildId, justToggledId = null) { + const t = tWrap(ctx, guildId); const prefix = ctx.handler.getPrefix(guildId); + const channels = [...get247Channels(set)]; + const panelKey = (k, vars = {}) => t("responses.settings.247Panel." + k, vars); - if (channels.length > 0) { - const lines = channels.map(id => { - const name = resolveChannelName(ctx.client, id); - const isActive = id === channelId; - return (isActive ? "\u25b6 " : "\u2022 ") + (name ? "**" + name + "** " : "") + "<#" + id + ">"; - }); - return embed( - channels.length === 1 && channelId - ? "\u2705 24/7 is now **enabled** in <#" + channelId + ">\n\n" + - "The bot will stay connected and auto-rejoin if disconnected." - : "\u2705 24/7 active in " + channels.length + " channel(s):\n\n" + lines.join("\n"), - { title: "\u2705 24/7 Mode" } - ); + const watchdog = ctx.gatewayHandler; + const watchdogOn = watchdog?.isWatchdog247Running?.() === true; + const sweepSeconds = Math.round((watchdog?._247WatchdogInterval ?? 60_000) / 1000); + const recoveryLine = watchdogOn + ? panelKey("autoRecoveryLine", { seconds: sweepSeconds }) + : panelKey("autoRecoveryDisabledLine"); + + if (channels.length === 0) { + return "\u274C 24/7 is **disabled**\n\n" + + panelKey("allChannelsDisabled") + "\n\n" + + panelKey("disabledHint", { prefix }) + "\n\n" + + recoveryLine; } + const statuses = channels + .map(id => channelStatus(ctx, guildId, id, t)) + .sort((a, b) => a.order - b.order); + + const lines = statuses.map(s => + s.line + (justToggledId && s.line.includes("<#" + cleanId(justToggledId) + ">") ? " \u2190" : "") + ); + + const allConnected = statuses.every(s => s.state === "connected"); + + return (channels.length === 1 && allConnected + ? panelKey("enabledLine") + "\n\n" + : "\u2705 24/7 active in " + channels.length + " channel(s):\n\n") + + lines.join("\n") + + "\n\n" + recoveryLine; +} + +/** + * Build a localized, live-status embed showing the current 24/7 state for + * the guild: every saved channel with its connection state, plus the + * auto-recovery line. + * @param {ServerSettings} set - The guild settings instance. + * @param {object} ctx - The bot (Remix) context. + * @param {string} guildId - The guild ID. + * @param {string|null} [justToggledId=null] - Channel that was just toggled + * (surfaced first and marked with ←). + * @returns {object} Embed payload object for message.reply(). + */ +export function build247Panel(set, ctx, guildId, justToggledId = null) { + const t = tWrap(ctx, guildId); + const prefix = ctx.handler.getPrefix(guildId); + const panelKey = (k, vars = {}) => t("responses.settings.247Panel." + k, vars); return embed( - "\u274c 24/7 is **disabled**\n\n" + - "The bot will leave voice channels when idle.\n\n" + - "Join a voice channel and use `" + prefix + "247` to enable.", - { title: "\u274c 24/7 Mode" } + build247PanelDescription(set, ctx, guildId, justToggledId), + { title: panelKey("title"), footer: panelKey("footerLine", { prefix }) } ); } /** * Disable 24/7 mode for a specific channel. - * Removes the channel from stay_247, marks intentional leave, and destroys the player. + * Removes the channel from stay_247, marks intentional leave (cancels any + * armed rejoin), and destroys the player. * @param {object} ctx - The bot (Remix) context. * @param {ServerSettings} set - The guild settings instance. * @param {string} guildId - The guild ID. @@ -99,6 +181,7 @@ export async function disable247(ctx, set, guildId, channelId) { const channels = get247Channels(set); channels.delete(id); save247Channels(set, channels); + ctx.cancel247Rejoin?.(id); ctx.markIntentionalLeave?.(id); const player = ctx.players.playerMap.get(id) ?? [...ctx.players.playerMap.values()].find(p => @@ -131,6 +214,7 @@ async function enable247(ctx, set, guildId, channelId) { if (channels.size >= MAX_247_CHANNELS) { for (const oldId of channels) { if (oldId !== id) { + ctx.cancel247Rejoin?.(oldId); ctx.markIntentionalLeave?.(oldId); const oldPlayer = ctx.players.playerMap.get(oldId) ?? [...ctx.players.playerMap.values()].find(p => @@ -161,7 +245,8 @@ async function enable247(ctx, set, guildId, channelId) { } /** * Handle the !247 toggle command. If the user is in a 24/7 channel, disable it; - * otherwise, enable it for the user's current voice channel. + * otherwise, enable it for the user's current voice channel. Replies with an + * explicit confirmation line plus the live-status panel. * @param {object} ctx - The bot (Remix) context. * @param {object} message - The command message. * @param {ServerSettings} set - The guild settings instance. @@ -169,8 +254,9 @@ async function enable247(ctx, set, guildId, channelId) { * @returns {Promise} */ export async function handle247Toggle(ctx, message, set, guildId) { - const loc = tWrap(ctx, guildId); - if (!guildId) return message.reply(embed(loc("responses.settings.noServer"))); + const t = tWrap(ctx, guildId); + const panelKey = (k, vars = {}) => t("responses.settings.247Panel." + k, vars); + if (!guildId) return message.reply(embed(t("responses.settings.noServer"))); const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message); if (!userChannelId) { @@ -182,15 +268,17 @@ export async function handle247Toggle(ctx, message, set, guildId) { if (channels.has(id)) { await disable247(ctx, set, guildId, userChannelId); - return message.reply(build247Panel(set, ctx, guildId, id)); - } - - const result = await enable247(ctx, set, guildId, userChannelId); - if (result?.max) { return message.reply(embed( - loc("responses.settings.max247Channels", { max: MAX_247_CHANNELS, prefix: ctx.handler.getPrefix(guildId) }) + panelKey("confirmDisabled", { channel: id }) + "\n\n" + + build247PanelDescription(set, ctx, guildId, null), + { title: panelKey("title") } )); } - return message.reply(build247Panel(set, ctx, guildId, id)); + await enable247(ctx, set, guildId, userChannelId); + return message.reply(embed( + panelKey("confirmEnabled", { channel: id }) + "\n\n" + + build247PanelDescription(set, ctx, guildId, id), + { title: panelKey("title") } + )); } diff --git a/commands/settings/setters.mjs b/commands/settings/setters.mjs index aff741e..c98ba38 100644 --- a/commands/settings/setters.mjs +++ b/commands/settings/setters.mjs @@ -105,11 +105,16 @@ export async function handleShortcut(ctx, message, settingKey, valueTokens) { const mode = rawValue.toLowerCase().trim(); if (mode === "off" || mode === "false" || mode === "disable" || mode === "0") { const loc = tWrap(ctx, guildId); + const panelKey = (k, vars = {}) => loc("responses.settings.247Panel." + k, vars); if (!guildId) return message.reply(embed(loc("responses.settings.noServer"))); const { channelId } = await ctx.players.checkVoiceChannels(message); if (channelId) { await disable247(ctx, set, guildId, channelId); - return message.reply(build247Panel(set, ctx, guildId, cleanId(channelId))); + return message.reply(embed( + panelKey("confirmDisabled", { channel: "<#" + cleanId(channelId) + ">" }) + "\n\n" + + loc("responses.settings.247Disabled", { channel: cleanId(channelId), prefix: ctx.handler.getPrefix(guildId) }), + { title: panelKey("title") } + )); } for (const [chId, player] of [...ctx.players.playerMap.entries()]) { if (cleanId(player?._guildId ?? "") === cleanId(guildId)) { @@ -122,7 +127,11 @@ export async function handleShortcut(ctx, message, settingKey, valueTokens) { } } save247Channels(set, new Set()); - return message.reply(build247Panel(set, ctx, guildId, null)); + return message.reply(embed( + panelKey("confirmDisabledAll") + "\n\n" + + loc("responses.settings.247DisabledAll"), + { title: panelKey("title") } + )); } return handle247Toggle(ctx, message, set, guildId); } diff --git a/index.mjs b/index.mjs index c8ec63c..c9b763e 100644 --- a/index.mjs +++ b/index.mjs @@ -132,6 +132,18 @@ const saveAndExit = async () => { } catch (e) { logger.error("[Shutdown] Failed to close Dashboard DB:", e.message); } + try { + remix.gatewayHandler?.stop247Watchdog?.(); + } catch (e) { + logger.warn("[Shutdown] Watchdog stop error:", e?.message); + } + try { + if (remix.settingsMgr?.shutdown) { + await remix.settingsMgr.shutdown(); + } + } catch (e) { + logger.error("[Shutdown] Settings flush failed:", e.message); + } process.exit(0); }; diff --git a/src/db/Settings.mjs b/src/db/Settings.mjs index 854689a..aa182b9 100644 --- a/src/db/Settings.mjs +++ b/src/db/Settings.mjs @@ -194,13 +194,24 @@ export class RemoteSettingsManager extends SettingsManager { } /** - * Stop all pending debounced writes. Call before process exit. + * Stop accepting new writes and flush any pending debounced writes to the + * database. Call before process exit — previously this DISCARDED pending + * writes, which could lose a 24/7 toggle made within the 80ms debounce + * window of a shutdown. * @returns {Promise} */ async shutdown() { + if (this._shuttingDown) return; this._shuttingDown = true; + const pendingServers = [...this._debounceTimers.keys()] + .map(id => this.guilds.get(id)) + .filter(Boolean); for (const [, timer] of this._debounceTimers) clearTimeout(timer); this._debounceTimers.clear(); + if (pendingServers.length > 0) { + logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`); + } + await Promise.allSettled(pendingServers.map(server => this._doSave(server))); } /** @@ -354,6 +365,20 @@ export class RemoteSettingsManager extends SettingsManager { this.emit('ready'); } + /** + * Internal flag-free save of the full settings blob. Used by remoteSave + * and by the shutdown flush (which runs after _shuttingDown is set). + * @param {ServerSettings} server - The guild settings instance. + * @returns {Promise} + * @private + */ + async _doSave(server) { + const escapedData = mysql.escape(JSON.stringify(server.data)); + const escapedId = mysql.escape(server.id); + const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}`); + if (r.error) logger.error('[Settings] save error:', r.error); + } + /** * Persist a single key change via MySQL JSON_SET. Falls back to a full blob save for arrays/objects. * @param {ServerSettings} server - The guild settings instance. @@ -381,10 +406,7 @@ export class RemoteSettingsManager extends SettingsManager { */ async remoteSave(server) { if (this._shuttingDown) return; - const escapedData = mysql.escape(JSON.stringify(server.data)); - const escapedId = mysql.escape(server.id); - const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}`); - if (r.error) logger.error('[Settings] remoteSave error:', r.error); + return this._doSave(server); } /** @@ -432,7 +454,9 @@ export class RemoteSettingsManager extends SettingsManager { /** * Queue a debounced database write for a single key change (80ms delay per guild). - * If the guild is not yet cached, it is added and a CREATE is issued. + * If the guild is not yet cached, it is added and a CREATE is issued. + * Critical keys (stay_247) flush immediately instead of debouncing — a + * 24/7 toggle must survive even an instant crash/restart. * @param {ServerSettings} server - The guild settings instance. * @param {string} key - The changed key. */ @@ -444,6 +468,12 @@ export class RemoteSettingsManager extends SettingsManager { } const s = this.guilds.get(server.id); s.data[key] = server.data[key]; + if (key === 'stay_247') { + const existing = this._debounceTimers.get(server.id); + if (existing) { clearTimeout(existing); this._debounceTimers.delete(server.id); } + this.remoteSave(s).catch(e => logger.error('[Settings] immediate save error:', e.message)); + return; + } const existing = this._debounceTimers.get(server.id); if (existing) clearTimeout(existing); this._debounceTimers.set(server.id, setTimeout(() => { diff --git a/src/music/audio/WebMOpusMuxer.mjs b/src/music/audio/WebMOpusMuxer.mjs index 8ba2b7d..8bfb6af 100644 --- a/src/music/audio/WebMOpusMuxer.mjs +++ b/src/music/audio/WebMOpusMuxer.mjs @@ -60,12 +60,12 @@ function uintPayload(value) { export function buildOpusHead(sampleRate, channels) { const buf = Buffer.alloc(19); buf.write("OpusHead", 0, "ascii"); - buf.writeUInt8(1, 8); // version + buf.writeUInt8(1, 8); buf.writeUInt8(channels, 9); - buf.writeUInt16LE(0, 10); // pre-skip (we encode ourselves; no trimming) + buf.writeUInt16LE(0, 10); buf.writeUInt32LE(sampleRate, 12); - buf.writeInt16LE(0, 16); // output gain - buf.writeUInt8(0, 18); // mapping family (mono/stereo) + buf.writeInt16LE(0, 16); + buf.writeUInt8(0, 18); return buf; } @@ -79,41 +79,38 @@ export function buildOpusHead(sampleRate, channels) { */ function buildHeader(sampleRate, channels) { const ebml = element("1a45dfa3", Buffer.concat([ - element("4286", uintPayload(1)), // EBMLVersion - element("42f7", uintPayload(1)), // EBMLReadVersion - element("42f2", uintPayload(4)), // EBMLMaxIDLength - element("42f3", uintPayload(8)), // EBMLMaxSizeLength - element("4282", Buffer.from("webm", "ascii")), // DocType - element("4287", uintPayload(2)), // DocTypeVersion - element("4285", uintPayload(2)), // DocTypeReadVersion + element("4286", uintPayload(1)), + element("42f7", uintPayload(1)), + element("42f2", uintPayload(4)), + element("42f3", uintPayload(8)), + element("4282", Buffer.from("webm", "ascii")), + element("4287", uintPayload(2)), + element("4285", uintPayload(2)), ])); const info = element("1549a966", Buffer.concat([ - element("2ad7b1", uintPayload(1000000)), // TimecodeScale (1ms) - element("4d80", Buffer.from("fluxer-remix", "ascii")),// MuxingApp - element("5741", Buffer.from("fluxer-remix", "ascii")),// WritingApp + element("2ad7b1", uintPayload(1000000)), + element("4d80", Buffer.from("fluxer-remix", "ascii")), + element("5741", Buffer.from("fluxer-remix", "ascii")), ])); const floatBuf = Buffer.alloc(4); floatBuf.writeFloatBE(sampleRate, 0); const audio = element("e1", Buffer.concat([ - element("b5", floatBuf), // SamplingFrequency - element("9f", uintPayload(channels)), // Channels + element("b5", floatBuf), + element("9f", uintPayload(channels)), ])); const trackEntry = element("ae", Buffer.concat([ - element("d7", uintPayload(1)), // TrackNumber (must be 1 — demuxer masks data[0] & 0xF) - element("73c5", uintPayload(1)), // TrackUID - element("83", uintPayload(2)), // TrackType: audio - element("86", Buffer.from("A_OPUS", "ascii")), // CodecID - element("63a2", buildOpusHead(sampleRate, channels)), // CodecPrivate: OpusHead + element("d7", uintPayload(1)), + element("73c5", uintPayload(1)), + element("83", uintPayload(2)), + element("86", Buffer.from("A_OPUS", "ascii")), + element("63a2", buildOpusHead(sampleRate, channels)), audio, ])); const tracks = element("1654ae6b", trackEntry); - // Streaming Segment size: a huge finite vint (0x01 + 7x0xFF = 2^56-1). The - // canonical all-0xFF unknown-size marker is misparsed by prism-media's - // vintLength (it reads 0xFF as a 1-byte vint), so we use this equivalent form. const segmentStart = Buffer.concat([ Buffer.from("18538067", "hex"), Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), diff --git a/src/voice/gateway/GatewayHandler.mjs b/src/voice/gateway/GatewayHandler.mjs index 129f701..6da65bb 100644 --- a/src/voice/gateway/GatewayHandler.mjs +++ b/src/voice/gateway/GatewayHandler.mjs @@ -18,6 +18,7 @@ import { applyMixins } from "../../utils/mixins.mjs"; import VoiceStateRouting from "./VoiceStateRouting.mjs"; import GuildSync from "./GuildSync.mjs"; import RejoinManager from "./RejoinManager.mjs"; +import Watchdog247 from "./Watchdog247.mjs"; const RAW_GATEWAY_INTEREST = /"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/; @@ -446,6 +447,7 @@ class GatewayHandler { }, this._startupDeleteGraceMs); this.rejoin247Channels(); + this.start247Watchdog(); } /** @@ -492,6 +494,16 @@ class GatewayHandler { return; } + try { + const lava = remix.lavalink; + if (lava?.hasConnectedNode && !lava.hasConnectedNode() && lava.waitForNode) { + logger.voice247("[BootRecovery] Waiting up to 90s for the Lavalink node to connect..."); + await lava.waitForNode({ timeoutMs: 90_000, intervalMs: 2_000 }).catch(() => { + logger.warn("[BootRecovery] Lavalink still not connected — attempting rejoins anyway (watchdog will retry)."); + }); + } + } catch (_) { /* best effort */ } + logger.voice247( `[BootRecovery] Found ${channelsToRejoin.length} 24/7 channel(s) to rejoin: ` + channelsToRejoin.map(c => `${c.channelId}(${c.mode})`).join(", ") @@ -520,25 +532,20 @@ class GatewayHandler { continue; } - const channelObj = remix.client?.channels?.get?.(channelId); - if (!channelObj) { + const { channel: channelObj, definitive } = await this._resolve247Channel(channelId); + if (!channelObj && definitive) { logger.warn( `[BootRecovery] Channel ${channelId} in guild ${guildId} no longer exists — ` + `removing from 24/7 settings to prevent repeated failures.` ); - try { - const set = remix.settingsMgr.getServer(guildId); - if (set) { - const raw = set.get("stay_247"); - const arr = Array.isArray(raw) ? raw : raw ? [raw] : []; - const filtered = arr.filter(id => id && id !== "none" && cleanId(id) !== channelId); - const remainingSet = new Set(filtered.map(id => cleanId(id))); - remove247ChannelMode(set, channelId, remainingSet); - set.set("stay_247", filtered.length > 0 ? filtered : "none"); - } - } catch (cleanupErr) { - logger.warn(`[BootRecovery] Failed to auto-remove missing channel ${channelId} from 24/7:`, cleanupErr?.message); - } + this._prune247Channel(guildId, channelId); + continue; + } + if (!channelObj && !definitive) { + logger.warn( + `[BootRecovery] Channel ${channelId} could not be resolved (cache miss + REST failure) — ` + + `keeping the 24/7 setting; the watchdog will retry later.` + ); continue; } if (channelObj.type !== 2) { @@ -583,6 +590,6 @@ class GatewayHandler { } } -applyMixins(GatewayHandler, VoiceStateRouting, GuildSync, RejoinManager); +applyMixins(GatewayHandler, VoiceStateRouting, GuildSync, RejoinManager, Watchdog247); export { GatewayHandler }; diff --git a/src/voice/gateway/Watchdog247.mjs b/src/voice/gateway/Watchdog247.mjs new file mode 100644 index 0000000..6a0bb10 --- /dev/null +++ b/src/voice/gateway/Watchdog247.mjs @@ -0,0 +1,234 @@ +/** + * @module src/voice/gateway/Watchdog247 + * @description Continuous 24/7 self-healing watchdog for {@link GatewayHandler}. + * + * Boot recovery (rejoin247Channels) is one-shot: if a rejoin fails — Lavalink + * not up yet, transient voice error, gateway hiccup — the channel stays dead + * until the next restart. This mixin adds a periodic sweep so every saved + * 24/7 channel converges on a live player: + * + * healthy player -> nothing to do + * zombie / dead player -> evict from the map + arm bot-level rejoin + * no player at all -> arm bot-level rejoin + * intentional leave -> never re-armed (respect the user's !leave/!247 off) + * channel gone -> verified via cache AND REST before the setting + * is pruned (cache-miss alone is NOT proof the + * channel was deleted — the channels cache is + * FIFO-bounded since the OOM fix) + * + * Sweeps are skipped while boot recovery is running so the two systems never + * race. The interval is unref'd so it never holds the process open. + */ + +import { logger } from "../../core/Logger.mjs"; +import { cleanId } from "../../utils/Utils.mjs"; +import { get247ChannelMode, isPlayerConnectionDead, detachPlayerFromManager } from "../../utils/Helpers247.mjs"; + +/** @type {number} Default sweep interval (ms). Overridable via config.timers.watchdog247Interval. */ +const DEFAULT_SWEEP_INTERVAL = 60_000; + +/** + * @type {object} + * @description Watchdog mixin — applied to GatewayHandler alongside + * VoiceStateRouting / GuildSync / RejoinManager. + */ +const Watchdog247 = { + /** + * Start the 24/7 watchdog sweep loop (idempotent). + * @this {GatewayHandler} + * @returns {void} + */ + start247Watchdog() { + if (this._247WatchdogTimer) return; + const interval = Number(this.remix?.config?.timers?.watchdog247Interval) || DEFAULT_SWEEP_INTERVAL; + this._247WatchdogInterval = interval; + this._247WatchdogTimer = setInterval(() => { + this._sweep247Channels().catch(err => { + logger.warn("[Watchdog247] Sweep crashed:", err?.message ?? err); + }); + }, interval); + this._247WatchdogTimer.unref?.(); + logger.voice247(`[Watchdog247] Active — checking every ${interval / 1000}s.`); + }, + + /** + * Stop the watchdog sweep loop (idempotent). Called on shutdown. + * @this {GatewayHandler} + * @returns {void} + */ + stop247Watchdog() { + if (!this._247WatchdogTimer) return; + clearInterval(this._247WatchdogTimer); + this._247WatchdogTimer = null; + logger.voice247("[Watchdog247] Stopped."); + }, + + /** + * Whether the watchdog loop is currently running. + * @this {GatewayHandler} + * @returns {boolean} + */ + isWatchdog247Running() { + return Boolean(this._247WatchdogTimer); + }, + + /** + * Resolve a channel by ID with a REST fallback. The channels cache is + * FIFO-bounded (OOM fix), so a cache miss does NOT mean the channel was + * deleted — only a REST fetch that definitively fails (404-style) proves + * deletion. Network errors keep the setting intact. + * @this {GatewayHandler} + * @param {string} channelId - The channel ID to resolve. + * @returns {Promise<{channel: object|null, definitive: boolean}>} + * `channel` when found; otherwise `definitive: true` only when the + * channel is provably gone. + * @private + */ + async _resolve247Channel(channelId) { + const clean = cleanId(channelId); + if (!clean) return { channel: null, definitive: true }; + + const cached = this.remix?.client?.channels?.get?.(clean) ?? null; + if (cached) return { channel: cached, definitive: false }; + + try { + const fetched = await this.remix?.client?.channels?.fetch?.(clean); + if (fetched) return { channel: fetched, definitive: false }; + return { channel: null, definitive: true }; + } catch (_) { + return { channel: null, definitive: false }; + } + }, + + /** + * Remove a channel from the guild's stay_247 setting (prune). + * @this {GatewayHandler} + * @param {string} guildId - The guild ID. + * @param {string} channelId - The channel ID to prune. + * @returns {boolean} True when the setting was modified. + * @private + */ + _prune247Channel(guildId, channelId) { + const cleanG = cleanId(guildId); + const cleanCh = cleanId(channelId); + if (!cleanG || !cleanCh) return false; + try { + const set = this.remix?.settingsMgr?.getServer?.(cleanG); + if (!set?.get) return false; + const raw = set.get("stay_247"); + if (!raw || raw === "none") return false; + const arr = Array.isArray(raw) ? raw : [raw]; + const filtered = arr.map(id => cleanId(id)).filter(id => id && id !== cleanCh); + if (filtered.length === arr.map(id => cleanId(id)).filter(Boolean).length) return false; + set.set("stay_247", filtered.length > 0 ? filtered : "none"); + return true; + } catch (err) { + logger.warn(`[Watchdog247] Failed to prune ${cleanCh} from guild ${cleanG}:`, err?.message); + return false; + } + }, + + /** + * One watchdog sweep: verify every saved 24/7 channel has a live player, + * self-heal the ones that don't, and prune provably-deleted channels. + * Also cancels stale rejoin timers whose channel is no longer saved. + * @this {GatewayHandler} + * @returns {Promise} + * @private + */ + async _sweep247Channels() { + const { remix } = this; + if (!remix?.players?.playerMap) return; + if (this._bootRecoveryActive) { + logger.voice247("[Watchdog247] Boot recovery in progress — skipping sweep."); + return; + } + + let healthy = 0, healed = 0, pruned = 0, skipped = 0; + const savedChannels = []; + + for (const [guildId, serverSettings] of remix.settingsMgr.guilds) { + const raw = serverSettings?.get?.("stay_247"); + if (!raw || raw === "none") continue; + const channels = (Array.isArray(raw) ? raw : [raw]) + .map(id => cleanId(id)) + .filter(id => id && id.length >= 15 && id.length <= 22); + for (const channelId of channels) { + if (get247ChannelMode(serverSettings, channelId) !== "on") continue; + savedChannels.push({ guildId, channelId }); + } + } + + for (const { guildId, channelId } of savedChannels) { + if (remix.intentionalLeaves?.has?.(channelId)) { + skipped++; + continue; + } + + const player = remix.players.playerMap.get(channelId) + ?? [...remix.players.playerMap.values()].find(p => + cleanId(p?._channelId ?? "") === channelId && + cleanId(p?._guildId ?? "") === cleanId(guildId) + ); + + if (player && !isPlayerConnectionDead(player)) { + healthy++; + continue; + } + + if (player) { + logger.voice247( + `[Watchdog247] ${channelId} player is a zombie — evicting and re-arming rejoin.` + ); + try { player.destroy?.(); } catch (_) {} + detachPlayerFromManager(remix, player, channelId); + } + + const { channel, definitive } = await this._resolve247Channel(channelId); + if (!channel && definitive) { + if (this._prune247Channel(guildId, channelId)) { + pruned++; + remix.cancel247Rejoin?.(channelId); + logger.voice247(`[Watchdog247] ${channelId} no longer exists — pruned from 24/7 settings.`); + } + continue; + } + if (!channel && !definitive) { + skipped++; + continue; + } + if (channel && channel.type !== 2) { + if (this._prune247Channel(guildId, channelId)) { + pruned++; + remix.cancel247Rejoin?.(channelId); + logger.voice247(`[Watchdog247] ${channelId} is not a voice channel anymore — pruned.`); + } + continue; + } + + if (typeof remix.schedule247Rejoin === "function") { + remix.schedule247Rejoin(channelId, guildId); + healed++; + } + } + + const savedSet = new Set(savedChannels.map(c => c.channelId)); + for (const timerKey of remix._247RejoinTimers?.keys() ?? []) { + if (!savedSet.has(cleanId(timerKey))) { + remix.cancel247Rejoin?.(timerKey); + logger.voice247(`[Watchdog247] Cancelled stale rejoin timer for ${timerKey} (not a saved 24/7 channel).`); + } + } + + if (healthy || healed || pruned || skipped) { + logger.voice247( + `[Watchdog247] Sweep done — healthy: ${healthy}, re-armed: ${healed}, ` + + `pruned: ${pruned}, skipped: ${skipped}.` + ); + } + }, +}; + + +export default Watchdog247; +export { Watchdog247 }; diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index 1502846..8a9ad0a 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -652,7 +652,18 @@ "allChannelsLabel": "❌ All Channels", "allChannelsDisabled": "24/7 mode **disabled** for all channels in this server.\nThe bot will leave voice after inactivity.", "noChannelsSavedShort": "No channels saved", - "joinFailed": "⚠️ 24/7 {{mode}} saved, but failed to join <#{{channel}}>.\nError: `{{error}}`\n\nTry `{{prefix}}join` or `{{prefix}}play` later." + "joinFailed": "⚠️ 24/7 {{mode}} saved, but failed to join <#{{channel}}>.\nError: `{{error}}`\n\nTry `{{prefix}}join` or `{{prefix}}play` later.", + "statusConnected": "🟢 Connected", + "statusReconnecting": "🟡 Reconnecting", + "statusOffline": "🔴 Offline", + "autoRecoveryLine": "♻️ Auto-recovery active — saved channels are checked every {{seconds}}s", + "autoRecoveryDisabledLine": "♻️ Auto-recovery standing by", + "enabledLine": "✅ 24/7 is **enabled** — the bot stays connected and auto-rejoins if disconnected.", + "disabledHint": "Join a voice channel and use `{{prefix}}247` to enable.", + "footerLine": "{{prefix}}247 · toggle · {{prefix}}247 off · disable all", + "confirmEnabled": "✅ 24/7 enabled in {{channel}} — the bot will stay connected and auto-rejoin if disconnected.", + "confirmDisabled": "❌ 24/7 disabled in {{channel}} — the bot will leave when idle.", + "confirmDisabledAll": "❌ 24/7 disabled for all channels in this server — the bot will leave when idle." } }, "shuffle": {