Skip to content
Myr

binding.test.ts

This file

Path

packages/artifacts/test/binding.test.ts

1,078 lines · 32.8 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { CommitSha, RepoPath } from "@repo/protocol/ids";4import { fakeArtifactsBinding } from "@repo/testkit/fake-artifacts-binding";5import type {6  FakeOptions,7  HostLike,8} from "@repo/testkit/fake-artifacts-binding";9import { gitClient } from "@repo/testkit/git-client";10import { httpBackend } from "@repo/testkit/http-backend";11import {12  Duration,13  Effect,14  Exit,15  Fiber,16  FiberSet,17  FileSystem,18  Layer,19  Option,20  Redacted,21  Ref,22} from "effect";23import type { Scope } from "effect";24import type { ChildProcessSpawner } from "effect/process";25import { TestClock } from "effect/testing";26import { readCommit } from "isomorphic-git";2728import { Fetch, FetchFailed } from "../src/fetch.ts";29import {30  BranchName,31  ForkInProgress,32  HostBusy,33  inRepoSession,34  ObjectId,35  RefName,36  RefOutcome,37  RepoExists,38  RepoHost,39  RepoName,40  RepoNotFound,41  Revision,42} from "../src/repo-host.ts";43import { RepoHostBinding } from "../src/repo-host/binding.ts";44import { RepoHostLocal } from "../src/repo-host/local.ts";45import { memoryFs } from "../src/repo-host/memory-fs.ts";46import { fetchInto, listRefs, pushRefs } from "../src/repo-host/smart-http.ts";47import { describeRepoHost } from "./repo-host-contract.ts";48import { temporaryRoot } from "./temporary-root.ts";4950const main = RefName.make("refs/heads/main");5152const landed = RefName.make("refs/asked/landed");5354const remoteBase = "https://artifacts.test/git/projects";5556const fatal = (message: string) => {57  const payload = new TextEncoder().encode(`\u0003${message}`);58  const length = (payload.length + 4).toString(16).padStart(4, "0");5960  return new Uint8Array([...new TextEncoder().encode(length), ...payload]);61};6263const busyReply = () =>64  new Response(fatal("artifacts_git_receive_pack_busy\n"), {65    headers: { "content-type": "application/x-git-receive-pack-result" },66  });6768interface Seen {69  readonly url: string;70  readonly authorization: string | null;71}7273type Intercept = (request: Request) => Effect.Effect<Option.Option<Response>>;7475const world = (76  options: FakeOptions & {77    readonly wrap?: (host: HostLike) => HostLike;78    readonly making?: {79      readonly code: "CREATE_IN_PROGRESS" | "IMPORT_IN_PROGRESS";80      readonly gets: number;81    };82  } = {}83) =>84  Effect.gen(function* () {85    const root = yield* temporaryRoot;8687    const spawner =88      yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();8990    const backend = httpBackend(root);91    const seen = yield* Ref.make<readonly Seen[]>([]);92    const intercept = yield* Ref.make<Option.Option<Intercept>>(Option.none());9394    const fetch = Fetch.of({95      fetch: (request) =>96        Effect.gen(function* () {97          if (!request.url.startsWith(`${remoteBase}/`)) {98            return yield* new FetchFailed({99              reason: "no route to host",100              url: request.url,101            });102          }103104          yield* Ref.update(seen, (all) => [105            ...all,106            {107              authorization: request.headers.get("authorization"),108              url: request.url,109            },110          ]);111112          const once = yield* Ref.getAndSet(intercept, Option.none());113114          if (115            Option.isSome(once) &&116            request.url.endsWith("/git-receive-pack")117          ) {118            const reply = yield* once.value(request);119120            if (Option.isSome(reply)) {121              return reply.value;122            }123          } else if (Option.isSome(once)) {124            yield* Ref.set(intercept, once);125          }126127          return yield* Effect.scoped(backend(request)).pipe(128            Effect.provide(spawner)129          );130        }),131    });132133    const store = yield* RepoHost.pipe(134      Effect.provide(135        RepoHostLocal.layer({ remoteBase, root }).pipe(136          Layer.provide(Layer.succeed(Fetch, fetch))137        )138      )139    );140141    const fake = fakeArtifactsBinding(142      options.wrap === undefined ? store : options.wrap(store),143      options144    );145146    // The fake's handles dispose as a no-op; this wrapper counts each handle147    // `get` gave out against the disposals, and keeps each token minted.148    const run = yield* FiberSet.makeRuntimePromise();149    const counts = { disposed: 0, gets: 0 };150    const tokens: { id: string; plaintext: string }[] = [];151    let making = options.making?.gets ?? 0;152153    const binding: Artifacts = {154      ...fake,155      get: (name) => {156        if (making > 0 && options.making !== undefined) {157          making -= 1;158159          return Promise.reject(160            Object.assign(new Error("the repo is still being made"), {161              code: options.making.code,162            })163          );164        }165166        return run(167          Effect.promise(() => fake.get(name)).pipe(168            Effect.map((repo): ArtifactsRepo => {169              counts.gets += 1;170171              return {172                ...repo,173                createToken: (scope, ttl) =>174                  run(175                    Effect.promise(() => repo.createToken(scope, ttl)).pipe(176                      Effect.tap((token) =>177                        Effect.sync(() => tokens.push(token))178                      )179                    )180                  ),181                [Symbol.dispose]: () => {182                  counts.disposed += 1;183                  repo[Symbol.dispose]();184                },185              };186            })187          )188        );189      },190    };191192    return {193      binding,194      counts,195      fake,196      fetch,197      intercept,198      layer: RepoHostBinding.layer(binding).pipe(199        Layer.provide(Layer.succeed(Fetch, fetch))200      ),201      root,202      seen,203      store,204      tokens,205    };206  });207208type World = Effect.Success<ReturnType<typeof world>>;209210const within = <A, E>(211  body: (212    world: World213  ) => Effect.Effect<214    A,215    E,216    RepoHost | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner217  >,218  options?: Parameters<typeof world>[0]219) =>220  Effect.gen(function* () {221    const made = yield* world(options);222223    return yield* body(made).pipe(Effect.provide(made.layer));224  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));225226describeRepoHost(227  "binding",228  Layer.unwrap(Effect.map(world(), ({ layer }) => layer)).pipe(229    Layer.provide(NodeServices.layer)230  ),231  {232    importUrl: (name) =>233      RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),234  }235);236237const seeded = (name: RepoName) =>238  Effect.gen(function* () {239    const repos = yield* RepoHost;240    const client = yield* gitClient(memoryFs());241    const first = yield* client.commit("first", [["a.txt", "1"]]);242243    yield* repos.create(name).pipe(Effect.orDie);244    yield* repos245      .push(name, client.source, [246        { from: Option.none(), ref: main, to: first },247      ])248      .pipe(Effect.orDie);249250    return { client, first };251  });252253describe("the Workers binding's surprises, typed", () => {254  // Under `wrangler dev`, the binding throws plain `Error`s.255  it.live(256    "reads a missing repo as RepoNotFound when errors carry no code",257    () =>258      within(259        () =>260          Effect.gen(function* () {261            const repos = yield* RepoHost;262            const missing = RepoName.make("missing");263            const taken = RepoName.make("taken");264265            yield* repos.create(taken).pipe(Effect.orDie);266267            expect(268              yield* Effect.flip(269                repos.readFile(270                  missing,271                  Revision.Branch({ name: BranchName.make("main") }),272                  RepoPath.make("a.txt")273                )274              )275            ).toStrictEqual(new RepoNotFound({ name: missing }));276            expect(yield* Effect.flip(repos.refs(missing))).toStrictEqual(277              new RepoNotFound({ name: missing })278            );279            expect(yield* Effect.flip(repos.create(taken))).toStrictEqual(280              new RepoExists({ name: taken })281            );282            expect(yield* Effect.flip(repos.fork(taken, taken))).toStrictEqual(283              new RepoExists({ name: taken })284            );285          }),286        { codeless: true }287      )288  );289290  // Under load a fork answers 500 after making the repo, and a retry291  // answers 409. The fork's name is the claim's, so the retry converges.292  it.live.each([293    { codeless: false, label: "with codes" },294    { codeless: true, label: "without codes" },295  ])(296    "forks once through a 500 then an already-exists, $label",297    ({ codeless }) =>298      within(299        ({ fake }) =>300          Effect.gen(function* () {301            const repos = yield* RepoHost;302            const base = RepoName.make("demo");303            const name = RepoName.make("demo--fix--alice");304            const { first } = yield* seeded(base);305306            const created = yield* repos.fork(base, name).pipe(Effect.orDie);307            const listed = yield* Effect.promise(() => fake.list());308309            expect(created).toStrictEqual({310              name,311              remote: `${remoteBase}/${name}.git`,312            });313            expect(314              listed.repos.map((repo) => repo.name).toSorted()315            ).toStrictEqual([base, name]);316            expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(317              new Map([[main, first]])318            );319          }),320        { codeless, forkFailures: 1 }321      )322  );323324  it.live("reads a fork still in progress as ForkInProgress", () =>325    within(326      () =>327        Effect.gen(function* () {328          const repos = yield* RepoHost;329          const base = RepoName.make("demo");330          const name = RepoName.make("demo--fix--bob");331332          yield* seeded(base);333334          expect(yield* Effect.flip(repos.fork(base, name))).toStrictEqual(335            new ForkInProgress({ name })336          );337        }),338      {339        wrap: (host) => ({340          ...host,341          fork: (_base, name) => Effect.fail(new ForkInProgress({ name })),342        }),343      }344    )345  );346347  it.live("reads a busy receive-pack as HostBusy, and moves nothing", () =>348    within(({ intercept }) =>349      Effect.gen(function* () {350        const repos = yield* RepoHost;351        const name = RepoName.make("busy");352        const { client, first } = yield* seeded(name);353354        const second = yield* client.commit(355          "second",356          [["a.txt", "2"]],357          [first]358        );359360        const update = { from: Option.some(first), ref: main, to: second };361362        yield* Ref.set(363          intercept,364          Option.some(() => Effect.succeedSome(busyReply()))365        );366367        expect(368          yield* Effect.flip(repos.push(name, client.source, [update]))369        ).toStrictEqual(new HostBusy({ name }));370        expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(371          new Map([[main, first]])372        );373        expect(374          yield* repos.push(name, client.source, [update]).pipe(Effect.orDie)375        ).toStrictEqual([RefOutcome.Updated({ ref: main })]);376      })377    )378  );379380  it.live(381    "reports a ref that moved during the push as Stale at its new tip",382    () =>383      within(({ intercept, store }) =>384        Effect.gen(function* () {385          const repos = yield* RepoHost;386          const name = RepoName.make("raced");387          const { client, first } = yield* seeded(name);388          const ours = yield* client.commit("ours", [["a.txt", "2"]], [first]);389390          const theirs = yield* client.commit(391            "theirs",392            [["a.txt", "3"]],393            [first]394          );395396          yield* Ref.set(397            intercept,398            Option.some(() =>399              store400                .push(name, client.source, [401                  { from: Option.some(first), ref: main, to: theirs },402                ])403                .pipe(Effect.orDie, Effect.as(Option.none()))404            )405          );406407          expect(408            yield* repos409              .push(name, client.source, [410                { from: Option.some(first), ref: main, to: ours },411              ])412              .pipe(Effect.orDie)413          ).toStrictEqual([414            RefOutcome.Stale({ ref: main, tip: Option.some(theirs) }),415          ]);416        })417      )418  );419420  // Artifacts takes any update whose old value matches, and `/memory`421  // and `/local` apply it too: the compare-and-swap is the only check.422  it.live(423    "moves a ref whose tip is `from` to a `to` that is not a fast-forward",424    () =>425      within(() =>426        Effect.gen(function* () {427          const repos = yield* RepoHost;428          const name = RepoName.make("rewound");429          const { client, first } = yield* seeded(name);430          const unrelated = yield* client.commit("unrelated", [["b.txt", "1"]]);431432          expect(433            yield* Effect.exit(434              repos.push(name, client.source, [435                { from: Option.some(first), ref: main, to: unrelated },436              ])437            )438          ).toStrictEqual(Exit.succeed([RefOutcome.Updated({ ref: main })]));439          expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(440            new Map([[main, unrelated]])441          );442        })443      )444  );445446  // The Lander moves its mirror ref to a landing the store already holds,447  // pushing from a scratch repo that holds none of its objects.448  it.live(449    "moves a ref to a commit the store has, from a source that has none of it",450    () =>451      within(() =>452        Effect.gen(function* () {453          const repos = yield* RepoHost;454          const name = RepoName.make("mirrored");455          const { client, first } = yield* seeded(name);456          const empty = yield* gitClient(memoryFs());457458          const second = yield* client.commit(459            "second",460            [["a.txt", "2"]],461            [first]462          );463464          yield* repos465            .push(name, client.source, [466              { from: Option.none(), ref: landed, to: first },467              { from: Option.some(first), ref: main, to: second },468            ])469            .pipe(Effect.orDie);470471          expect(472            yield* Effect.exit(473              repos.push(name, empty.source, [474                { from: Option.some(first), ref: landed, to: second },475              ])476            )477          ).toStrictEqual(Exit.succeed([RefOutcome.Updated({ ref: landed })]));478          expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(479            new Map([480              [landed, second],481              [main, second],482            ])483          );484        })485      )486  );487488  it.live("reads no tree at a blob's id or a commit's id", () =>489    within(490      () =>491        Effect.gen(function* () {492          const repos = yield* RepoHost;493          const name = RepoName.make("kinds");494          const { first } = yield* seeded(name);495496          const commit = yield* repos497            .readCommit(name, first)498            .pipe(Effect.orDie);499500          const tree = Option.getOrThrow(501            Option.map(commit, (read) => read.tree)502          );503504          const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);505          const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;506507          expect(blob).not.toBe(tree);508          expect(yield* Effect.exit(repos.readTree(name, blob))).toStrictEqual(509            Exit.succeed(Option.none())510          );511          expect(512            yield* Effect.exit(repos.readTree(name, ObjectId.make(first)))513          ).toStrictEqual(Exit.succeed(Option.none()));514        }),515      {516        wrap: (host) => ({517          ...host,518          readTree: (repo, sha) =>519            Effect.gen(function* () {520              const tree = yield* host.readTree(repo, sha);521              const blob = yield* host.readBlob(repo, sha);522              const commit = yield* host.readCommit(repo, CommitSha.make(sha));523524              return Option.isNone(tree) &&525                (Option.isSome(blob) || Option.isSome(commit))526                ? yield* Effect.die(527                    Object.assign(new Error("An internal error occurred."), {528                      code: "INTERNAL_ERROR",529                      name: "ArtifactsError",530                      numericCode: 10_400,531                    })532                  )533                : tree;534            }),535        }),536      }537    )538  );539});540541describe("tokens and handles the binding takes", () => {542  it.live("leaves no live token on a repo it created, forked or imported", () =>543    within(({ fake }) =>544      Effect.gen(function* () {545        const repos = yield* RepoHost;546        const base = RepoName.make("kept");547        const fork = RepoName.make("kept--fix--bob");548        const imported = RepoName.make("imported");549550        yield* seeded(base);551        yield* repos.fork(base, fork).pipe(Effect.orDie);552        yield* repos553          .importFrom(imported, {554            url: yield* repos.remote(base).pipe(Effect.orDie),555          })556          .pipe(Effect.orDie);557558        const left = yield* Effect.forEach([base, fork, imported], (name) =>559          Effect.acquireUseRelease(560            Effect.promise(() => fake.get(name)),561            (repo) =>562              Effect.promise(() => repo.listTokens()).pipe(563                Effect.map(564                  ({ tokens: listed }) =>565                    [566                      name,567                      listed.filter(({ state }) => state === "active").length,568                    ] as const569                )570              ),571            (repo) =>572              Effect.sync(() => {573                repo[Symbol.dispose]();574              })575          )576        );577578        expect(left).toStrictEqual([579          [base, 0],580          [fork, 0],581          [imported, 0],582        ]);583      })584    )585  );586587  it.live.each(["CREATE_IN_PROGRESS", "IMPORT_IN_PROGRESS"] as const)(588    "waits out a repo still being made (%s) before it reads it",589    (code) =>590      within(591        () =>592          Effect.gen(function* () {593            const repos = yield* RepoHost;594            const name = RepoName.make("making");595            const { first } = yield* seeded(name);596597            expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(598              new Map([[main, first]])599            );600          }),601        { making: { code, gets: 2 } }602      )603  );604605  it.live(606    "sends each minted token only to the repo's own remote, then revokes it",607    () =>608      within(({ fake, seen, tokens }) =>609        Effect.gen(function* () {610          const repos = yield* RepoHost;611          const name = RepoName.make("tokens");612          const { client, first } = yield* seeded(name);613614          const second = yield* client.commit(615            "second",616            [["a.txt", "2"]],617            [first]618          );619620          yield* Ref.set(seen, []);621          tokens.length = 0;622623          yield* repos624            .push(name, client.source, [625              { from: Option.some(first), ref: main, to: second },626            ])627            .pipe(Effect.orDie);628          yield* repos.refs(name).pipe(Effect.orDie);629630          const requests = yield* Ref.get(seen);631632          const repo = yield* Effect.acquireRelease(633            Effect.promise(() => fake.get(name)),634            (handle) =>635              Effect.sync(() => {636                handle[Symbol.dispose]();637              })638          );639640          const revoked = yield* Effect.forEach(tokens, ({ id }) =>641            Effect.promise(() => repo.revokeToken(id))642          );643644          expect(tokens.length).toBeGreaterThan(0);645          expect(requests.length).toBeGreaterThan(0);646          expect(647            requests.every(648              ({ authorization, url }) =>649                url.startsWith(`${remoteBase}/${name}.git/`) &&650                tokens.some(651                  ({ plaintext }) => authorization === `Bearer ${plaintext}`652                )653            )654          ).toBeTruthy();655          expect(revoked.every((again) => !again)).toBeTruthy();656        })657      )658  );659660  it.live(661    "disposes every repo handle it opened, after success or failure",662    () =>663      within(({ counts, intercept }) =>664        Effect.gen(function* () {665          const repos = yield* RepoHost;666          const name = RepoName.make("handles");667          const missing = RepoName.make("missing");668          const { client, first } = yield* seeded(name);669670          const second = yield* client.commit(671            "second",672            [["a.txt", "2"]],673            [first]674          );675676          const at = Revision.Branch({ name: BranchName.make("main") });677678          yield* repos679            .push(name, client.source, [680              { from: Option.some(first), ref: main, to: second },681            ])682            .pipe(Effect.orDie);683          yield* repos.refs(name).pipe(Effect.orDie);684          yield* repos.remote(name).pipe(Effect.orDie);685          yield* repos686            .readFile(name, at, RepoPath.make("a.txt"))687            .pipe(Effect.orDie);688          yield* repos.log(name, at, 5).pipe(Effect.orDie);689          yield* repos.readCommit(name, second).pipe(Effect.orDie);690691          const token = yield* repos692            .mintToken(name, "read", Duration.minutes(5))693            .pipe(Effect.orDie);694695          yield* repos.revokeToken(name, token.id).pipe(Effect.orDie);696          yield* repos697            .fork(name, RepoName.make("handles--fork"))698            .pipe(Effect.orDie);699          yield* Ref.set(700            intercept,701            Option.some(() => Effect.succeedSome(busyReply()))702          );703704          const third = yield* client.commit(705            "third",706            [["a.txt", "3"]],707            [second]708          );709710          expect(711            yield* Effect.flip(712              repos.push(name, client.source, [713                { from: Option.some(second), ref: main, to: third },714              ])715            )716          ).toStrictEqual(new HostBusy({ name }));717          expect(yield* Effect.flip(repos.refs(missing))).toStrictEqual(718            new RepoNotFound({ name: missing })719          );720          expect(counts.gets).toBeGreaterThan(5);721          expect(counts.disposed).toBe(counts.gets);722        })723      )724  );725});726727describe("git smart HTTP over the Fetch port", () => {728  const token = Redacted.make("test-token");729730  it.live(731    "lists refs, pushes one compare-and-swap per ref, and fetches a ref",732    () =>733      within(({ fetch, store }) =>734        Effect.gen(function* () {735          const name = RepoName.make("wire");736          const client = yield* gitClient(memoryFs());737          const first = yield* client.commit("first", [["a.txt", "1"]]);738739          const second = yield* client.commit(740            "second",741            [["a.txt", "2"]],742            [first]743          );744745          const remote = `${remoteBase}/${name}.git`;746747          yield* store.create(name).pipe(Effect.orDie);748749          const outcomes = yield* pushRefs({750            remote,751            source: client.source,752            token,753            updates: [754              { from: Option.none(), ref: main, to: second },755              { from: Option.some(first), ref: landed, to: second },756            ],757          });758759          const fs = memoryFs();760761          const fetched = yield* fetchInto({762            depth: 1,763            fs,764            gitdir: "/scratch.git",765            ref: "main",766            remote,767            token,768          });769770          const absent = yield* fetchInto({771            fs,772            gitdir: "/scratch.git",773            ref: "absent",774            remote,775            token,776          });777778          const read = yield* Effect.promise(() =>779            readCommit({ fs, gitdir: "/scratch.git", oid: second })780          );781782          expect(outcomes).toStrictEqual([783            RefOutcome.Updated({ ref: main }),784            RefOutcome.Stale({ ref: landed, tip: Option.none() }),785          ]);786          expect(yield* listRefs(remote, token)).toStrictEqual(787            new Map<RefName, CommitSha>([[main, second]])788          );789          expect(fetched).toStrictEqual(Option.some(second));790          expect(absent).toStrictEqual(Option.none());791          expect(read.commit.message).toBe("second\n");792        }).pipe(Effect.provideService(Fetch, fetch))793      )794  );795796  it.live("names the repo a remote does not serve", () =>797    within(({ fetch }) =>798      Effect.gen(function* () {799        const name = RepoName.make("nowhere");800        const remote = `${remoteBase}/${name}.git`;801802        expect(yield* Effect.flip(listRefs(remote, token))).toStrictEqual(803          new RepoNotFound({ name })804        );805        expect(806          yield* Effect.flip(807            fetchInto({808              fs: memoryFs(),809              gitdir: "/x.git",810              ref: "main",811              remote,812              token,813            })814          )815        ).toStrictEqual(new RepoNotFound({ name }));816      }).pipe(Effect.provideService(Fetch, fetch))817    )818  );819});820821/**822 * Runs `effect` on the TestClock, moving the clock by the binding's longest823 * sleep while it runs, so a wait of minutes passes at once.824 */825const onTestClock = <A, E, R>(effect: Effect.Effect<A, E, R>) =>826  Effect.gen(function* () {827    const fiber = yield* Effect.forkChild(effect);828829    while (fiber.pollUnsafe() === undefined) {830      yield* TestClock.adjust(Duration.seconds(16));831      yield* Effect.yieldNow;832    }833834    return yield* Fiber.await(fiber);835  });836837const liveTokens = (fake: Artifacts, name: RepoName) =>838  Effect.acquireUseRelease(839    Effect.promise(() => fake.get(name)),840    (repo) =>841      Effect.promise(() => repo.listTokens()).pipe(842        Effect.map(843          ({ tokens: listed }) =>844            listed.filter(({ state }) => state === "active").length845        )846      ),847    (repo) =>848      Effect.sync(() => {849        repo[Symbol.dispose]();850      })851  );852853describe("an import Artifacts is still copying", () => {854  const master = RefName.make("refs/heads/master");855856  it.live(857    "imports a remote whose default branch is master without being told",858    () =>859      within(860        ({ root }) =>861          Effect.gen(function* () {862            const repos = yield* RepoHost;863            const client = yield* gitClient(memoryFs());864            const first = yield* client.commit("first", [["a", "1"]]);865            const remote = RepoName.make("upstream-master");866            const name = RepoName.make("adopted-master");867868            yield* repos.create(remote).pipe(Effect.orDie);869            yield* repos870              .push(remote, client.source, [871                { from: Option.none(), ref: master, to: first },872              ])873              .pipe(Effect.orDie);874            yield* FileSystem.FileSystem.use((fs) =>875              fs.writeFileString(876                `${root}/${remote}.git/HEAD`,877                "ref: refs/heads/master\n"878              )879            ).pipe(Effect.provide(NodeServices.layer), Effect.orDie);880881            yield* repos882              .importFrom(name, {883                url: yield* repos.remote(remote).pipe(Effect.orDie),884              })885              .pipe(Effect.orDie);886887            expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(888              new Map([[master, first]])889            );890          }),891        { defaultBranch: "master" }892      )893  );894895  // An import may be asked about for three minutes, so twelve busy answers pass.896  it.effect(897    "waits through twelve IMPORT_IN_PROGRESS answers, then revokes the import's token and reads it",898    () =>899      within(900        ({ fake }) =>901          Effect.gen(function* () {902            const repos = yield* RepoHost;903            const name = RepoName.make("slow-import");904            const { first } = yield* seeded(RepoName.make("slow-source"));905906            const imported = yield* onTestClock(907              repos.importFrom(name, {908                url: yield* repos909                  .remote(RepoName.make("slow-source"))910                  .pipe(Effect.orDie),911              })912            );913914            const read = yield* onTestClock(repos.refs(name));915916            expect(Exit.isSuccess(imported)).toBeTruthy();917            expect(read).toStrictEqual(Exit.succeed(new Map([[main, first]])));918            // Revoked by the import's own wait, which outlasted all twelve.919            expect(yield* liveTokens(fake, name)).toBe(0);920          }),921        { importing: 12 }922      )923  );924925  it.effect("still gives a repo being created seven asks, no more", () =>926    within(927      ({ fake }) =>928        Effect.gen(function* () {929          const repos = yield* RepoHost;930          const name = RepoName.make("slow-create");931932          // The create's own wait asks eight times and gives up, leaving933          // its write token live; the read after it waits out the ninth.934          const created = yield* onTestClock(repos.create(name));935          const read = yield* onTestClock(repos.refs(name));936937          expect(Exit.isSuccess(created)).toBeTruthy();938          expect(read).toStrictEqual(Exit.succeed(new Map()));939          expect(yield* liveTokens(fake, name)).toBe(1);940        }),941      { making: { code: "CREATE_IN_PROGRESS", gets: 9 } }942    )943  );944945  // Past the wait, the read dies with the repo made; the project's retry946  // meets `RepoExists`, and a read once the import is done finds it.947  it.effect(948    "dies past the wait, then answers RepoExists to the retry and reads the repo once it is copied",949    () =>950      within(951        ({ fake }) =>952          Effect.gen(function* () {953            const repos = yield* RepoHost;954            const name = RepoName.make("stuck-import");955            const source = RepoName.make("stuck-source");956            const { first } = yield* seeded(source);957            const url = yield* repos.remote(source).pipe(Effect.orDie);958959            const imported = yield* onTestClock(960              repos.importFrom(name, { url })961            );962963            const died = yield* onTestClock(repos.refs(name));964            const again = yield* onTestClock(repos.importFrom(name, { url }));965            const read = yield* onTestClock(repos.refs(name));966967            expect(Exit.isSuccess(imported)).toBeTruthy();968            expect(Exit.hasDies(died)).toBeTruthy();969            expect(again).toStrictEqual(Exit.fail(new RepoExists({ name })));970            expect(read).toStrictEqual(Exit.succeed(new Map([[main, first]])));971            // The import's day-long write token outlived the wait; nothing972            // was handed it, and it expires.973            expect(yield* liveTokens(fake, name)).toBe(1);974          }),975        { importing: 40 }976      )977  );978});979980describe("reads in one session, and Artifacts' rate limit", () => {981  const at = Revision.Branch({ name: BranchName.make("main") });982983  it.live(984    "asks for one handle for every read of one session, and disposes it once",985    () =>986      within(({ counts }) =>987        Effect.gen(function* () {988          const repos = yield* RepoHost;989          const name = RepoName.make("session");990          const { first } = yield* seeded(name);991          const before = { ...counts };992993          const read = yield* inRepoSession(994            Effect.all(995              [996                repos.readCommit(name, first),997                repos.log(name, at, 5),998                repos.readFile(name, at, RepoPath.make("a.txt")),999                repos.readCommit(name, first),1000              ],1001              { concurrency: 4 }1002            )1003          ).pipe(Effect.orDie);10041005          expect(read[1].map(({ sha }) => sha)).toStrictEqual([first]);1006          expect([1007            counts.gets - before.gets,1008            counts.disposed - before.disposed,1009          ]).toStrictEqual([1, 1]);1010        })1011      )1012  );10131014  it.live(1015    "reads in a session inside another over the outer session's handle",1016    () =>1017      within(({ counts }) =>1018        Effect.gen(function* () {1019          const repos = yield* RepoHost;1020          const name = RepoName.make("nested");1021          const { first } = yield* seeded(name);1022          const before = { ...counts };10231024          yield* inRepoSession(1025            Effect.all([1026              repos.readCommit(name, first),1027              inRepoSession(repos.log(name, at, 5)),1028              repos.readFile(name, at, RepoPath.make("a.txt")),1029            ])1030          ).pipe(Effect.orDie);10311032          expect([1033            counts.gets - before.gets,1034            counts.disposed - before.disposed,1035          ]).toStrictEqual([1, 1]);1036        })1037      )1038  );10391040  it.effect(1041    "asks again after each of four rate-limited reads, then reads",1042    () =>1043      within(1044        () =>1045          Effect.gen(function* () {1046            const repos = yield* RepoHost;1047            const name = RepoName.make("limited");1048            const { first } = yield* seeded(name);1049            const read = yield* onTestClock(repos.readCommit(name, first));10501051            expect(1052              Exit.map(1053                read,1054                Option.map(({ sha }) => sha)1055              )1056            ).toStrictEqual(Exit.succeed(Option.some(first)));1057          }),1058        { rateLimited: 4 }1059      )1060  );10611062  it.effect(1063    "fails the read once four asks after the first were all rate limited",1064    () =>1065      within(1066        () =>1067          Effect.gen(function* () {1068            const repos = yield* RepoHost;1069            const name = RepoName.make("throttled");1070            const { first } = yield* seeded(name);1071            const read = yield* onTestClock(repos.readCommit(name, first));10721073            expect(Exit.hasDies(read)).toBeTruthy();1074          }),1075        { rateLimited: 5 }1076      )1077  );1078});