Skip to content
Myr

binding.ts

This file

Path

packages/telemetry/src/spans/binding.ts

179 lines · 4.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–6why, one step back
1// Effect's spans onto a Worker's trace, through its `tracing`. Each span opens
2// with `startSpan`, which the runtime never makes active, and workerd has no3// way to make a span active once it is open: every span opened here is a4// child of the invocation's root span, a sibling of the others and of the5// runtime's own (fetch, RPC, D1, storage) opened while it runs. Effect keeps6// the nesting; the trace shows each span's name, timing, ids and failures.

Merge observability/typed-failures into mainoscabrielbefore adoption0d940fc

line 7why, one step back
7import { Array, Cause, Exit, Layer, Predicate, Tracer } from "effect";

Merge observability into mainoscabrielbefore adoption1985111

lines 8–33why, one step back
8
9import type { DefectKeeping } from "../defects.ts";10import type { Scrub } from "../logger.ts";11import { INVOCATION_KEYS, InvocationSpan, SPAN_KEYS } from "../spans.ts";12import type {13 InvocationIds,14 SpanValue,15 WorkerSpan,16 WorkerTracing,17} from "../spans.ts";1819const isSpanValue = (value: unknown): value is SpanValue =>20 Predicate.isString(value) ||21 Predicate.isNumber(value) ||22 Predicate.isBoolean(value);2324/** What a span keeps of what it carries. */25export interface Keeping {26 readonly scrub: Scrub;27 /**28 * All of a defect, scrubbed, or its name alone where its text may quote29 * what no trace may hold (a layer's repo, a held-back check's path).30 */31 readonly defects: DefectKeeping;32}33

Merge observability/typed-failures into mainoscabrielbefore adoption0d940fc

lines 34–37why, one step back
34// A typed failure is a refusal or a port's error, the product working: its
35// tag goes on the span as `failure`. workerd logs each recorded exception at36// error level, where Issues, smoke and the alerts count it, so only a defect37// is recorded as one, with its message and stack, scrubbed.

Merge observability into mainoscabrielbefore adoption1985111

lines 38–46why, one step back
38const recordFailures = <A, E>(
39 span: WorkerSpan,40 exit: Exit.Exit<A, E>,41 { defects, scrub }: Keeping42) => {43 if (Exit.isSuccess(exit)) {44 return;45 }46

Merge observability/typed-failures into mainoscabrielbefore adoption0d940fc

lines 47–52why, one step back
47 const failures = Array.dedupe(
48 exit.cause.reasons.flatMap((reason) => {49 if (!Cause.isFailReason(reason)) {50 return [];51 }52

Merge observability into mainoscabrielbefore adoption1985111

lines 53–54why, one step back
53 const failure = reason.error;
54

Merge observability/typed-failures into mainoscabrielbefore adoption0d940fc

lines 55–62why, one step back
55 return [
56 Predicate.hasProperty(failure, "_tag") &&57 Predicate.isString(failure._tag)58 ? failure._tag59 : "Failure",60 ];61 })62 );

Merge observability into mainoscabrielbefore adoption1985111

line 63why, one step back
63

Merge observability/typed-failures into mainoscabrielbefore adoption0d940fc

lines 64–68why, one step back
64 if (Array.isReadonlyArrayNonEmpty(failures)) {
65 span.setAttribute("failure", failures.join(","));66 }6768 for (const reason of exit.cause.reasons) {

Merge observability into mainoscabrielbefore adoption1985111

lines 69–179why, one step back
69 if (Cause.isDieReason(reason)) {
70 for (const error of Cause.prettyErrors(Cause.fromReasons([reason]))) {71 span.recordException(72 defects === "name"73 ? { name: error.name }74 : {75 message: scrub(error.message),76 name: error.name,77 stack: scrub(error.stack ?? ""),78 }79 );80 }81 }82 }83};8485const mirrored = (86 span: Tracer.NativeSpan,87 mirror: WorkerSpan | undefined,88 keeping: Keeping89): Tracer.Span => {90 const traced = mirror?.isTraced === true ? mirror : undefined;9192 return {93 _tag: span._tag,94 addLinks: (links) => {95 span.addLinks(links);96 },97 annotations: span.annotations,98 attribute: (key, value) => {99 span.attribute(key, value);100101 if (traced !== undefined && SPAN_KEYS.has(key) && isSpanValue(value)) {102 traced.setAttribute(key, value);103 }104 },105 get attributes() {106 return span.attributes;107 },108 end: (endTime, exit) => {109 span.end(endTime, exit);110111 if (traced !== undefined) {112 recordFailures(traced, exit, keeping);113 }114115 mirror?.end();116 },117 event: (name, startTime, attributes) => {118 span.event(name, startTime, attributes);119 },120 kind: span.kind,121 links: span.links,122 name: span.name,123 parent: span.parent,124 sampled: span.sampled,125 get spanId() {126 return span.spanId;127 },128 get status() {129 return span.status;130 },131 get traceId() {132 return span.traceId;133 },134 };135};136137/**138 * A `client` span (fetch, RPC, D1, storage) is the runtime's own to trace,139 * with what it carries, and SQL's run once per statement: none is opened twice.140 */141export const tracerOver = (142 tracing: WorkerTracing,143 keeping: Keeping144): Tracer.Tracer =>145 Tracer.make({146 span: (options) =>147 mirrored(148 new Tracer.NativeSpan(options),149 options.sampled && options.kind !== "client"150 ? tracing.startSpan(options.name)151 : undefined,152 keeping153 ),154 });155156const annotateRoot = (tracing: WorkerTracing) => (ids: InvocationIds) => {157 const root = tracing.getActiveSpan();158159 if (root?.isTraced !== true) {160 return;161 }162163 for (const key of INVOCATION_KEYS) {164 const value = ids[key];165166 if (value !== undefined) {167 root.setAttribute(key, value);168 }169 }170};171172export const SpansBinding = (173 tracing: WorkerTracing,174 keeping: Keeping175): Layer.Layer<never> =>176 Layer.mergeAll(177 Layer.succeed(Tracer.Tracer, tracerOver(tracing, keeping)),178 Layer.succeed(InvocationSpan, { annotate: annotateRoot(tracing) })179 );