From 0f085a6ae4a16c4acf0f2464bd9120b4b45e9418 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Fri, 4 Sep 2026 20:40:04 +0300 Subject: [PATCH] ...little changes --- commands/stats.mjs | 426 ++++++++++++++++++++++++++++----------------- 1 file changed, 268 insertions(+), 158 deletions(-) diff --git a/commands/stats.mjs b/commands/stats.mjs index fd7cb6c..9dd45f0 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -3,6 +3,8 @@ * @description Display bot statistics including guild count, user count, uptime, and ping. */ +import * as fs from "node:fs"; +import * as path from "node:path"; import { CommandBuilder } from "../src/CommandHandler.mjs"; import { Utils } from "../src/Utils.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; @@ -19,89 +21,188 @@ export const command = new CommandBuilder() .addAliases("info") .setCategory("util"); +/** Cache is considered fresh for this long; older values trigger a background refresh. */ const CACHE_TTL_MS = 5 * 60 * 1000; +/** Max time the fill-in edit waits for Last.fm values before giving up (next run shows them). */ +const LASTFM_FILL_BUDGET_MS = 2500; +/** Max time the fill-in edit waits for the background refresh to produce a user count. */ +const REFRESH_FILL_BUDGET_MS = 10_000; +/** How many times a rate-limited message send is retried before giving up. */ +const RATE_LIMIT_MAX_RETRIES = 2; +/** Upper bound for a single rate-limit backoff wait. */ +const RATE_LIMIT_MAX_WAIT_MS = 15_000; +/** Where the warm cache is persisted (cwd-relative, same convention as ./storage/defaults.json). */ +const CACHE_FILE = path.join(process.cwd(), "storage", "stats-cache.json"); -let cachedUserCount = null; -let cacheExpiresAt = 0; -let inflightPromise = null; +let cache = { guilds: null, users: null, scrobbles: null, linkedUsers: null, updatedAt: 0 }; +let lastPing = null; +let refreshInflight = null; -/** - * Run tasks with a concurrency limit. - * @private - * @param {number} limit - Maximum number of concurrent tasks. - * @param {Function[]} tasks - Array of task functions to execute. - * @returns {Promise} Array of task results. - */ -async function pool(limit, tasks) { - const results = []; - const executing = new Set(); - for (const task of tasks) { - const p = Promise.resolve().then(task).then(r => { results.push(r); executing.delete(p); }); - executing.add(p); - if (executing.size >= limit) await Promise.race(executing); - } - await Promise.all(executing); - return results; +try { + const raw = JSON.parse(fs.readFileSync(CACHE_FILE, "utf8")); + cache = { + guilds: typeof raw?.guilds === "number" ? raw.guilds : null, + users: typeof raw?.users === "number" ? raw.users : null, + scrobbles: typeof raw?.scrobbles === "number" ? raw.scrobbles : null, + linkedUsers: typeof raw?.linkedUsers === "number" ? raw.linkedUsers : null, + updatedAt: typeof raw?.updatedAt === "number" ? raw.updatedAt : 0, + }; +} catch { + /* first run or unreadable cache — start cold, warm up in background */ } -/** - * Fetch the total member count for a guild by paginating through members. - * @private - * @async - * @param {object} guild - The Discord guild object. - * @returns {Promise} Total member count. - */ -async function fetchGuildMemberCount(guild) { +/** Persist the current cache to disk so the next restart serves warm data. @private */ +function persistCache() { try { - let after = undefined; - let total = 0; - for (let page = 0; page < 1000; page++) { - const raw = await guild.members.fetch({ limit: 1000, after }); - const batch = Array.isArray(raw) - ? raw - : typeof raw?.values === "function" - ? [...raw.values()] - : Object.values(raw ?? {}); - total += batch.length; - if (batch.length < 1000) break; - after = batch.reduce((max, m) => { - const id = m.id ?? m.user?.id ?? ""; - return id > max ? id : max; - }, "0"); - } - return total; + fs.mkdirSync(path.dirname(CACHE_FILE), { recursive: true }); + fs.writeFileSync(CACHE_FILE, JSON.stringify(cache)); } catch (e) { - logger.warn("[Stats] Error:", e?.message); - return guild.memberCount ?? guild.members?.size ?? 0; + logger.warn("[Stats] Failed to persist stats cache:", e?.message); } } /** - * Refresh the cached total user count across all guilds. + * Sum guild and member totals directly from the gateway cache. + * memberCount comes with every guild payload, so no member listing is needed. * @private - * @async - * @param {object} client - The Discord client instance. - * @returns {Promise} Total user count. + * @param {object} client - The client instance. + * @returns {{guilds: number, users: number}} Instant totals. */ -async function refreshUserCount(client) { - const guilds = [...client.guilds.values()]; - const counts = await pool(10, guilds.map(g => () => fetchGuildMemberCount(g))); - cachedUserCount = counts.reduce((a, b) => a + b, 0); - cacheExpiresAt = Date.now() + CACHE_TTL_MS; - inflightPromise = null; - return cachedUserCount; +function computeInstantTotals(client) { + let guilds = 0; + let users = 0; + for (const guild of client.guilds.values()) { + guilds++; + users += guild.memberCount ?? guild.members?.size ?? 0; + } + return { guilds, users }; } /** - * Get the total user count, using cache if still valid or refreshing if expired. + * Resolve the totals to display right now, merging the gateway cache with the + * last known values. While the cache is fresh, the higher of the two smooths + * over guilds still streaming in; the background refresh rewrites cache.users + * with the pure gateway sum so counts still drop when members leave. * @private - * @param {object} client - The Discord client instance. - * @returns {Promise} Total user count. + * @param {object} client - The client instance. + * @returns {{guildCount: number, userCount: number, needsLoading: boolean}} */ -function getUserCount(client) { - if (cachedUserCount !== null && Date.now() < cacheExpiresAt) return Promise.resolve(cachedUserCount); - if (!inflightPromise) inflightPromise = refreshUserCount(client); - return inflightPromise; +function getTotals(client) { + const instant = computeInstantTotals(client); + const cacheFresh = cache.updatedAt > 0 && Date.now() - cache.updatedAt < CACHE_TTL_MS; + + const guildCount = instant.guilds || cache.guilds || 0; + const userCount = cacheFresh + ? Math.max(instant.users || 0, cache.users || 0) + : instant.users; + + const needsLoading = userCount === 0 && !cache.users; + return { guildCount, userCount, needsLoading }; +} + +/** + * Refresh the cache in the background if it is older than the TTL. + * Verifies the guild count via REST (covers guilds missing from the gateway + * cache) and warms the Last.fm totals. Results are persisted for restarts. + * @private + * @param {object} client - The client instance. + * @param {object|null} lastfm - The Last.fm manager, if enabled. + * @returns {void} + */ +function scheduleBackgroundRefresh(client, lastfm) { + if (cache.updatedAt > 0 && Date.now() - cache.updatedAt < CACHE_TTL_MS) return; + if (refreshInflight) return; + + refreshInflight = (async () => { + const instant = computeInstantTotals(client); + + let guilds = instant.guilds; + try { + let total = 0; + let after = null; + while (true) { + const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : ""); + const chunk = await client.rest.get(url); + if (!Array.isArray(chunk) || chunk.length === 0) break; + total += chunk.length; + if (chunk.length < 200) break; + after = chunk[chunk.length - 1].id; + } + if (total > 0) guilds = Math.max(guilds, total); + } catch (e) { + logger.warn("[Stats] Background guild count refresh failed:", e?.message); + } + + cache.guilds = guilds || cache.guilds; + cache.users = instant.users || cache.users; + cache.updatedAt = Date.now(); + persistCache(); + + if (lastfm?.enabled) { + const [sc, lu] = await Promise.allSettled([ + lastfm.getTotalScrobbles(), + lastfm.getLinkedUsersCount(), + ]); + if (sc.status === "fulfilled" && typeof sc.value === "number") cache.scrobbles = sc.value; + if (lu.status === "fulfilled" && typeof lu.value === "number") cache.linkedUsers = lu.value; + persistCache(); + } + })() + .catch((e) => logger.warn("[Stats] Background refresh failed:", e?.message)) + .finally(() => { refreshInflight = null; }); +} + +/** + * Race a promise against a timeout. Resolves `{ timedOut: true, value: fallback }` + * when the budget is spent; the underlying promise keeps running either way. + * @private + * @template T + * @param {Promise} promise - The promise to race. + * @param {number} ms - Timeout budget in milliseconds. + * @param {T} fallback - Value returned when the budget is spent or rejected. + * @returns {Promise<{timedOut: boolean, value: T}>} + */ +function withBudget(promise, ms, fallback) { + return new Promise((resolve) => { + let done = false; + const finish = (timedOut, value) => { + if (done) return; + done = true; + clearTimeout(timer); + resolve({ timedOut, value }); + }; + const timer = setTimeout(() => finish(true, fallback), ms); + timer.unref?.(); + promise.then( + (v) => finish(false, v), + () => finish(true, fallback), + ); + }); +} + +/** + * Run a message send/edit action, transparently retrying when the REST + * library throws a 429 RateLimitError. Waits exactly as long as the API + * asks for (capped), so bursts in a busy channel degrade to a short delay + * instead of an error. + * @private + * @template T + * @param {Function} fn - Async action returning the message. + * @param {string} [label] - Label used in warning logs. + * @returns {Promise} The action result. + */ +async function withRateLimitRetry(fn, label = "send") { + for (let attempt = 0; ; attempt++) { + try { + return await fn(); + } catch (e) { + const isRateLimit = e?.code === "RATE_LIMITED" || e?.statusCode === 429; + if (!isRateLimit || attempt >= RATE_LIMIT_MAX_RETRIES) throw e; + const waitMs = Math.min(Math.ceil((e.retryAfter ?? 1) * 1000), RATE_LIMIT_MAX_WAIT_MS); + logger.warn(`[Stats] Rate limited on ${label}, retrying in ${waitMs}ms (attempt ${attempt + 1}/${RATE_LIMIT_MAX_RETRIES})`); + await new Promise((r) => setTimeout(r, waitMs)); + } + } } /** @@ -135,89 +236,49 @@ function getLivePlayerCount(playerMap) { return live; } -let cachedGuildCount = null; -let guildCacheExpiresAt = 0; - -/** - * Get the total guild count via REST API with caching. - * @private - * @async - * @param {object} client - The Discord client instance. - * @returns {Promise} Total guild count. - */ -async function getGuildCount(client) { - if (cachedGuildCount !== null && Date.now() < guildCacheExpiresAt) { - return cachedGuildCount; - } - - try { - let total = 0; - let after = null; - - while (true) { - const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : ""); - const chunk = await client.rest.get(url); - - if (!Array.isArray(chunk) || chunk.length === 0) break; - - total += chunk.length; - - if (chunk.length < 200) break; - - after = chunk[chunk.length - 1].id; - } - - cachedGuildCount = total; - guildCacheExpiresAt = Date.now() + CACHE_TTL_MS; - return total; - } catch (e) { - logger.warn("[Stats] REST guild count fetch failed:", e?.message); - if (typeof client.guilds?.size === "number") return client.guilds.size; - return Object.keys(client.guilds ?? {}).length; - } -} - /** * Build the stats embed with all bot information. * @private * @param {Function} t - Translation function. * @param {object} msg - The command message wrapper. - * @param {object} stats - Statistics data object. - * @param {number} stats.guildCount - Number of guilds. - * @param {number} stats.userCount - Number of users. - * @param {number} stats.playerCount - Number of active players. - * @param {number} stats.scrobbleCount - Total Last.fm scrobbles. - * @param {number} stats.linkedUsers - Number of Last.fm linked users. - * @param {number} stats.ping - Bot response ping in ms. - * @param {string} stats.uptime - Formatted uptime string. - * @param {string} stats.comHash - Git commit hash. - * @param {string} stats.comLink - Git commit link URL. - * @param {string} [stats.reason] - Last restart reason. - * @param {string} [stats.footer] - Custom footer text. - * @param {boolean} stats.loading - Whether data is still loading. - * @param {boolean} stats.lastfmEnabled - Whether Last.fm integration is enabled. + * @param {object} s - Statistics data object. + * @param {number} s.guildCount - Number of guilds. + * @param {number} s.userCount - Number of users. + * @param {number} s.playerCount - Number of active players. + * @param {number} s.scrobbleCount - Total Last.fm scrobbles. + * @param {number} s.linkedUsers - Number of Last.fm linked users. + * @param {number} s.ping - Bot response ping in ms. + * @param {string} s.uptime - Formatted uptime string. + * @param {string} s.comHash - Git commit hash. + * @param {string} s.comLink - Git commit link URL. + * @param {string} [s.reason] - Last restart reason. + * @param {string} [s.footer] - Custom footer text. + * @param {boolean} s.lastfmEnabled - Whether Last.fm integration is enabled. + * @param {string[]} [pending] - Keys to render as "..." while still unknown. * @returns {EmbedBuilder} The constructed embed. */ -function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) { - const num = (v) => Utils.formatNumber(v); - const ld = (v) => loading ? "..." : v; +function buildEmbed(t, msg, s, pending = []) { + const num = (v) => Utils.formatNumber(v); + const field = (key, value) => `\`${pending.includes(key) ? "..." : value}\``; const description = [ - `${t(msg, "responses.stats.servers")} — \`${num(guildCount)}\``, - `${t(msg, "responses.stats.users")} — \`${ld(num(userCount))}\``, - `${t(msg, "responses.stats.players")} — \`${num(playerCount)}\``, + `${t(msg, "responses.stats.servers")} — ${field("guilds", num(s.guildCount))}`, + `${t(msg, "responses.stats.users")} — ${field("users", num(s.userCount))}`, + `${t(msg, "responses.stats.players")} — ${field("players", num(s.playerCount))}`, ]; - if (lastfmEnabled) { - description.push(`${t(msg, "responses.stats.scrobbles")} — \`${ld(num(scrobbleCount))}\``); - description.push(`${t(msg, "responses.stats.linkedUsers")} — \`${ld(num(linkedUsers))}\``); + if (s.lastfmEnabled) { + description.push( + `${t(msg, "responses.stats.scrobbles")} — ${field("scrobbles", num(s.scrobbleCount))}`, + `${t(msg, "responses.stats.linkedUsers")} — ${field("linkedUsers", num(s.linkedUsers))}`, + ); } description.push( - `${t(msg, "responses.stats.ping")} — \`${ld(`${num(ping)}ms`)}\``, - `${t(msg, "responses.stats.uptime")} — \`${uptime}\``, - `${t(msg, "responses.stats.build")} — [\`${comHash}\`](${comLink})`, - reason ? `${t(msg, "responses.stats.lastRestart")} — \`${reason}\`` : null, + `${t(msg, "responses.stats.ping")} — ${field("ping", `${num(s.ping)}ms`)}`, + `${t(msg, "responses.stats.uptime")} — \`${s.uptime}\``, + `${t(msg, "responses.stats.build")} — [\`${s.comHash}\`](${s.comLink})`, + s.reason ? `${t(msg, "responses.stats.lastRestart")} — \`${s.reason}\`` : null, ``, t(msg, "responses.stats.supportKofi"), t(msg, "responses.stats.community"), @@ -229,7 +290,7 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, .setColor(getGlobalColor()) .setAuthor({ name: t(msg, "responses.stats.title") }) .setDescription(desc) - .setFooter({ text: footer || t(msg, "responses.stats.title") }); + .setFooter({ text: s.footer || t(msg, "responses.stats.title") }); if (typeof builder.setTimestamp === "function") builder.setTimestamp(); return builder; @@ -237,8 +298,9 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, /** * Run handler for the stats command. - * Collects bot statistics and displays them in an embed, initially with loading - * state then edited with the real data. + * Replies instantly with everything known from the gateway cache and the warm + * cache; slow sources are refreshed in the background and filled in with a + * single bounded, fire-and-forget edit when needed. * * @param {object} message - The command message wrapper. * @returns {Promise} @@ -246,13 +308,28 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, export async function run(message) { const lastfm = this.lastfm; const lastfmEnabled = lastfm?.enabled ?? false; + const t = (...a) => this.t(...a); - const shared = { - guildCount: cachedGuildCount ?? this.client.guilds?.size ?? 0, + const totals = getTotals(this.client); + + scheduleBackgroundRefresh(this.client, lastfmEnabled ? lastfm : null); + + const pending = []; + if (totals.needsLoading) pending.push("users"); + if (lastfmEnabled) { + if (cache.scrobbles === null) pending.push("scrobbles"); + if (cache.linkedUsers === null) pending.push("linkedUsers"); + } + if (lastPing === null) pending.push("ping"); + + const embedData = { + guildCount: totals.guildCount, + userCount: totals.userCount, playerCount: getLivePlayerCount(this.players.playerMap), - scrobbleCount: 0, - linkedUsers: 0, + scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0, + linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0, lastfmEnabled, + ping: lastPing ?? 0, uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000), comHash: this.comHash, comLink: this.comLink, @@ -260,25 +337,58 @@ export async function run(message) { footer: this.config.customStatsFooter || null, }; - const scrobblePromise = lastfmEnabled ? lastfm.getTotalScrobbles() : Promise.resolve(0); - const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0); + let msg = null; + try { + msg = await withRateLimitRetry(async () => { + const t0 = Date.now(); + const m = await message.reply({ embeds: [buildEmbed(t, message, embedData, pending)] }); + lastPing = Date.now() - t0; + return m; + }, "stats reply"); + } catch (e) { + logger.warn("[Stats] Could not send stats reply:", e?.message); + return; + } - const hasCached = cachedUserCount !== null; + if (pending.length > 0) { + (async () => { + if (totals.needsLoading && refreshInflight) { + await withBudget(refreshInflight, REFRESH_FILL_BUDGET_MS, null); + } - const start = Date.now(); - const msg = await message.reply({ - embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, userCount: hasCached ? cachedUserCount : 0, ping: 0, loading: true })] - }); - const ping = Date.now() - start; + if (lastfmEnabled && (cache.scrobbles === null || cache.linkedUsers === null)) { + const [sc, lu] = await Promise.all([ + withBudget(lastfm.getTotalScrobbles(), LASTFM_FILL_BUDGET_MS, null), + withBudget(lastfm.getLinkedUsersCount(), LASTFM_FILL_BUDGET_MS, null), + ]); + if (!sc.timedOut && typeof sc.value === "number") cache.scrobbles = sc.value; + if (!lu.timedOut && typeof lu.value === "number") cache.linkedUsers = lu.value; + persistCache(); + } - const [users, scrobbleCount, linkedUsers, guildCount] = await Promise.all([ - getUserCount(this.client), - scrobblePromise, - linkedPromise, - getGuildCount(this.client), - ]); + const fresh = getTotals(this.client); + const fill = { + ...embedData, + guildCount: fresh.guildCount, + userCount: fresh.userCount, + scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0, + linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0, + ping: lastPing ?? 0, + }; - await msg.edit({ - embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, guildCount, userCount: users, scrobbleCount, linkedUsers, ping, loading: false })] - }).catch((err) => logger.error("[stats] editEmbed failed:", err)); + const stillPending = []; + if (fresh.userCount === 0 && !cache.users) stillPending.push("users"); + if (lastPing === null) stillPending.push("ping"); + if (lastfmEnabled) { + if (cache.scrobbles === null) stillPending.push("scrobbles"); + if (cache.linkedUsers === null) stillPending.push("linkedUsers"); + } + if (stillPending.length >= pending.length && stillPending.length > 0) return; + + await withRateLimitRetry( + () => msg.edit({ embeds: [buildEmbed(t, message, fill, stillPending)] }), + "stats fill-in edit", + ); + })().catch((e) => logger.warn("[Stats] Fill-in edit failed:", e?.message)); + } }