telemetry.test.ts
This file
Path
apps/platform/test/telemetry.test.ts
379 lines · 12.1 KiB · TypeScript
Last changed by
Merge observability/visibility-logs into mainoscabrielbefore adoption2858640
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380import { describe, expect, it } from "@effect/vitest";import { RepoHost } from "@repo/artifacts/repo-host";import { CheckRunner } from "@repo/checks/check-runner";import { EvidenceStore } from "@repo/checks/evidence-store";import { Lander } from "@repo/project/lander";import { LandingCommand } from "@repo/project/landing";import { Projects } from "@repo/project/projects";import { LandedSha, RequestId } from "@repo/protocol/ids";import { VerifierBlocked } from "@repo/protocol/refusal";import { recordingConsole } from "@repo/telemetry/logger/memory";import { recordingTracing, ROOT } from "@repo/telemetry/spans/memory";import { Telemetry } from "@repo/telemetry/telemetry";import { untouchable } from "@repo/testkit/untouchable";import { Cause, Effect, Exit, Layer, Redacted, Schema } from "effect";import { HttpRouter } from "effect/http";
import { DoProjects } from "../src/adapters/do-projects.ts";import { PlatformEnv } from "../src/platform.ts";import { telemetryOf } from "../src/ports.ts";import { buildHandler } from "../src/router-build.ts";import { runWorkflow } from "../src/workflows/answer.ts";import { instance, invocation } from "../src/workflows/instance.ts";import { StepRunner, workflowSteps } from "../src/workflows/step.ts";import { fakeEnv } from "./fake-env.ts";import { alice, bob, namespaceOf, parseIso, project, world,} from "./project-do.fixtures.ts";
const telemetry = () => { const console = recordingConsole(); const recording = recordingTracing();
return { console, layer: Layer.merge( Telemetry({ secrets: [], tracing: recording.tracing }), console.layer ), recording, };};
const origin = "https://platform.test";
const requestId = RequestId.make("req-none0001");
const routes = HttpRouter.use((router) => Effect.gen(function* () { yield* router.add( "GET", "/dies", Effect.die(new Error("the store is gone")) ); yield* router.add("GET", "/refuses", Effect.fail(new VerifierBlocked({}))); }));
describe("a platform router", () => { it.effect( "reports a route's defect once, at Error, and never a route's typed failure", () => Effect.gen(function* () { const { console, layer } = telemetry(); const { dispose, handler } = buildHandler(routes, layer);
const statuses = yield* Effect.forEach(["dies", "refuses"], (path) => Effect.promise(() => handler(new Request(`${origin}/${path}`))).pipe( Effect.map(({ status }) => status) ) );
yield* Effect.promise(dispose);
expect(statuses).toStrictEqual([500, 500]); expect(console.errors()).toHaveLength(1); expect(console.errors()[0]).toHaveProperty( "cause", expect.stringMatching(/^Error: the store is gone\n\s+at /u) ); }) );});
const platformConfig = (env: Readonly<Record<string, string>> = {}) => Schema.decodeUnknownEffect(PlatformEnv)({ ...fakeEnv(), ...env }).pipe( Effect.orDie );
describe("the Worker's telemetry", () => { it.effect( "takes every secret the env holds out of each line it logs, each session token included", () => Effect.gen(function* () { const session = "session-token-0123456789abcdef0123456789";
const config = yield* platformConfig({ SESSION_TOKENS: JSON.stringify({ [session]: "alice" }), });
const secrets = [ config.COOKIE_KEY, config.MASTER_KEY, config.OPERATOR_TOKEN, config.PASSWORD_PEPPER, ].map((secret) => Redacted.value(secret));
const held = `held ${[...secrets, session].join(" ")}`; const console = recordingConsole();
const { dispose, handler } = buildHandler( HttpRouter.use((router) => router.add( "GET", "/dies", Effect.logWarning(held).pipe( Effect.andThen(Effect.die(new Error(held))) ) ) ), Layer.merge(telemetryOf(config), console.layer) );
yield* Effect.promise(() => handler(new Request(`${origin}/dies`))); yield* Effect.promise(dispose);
const logged = JSON.stringify(console.written());
expect(console.errors()).toHaveLength(1); expect( [...secrets, session].filter((secret) => logged.includes(secret)) ).toStrictEqual([]); expect(logged).toContain("held <redacted> <redacted>"); }) );
it.effect( "keeps a defect by its name and frames alone, a route's and a Project DO's, since its text may name a layer's repo", () => Effect.gen(function* () { const config = yield* platformConfig(); const repo = "alice--datekit--private"; const console = recordingConsole(); const layer = Layer.merge(telemetryOf(config), console.layer);
const { dispose, handler } = buildHandler( HttpRouter.use((router) => router.add( "GET", "/dies", Effect.die(new Error(`the layer repo ${repo} has no commit`)) ) ), layer );
yield* Effect.promise(() => handler(new Request(`${origin}/dies`))); yield* Effect.promise(dispose);
const { namespace } = yield* namespaceOf.pipe(Effect.provide(layer));
yield* Effect.gen(function* () { const made = yield* (yield* Projects).create(project);
yield* made.initProject(alice, {}); yield* Effect.exit( made.advanceAnswer( requestId, LandingCommand.Start({ main: LandedSha.make("a".repeat(40)) }) ) ); }).pipe(Effect.provide(DoProjects(namespace)));
const logged = JSON.stringify(console.written());
const withheld = /^Error: <withheld>\n\s+at /u;
expect(console.errors()).toMatchObject([ { message: "Error: <withheld>" }, { message: "Error: <withheld>", project }, ]); expect(console.errors()[0]).toHaveProperty( "cause", expect.stringMatching(withheld) ); expect(console.errors()[1]).toHaveProperty( "cause", expect.stringMatching(withheld) ); expect( [repo, requestId].filter((text) => logged.includes(text)) ).toStrictEqual([]); }).pipe(Effect.provide(world)) );
it.effect( "keeps a defect a warning carries by its name and frames alone too, since a caught cause is logged as well as reported", () => Effect.gen(function* () { const config = yield* platformConfig(); const repo = "alice--datekit--private"; const console = recordingConsole();
yield* Effect.logWarning( "a visibility effect did not settle", Cause.die(new Error(`the layer repo ${repo} lost a blob`)) ).pipe(Effect.provide(Layer.merge(telemetryOf(config), console.layer)));
expect(console.written()).toMatchObject([ { line: { level: "warn" }, method: "warn" }, ]); expect(console.written()[0]?.line).toHaveProperty( "cause", expect.stringMatching(/^Error: <withheld>\n\s+at /u) ); expect(JSON.stringify(console.written())).not.toContain(repo); }) );});
describe("a Project DO call", () => { it.effect( "reports its defect once, in the DO, by its project, and its caller reports it no more", () => Effect.gen(function* () { const durable = telemetry(); const caller = telemetry();
const { namespace } = yield* namespaceOf.pipe( Effect.provide(durable.layer) );
const refused = yield* Effect.gen(function* () { const projects = yield* Projects; const made = yield* projects.create(project);
yield* made.initProject(alice, {}); yield* Effect.exit( made .advanceAnswer( requestId, LandingCommand.Start({ main: LandedSha.make("a".repeat(40)) }) ) .pipe(Effect.withErrorReporting) );
return yield* Effect.flip( made.claim(bob, parseIso).pipe(Effect.withErrorReporting) ); }).pipe( Effect.provide(Layer.merge(DoProjects(namespace), caller.layer)) );
expect(refused._tag).toBe("UnknownAsk"); expect(caller.console.errors()).toStrictEqual([]); expect(durable.console.errors()).toHaveLength(1); expect(durable.console.errors()[0]).toMatchObject({ message: "Error: no answer request req-none0001", project, }); expect( durable.recording .spans() .flatMap(({ name }) => (name.startsWith("Project.") ? [name] : [])) ).toStrictEqual([ "Project.listAsks", "Project.initProject", "Project.advanceAnswer", "Project.claim", ]); }).pipe(Effect.provide(world)) );});
describe("a Workflow instance", () => { it.effect( "reports a Project DO's defect, met inside a step, no more: the DO reported it", () => Effect.gen(function* () { const durable = telemetry(); const caller = telemetry();
const { namespace } = yield* namespaceOf.pipe( Effect.provide(durable.layer) );
// An engine whose step rejects as the body did, as a step past its retries does. const engine = workflowSteps({ do: (_name, _config, body) => body() });
const exit = yield* Effect.gen(function* () { const made = yield* (yield* Projects).create(project);
yield* made.initProject(alice, {});
return yield* StepRunner.use(({ step }) => step( "advance", Schema.Null, made .advanceAnswer( requestId, LandingCommand.Start({ main: LandedSha.make("a".repeat(40)) }) ) .pipe(Effect.as(null)) ) ); }).pipe( invocation({ project, requestId }), instance("Answer.run"), Effect.provide( Layer.mergeAll(DoProjects(namespace), engine, caller.layer) ), Effect.exit );
expect(Exit.isFailure(exit)).toBeTruthy(); expect(caller.console.errors()).toStrictEqual([]); expect(durable.console.errors()).toMatchObject([ { message: "Error: no answer request req-none0001", project }, ]); }).pipe(Effect.provide(world)) );
it.effect( "reports its defect once, by its project and request, and still rejects", () => Effect.gen(function* () { const { console, layer, recording } = telemetry();
const ports = Layer.mergeAll( Layer.succeed( CheckRunner, untouchable<CheckRunner["Service"]>("CheckRunner") ), Layer.succeed( EvidenceStore, untouchable<EvidenceStore["Service"]>("EvidenceStore") ), Layer.succeed(Lander, untouchable<Lander["Service"]>("Lander")), Layer.succeed(Projects, untouchable<Projects["Service"]>("Projects")), Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")), layer );
const rejected = yield* Effect.flip( Effect.tryPromise(() => runWorkflow( ports, { project, requestId }, { do: (_name, _config, body) => body() } ) ) );
expect(rejected.cause).toHaveProperty("name", "TouchedError"); expect(console.errors()).toHaveLength(1); expect(console.errors()[0]).toMatchObject({ message: "TouchedError: a test touched Projects.get", project, requestId, }); expect( Object.fromEntries(recording.spans()[0]?.attributes ?? []) ).toStrictEqual({ project, requestId, }); expect(recording.spans().map(({ name }) => name)).toStrictEqual([ ROOT, "Answer.run", "Workflow.load", ]); }) );});