Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Relay usage stats: daily peaks on the relay, daily counts in the control plane (#4689)

Milind Soni076ab5c5b6ce
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.md
index 6ca24f32c8..1e74eacf82 100644
--- a/cloudflare/control-plane/README.md
+++ b/cloudflare/control-plane/README.md
@@ -614,12 +614,18 @@ old one; no identifiers) answers:
stays in as the number grows; `RELAY_ALLOW_INSTALLATIONS` admits named installations (the team) at any percentage.
- **Adoption.** Every request records its counts in `relay_adoption`, in the rollout or not; `/healthz` reports
`relayAdoption: {e2eDevices, legacyDevices, installs}` over the last 30 days. The tunnel path retires on these numbers.
+- **Usage per day** (`migrations/0014`). `relay_daily` counts installations once per UTC day and kind: `seen` (asked
+ for a token), `token` (got one), `e2e` (reported end-to-end phones), `new` (asked for the first time). It holds only
+ the day, the kind and a count; `relay_adoption.first_seen_at`, `token_at` and `e2e_at` tell a request whether its
+ installation was already counted today. The stats dashboard (stats.openmausbot.com) charts it. A Worker without the
+ migration keeps minting tokens and writing `relay_adoption`, and logs `relay_daily_schema` once per isolate.
- **Tunnels.** From `RELAY_CAPABLE_MIN_VERSION`, a desktop at that version or later that reports `legacyDevices: 0` gets
`409 relay_capable` instead of a new tunnel. An endpoint it already holds keeps working.
Setup, once:
-1. `wrangler d1 migrations apply DB --config wrangler.jsonc` (0012).
+1. `wrangler d1 migrations apply DB --config wrangler.jsonc --remote` (0012, and 0014 for the daily counts; apply 0014
+ before deploying the Worker that writes it).
2. Make a key pair: a 32-byte Ed25519 seed for this Worker, its public key for the relay's `RELAY_TOKEN_KEYS`
(`{"k1":"<b64u public key>"}`). `wrangler secret put RELAY_TOKEN_SIGNING_KEY --config wrangler.jsonc` with the seed as
base64url. Until it exists every request answers 503. Once it is set it is listed in `secrets.required`: a deploy
diff --git a/cloudflare/control-plane/migrations/0014_relay_daily.sql b/cloudflare/control-plane/migrations/0014_relay_daily.sql
new file mode 100644
index 0000000000..c287427e34
--- /dev/null
+++ b/cloudflare/control-plane/migrations/0014_relay_daily.sql
@@ -0,0 +1,27 @@
+-- MausBot Relay usage per UTC day, as counts only: how many installations asked for a relay token, got one, reported
+-- end-to-end phones, or asked for the first time. A row is (day, kind, installs); no installation id, device or
+-- address is kept in it. The three timestamps on relay_adoption let a request tell whether its installation was
+-- already counted today.
+ALTER TABLE relay_adoption ADD COLUMN first_seen_at INTEGER;
+ALTER TABLE relay_adoption ADD COLUMN token_at INTEGER;
+ALTER TABLE relay_adoption ADD COLUMN e2e_at INTEGER;
+
+-- Rows from before this migration: first seen at their last request (0012 kept no earlier time), and counted below on
+-- that day, so a request later the same day is not counted twice. Which of them got a token was never recorded.
+UPDATE relay_adoption
+ SET first_seen_at = updated_at,
+ e2e_at = CASE WHEN e2e_devices > 0 THEN updated_at END;
+
+CREATE TABLE relay_daily (
+ day TEXT NOT NULL CHECK (day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'),
+ kind TEXT NOT NULL CHECK (kind IN ('seen', 'token', 'e2e', 'new')),
+ installs INTEGER NOT NULL CHECK (installs >= 0),
+ PRIMARY KEY (day, kind)
+) WITHOUT ROWID;
+
+INSERT INTO relay_daily (day, kind, installs)
+ SELECT strftime('%Y-%m-%d', updated_at / 1000, 'unixepoch'), 'seen', COUNT(*) FROM relay_adoption GROUP BY 1;
+INSERT INTO relay_daily (day, kind, installs)
+ SELECT strftime('%Y-%m-%d', updated_at / 1000, 'unixepoch'), 'new', COUNT(*) FROM relay_adoption GROUP BY 1;
+INSERT INTO relay_daily (day, kind, installs)
+ SELECT strftime('%Y-%m-%d', e2e_at / 1000, 'unixepoch'), 'e2e', COUNT(*) FROM relay_adoption WHERE e2e_at IS NOT NULL GROUP BY 1;
diff --git a/cloudflare/control-plane/src/relay.ts b/cloudflare/control-plane/src/relay.ts
index 66d2d10f7d..0613dfd795 100644
--- a/cloudflare/control-plane/src/relay.ts
+++ b/cloudflare/control-plane/src/relay.ts
@@ -173,6 +173,70 @@ function relaySchemaMissing(): Response {
return unavailable();
}
+const DAY_MS = 24 * HOUR_MS;
+let dailyWarned = false;
+
+export type RelayDailyKind = "seen" | "token" | "e2e" | "new";
+
+interface RelayUse {
+ installationId: string;
+ appVersion: string;
+ e2e: number;
+ legacy: number;
+ continent: string | null;
+ /** A token is minted for this request. */
+ token: boolean;
+ now: number;
+}
+
+/**
+ * Records a request in `relay_adoption` and, once per installation per UTC day and kind, adds 1 to `relay_daily`: `seen`
+ * (asked), `token` (got one), `e2e` (reported end-to-end phones), `new` (asked for the first time). Each count runs before
+ * the row is written, in one batch, so it reads the row as the previous request left it. Without migration 0014 the
+ * daily counts are skipped and only the adoption row is written, as before. False when neither could be written.
+ */
+async function recordUse(env: Env, use: RelayUse): Promise<boolean> {
+ const day = new Date(use.now).toISOString().slice(0, 10);
+ const dayStart = use.now - (use.now % DAY_MS);
+ /** `since`: the column that says the installation was already counted today; none for `new` (any row at all). */
+ const bump = (kind: RelayDailyKind, since?: "updated_at" | "token_at" | "e2e_at") =>
+ env.DB.prepare(
+ `INSERT INTO relay_daily (day, kind, installs)
+ SELECT ?1, ?2, 1 WHERE NOT EXISTS (SELECT 1 FROM relay_adoption WHERE installation_id = ?3${since ? ` AND ${since} >= ?4` : ""})
+ ON CONFLICT (day, kind) DO UPDATE SET installs = installs + 1`,
+ ).bind(day, kind, use.installationId, ...(since ? [dayStart] : []));
+ const write = env.DB.prepare(
+ `INSERT INTO relay_adoption
+ (installation_id, app_version, e2e_devices, legacy_devices, continent, updated_at, first_seen_at, token_at, e2e_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7, ?8)
+ ON CONFLICT(installation_id) DO UPDATE SET
+ app_version = excluded.app_version, e2e_devices = excluded.e2e_devices,
+ legacy_devices = excluded.legacy_devices, continent = excluded.continent, updated_at = excluded.updated_at,
+ first_seen_at = COALESCE(first_seen_at, excluded.first_seen_at),
+ token_at = COALESCE(excluded.token_at, token_at), e2e_at = COALESCE(excluded.e2e_at, e2e_at)`,
+ ).bind(use.installationId, use.appVersion, use.e2e, use.legacy, use.continent, use.now,
+ use.token ? use.now : null, use.e2e > 0 ? use.now : null);
+ const statements = [
+ bump("new"),
+ bump("seen", "updated_at"),
+ ...(use.token ? [bump("token", "token_at")] : []),
+ ...(use.e2e > 0 ? [bump("e2e", "e2e_at")] : []),
+ write,
+ ];
+ if (await env.DB.batch(statements).then(() => true, () => false)) return true;
+ if (!dailyWarned) {
+ dailyWarned = true;
+ console.error(JSON.stringify({ message: "relay daily counts not written; apply migration 0014", errorCode: "relay_daily_schema" }));
+ }
+ return env.DB.prepare(
+ `INSERT INTO relay_adoption (installation_id, app_version, e2e_devices, legacy_devices, continent, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT(installation_id) DO UPDATE SET
+ app_version = excluded.app_version, e2e_devices = excluded.e2e_devices,
+ legacy_devices = excluded.legacy_devices, continent = excluded.continent, updated_at = excluded.updated_at`,
+ ).bind(use.installationId, use.appVersion, use.e2e, use.legacy, use.continent, use.now).run().then(() => true, () => false);
+}
+
export async function issueRelayToken(request: Request, env: Env): Promise<Response> {
const installation = await requireInstallation(request, env);
const parsed = requestSchema.safeParse(await readBoundedJSON(request).catch(() => null));
@@ -196,19 +260,20 @@ export async function issueRelayToken(request: Request, env: Env): Promise<Respo
const { hostId, blocked } = host;
const continent = (request as Request & { cf?: { continent?: unknown } }).cf?.continent;
const region = typeof continent === "string" && /^[A-Z]{2}$/.test(continent) ? continent : null;
+ const hostBytes = fromB64u(hostId) as Uint8Array;
+ const included = !blocked && (settings.allowInstallations.has(installation.installation_id)
+ || (await rolloutBucket(hostBytes)) < settings.rolloutPercent);
// Counted for every relay-capable desktop, in the rollout or not: the tunnel path retires on these numbers.
- const counted = await env.DB.prepare(
- `INSERT INTO relay_adoption (installation_id, app_version, e2e_devices, legacy_devices, continent, updated_at)
- VALUES (?, ?, ?, ?, ?, ?)
- ON CONFLICT(installation_id) DO UPDATE SET
- app_version = excluded.app_version, e2e_devices = excluded.e2e_devices,
- legacy_devices = excluded.legacy_devices, continent = excluded.continent, updated_at = excluded.updated_at`,
- ).bind(installation.installation_id, parsed.data.appVersion, parsed.data.devices.e2e, parsed.data.devices.legacy, region, now).run().then(() => true, () => false);
+ const counted = await recordUse(env, {
+ installationId: installation.installation_id,
+ appVersion: parsed.data.appVersion,
+ e2e: parsed.data.devices.e2e,
+ legacy: parsed.data.devices.legacy,
+ continent: region,
+ token: included,
+ now,
+ });
if (!counted) return relaySchemaMissing();
- if (blocked) return unavailable();
- const hostBytes = fromB64u(hostId) as Uint8Array;
- const included = settings.allowInstallations.has(installation.installation_id)
- || (await rolloutBucket(hostBytes)) < settings.rolloutPercent;
if (!included) return unavailable();
const iat = Math.floor(now / 1000);
const token = await mintRelayToken({ kid: settings.kid, hid: hostId, iid: installation.installation_id, iat, exp: iat + RELAY_TOKEN_TTL_S }, settings.signingKey);
diff --git a/cloudflare/control-plane/test/relay.test.ts b/cloudflare/control-plane/test/relay.test.ts
index 3fce0113f5..1b4ae14ccd 100644
--- a/cloudflare/control-plane/test/relay.test.ts
+++ b/cloudflare/control-plane/test/relay.test.ts
@@ -154,6 +154,53 @@ describe("relay host tokens", () => {
});
});
+describe("relay usage per UTC day", () => {
+ type Counts = Record<string, number>;
+ const today = () => new Date().toISOString().slice(0, 10);
+ async function daily(day = today()): Promise<Counts> {
+ const rows = await env.DB.prepare("SELECT kind, installs FROM relay_daily WHERE day = ?").bind(day).all<{ kind: string; installs: number }>();
+ return Object.fromEntries(rows.results.map((row) => [row.kind, row.installs]));
+ }
+ const delta = (after: Counts, before: Counts) =>
+ Object.fromEntries(["seen", "token", "e2e", "new"].map((kind) => [kind, (after[kind] ?? 0) - (before[kind] ?? 0)]));
+
+ it("counts each installation once per day and kind: asked, got a token, has end-to-end phones, first time", async () => {
+ const a = await installation("[email protected]");
+ const b = await installation("[email protected]");
+ let before = await daily();
+ expect((await ask(relayEnv(), a.credential, { e2e: 2, legacy: 0 })).status).toBe(200);
+ expect((await ask(relayEnv(), a.credential, { e2e: 1, legacy: 0 })).status).toBe(200);
+ expect(delta(await daily(), before)).toEqual({ seen: 1, token: 1, e2e: 1, new: 1 });
+
+ before = await daily();
+ expect((await ask(relayEnv({ RELAY_ROLLOUT_PERCENT: "0" }), b.credential, { e2e: 0, legacy: 3 })).status).toBe(503);
+ expect(delta(await daily(), before)).toEqual({ seen: 1, token: 0, e2e: 0, new: 1 });
+ before = await daily();
+ expect((await ask(relayEnv(), b.credential, { e2e: 0, legacy: 3 })).status).toBe(200);
+ expect((await ask(relayEnv(), b.credential, { e2e: 0, legacy: 3 })).status).toBe(200);
+ expect(delta(await daily(), before)).toEqual({ seen: 0, token: 1, e2e: 0, new: 0 });
+
+ const c = await installation("[email protected]");
+ before = await daily();
+ for (let index = 0; index < 2; index += 1) expect((await ask(relayEnv({ RELAY_ROLLOUT_PERCENT: "0" }), c.credential, { e2e: 1, legacy: 0 })).status).toBe(503);
+ expect(delta(await daily(), before)).toEqual({ seen: 1, token: 0, e2e: 1, new: 1 });
+
+ // The next day: a's row as yesterday's requests left it.
+ const yesterday = Date.now() - 24 * 60 * 60 * 1000;
+ await env.DB.prepare("UPDATE relay_adoption SET updated_at = ?1, token_at = ?1, e2e_at = ?1 WHERE installation_id = ?2").bind(yesterday, a.id).run();
+ before = await daily();
+ expect((await ask(relayEnv(), a.credential, { e2e: 1, legacy: 0 })).status).toBe(200);
+ expect(delta(await daily(), before)).toEqual({ seen: 1, token: 1, e2e: 1, new: 0 });
+ const row = await env.DB.prepare("SELECT first_seen_at, token_at, e2e_at FROM relay_adoption WHERE installation_id = ?").bind(a.id).first<Record<string, number>>();
+ expect(row!.first_seen_at).toBeLessThan(row!.token_at);
+ });
+
+ it("keep only the day, the kind and a count", async () => {
+ const columns = await env.DB.prepare("PRAGMA table_info(relay_daily)").all<{ name: string }>();
+ expect(columns.results.map((column) => column.name)).toEqual(["day", "kind", "installs"]);
+ });
+});
+
describe("node order", () => {
const nodes = ["relay1.openmausbot.com", "relay2.openmausbot.com", "relay3.openmausbot.com"];
@@ -240,3 +287,30 @@ describe("a Worker deployed before migration 0012", () => {
expect((await call(oldEnv, "/v1/installations/self", { token: credential, method: "GET" })).status).toBe(200);
});
});
+
+describe("a Worker deployed before migration 0014", () => {
+ it("still mints tokens and records adoption, without the daily counts", async () => {
+ const db = env.MIGRATION_DB;
+ const daily = env.TEST_MIGRATIONS.findIndex((migration) => migration.name.startsWith("0014_"));
+ expect(daily).toBeGreaterThan(0);
+ await applyD1Migrations(db, env.TEST_MIGRATIONS.slice(0, daily));
+ const oldEnv = { ...relayEnv(), DB: db } as unknown as Env;
+ const now = Date.now();
+ const lookup = b64u(crypto.getRandomValues(new Uint8Array(16)));
+ const credential = `omb_install_${lookup}.${b64u(crypto.getRandomValues(new Uint8Array(32)))}`;
+ const secretHash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(credential)))]
+ .map((byte) => byte.toString(16).padStart(2, "0")).join("");
+ const installationId = crypto.randomUUID();
+ await db.batch([
+ db.prepare('INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES (?, ?, ?, 1, ?, ?)').bind("pre-0014-user", "Old", "[email protected]", now, now),
+ db.prepare("INSERT INTO installations (id, owner_user_id, client_instance_id, display_name, platform, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
+ .bind(installationId, "pre-0014-user", crypto.randomUUID(), "Old computer", "darwin", now, now),
+ db.prepare("INSERT INTO installation_credentials (id, installation_id, lookup_id, secret_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)")
+ .bind(crypto.randomUUID(), installationId, lookup, secretHash, now, now + 3_600_000),
+ ]);
+ const response = await ask(oldEnv, credential, { e2e: 1, legacy: 2 });
+ expect(response.status).toBe(200);
+ const row = await db.prepare("SELECT e2e_devices, legacy_devices FROM relay_adoption WHERE installation_id = ?").bind(installationId).first();
+ expect(row).toEqual({ e2e_devices: 1, legacy_devices: 2 });
+ });
+});
diff --git a/relay/src/hosts.ts b/relay/src/hosts.ts
index de81cd9264..0dd5c203ff 100644
--- a/relay/src/hosts.ts
+++ b/relay/src/hosts.ts
@@ -34,6 +34,8 @@ export class Hosts {
private readonly entries = new Map<string, HostEntry>();
private readonly slots: number;
connected = 0;
+ /** Sessions spliced right now, across every host. */
+ spliced = 0;
constructor(admissionMax: number) {
this.slots = admissionMax;
@@ -145,7 +147,7 @@ export function handleControl(ctx: Context, ws: WebSocket): void {
entry.control = ws;
entry.admission = [];
if (previous) closeWith(ctx, previous, Close.Replaced);
- else ctx.hosts.connected += 1;
+ else ctx.metrics.peak("hosts_connected", (ctx.hosts.connected += 1));
const since = ctx.now();
const rate = new TokenBucket(ctx.limits.controlBurst, ctx.limits.controlPerSecond / 1000, ctx.now);
diff --git a/relay/src/metrics.ts b/relay/src/metrics.ts
index 36ef8140a0..a9b684a3bf 100644
--- a/relay/src/metrics.ts
+++ b/relay/src/metrics.ts
@@ -23,6 +23,50 @@ export interface Gauge {
value: number;
}
+/** Gauges whose highest value of each UTC day this node keeps, today's and the day before's. */
+export type PeakName = "hosts_connected" | "sessions_spliced" | "sockets_open";
+const PEAKS: Record<PeakName, string> = {
+ hosts_connected: "Most hosts with a control socket at once on this node, by UTC day (today and the day before)",
+ sessions_spliced: "Most phone sessions spliced at once on this node, by UTC day (today and the day before)",
+ sockets_open: "Most WebSockets held at once on this node, by UTC day (today and the day before)",
+};
+/** The gauge each peak follows; a scrape counts toward the peak too, so a day with no rise still starts from what is held. */
+const PEAK_OF: Record<string, PeakName> = {
+ relay_hosts_connected: "hosts_connected",
+ relay_sessions_spliced: "sessions_spliced",
+ relay_sockets_open: "sockets_open",
+};
+const DAY_S = 86_400;
+
+/**
+ * A gauge's highest value per UTC day. A scraper that misses minutes (or scrapes rarely) still reads the day's true peak
+ * since this process started; the day before is kept so the last minutes of a day are not lost at midnight.
+ */
+class DailyPeak {
+ private day = -1;
+ private today = 0;
+ private yesterday: { day: number; value: number } | undefined;
+
+ see(value: number, day: number): void {
+ this.roll(day);
+ if (value > this.today) this.today = value;
+ }
+
+ values(day: number): { day: number; value: number }[] {
+ this.roll(day);
+ return [...(this.yesterday && this.yesterday.day === day - 1 ? [this.yesterday] : []), { day, value: this.today }];
+ }
+
+ private roll(day: number): void {
+ if (day === this.day) return;
+ this.yesterday = this.day === day - 1 ? { day: this.day, value: this.today } : undefined;
+ this.day = day;
+ this.today = 0;
+ }
+}
+
+const isoDay = (day: number) => new Date(day * DAY_S * 1000).toISOString().slice(0, 10);
+
const LAG_TICK_MS = 100;
const LAG_SAMPLES_MAX = 4_096;
@@ -56,6 +100,13 @@ class LoopLag {
export class Metrics {
private readonly counts = new Map<string, number>();
private readonly lag = new LoopLag();
+ private readonly peaks = new Map<PeakName, DailyPeak>();
+ private readonly utcDay: () => number;
+
+ /** `wallSeconds` is the clock the daily peaks are bucketed by. */
+ constructor(wallSeconds: () => number = () => Date.now() / 1000) {
+ this.utcDay = () => Math.floor(wallSeconds() / DAY_S);
+ }
inc(name: CounterName, label?: string | number, by = 1): void {
const key = label === undefined ? name : `${name}\u0000${label}`;
@@ -66,6 +117,13 @@ export class Metrics {
return this.counts.get(label === undefined ? name : `${name}\u0000${label}`) ?? 0;
}
+ /** Records a gauge's current value toward today's peak. Call it where the gauge goes up. */
+ peak(name: PeakName, value: number): void {
+ let peak = this.peaks.get(name);
+ if (!peak) this.peaks.set(name, (peak = new DailyPeak()));
+ peak.see(value, this.utcDay());
+ }
+
/** Prometheus text format. The event-loop lag window restarts at each render, so it covers one scrape interval. */
render(gauges: Gauge[]): string {
const lines: string[] = [];
@@ -78,6 +136,13 @@ export class Metrics {
lines.push(at < 0 ? `${name} ${value}` : `${name}{${label}="${key.slice(at + 1)}"} ${value}`);
}
}
+ for (const { name, value } of gauges) if (PEAK_OF[name]) this.peak(PEAK_OF[name], value);
+ const day = this.utcDay();
+ for (const [name, help] of Object.entries(PEAKS) as [PeakName, string][]) {
+ lines.push(`# HELP relay_${name}_peak ${help}`, `# TYPE relay_${name}_peak gauge`);
+ const values = this.peaks.get(name)?.values(day) ?? [{ day, value: 0 }];
+ for (const { day: at, value } of values) lines.push(`relay_${name}_peak{day="${isoDay(at)}"} ${value}`);
+ }
const usage = process.cpuUsage();
const memory = process.memoryUsage();
const lag = this.lag.take();
diff --git a/relay/src/server.ts b/relay/src/server.ts
index 95f6fd6509..6e03769007 100644
--- a/relay/src/server.ts
+++ b/relay/src/server.ts
@@ -48,7 +48,7 @@ export async function startRelay(config: RelayConfig, options: RelayOptions = {}
const { limits } = config;
const now = options.now ?? (() => performance.now());
const wallSeconds = options.wallSeconds ?? (() => Date.now() / 1000);
- const metrics = new Metrics();
+ const metrics = new Metrics(wallSeconds);
const ctx = {
node: config.node,
limits,
@@ -76,17 +76,13 @@ export async function startRelay(config: RelayConfig, options: RelayOptions = {}
const gauges = () => {
let pending = 0;
- let spliced = 0;
for (const entry of ctx.hosts.all()) {
- for (const session of entry.sessions.values()) {
- if (session.state === "pending") pending += 1;
- else if (session.state === "spliced") spliced += 1;
- }
+ for (const session of entry.sessions.values()) if (session.state === "pending") pending += 1;
}
return [
{ name: "relay_hosts_connected", help: "Hosts with a control socket on this node", value: ctx.hosts.connected },
{ name: "relay_sessions_pending", help: "Phones waiting for their host's data socket", value: pending },
- { name: "relay_sessions_spliced", help: "Phone sessions spliced to a host", value: spliced },
+ { name: "relay_sessions_spliced", help: "Phone sessions spliced to a host", value: ctx.hosts.spliced },
{ name: "relay_sockets_open", help: "WebSockets held, every route", value: sockets.size },
{ name: "relay_sockets_max", help: "WebSockets this node holds before answering 4503", value: limits.socketsMax },
{ name: "relay_ip_entries", help: "Client keys with limiter state", value: ipLimiter.size },
@@ -159,6 +155,7 @@ export async function startRelay(config: RelayConfig, options: RelayOptions = {}
}
metrics.inc("relay_upgrades_total", route);
sockets.set(ws, route);
+ metrics.peak("sockets_open", sockets.size);
ws.once("close", () => {
sockets.delete(ws);
ipLimiter.release(key);
diff --git a/relay/src/splice.ts b/relay/src/splice.ts
index 276df8f9f6..fbb06725e8 100644
--- a/relay/src/splice.ts
+++ b/relay/src/splice.ts
@@ -102,6 +102,7 @@ export class Session {
this.ctx.heartbeat.track(this.phone);
this.ctx.heartbeat.track(data);
this.ctx.metrics.inc("relay_sessions_total");
+ this.ctx.metrics.peak("sessions_spliced", (this.ctx.hosts.spliced += 1));
sendJson(this.phone, { t: "ready" });
}
@@ -209,6 +210,7 @@ export class Session {
}
private finish(code: number): void {
+ if (this.state === "spliced") this.ctx.hosts.spliced -= 1;
this.state = "closed";
clearTimeout(this.openTimer);
for (const dir of [this.toHost, this.toPhone]) clearTimeout(dir?.wedge);
diff --git a/relay/test/metrics.test.ts b/relay/test/metrics.test.ts
index 72e32d4426..5e456218dd 100644
--- a/relay/test/metrics.test.ts
+++ b/relay/test/metrics.test.ts
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { describe, test } from "node:test";
import { bearerMatches, Metrics } from "../src/metrics.ts";
-import { sleep } from "./helpers.ts";
+import { sleep, splicedPair, startTestRelay } from "./helpers.ts";
const value = (text: string, name: string) => Number(new RegExp(`^${name.replace(/[{}"]/g, "\\$&")} (\\S+)$`, "m").exec(text)?.[1]);
@@ -49,4 +49,63 @@ describe("metrics", () => {
metrics.close();
}
});
+
+ test("daily peaks keep the day's highest value, today's and the day before's, by UTC day", () => {
+ let now = Date.parse("2026-11-06T23:59:00Z") / 1000;
+ const metrics = new Metrics(() => now);
+ try {
+ metrics.peak("hosts_connected", 3);
+ metrics.peak("hosts_connected", 7);
+ metrics.peak("hosts_connected", 5);
+ let text = metrics.render([]);
+ assert.equal(value(text, 'relay_hosts_connected_peak{day="2026-11-06"}'), 7);
+ assert.equal(value(text, 'relay_sessions_spliced_peak{day="2026-11-06"}'), 0);
+ now += 120;
+ metrics.peak("hosts_connected", 2);
+ text = metrics.render([]);
+ assert.equal(value(text, 'relay_hosts_connected_peak{day="2026-11-06"}'), 7);
+ assert.equal(value(text, 'relay_hosts_connected_peak{day="2026-11-07"}'), 2);
+ // What a scrape sees is held now: a day with no rise still starts from it.
+ now += 86_400;
+ text = metrics.render([{ name: "relay_hosts_connected", help: "h", value: 4 }]);
+ assert.equal(value(text, 'relay_hosts_connected_peak{day="2026-11-08"}'), 4);
+ assert.equal(value(text, 'relay_hosts_connected_peak{day="2026-11-07"}'), 2);
+ assert.ok(!text.includes('day="2026-11-06"'));
+ // A gap of more than a day leaves no stale "day before".
+ now += 3 * 86_400;
+ text = metrics.render([]);
+ assert.ok(!text.includes('day="2026-11-08"'));
+ assert.equal(value(text, 'relay_hosts_connected_peak{day="2026-11-11"}'), 0);
+ } finally {
+ metrics.close();
+ }
+ });
+
+ test("a running relay's peaks follow hosts, sessions and sockets, and the spliced gauge returns to 0", async () => {
+ const t = await startTestRelay();
+ try {
+ const { host, phone, data } = await splicedPair(t.url, t.key);
+ const day = new Date().toISOString().slice(0, 10);
+ const scrape = async () => {
+ const response = await fetch(`http://127.0.0.1:${t.relay.port}/metrics`, { headers: { authorization: `Bearer ${"m".repeat(40)}` } });
+ return response.text();
+ };
+ let text = await scrape();
+ assert.equal(value(text, "relay_sessions_spliced"), 1);
+ assert.equal(value(text, `relay_hosts_connected_peak{day="${day}"}`), 1);
+ assert.equal(value(text, `relay_sessions_spliced_peak{day="${day}"}`), 1);
+ assert.ok(value(text, `relay_sockets_open_peak{day="${day}"}`) >= 3);
+ phone.ws.close(1000);
+ await data.closeCode();
+ host.control.ws.close();
+ const until = performance.now() + 2_000;
+ while (t.relay.ctx.hosts.connected > 0 && performance.now() < until) await sleep(20);
+ text = await scrape();
+ assert.equal(value(text, "relay_sessions_spliced"), 0);
+ assert.equal(value(text, "relay_hosts_connected"), 0);
+ assert.equal(value(text, `relay_sessions_spliced_peak{day="${day}"}`), 1);
+ } finally {
+ await t.stop();
+ }
+ });
});