This commit is contained in:
NoLogicAlan committed 2026-05-13 16:18:46 +03:00
1 parent e4ae6a98bc
commit 77e6008649
1 file changed
+102 -56
+102 -56
View File
@@ -9,66 +9,98 @@ export const command = new CommandBuilder()
.addAliases("info") .addAliases("info")
.setCategory("util"); .setCategory("util");
// ── User count cache ────────────────────────────────────────────────────────── // ── Stats cache ───────────────────────────────────────────────────────────────
const CACHE_TTL_MS = 5 * 60 * 1000; // refresh every 5 minutes const CACHE_TTL_MS = 5 * 60 * 1000; // refresh every 5 minutes
let cachedUserCount = null; // null = never fetched, 0 = real zero let cachedStats = null; // { guildCount, userCount } or null
let cacheExpiresAt = 0; let cacheExpiresAt = 0;
let inflightPromise = null; let inflightPromise = null;
async function pool(limit, tasks) { /**
const results = []; * Accurate guild count — same multi-layer strategy as ErinJS:
const executing = new Set(); * 1. Try client.fetchTotalGuildCount() (shard-aware, if available)
for (const task of tasks) { * 2. Try client.fetchAllStats().guilds (shard-aware, if available)
const p = Promise.resolve().then(task).then(r => { results.push(r); executing.delete(p); }); * 3. Paginate REST API via /users/@me/guilds?limit=200
executing.add(p); * 4. Fallback to client.guilds.size (local shard only)
if (executing.size >= limit) await Promise.race(executing); */
async function fetchAccurateGuildCount(client) {
// Strategy 1: built-in shard-aware method
if (typeof client.fetchTotalGuildCount === "function") {
try {
const count = await client.fetchTotalGuildCount();
if (typeof count === "number" && count >= 0) return count;
} catch {}
} }
await Promise.all(executing);
return results; // Strategy 2: built-in stats aggregator
if (typeof client.fetchAllStats === "function") {
try {
const stats = await client.fetchAllStats();
if (typeof stats?.guilds === "number" && stats.guilds >= 0) return stats.guilds;
} catch {}
}
// Strategy 3: REST API pagination — gets all guilds across shards
if (client.rest && typeof client.rest.get === "function") {
try {
let total = 0;
let after = undefined;
for (let page = 0; page < 500; page++) {
const route = `/users/@me/guilds?limit=200${after ? `&after=${after}` : ""}`;
const response = await client.rest.get(route);
const batch = Array.isArray(response) ? response : (response?.guilds ?? []);
total += batch.length;
if (batch.length < 200) break;
after = batch[batch.length - 1]?.id;
if (!after) break;
}
return total;
} catch {}
}
// Strategy 4: fallback — local shard cache only
return client.guilds?.size ?? 0;
} }
async function fetchGuildMemberCount(guild) { /**
* Accurate user count — sum memberCount across all guilds.
* Uses guild.memberCount from the GUILD_CREATE payload (O(1), no API calls).
* Falls back to guild.members.size if memberCount is missing.
*/
function computeUserCount(client) {
let total = 0;
for (const [, guild] of client.guilds) {
total += guild.memberCount ?? guild.members?.size ?? 0;
}
return total;
}
async function refreshStats(client) {
try { try {
let after = undefined; const [guildCount, userCount] = await Promise.all([
let total = 0; fetchAccurateGuildCount(client),
// Guard against runaway pagination: Fluxer may have far fewer than 1000 members Promise.resolve(computeUserCount(client)),
// but return a Collection (Map-like) instead of an array, causing batch.length ]);
// to be undefined and the loop to run forever. Normalise to an array first. cachedStats = { guildCount, userCount };
for (let page = 0; page < 1000; page++) { } catch (err) {
const raw = await guild.members.fetch({ limit: 1000, after }); console.error("[stats] refreshStats failed:", err);
// Normalise: Collection (Map), array, or plain object → array // Keep old cache instead of overwriting with bad data
const batch = Array.isArray(raw) if (cachedStats) {
? raw cacheExpiresAt = Date.now() + CACHE_TTL_MS;
: typeof raw?.values === "function" inflightPromise = null;
? [...raw.values()] return cachedStats;
: 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; cachedStats = { guildCount: client.guilds?.size ?? 0, userCount: 0 };
} catch {
return guild.memberCount ?? guild.members?.size ?? 0;
} }
}
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; cacheExpiresAt = Date.now() + CACHE_TTL_MS;
inflightPromise = null; inflightPromise = null;
return cachedUserCount; return cachedStats;
} }
function getUserCount(client) { function getStats(client) {
if (cachedUserCount !== null && Date.now() < cacheExpiresAt) return Promise.resolve(cachedUserCount); if (cachedStats && Date.now() < cacheExpiresAt) return Promise.resolve(cachedStats);
if (!inflightPromise) inflightPromise = refreshUserCount(client); if (!inflightPromise) inflightPromise = refreshStats(client);
return inflightPromise; return inflightPromise;
} }
@@ -114,13 +146,13 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
} }
description.push( description.push(
`${t(msg, "responses.stats.ping")} — \`${ld(`${num(ping)}ms`)}\``, `${t(msg, "responses.stats.ping")} — \`${ld(`${num(ping)}ms`)}\``,
`${t(msg, "responses.stats.uptime")} — \`${uptime}\``, `${t(msg, "responses.stats.uptime")} — \`${uptime}\``,
`${t(msg, "responses.stats.build")} — [\`${comHash}\`](${comLink})`, `${t(msg, "responses.stats.build")} — [\`${comHash}\`](${comLink})`,
reason ? `${t(msg, "responses.stats.lastRestart")} — \`${reason}\`` : null, reason ? `${t(msg, "responses.stats.lastRestart")} — \`${reason}\`` : null,
``, ``,
t(msg, "responses.stats.supportKofi"), t(msg, "responses.stats.supportKofi"),
t(msg, "responses.stats.community"), t(msg, "responses.stats.community"),
); );
const desc = description.filter(l => l !== null).join("\n"); const desc = description.filter(l => l !== null).join("\n");
@@ -158,22 +190,36 @@ export async function run(message) {
const scrobblePromise = lastfmEnabled ? lastfm.getTotalScrobbles() : Promise.resolve(0); const scrobblePromise = lastfmEnabled ? lastfm.getTotalScrobbles() : Promise.resolve(0);
const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0); const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0);
const hasCached = cachedUserCount !== null; const hasCached = cachedStats !== null;
// Measure real round-trip latency // Measure real round-trip latency
const start = Date.now(); const start = Date.now();
const msg = await message.reply({ const msg = await message.reply({
embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, userCount: hasCached ? cachedUserCount : 0, ping: 0, loading: !hasCached })] embeds: [buildEmbed((...a) => this.t(...a), message, {
...shared,
guildCount: hasCached ? cachedStats.guildCount : shared.guildCount,
userCount: hasCached ? cachedStats.userCount : 0,
ping: 0,
loading: !hasCached,
})]
}); });
const ping = Date.now() - start; const ping = Date.now() - start;
const [users, scrobbleCount, linkedUsers] = await Promise.all([ const [stats, scrobbleCount, linkedUsers] = await Promise.all([
getUserCount(this.client), getStats(this.client),
scrobblePromise, scrobblePromise,
linkedPromise, linkedPromise,
]); ]);
await msg.edit({ await msg.edit({
embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, userCount: users, scrobbleCount, linkedUsers, ping, loading: false })] embeds: [buildEmbed((...a) => this.t(...a), message, {
...shared,
guildCount: stats.guildCount,
userCount: stats.userCount,
scrobbleCount,
linkedUsers,
ping,
loading: false,
})]
}).catch((err) => console.error("[stats] editEmbed failed:", err)); }).catch((err) => console.error("[stats] editEmbed failed:", err));
} }