Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
relay: measure event-loop lag from a 100 ms timer's lateness; metrics tests
milind-sonibab542d319e2
diff --git a/relay/load/load.ts b/relay/load/load.tsindex 1d4bbd1ad5..e2aa07b413 100644--- a/relay/load/load.ts+++ b/relay/load/load.ts@@ -179,7 +179,7 @@ async function scrape(url: string, bearer: string): Promise<Record<string, numbeconst text = await (await fetch(`${url}/metrics`, { headers: { authorization: `Bearer ${bearer}` } })).text();const out: Record<string, number> = {};for (const line of text.split("\n")) {- const match = /^([a-z_]+(?:\{[^}]*\})?) ([0-9.e+-]+)$/.exec(line);+ const match = /^([a-z0-9_]+(?:\{[^}]*\})?) ([0-9.e+-]+)$/.exec(line);if (match) out[match[1]!] = Number(match[2]);}return out;diff --git a/relay/src/metrics.ts b/relay/src/metrics.tsindex 4eb3203a51..36ef8140a0 100644--- a/relay/src/metrics.ts+++ b/relay/src/metrics.ts@@ -1,5 +1,5 @@import { timingSafeEqual } from "node:crypto";-import { monitorEventLoopDelay } from "node:perf_hooks";+import { performance } from "node:perf_hooks";import { sha256 } from "./wire.ts";const COUNTERS = {@@ -23,14 +23,40 @@ export interface Gauge {value: number;}-export class Metrics {- private readonly counts = new Map<string, number>();- private readonly loopDelay = monitorEventLoopDelay({ resolution: 10 });+const LAG_TICK_MS = 100;+const LAG_SAMPLES_MAX = 4_096;++/** How late a 100 ms timer fires, sample by sample: the time the event loop was busy with something else. */+class LoopLag {+ private samples: number[] = [];+ private last = performance.now();+ private readonly timer = setInterval(() => {+ const now = performance.now();+ if (this.samples.length < LAG_SAMPLES_MAX) this.samples.push(Math.max(0, now - this.last - LAG_TICK_MS));+ this.last = now;+ }, LAG_TICK_MS);constructor() {- this.loopDelay.enable();+ this.timer.unref();}+ /** p99 and max in seconds since the last call. */+ take(): { p99: number; max: number } {+ const sorted = this.samples.sort((a, b) => a - b);+ this.samples = [];+ if (sorted.length === 0) return { p99: 0, max: 0 };+ return { p99: sorted[Math.floor(0.99 * (sorted.length - 1))]! / 1000, max: sorted.at(-1)! / 1000 };+ }++ stop(): void {+ clearInterval(this.timer);+ }+}++export class Metrics {+ private readonly counts = new Map<string, number>();+ private readonly lag = new LoopLag();+inc(name: CounterName, label?: string | number, by = 1): void {const key = label === undefined ? name : `${name}\u0000${label}`;this.counts.set(key, (this.counts.get(key) ?? 0) + by);@@ -54,16 +80,16 @@ export class Metrics {}const usage = process.cpuUsage();const memory = process.memoryUsage();+ const lag = this.lag.take();const all: Gauge[] = [...gauges,- { name: "relay_event_loop_lag_p99_seconds", help: "Event-loop delay p99 since the last scrape", value: this.loopDelay.percentile(99) / 1e9 },- { name: "relay_event_loop_lag_max_seconds", help: "Event-loop delay max since the last scrape", value: this.loopDelay.max / 1e9 },+ { name: "relay_event_loop_lag_p99_seconds", help: "Event-loop lag p99 since the last scrape", value: lag.p99 },+ { name: "relay_event_loop_lag_max_seconds", help: "Event-loop lag max since the last scrape", value: lag.max },{ name: "process_resident_memory_bytes", help: "Resident memory", value: memory.rss },{ name: "process_heap_used_bytes", help: "V8 heap in use", value: memory.heapUsed },{ name: "process_cpu_seconds_total", help: "User and system CPU time", value: (usage.user + usage.system) / 1e6 },{ name: "process_start_time_seconds", help: "Start time, Unix seconds", value: Math.round(Date.now() / 1000 - process.uptime()) },];- this.loopDelay.reset();for (const { name, help, value } of all) {const type = name.endsWith("_total") ? "counter" : "gauge";lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} ${type}`, `${name} ${Number.isFinite(value) ? value : 0}`);@@ -72,7 +98,7 @@ export class Metrics {}close(): void {- this.loopDelay.disable();+ this.lag.stop();}}diff --git a/relay/test/metrics.test.ts b/relay/test/metrics.test.tsnew file mode 100644index 0000000000..72e32d4426--- /dev/null+++ b/relay/test/metrics.test.ts@@ -0,0 +1,52 @@+import assert from "node:assert/strict";+import { describe, test } from "node:test";+import { bearerMatches, Metrics } from "../src/metrics.ts";+import { sleep } from "./helpers.ts";++const value = (text: string, name: string) => Number(new RegExp(`^${name.replace(/[{}"]/g, "\\$&")} (\\S+)$`, "m").exec(text)?.[1]);++describe("metrics", () => {+ test("the bearer must match in full", () => {+ const token = "t".repeat(40);+ assert.equal(bearerMatches(`Bearer ${token}`, token), true);+ assert.equal(bearerMatches(`Bearer ${token}x`, token), false);+ assert.equal(bearerMatches(`Bearer ${token.slice(1)}`, token), false);+ assert.equal(bearerMatches(token, token), false);+ assert.equal(bearerMatches("Bearer ", token), false);+ assert.equal(bearerMatches(undefined, token), false);+ });++ test("counters render with their labels, and unlabelled ones start at 0", () => {+ const metrics = new Metrics();+ try {+ metrics.inc("relay_closes_total", 4404);+ metrics.inc("relay_closes_total", 4404);+ metrics.inc("relay_bytes_total", "up", 1_000);+ const text = metrics.render([{ name: "relay_hosts_connected", help: "h", value: 3 }]);+ assert.equal(value(text, 'relay_closes_total{code="4404"}'), 2);+ assert.equal(value(text, 'relay_bytes_total{dir="up"}'), 1_000);+ assert.equal(value(text, "relay_sessions_total"), 0);+ assert.equal(value(text, "relay_hosts_connected"), 3);+ assert.match(text, /^# TYPE relay_closes_total counter$/m);+ } finally {+ metrics.close();+ }+ });++ test("a blocked event loop shows as lag in the next scrape, and only there", async () => {+ const metrics = new Metrics();+ try {+ await sleep(250);+ metrics.render([]);+ const until = performance.now() + 300;+ while (performance.now() < until) {}+ await sleep(250);+ const blocked = metrics.render([]);+ assert.ok(value(blocked, "relay_event_loop_lag_max_seconds") >= 0.2, blocked);+ await sleep(250);+ assert.ok(value(metrics.render([]), "relay_event_loop_lag_max_seconds") < 0.1);+ } finally {+ metrics.close();+ }+ });+});