Skip to content
Myr

spans.test.ts

This file

Path

packages/telemetry/test/spans.test.ts

320 lines · 9.7 KiB · TypeScript

Last changed by

Merge observability/typed-failures into mainoscabrielbefore adoption0d940fc

History of this file

Take it

Merge observability into mainoscabrielbefore adoption1985111

lines 1–116why, one step back
1import { describe, expect, it } from "@effect/vitest";
2import { ProjectName } from "@repo/protocol/ids";3import { UnknownProject, VerifierBlocked } from "@repo/protocol/refusal";4import { Effect, Layer, Logger, Option, Redacted } from "effect";56import { scrubberOf } from "../src/logger.ts";7import {8 annotateInvocation,9 refusedWith,10 withInvocation,11} from "../src/spans.ts";12import { tracerOver } from "../src/spans/binding.ts";13import type { Keeping } from "../src/spans/binding.ts";14import {15 recordingTracing,16 ROOT,17 SpansMemory,18 SpansRecorded,19} from "../src/spans/memory.ts";20import type { RecordedSpan } from "../src/spans/memory.ts";2122const recorded = <A, E>(body: Effect.Effect<A, E>, traced = true) =>23 Effect.gen(function* () {24 const { spans } = yield* SpansRecorded;2526 yield* Effect.exit(body);2728 return yield* spans;29 }).pipe(Effect.provide(SpansMemory({ traced })));3031const lineageOf = ({ name, parent }: RecordedSpan) => ({ name, parent });3233const whole = (secrets: readonly Redacted.Redacted[]): Keeping => ({34 defects: "whole",35 scrub: scrubberOf(secrets),36});3738const died = (keeping: Keeping) =>39 Effect.gen(function* () {40 const recording = recordingTracing();4142 yield* Effect.die(new TypeError("no file at secret/plan.md")).pipe(43 Effect.withSpan("Checker.Run"),44 Effect.withTracer(tracerOver(recording.tracing, keeping)),45 Effect.exit46 );4748 return recording.spans()[1]?.exceptions;49 });5051describe("the spans bridge", () => {52 it.effect(53 "opens every span under the invocation's root: siblings of each other and of the runtime's own, while Effect keeps their nesting",54 () =>55 Effect.gen(function* () {56 const recording = recordingTracing();5758 const [land, git] = yield* Effect.currentSpan.pipe(59 // A span the runtime opens itself, as fetch or a Durable Object call does.60 Effect.tap(() =>61 Effect.sync(() => {62 recording.tracing.startSpan("fetch").end();63 })64 ),65 Effect.withSpan("Lander.git"),66 Effect.flatMap((inner) =>67 Effect.map(Effect.currentSpan, (outer) => [outer, inner] as const)68 ),69 Effect.withSpan("Lander.land"),70 Effect.withTracer(tracerOver(recording.tracing, whole([])))71 );7273 expect(recording.spans().map(lineageOf)).toStrictEqual([74 { name: ROOT, parent: undefined },75 { name: "Lander.land", parent: ROOT },76 { name: "Lander.git", parent: ROOT },77 { name: "fetch", parent: ROOT },78 ]);79 expect(Option.map(git.parent, ({ spanId }) => spanId)).toStrictEqual(80 Option.some(land.spanId)81 );82 expect(83 recording.spans().flatMap(({ ended, name }) => (ended ? [] : [name]))84 ).toStrictEqual([ROOT]);85 })86 );8788 it.effect(89 "carries a listed id whose value is a string, a number or a boolean, and drops any other key or value",90 () =>91 Effect.gen(function* () {92 const spans = yield* recorded(93 Effect.void.pipe(94 Effect.withSpan("Workflow.step", {95 attributes: {96 lane: "unit",97 path: "secret/plan.md",98 project: { name: "alice/datekit" },99 repo: "alice__datekit",100 sha: "7".repeat(40),101 step: "cheap#2",102 "url.full": "https://example.com/?code=abc",103 },104 })105 )106 );107108 expect(Object.fromEntries(spans[1]?.attributes ?? [])).toStrictEqual({109 lane: "unit",110 sha: "7".repeat(40),111 step: "cheap#2",112 });113 })114 );115116 it.effect(

Merge observability/typed-failures into mainoscabrielbefore adoption0d940fc

line 117why, one step back
117 "keeps a typed failure's tag as an attribute, never an exception workerd would log as an error, and records a defect by its name, message and stack, scrubbed",

Merge observability into mainoscabrielbefore adoption1985111

lines 118–148why, one step back
118 () =>
119 Effect.gen(function* () {120 const secret = "tok_0123456789abcdef0123456789abcdef";121122 const spans = yield* Effect.gen(function* () {123 const recording = recordingTracing();124125 yield* Effect.exit(126 Effect.all([127 Effect.exit(128 Effect.fail(new VerifierBlocked({})).pipe(129 Effect.withSpan("Checker.Setup")130 )131 ),132 Effect.exit(133 Effect.die(new TypeError(`no fetch with ${secret}`)).pipe(134 Effect.withSpan("Checker.Run")135 )136 ),137 ]).pipe(138 Effect.withTracer(139 tracerOver(recording.tracing, whole([Redacted.make(secret)]))140 )141 )142 );143144 return recording.spans();145 });146147 const [, refused, defect] = spans;148

Merge observability/typed-failures into mainoscabrielbefore adoption0d940fc

lines 149–153why, one step back
149 expect(refused?.exceptions).toStrictEqual([]);
150 expect(Object.fromEntries(refused?.attributes ?? [])).toStrictEqual({151 failure: "VerifierBlocked",152 });153 expect(Object.fromEntries(defect?.attributes ?? [])).toStrictEqual({});

Merge observability into mainoscabrielbefore adoption1985111

lines 154–320why, one step back
154 expect(
155 defect?.exceptions.map(({ message, name }) => ({ message, name }))156 ).toStrictEqual([157 { message: "no fetch with <redacted>", name: "TypeError" },158 ]);159 expect(defect?.exceptions[0]?.stack).toMatch(160 /^TypeError: no fetch with <redacted>\n\s+at /u161 );162 })163 );164165 it.effect(166 "records a defect by its name alone where its text may quote what no trace may hold",167 () =>168 Effect.gen(function* () {169 expect([170 yield* died({ defects: "name", scrub: scrubberOf([]) }),171 (yield* died(whole([])))?.map(({ message }) => message),172 ]).toStrictEqual([173 [{ name: "TypeError" }],174 ["no file at secret/plan.md"],175 ]);176 })177 );178179 it.effect(180 "opens no span Effect did not sample, nor a client's, which the runtime traces itself",181 () =>182 Effect.gen(function* () {183 const spans = yield* recorded(184 Effect.all([185 Effect.void.pipe(Effect.withSpan("unsampled", { sampled: false })),186 Effect.void.pipe(187 Effect.withSpan("sql.execute", { kind: "client" })188 ),189 Effect.void.pipe(Effect.withSpan("Project.claim")),190 ])191 );192193 expect(spans.map(({ name }) => name)).toStrictEqual([194 ROOT,195 "Project.claim",196 ]);197 })198 );199200 it.effect(201 "sets nothing on an invocation the head sampling left out, and still ends each span",202 () =>203 Effect.gen(function* () {204 const spans = yield* recorded(205 Effect.fail(new VerifierBlocked({})).pipe(206 Effect.withSpan("Project.claim", { attributes: { sha: "7" } }),207 Effect.tap(() => annotateInvocation({ project: "alice/datekit" }))208 ),209 false210 );211212 expect(213 spans.map(({ attributes, ended, exceptions, name }) => ({214 attributes: attributes.size,215 ended,216 exceptions: exceptions.length,217 name,218 }))219 ).toStrictEqual([220 { attributes: 0, ended: false, exceptions: 0, name: ROOT },221 { attributes: 0, ended: true, exceptions: 0, name: "Project.claim" },222 ]);223 })224 );225});226227describe(recordingTracing, () => {228 it("traces a span no more once it ends, as workerd does, so what it is handed then is lost", () => {229 const recording = recordingTracing();230 const span = recording.tracing.startSpan("Checker.Run");231232 span.setAttribute("sha", "7");233234 const before = span.isTraced;235236 span.end();237 span.setAttribute("lane", "lint");238 span.recordException({ name: "TypeError" });239240 expect([before, span.isTraced, recording.spans()[1]]).toStrictEqual([241 true,242 false,243 {244 attributes: new Map([["sha", "7"]]),245 ended: true,246 exceptions: [],247 name: "Checker.Run",248 parent: ROOT,249 },250 ]);251 });252});253254describe(annotateInvocation, () => {255 it.effect(256 "sets the ids on the invocation's root span, where Issues reads them",257 () =>258 Effect.gen(function* () {259 const spans = yield* recorded(260 annotateInvocation({261 project: "alice/datekit",262 refusal: "OutOfScope,Weakened",263 requestId: "push-1",264 })265 );266267 expect(Object.fromEntries(spans[0]?.attributes ?? [])).toStrictEqual({268 project: "alice/datekit",269 refusal: "OutOfScope,Weakened",270 requestId: "push-1",271 });272 })273 );274275 it.effect(276 "goes, by withInvocation, onto the root span and onto each line logged under it",277 () =>278 Effect.gen(function* () {279 const lines: unknown[] = [];280281 const spans = yield* recorded(282 Effect.logInfo("a run started").pipe(283 withInvocation({ project: "alice/datekit", requestId: "push-1" }),284 Effect.provide(285 Logger.layer([286 Logger.map(Logger.formatStructured, ({ annotations }) => {287 lines.push(annotations);288 }),289 ])290 )291 )292 );293294 expect([295 Object.fromEntries(spans[0]?.attributes ?? []),296 lines,297 ]).toStrictEqual([298 { project: "alice/datekit", requestId: "push-1" },299 [{ project: "alice/datekit", requestId: "push-1" }],300 ]);301 })302 );303304 it("names each tag an invocation was refused with once, and none when it was not", () => {305 expect([306 refusedWith([307 new VerifierBlocked({}),308 new UnknownProject({ project: ProjectName.make("alice/datekit") }),309 new VerifierBlocked({}),310 ]),311 refusedWith([]),312 ]).toStrictEqual([{ refusal: "VerifierBlocked,UnknownProject" }, {}]);313 });314315 it.effect("is a no-op where no Worker's spans are installed", () =>316 annotateInvocation({ project: "alice/datekit" }).pipe(317 Effect.provide(Layer.empty)318 )319 );320});