src/transport/telemetry.ts
v0.3.0 · 1.8 KB
// Per-label request counters.
//
// Label every request by subsystem (e.g. `bg:<type>` for background reads, `trade:<type>` for the
// trading path) and periodically log the breakdown. The main duplicate signal is the SAME data
// fetched by two subsystems: `bg:meta` + `trade:meta` is a duplicate (there is one global meta),
// while `clearinghouseState` of two different accounts is not. A periodic breakdown line exposes a
// `meta` stampede this way: many calls per subsystem where one is expected.
/** One row of a counter breakdown. */
export interface LabelCount {
label: string;
requests: number;
weight: number;
}
/** Counter handle returned by {@link createRequestCounter}. */
export interface RequestCounter {
/** Records one real request (every attempt, retries included). */
record(label: string, weight?: number): void;
/** Rows sorted by weight, then by requests (descending), without resetting. */
snapshot(): LabelCount[];
/** Same as {@link snapshot}, then resets the counters. */
drain(): LabelCount[];
}
/** Creates an in-memory per-label counter. Feed it from `createInfoClient({ onAttempt })`. */
export function createRequestCounter(): RequestCounter {
const rows = new Map<string, LabelCount>();
const snapshot = (): LabelCount[] =>
[...rows.values()]
.map((r) => ({ ...r }))
.sort((a, b) => b.weight - a.weight || b.requests - a.requests || a.label.localeCompare(b.label));
return {
record(label, weight = 0) {
const row = rows.get(label) ?? { label, requests: 0, weight: 0 };
row.requests += 1;
row.weight += Number.isFinite(weight) && weight > 0 ? weight : 0;
rows.set(label, row);
},
snapshot,
drain() {
const out = snapshot();
rows.clear();
return out;
},
};
}