smoke.ts
This file
Path
infra/smoke.ts
770 lines · 21.7 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
1import { UnknownProject } from "@repo/protocol/refusal";2import {3 Config,4 Console,5 DateTime,6 Duration,7 Effect,8 Option,9 Result,10 Schedule,11 Schema,12} from "effect";13import type { Redacted } from "effect";14import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";1516import { ANALYTICS_READ, errorsQuery, SQL_API, workersOf } from "./logs.ts";17import {18 flagValue,19 platformOrigin,20 recordedSubdomain,21 stageOf,22 subdomainFile,23 webOrigin,24} from "./stages.ts";25import type { Stage } from "./stages.ts";2627export const platformProbes = [28 "health",29 "oauth-metadata",30 "mcp-needs-credential",31 "anonymous-unknown-project",32 "missing-repo-404",33 "platform-root",34] as const;3536export const webProbes = [37 "web-front-page",38 "web-llms-txt",39 "web-project-llms-txt",40 "web-ask-md",41 "web-agent-skills",42] as const;4344export const AGENT_BUDGET_MS = 500;4546const SEEDED = { ask: "format-ordinal", project: "oscabriel/datekit" } as const;4748export const seededProbes: ReadonlySet<Probe> = new Set([49 "web-project-llms-txt",50 "web-ask-md",51]);5253export const agentProbes = [54 { contentType: "text/markdown", path: "/llms.txt", probe: "web-llms-txt" },55 {56 contentType: "text/markdown",57 path: `/${SEEDED.project}/llms.txt`,58 probe: "web-project-llms-txt",59 },60 {61 contentType: "text/markdown",62 path: `/${SEEDED.project}/asks/${SEEDED.ask}.md`,63 probe: "web-ask-md",64 },65 {66 contentType: "application/json",67 path: "/.well-known/agent-skills/index.json",68 probe: "web-agent-skills",69 },70] as const satisfies readonly {71 readonly contentType: string;72 readonly path: string;73 readonly probe: (typeof webProbes)[number];74}[];7576export const probes = [...platformProbes, ...webProbes] as const;7778// Run after every other probe, and only when smoke is told when the deploy began.79export const logProbes = ["worker-logs"] as const;8081export const Probe = Schema.Literals([...probes, ...logProbes]);8283export type Probe = typeof Probe.Type;8485const MISSING = "oscabriel/no-such-project";8687const PATIENCE = Duration.seconds(30);8889// A fresh deploy answers with server errors or defects for its first seconds.90const SETTLING = Duration.seconds(30);9192const ASK_AGAIN = Duration.seconds(1);9394// Workers Logs reach the SQL API some seconds after the invocation, so the95// logs are read this long after the probes, whose own errors then count.96const INGESTION = Duration.seconds(30);9798export class SmokeFailed extends Schema.TaggedError<SmokeFailed>()(99 "SmokeFailed",100 {101 failures: Schema.Array(102 Schema.Struct({ probe: Probe, reason: Schema.String })103 ),104 origin: Schema.String,105 }106) {107 override get message() {108 const failed = this.failures.map(({ probe }) => probe).join(", ");109110 return `${failed} failed at ${this.origin}`;111 }112}113114export interface SmokeReport {115 readonly origin: string;116 readonly stage: string;117 readonly probes: readonly {118 readonly probe: Probe;119 readonly elapsedMs: number;120 readonly budgetMs?: number;121 }[];122 readonly warnings: readonly string[];123}124125class Missed extends Schema.TaggedError<Missed>()("Missed", {126 reason: Schema.String,127 transient: Schema.optionalKey(Schema.Boolean),128}) {}129130interface Answer {131 readonly contentType: string;132 readonly status: number;133 readonly text: string;134}135136const send = (137 label: string,138 request: HttpClientRequest.HttpClientRequest139): Effect.Effect<Answer, Missed, HttpClient.HttpClient> =>140 Effect.gen(function* () {141 const client = yield* HttpClient.HttpClient;142 const response = yield* client.execute(request);143 const text = yield* response.text;144145 return {146 contentType: response.headers["content-type"] ?? "",147 status: response.status,148 text,149 };150 }).pipe(151 Effect.catchTag("HttpClientError", ({ reason }) =>152 Effect.fail(153 new Missed({ reason: `${label} got no answer (${reason._tag})` })154 )155 ),156 Effect.timeoutOrElse({157 duration: PATIENCE,158 orElse: () =>159 Effect.fail(160 new Missed({161 reason: `${label} got no answer within ${Duration.format(PATIENCE)}`,162 })163 ),164 })165 );166167const serverError = (status: number) => status >= 500;168169// A fresh workers.dev deploy, or one adding a route, answers 404 for its first seconds.170const notServingYet = (status: number) => status >= 500 || status === 404;171172const statusIs =173 (label: string, expected: number, transient = serverError) =>174 (answer: Answer) =>175 answer.status === expected176 ? Effect.succeed(answer)177 : Effect.fail(178 new Missed({179 reason: `${label} answered ${answer.status}, not ${expected}`,180 transient: transient(answer.status),181 })182 );183184const missing =185 (reason: string) =>186 <A, E, R>(self: Effect.Effect<A, E, R>) =>187 Effect.mapError(self, () => new Missed({ reason }));188189const decodeHealth = Schema.decodeUnknownEffect(190 Schema.fromJsonString(191 Schema.Struct({ ok: Schema.Literal(true), stage: Schema.NonEmptyString })192 )193);194195const health = (origin: string, expected: Option.Option<Stage>) =>196 Effect.gen(function* () {197 const label = "GET /health";198199 const { text } = yield* send(200 label,201 HttpClientRequest.get(`${origin}/health`)202 ).pipe(Effect.flatMap(statusIs(label, 200)));203204 const { stage } = yield* decodeHealth(text).pipe(205 missing(`${label} answered 200 without {"ok":true,"stage":…}`)206 );207208 return yield* Option.match(expected, {209 onNone: () => Effect.succeed(stage),210 onSome: (wanted) =>211 stage === wanted212 ? Effect.succeed(stage)213 : Effect.fail(214 new Missed({215 reason: `${label} named stage ${stage}, not ${wanted}`,216 })217 ),218 });219 });220221const decodeResourceMetadata = Schema.decodeUnknownEffect(222 Schema.fromJsonString(Schema.Struct({ resource: Schema.NonEmptyString }))223);224225const oauthMetadata = (origin: string) =>226 Effect.gen(function* () {227 const route = "/.well-known/oauth-protected-resource";228 const label = `GET ${route}`;229230 const { text } = yield* send(231 label,232 HttpClientRequest.get(`${origin}${route}`)233 ).pipe(Effect.flatMap(statusIs(label, 200)));234235 yield* decodeResourceMetadata(text).pipe(236 missing(`${label} answered 200 without a "resource"`)237 );238 });239240const mcpNeedsCredential = (origin: string) => {241 const label = "POST /mcp without a credential";242243 return send(244 label,245 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${origin}/mcp`), {246 id: 1,247 jsonrpc: "2.0",248 method: "tools/list",249 params: {},250 })251 ).pipe(Effect.flatMap(statusIs(label, 401)), Effect.asVoid);252};253254const RpcRequest = Schema.TaggedStruct("Request", {255 headers: Schema.Array(Schema.Tuple([Schema.String, Schema.String])),256 id: Schema.String,257 payload: Schema.Struct({ project: Schema.String }),258 tag: Schema.Literal("listAsks"),259});260261const decodeRefused = Schema.decodeUnknownEffect(262 Schema.fromJsonString(263 Schema.Tuple([264 Schema.TaggedStruct("Exit", {265 exit: Schema.TaggedStruct("Failure", {266 cause: Schema.Tuple([267 Schema.TaggedStruct("Fail", { error: UnknownProject }),268 ]),269 }),270 }),271 ])272 )273);274275const decodeDefect = Schema.decodeUnknownOption(276 Schema.fromJsonString(277 Schema.Tuple([Schema.TaggedStruct("Defect", { defect: Schema.Unknown })])278 )279);280281const listAsks = (origin: string, project: string, label: string) =>282 send(283 label,284 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${origin}/rpc`), [285 RpcRequest.make({286 headers: [],287 id: "1",288 payload: { project },289 tag: "listAsks",290 }),291 ])292 );293294const anonymousUnknownProject = (origin: string) =>295 Effect.gen(function* () {296 const label = "POST /rpc listAsks";297298 const { text } = yield* listAsks(origin, MISSING, label).pipe(299 Effect.flatMap(statusIs(label, 200))300 );301302 const [reply] = yield* decodeRefused(text).pipe(303 Effect.mapError(() =>304 Option.isSome(decodeDefect(text))305 ? new Missed({306 reason: `${label} for ${MISSING} died in the platform (a defect)`,307 transient: true,308 })309 : new Missed({310 reason: `${label} for ${MISSING} answered 200 without an UnknownProject refusal`,311 })312 )313 );314315 const [cause] = reply.exit.cause;316317 return yield* cause.error.project === MISSING318 ? Effect.void319 : Effect.fail(320 new Missed({321 reason: `${label} for ${MISSING} refused another project, ${cause.error.project}`,322 })323 );324 });325326// False only on an UnknownProject refusal; any other answer leaves the probes to report it.327const holdsSeeded = (origin: string) =>328 listAsks(origin, SEEDED.project, `POST /rpc listAsks ${SEEDED.project}`).pipe(329 Effect.flatMap(({ text }) => Effect.option(decodeRefused(text))),330 Effect.map(331 Option.match({332 onNone: () => true,333 onSome: ([{ exit }]) => exit.cause[0].error.project !== SEEDED.project,334 })335 ),336 Effect.orElseSucceed(() => true)337 );338339const missingRepo = (origin: string) => {340 const route = `/${MISSING}.git/info/refs`;341 const label = `GET ${route}`;342343 return send(344 label,345 HttpClientRequest.get(`${origin}${route}?service=git-upload-pack`)346 ).pipe(Effect.flatMap(statusIs(label, 404)), Effect.asVoid);347};348349const platformRoot = (origin: string) => {350 const label = "GET /";351352 return send(label, HttpClientRequest.get(`${origin}/`)).pipe(353 Effect.flatMap(statusIs(label, 200, notServingYet)),354 Effect.flatMap(({ text }) =>355 text.includes("/mcp") && text.includes("install.sh")356 ? Effect.void357 : Effect.fail(358 new Missed({359 reason: `${label} answered 200 without naming /mcp and install.sh`,360 })361 )362 )363 );364};365366const typeIs =367 (label: string, wanted: string, said: string) => (answer: Answer) =>368 answer.contentType.split(";")[0]?.trim() === wanted369 ? Effect.succeed(answer)370 : Effect.fail(371 new Missed({372 reason: `${label} answered ${answer.contentType || "no content type"}, not ${said}`,373 })374 );375376const webFrontPage = (web: string) => {377 const label = "GET / on the web";378379 return send(label, HttpClientRequest.get(`${web}/`)).pipe(380 Effect.flatMap(statusIs(label, 200, notServingYet)),381 Effect.flatMap(typeIs(label, "text/html", "HTML")),382 Effect.asVoid383 );384};385386const agentSurface = (387 web: string,388 { contentType, path }: (typeof agentProbes)[number]389) => {390 const label = `GET ${path} on the web`;391392 return send(label, HttpClientRequest.get(`${web}${path}`)).pipe(393 Effect.flatMap(statusIs(label, 200, notServingYet)),394 Effect.flatMap(typeIs(label, contentType, contentType))395 );396};397398// The web answers 503 when the platform does not, so a 200 proves the service binding.399const webLlmsTxt = (web: string, probe: (typeof agentProbes)[number]) => {400 const label = "GET /llms.txt on the web";401402 return agentSurface(web, probe).pipe(403 Effect.flatMap(({ text }) =>404 text.startsWith("# ")405 ? Effect.void406 : Effect.fail(407 new Missed({ reason: `${label} answered 200 without a title` })408 )409 )410 );411};412413// What reading the stage's logs needs: the instant the deploy's first upload414// began, the Workers to read, and infra's credentials.415export interface LogsCheck {416 readonly since: DateTime.Utc;417 readonly workers: readonly string[];418 readonly accountId: string;419 readonly token: Redacted.Redacted;420 // The SQL API's endpoint; a test points it at a fake.421 readonly api?: string;422 readonly ingestion?: Duration.Input;423}424425const decodeErrors = Schema.decodeUnknownEffect(426 Schema.fromJsonString(427 Schema.Struct({428 data: Schema.Array(429 Schema.Struct({ errors: Schema.Int, scriptName: Schema.String })430 ),431 })432 )433);434435// How the API refuses the credentials, as seen live: 400 (error 9106) for a436// token it can't authenticate, and 422 naming the account tag for an account437// the token can't read; 401 and 403 are its usual answers to a missing438// permission.439const refusedCredentials = (status: number, text: string) =>440 status === 400 ||441 status === 401 ||442 status === 403 ||443 (status === 422 && text.includes("account or zone tag"));444445// The API's own first line, which names what it could not run.446const unread = (label: string, status: number, text: string) => {447 const said = text.split("\n")[0]?.trim().slice(0, 200) ?? "";448449 if (refusedCredentials(status, text)) {450 return `${label} answered ${status}: CLOUDFLARE_API_TOKEN needs ${ANALYTICS_READ} on the account CLOUDFLARE_ACCOUNT_ID names`;451 }452453 return said === ""454 ? `${label} answered ${status}`455 : `${label} answered ${status}: ${said}`;456};457458const workerLogs = (check: LogsCheck) =>459 Effect.gen(function* () {460 const label = "POST /analytics/sql for the stage's Workers Logs";461 const since = DateTime.formatIso(check.since);462463 const { status, text } = yield* send(464 label,465 HttpClientRequest.bodyJsonUnsafe(466 HttpClientRequest.post(check.api ?? SQL_API),467 {468 query: errorsQuery(check.workers),469 scope: { accountTag: check.accountId },470 time_range: { start: since },471 }472 ).pipe(HttpClientRequest.bearerToken(check.token))473 );474475 if (status !== 200) {476 return yield* new Missed({477 reason: unread(label, status, text),478 transient: serverError(status),479 });480 }481482 const { data } = yield* decodeErrors(text).pipe(483 missing(`${label} answered 200 without {"data":[{scriptName, errors}]}`)484 );485486 const logged = check.workers.flatMap((worker) => {487 const errors = data488 .filter(({ scriptName }) => scriptName === worker)489 .reduce((sum, row) => sum + row.errors, 0);490491 return errors > 0 ? [`${worker} ${errors}`] : [];492 });493494 return yield* logged.length === 0495 ? Effect.void496 : Effect.fail(497 new Missed({498 reason: `exceptions or error-level lines since ${since}: ${logged.join(", ")}`,499 })500 );501 });502503const timed = <A>(504 probe: Probe,505 run: Effect.Effect<A, Missed, HttpClient.HttpClient>,506 settling: Duration.Input507) =>508 Effect.timed(509 Effect.result(510 Effect.retry(run, {511 schedule: Schedule.spaced(ASK_AGAIN).pipe(512 Schedule.upTo({ duration: settling })513 ),514 while: ({ transient }) => transient === true,515 })516 )517 ).pipe(518 Effect.map(([elapsed, outcome]) => ({519 elapsedMs: Math.round(Duration.toMillis(elapsed)),520 outcome,521 probe,522 }))523 );524525export const smoke = (526 origin: string,527 options: {528 readonly stage?: Stage;529 readonly settling?: Duration.Input;530 readonly web?: string;531 readonly logs?: LogsCheck;532 } = {}533): Effect.Effect<SmokeReport, SmokeFailed, HttpClient.HttpClient> =>534 Effect.gen(function* () {535 const settling = options.settling ?? SETTLING;536537 const first = yield* timed(538 "health",539 health(origin, Option.fromUndefinedOr(options.stage)),540 settling541 );542543 const { web } = options;544545 const seeded = web === undefined ? true : yield* holdsSeeded(origin);546547 const skipped = seeded548 ? []549 : agentProbes.filter(({ probe }) => seededProbes.has(probe));550551 const rest = yield* Effect.forEach(552 [553 ["oauth-metadata", oauthMetadata(origin)],554 ["mcp-needs-credential", mcpNeedsCredential(origin)],555 ["anonymous-unknown-project", anonymousUnknownProject(origin)],556 ["missing-repo-404", missingRepo(origin)],557 ["platform-root", platformRoot(origin)],558 ...(web === undefined559 ? []560 : ([561 ["web-front-page", webFrontPage(web)],562 ...agentProbes.flatMap((agent) =>563 skipped.includes(agent)564 ? []565 : [566 [567 agent.probe,568 agent.probe === "web-llms-txt"569 ? webLlmsTxt(web, agent)570 : Effect.asVoid(agentSurface(web, agent)),571 ] as const,572 ]573 ),574 ] as const)),575 ] as const,576 ([probe, run]) => timed(probe, run, settling)577 );578579 const { logs } = options;580581 const read =582 logs === undefined583 ? []584 : [585 yield* Effect.sleep(logs.ingestion ?? INGESTION).pipe(586 Effect.andThen(timed("worker-logs", workerLogs(logs), settling))587 ),588 ];589590 const runs: readonly {591 readonly probe: Probe;592 readonly elapsedMs: number;593 readonly outcome: Result.Result<unknown, Missed>;594 }[] = [first, ...rest, ...read];595596 const failures = runs.flatMap(({ outcome, probe }) =>597 Result.isFailure(outcome)598 ? [{ probe, reason: outcome.failure.reason }]599 : []600 );601602 // `first`'s own check, too, so its stage below is known to be there.603 if (Result.isFailure(first.outcome) || failures.length > 0) {604 return yield* new SmokeFailed({ failures, origin });605 }606607 const budgeted = new Set<Probe>(agentProbes.map(({ probe }) => probe));608609 const timings = runs.map(({ elapsedMs, probe }) =>610 budgeted.has(probe)611 ? { budgetMs: AGENT_BUDGET_MS, elapsedMs, probe }612 : { elapsedMs, probe }613 );614615 return {616 origin,617 probes: timings,618 stage: first.outcome.success,619 warnings: [620 ...skipped.map(621 ({ probe }) =>622 `${probe} was skipped: ${SEEDED.project} is not on this stage (bun run seed puts it there)`623 ),624 ...timings.flatMap(({ budgetMs, elapsedMs, probe }) =>625 budgetMs !== undefined && elapsedMs > budgetMs626 ? [627 `${probe} answered in ${elapsedMs} ms, over its ${budgetMs} ms budget`,628 ]629 : []630 ),631 ],632 };633 });634635export class NoOrigin extends Schema.TaggedError<NoOrigin>()("NoOrigin", {636 file: Schema.String,637 stage: Schema.String,638}) {639 override get message() {640 return `no --url, and ${this.file} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${this.stage} first`;641 }642}643644export class BadSince extends Schema.TaggedError<BadSince>()("BadSince", {645 given: Schema.String,646}) {647 override get message() {648 return `--since ${this.given} is not an ISO 8601 instant, as 2026-10-13T12:00:00.000Z`;649 }650}651652export class NoLogCredentials extends Schema.TaggedError<NoLogCredentials>()(653 "NoLogCredentials",654 {}655) {656 override readonly message =657 "--since reads the stage's Workers Logs with infra's credentials, and CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN is not set: run smoke as the deploy does, through bunx varlock run --path infra/ --";658}659660const Credentials = Config.all({661 accountId: Config.String("CLOUDFLARE_ACCOUNT_ID"),662 token: Config.Redacted("CLOUDFLARE_API_TOKEN"),663});664665const decodeSince = Schema.decodeUnknownOption(Schema.DateTimeUtcFromString);666667const logsOf = (argv: readonly string[], stage: Stage) =>668 Option.match(flagValue(argv, "--since"), {669 onNone: () => Effect.succeedNone,670 onSome: (given) =>671 Effect.gen(function* () {672 const since = yield* Effect.fromOption(decodeSince(given)).pipe(673 Effect.mapError(() => new BadSince({ given }))674 );675676 const { accountId, token } = yield* Credentials.pipe(677 Effect.mapError(() => new NoLogCredentials())678 );679680 return Option.some({681 accountId,682 since,683 token,684 workers: workersOf(stage),685 } satisfies LogsCheck);686 }),687 });688689interface Origins {690 readonly platform: string;691 readonly web: Option.Option<string>;692}693694const trimmed = (origin: string) => origin.replace(/\/+$/u, "");695696const originsOf = (argv: readonly string[], stage: Stage) =>697 Effect.gen(function* () {698 const given = flagValue(argv, "--url");699 const web = Option.map(flagValue(argv, "--web-url"), trimmed);700701 if (Option.isSome(given)) {702 return { platform: trimmed(given.value), web } satisfies Origins;703 }704705 const subdomain = yield* recordedSubdomain.pipe(706 Effect.flatMap(Effect.fromOption),707 Effect.mapError(() => new NoOrigin({ file: subdomainFile, stage }))708 );709710 return {711 platform: platformOrigin(stage, subdomain),712 web: Option.orElse(web, () => Option.some(webOrigin(stage, subdomain))),713 } satisfies Origins;714 });715716export const main = (argv: readonly string[]) =>717 Effect.gen(function* () {718 const stage = yield* stageOf(argv);719 const origins = yield* originsOf(argv, stage);720 const logs = yield* logsOf(argv, stage);721722 yield* Console.log(723 `smoke ${stage}: ${origins.platform}${Option.match(origins.web, {724 onNone: () => "",725 onSome: (web) => ` and ${web}`,726 })}${Option.match(logs, {727 onNone: () => "",728 onSome: ({ since }) =>729 `, then its Workers' logs since ${DateTime.formatIso(since)}`,730 })}`731 );732733 const report = yield* smoke(origins.platform, {734 stage,735 ...Option.match(origins.web, {736 onNone: () => ({}),737 onSome: (web) => ({ web }),738 }),739 ...Option.match(logs, {740 onNone: () => ({}),741 onSome: (check) => ({ logs: check }),742 }),743 }).pipe(744 Effect.tapError(({ failures }) =>745 Effect.forEach(746 failures,747 ({ probe, reason }) =>748 Console.error(`smoke ${stage}: ${probe} failed: ${reason}`),749 { discard: true }750 )751 )752 );753754 yield* Effect.forEach(755 report.probes,756 ({ budgetMs, elapsedMs, probe }) =>757 Console.log(758 `smoke ${stage}: ${probe} passed in ${elapsedMs} ms${759 budgetMs === undefined ? "" : ` (budget ${budgetMs} ms)`760 }`761 ),762 { discard: true }763 );764765 yield* Effect.forEach(766 report.warnings,767 (line) => Console.warn(`smoke ${stage}: warning: ${line}`),768 { discard: true }769 );770 }).pipe(Effect.provide(FetchHttpClient.layer));