Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions src/Voice/VoiceRegion.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { DefaultNodeOptions } from "../Constants";
import { OnPingUpdateSymbol } from "../Constants/Symbols";
import type { PlayerState } from "../Typings";
import type { Player } from "../Main";
Expand All @@ -8,9 +9,15 @@ interface VoiceNodePingStats {
startTime: number;
}

/**
* Class representing a voice region and evaluating performing nodes
*/
export class VoiceRegion {
#stats = new Map<string, VoiceNodePingStats>();

/**
* Id of the region
*/
readonly id: string;
readonly player: Player;

Expand All @@ -31,25 +38,46 @@ export class VoiceRegion {
} satisfies { [K in keyof VoiceRegion]?: PropertyDescriptor });
}

/**
* Whether this region has an entry for all nodes that are ready
*/
inSync() {
return !this.player.nodes.values().some((n) => n.ready && !this.#stats.has(n.name));
}

/**
* Delete a node's entry
* @param name Name of the node
*/
forgetNode(name: string) {
return this.#stats.delete(name);
}

/**
* Delete all node entries
*/
forgetAllNodes() {
this.#stats.clear();
}

/**
* Get the average ping of a node
* @param node Name of the node
*/
getAveragePing(node: string) {
const stats = this.#stats.get(node);
if (!stats) return null;
if (Date.now() - stats.startTime > 60_000) return null;
if (Date.now() - stats.startTime > DefaultNodeOptions.statsInterval) return null;
return Math.round(stats.pingTotal / stats.pingCount);
}

/**
* Get a node relevant for this region.
*
* When in sync, this will return the node with the lowest average ping.
*
* When not in sync, this will continue to yield nodes it doesn't have an entry for.
*/
getRelevantNode() {
return this.player.nodes.relevant().sort((a, b) => {
return (this.getAveragePing(a.name) ?? 0) - (this.getAveragePing(b.name) ?? 0);
Expand All @@ -68,7 +96,7 @@ export class VoiceRegion {
});
return;
}
if (state.time - stats.startTime <= 60_000) {
if (state.time - stats.startTime <= DefaultNodeOptions.statsInterval) {
stats.pingTotal += state.ping;
stats.pingCount++;
return;
Expand Down
Loading