diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 2e24169..a9a8f05 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -8,6 +8,10 @@ services: depends_on: mysql: condition: service_healthy + redis: + condition: service_healthy + nodelink: + condition: service_healthy volumes: - ./config.json:/app/config.json - ../storage:/app/storage @@ -63,6 +67,12 @@ services: - ./nodelink.config.json:/nodelink/config.json:ro ports: - "${NODELINK_PORT:-3000}:3000" + healthcheck: + test: ["CMD", "node", "-e", "require('net').connect(3000,'127.0.0.1').on('connect',function(){process.exit(0)}).on('error',function(){process.exit(1)})"] + interval: 5s + timeout: 3s + retries: 30 + start_period: 60s networks: - remix-net diff --git a/src/dashboard/RedisHandler.mjs b/src/dashboard/RedisHandler.mjs index 104c781..0da6a77 100644 --- a/src/dashboard/RedisHandler.mjs +++ b/src/dashboard/RedisHandler.mjs @@ -41,6 +41,9 @@ export class RedisHandler { /** @private @type {boolean} Whether the handler has been destroyed. */ _destroyed = false; + /** @private @type {{main: number, subscriber: number}} Consecutive socket errors since the last successful connect, per client. */ + _errorStreaks = { main: 0, subscriber: 0 }; + /** * Create a new RedisHandler and immediately begin connecting. * @param {object} [opts={}] - Redis connection options (passed to `createClient`). @@ -51,6 +54,7 @@ export class RedisHandler { const { platform: _platform, ...clientOpts } = { ...opts }; clientOpts.socket = { + connectTimeout: 5_000, ...(clientOpts.socket ?? {}), reconnectStrategy: DEFAULT_RETRY_STRATEGY, }; @@ -58,16 +62,40 @@ export class RedisHandler { this.client = createClient(clientOpts); this.client.on("error", (err) => { logger.warn("[Redis/Main] Error:", err.message); + this._noteErrorStreak("main"); }); + this.client.on("ready", () => { this._errorStreaks.main = 0; }); this.subscriber = this.client.duplicate(); this.subscriber.on("error", (err) => { logger.warn("[Redis/Subscriber] Error:", err.message); + this._noteErrorStreak("subscriber"); }); + this.subscriber.on("ready", () => { this._errorStreaks.subscriber = 0; }); this._connect(); } + /** + * After enough consecutive failures on one client, log a single actionable + * diagnostic instead of letting the identical connection-error line repeat + * forever. Resets whenever that client reaches "ready". + * @private + * @param {"main"|"subscriber"} which + */ + _noteErrorStreak(which) { + this._errorStreaks[which] = (this._errorStreaks[which] ?? 0) + 1; + if (this._errorStreaks[which] === 8) { + const label = which === "main" ? "Main" : "Subscriber"; + logger.error( + `[Redis/${label}] Still failing to connect after repeated attempts — this looks like a ` + + "network-reachability problem, not an app bug: confirm the host in config.json -> dashboard.redis.url " + + "is reachable from inside the bot's container. If Redis runs in the same docker-compose stack, point " + + "this at the service name (e.g. redis://redis:6379) instead of a bare external IP." + ); + } + } + /** * Connect both the publisher and subscriber clients, then subscribe * to the "request" and "info" channels and start the ping interval. diff --git a/src/db/MysqlGuard.mjs b/src/db/MysqlGuard.mjs index 0ea54af..b2973b1 100644 --- a/src/db/MysqlGuard.mjs +++ b/src/db/MysqlGuard.mjs @@ -59,9 +59,16 @@ const _guardedPools = new WeakSet(); * Idempotent: calling twice on the same pool is a no-op. * @param {object} pool - mysql2 Pool or PromisePool instance. * @param {string} [label="MySQL"] - Label used in log lines. + * @param {object} [options={}] + * @param {number} [options.keepAliveIntervalMs=20000] - How often to ping the pool + * with a trivial query to keep at least one connection active. Many shared/cheap + * MySQL hosts enforce a `wait_timeout` well under mysql2's own 60s idle default + * (error 4031, "disconnected because of inactivity") — a query at this interval + * keeps connections from ever sitting idle long enough to get killed server-side. + * Set to 0 to disable. * @returns {object} The core (callback-API) pool that was guarded. */ -function attachMysqlPoolGuard(pool, label = "MySQL") { +function attachMysqlPoolGuard(pool, label = "MySQL", { keepAliveIntervalMs = 20_000 } = {}) { if (!pool) return pool; const corePool = typeof pool.getConnection === "function" && pool.pool && pool.pool.getConnection ? pool.pool @@ -86,6 +93,17 @@ function attachMysqlPoolGuard(pool, label = "MySQL") { logger.error(`[${label}] MySQL pool error:`, err?.code ?? err?.message ?? err); }); + if (keepAliveIntervalMs > 0) { + const timer = setInterval(() => { + corePool.query("SELECT 1", (err) => { + if (err) { + logger.warn(`[${label}] Keepalive ping failed:`, err?.code ?? err?.message ?? err); + } + }); + }, keepAliveIntervalMs); + timer.unref?.(); + } + return corePool; } diff --git a/src/services/lastfm/ScrobblingMixin.mjs b/src/services/lastfm/ScrobblingMixin.mjs index fe01d50..9a4e999 100644 --- a/src/services/lastfm/ScrobblingMixin.mjs +++ b/src/services/lastfm/ScrobblingMixin.mjs @@ -7,7 +7,7 @@ */ import { logger } from "../../core/Logger.mjs"; -import { apiCall, isLastFmUserNotFound, noteStaleUser } from "./constants.mjs"; +import { apiCall, isLastFmFatalLinkError, isLastFmUserNotFound, noteStaleUser } from "./constants.mjs"; /** * @type {object} @@ -42,6 +42,12 @@ const ScrobblingMixin = { } return; } + if (isLastFmFatalLinkError(err)) { + if (noteStaleUser(this, userId)) { + logger.warn(`[LastFm] Now-playing updates paused for ${userId}: ${err.message} (session revoked — attempting auto-recovery, will auto-unlink if unrecoverable)`); + } + return; + } logger.warn(`[LastFm] updateNowPlaying failed for ${userId}: ${err.message}`); } }, @@ -77,6 +83,12 @@ const ScrobblingMixin = { } return; } + if (isLastFmFatalLinkError(err)) { + if (noteStaleUser(this, userId)) { + logger.warn(`[LastFm] Scrobbling paused for ${userId}: ${err.message} (session revoked — attempting auto-recovery, will auto-unlink if unrecoverable)`); + } + return; + } logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`); } }, @@ -106,6 +118,12 @@ const ScrobblingMixin = { } return 0; } + if (isLastFmFatalLinkError(e)) { + if (noteStaleUser(this, userId)) { + logger.warn(`[LastFm] Scrobble count sync skipped for ${userId}: ${e.message} (session revoked — attempting auto-recovery, will auto-unlink if unrecoverable)`); + } + return 0; + } logger.warn("[LastFm] Error:", e?.message); return 0; } diff --git a/src/services/lastfm/constants.mjs b/src/services/lastfm/constants.mjs index d0298bc..0626eb7 100644 --- a/src/services/lastfm/constants.mjs +++ b/src/services/lastfm/constants.mjs @@ -74,7 +74,10 @@ function isLastFmUserNotFound(err) { function isLastFmFatalLinkError(err) { if (isLastFmUserNotFound(err)) return true; const msg = String(err?.message ?? ""); - return /Last\.fm error 4:/.test(msg) || /authentication failed/i.test(msg); + return /Last\.fm error [49]:/.test(msg) + || /authentication failed/i.test(msg) + || /invalid session key/i.test(msg) + || /Last\.fm HTTP 40[13]:/.test(msg); } /** @type {Set} @description Users already warned about as stale (dedup for background flows). */