Skip to content
Myr

smoke-loop.test.ts

This file

Path

packages/config/test/smoke-loop.test.ts

512 lines · 15.1 KiB · TypeScript

Last changed by

Merge infra/drop-demo into mainoscabrielbefore adoptionc49b6bf

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4  Effect,5  FileSystem,6  Layer,7  Path,8  Redacted,9  Ref,10  Result,11  Sink,12  Stream,13} from "effect";14import { FetchHttpClient } from "effect/http";15import { ChildProcess, ChildProcessSpawner } from "effect/process";1617import { LedgerFile, readLedger } from "../../../infra/created.ts";18import { servedWorld } from "../../../scripts/lib/seed.ts";19import {20  PublicStageRefused,21  smokeLoop,22} from "../../../scripts/lib/smoke/loop.ts";23import { DraftNeedsLoop, main } from "../../../scripts/smoke.ts";24import { Brand } from "../../brand/src/index.ts";25import { Handle } from "../../protocol/src/ids.ts";2627const decider = Handle.make("ines-v");2829const answerer = Handle.make("bram");3031const tokens = {32  answerer: Redacted.make("bram-smoke-loop-world-token-0123456789abcdef"),33  decider: Redacted.make("ines-v-smoke-loop-world-token-0123456789abcd"),34};3536const credited = (handle: string) =>37  `${handle} <${handle}@users.${Brand.domain}>`;3839const textOf = <E>(bytes: Stream.Stream<Uint8Array, E>) =>40  bytes.pipe(Stream.decodeText(), Stream.mkString);4142const anonymousTip = (remote: string, ref: string) =>43  Effect.scoped(44    Effect.gen(function* () {45      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;4647      const child = yield* spawner.spawn(48        ChildProcess.make("git", ["ls-remote", remote, ref], {49          env: {50            GIT_CONFIG_GLOBAL: "/dev/null",51            GIT_CONFIG_NOSYSTEM: "1",52            GIT_TERMINAL_PROMPT: "0",53          },54          extendEnv: true,55        })56      );5758      const [listed] = yield* Effect.all(59        [textOf(child.stdout), child.exitCode],60        { concurrency: "unbounded" }61      );6263      return listed.split("\t")[0] ?? "";64    })65  );6667describe("smokeLoop, against the Node world", () => {68  it.live(69    "opens an ask red first, hears OutOfScope from git, lands the fix with its author, committer and trailers, finds the verdict note, and writes its throwaways to the ledger",70    () =>71      Effect.gen(function* () {72        const fs = yield* FileSystem.FileSystem;73        const path = yield* Path.Path;74        const dir = yield* fs.makeTempDirectoryScoped({ prefix: "smoke-806-" });75        const ledger = path.join(dir, "created.jsonl");7677        const { main: tip, report } = yield* Effect.scoped(78          Effect.gen(function* () {79            const origin = yield* servedWorld(80              new Map([81                [decider, tokens.decider],82                [answerer, tokens.answerer],83              ])84            );8586            const ran = yield* smokeLoop({87              answerer: tokens.answerer,88              decider: tokens.decider,89              origin,90              run: "r1",91              stage: "node",92            });9394            return {95              main: yield* anonymousTip(96                `${origin}/${ran.project}.git`,97                "refs/heads/main"98              ),99              report: ran,100            };101          })102        ).pipe(Effect.provideService(LedgerFile, ledger));103104        expect({105          author: report.author,106          committer: report.committer,107          landed: report.landed,108          noteFound: report.noteFound,109          project: report.project,110          refusedWith: report.refusedWith,111          steps: report.timings.map(({ step }) => step),112          timed: report.timings.every(({ ms }) => ms >= 0),113          trailers: report.trailers.filter((trailer) =>114            /^(?:Asked-by|Signed-off-by):/u.test(trailer)115          ),116        }).toStrictEqual({117          author: "bram",118          committer: Brand.name,119          landed: tip,120          noteFound: true,121          project: "ines-v/smoke-r1",122          refusedWith: ["OutOfScope"],123          steps: [124            "people",125            "init",126            "open-ask",127            "claim",128            "out-of-scope",129            "answer",130            "landing",131            "verdict-note",132          ],133          timed: true,134          trailers: [135            `Asked-by: ${credited("ines-v")}`,136            `Signed-off-by: ${credited("bram")}`,137          ],138        });139140        expect(141          (yield* readLedger.pipe(142            Effect.provideService(LedgerFile, ledger)143          )).map(({ by, kind, name, stage }) => ({ by, kind, name, stage }))144        ).toStrictEqual([145          {146            by: "smoke",147            kind: "project",148            name: "ines-v__smoke-r1",149            stage: "node",150          },151          {152            by: "smoke",153            kind: "repo",154            name: "ines-v__smoke-r1",155            stage: "node",156          },157          {158            by: "smoke",159            kind: "repo",160            name: "ines-v__smoke-r1--parse-year--bram",161            stage: "node",162          },163        ]);164      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),165    240_000166  );167});168169/** Any command fails, so a run that reached one could not pass by accident. */170const refusing = Effect.gen(function* () {171  const asked = yield* Ref.make<readonly string[]>([]);172173  const spawner = ChildProcessSpawner.make((command) =>174    Effect.gen(function* () {175      yield* Ref.update(asked, (all) => [176        ...all,177        ChildProcess.isStandardCommand(command) ? command.command : "a pipe",178      ]);179180      return ChildProcessSpawner.makeHandle({181        all: Stream.empty,182        exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),183        getInputFd: () => Sink.drain,184        getOutputFd: () => Stream.empty,185        isRunning: Effect.succeed(false),186        kill: () => Effect.void,187        pid: ChildProcessSpawner.ProcessId(1),188        stderr: Stream.empty,189        stdin: Sink.drain,190        stdout: Stream.empty,191        unref: Effect.succeed(Effect.void),192      });193    })194  );195196  return {197    asked: Ref.get(asked),198    layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),199  };200});201202/** `init` makes the project and then fails, as a push that answered 500 after making it did. */203const scripted = (listed: readonly string[]) =>204  Effect.gen(function* () {205    const asked = yield* Ref.make<readonly string[]>([]);206207    const replies = new Map([208      [209        "status",210        {211          code: 0,212          stdout: JSON.stringify({213            command: "status",214            data: { handle: decider },215            ok: true,216            v: 1,217          }),218        },219      ],220      [221        "projects",222        {223          code: 0,224          stdout: JSON.stringify({225            command: "projects",226            data: {227              projects: listed.map((project) => ({228                openAsks: 0,229                posture: "open",230                project,231              })),232            },233            ok: true,234            v: 1,235          }),236        },237      ],238      ["init", { code: 1, stdout: "" }],239    ]);240241    const spawner = ChildProcessSpawner.make((command) =>242      Effect.gen(function* () {243        const [program, args] = ChildProcess.isStandardCommand(command)244          ? [command.command, command.args]245          : ["a pipe", []];246247        const said =248          program === "bun" ? (args[1] ?? "") : `${program} ${args[0] ?? ""}`;249250        yield* Ref.update(asked, (all) => [...all, said]);251252        const reply = replies.get(said) ?? { code: 0, stdout: "" };253254        return ChildProcessSpawner.makeHandle({255          all: Stream.empty,256          exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(reply.code)),257          getInputFd: () => Sink.drain,258          getOutputFd: () => Stream.empty,259          isRunning: Effect.succeed(false),260          kill: () => Effect.void,261          pid: ChildProcessSpawner.ProcessId(1),262          stderr: Stream.empty,263          stdin: Sink.drain,264          stdout: Stream.make(new TextEncoder().encode(reply.stdout)),265          unref: Effect.succeed(Effect.void),266        });267      })268    );269270    return {271      asked: Ref.get(asked),272      layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),273    };274  });275276const loopOnScripted = (listed: readonly string[]) =>277  Effect.gen(function* () {278    const fs = yield* FileSystem.FileSystem;279    const path = yield* Path.Path;280    const dir = yield* fs.makeTempDirectoryScoped({ prefix: "smoke-ledger-" });281    const ledger = path.join(dir, "created.jsonl");282    const platform = yield* scripted(listed);283284    const failure = yield* smokeLoop({285      answerer: tokens.answerer,286      decider: tokens.decider,287      origin: "https://platform-dev.example.workers.dev",288      run: "r1",289      stage: "dev-example",290    }).pipe(291      Effect.catchTag("PublicStageRefused", Effect.die),292      Effect.flip,293      Effect.provide(platform.layer),294      Effect.provideService(LedgerFile, ledger)295    );296297    const lines = yield* readLedger.pipe(298      Effect.provideService(LedgerFile, ledger)299    );300301    return {302      cli: (yield* platform.asked).filter((said) => !said.startsWith("git ")),303      failure,304      ledger: lines.map(({ by, kind, name, stage }) => ({305        by,306        kind,307        name,308        stage,309      })),310    };311  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));312313describe("smoke --loop's throwaway ledger", () => {314  it.live(315    "writes the project and its repo before init, so an init that made the project and then failed leaves them in the ledger",316    () =>317      Effect.gen(function* () {318        const { cli, failure, ledger } = yield* loopOnScripted([]);319320        expect({ cli, ledger, step: failure.step }).toStrictEqual({321          cli: ["status", "status", "projects", "init"],322          ledger: [323            {324              by: "smoke",325              kind: "project",326              name: "ines-v__smoke-r1",327              stage: "dev-example",328            },329            {330              by: "smoke",331              kind: "repo",332              name: "ines-v__smoke-r1",333              stage: "dev-example",334            },335          ],336          step: "init",337        });338      })339  );340341  it.live(342    "stops before init on a name the platform already lists, and writes nothing",343    () =>344      Effect.gen(function* () {345        const { cli, failure, ledger } = yield* loopOnScripted([346          "oscabriel/datekit",347          "ines-v/smoke-r1",348        ]);349350        expect({351          cli,352          ledger,353          reason: failure.reason,354          step: failure.step,355        }).toStrictEqual({356          cli: ["status", "status", "projects"],357          ledger: [],358          reason:359            "ines-v/smoke-r1 is on the platform already, so nothing was made or recorded: a run a second later takes another name",360          step: "init",361        });362      })363  );364});365366describe("smoke --loop on prod", () => {367  it.live(368    "is refused with PublicStageRefused before any request or process: a throwaway project would show on prod's front page",369    () =>370      Effect.gen(function* () {371        const fetched: string[] = [];372        const spawner = yield* refusing;373374        const result = yield* main(["--stage", "prod", "--loop"]).pipe(375          Effect.provide(spawner.layer),376          Effect.provideService(FetchHttpClient.Fetch, (input) => {377            fetched.push(new Request(input).url);378379            return Promise.reject(new Error("smoke --loop on prod fetched"));380          }),381          Effect.result382        );383384        expect({385          fetched,386          result,387          spawned: yield* spawner.asked,388        }).toStrictEqual({389          fetched: [],390          result: Result.fail(new PublicStageRefused({ stage: "prod" })),391          spawned: [],392        });393      }).pipe(Effect.provide(NodeServices.layer))394  );395396  it.live("is refused by smokeLoop itself, whoever calls it", () =>397    Effect.gen(function* () {398      const spawner = yield* refusing;399400      const failure = yield* Effect.flip(401        smokeLoop({402          answerer: tokens.answerer,403          decider: tokens.decider,404          origin: "https://platform-prod.example.workers.dev",405          run: "r1",406          stage: "prod",407        })408      ).pipe(Effect.provide(spawner.layer));409410      expect({411        failure,412        message: failure.message,413        spawned: yield* spawner.asked,414      }).toStrictEqual({415        failure: new PublicStageRefused({ stage: "prod" }),416        message:417          "--loop makes a throwaway project, which would show on prod's front page: run it on a dev stage",418        spawned: [],419      });420    }).pipe(Effect.provide(NodeServices.layer))421  );422});423424describe("smokeLoop --draft, against the Node world", () => {425  it.live(426    "after the loop, the answerer's want is drafted red first by the memory drafter, the maintainer accepts it, and the ask opens disclosing the drafter beside the asker",427    () =>428      Effect.gen(function* () {429        const fs = yield* FileSystem.FileSystem;430        const path = yield* Path.Path;431        const dir = yield* fs.makeTempDirectoryScoped({ prefix: "drafting-" });432433        const report = yield* Effect.scoped(434          Effect.gen(function* () {435            const origin = yield* servedWorld(436              new Map([437                [decider, tokens.decider],438                [answerer, tokens.answerer],439              ])440            );441442            return yield* smokeLoop({443              answerer: tokens.answerer,444              decider: tokens.decider,445              draft: true,446              origin,447              run: "r2",448              stage: "node",449            });450          })451        ).pipe(452          Effect.provideService(LedgerFile, path.join(dir, "created.jsonl"))453        );454455        expect({456          attempts: report.draft?.attempts,457          model: report.draft?.model,458          steps: report.timings.map(({ step }) => step).slice(-3),459          timed: (report.draft?.ms ?? -1) >= 0,460          trailers: report.draft?.trailers.filter((trailer) =>461            /^(?:Ask|Asked-by|Assisted-by):/u.test(trailer)462          ),463        }).toStrictEqual({464          attempts: 1,465          model: "memory",466          steps: ["draft-propose", "draft-ready", "draft-accept"],467          timed: true,468          trailers: [469            `Asked-by: ${credited("bram")}`,470            `Assisted-by: ${Brand.cli}-drafter:memory (verified)`,471            "Ask: ines-v/smoke-r2/parse-ordinal",472          ],473        });474      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),475    240_000476  );477});478479describe("smoke --draft without --loop", () => {480  it.live(481    "is refused with DraftNeedsLoop before any request or process: only the loop has a project to draft on",482    () =>483      Effect.gen(function* () {484        const fetched: string[] = [];485        const spawner = yield* refusing;486487        const result = yield* main([488          "--stage",489          "dev-oscabriel",490          "--draft",491        ]).pipe(492          Effect.provide(spawner.layer),493          Effect.provideService(FetchHttpClient.Fetch, (input) => {494            fetched.push(new Request(input).url);495496            return Promise.reject(new Error("smoke --draft fetched"));497          }),498          Effect.result499        );500501        expect({502          fetched,503          result,504          spawned: yield* spawner.asked,505        }).toStrictEqual({506          fetched: [],507          result: Result.fail(new DraftNeedsLoop({ flag: "--draft" })),508          spawned: [],509        });510      }).pipe(Effect.provide(NodeServices.layer))511  );512});