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 gitCommandsTotal = Metric.counter("t3_git_commands_total", {
67 description: "Total git commands executed by the server runtime.",
68});
69
70export const gitCommandDuration = Metric.timer("t3_git_command_duration", {
71 description: "Git command execution duration.",
72});
73
74export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", {
75 description: "Total terminal sessions started.",
76});
77
78export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", {
79 description: "Total terminal restart requests handled.",
80});
81
82export const webhookDeliveriesTotal = Metric.counter("t3_webhook_deliveries_total", {
83 description: "Webhook requests handled, by outcome and source.",
84});
85
86export const webhookDeliveryDuration = Metric.timer("t3_webhook_delivery_duration", {
87 description: "Time to verify, log, and enqueue one webhook request.",
88});
89
90export const webhookHeldDelay = Metric.timer("t3_webhook_held_delay", {
91 description:
92 "Time between the relay receiving a webhook request and the environment handling it.",
93});
94
95export const webhookRunsTotal = Metric.counter("t3_webhook_runs_total", {
96 description: "Runs started from webhook deliveries, by outcome.",
97});
98
99export const secretRequestsTotal = Metric.counter("t3_secret_requests_total", {
100 description: "Secrets agents asked users for, by how each request ended.",
101});
102
103export const secretRefsConsumedTotal = Metric.counter("t3_secret_refs_consumed_total", {
104 description: "Secret refs tools tried to use, by result.",
105});
106
107export const metricAttributes = (
108 attributes: Readonly<Record<string, unknown>>,
109): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
110
111export const increment = (
112 metric: Metric.Metric<number, unknown>,
113 attributes: Readonly<Record<string, unknown>>,
114 amount = 1,
115) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);
116
117export interface WithMetricsOptions {
118 readonly counter?: Metric.Metric<number, unknown>;
119 readonly timer?: Metric.Metric<Duration.Duration, unknown>;
120 readonly attributes?:
121 | Readonly<Record<string, unknown>>
122 | (() => Readonly<Record<string, unknown>>);
123 readonly outcomeAttributes?: (
124 outcome: ReturnType<typeof outcomeFromExit>,
125 ) => Readonly<Record<string, unknown>>;
126}
127
128const recordMetrics =
129 /* Instrumentation must not create its own span for every recorded operation. */
130 Effect.fnUntraced(function* (
131 options: WithMetricsOptions,
132 startedAt: bigint,
133 exit: Exit.Exit<unknown, unknown>,
134 ) {
135 const duration = Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt);
136 const baseAttributes =
137 typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
138
139 if (options.timer) {
140 yield* Metric.update(
141 Metric.withAttributes(options.timer, metricAttributes(baseAttributes)),
142 duration,
143 );
144 }
145
146 if (options.counter) {
147 const outcome = outcomeFromExit(exit);
148 yield* Metric.update(
149 Metric.withAttributes(
150 options.counter,
151 metricAttributes({
152 ...baseAttributes,
153 outcome,
154 ...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}),
155 }),
156 ),
157 1,
158 );
159 }
160 });
161
162// Durations come from the monotonic clock, so wall-clock corrections cannot skew them, and
163// metrics are recorded in an exit finalizer, so interrupted work is counted as "interrupt".
164const withMetricsImpl = <A, E, R>(
165 effect: Effect.Effect<A, E, R>,
166 options: WithMetricsOptions,
167): Effect.Effect<A, E, R> =>
168 Effect.flatMap(Clock.monotonicTimeNanos, (startedAt) =>
169 Effect.onExit(effect, (exit) => recordMetrics(options, startedAt, exit)),
170 );
171
172export const withMetrics: {
173 (
174 options: WithMetricsOptions,
175 ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
176 <A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;
177} = dual(2, withMetricsImpl);