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