fix(gateway): resolve zombie connection hangs on gateway drops and reconnect opcodes

- Handle opcodes 7 (Reconnect) and 9 (InvalidSession) by terminating sockets and clearing session state for clean re-IDENTIFY
- Update gateway heartbeat timestamp exclusively on genuine Dispatch (op 0) and Heartbeat ACK (op 11)
- Trigger proactive shard reconnect immediately on raw WebSocket close events
- Tighten gateway watchdog intervals and add a hard-kill timeout on gracefulShutdown to prevent process hangs
- Allow child bot processes to control the Docker container health file
- Add guildId/guild getters on Message wrapper for robust command routing
This commit is contained in:
NoLogicAlan committed 2026-11-05 02:24:23 +03:00
1 parent 1251d8a53f
commit 36ad89b1d2
5 files changed
+157 -21

No files matched your search

+3 -1
View File
@@ -132,9 +132,11 @@ manager.on("error", (err) => {
const healthFile = path.join(os.tmpdir(), ".remix-health");
const updateHealth = () => {
try {
/* Only touch healthFile during supervisor boot before child shards are spawned.
* Once child processes exist, Bot.mjs in the child controls the heartbeat based on gateway health. */
if (manager.shards && manager.shards.size > 0) {
const anyAlive = [...manager.shards.values()].some(s => s.process && !s.process.killed);
if (!anyAlive) return;
if (anyAlive) return;
}
fs.writeFile(healthFile, Date.now().toString(), () => {});
} catch (_) {}
+1 -1
View File
@@ -143,7 +143,7 @@ export class CommandHandler extends EventEmitter {
return;
}
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const guildId = msg.guildId ?? msg.guild?.id ?? msg.channel?.guildId ?? msg.channel?.channel?.guildId ?? msg.message?.guildId ?? null;
const prefix = this.getPrefix(guildId);
const ping = `<@${this.client.user?.id}>`;
const pingBang = `<@!${this.client.user?.id}>`;
+63 -11
View File
@@ -273,6 +273,7 @@ class Remix {
/* Gateway activity timestamps and status tracking */
this._lastGatewayHeartbeat = Date.now();
this._lastGatewayDisconnect = 0;
this._gatewayConnected = false;
/* Event loop health heartbeat for Docker container healthcheck (Issue #12) */
@@ -280,9 +281,11 @@ class Remix {
const updateHealth = () => {
try {
/* Only touch health file if gateway is healthy or still in initial boot */
const silenceMs = this._hasBooted ? Date.now() - (this._lastGatewayHeartbeat || 0) : 0;
if (silenceMs < 90_000) {
fs.writeFile(healthFile, Date.now().toString(), () => {});
const now = Date.now();
const silenceMs = this._hasBooted ? now - (this._lastGatewayHeartbeat || 0) : 0;
const disconnectedMs = (!this._gatewayConnected && this._hasBooted) ? (now - (this._lastGatewayDisconnect || now)) : 0;
if (silenceMs < 60_000 && disconnectedMs < 45_000) {
fs.writeFile(healthFile, now.toString(), () => {});
}
} catch (_) {}
};
@@ -293,10 +296,12 @@ class Remix {
/* Active gateway self-healing watchdog */
this._gatewayWatchdogInterval = setInterval(async () => {
if (!this._hasBooted) return;
const silenceMs = Date.now() - (this._lastGatewayHeartbeat || 0);
const now = Date.now();
const silenceMs = now - (this._lastGatewayHeartbeat || 0);
const disconnectedMs = !this._gatewayConnected ? (now - (this._lastGatewayDisconnect || now)) : 0;
/* After 45s of silence, actively trigger reconnect attempts on local shards */
if (silenceMs >= 45_000) {
/* After 25s of silence or disconnection, actively trigger reconnect attempts on local shards */
if (!this._gatewayConnected || silenceMs >= 25_000) {
const shards = ShardingUtils.getLocalShards(this.client);
for (const [id, shard] of shards) {
try {
@@ -307,15 +312,25 @@ class Remix {
}
}
/* After 120s of total gateway silence (dead/zombie socket), perform graceful restart to auto-recover */
if (silenceMs >= 120_000) {
logger.error(`[GatewayWatchdog] Gateway unresponsive for ${Math.round(silenceMs / 1000)}s — performing graceful restart to restore service.`);
/* After 60s of total gateway silence or 45s of persistent disconnection, restart to auto-recover */
if (silenceMs >= 60_000 || disconnectedMs >= 45_000) {
logger.error(`[GatewayWatchdog] Gateway unresponsive (silence=${Math.round(silenceMs / 1000)}s, disconnected=${Math.round(disconnectedMs / 1000)}s) — performing graceful restart to restore service.`);
/* Hard kill timer in case gracefulShutdown hangs on network or database locks */
const hardKillTimer = setTimeout(() => {
process.exit(1);
}, 5_000);
hardKillTimer.unref?.();
try {
await this.gracefulShutdown();
await Promise.race([
this.gracefulShutdown(),
new Promise((_, reject) => setTimeout(() => reject(new Error("gracefulShutdown timed out")), 4_000))
]);
} catch (_) {}
process.exit(1);
}
}, 15_000);
}, 10_000);
this._gatewayWatchdogInterval.unref?.();
// Direct process signal fallback handlers
@@ -331,6 +346,9 @@ class Remix {
client.on(Events.Ready, async () => {
try {
logger.player("Logged in as " + (client.user?.username ?? "bot"));
this._lastGatewayHeartbeat = Date.now();
this._gatewayConnected = true;
this._lastGatewayDisconnect = 0;
this._attachWsErrorHandlers();
@@ -652,9 +670,43 @@ class Remix {
shard._fluxerErrorHandled = true;
attachedNew = true;
shard.on("error", (err) => logWsError(`Shard ${id}`, err));
if (typeof shard.on === "function") {
shard.on("disconnect", () => {
this._gatewayConnected = false;
if (!this._lastGatewayDisconnect) this._lastGatewayDisconnect = Date.now();
});
shard.on("resume", () => {
this._gatewayConnected = true;
this._lastGatewayHeartbeat = Date.now();
this._lastGatewayDisconnect = 0;
});
shard.on("ready", () => {
this._gatewayConnected = true;
this._lastGatewayHeartbeat = Date.now();
this._lastGatewayDisconnect = 0;
});
}
if (shard.ws) attachToSocket(shard.ws, `Shard ${id} socket`);
};
if (typeof this.client?.on === "function" && !this.client._fluxerShardEventsBound) {
this.client._fluxerShardEventsBound = true;
this.client.on("shardDisconnect", () => {
this._gatewayConnected = false;
if (!this._lastGatewayDisconnect) this._lastGatewayDisconnect = Date.now();
});
this.client.on("shardResume", () => {
this._gatewayConnected = true;
this._lastGatewayHeartbeat = Date.now();
this._lastGatewayDisconnect = 0;
});
this.client.on("shardReady", () => {
this._gatewayConnected = true;
this._lastGatewayHeartbeat = Date.now();
this._lastGatewayDisconnect = 0;
});
}
for (const [id, shard] of ShardingUtils.getLocalShards(this.client)) {
attachToShard(shard, id);
}
+4
View File
@@ -132,6 +132,10 @@ export class Message {
get attachments() { return this.message.attachments ?? []; }
/** @returns {Channel} The wrapped channel this message was sent in. */
get channel() { return this.handler.getChannel(this.message.channelId); }
/** @returns {string|null} The guild ID. */
get guildId() { return this.message?.guildId ?? this.message?.guild?.id ?? this.channel?.channel?.guildId ?? this.channel?.guildId ?? null; }
/** @returns {object|null} The guild instance, if available. */
get guild() { return this.message?.guild ?? this.channel?.channel?.guild ?? this.channel?.guild ?? null; }
/**
* Observe reactions on this message.
+86 -8
View File
@@ -22,7 +22,7 @@ import Watchdog247 from "./Watchdog247.mjs";
import RejoinBackoff from "./RejoinBackoff.mjs";
const RAW_GATEWAY_INTEREST =
/"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/;
/"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED|MESSAGE_CREATE)"|(?:0|7|9|10|11|12)\b)/;
/** @class GatewayHandler @description Handles all gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. Key responsibilities include voice state cache seeding and updates, bot move-away detection with 24/7 rejoin scheduling, boot recovery with sequential rejoin of 24/7 channels, inactivity timer management on human join/leave, and guild create/delete handling with startup grace period. */
class GatewayHandler {
@@ -147,28 +147,96 @@ class GatewayHandler {
if (!remix._rawGatewayHandler) {
remix._rawGatewayHandler = (data) => {
try {
remix._lastGatewayHeartbeat = Date.now();
remix._gatewayConnected = true;
const client = remix.client;
if (typeof data === "string" && !RAW_GATEWAY_INTEREST.test(data)) return;
const payload = typeof data === "string" ? JSON.parse(data) : data;
/* Opcode 11 (Heartbeat ACK): confirms the gateway received and acknowledged bot heartbeat */
if (payload?.op === GatewayOpcodes.HeartbeatAck || payload?.op === 11) {
remix._lastGatewayHeartbeat = Date.now();
remix._gatewayConnected = true;
remix._lastGatewayDisconnect = 0;
return;
}
if (payload?.op === GatewayOpcodes.GatewayError || payload?.op === 12) {
logger.warn("[Gateway] GatewayError (12) received from Fluxer:", payload.d);
remix._gatewayConnected = false;
if (!remix._lastGatewayDisconnect) remix._lastGatewayDisconnect = Date.now();
return;
}
if (payload?.op === GatewayOpcodes.Hello || payload?.op === 10) {
logger.player(`[Gateway] HELLO received (heartbeat ${payload.d?.heartbeat_interval ?? "unknown"}ms)`);
remix._gatewayConnected = true;
return;
}
/* Opcode 7 (Reconnect): Gateway requests immediate close and resume */
if (payload?.op === GatewayOpcodes.Reconnect || payload?.op === 7) {
logger.warn("[Gateway] RECONNECT requested by gateway.");
logger.warn("[Gateway] RECONNECT (op 7) requested by gateway — terminating socket to trigger reconnect.");
remix._gatewayConnected = false;
if (!remix._lastGatewayDisconnect) remix._lastGatewayDisconnect = Date.now();
this._lastReadyAt = 0;
const wsObjs = ShardingUtils.localShardSockets(client);
for (const ws of wsObjs) {
try {
if (typeof ws?.close === "function") ws.close(4000, "Gateway requested reconnect");
else if (typeof ws?.terminate === "function") ws.terminate();
} catch (_) {}
}
setTimeout(() => {
for (const [id, shard] of ShardingUtils.getLocalShards(client)) {
try {
if (typeof shard.connect === "function") shard.connect();
else if (typeof shard.reconnect === "function") shard.reconnect();
} catch (_) {}
}
}, 1_000).unref?.();
return;
}
/* Opcode 9 (InvalidSession): Session invalidated by gateway */
if (payload?.op === GatewayOpcodes.InvalidSession || payload?.op === 9) {
logger.warn("[Gateway] INVALID_SESSION received from gateway.");
const canResume = Boolean(payload.d);
logger.warn(`[Gateway] INVALID_SESSION (op 9, resumable=${canResume}) received from gateway.`);
remix._gatewayConnected = false;
if (!remix._lastGatewayDisconnect) remix._lastGatewayDisconnect = Date.now();
this._lastReadyAt = 0;
if (!canResume) {
for (const [id, shard] of ShardingUtils.getLocalShards(client)) {
try {
if (shard.sessionId) shard.sessionId = null;
if (shard.session_id) shard.session_id = null;
if (shard.resumeGatewayUrl) shard.resumeGatewayUrl = null;
} catch (_) {}
}
}
const wsObjs = ShardingUtils.localShardSockets(client);
for (const ws of wsObjs) {
try {
if (typeof ws?.close === "function") ws.close(canResume ? 4000 : 1000, "Invalid session");
else if (typeof ws?.terminate === "function") ws.terminate();
} catch (_) {}
}
setTimeout(() => {
for (const [id, shard] of ShardingUtils.getLocalShards(client)) {
try {
if (typeof shard.connect === "function") shard.connect();
else if (typeof shard.reconnect === "function") shard.reconnect();
} catch (_) {}
}
}, 1_500).unref?.();
return;
}
if (payload?.op !== 0) return;
/* Genuine Dispatch event (op 0) — gateway is actively delivering traffic */
remix._lastGatewayHeartbeat = Date.now();
remix._gatewayConnected = true;
remix._lastGatewayDisconnect = 0;
if (payload.t === "READY") {
logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`);
this._lastReadyAt = Date.now();
@@ -272,10 +340,20 @@ class GatewayHandler {
const code = eventOrCode?.code ?? (typeof eventOrCode === "number" ? eventOrCode : "unknown");
const reason = eventOrCode?.reason ?? maybeReason ?? "";
remix._gatewayConnected = false;
if (!remix._lastGatewayDisconnect) remix._lastGatewayDisconnect = Date.now();
const now = Date.now();
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
_wsErrorCooldown.lastLogged = now;
logger.warn(`[Gateway] Raw WebSocket closed (code=${code}, reason=${reason || "none"}) — watchdog tracking reconnect.`);
if (now - _wsErrorCooldown.lastLogged >= _wsErrorCooldown.COOLDOWN_MS) {
_wsErrorCooldown.lastLogged = now;
logger.warn(`[Gateway] Raw WebSocket closed (code=${code}, reason=${reason || "none"}) — proactively reconnecting shards.`);
}
/* Immediately attempt proactive shard reconnect */
for (const [id, shard] of ShardingUtils.getLocalShards(remix.client)) {
try {
if (typeof shard.connect === "function") shard.connect();
else if (typeof shard.reconnect === "function") shard.reconnect();
else if (typeof shard.ws?.connect === "function") shard.ws.connect();
} catch (_) {}
}
};
remix._rawGatewayMessageListener = (event) => remix._rawGatewayHandler(event?.data ?? event);
}