feat: collect relay metrics

This commit is contained in:
2023-11-08 09:41:12 +00:00
parent 8dbbb24729
commit 3326aedc52
5 changed files with 125 additions and 35 deletions

View File

@ -1,13 +1,70 @@
import { FeedCache } from "@snort/shared";
import { FeedCache, unixNowMs } from "@snort/shared";
import { Connection } from "connection";
import { RelayMetrics } from "cache";
import { TraceReport } from "query";
export class RelayMetricHandler {
readonly #cache: FeedCache<RelayMetrics>;
constructor(cache: FeedCache<RelayMetrics>) {
this.#cache = cache;
setInterval(() => {
this.#flush();
}, 10_000);
}
onDisconnect(c: Connection, code: number) {}
async onEvent(addr: string) {
const v = await this.#cache.get(addr);
if (v) {
v.events++;
v.lastSeen = unixNowMs();
}
}
async onConnect(addr: string) {
const v = await this.#cache.get(addr);
if (v) {
v.connects++;
v.lastSeen = unixNowMs();
} else {
await this.#cache.set({
addr: addr,
connects: 1,
disconnects: 0,
events: 0,
lastSeen: unixNowMs(),
latency: [],
});
}
}
async onDisconnect(addr: string, code: number) {
const v = await this.#cache.get(addr);
if (v) {
v.disconnects++;
} else {
await this.#cache.set({
addr: addr,
connects: 0,
disconnects: 1,
events: 0,
lastSeen: unixNowMs(),
latency: [],
});
}
}
onTraceReport(t: TraceReport) {
const v = this.#cache.getFromCache(t.conn.Address);
if (v) {
v.latency.push(t.responseTime);
v.latency = v.latency.slice(-50);
}
}
async #flush() {
const data = this.#cache.snapshot();
await this.#cache.bulkSet(data);
}
}