Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Metric from "effect/Metric";
5import { HttpClient, HttpClientResponse } from "effect/http";
6import { OtlpMetrics, OtlpSerialization } from "effect/observability";
7import { describe } from "vite-plus/test";
8
9import * as Metrics from "./Metrics.ts";
10
11const TOTAL_COUNTERS = Object.values(Metrics).filter(
12 (value): value is Metric.Counter<number> => Metric.isMetric(value) && value.type === "Counter",
13);
14
15interface OtlpMetricsPayload {
16 readonly resourceMetrics?: ReadonlyArray<{
17 readonly scopeMetrics?: ReadonlyArray<{
18 readonly metrics?: ReadonlyArray<{
19 readonly name?: string;
20 readonly sum?: { readonly isMonotonic?: boolean };
21 }>;
22 }>;
23 }>;
24}
25
26describe("Metrics", () => {
27 it.effect("exports every *_total counter as a monotonic OTLP sum", () => {
28 const exported: Array<OtlpMetricsPayload> = [];
29 const client = HttpClient.make((request) => {
30 if (request.body._tag === "Uint8Array") {
31 exported.push(
32 JSON.parse(new TextDecoder().decode(request.body.body)) as OtlpMetricsPayload,
33 );
34 }
35 return Effect.succeed(
36 HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
37 );
38 });
39 const layer = OtlpMetrics.layer({
40 url: "http://localhost:4318/v1/metrics",
41 resource: { serviceName: "t3-test" },
42 exportInterval: "1 hour",
43 shutdownTimeout: "1 second",
44 }).pipe(
45 Layer.provide(OtlpSerialization.layerJson),
46 Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
47 );
48
49 return Effect.gen(function* () {
50 const registry = new Map();
51 yield* Effect.scoped(
52 Effect.gen(function* () {
53 yield* Layer.build(layer);
54 for (const counter of TOTAL_COUNTERS) {
55 yield* Metric.update(counter, 1);
56 }
57 }),
58 ).pipe(Effect.provideService(Metric.MetricRegistry, registry));
59
60 const sumsByName = new Map(
61 exported
62 .flatMap((payload) => payload.resourceMetrics ?? [])
63 .flatMap((resourceMetric) => resourceMetric.scopeMetrics ?? [])
64 .flatMap((scopeMetric) => scopeMetric.metrics ?? [])
65 .flatMap((metric) =>
66 typeof metric.name === "string" && metric.sum !== undefined
67 ? [[metric.name, metric.sum.isMonotonic] as const]
68 : [],
69 ),
70 );
71
72 assert.isAbove(TOTAL_COUNTERS.length, 0);
73 assert.strictEqual(sumsByName.size, TOTAL_COUNTERS.length);
74 for (const [name, isMonotonic] of sumsByName) {
75 assert.isTrue(isMonotonic, `${name} should export with sum.isMonotonic = true`);
76 }
77 });
78 });
79});