Skip to content
Myr

code.test.ts

This file

Path

packages/project/test/code.test.ts

1,257 lines · 38.1 KiB · TypeScript

Last changed by

Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { RepoHost } from "@repo/artifacts/repo-host";3import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4import { Brand } from "@repo/brand";5import { CommitDiff } from "@repo/protocol/domain/code";6import { CommitSha, LandedSha, RepoName, RepoPath } from "@repo/protocol/ids";7import {8  UnknownCommit,9  UnknownPath,10  UnknownRevision,11} from "@repo/protocol/refusal";12import {13  DateTime,14  Effect,15  Exit,16  Fiber,17  Layer,18  Option,19  Ref,20  Schema,21} from "effect";22import { TestClock } from "effect/testing";2324import { CodeStore } from "../src/code-store.ts";25import { CodeStoreCounts, CodeStoreMemory } from "../src/code-store/memory.ts";26import {27  commitOf,28  fileOf,29  logOf,30  pathsOf,31  refsOf,32  treeOf,33  whyOf,34} from "../src/code.ts";35import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";36import { commitKey, DIFF_TEXT } from "../src/code/commit.ts";37import { commitKept, objectKey } from "../src/code/objects.ts";38import { filesUnder } from "../src/code/paths.ts";39import { compareTags } from "../src/code/refs.ts";40import { READS_AT_ONCE } from "../src/code/tree.ts";41import {42  big,43  Content,44  datekit,45  fork,46  forked,47  linkedReadmes,48  longHistory,49  project,50  overlappingTrees,51  wide,52  writer,53} from "./code-fixtures.ts";5455const revision = (name: string) => Option.some(name);5657const main = Option.none();5859const path = (text: string) => Option.some(RepoPath.make(text));6061const page = { at: main, from: 0, limit: 30, path: Option.none() };6263// Hundreds of commits in memory: under a second alone, much longer beside other packages' tests.64const long = { timeout: 30_000 };6566describe("a project's refs", () => {67  it.effect(68    "are main's landed commit, its tags newest first and its forks, and nothing of the platform's own",69    () =>70      Effect.gen(function* () {71        const { c1, c2, c3, c4, code } = yield* datekit;7273        expect(yield* refsOf(code)).toStrictEqual({74          forks: [fork],75          landed: c4,76          project,77          tags: [78            { name: "v1.10.0", sha: c2 },79            { name: "v1.9.0", sha: c1 },80            { name: "@datekit/core@2.0.0", sha: c3 },81          ],82        });83      }).pipe(Effect.provide(RepoHostMemory))84  );8586  it("sort by version, newest first, each package's together", () => {87    expect(88      [89        "v1.9.0",90        "v1.10.0",91        "v1.10.0-beta.1",92        "v2.0.0",93        "@changesets/cli@2.27.1",94        "@changesets/cli@2.3.0",95        "@changesets/apply@1.0.0",96      ].toSorted(compareTags)97    ).toStrictEqual([98      "v2.0.0",99      "v1.10.0",100      "v1.10.0-beta.1",101      "v1.9.0",102      "@changesets/cli@2.27.1",103      "@changesets/cli@2.3.0",104      "@changesets/apply@1.0.0",105    ]);106  });107});108109describe("a folder", () => {110  it.effect(111    "lists folders first, then files by name, each by its kind, with its README",112    () =>113      Effect.gen(function* () {114        const { c4, code } = yield* datekit;115        const listing = yield* treeOf(code, main, Option.none());116117        expect(listing.at).toBe(c4);118        expect(listing.path).toBeUndefined();119        expect(120          listing.entries.map(({ name, path: at, type }) => [name, at, type])121        ).toStrictEqual([122          ["lib", "lib", "tree"],123          ["src", "src", "tree"],124          ["README.md", "README.md", "blob"],125          ["big.txt", "big.txt", "blob"],126          ["feed.xml", "feed.xml", "blob"],127          ["latest", "latest", "symlink"],128          ["logo.png", "logo.png", "blob"],129          ["logo.svg", "logo.svg", "blob"],130          ["new.txt", "new.txt", "blob"],131          ["page.html", "page.html", "blob"],132          ["vendor", "vendor", "submodule"],133        ]);134        expect({135          readme: listing.readme,136          vendor: listing.entries.find(({ name }) => name === "vendor"),137        }).toMatchObject({138          readme: {139            path: "README.md",140            sha: listing.entries.find(({ name }) => name === "README.md")?.sha,141          },142          vendor: { mode: "160000", sha: "a".repeat(40) },143        });144      }).pipe(Effect.provide(RepoHostMemory))145  );146147  it.effect("finds a lowercase readme.md before a README.txt", () =>148    Effect.gen(function* () {149      const { code } = yield* datekit;150      const listing = yield* treeOf(code, main, path("lib"));151152      expect(listing.path).toBe("lib");153      expect(listing.entries.map(({ path: at }) => at)).toStrictEqual([154        "lib/README.txt",155        "lib/readme.md",156      ]);157      expect(listing.readme?.path).toBe("lib/readme.md");158    }).pipe(Effect.provide(RepoHostMemory))159  );160161  it.effect(162    "follows a README that is a symlink to the file it names in the repo, and reads it there",163    () =>164      Effect.gen(function* () {165        const { code } = yield* linkedReadmes;166        const root = yield* treeOf(code, main, Option.none());167        const crate = yield* treeOf(code, main, path("crate"));168        const docs = yield* treeOf(code, main, path("docs"));169        const target = crate.entries.find(({ name }) => name === "README.md");170171        expect(172          root.entries.find(({ name }) => name === "README.md")?.type173        ).toBe("symlink");174        expect([root.readme, docs.readme]).toStrictEqual([175          { path: "crate/README.md", sha: target?.sha },176          { path: "crate/README.md", sha: target?.sha },177        ]);178      }).pipe(Effect.provide(RepoHostMemory))179  );180181  it.effect(182    "passes over a dangling README link to a readme file beside it",183    () =>184      Effect.gen(function* () {185        const { code } = yield* linkedReadmes;186        const listing = yield* treeOf(code, main, path("both"));187188        expect(listing.readme?.path).toBe("both/readme.md");189      }).pipe(Effect.provide(RepoHostMemory))190  );191192  it.effect(193    "has no README where its symlink leaves the repo, names nothing, names a folder, names another link, or is absolute",194    () =>195      Effect.gen(function* () {196        const { code } = yield* linkedReadmes;197198        const readmes = yield* Effect.forEach(199          ["out", "gone", "folder", "chain", "rooted"],200          (at) =>201            Effect.map(treeOf(code, main, path(at)), ({ readme }) =>202              Option.fromUndefinedOr(readme)203            )204        );205206        expect(readmes.every(Option.isNone)).toBeTruthy();207        expect(readmes).toHaveLength(5);208      }).pipe(Effect.provide(RepoHostMemory))209  );210211  it.effect("is UnknownPath when missing, or a file", () =>212    Effect.gen(function* () {213      const { c4, code } = yield* datekit;214215      expect(216        yield* Effect.exit(treeOf(code, main, path("nope")))217      ).toStrictEqual(218        Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("nope") }))219      );220      expect(221        yield* Effect.exit(treeOf(code, main, path("src/a.ts/x")))222      ).toStrictEqual(223        Exit.fail(224          new UnknownPath({ commit: c4, path: RepoPath.make("src/a.ts/x") })225        )226      );227      expect(228        yield* Effect.exit(treeOf(code, main, path("README.md")))229      ).toStrictEqual(230        Exit.fail(231          new UnknownPath({ commit: c4, path: RepoPath.make("README.md") })232        )233      );234    }).pipe(Effect.provide(RepoHostMemory))235  );236});237238describe("a revision", () => {239  it.effect(240    "is main, a commit the repo holds, or a tag by its exact name, peeled",241    () =>242      Effect.gen(function* () {243        const { c1, c2, c3, c4, code } = yield* datekit;244245        const resolved = (rev: string) =>246          Effect.map(247            treeOf(code, revision(rev), Option.none()),248            ({ at: sha }) => sha249          );250251        expect(252          yield* Effect.all([253            resolved("main"),254            resolved(c1),255            resolved("v1.9.0"),256            resolved("v1.10.0"),257            resolved("@datekit/core@2.0.0"),258          ])259        ).toStrictEqual([c4, c1, c1, c2, c3]);260      }).pipe(Effect.provide(RepoHostMemory))261  );262263  it.effect(264    "is UnknownRevision for anything else, a ref path or another branch included",265    () =>266      Effect.gen(function* () {267        const { code } = yield* datekit;268269        const refused = [270          "v9",271          "master",272          "../heads/master",273          "refs/heads/master",274          "refs/tags/v1.9.0",275          `${Brand.refsPrefix}landed`,276          "f".repeat(40),277          "HEAD",278        ];279280        expect(281          yield* Effect.forEach(refused, (rev) =>282            Effect.exit(treeOf(code, revision(rev), Option.none()))283          )284        ).toStrictEqual(285          refused.map((rev) => Exit.fail(new UnknownRevision({ rev })))286        );287      }).pipe(Effect.provide(RepoHostMemory))288  );289});290291describe("a fork", () => {292  it.effect(293    "is read at its address when the project lists it: its main, a branch by its exact name, or a commit it holds",294    () =>295      Effect.gen(function* () {296        const { answer, c4, code, tried } = yield* forked;297298        const resolved = (rev: string) =>299          Effect.map(300            treeOf(code, revision(rev), Option.none()),301            ({ at: sha }) => sha302          );303304        expect(305          yield* Effect.all([306            resolved("@bob/parse-iso"),307            resolved("@Bob/parse-iso"),308            resolved("@bob/parse-iso:main"),309            resolved("@bob/parse-iso:try"),310            resolved(`@bob/parse-iso:${c4}`),311          ])312        ).toStrictEqual([answer, answer, answer, tried, c4]);313      }).pipe(Effect.provide(RepoHostMemory))314  );315316  it.effect("lists the fork's own tree, not main's", () =>317    Effect.gen(function* () {318      const { code } = yield* forked;319      const src = yield* treeOf(code, revision("@bob/parse-iso"), path("src"));320321      expect(src.entries.map(({ path: at }) => at)).toStrictEqual([322        "src/a.ts",323        "src/parse.ts",324      ]);325    }).pipe(Effect.provide(RepoHostMemory))326  );327328  it.effect(329    "is UnknownRevision when the project does not list it, for a layer's repo, or for a ref path",330    () =>331      Effect.gen(function* () {332        const { answer, code, unlisted } = yield* forked;333334        const refused = [335          "@carol/parse-iso",336          "@layer/secrets",337          "@bob/layer",338          "@bob/other",339          "alice__datekit--layer--secrets",340          "alice__datekit--parse-iso--bob",341          "alice__datekit--parse-iso--carol",342          "@bob/parse-iso:",343          "@bob/parse-iso:missing",344          "@bob/parse-iso:refs/heads/try",345          "@bob/parse-iso:../heads/try",346          `@bob/parse-iso:${Brand.refsPrefix}landed`,347          `@bob/parse-iso:${unlisted}`,348          "@bob/parse-iso/try",349          "@bob",350          answer,351          unlisted,352        ];353354        expect(355          yield* Effect.forEach(refused, (rev) =>356            Effect.exit(treeOf(code, revision(rev), Option.none()))357          )358        ).toStrictEqual(359          refused.map((rev) => Exit.fail(new UnknownRevision({ rev })))360        );361      }).pipe(Effect.provide(RepoHostMemory))362  );363364  it.effect(365    "reads its files, paths, log, why and commits from the fork's repo",366    () =>367      Effect.gen(function* () {368        const { answer, code } = yield* forked;369        const at = revision("@bob/parse-iso");370        const parse = RepoPath.make("src/parse.ts");371        const file = yield* fileOf(code, at, parse);372        const paths = yield* pathsOf(code, at);373        const log = yield* logOf(code, { ...page, at, path: path("src") });374        const why = yield* whyOf(code, at, parse);375        const diff = yield* commitOf(code, answer, at);376377        expect([file.text, paths.paths.includes(parse)]).toStrictEqual([378          "export const parse = Date.parse;\n",379          true,380        ]);381        expect(log.commits.map(({ subject }) => subject)).toStrictEqual([382          "Parse ISO dates",383          "Rework a",384          "Start",385        ]);386        expect(why.commits.map(({ sha }) => sha)).toStrictEqual([answer]);387        expect(diff.files.map(({ path: changed }) => changed)).toStrictEqual([388          "src/parse.ts",389        ]);390        expect(yield* Effect.exit(commitOf(code, answer))).toStrictEqual(391          Exit.fail(new UnknownCommit({ sha: answer }))392        );393      }).pipe(Effect.provide(RepoHostMemory))394  );395396  it.effect(397    "reads a commit only at a revision every other read resolves: nonsense, an unlisted fork and a fork's repo name are UnknownRevision",398    () =>399      Effect.gen(function* () {400        const { answer, code } = yield* forked;401402        const refused = [403          "nonsense",404          "@carol/parse-iso",405          "alice__datekit--parse-iso--bob",406        ];407408        expect(409          yield* Effect.forEach(refused, (rev) =>410            Effect.exit(commitOf(code, answer, revision(rev)))411          )412        ).toStrictEqual(413          refused.map((rev) => Exit.fail(new UnknownRevision({ rev })))414        );415      }).pipe(Effect.provide(RepoHostMemory))416  );417418  it.effect(419    "is kept in the code store under no key, and cached under the fork's repo alone",420    () =>421      Effect.gen(function* () {422        const keys = yield* Ref.make<readonly string[]>([]);423424        const recording = Layer.succeed(CodeCache, {425          through: (key, read) =>426            Ref.update(keys, (all) => [...all, key]).pipe(Effect.andThen(read)),427        });428429        const counts = yield* Effect.gen(function* () {430          const { answer, code } = yield* forked;431          const at = revision("@bob/parse-iso");432          const parse = RepoPath.make("src/parse.ts");433434          yield* treeOf(code, at, Option.none());435          yield* fileOf(code, at, parse);436          yield* logOf(code, { ...page, at, path: path("src") });437          yield* whyOf(code, at, parse);438          yield* commitOf(code, answer, at);439440          return yield* (yield* CodeStoreCounts).counts;441        }).pipe(442          Effect.provide(443            Layer.mergeAll(RepoHostMemory, CodeStoreMemory, recording)444          )445        );446447        const all = yield* Ref.get(keys);448449        expect(counts).toStrictEqual({ gets: 0, puts: 0 });450        expect(all.length).toBeGreaterThan(0);451        expect(452          all.filter((key) => key.split(/[:/]/u)[0] !== fork.repo)453        ).toStrictEqual([]);454      })455  );456});457458describe("a file", () => {459  it.effect("is its text, with its blob id and size", () =>460    Effect.gen(function* () {461      const { c4, code } = yield* datekit;462      const listing = yield* treeOf(code, main, Option.none());463464      expect(465        yield* fileOf(code, main, RepoPath.make("README.md"))466      ).toStrictEqual({467        at: c4,468        binary: false,469        path: "README.md",470        sha: listing.readme?.sha,471        size: 18,472        text: "# datekit, landed\n",473        truncated: false,474      });475    }).pipe(Effect.provide(RepoHostMemory))476  );477478  it.effect("past 1 MiB is truncated, with no text", () =>479    Effect.gen(function* () {480      const { code } = yield* datekit;481      const file = yield* fileOf(code, main, RepoPath.make("big.txt"));482483      expect(file).toMatchObject({484        binary: false,485        size: big.length,486        truncated: true,487      });488      expect(file.text).toBeUndefined();489    }).pipe(Effect.provide(RepoHostMemory))490  );491492  it.effect("with a NUL among its first bytes is binary, with no text", () =>493    Effect.gen(function* () {494      const { code } = yield* datekit;495      const file = yield* fileOf(code, main, RepoPath.make("logo.png"));496497      expect(file).toMatchObject({ binary: true, size: 12, truncated: false });498      expect(file.text).toBeUndefined();499    }).pipe(Effect.provide(RepoHostMemory))500  );501502  it.effect("is UnknownPath for a folder or a missing path", () =>503    Effect.gen(function* () {504      const { c4, code } = yield* datekit;505506      expect(507        yield* Effect.exit(fileOf(code, main, RepoPath.make("src")))508      ).toStrictEqual(509        Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("src") }))510      );511      expect(512        yield* Effect.exit(fileOf(code, main, RepoPath.make("src/b.ts")))513      ).toStrictEqual(514        Exit.fail(515          new UnknownPath({ commit: c4, path: RepoPath.make("src/b.ts") })516        )517      );518    }).pipe(Effect.provide(RepoHostMemory))519  );520});521522describe("every path", () => {523  it.effect("lists each file, symlink and submodule at the revision", () =>524    Effect.gen(function* () {525      const { c1, code } = yield* datekit;526527      expect(yield* pathsOf(code, revision(c1))).toStrictEqual({528        at: c1,529        paths: [530          "README.md",531          "big.txt",532          "feed.xml",533          "latest",534          "lib/README.txt",535          "lib/readme.md",536          "logo.png",537          "logo.svg",538          "old.txt",539          "page.html",540          "src/a.ts",541          "vendor",542        ],543        truncated: false,544      });545    }).pipe(Effect.provide(RepoHostMemory))546  );547});548549describe("every path past the cap", () => {550  it.effect(551    "is the first by path among the folders read before the cap, truncated",552    () =>553      Effect.gen(function* () {554        const { c1, code } = yield* datekit;555        const host = yield* RepoHost;556        const commit = yield* host.readCommit(code.repo, c1);557        const { tree } = Option.getOrThrow(commit);558        const capped = yield* filesUnder(code.repo, tree, 3);559560        // The root alone holds nine files, so no folder below it is read.561        expect({562          paths: capped.files.map(({ path: at }) => at),563          truncated: capped.truncated,564        }).toStrictEqual({565          paths: ["README.md", "big.txt", "feed.xml"],566          truncated: true,567        });568        expect((yield* filesUnder(code.repo, tree, 12)).truncated).toBeFalsy();569      }).pipe(Effect.provide(RepoHostMemory))570  );571});572573describe("the log", () => {574  it.effect(575    "is first parents from the revision, each landing with the platform's record and no other",576    () =>577      Effect.gen(function* () {578        const { c1, c2, c3, c4, code } = yield* datekit;579        const { commits, next } = yield* logOf(code, page);580581        expect(next).toBeUndefined();582        expect(commits.map(({ sha }) => sha)).toStrictEqual([c4, c3, c2, c1]);583584        const [landed, imported] = commits;585586        expect(landed?.landing).toMatchObject({ ask: "parse-iso", sha: c4 });587        expect(imported?.landing).toBeUndefined();588        expect(589          Option.map(Option.fromUndefinedOr(imported), (commit) => ({590            at: DateTime.formatIso(commit.author.at),591            email: commit.author.email,592            name: commit.author.name,593            parents: commit.parents,594            subject: commit.subject,595            trailers: commit.trailers,596          }))597        ).toStrictEqual(598          Option.some({599            at: "2026-10-01T00:00:03.000Z",600            email: "writer@example.com",601            name: "Writer",602            parents: [c2],603            subject: "Tidy the readme",604            trailers: [605              { key: "Asked-by", value: "mallory <mallory@example.com>" },606            ],607          })608        );609      }).pipe(Effect.provide(RepoHostMemory))610  );611612  it.effect(613    "pages 30 at a time, naming where the next page starts",614    () =>615      Effect.gen(function* () {616        const { code, shas } = yield* longHistory(250);617        const first = yield* logOf(code, page);618619        expect(first.commits).toHaveLength(30);620        expect(first.commits[0]?.sha).toBe(shas[249]);621        expect(first.next).toBe(30);622623        const last = yield* logOf(code, { ...page, from: 240 });624625        expect(last.commits.map(({ sha }) => sha)).toStrictEqual(626          shas.slice(0, 10).toReversed()627        );628        expect(last.next).toBeUndefined();629      }).pipe(Effect.provide(RepoHostMemory)),630    long631  );632633  it.effect(634    "for a path, keeps only the commits that changed it, scanning at most 200 a call",635    () =>636      Effect.gen(function* () {637        const { code, shas } = yield* longHistory(250);638        const once = { ...page, path: path("once.txt") };639        const scanned = yield* logOf(code, once);640641        expect(scanned).toStrictEqual({ commits: [], next: 200 });642643        const older = yield* logOf(code, { ...once, from: 200 });644645        expect(older.commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);646        expect(older.next).toBeUndefined();647648        const counted = yield* logOf(code, {649          ...page,650          limit: 3,651          path: path("count.txt"),652        });653654        expect(counted.commits.map(({ sha }) => sha)).toStrictEqual(655          shas.slice(247).toReversed()656        );657        expect(counted.next).toBe(3);658      }).pipe(Effect.provide(RepoHostMemory)),659    long660  );661});662663describe("a path's log, read live", () => {664  it.live(665    "reads the file in its commits several at a time, not one after another",666    () =>667      Effect.gen(function* () {668        const reading = yield* Ref.make(false);669        const peak = yield* Ref.make(0);670671        yield* Effect.gen(function* () {672          const { code, shas } = yield* longHistory(64);673674          yield* Ref.set(reading, true);675676          const { commits } = yield* logOf(code, {677            ...page,678            path: path("once.txt"),679          });680681          expect(commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);682        }).pipe(Effect.provide(overlappingTrees(reading, peak, "file")));683684        // 64 commits, the file read whole in each, `READS_AT_ONCE` at a time.685        expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);686        expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE);687      }),688    long689  );690});691692describe("a commit", () => {693  it.effect("at the root adds every file", () =>694    Effect.gen(function* () {695      const { c1, code } = yield* datekit;696      const diff = yield* commitOf(code, c1);697698      expect([diff.commit.sha, diff.truncated]).toStrictEqual([c1, false]);699      expect(700        diff.files.map(({ path: at, status }) => [at, status])701      ).toStrictEqual(702        (yield* pathsOf(code, revision(c1))).paths.map((at) => [at, "added"])703      );704      expect(705        diff.files.find(({ path: at }) => at === "src/a.ts")706      ).toMatchObject({ binary: false, newText: "export const a = 1;\n" });707708      const logo = diff.files.find(({ path: at }) => at === "logo.png");709710      expect([logo?.binary, logo?.newText]).toStrictEqual([true, undefined]);711    }).pipe(Effect.provide(RepoHostMemory))712  );713714  it.effect(715    "after it shows each change against the first parent, with both blob ids",716    () =>717      Effect.gen(function* () {718        const { c2, code } = yield* datekit;719        const diff = yield* commitOf(code, c2);720721        expect(722          diff.files.map(({ before, after, path: at, status }) => [723            at,724            status,725            before !== undefined,726            after !== undefined,727          ])728        ).toStrictEqual([729          ["new.txt", "added", false, true],730          ["old.txt", "deleted", true, false],731          ["src/a.ts", "modified", true, true],732        ]);733        expect(734          diff.files.find(({ path: at }) => at === "src/a.ts")735        ).toMatchObject({736          newText: "export const a = 2;\n",737          oldText: "export const a = 1;\n",738        });739        expect(diff.commit.landing).toBeUndefined();740      }).pipe(Effect.provide(RepoHostMemory))741  );742743  it.effect(744    "past 300 files lists paths only, truncated",745    () =>746      Effect.gen(function* () {747        const { code, sha } = yield* wide(301);748        const diff = yield* commitOf(code, sha);749750        expect([diff.truncated, diff.files.length]).toStrictEqual([true, 301]);751        expect(752          diff.files.filter(753            ({ newText, oldText }) =>754              newText !== undefined || oldText !== undefined755          )756        ).toStrictEqual([]);757      }).pipe(Effect.provide(RepoHostMemory)),758    long759  );760761  it.effect("the repo does not hold is UnknownCommit", () =>762    Effect.gen(function* () {763      const { code } = yield* datekit;764      const missing = CommitSha.make("f".repeat(40));765766      expect(yield* Effect.exit(commitOf(code, missing))).toStrictEqual(767        Exit.fail(new UnknownCommit({ sha: missing }))768      );769    }).pipe(Effect.provide(RepoHostMemory))770  );771});772773/** 150 KiB of text: fourteen of them run past a diff's 2 MiB of text. */774const sizable = (name: string) => `${name.padEnd(1023, "y")}\n`.repeat(150);775776const twentyFiles = Effect.gen(function* () {777  const git = yield* writer;778  const name = RepoName.make("twentykit");779780  const paths = Array.from(781    { length: 20 },782    (_, at) => `f${String(at).padStart(2, "0")}.txt`783  );784785  const before = yield* git.commit(786    "Small",787    paths.map((at) => [at, Content.Text({ text: `${at}\n` })] as const),788    [],789    1790  );791792  const after = yield* git.commit(793    "Large",794    paths.map(795      (at) =>796        [797          at,798          Content.Text({799            text: at === "f14.txt" ? "small\n" : sizable(at),800          }),801        ] as const802    ),803    [before],804    2805  );806807  yield* git.push(name, [["refs/heads/main", after]]);808809  return {810    after,811    code: {812      forks: Effect.succeed([]),813      head: Effect.succeedNone,814      landings: () => Effect.succeed([]),815      project,816      repo: name,817    },818    paths,819  };820});821822describe("a commit's texts, read live", () => {823  it.live(824    "are read several at a time, and cut at the budget in path order as one after another would",825    () =>826      Effect.gen(function* () {827        const reading = yield* Ref.make(false);828        const peak = yield* Ref.make(0);829830        const { diff, paths } = yield* Effect.gen(function* () {831          const made = yield* twentyFiles;832833          yield* Ref.set(reading, true);834835          return {836            diff: yield* commitOf(made.code, made.after),837            paths: made.paths,838          };839        }).pipe(Effect.provide(overlappingTrees(reading, peak, "blob")));840841        const most = yield* Ref.get(peak);842843        // Thirteen files' texts fit the budget, and a fourteenth does not.844        expect([845          13 * sizable("f00.txt").length <= DIFF_TEXT,846          14 * sizable("f00.txt").length > DIFF_TEXT,847        ]).toStrictEqual([true, true]);848        expect({849          files: diff.files.map(({ newText, oldText, path: at, status }) => [850            at,851            status,852            oldText,853            newText,854          ]),855          truncated: diff.truncated,856        }).toStrictEqual({857          files: paths.map((at, index) =>858            index < 13859              ? [at, "modified", `${at}\n`, sizable(at)]860              : [at, "modified", undefined, undefined]861          ),862          truncated: true,863        });864        // Several at once, never past the fan-out of 8.865        expect([most > 1, most <= 8]).toStrictEqual([true, true]);866      }),867    long868  );869});870871const blobsCountedBy = (reads: Ref.Ref<number>) =>872  Layer.effect(873    RepoHost,874    Effect.gen(function* () {875      const host = yield* RepoHost;876877      return RepoHost.of({878        ...host,879        readBlob: (name, blob) =>880          Ref.update(reads, (count) => count + 1).pipe(881            Effect.andThen(host.readBlob(name, blob))882          ),883      });884    })885  ).pipe(Layer.provide(RepoHostMemory));886887const keptUnder = (key: string) =>888  Effect.map(889    Effect.flatMap(Effect.service(CodeStore), (store) => store.get(key)),890    Option.flatMap(891      Schema.decodeUnknownOption(Schema.fromJsonString(CommitDiff))892    )893  );894895describe("a commit kept by its id", () => {896  it.effect(897    "is kept without its landing, read again with no blob read, and its landing still asked for",898    () =>899      Effect.gen(function* () {900        const blobs = yield* Ref.make(0);901        const asked = yield* Ref.make<readonly (readonly CommitSha[])[]>([]);902903        yield* Effect.gen(function* () {904          const { c4, code } = yield* datekit;905906          const counted = {907            ...code,908            landings: (shas: readonly CommitSha[]) =>909              Ref.update(asked, (all) => [...all, shas]).pipe(910                Effect.andThen(code.landings(shas))911              ),912          };913914          const first = yield* commitOf(counted, c4);915          const read = yield* Ref.get(blobs);916917          expect([first.commit.landing?.sha, read > 0]).toStrictEqual([918            c4,919            true,920          ]);921922          const kept = yield* keptUnder(commitKey(code.repo, c4));923924          // Kept with no landing: the rest is the diff as it was answered.925          expect(926            Option.map(kept, (decoded) => ({927              kept: decoded.commit.landing,928              restored: {929                ...decoded,930                commit: { ...decoded.commit, landing: first.commit.landing },931              },932            }))933          ).toStrictEqual(Option.some({ kept: undefined, restored: first }));934935          const second = yield* commitOf(counted, c4);936937          expect({938            asked: yield* Ref.get(asked),939            blobs: yield* Ref.get(blobs),940            second,941          }).toStrictEqual({ asked: [[c4], [c4]], blobs: read, second: first });942        }).pipe(943          Effect.provide(Layer.merge(blobsCountedBy(blobs), CodeStoreMemory))944        );945      })946  );947948  it.effect("is computed again when what is kept no longer decodes", () =>949    Effect.gen(function* () {950      const blobs = yield* Ref.make(0);951952      yield* Effect.gen(function* () {953        const { c2, code } = yield* datekit;954        const store = yield* CodeStore;955        const key = commitKey(code.repo, c2);956957        const fresh = yield* commitOf(code, c2).pipe(958          Effect.provideService(CodeStore, CodeStore.defaultValue())959        );960961        const read = yield* Ref.get(blobs);962963        yield* store.put(key, '{"files":"no longer a diff"}');964965        expect(yield* commitOf(code, c2)).toStrictEqual(fresh);966        expect(yield* Ref.get(blobs)).toBe(2 * read);967        expect(yield* keptUnder(key)).toStrictEqual(Option.some(fresh));968      }).pipe(969        Effect.provide(Layer.merge(blobsCountedBy(blobs), CodeStoreMemory))970      );971    })972  );973});974975const countedBy = (reads: Ref.Ref<readonly string[]>) =>976  Layer.effect(977    RepoHost,978    Effect.gen(function* () {979      const host = yield* RepoHost;980981      return RepoHost.of({982        ...host,983        readTree: (name, tree) =>984          Ref.update(reads, (all) => [...all, tree]).pipe(985            Effect.andThen(host.readTree(name, tree))986          ),987      });988    })989  ).pipe(Layer.provide(RepoHostMemory));990991describe("reads by object id", () => {992  it.effect("are kept once read, while main resolves every time", () =>993    Effect.gen(function* () {994      const reads = yield* Ref.make<readonly string[]>([]);995996      yield* Effect.gen(function* () {997        const { code } = yield* datekit;998        const first = yield* treeOf(code, main, Option.none());999        const counted = (yield* Ref.get(reads)).length;10001001        expect(counted).toBeGreaterThan(0);10021003        const again = yield* treeOf(code, main, Option.none());10041005        expect(again).toStrictEqual(first);1006        expect(yield* Ref.get(reads)).toHaveLength(counted);1007      }).pipe(1008        Effect.provide(Layer.merge(countedBy(reads), CodeCacheLive(100)))1009      );1010    })1011  );10121013  it.effect("keep heavy reads apart, so many texts never push out a tree", () =>1014    Effect.gen(function* () {1015      const cache = yield* CodeCache;1016      const reads = yield* Ref.make<readonly string[]>([]);10171018      const read = (key: string, heavy: boolean) =>1019        cache.through(1020          key,1021          Ref.update(reads, (all) => [...all, key]),1022          { heavy }1023        );10241025      yield* read("datekit:tree:t", false);1026      yield* read("datekit:text:1", true);1027      yield* read("datekit:text:2", true);1028      yield* read("datekit:tree:t", false);1029      yield* read("datekit:text:2", true);1030      yield* read("datekit:text:1", true);10311032      expect(yield* Ref.get(reads)).toStrictEqual([1033        "datekit:tree:t",1034        "datekit:text:1",1035        "datekit:text:2",1036        "datekit:text:1",1037      ]);1038    }).pipe(Effect.provide(CodeCacheLive(2, 1)))1039  );10401041  it.effect(1042    "never make a caller wait on a read another caller left unfinished",1043    () =>1044      Effect.gen(function* () {1045        // A Worker whose client goes away is cancelled without interrupting its1046        // fibers, so a read it began never ends: the next request must read for itself.1047        const cache = yield* CodeCache;10481049        yield* Effect.forkDetach(1050          cache.through("burrow:text:abandoned", Effect.never)1051        );10521053        yield* Effect.yieldNow;10541055        const next = yield* cache1056          .through("burrow:text:abandoned", Effect.succeed("read"))1057          .pipe(Effect.timeoutOption("1 second"), Effect.forkChild);10581059        yield* TestClock.adjust("1 second");10601061        expect(yield* Fiber.join(next)).toStrictEqual(Option.some("read"));1062      }).pipe(Effect.provide(CodeCacheLive(10, 10)))1063  );1064});10651066const countedIn =1067  (reads: Ref.Ref<number>) =>1068  <A, E>(read: Effect.Effect<A, E>) =>1069    Ref.update(reads, (count) => count + 1).pipe(Effect.andThen(read));10701071const hostCountedBy = (reads: Ref.Ref<number>) =>1072  Layer.effect(1073    RepoHost,1074    Effect.gen(function* () {1075      const host = yield* RepoHost;1076      const counted = countedIn(reads);10771078      return RepoHost.of({1079        ...host,1080        log: (name, at, limit, offset) =>1081          counted(host.log(name, at, limit, offset)),1082        readBlob: (name, blob) => counted(host.readBlob(name, blob)),1083        readCommit: (name, sha) => counted(host.readCommit(name, sha)),1084        readFile: (name, at, file) => counted(host.readFile(name, at, file)),1085        readTree: (name, tree) => counted(host.readTree(name, tree)),1086      });1087    })1088  ).pipe(Layer.provide(RepoHostMemory));10891090const onIsolate = <A, E, R>(effect: Effect.Effect<A, E, R>) =>1091  Effect.provide(effect, CodeCacheLive(100));10921093const byText = (one: string, other: string) => one.localeCompare(other);10941095const readme = RepoPath.make("README.md");10961097describe("objects kept across isolates", () => {1098  it.effect(1099    "answer a folder, a file, a log page and a commit on a second isolate from the store, reaching the host no more",1100    () =>1101      Effect.gen(function* () {1102        const reads = yield* Ref.make(0);11031104        yield* Effect.gen(function* () {1105          const { c4, code } = yield* datekit;11061107          const views = Effect.all([1108            treeOf(code, main, Option.none()),1109            treeOf(code, main, path("src")),1110            fileOf(code, main, readme),1111            logOf(code, page),1112            commitOf(code, c4),1113          ]);11141115          const first = yield* onIsolate(views);1116          const counted = yield* Ref.get(reads);11171118          expect(counted).toBeGreaterThan(0);11191120          const again = yield* onIsolate(views);11211122          expect(again).toStrictEqual(first);1123          expect(yield* Ref.get(reads)).toBe(counted);1124        }).pipe(1125          Effect.provide(Layer.merge(hostCountedBy(reads), CodeStoreMemory))1126        );1127      })1128  );11291130  it.effect(1131    "leave main resolved every time: a landing between two reads shows in the second, store and isolate warm",1132    () =>1133      Effect.gen(function* () {1134        const { c3, c4, code } = yield* datekit;1135        const head = yield* Ref.make(Option.some(LandedSha.make(c3)));1136        const asked = yield* Ref.make(0);11371138        const moving = {1139          ...code,1140          head: Ref.update(asked, (count) => count + 1).pipe(1141            Effect.andThen(Ref.get(head))1142          ),1143        };11441145        const before = yield* treeOf(moving, main, Option.none());11461147        yield* Ref.set(head, Option.some(LandedSha.make(c4)));11481149        const after = yield* treeOf(moving, main, Option.none());11501151        expect([before.at, after.at, yield* Ref.get(asked)]).toStrictEqual([1152          c3,1153          c4,1154          2,1155        ]);1156      }).pipe(1157        Effect.provide(1158          Layer.mergeAll(RepoHostMemory, CodeStoreMemory, CodeCacheLive(100))1159        )1160      )1161  );11621163  it.effect(1164    "read again a kept object that no longer decodes, or that names another id, and replace it",1165    () =>1166      Effect.gen(function* () {1167        const reads = yield* Ref.make(0);11681169        yield* Effect.gen(function* () {1170          const { c3, c4, code } = yield* datekit;1171          const store = yield* CodeStore;1172          const key = objectKey(commitKept, code.repo, c4);11731174          const fresh = yield* onIsolate(treeOf(code, main, Option.none()));11751176          yield* onIsolate(treeOf(code, revision(c3), Option.none()));11771178          const kept = yield* store.get(key);11791180          const other = yield* store.get(objectKey(commitKept, code.repo, c3));11811182          expect([Option.isSome(kept), Option.isSome(other)]).toStrictEqual([1183            true,1184            true,1185          ]);11861187          for (const planted of [1188            '{"sha":"not a commit"}',1189            Option.getOrElse(other, () => ""),1190          ]) {1191            yield* store.put(key, planted);1192            yield* Ref.set(reads, 0);11931194            expect(1195              yield* onIsolate(treeOf(code, main, Option.none()))1196            ).toStrictEqual(fresh);1197            expect(yield* Ref.get(reads)).toBeGreaterThan(0);1198            expect(yield* store.get(key)).toStrictEqual(kept);1199          }1200        }).pipe(1201          Effect.provide(Layer.merge(hostCountedBy(reads), CodeStoreMemory))1202        );1203      })1204  );12051206  it.effect(1207    "are keyed under the project's own repo by kind, version and id, and hold no landing",1208    () =>1209      Effect.gen(function* () {1210        const kept = yield* Ref.make<ReadonlyMap<string, string>>(new Map());12111212        const recording = Layer.succeed(CodeStore, {1213          get: (key) =>1214            Effect.map(Ref.get(kept), (all) =>1215              Option.fromUndefinedOr(all.get(key))1216            ),1217          put: (key, value) =>1218            Ref.update(kept, (all) => new Map([...all, [key, value]])),1219        });12201221        const repo = yield* Effect.gen(function* () {1222          const { c4, code } = yield* datekit;12231224          yield* treeOf(code, main, Option.none());1225          yield* fileOf(code, main, readme);1226          yield* logOf(code, page);1227          yield* commitOf(code, c4);12281229          return code.repo;1230        }).pipe(Effect.provide(Layer.merge(RepoHostMemory, recording)));12311232        const all = [...(yield* Ref.get(kept))];12331234        const ownKey = new RegExp(1235          `^${repo}/(blob|commit|commit-object|file|log|tree)/v[1-9]\\d*/`,1236          "u"1237        );12381239        expect(all.filter(([key]) => !ownKey.test(key))).toStrictEqual([]);1240        expect(1241          [...new Set(all.map(([key]) => key.split("/").at(1) ?? ""))].toSorted(1242            byText1243          )1244        ).toStrictEqual([1245          "blob",1246          "commit",1247          "commit-object",1248          "file",1249          "log",1250          "tree",1251        ]);1252        expect(1253          all.filter(([, value]) => value.includes("landedAt"))1254        ).toStrictEqual([]);1255      })1256  );1257});