@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 54 lines 2.06 KB
Raw
1 import type { OtlpSignal } from "@t3tools/contracts";
2 import * as Context from "effect/Context";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Metric from "effect/Metric";
6 import { HttpClient } from "effect/http";
7 import type { HttpBody } from "effect/http";
8 import { OtlpSerialization } from "effect/observability";
9
10 import { otlpExportAttemptFailuresTotal } from "./Metrics.ts";
11
12 /**
13 * Re-provides the HttpClient and OtlpSerialization one OTLP exporter uses, counting its failed
14 * attempts on the metrics channel. The exporter applies `filterStatusOk` and its retries outside
15 * this client, so a non-2xx arrives here as a response and each retry is counted.
16 */
17 export const layer = (signal: OtlpSignal) =>
18 Layer.effectContext(
19 Effect.gen(function* () {
20 const context = yield* Effect.context<never>();
21 const client = yield* HttpClient.HttpClient;
22 const serialization = yield* OtlpSerialization.OtlpSerialization;
23 const failures = (reason: string) =>
24 Metric.withAttributes(otlpExportAttemptFailuresTotal, { signal, reason });
25 // Encoding runs synchronously inside the exporter, before any request exists.
26 const counted =
27 <A>(encode: (data: A) => HttpBody.HttpBody) =>
28 (data: A) => {
29 try {
30 return encode(data);
31 } catch (error) {
32 failures("encode").updateUnsafe(1, context);
33 throw error;
34 }
35 };
36 return Context.make(
37 HttpClient.HttpClient,
38 client.pipe(
39 HttpClient.tap((response) =>
40 response.status >= 200 && response.status < 300
41 ? Effect.void
42 : Metric.update(failures(`status_${response.status}`), 1),
43 ),
44 HttpClient.tapError(() => Metric.update(failures("transport"), 1)),
45 ),
46 ).pipe(
47 Context.add(OtlpSerialization.OtlpSerialization, {
48 traces: counted(serialization.traces),
49 metrics: counted(serialization.metrics),
50 logs: counted(serialization.logs),
51 }),
52 );
53 }),
54 );