Skip to content
Myr

defects.ts

This file

Path

packages/telemetry/src/defects.ts

148 lines · 4.2 KiB · TypeScript

Last changed by

Merge observability into mainoscabrielbefore adoption1985111

History of this file

Take it

Merge observability into mainoscabrielbefore adoption1985111

lines 1–148why, one step back
1// Crash reporting. A defect is the platform's own fault, so it is logged at
2// Error, with its cause and stack, where Issues groups it. A typed failure is3// never reported: a refusal is the product working (AGENTS.md principle 3),4// and a port's error is handled where it is typed. Where a defect's text may5// quote what no log may hold, it is kept by its name and frames alone.6import {7 Array,8 Cause,9 Context,10 DateTime,11 Effect,12 ErrorReporter,13 Logger,14 Predicate,15} from "effect";1617const NANOS_PER_MILLI = 1_000_000n;1819class ReportedElsewhere extends Context.Service<ReportedElsewhere, true>()(20 "telemetry/ReportedElsewhere"21) {}2223/**24 * What a report keeps of a defect: all of it, scrubbed, or its name and the25 * frames of its stack alone, where its text may quote what no log may hold26 * (a layer's repo, a held-back check's path).27 */28export type DefectKeeping = "whole" | "name";2930const WITHHELD = "<withheld>";3132const FRAME = /^\s+at /u;3334const withheld = (reason: Cause.Die): Cause.Die => {35 const [error] = Cause.prettyErrors(Cause.fromReasons([reason]));36 const name = error?.name ?? "Error";37 const kept = new Error(WITHHELD);3839 kept.name = name;40 // The frames Effect adds for its spans included; the message, and any41 // cause the defect carries, left out.42 kept.stack = [43 `${name}: ${WITHHELD}`,44 ...(error?.stack ?? "").split("\n").filter((line) => FRAME.test(line)),45 ].join("\n");4647 return Cause.makeDieReason(kept);48};4950/** `cause` with each defect kept by its name and stack frames alone. */51export const unquoted = <E>(cause: Cause.Cause<E>): Cause.Cause<E> =>52 Cause.fromReasons(53 cause.reasons.map((reason) =>54 Cause.isDieReason(reason) ? withheld(reason) : reason55 )56 );5758/**59 * Reports each defect once, through the reporting fiber's own loggers and60 * annotations, however many boundaries it crosses.61 */62export const defectReporter = (63 keeping: DefectKeeping = "whole"64): ErrorReporter.ErrorReporter => {65 const seen = new WeakSet<object>();6667 const unreported = <E>(reason: Cause.Reason<E>): readonly Cause.Die[] => {68 if (69 !Cause.isDieReason(reason) ||70 ErrorReporter.isIgnored(reason.defect) ||71 Context.getOrUndefined(72 Cause.reasonAnnotations(reason),73 ReportedElsewhere74 ) === true75 ) {76 return [];77 }7879 if (Predicate.isObject(reason.defect)) {80 if (seen.has(reason.defect)) {81 return [];82 }8384 seen.add(reason.defect);85 }8687 return [reason];88 };8990 return {91 [ErrorReporter.TypeId]: ErrorReporter.TypeId,92 report: ({ cause, fiber, timestamp }) => {93 const defects = cause.reasons.flatMap(unreported);9495 if (!Array.isReadonlyArrayNonEmpty(defects)) {96 return;97 }9899 const whole = Cause.fromReasons(defects);100 const reported = keeping === "name" ? unquoted(whole) : whole;101 const [first] = Cause.prettyErrors(reported);102103 const date = DateTime.toDateUtc(104 DateTime.makeUnsafe(Number(timestamp / NANOS_PER_MILLI))105 );106107 for (const logger of fiber.getRef(Logger.CurrentLoggers)) {108 logger.log({109 cause: reported,110 date,111 fiber,112 logLevel: "Error",113 message: [114 first === undefined115 ? "a defect"116 : `${first.name}: ${first.message}`,117 ],118 });119 }120 },121 };122};123124/**125 * Marks the defects of a cause another side reported already, with the stack126 * only it held: one that comes back over a wire (a Durable Object's reply) is127 * reported there, never again here. The mark rides on the cause, so the128 * defect itself stays as it came.129 */130export const reportedElsewhere = <E>(cause: Cause.Cause<E>): Cause.Cause<E> =>131 Cause.annotate(cause, Context.make(ReportedElsewhere, true));132133/**134 * A reporting boundary: reports the defects `effect` dies with, then marks135 * them, so a boundary further out lets them pass. Its place is where the136 * invocation's ids annotate the logs, so the report carries them.137 */138export const reportDefects = <A, E, R>(139 effect: Effect.Effect<A, E, R>140): Effect.Effect<A, E, R> =>141 effect.pipe(142 Effect.catchCauseIf(Cause.hasDies, (cause) =>143 Effect.andThen(144 ErrorReporter.report(cause),145 Effect.failCause(reportedElsewhere(cause))146 )147 )148 );