Skip to content
Myr

sandbox-adapters.test.ts

This file

Path

apps/platform/test/sandbox-adapters.test.ts

739 lines · 21.0 KiB · TypeScript

Last changed by

Merge observability into mainoscabrielbefore adoption1985111

History of this file

Take it

1import { describe, expect, expectTypeOf, it } from "@effect/vitest";2import { RepoHost } from "@repo/artifacts/repo-host";3import type { TokenScope } from "@repo/artifacts/repo-host";4import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";5import { Brand } from "@repo/brand";6import { CheckAt, CheckRunner } from "@repo/checks/check-runner";7import type { CheckJob } from "@repo/checks/check-runner";8import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";9import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";10import { Lander, Rebuild } from "@repo/project/lander";11import type { LandJob } from "@repo/project/lander";12import { LanderMemory } from "@repo/project/lander/memory";13import type { LanderScript } from "@repo/project/lander/memory";14import {15  BundleExit,16  BundleWire,17  ComposeExit,18  ComposeWire,19  LandExit,20  LandWire,21  MergeExit,22  MergeWire,23} from "@repo/project/lander/wire";24import type { LaneResult } from "@repo/protocol/domain/answer";25import { Command } from "@repo/protocol/domain/common";26import {27  CommitSha,28  Handle,29  LandedSha,30  LaneName,31  ProjectName,32  RepoName,33  RepoPath,34  RequestId,35  TreeSha,36} from "@repo/protocol/ids";37import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";38import type { WorkerEntrypoint } from "cloudflare:workers";39import {40  Duration,41  Effect,42  Exit,43  FiberSet,44  Layer,45  Logger,46  Option,47  Redacted,48  Result,49  Schema,50} from "effect";5152import { CheckRunnerSandbox } from "../src/adapters/check-runner-sandbox.ts";53import type { SandboxBinding } from "../src/adapters/check-runner-sandbox.ts";54import { LanderSandbox } from "../src/adapters/lander-sandbox.ts";5556const project = ProjectName.make("alice/datekit");5758const canonical = RepoName.make("alice__datekit");5960const fork = RepoName.make("alice__datekit--fix-parse--alice");6162const base = CommitSha.make("2".repeat(40));6364const head = CommitSha.make("3".repeat(40));6566const main = LandedSha.make("4".repeat(40));6768const tree = TreeSha.make("5".repeat(40));6970const composed = CommitSha.make("6".repeat(40));7172const landed = LandedSha.make("7".repeat(40));7374const path = RepoPath.make("src/parse.ts");7576const lane = LaneName.make("test");7778const failed: LaneResult = {79  command: "bun test",80  durationMs: 1200,81  lane,82  result: "failed",83};8485const checkJob: CheckJob = {86  at: CheckAt.cases.Tree.make({ tree }),87  lanes: [{ command: "bun test", lane }],88  placeholders: [],89  project,90  proxies: [],91  repo: fork,92  run: { checks: {}, test: Command.make("bun test {path}") },93};9495const mergeJob = { base, fork, head, main, repo: canonical };9697const landJob = (rebuild: Rebuild): LandJob => ({98  author: Handle.make("alice"),99  main,100  message: "Fix the parser\n\nRequest-Id: request-0001\n",101  rebuild,102  repo: canonical,103  requestId: RequestId.make("request-0001"),104  tree,105  verdict: Option.none(),106});107108const landMerge = landJob(Rebuild.Merge({ base, fork, head }));109110const composeJob = {111  files: [{ content: "export {};\n", path }] as const,112  main,113  repo: canonical,114};115116const bundleJob = { at: main, repo: canonical };117118const bundle = {119  entry: `${Brand.configDir}/project.ts`,120  modules: {},121  sdkVersion: "1.0.0",122};123124const merged = { changes: [{ path, status: "modified" as const }], tree };125126const stale = new StaleBase({ base, conflicts: [path], main });127128const landerScript: LanderScript = {129  bundle: [Result.succeed(bundle)],130  compose: [Result.succeed({ commit: composed, tree })],131  land: [Result.succeed({ pending: [], sha: landed })],132  merge: [Result.succeed(merged)],133};134135interface Minted {136  readonly repo: RepoName;137  readonly scope: TokenScope;138  readonly ttlMs: number;139  readonly id: string;140  readonly secret: string;141}142143const recordingRepoHost = (failRevoke: boolean) =>144  Effect.gen(function* () {145    const store = yield* RepoHost;146    const minted: Minted[] = [];147    const revoked: { readonly repo: RepoName; readonly id: string }[] = [];148149    yield* store.create(canonical);150    yield* store.create(fork);151152    const host = RepoHost.of({153      ...store,154      mintToken: (repo, scope, ttl) =>155        store.mintToken(repo, scope, ttl).pipe(156          Effect.tap(({ id, secret }) =>157            Effect.sync(() =>158              minted.push({159                id,160                repo,161                scope,162                secret: Redacted.value(secret),163                ttlMs: Duration.toMillis(ttl),164              })165            )166          )167        ),168      revokeToken: (repo, id) =>169        Effect.sync(() => revoked.push({ id, repo })).pipe(170          Effect.andThen(171            failRevoke172              ? Effect.die(173                  new Error(174                    `cannot revoke ${minted.find((token) => token.id === id)?.secret}`175                  )176                )177              : store.revokeToken(repo, id)178          )179        ),180    });181182    return { host, minted, revoked };183  }).pipe(Effect.provide(RepoHostMemory));184185interface Seen {186  readonly bundleRules: (typeof BundleWire.Type)[];187  readonly check: (typeof CheckWire.Type)[];188  readonly compose: (typeof ComposeWire.Type)[];189  readonly land: (typeof LandWire.Type)[];190  readonly merge: (typeof MergeWire.Type)[];191}192193const fakeSandbox = Effect.gen(function* () {194  const run = yield* FiberSet.makeRuntimePromise<CheckRunner | Lander>();195196  const seen: Seen = {197    bundleRules: [],198    check: [],199    compose: [],200    land: [],201    merge: [],202  };203204  const answer =205    <W, WI, A, E, X>(206      wire: Schema.Codec<W, WI>,207      exit: Schema.Codec<Exit.Exit<A, E>, X>,208      into: W[],209      job: (decoded: W) => Effect.Effect<A, E, CheckRunner | Lander>210    ) =>211    (encoded: WI): Promise<X> =>212      run(213        Schema.decodeEffect(wire)(encoded).pipe(214          Effect.orDie,215          Effect.tap((decoded) => Effect.sync(() => into.push(decoded))),216          Effect.flatMap(job),217          Effect.exit,218          Effect.flatMap((outcome) =>219            Effect.orDie(Schema.encodeEffect(exit)(outcome))220          )221        )222      );223224  const sandbox: SandboxBinding = {225    bundleRules: answer(BundleWire, BundleExit, seen.bundleRules, ({ job }) =>226      Lander.use((lander) => lander.bundleRules(job))227    ),228    check: answer(CheckWire, CheckExit, seen.check, ({ job }) =>229      CheckRunner.use((runner) => runner.run(job))230    ),231    compose: answer(ComposeWire, ComposeExit, seen.compose, ({ job }) =>232      Lander.use((lander) => lander.compose(job))233    ),234    land: answer(LandWire, LandExit, seen.land, ({ job }) =>235      Lander.use((lander) => lander.land(job))236    ),237    merge: answer(MergeWire, MergeExit, seen.merge, ({ job }) =>238      Lander.use((lander) => lander.merge(job))239    ),240  };241242  return { sandbox, seen };243});244245interface WorldOptions {246  readonly script?: LanderScript;247  readonly binding?: (sandbox: SandboxBinding) => SandboxBinding;248  readonly failRevoke?: boolean;249}250251const world = (options: WorldOptions = {}) =>252  Effect.gen(function* () {253    const { host, minted, revoked } = yield* recordingRepoHost(254      options.failRevoke ?? false255    );256257    const fake = yield* fakeSandbox.pipe(258      Effect.provide(259        Layer.mergeAll(260          CheckRunnerMemory.layer(261            new Map([[scriptKey(checkJob.at, lane), [failed]]])262          ),263          LanderMemory.layer(options.script ?? landerScript)264        )265      )266    );267268    const binding = options.binding?.(fake.sandbox) ?? fake.sandbox;269270    const { lander, runner } = yield* Effect.gen(function* () {271      return { lander: yield* Lander, runner: yield* CheckRunner };272    }).pipe(273      Effect.provide(274        Layer.mergeAll(275          CheckRunnerSandbox(binding),276          LanderSandbox(binding)277        ).pipe(Layer.provide(Layer.succeed(RepoHost, host)))278      )279    );280281    return { host, lander, minted, revoked, runner, seen: fake.seen };282  });283284type Line = ReturnType<typeof Logger.formatStructured.log>;285286const withLogs = <A, E>(body: Effect.Effect<A, E>) =>287  Effect.gen(function* () {288    const lines: Line[] = [];289290    const exit = yield* Effect.exit(body).pipe(291      Effect.provide(292        Logger.layer([293          Logger.make((options) => {294            lines.push(Logger.formatStructured.log(options));295          }),296        ])297      )298    );299300    return { exit, lines };301  });302303const mintsOf = (minted: readonly Minted[]) =>304  minted.map(({ repo, scope }) => ({ repo, scope }));305306const opened = (remote: {307  readonly token: Redacted.Redacted;308  readonly url: string;309}) => ({310  token: Redacted.value(remote.token),311  url: remote.url,312});313314type World = Effect.Success<ReturnType<typeof world>>;315316const everyJob = ({317  lander,318  runner,319}: World): readonly Effect.Effect<320  object,321  RepoBusy | StaleBase | VerifierBlocked322>[] => [323  runner.run(checkJob),324  lander.merge(mergeJob),325  lander.land(landMerge),326  lander.land(landJob(Rebuild.Existing({ commit: composed }))),327  lander.compose(composeJob),328  lander.bundleRules(bundleJob),329];330331const byId = <T extends { readonly id: string }>(tokens: readonly T[]) =>332  tokens.toSorted((a, b) => a.id.localeCompare(b.id));333334interface SandboxEntrypoint extends WorkerEntrypoint<Env> {335  readonly check: (336    wire: typeof CheckWire.Encoded337  ) => Promise<typeof CheckExit.Encoded>;338  readonly merge: (339    wire: typeof MergeWire.Encoded340  ) => Promise<typeof MergeExit.Encoded>;341  readonly land: (342    wire: typeof LandWire.Encoded343  ) => Promise<typeof LandExit.Encoded>;344  readonly compose: (345    wire: typeof ComposeWire.Encoded346  ) => Promise<typeof ComposeExit.Encoded>;347  readonly bundleRules: (348    wire: typeof BundleWire.Encoded349  ) => Promise<typeof BundleExit.Encoded>;350}351352describe("the sandbox binding", () => {353  it("is the service binding's RPC stub as the runtime types it", () => {354    expectTypeOf<Service<SandboxEntrypoint>>().toExtend<SandboxBinding>();355  });356});357358describe("the sandbox CheckRunner", () => {359  it.effect(360    "returns the Checker's run, cloned with a read token on the answer's repo",361    () =>362      Effect.gen(function* () {363        const { host, minted, runner, seen } = yield* world();364365        expect(yield* Effect.exit(runner.run(checkJob))).toStrictEqual(366          Exit.succeed({367            durationMs: 1200,368            evidence: [{ lane, signature: "test: scripted failure" }],369            heldBack: [],370            lanes: [failed],371          })372        );373        expect(mintsOf(minted)).toStrictEqual([{ repo: fork, scope: "read" }]);374        expect(seen.check.map(({ clone }) => opened(clone))).toStrictEqual([375          { token: minted[0]?.secret, url: yield* host.remote(fork) },376        ]);377      })378  );379});380381describe("the sandbox Lander", () => {382  it.effect(383    "merges with a read token on canonical and a write token on the fork, for the merged commit's ref, and nothing more",384    () =>385      Effect.gen(function* () {386        const { host, lander, minted, seen } = yield* world();387388        expect(yield* Effect.exit(lander.merge(mergeJob))).toStrictEqual(389          Exit.succeed(merged)390        );391        expect(mintsOf(minted)).toStrictEqual([392          { repo: canonical, scope: "read" },393          { repo: fork, scope: "write" },394        ]);395        expect(396          seen.merge.map((wire) => ({397            fork: opened(wire.fork),398            main: opened(wire.main),399          }))400        ).toStrictEqual([401          {402            fork: { token: minted[1]?.secret, url: yield* host.remote(fork) },403            main: {404              token: minted[0]?.secret,405              url: yield* host.remote(canonical),406            },407          },408        ]);409      })410  );411412  it.effect(413    "lands a merge with one write token on canonical and a read token on the fork",414    () =>415      Effect.gen(function* () {416        const { host, lander, minted, seen } = yield* world();417418        expect(yield* Effect.exit(lander.land(landMerge))).toStrictEqual(419          Exit.succeed({ pending: [], sha: landed })420        );421        expect(mintsOf(minted)).toStrictEqual([422          { repo: canonical, scope: "write" },423          { repo: fork, scope: "read" },424        ]);425        expect(426          seen.land.map((wire) => ({427            fork: Option.map(Option.fromUndefinedOr(wire.fork), opened),428            main: Redacted.value(wire.main.token),429          }))430        ).toStrictEqual([431          {432            fork: Option.some({433              token: minted[1]?.secret,434              url: yield* host.remote(fork),435            }),436            main: minted[0]?.secret,437          },438        ]);439      })440  );441442  it.effect.each([443    Rebuild.Compose({ files: composeJob.files }),444    Rebuild.Existing({ commit: composed }),445  ])(446    "lands a $_tag rebuild with the write token on canonical alone",447    (rebuild) =>448      Effect.gen(function* () {449        const { lander, minted, seen } = yield* world();450451        expect(yield* Effect.exit(lander.land(landJob(rebuild)))).toStrictEqual(452          Exit.succeed({ pending: [], sha: landed })453        );454        expect(mintsOf(minted)).toStrictEqual([455          { repo: canonical, scope: "write" },456        ]);457        expect(seen.land.map((wire) => wire.fork)).toStrictEqual([undefined]);458      })459  );460461  it.effect(462    "composes with one write token on canonical, for its compose ref",463    () =>464      Effect.gen(function* () {465        const { lander, minted, seen } = yield* world();466467        expect(yield* Effect.exit(lander.compose(composeJob))).toStrictEqual(468          Exit.succeed({ commit: composed, tree })469        );470        expect(mintsOf(minted)).toStrictEqual([471          { repo: canonical, scope: "write" },472        ]);473        expect(474          seen.compose.map((wire) => Redacted.value(wire.main.token))475        ).toStrictEqual([minted[0]?.secret]);476      })477  );478479  it.effect("bundles the config folder with one read token on canonical", () =>480    Effect.gen(function* () {481      const { lander, minted, seen } = yield* world();482483      expect(yield* Effect.exit(lander.bundleRules(bundleJob))).toStrictEqual(484        Exit.succeed(bundle)485      );486      expect(mintsOf(minted)).toStrictEqual([487        { repo: canonical, scope: "read" },488      ]);489      expect(490        seen.bundleRules.map((wire) => Redacted.value(wire.main.token))491      ).toStrictEqual([minted[0]?.secret]);492    })493  );494495  it.effect("gives every token a lifetime of five minutes", () =>496    Effect.gen(function* () {497      const ok = yield* world();498499      yield* Effect.forEach(everyJob(ok), (job) => Effect.exit(job));500501      expect(ok.minted.map(({ ttlMs }) => ttlMs)).toStrictEqual(502        Array.from({ length: 8 }, () => 300_000)503      );504    })505  );506});507508interface Breakage {509  readonly name: string;510  readonly failure: string;511  readonly merge: SandboxBinding["merge"];512}513514const breakages: readonly Breakage[] = [515  {516    failure: "rejected",517    merge: (wire) =>518      Promise.reject(519        new Error(`no fetch from ${wire.main.url}: ${wire.main.token}`)520      ),521    name: "rejects",522  },523  {524    failure: "rejected",525    merge: (wire) => {526      throw new Error(`no fork at ${wire.fork.token}`);527    },528    name: "throws",529  },530  {531    failure: "undecodable",532    merge: (wire) => Promise.resolve({ sha: wire.main.token }),533    name: "answers with something that is not an Exit",534  },535  {536    failure: "defect",537    merge: (wire) =>538      Promise.resolve(539        Schema.encodeSync(MergeExit)(540          Exit.die(new Error(`git said ${wire.main.token}`))541        )542      ),543    name: "dies on the far side",544  },545];546547const leaked = (text: string, minted: readonly Minted[]) =>548  minted.flatMap(({ secret }) => (text.includes(secret) ? [secret] : []));549550describe("a sandbox job that fails", () => {551  it.effect(552    "arrives as the typed StaleBase or RepoBusy the Lander refused with",553    () =>554      Effect.gen(function* () {555        const busy = new RepoBusy({});556557        const { lander } = yield* world({558          script: { land: [Result.fail(busy)], merge: [Result.fail(stale)] },559        });560561        expect(yield* Effect.exit(lander.merge(mergeJob))).toStrictEqual(562          Exit.fail(stale)563        );564        expect(yield* Effect.exit(lander.land(landMerge))).toStrictEqual(565          Exit.fail(busy)566        );567      })568  );569570  it.effect.each(breakages)(571    "is VerifierBlocked, logged once by its method and with no token, when the sandbox $name",572    ({ failure, merge }) =>573      Effect.gen(function* () {574        const { lander, minted, revoked } = yield* world({575          binding: (sandbox) => ({ ...sandbox, merge }),576        });577578        const { exit, lines } = yield* withLogs(lander.merge(mergeJob));579580        expect(exit).toStrictEqual(Exit.fail(new VerifierBlocked({})));581        expect(582          lines583            .filter(({ level }) => level === "ERROR")584            .map(({ annotations }) => ({585              failure: annotations.failure,586              method: annotations.method,587            }))588        ).toStrictEqual([{ failure, method: "merge" }]);589        expect(leaked(JSON.stringify(lines), minted)).toStrictEqual([]);590        expect(revoked.map(({ id }) => id)).toStrictEqual(591          minted.map(({ id }) => id).toReversed()592        );593      })594  );595596  it.effect(597    "is VerifierBlocked on a repo the store does not know, and revokes what it minted first",598    () =>599      Effect.gen(function* () {600        const { lander, minted, revoked } = yield* world();601        const gone = RepoName.make("alice__datekit--gone--bob");602603        const { exit, lines } = yield* withLogs(604          lander.merge({ ...mergeJob, fork: gone })605        );606607        expect(exit).toStrictEqual(Exit.fail(new VerifierBlocked({})));608        expect(mintsOf(minted)).toStrictEqual([609          { repo: canonical, scope: "read" },610        ]);611        expect(revoked.map(({ id }) => id)).toStrictEqual(612          minted.map(({ id }) => id)613        );614        expect(615          lines.map(({ annotations, level }) => ({616            failure: annotations.failure,617            level,618            method: annotations.method,619            repo: annotations.repo,620          }))621        ).toStrictEqual([622          {623            failure: "repo not found",624            level: "ERROR",625            method: "merge",626            repo: gone,627          },628        ]);629      })630  );631632  it.effect(633    "logs a defect from the far side by its name and frames alone, since a Checker's may quote a sealed file's path",634    () =>635      Effect.gen(function* () {636        const sealed = "tests/sealed/parse.test.ts";637638        const { lander } = yield* world({639          binding: (sandbox) => ({640            ...sandbox,641            merge: () =>642              Promise.resolve(643                Schema.encodeSync(MergeExit)(644                  Exit.die(new Error(`no file at ${sealed}`))645                )646              ),647          }),648        });649650        const { lines } = yield* withLogs(lander.merge(mergeJob));651652        expect(653          lines.map(({ annotations }) => annotations.detail)654        ).toStrictEqual([expect.stringMatching(/^Error: <withheld>/u)]);655        expect(JSON.stringify(lines)).not.toContain(sealed);656      })657  );658});659660describe("a sandbox job's tokens", () => {661  it.effect("are each revoked once their job has ended", () =>662    Effect.gen(function* () {663      const ok = yield* world();664665      yield* Effect.forEach(everyJob(ok), (job) => Effect.exit(job));666667      expect(ok.minted).toHaveLength(8);668      expect(byId(ok.revoked)).toStrictEqual(669        byId(ok.minted.map(({ id, repo }) => ({ id, repo })))670      );671    })672  );673674  it.effect(675    "fail no job when they cannot be revoked, and are warned of by repo and id alone",676    () =>677      Effect.gen(function* () {678        const { lander, minted, revoked } = yield* world({ failRevoke: true });679680        const { exit, lines } = yield* withLogs(lander.land(landMerge));681682        expect(exit).toStrictEqual(Exit.succeed({ pending: [], sha: landed }));683        expect(revoked.map(({ id }) => id)).toStrictEqual(684          minted.map(({ id }) => id).toReversed()685        );686        expect(687          lines.map(({ annotations, level }) => ({688            level,689            method: annotations.method,690            repo: annotations.repo,691            tokenId: annotations.tokenId,692          }))693        ).toStrictEqual(694          minted.toReversed().map(({ id, repo }) => ({695            level: "WARN",696            method: "land",697            repo,698            tokenId: id,699          }))700        );701        expect(leaked(JSON.stringify(lines), minted)).toStrictEqual([]);702      })703  );704705  it.effect("appear in no result, refusal or log line", () =>706    Effect.gen(function* () {707      const ok = yield* world();708709      const refusing = yield* world({710        script: {711          ...landerScript,712          land: [Result.fail(new RepoBusy({}))],713          merge: [Result.fail(stale)],714        },715      });716717      const broken = yield* Effect.forEach(breakages, ({ merge }) =>718        world({ binding: (sandbox) => ({ ...sandbox, merge }) })719      );720721      const { exit, lines } = yield* withLogs(722        Effect.forEach(723          [724            ...everyJob(ok),725            ...everyJob(refusing),726            ...broken.map(({ lander }) => lander.merge(mergeJob)),727          ],728          (job) => Effect.exit(job)729        )730      );731732      const minted = [ok, refusing, ...broken].flatMap((each) => each.minted);733734      expect(minted).toHaveLength(24);735      expect(leaked(JSON.stringify(exit), minted)).toStrictEqual([]);736      expect(leaked(JSON.stringify(lines), minted)).toStrictEqual([]);737    })738  );739});