This commit is contained in:
NoLogicAlan committed 2026-09-13 02:30:47 +03:00
1 parent cc0b438ef6
commit 207c60ceec
5 files changed
+93 -34

No files matched your search

+10 -1
View File
@@ -212,6 +212,11 @@ export class RemoteSettingsManager extends SettingsManager {
logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`); logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`);
} }
await Promise.allSettled(pendingServers.map(server => this._doSave(server))); 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} * @returns {ServerSettings}
*/ */
getServer(id) { 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); return this.guilds.get(id);
} }
+9 -5
View File
@@ -43,7 +43,8 @@ const StreamPipeline = {
* @returns {Promise<void>} * @returns {Promise<void>}
* @private * @private
*/ */
_awaitEnd(durationMs) { return new Promise((resolve, reject) => { _awaitEnd(durationMs) {
return new Promise((resolve, reject) => {
this._endResolve = resolve; this._endResolve = resolve;
this._endReject = reject; this._endReject = reject;
const failFast = (err) => { const failFast = (err) => {
@@ -55,17 +56,20 @@ const StreamPipeline = {
} }
}; };
if (durationMs > 0) {
this._durationTimer = setTimeout(resolve, durationMs);
} else {
const stream = this._stream; const stream = this._stream;
if (!stream) return resolve(); if (stream) {
const onEnd = () => resolve(); const onEnd = () => resolve();
stream.once("end", onEnd); stream.once("end", onEnd);
stream.once("close", onEnd); stream.once("close", onEnd);
stream.once("error", failFast); stream.once("error", failFast);
} }
if (durationMs > 0) {
this._durationTimer = setTimeout(resolve, durationMs);
} else if (!stream) {
return resolve();
}
if (this._sourceStream) { if (this._sourceStream) {
this._sourceStream.once("error", failFast); this._sourceStream.once("error", failFast);
} }
+62 -2
View File
@@ -11,13 +11,48 @@ const BLOCKS_PER_CLUSTER = 250;
/** @type {number} @description Force a cluster flush when buffered blocks exceed this size. */ /** @type {number} @description Force a cluster flush when buffered blocks exceed this size. */
const CLUSTER_FLUSH_BYTES = 64 * 1024; 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). * 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). * @param {number} value - Size to encode (must be >= 0).
* @returns {Buffer} * @returns {Buffer}
*/ */
function encodeSizeVint(value) { 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++; while (value > 2 ** (7 * length) - 1 && length < 8) length++;
const buf = Buffer.alloc(length); const buf = Buffer.alloc(length);
for (let i = length - 1; i >= 0; i--) { for (let i = length - 1; i >= 0; i--) {
@@ -35,7 +70,7 @@ function encodeSizeVint(value) {
* @returns {Buffer} * @returns {Buffer}
*/ */
function element(idHex, payload) { 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) { function buildSimpleBlock(packet, relTimeMs) {
const clamped = Math.max(-32768, Math.min(32767, relTimeMs)); const clamped = Math.max(-32768, Math.min(32767, relTimeMs));
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]); const header = Buffer.from([0x81, (clamped >> 8) & 0xff, clamped & 0xff, 0x80]);
return element("a3", Buffer.concat([header, packet])); return element("a3", Buffer.concat([header, packet]));
}
return block;
} }
/** /**
+7 -25
View File
@@ -24,8 +24,6 @@ export class VoiceStateCache {
this._maxUsers = opts.maxUsers ?? 50_000; this._maxUsers = opts.maxUsers ?? 50_000;
this._maxBots = opts.maxBots ?? 10_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. * 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. * 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 * @param {{ guildId: string, userId: string, channelId: string|null, isBot?: boolean }} opts
*/ */
updateUser({ guildId, userId, channelId, isBot = false }) { updateUser({ guildId, userId, channelId, isBot = false }) {
@@ -63,7 +61,6 @@ export class VoiceStateCache {
const locations = isBot ? this.botLocations : this.userLocations; const locations = isBot ? this.botLocations : this.userLocations;
const channelIdx = isBot ? this.botChannelMembers : this.channelMembers; const channelIdx = isBot ? this.botChannelMembers : this.channelMembers;
const maxEntries = isBot ? this._maxBots : this._maxUsers; const maxEntries = isBot ? this._maxBots : this._maxUsers;
const lruKeys = isBot ? this._lruBotKeys : this._lruUserKeys;
const uKey = VoiceStateCache.userKey(cleanGuild, cleanUser); const uKey = VoiceStateCache.userKey(cleanGuild, cleanUser);
const prev = locations.get(uKey); const prev = locations.get(uKey);
@@ -85,17 +82,11 @@ export class VoiceStateCache {
locations.delete(uKey); locations.delete(uKey);
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser }); 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) { while (locations.size > maxEntries) {
let evicted = false; const oldestKey = locations.keys().next().value;
for (let i = 0; i < lruKeys.length; i++) { if (!oldestKey) break;
const evictKey = lruKeys[i];
if (evictKey === uKey) continue;
const evictEntry = locations.get(evictKey); const evictEntry = locations.get(oldestKey);
if (evictEntry) { if (evictEntry) {
const evictCKey = VoiceStateCache.channelKey(evictEntry.guildId, evictEntry.channelId); const evictCKey = VoiceStateCache.channelKey(evictEntry.guildId, evictEntry.channelId);
const evictSet = channelIdx.get(evictCKey); const evictSet = channelIdx.get(evictCKey);
@@ -103,18 +94,11 @@ export class VoiceStateCache {
evictSet.delete(evictEntry.userId); evictSet.delete(evictEntry.userId);
if (evictSet.size === 0) channelIdx.delete(evictCKey); if (evictSet.size === 0) channelIdx.delete(evictCKey);
} }
locations.delete(evictKey);
} }
lruKeys.splice(i, 1); locations.delete(oldestKey);
evicted = true;
break;
}
if (!evicted) break;
} }
} else { } else {
locations.delete(uKey); 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); if (cKey.startsWith(prefix)) channelKeysToRemove.push(cKey);
} }
for (const cKey of channelKeysToRemove) this.channelMembers.delete(cKey); for (const cKey of channelKeysToRemove) this.channelMembers.delete(cKey);
this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix));
const botKeysToRemove = []; const botKeysToRemove = [];
for (const [uKey, loc] of this.botLocations) { for (const [uKey, loc] of this.botLocations) {
@@ -247,7 +230,6 @@ export class VoiceStateCache {
if (cKey.startsWith(prefix)) botChannelKeysToRemove.push(cKey); if (cKey.startsWith(prefix)) botChannelKeysToRemove.push(cKey);
} }
for (const cKey of botChannelKeysToRemove) this.botChannelMembers.delete(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, botUsers: this.botLocations.size,
humanChannels: this.channelMembers.size, humanChannels: this.channelMembers.size,
botChannels: this.botChannelMembers.size, botChannels: this.botChannelMembers.size,
lruUserKeysLen: this._lruUserKeys.length, lruUserKeysLen: this.userLocations.size,
lruBotKeysLen: this._lruBotKeys.length, lruBotKeysLen: this.botLocations.size,
}; };
} }
} }
+5 -1
View File
@@ -65,7 +65,10 @@ export function hasHumansInChannel({ guildId, channelId, client, voiceCache, obs
} }
if (observedVoiceUsers) { if (observedVoiceUsers && observedVoiceUsers !== voiceCache) {
if (typeof observedVoiceUsers.hasHumansInChannel === "function") {
if (observedVoiceUsers.hasHumansInChannel(guildId, channelId)) return true;
} else {
try { try {
const iterator = typeof observedVoiceUsers.iterateHumanUsers === "function" const iterator = typeof observedVoiceUsers.iterateHumanUsers === "function"
? observedVoiceUsers.iterateHumanUsers() ? observedVoiceUsers.iterateHumanUsers()
@@ -80,6 +83,7 @@ export function hasHumansInChannel({ guildId, channelId, client, voiceCache, obs
logger.warn("[VoiceStateResolver] ObservedVoiceUsers check failed:", e?.message); logger.warn("[VoiceStateResolver] ObservedVoiceUsers check failed:", e?.message);
} }
} }
}
if (client) { if (client) {