fix(status-channel): add automatic retry on transient socket closures during card updates

- Detect transient socket errors (other side closed, ECONNRESET, UND_ERR_SOCKET)
- Add 2x retry backoff in _patchMessage and _postMessage in StatusChannelManager
- Suppress single-tick transient socket resets from triggering warning channel embeds
This commit is contained in:
NoLogicAlan committed 2026-11-15 00:26:33 +03:00
1 parent 755efa5afd
commit 5ac04535f3
2 files changed
+77 -31

No files matched your search

+2
View File
@@ -290,6 +290,8 @@ function _forward(level, tag, args) {
const body = _formatArgs(args); const body = _formatArgs(args);
/* Suppress expected external not-found lookups from generating alarmist telemetry warnings */ /* Suppress expected external not-found lookups from generating alarmist telemetry warnings */
if (tag.includes("[LastFm]") && (/not found|error 6:/i.test(body) || /Track not found/i.test(body))) return; if (tag.includes("[LastFm]") && (/not found|error 6:/i.test(body) || /Track not found/i.test(body))) return;
/* Suppress transient socket drops from routine status channel updates */
if (tag.includes("[StatusChannel]") && (/other side closed/i.test(body) || /fetch failed/i.test(body))) return;
const now = Date.now(); const now = Date.now();
const key = `${level}|${tag}|${(body || tag).slice(0, 200)}`; const key = `${level}|${tag}|${(body || tag).slice(0, 200)}`;
const last = _forwardDedup.get(key); const last = _forwardDedup.get(key);
+75 -31
View File
@@ -19,6 +19,22 @@ import { logger } from "../core/Logger.mjs";
/** @type {string} Default API endpoint for direct REST fallback */ /** @type {string} Default API endpoint for direct REST fallback */
const DEFAULT_API_BASE = "https://fluxer.com/api/v1"; const DEFAULT_API_BASE = "https://fluxer.com/api/v1";
/**
* @private
* Detect transient network or socket reset errors that can be retried.
* @param {Error|object} err
* @returns {boolean}
*/
function isTransientNetworkError(err) {
if (!err) return false;
const msg = String(err?.message ?? err);
const cause = String(err?.cause?.message ?? err?.cause ?? "");
return (
/other side closed|fetch failed|ECONNRESET|ETIMEDOUT|ECONNREFUSED|UND_ERR_SOCKET|socket hang up/i.test(msg) ||
/other side closed|ECONNRESET|ETIMEDOUT|ECONNREFUSED|UND_ERR_SOCKET/i.test(cause)
);
}
/** /**
* @class StatusChannelManager * @class StatusChannelManager
* @description Oversees public status notifications and live health telemetry. * @description Oversees public status notifications and live health telemetry.
@@ -233,15 +249,21 @@ export class StatusChannelManager {
if (this.liveMessageId) { if (this.liveMessageId) {
try { try {
await this._patchMessage(this.liveMessageId, { embeds: [embed] }); await this._patchMessage(this.liveMessageId, { embeds: [embed] });
this._consecutivePatchFailures = 0;
return; return;
} catch (err) { } catch (err) {
const status = err?.statusCode ?? err?.status; const status = err?.statusCode ?? err?.status;
/* If message was deleted (404), fall through to post a fresh one */ /* If message was deleted (404), fall through to post a fresh one */
if (status !== 404) { if (status === 404) {
logger.warn("[StatusChannel] Failed to patch status card:", err?.message); this.liveMessageId = null;
} else {
this._consecutivePatchFailures = (this._consecutivePatchFailures || 0) + 1;
/* Only log warning if not a transient network drop or if failing repeatedly */
if (!isTransientNetworkError(err) || this._consecutivePatchFailures >= 3) {
logger.warn("[StatusChannel] Failed to patch status card:", err?.message);
}
return; return;
} }
this.liveMessageId = null;
} }
} }
@@ -504,50 +526,72 @@ export class StatusChannelManager {
} }
/** /**
* Post a message to the status channel with raw fetch fallback. * Post a message to the status channel with raw fetch fallback and transient retry.
* @private * @private
* @param {object} payload * @param {object} payload
* @param {number} [retries=2]
* @returns {Promise<object>} * @returns {Promise<object>}
*/ */
async _postMessage(payload) { async _postMessage(payload, retries = 2) {
const body = this._normalizePayload(payload); const body = this._normalizePayload(payload);
const rest = this.client?.rest; for (let attempt = 0; attempt <= retries; attempt++) {
if (typeof rest?.post === "function") { try {
return await rest.post(`/channels/${this.channelId}/messages`, { body }); const rest = this.client?.rest;
if (typeof rest?.post === "function") {
return await rest.post(`/channels/${this.channelId}/messages`, { body });
}
const token = this.client?.token || this.remix.config?.token;
const res = await fetch(`${this.apiBase}/channels/${this.channelId}/messages`, {
method: "POST",
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new Error("HTTP " + res.status);
return await res.json().catch(() => ({}));
} catch (err) {
if (attempt < retries && isTransientNetworkError(err)) {
await new Promise((res) => setTimeout(res, 1_000 * (attempt + 1)));
continue;
}
throw err;
}
} }
const token = this.client?.token || this.remix.config?.token;
const res = await fetch(`${this.apiBase}/channels/${this.channelId}/messages`, {
method: "POST",
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new Error("HTTP " + res.status);
return await res.json().catch(() => ({}));
} }
/** /**
* Patch an existing message in the status channel with raw fetch fallback. * Patch an existing message in the status channel with raw fetch fallback and transient retry.
* @private * @private
* @param {string} messageId * @param {string} messageId
* @param {object} payload * @param {object} payload
* @param {number} [retries=2]
* @returns {Promise<object>} * @returns {Promise<object>}
*/ */
async _patchMessage(messageId, payload) { async _patchMessage(messageId, payload, retries = 2) {
const body = this._normalizePayload(payload); const body = this._normalizePayload(payload);
const rest = this.client?.rest; for (let attempt = 0; attempt <= retries; attempt++) {
if (typeof rest?.patch === "function") { try {
return await rest.patch(`/channels/${this.channelId}/messages/${messageId}`, { body }); const rest = this.client?.rest;
if (typeof rest?.patch === "function") {
return await rest.patch(`/channels/${this.channelId}/messages/${messageId}`, { body });
}
const token = this.client?.token || this.remix.config?.token;
const res = await fetch(`${this.apiBase}/channels/${this.channelId}/messages/${messageId}`, {
method: "PATCH",
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new Error("HTTP " + res.status);
return await res.json().catch(() => ({}));
} catch (err) {
if (attempt < retries && isTransientNetworkError(err)) {
await new Promise((res) => setTimeout(res, 1_000 * (attempt + 1)));
continue;
}
throw err;
}
} }
const token = this.client?.token || this.remix.config?.token;
const res = await fetch(`${this.apiBase}/channels/${this.channelId}/messages/${messageId}`, {
method: "PATCH",
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new Error("HTTP " + res.status);
return await res.json().catch(() => ({}));
} }
/** /**