From 207c60ceec7cebf0f95187ae5bae9960e03f1b02 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Sun, 13 Sep 2026 02:30:47 +0300 Subject: [PATCH] hotfix --- src/db/Settings.mjs | 11 ++++- src/music/audio/StreamPipeline.mjs | 58 +++++++++++++------------ src/music/audio/WebMOpusMuxer.mjs | 68 ++++++++++++++++++++++++++++-- src/voice/VoiceStateCache.mjs | 44 ++++++------------- src/voice/VoiceStateResolver.mjs | 26 +++++++----- 5 files changed, 133 insertions(+), 74 deletions(-) diff --git a/src/db/Settings.mjs b/src/db/Settings.mjs index aa182b9..7523b62 100644 --- a/src/db/Settings.mjs +++ b/src/db/Settings.mjs @@ -212,6 +212,11 @@ export class RemoteSettingsManager extends SettingsManager { logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`); } await Promise.allSettled(pendingServers.map(server => this._doSave(server))); + try { + if (this.db?.end) { + await new Promise(r => this.db.end(() => r())); + } + } catch (_) {} } /** @@ -503,7 +508,11 @@ export class RemoteSettingsManager extends SettingsManager { * @returns {ServerSettings} */ getServer(id) { - if (!this.guilds.has(id)) return new ServerSettings(id, this); + if (!this.guilds.has(id)) { + const server = new ServerSettings(id, this); + this.guilds.set(id, server); + return server; + } return this.guilds.get(id); } diff --git a/src/music/audio/StreamPipeline.mjs b/src/music/audio/StreamPipeline.mjs index 79557b1..de30396 100644 --- a/src/music/audio/StreamPipeline.mjs +++ b/src/music/audio/StreamPipeline.mjs @@ -43,36 +43,40 @@ const StreamPipeline = { * @returns {Promise} * @private */ - _awaitEnd(durationMs) { return new Promise((resolve, reject) => { - this._endResolve = resolve; - this._endReject = reject; - const failFast = (err) => { - if (this._playing && !this._stopped) { - this._playing = false; - reject(err); - } else { - resolve(); - } - }; + _awaitEnd(durationMs) { + return new Promise((resolve, reject) => { + this._endResolve = resolve; + this._endReject = reject; + const failFast = (err) => { + if (this._playing && !this._stopped) { + this._playing = false; + reject(err); + } else { + resolve(); + } + }; - if (durationMs > 0) { - this._durationTimer = setTimeout(resolve, durationMs); - } else { const stream = this._stream; - if (!stream) return resolve(); - const onEnd = () => resolve(); - stream.once("end", onEnd); - stream.once("close", onEnd); - stream.once("error", failFast); - } + if (stream) { + const onEnd = () => resolve(); + stream.once("end", onEnd); + stream.once("close", onEnd); + stream.once("error", failFast); + } - if (this._sourceStream) { - this._sourceStream.once("error", failFast); - } - if (this._encoder) { - this._encoder.once("error", failFast); - } - }); + if (durationMs > 0) { + this._durationTimer = setTimeout(resolve, durationMs); + } else if (!stream) { + return resolve(); + } + + if (this._sourceStream) { + this._sourceStream.once("error", failFast); + } + if (this._encoder) { + this._encoder.once("error", failFast); + } + }); }, /** diff --git a/src/music/audio/WebMOpusMuxer.mjs b/src/music/audio/WebMOpusMuxer.mjs index 8bfb6af..40b6636 100644 --- a/src/music/audio/WebMOpusMuxer.mjs +++ b/src/music/audio/WebMOpusMuxer.mjs @@ -11,13 +11,48 @@ const BLOCKS_PER_CLUSTER = 250; /** @type {number} @description Force a cluster flush when buffered blocks exceed this size. */ const CLUSTER_FLUSH_BYTES = 64 * 1024; +const HEX_CACHE = new Map(); + +/** + * Get or create a Buffer from a hex string. + * @param {string} hex + * @returns {Buffer} + */ +function getHexBuf(hex) { + let b = HEX_CACHE.get(hex); + if (!b) { + b = Buffer.from(hex, "hex"); + HEX_CACHE.set(hex, b); + } + return b; +} + /** * Encode a Matroska variable-length size integer (finite size). + * Uses fast paths for 1, 2, and 3-byte lengths to avoid loops and allocations. * @param {number} value - Size to encode (must be >= 0). * @returns {Buffer} */ function encodeSizeVint(value) { - let length = 1; + if (value <= 127) { + const buf = Buffer.allocUnsafe(1); + buf[0] = value | 0x80; + return buf; + } + if (value <= 16383) { + const buf = Buffer.allocUnsafe(2); + buf[0] = ((value >> 8) & 0xff) | 0x40; + buf[1] = value & 0xff; + return buf; + } + if (value <= 2097151) { + const buf = Buffer.allocUnsafe(3); + buf[0] = ((value >> 16) & 0xff) | 0x20; + buf[1] = (value >> 8) & 0xff; + buf[2] = value & 0xff; + return buf; + } + let length = 4; while (value > 2 ** (7 * length) - 1 && length < 8) length++; const buf = Buffer.alloc(length); for (let i = length - 1; i >= 0; i--) { @@ -35,7 +70,7 @@ function encodeSizeVint(value) { * @returns {Buffer} */ function element(idHex, payload) { - return Buffer.concat([Buffer.from(idHex, "hex"), encodeSizeVint(payload.length), payload]); + return Buffer.concat([getHexBuf(idHex), encodeSizeVint(payload.length), payload]); } /** @@ -127,8 +162,33 @@ function buildHeader(sampleRate, channels) { */ function buildSimpleBlock(packet, relTimeMs) { const clamped = Math.max(-32768, Math.min(32767, relTimeMs)); - const header = Buffer.from([0x81, (clamped >> 8) & 0xff, clamped & 0xff, 0x80]); - return element("a3", Buffer.concat([header, packet])); + const payloadLen = 4 + packet.length; + let block; + + if (payloadLen <= 127) { + block = Buffer.allocUnsafe(1 + 1 + 4 + packet.length); + block[0] = 0xa3; // SimpleBlock EBML ID + block[1] = payloadLen | 0x80; // 1-byte VINT + block[2] = 0x81; // Track 1 + block[3] = (clamped >> 8) & 0xff; + block[4] = clamped & 0xff; + block[5] = 0x80; // Keyframe flag + packet.copy(block, 6); + } else if (payloadLen <= 16383) { + block = Buffer.allocUnsafe(1 + 2 + 4 + packet.length); + block[0] = 0xa3; // SimpleBlock EBML ID + block[1] = ((payloadLen >> 8) & 0xff) | 0x40; // 2-byte VINT + block[2] = payloadLen & 0xff; + block[3] = 0x81; // Track 1 + block[4] = (clamped >> 8) & 0xff; + block[5] = clamped & 0xff; + block[6] = 0x80; // Keyframe flag + packet.copy(block, 7); + } else { + const header = Buffer.from([0x81, (clamped >> 8) & 0xff, clamped & 0xff, 0x80]); + return element("a3", Buffer.concat([header, packet])); + } + return block; } /** diff --git a/src/voice/VoiceStateCache.mjs b/src/voice/VoiceStateCache.mjs index a5eacbe..56a52bd 100644 --- a/src/voice/VoiceStateCache.mjs +++ b/src/voice/VoiceStateCache.mjs @@ -24,8 +24,6 @@ export class VoiceStateCache { this._maxUsers = opts.maxUsers ?? 50_000; this._maxBots = opts.maxBots ?? 10_000; - this._lruUserKeys = []; - this._lruBotKeys = []; } /** @@ -51,7 +49,7 @@ export class VoiceStateCache { /** * Update (or remove) a user's voice-channel location in the cache. * When `channelId` is provided the user is added; when `null`/falsy the user is removed. - * Automatically evicts LRU entries when capacity is exceeded. + * Automatically evicts LRU entries in O(1) time when capacity is exceeded. * @param {{ guildId: string, userId: string, channelId: string|null, isBot?: boolean }} opts */ updateUser({ guildId, userId, channelId, isBot = false }) { @@ -63,7 +61,6 @@ export class VoiceStateCache { const locations = isBot ? this.botLocations : this.userLocations; const channelIdx = isBot ? this.botChannelMembers : this.channelMembers; const maxEntries = isBot ? this._maxBots : this._maxUsers; - const lruKeys = isBot ? this._lruBotKeys : this._lruUserKeys; const uKey = VoiceStateCache.userKey(cleanGuild, cleanUser); const prev = locations.get(uKey); @@ -85,36 +82,23 @@ export class VoiceStateCache { locations.delete(uKey); locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser }); - const lruIdx = lruKeys.indexOf(uKey); - if (lruIdx !== -1) lruKeys.splice(lruIdx, 1); - lruKeys.push(uKey); - while (locations.size > maxEntries) { - let evicted = false; - for (let i = 0; i < lruKeys.length; i++) { - const evictKey = lruKeys[i]; - if (evictKey === uKey) continue; + const oldestKey = locations.keys().next().value; + if (!oldestKey) break; - const evictEntry = locations.get(evictKey); - if (evictEntry) { - const evictCKey = VoiceStateCache.channelKey(evictEntry.guildId, evictEntry.channelId); - const evictSet = channelIdx.get(evictCKey); - if (evictSet) { - evictSet.delete(evictEntry.userId); - if (evictSet.size === 0) channelIdx.delete(evictCKey); - } - locations.delete(evictKey); + const evictEntry = locations.get(oldestKey); + if (evictEntry) { + const evictCKey = VoiceStateCache.channelKey(evictEntry.guildId, evictEntry.channelId); + const evictSet = channelIdx.get(evictCKey); + if (evictSet) { + evictSet.delete(evictEntry.userId); + if (evictSet.size === 0) channelIdx.delete(evictCKey); } - lruKeys.splice(i, 1); - evicted = true; - break; } - if (!evicted) break; + locations.delete(oldestKey); } } else { locations.delete(uKey); - const idx = lruKeys.indexOf(uKey); - if (idx !== -1) lruKeys.splice(idx, 1); } } @@ -227,7 +211,6 @@ export class VoiceStateCache { if (cKey.startsWith(prefix)) channelKeysToRemove.push(cKey); } for (const cKey of channelKeysToRemove) this.channelMembers.delete(cKey); - this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix)); const botKeysToRemove = []; for (const [uKey, loc] of this.botLocations) { @@ -247,7 +230,6 @@ export class VoiceStateCache { if (cKey.startsWith(prefix)) botChannelKeysToRemove.push(cKey); } for (const cKey of botChannelKeysToRemove) this.botChannelMembers.delete(cKey); - this._lruBotKeys = this._lruBotKeys.filter(k => !k.startsWith(prefix)); } /** @@ -582,8 +564,8 @@ export class VoiceStateCache { botUsers: this.botLocations.size, humanChannels: this.channelMembers.size, botChannels: this.botChannelMembers.size, - lruUserKeysLen: this._lruUserKeys.length, - lruBotKeysLen: this._lruBotKeys.length, + lruUserKeysLen: this.userLocations.size, + lruBotKeysLen: this.botLocations.size, }; } } diff --git a/src/voice/VoiceStateResolver.mjs b/src/voice/VoiceStateResolver.mjs index 02e3887..2167334 100644 --- a/src/voice/VoiceStateResolver.mjs +++ b/src/voice/VoiceStateResolver.mjs @@ -65,19 +65,23 @@ export function hasHumansInChannel({ guildId, channelId, client, voiceCache, obs } - if (observedVoiceUsers) { - try { - const iterator = typeof observedVoiceUsers.iterateHumanUsers === "function" - ? observedVoiceUsers.iterateHumanUsers() - : observedVoiceUsers.entries(); + if (observedVoiceUsers && observedVoiceUsers !== voiceCache) { + if (typeof observedVoiceUsers.hasHumansInChannel === "function") { + if (observedVoiceUsers.hasHumansInChannel(guildId, channelId)) return true; + } else { + try { + const iterator = typeof observedVoiceUsers.iterateHumanUsers === "function" + ? observedVoiceUsers.iterateHumanUsers() + : observedVoiceUsers.entries(); - for (const [, info] of iterator) { - const gId = String(info.guildId ?? ""); - const cId = String(info.channelId ?? ""); - if (gId === guildId && cId === channelId) return true; + for (const [, info] of iterator) { + const gId = String(info.guildId ?? ""); + const cId = String(info.channelId ?? ""); + if (gId === guildId && cId === channelId) return true; + } + } catch (e) { + logger.warn("[VoiceStateResolver] ObservedVoiceUsers check failed:", e?.message); } - } catch (e) { - logger.warn("[VoiceStateResolver] ObservedVoiceUsers check failed:", e?.message); } }