mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
...
This commit is contained in:
1 parent
f073b78449
commit
85c4bf4e8d
9 files changed
+475
-88
No files matched your search
+36
-6
@@ -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<void>}
|
||||
*/
|
||||
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<void>}
|
||||
* @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(() => {
|
||||
|
||||
@@ -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]),
|
||||
|
||||
@@ -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 };
|
||||
@@ -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<void>}
|
||||
* @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 };
|
||||
Reference in new issue
Block a user