... testing

This commit is contained in:
NoLogicAlan committed 2026-05-14 22:47:34 +03:00
1 parent 84c2bc0aca
commit 0f526c2d38
3 files changed
+146 -27

No files matched your search

+29 -5
View File
@@ -1275,13 +1275,37 @@ export class GatewayHandler {
// During startup grace batch, suppress individual cleanup logs to reduce spam // During startup grace batch, suppress individual cleanup logs to reduce spam
const batchMode = this._deferredDeleteCount > 3; const batchMode = this._deferredDeleteCount > 3;
// Protect 24/7 voice connections from GuildDelete cleanup ──
// During startup, the gateway sends GuildDelete for guilds that are
// temporarily unavailable. If we destroy players for 24/7 channels,
// BootRecovery has to rejoin from scratch, causing audio interruption.
// Instead, skip destroying players that have an active 24/7 mode
// and still have a healthy LiveKit room connection — the guild will
// come back via GuildCreate, and the voice connection stays alive.
for (const [channelId, player] of remix.players.playerMap) { for (const [channelId, player] of remix.players.playerMap) {
if (String(player._guildId ?? "").replace(/\D/g, "") === cleanGuildId) { if (String(player._guildId ?? "").replace(/\D/g, "") !== cleanGuildId) continue;
remix.players.playerMap.delete(channelId);
try { player.leave().catch(() => {}); } catch (_) {} // Check if this player is a 24/7 channel with an active connection
try { player.destroy(); } catch (_) {} const is247 = player._is247Enabled();
if (!batchMode) logger.guild(`[GuildDelete] Destroyed player for channel ${channelId}.`); const roomAlive = player.connection?.room?.isConnected ?? false;
if (is247 && roomAlive) {
// The LiveKit room is still connected and this is a 24/7 channel.
// The GuildDelete is stale (guild is temporarily unavailable).
// Keep the player alive — the guild will come back via GuildCreate.
if (!batchMode) {
logger.guild(
`[GuildDelete] Preserving 24/7 player for channel ${channelId} ` +
`(LiveKit room still connected — guild ${cleanGuildId} likely temporarily unavailable).`
);
}
continue;
} }
remix.players.playerMap.delete(channelId);
try { player.leave().catch(() => {}); } catch (_) {}
try { player.destroy(); } catch (_) {}
if (!batchMode) logger.guild(`[GuildDelete] Destroyed player for channel ${channelId}.`);
} }
for (const [userId, info] of [...remix.observedVoiceUsers]) { for (const [userId, info] of [...remix.observedVoiceUsers]) {
+73 -19
View File
@@ -666,27 +666,81 @@ export default class Player extends EventEmitter {
// re-check after async stop — player may have been destroyed // re-check after async stop — player may have been destroyed
if (this._destroyed) return false; if (this._destroyed) return false;
try { // publishToRoom with timeout and retry ──
this._mediaPlayer = new MediaPlayer(); // publishToRoom has no internal timeout and can hang indefinitely if the
this._mediaPlayer.setMaxListeners(0); // LiveKit server is slow or the network is congested. We wrap it in a
await this._mediaPlayer.publishToRoom(room); // Promise.race with a timeout, and retry up to 3 times with exponential
logger.mediaplayer("[Player] MediaPlayer published successfully"); // backoff. On final failure, we DON'T leave the channel — the player
return true; // stays connected and can retry later (critical for 24/7 channels).
} catch (e) { const PUBLISH_TIMEOUT_MS = 15_000; // 15s timeout per attempt
// "engine is closed" = LiveKit room disconnected mid-publish (transient race). const MAX_RETRIES = 3;
// Anything else = real failure. Both return false so the caller can retry, const BASE_BACKOFF_MS = 2_000;
// but we distinguish them in the log for easier diagnosis.
const isTransient = e.message?.includes("engine is closed") || for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
e.message?.includes("engine: connection error"); // Re-check room state before each attempt
if (isTransient) { if (!room.isConnected || this._destroyed) {
logger.mediaplayer(`[Player] publishToRoom transient fail (room mid-teardown): ${e.message}`); logger.mediaplayer(`[Player] Room disconnected or player destroyed before attempt ${attempt} — aborting`);
} else { return false;
logger.error(`[Player] publishToRoom failed: ${e.message}`); }
try {
this._mediaPlayer = new MediaPlayer();
this._mediaPlayer.setMaxListeners(0);
// Race publishToRoom against a timeout
await Promise.race([
this._mediaPlayer.publishToRoom(room),
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`publishToRoom timed out after ${PUBLISH_TIMEOUT_MS}ms`)), PUBLISH_TIMEOUT_MS)
),
]);
logger.mediaplayer(`[Player] MediaPlayer published successfully on attempt ${attempt}`);
return true;
} catch (e) {
const msg = e?.message ?? String(e);
const isTransient = msg.includes("engine is closed") ||
msg.includes("engine: connection error");
const isTimeout = msg.includes("timed out");
if (isTransient) {
logger.mediaplayer(`[Player] publishToRoom transient fail on attempt ${attempt} (room mid-teardown): ${msg}`);
} else if (isTimeout) {
logger.warn(`[Player] publishToRoom timed out on attempt ${attempt}/${MAX_RETRIES}: ${msg}`);
} else {
logger.error(`[Player] publishToRoom failed on attempt ${attempt}/${MAX_RETRIES}: ${msg}`);
}
// Clean up the failed MediaPlayer
try { this._mediaPlayer?.stop?.(); } catch (_) {}
this._mediaPlayer = null;
// If the room disconnected mid-attempt, don't retry
if (!room.isConnected || this._destroyed) {
logger.mediaplayer(`[Player] Room disconnected during publish attempt — aborting retries`);
return false;
}
// If we have more retries left, wait with backoff before retrying
if (attempt < MAX_RETRIES) {
const backoff = Math.min(BASE_BACKOFF_MS * Math.pow(2, attempt - 1), 10_000);
logger.mediaplayer(`[Player] Retrying publishToRoom in ${backoff}ms...`);
await new Promise(r => setTimeout(r, backoff));
} else {
// On final failure, DON'T leave the channel. The voice
// connection is still alive — just the audio publishing failed.
// Leaving the channel on play failure causes 24/7 drops. The
// player can retry publishing when the next track is played.
logger.error(
`[Player] All ${MAX_RETRIES} publishToRoom attempts failed — ` +
`staying in channel (connection still alive). Playback will retry on next track.`
);
return false;
}
} }
try { this._mediaPlayer?.stop?.(); } catch (_) {}
this._mediaPlayer = null;
return false;
} }
return false;
} }
async _stopMediaPlayer() { async _stopMediaPlayer() {
+44 -3
View File
@@ -606,11 +606,14 @@ export class FluxerRevoice extends EventEmitter {
if (e.message?.includes("401") || e.message?.includes("Unauthorized")) { if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
const gId = channelGuildId ?? this._resolveGuildForChannel(channelId); const gId = channelGuildId ?? this._resolveGuildForChannel(channelId);
if (gId) { if (gId) {
// Set 15-second cooldown for this guild to prevent rapid 401 retries // Reduced cooldown from 15s to 5s. 15s was too aggressive —
this._guild401Cooldown.set(gId, Date.now() + 15_000); // it blocked all join attempts for the guild for too long, causing
// BootRecovery to fail entirely. 5s is enough for the gateway to
// clean up the stale voice session.
this._guild401Cooldown.set(gId, Date.now() + 5_000);
logger.warn( logger.warn(
`[FluxerRevoice] 401 error for channel ${channelId} — ` + `[FluxerRevoice] 401 error for channel ${channelId} — ` +
`setting 15s cooldown for guild ${gId}` `setting 5s cooldown for guild ${gId}`
); );
} }
} }
@@ -741,6 +744,44 @@ export class FluxerRevoice extends EventEmitter {
if (nativeConnection && typeof nativeConnection.disconnect === "function") { if (nativeConnection && typeof nativeConnection.disconnect === "function") {
try { nativeConnection.disconnect(); } catch (_) {} try { nativeConnection.disconnect(); } catch (_) {}
} }
// Auto-rejoin on unexpected disconnect (serverLeave) ──
// Per the Fluxer.js Voice guide: "If using LiveKit, the server may
// emit serverLeave. Listen and reconnect if needed." When the LiveKit
// room disconnects unexpectedly (token expiry, server restart, network
// blip), we attempt to rejoin the same channel after a short delay.
// The rejoin triggers a fresh VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE
// flow, giving us a new LiveKit token. The global join queue ensures
// we don't collide with other in-flight joins.
if (channelGuildId) {
const rejoinDelay = 3_000; // 3s delay to let the gateway settle
logger.player(
`[FluxerRevoice] Scheduling auto-rejoin for channel ${channelId} ` +
`in ${rejoinDelay}ms after unexpected disconnect`
);
setTimeout(async () => {
try {
// Check if the bot was intentionally disconnected in the meantime
if (this._intentionalDisconnects.has(String(channelId))) {
logger.player(`[FluxerRevoice] Skipping auto-rejoin — intentional disconnect detected for ${channelId}`);
return;
}
// Check if another connection already exists (e.g. user ran !join)
if (this.connections.has(channelId)) {
logger.player(`[FluxerRevoice] Skipping auto-rejoin — connection already exists for ${channelId}`);
return;
}
logger.player(`[FluxerRevoice] Auto-rejoining channel ${channelId}...`);
await this.join(channelId);
logger.player(`[FluxerRevoice] Auto-rejoin succeeded for channel ${channelId}`);
} catch (e) {
logger.warn(
`[FluxerRevoice] Auto-rejoin failed for channel ${channelId}: ${e?.message ?? e}. ` +
`BootRecovery will retry on next restart.`
);
}
}, rejoinDelay);
}
} }
connection.emit("disconnect"); connection.emit("disconnect");