Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import { Effect, Metric } from "effect";
3
4import { withMetrics } from "./Metrics.ts";
5
6const hasMetricSnapshot = (
7 snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
8 id: string,
9 attributes: Readonly<Record<string, string>>,
10) =>
11 snapshots.some(
12 (snapshot) =>
13 snapshot.id === id &&
14 Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
15 );
16
17describe("withMetrics", () => {
18 it.effect("supports pipe-style usage", () =>
19 Effect.gen(function* () {
20 const counter = Metric.counter("with_metrics_pipe_total");
21 const timer = Metric.timer("with_metrics_pipe_duration");
22
23 const result = yield* Effect.succeed("ok").pipe(
24 withMetrics({
25 counter,
26 timer,
27 attributes: {
28 operation: "pipe",
29 },
30 }),
31 );
32
33 assert.equal(result, "ok");
34
35 const snapshots = yield* Metric.snapshot;
36 assert.equal(
37 hasMetricSnapshot(snapshots, "with_metrics_pipe_total", {
38 operation: "pipe",
39 outcome: "success",
40 }),
41 true,
42 );
43 assert.equal(
44 hasMetricSnapshot(snapshots, "with_metrics_pipe_duration", {
45 operation: "pipe",
46 }),
47 true,
48 );
49 }),
50 );
51
52 it.effect("supports direct invocation", () =>
53 Effect.gen(function* () {
54 const counter = Metric.counter("with_metrics_direct_total");
55
56 yield* withMetrics(Effect.fail("boom"), {
57 counter,
58 attributes: {
59 operation: "direct",
60 },
61 }).pipe(Effect.exit);
62
63 const snapshots = yield* Metric.snapshot;
64 assert.equal(
65 hasMetricSnapshot(snapshots, "with_metrics_direct_total", {
66 operation: "direct",
67 outcome: "failure",
68 }),
69 true,
70 );
71 }),
72 );
73
74 it.effect("evaluates attributes lazily after the wrapped effect runs", () =>
75 Effect.gen(function* () {
76 const counter = Metric.counter("with_metrics_lazy_total");
77 const timer = Metric.timer("with_metrics_lazy_duration");
78 let provider = "unknown";
79
80 yield* Effect.sync(() => {
81 provider = "codex";
82 }).pipe(
83 withMetrics({
84 counter,
85 timer,
86 attributes: () => ({
87 provider,
88 operation: "lazy",
89 }),
90 }),
91 );
92
93 const snapshots = yield* Metric.snapshot;
94 assert.equal(
95 hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
96 provider: "codex",
97 operation: "lazy",
98 outcome: "success",
99 }),
100 true,
101 );
102 assert.equal(
103 hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
104 provider: "codex",
105 operation: "lazy",
106 }),
107 true,
108 );
109 }),
110 );
111});