Open History to see the last commit
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});
13
14export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", {
15 description: "RPC request handling duration.",
16});
17
18export const orchestrationEffectClaimsTotal = Metric.counter(
19 "t3_orchestration_effect_claims_total",
20 {
21 description: "Total completed orchestration effect outbox claim attempts by result.",
22 },
23);
24
25export const orchestrationEffectQueueWait = Metric.timer("t3_orchestration_effect_queue_wait", {
26 description:
27 "Time from an orchestration effect's temporal availability until claim, including same-thread blocking.",
28});
29
30export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", {
31 description: "Total provider session lifecycle operations.",
32});
33
34export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", {
35 description: "Total provider turn lifecycle operations.",
36});
37
38export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", {
39 description: "Time for the provider adapter to start a turn, not how long the turn runs.",
40});
41
42// OTLP carries the unit, and Prometheus names the series by it: a unitless gauge gains `_ratio`.
43export const serverResidentBytes = Metric.gauge("t3_server_resident_bytes", {
44 description: "Resident memory of the server process.",
45 attributes: { unit: "By" },
46});
47
48export const serverHeapUsedBytes = Metric.gauge("t3_server_heap_used_bytes", {
49 description: "JavaScript heap in use by the server process.",
50 attributes: { unit: "By" },
51});
52
53export const serverCpuUtilization = Metric.gauge("t3_server_cpu_utilization", {
54 description: "CPU time the server used per second over the last sample; 1 is one full core.",
55});
56
57export const serverEventLoopUtilization = Metric.gauge("t3_server_event_loop_utilization", {
58 description: "Share of the last sample the server's event loop spent busy.",
59});
60
61export const serverEventLoopDelayMax = Metric.gauge("t3_server_event_loop_delay_max", {
62 description: "Longest event loop delay over the last sample.",
63 attributes: { unit: "ms" },
64});
65
66export const runsTotal = Metric.counter("t3_runs_total", {
67 description: "Runs that finished, by outcome. A later rollback does not count again.",
68});
69
70export const runDuration = Metric.timer("t3_run_duration", {
71 description: "Wall time of a run, from when it started to its terminal status.",
72});
73
74export const runQueueWait = Metric.timer("t3_run_queue_wait", {
75 description: "Time a run waited between being requested and starting.",
76});
77
78export const gitCommandsTotal = Metric.counter("t3_git_commands_total", {
79 description: "Total git commands executed by the server runtime.",
80});
81
82export const gitCommandDuration = Metric.timer("t3_git_command_duration", {
83 description: "Git command execution duration.",
84});
85
86export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", {
87 description: "Total terminal sessions started.",
88});
89
90export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", {
91 description: "Total terminal restart requests handled.",
92});
93
94export const webhookDeliveriesTotal = Metric.counter("t3_webhook_deliveries_total", {
95 description: "Webhook requests handled, by outcome and source.",
96});
97
98export const webhookDeliveryDuration = Metric.timer("t3_webhook_delivery_duration", {
99 description: "Time to verify, log, and enqueue one webhook request.",
100});
101
102export const webhookHeldDelay = Metric.timer("t3_webhook_held_delay", {
103 description:
104 "Time between the relay receiving a webhook request and the environment handling it.",
105});
106
107export const webhookRunsTotal = Metric.counter("t3_webhook_runs_total", {
108 description: "Runs started from webhook deliveries, by outcome.",
109});
110
111export const secretRequestsTotal = Metric.counter("t3_secret_requests_total", {
112 description: "Secrets agents asked users for, by how each request ended.",
113});
114
115export const secretRefsConsumedTotal = Metric.counter("t3_secret_refs_consumed_total", {
116 description: "Secret refs tools tried to use, by result.",
117});
118
119export const metricAttributes = (
120 attributes: Readonly<Record<string, unknown>>,
121): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
122
123export const increment = (
124 metric: Metric.Metric<number, unknown>,
125 attributes: Readonly<Record<string, unknown>>,
126 amount = 1,
127) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);
128
129export interface WithMetricsOptions {
130 readonly counter?: Metric.Metric<number, unknown>;
131 readonly timer?: Metric.Metric<Duration.Duration, unknown>;
132 readonly attributes?:
133 | Readonly<Record<string, unknown>>
134 | (() => Readonly<Record<string, unknown>>);
135 readonly outcomeAttributes?: (
136 outcome: ReturnType<typeof outcomeFromExit>,
137 ) => Readonly<Record<string, unknown>>;
138}
139
140const recordMetrics =
141 /* Instrumentation must not create its own span for every recorded operation. */
142 Effect.fnUntraced(function* (
143 options: WithMetricsOptions,
144 startedAt: bigint,
145 exit: Exit.Exit<unknown, unknown>,
146 ) {
147 const duration = Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt);
148 const baseAttributes =
149 typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
150
151 if (options.timer) {
152 yield* Metric.update(
153 Metric.withAttributes(options.timer, metricAttributes(baseAttributes)),
154 duration,
155 );
156 }
157
158 if (options.counter) {
159 const outcome = outcomeFromExit(exit);
160 yield* Metric.update(
161 Metric.withAttributes(
162 options.counter,
163 metricAttributes({
164 ...baseAttributes,
165 outcome,
166 ...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}),
167 }),
168 ),
169 1,
170 );
171 }
172 });
173
174// Durations come from the monotonic clock, so wall-clock corrections cannot skew them, and
175// metrics are recorded in an exit finalizer, so interrupted work is counted as "interrupt".
176const withMetricsImpl = <A, E, R>(
177 effect: Effect.Effect<A, E, R>,
178 options: WithMetricsOptions,
179): Effect.Effect<A, E, R> =>
180 Effect.flatMap(Clock.monotonicTimeNanos, (startedAt) =>
181 Effect.onExit(effect, (exit) => recordMetrics(options, startedAt, exit)),
182 );
183
184export const withMetrics: {
185 (
186 options: WithMetricsOptions,
187 ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
188 <A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;
189} = dual(2, withMetricsImpl);