Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Metrics.ts

226 lines8.0 KB

1import * as Clock from "effect/Clock";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Metric from "effect/Metric";
6import { dual } from "effect/Function";
7​
8import { compactMetricAttributes, outcomeFromExit } from "./Attributes.ts";
9​
10export const rpcRequestsTotal = Metric.counter("t3_rpc_requests_total", {
11 description: "Total RPC requests handled by the websocket RPC server.",
12 incremental: true,
13});
14​
15export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", {
16 description: "RPC request handling duration.",
17});
18​
19export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", {
20 description: "Total orchestration commands dispatched, by outcome.",
21 incremental: true,
22});
23​
24export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", {
25 description: "Orchestration command handling duration, excluding thread dispatch lock wait.",
26});
27​
28export const orchestrationEffectClaimsTotal = Metric.counter(
29 "t3_orchestration_effect_claims_total",
30 {
31 description: "Total completed orchestration effect outbox claim attempts by result.",
32 incremental: true,
33 },
34);
35​
36export const orchestrationEffectQueueWait = Metric.timer("t3_orchestration_effect_queue_wait", {
37 description:
38 "Time from an orchestration effect's temporal availability until claim, including same-thread blocking.",
39});
40​
41// A failed batch (transport errors and 408/429/500/502/503/504 after 3 retries) is dropped with
42// every push for the next 60 s, logged only at Debug. Incremental exports it as a monotonic counter.
43export const otlpExportAttemptFailuresTotal = Metric.counter(
44 "t3_otlp_export_attempt_failures_total",
45 {
46 description:
47 "Failed OTLP export attempts by signal and reason. Retries count too, so a dropped batch counts up to four.",
48 incremental: true,
49 },
50);
51​
52export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", {
53 description: "Total provider session lifecycle operations.",
54 incremental: true,
55});
56​
57export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", {
58 description: "Total provider turn lifecycle operations.",
59 incremental: true,
60});
61​
62export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", {
63 description: "Time for the provider adapter to start a turn, not how long the turn runs.",
64});
65​
66// OTLP carries the unit, and Prometheus names the series by it: a unitless gauge gains `_ratio`.
67export const serverResidentBytes = Metric.gauge("t3_server_resident_bytes", {
68 description: "Resident memory of the server process.",
69 attributes: { unit: "By" },
70});
71​
72export const serverHeapUsedBytes = Metric.gauge("t3_server_heap_used_bytes", {
73 description: "JavaScript heap in use by the server process.",
74 attributes: { unit: "By" },
75});
76​
77export const serverCpuUtilization = Metric.gauge("t3_server_cpu_utilization", {
78 description: "CPU time the server used per second over the last sample; 1 is one full core.",
79});
80​
81export const serverEventLoopUtilization = Metric.gauge("t3_server_event_loop_utilization", {
82 description: "Share of the last sample the server's event loop spent busy.",
83});
84​
85export const serverEventLoopDelayMax = Metric.gauge("t3_server_event_loop_delay_max", {
86 description: "Longest event loop delay over the last sample.",
87 attributes: { unit: "ms" },
88});
89​
90export const runsTotal = Metric.counter("t3_runs_total", {
91 description: "Runs that finished, by outcome. A later rollback does not count again.",
92 incremental: true,
93});
94​
95export const runDuration = Metric.timer("t3_run_duration", {
96 description: "Wall time of a run, from when it started to its terminal status.",
97});
98​
99export const runQueueWait = Metric.timer("t3_run_queue_wait", {
100 description: "Time a run waited between being requested and starting.",
101});
102​
103export const gitCommandsTotal = Metric.counter("t3_git_commands_total", {
104 description: "Total git commands executed by the server runtime.",
105 incremental: true,
106});
107​
108export const gitCommandDuration = Metric.timer("t3_git_command_duration", {
109 description: "Git command execution duration.",
110});
111​
112export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", {
113 description: "Total terminal sessions started.",
114 incremental: true,
115});
116​
117export const webhookDeliveriesTotal = Metric.counter("t3_webhook_deliveries_total", {
118 description: "Webhook requests handled, by outcome and source.",
119 incremental: true,
120});
121​
122export const webhookDeliveryDuration = Metric.timer("t3_webhook_delivery_duration", {
123 description: "Time to verify, log, and enqueue one webhook request.",
124});
125​
126export const webhookHeldDelay = Metric.timer("t3_webhook_held_delay", {
127 description:
128 "Time between the relay receiving a webhook request and the environment handling it.",
129});
130​
131export const webhookRunsTotal = Metric.counter("t3_webhook_runs_total", {
132 description: "Runs started from webhook deliveries, by outcome.",
133 incremental: true,
134});
135​
136export const secretRequestsTotal = Metric.counter("t3_secret_requests_total", {
137 description: "Secrets agents asked users for, by how each request ended.",
138 incremental: true,
139});
140​
141export const secretRefsConsumedTotal = Metric.counter("t3_secret_refs_consumed_total", {
142 description: "Secret refs tools tried to use, by result.",
143 incremental: true,
144});
145​
146export const metricAttributes = (
147 attributes: Readonly<Record<string, unknown>>,
148): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
149​
150export const increment = (
151 metric: Metric.Metric<number, unknown>,
152 attributes: Readonly<Record<string, unknown>>,
153 amount = 1,
154) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);
155​
156export interface WithMetricsOptions {
157 readonly counter?: Metric.Metric<number, unknown>;
158 readonly timer?: Metric.Metric<Duration.Duration, unknown>;
159 readonly attributes?:
160 | Readonly<Record<string, unknown>>
161 | (() => Readonly<Record<string, unknown>>);
162 readonly outcomeAttributes?: (
163 outcome: ReturnType<typeof outcomeFromExit>,
164 ) => Readonly<Record<string, unknown>>;
166​
167const recordMetrics =
168 /* Instrumentation must not create its own span for every recorded operation. */
169 Effect.fnUntraced(function* (
170 options: WithMetricsOptions,
171 startedAt: bigint,
172 exit: Exit.Exit<unknown, unknown>,
173 ) {
174 const duration = Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt);
175 const baseAttributes =
176 typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
177​
178 if (options.timer) {
179 yield* Metric.update(
180 Metric.withAttributes(options.timer, metricAttributes(baseAttributes)),
181 duration,
182 );
183 }
184​
185 if (options.counter) {
186 const outcome = outcomeFromExit(exit);
187 yield* Metric.update(
188 Metric.withAttributes(
189 options.counter,
190 metricAttributes({
191 ...baseAttributes,
192 outcome,
193 ...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}),
194 }),
195 ),
196 1,
197 );
198 }
199 });
200​
201// Monotonic timing ignores clock corrections; exit finalizers count interruptions.
202const withMetricsImpl = <A, E, R>(
203 effect: Effect.Effect<A, E, R>,
204 options: WithMetricsOptions,
205): Effect.Effect<A, E, R> =>
206 Effect.flatMap(Clock.monotonicTimeNanos, (startedAt) =>
207 Effect.onExit(effect, (exit) => recordMetrics(options, startedAt, exit)),
208 );
209​
210export const withMetrics: {
211 (
212 options: WithMetricsOptions,
213 ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
214 <A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;
215} = dual(2, withMetricsImpl);
216​
217// Shaped as an `Effect.fn` combinator: the command is the instrumented function's argument.
218export const withCommandMetrics = <A, E, R>(
219 effect: Effect.Effect<A, E, R>,
220 command: { readonly type: string },
221): Effect.Effect<A, E, R> =>
222 withMetrics(effect, {
223 counter: orchestrationCommandsTotal,
224 timer: orchestrationCommandDuration,
225 attributes: { commandType: command.type },
226 });