Skip to content
Myr

Merge build/1003

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 1a364b9, 81a3dda · Browse files · 12 files+1813 added−213 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+1813 added−213 removed

  • tests:+813 added−8 removed
  • other:+1000 added−205 removed

12 files+1813 added−213 removed

modified:packages/artifacts/src/repo-host/binding.ts+64 added-13 removed
8 unmodified lines
9 * second 500 after that may be the fork the first made: it is, if it lists10 * `main`;11 * - reads name a branch by its short name and a commit by its id, never12 * `refs/…`, so `refs` and `push` go over git smart HTTP instead;13 * - a busy receive-pack is `HostBusy`.13 * - a busy receive-pack is `HostBusy`;14 * - a call refused for Artifacts' rate limit (2,000 requests per 10 s per15 * repo) is asked again from 250 ms apart, doubling, at most four more16 * times; past that it fails as the call's own failure would.17 *18 * Refs and pushes use a token the adapter mints for the one call and revokes19 * after it; the token goes nowhere but the `Authorization` header of the20 * adapter's own requests. The day-long write token a create, a fork or an21 * import hands back is revoked at once: any write token can force-push22 * `main`, and no caller needs it. A repo still being23 * created is asked for again, from 250 ms apart, up to seven more times24 * (about 32 s); one still being imported up to sixteen (about 3 minutes),22 * each sleep at most 16 s. Every repo handle is disposed after use.25 * each sleep at most 16 s. Every repo handle is disposed after use: after26 * each read, or, for reads in one `RepoSession`, once when the session27 * ends, so a view's many reads ask `get` for one handle.28 */29import {30 Data,31 DateTime,
16 unmodified lines
48 RefName,49 RepoExists,50 RepoHost,51 RepoNotFound,52 RepoSession,53 TreeEntry,54} from "../repo-host.ts";55import type {56 RepoName,
36 unmodified lines
93class MaybeForked extends Data.TaggedError("MaybeForked")<{94 readonly thrown: Thrown;95}> {}9691/** A promise of the binding's, failing with what it threw, read. */97/**98 * How Artifacts words a refusal for its rate limit. ASSUMPTION: none has99 * been seen live and its error codes list none, so it is read from a code100 * or a message that names the limit, as an HTTP 429's "Too Many Requests"101 * does.102 */103const RATE_LIMITED = /rate[ _-]?limit|too[ _-]many[ _-]requests/iu;104105const isRateLimited = ({ error, message }: Thrown) =>106 RATE_LIMITED.test(message) ||107 (Predicate.hasProperty(error, "code") &&108 Predicate.isString(error.code) &&109 RATE_LIMITED.test(error.code));110111/** From 250 ms apart, doubling, four more asks while the limit refuses. */112const whileLimited = Schedule.exponential(Duration.millis(250)).pipe(113 Schedule.setInputType<Thrown>(),114 Schedule.while(115 ({ attempt: asked, input }) => asked <= 4 && isRateLimited(input)116 )117);118119/**120 * A promise of the binding's, failing with what it threw, read; asked121 * again while Artifacts' rate limit refuses it.122 */123const attempt = <A>(run: () => Promise<A>) =>124 Effect.tryPromise({125 catch: (error) => {126 const message = error instanceof Error ? error.message : String(error);
7 unmodified lines
134135 return new Thrown({ code, error, message });136 },137 try: run,107 });138 }).pipe(Effect.retry(whileLimited));139140const threw =141 (code: Code) =>142 (thrown: Thrown): boolean =>
118 unmodified lines
261 Effect.retry(whileMaking),262 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))263 );264265/** Gives a handle back: the binding's handles are RPC stubs. */266const disposeOf = (repo: ArtifactsRepo) =>267 Effect.sync(() => {268 repo[Symbol.dispose]();269 });270271/** `use` over a handle to `name`, disposed after, whatever `use` came to. */272const withRepo = <A, E, R>(273 binding: Artifacts,274 name: RepoName,275 use: (repo: ArtifactsRepo) => Effect.Effect<A, E, R>276) =>277 Effect.scoped(241 Effect.acquireRelease(handleOf(binding, name), (repo) =>242 Effect.sync(() => {243 repo[Symbol.dispose]();244 })245 ).pipe(Effect.flatMap(use))278 Effect.acquireRelease(handleOf(binding, name), disposeOf).pipe(279 Effect.flatMap(use)280 )281 );282283/**284 * The repo `made` names, its initial write token revoked: nothing the
230 unmodified lines
515 // The service alone: the layer's whole context would carry its Scope, and516 // every call's finalizers would wait for the layer's end.517 const fetch = yield* Fetch;518484 /** A read of `name`'s, failing only with `RepoNotFound`. */519 /**520 * A read of `name`'s, failing only with `RepoNotFound`: over the521 * session's handle to `name` when the read runs in a `RepoSession`,522 * else over a handle of its own.523 */524 const read = <A>(525 name: RepoName,526 use: (527 repo: ArtifactsRepo528 ) => Effect.Effect<A, RepoNotFound | RepoExists | ForkInProgress, Fetch>529 ) =>491 onlyNotFound(withRepo(binding, name, use)).pipe(492 Effect.provideService(Fetch, fetch)493 );530 Effect.gen(function* () {531 const session = yield* RepoSession;532533 return yield* Option.match(session, {534 onNone: () => withRepo(binding, name, use),535 onSome: ({ hold }) =>536 Effect.flatMap(537 hold(538 `binding:${name}`,539 Effect.acquireRelease(handleOf(binding, name), disposeOf)540 ),541 use542 ),543 });544 }).pipe(onlyNotFound, Effect.provideService(Fetch, fetch));545546 return RepoHost.of({547 create: (name) =>548 call(name, () => binding.create(name)).pipe(549 Effect.flatMap((made) => withoutToken(binding, made, name)),
94 unmodified lines
modified:packages/artifacts/src/repo-host.ts+80 added-6 removed
1import { CommitSha, RepoName } from "@repo/protocol/ids";2import type { RepoPath } from "@repo/protocol/ids";3import { Context, Data, Schema } from "effect";4import type {5 Array,6 DateTime,7 Duration,3import {4 Context,5 Data,6 Effect,7 Option,10 Redacted,8 Schema,9 Scope,10 Semaphore,11} from "effect";12import type { Array, DateTime, Duration, Redacted } from "effect";13import type { FsClient } from "isomorphic-git";1415/** A repo's name in its namespace: the one `RepoName`, from the domain. */16export { RepoName } from "@repo/protocol/ids";
221 unmodified lines
238 updates: Array.NonEmptyReadonlyArray<RefUpdate>239 ) => Effect.Effect<readonly RefOutcome[], RepoNotFound | HostBusy>;240 }241>()("artifacts/RepoHost") {}242243/**244 * What the reads of one session may share: a host keeps what it opens on a245 * repo (the binding's handle) under `key` until the session ends, rather246 * than opening and closing it for each read. One opening at a time, and247 * only a finished value is kept, so no read waits on another's opening248 * past its own session.249 */250export interface RepoSessionApi {251 readonly hold: <A, E>(252 key: string,253 open: Effect.Effect<A, E, Scope.Scope>254 ) => Effect.Effect<A, E>;255}256257/**258 * The session reads run in, if any. A `Context.Reference` whose default is259 * none, so each read opens and closes what it needs, as a host without a260 * session does. It lives in one request's context, never in an isolate's261 * state: a Worker whose client goes away is cancelled where it stands, so262 * nothing a request holds may outlive it.263 */264export const RepoSession = Context.Reference<Option.Option<RepoSessionApi>>(265 "artifacts/RepoSession",266 { defaultValue: Option.none }267);268269/**270 * `effect` with its reads in one session: what a host holds for them is271 * released when `effect` ends, whatever it came to. Inside a session272 * already, `effect` joins it, so a view whose parts each ask for a273 * session still reads over one handle.274 */275export const inRepoSession = <A, E, R>(276 effect: Effect.Effect<A, E, R>277): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>278 Effect.scoped(279 Effect.gen(function* () {280 if (Option.isSome(yield* RepoSession)) {281 return yield* effect;282 }283284 const scope = yield* Effect.scope;285 const opening = yield* Semaphore.make(1);286 const held = new Map<string, unknown>();287288 const session: RepoSessionApi = {289 hold: <B, F>(key: string, open: Effect.Effect<B, F, Scope.Scope>) =>290 opening.withPermits(1)(291 Effect.suspend(() => {292 if (held.has(key)) {293 // SAFETY: each key names one kind of value, which a caller294 // opens with one effect, so what it holds is a `B`.295 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one session holds every kind of value, so its map is typed `unknown`; see SAFETY.296 return Effect.succeed(held.get(key) as B);297 }298299 return Effect.tap(Scope.provide(open, scope), (value) =>300 Effect.sync(() => {301 held.set(key, value);302 })303 );304 })305 ),306 };307308 return yield* Effect.provideService(309 effect,310 RepoSession,311 Option.some(session)312 );313 })314 );
modified:packages/artifacts/test/binding.test.ts+101 added
28 unmodified lines
29import {30 BranchName,31 ForkInProgress,32 HostBusy,33 inRepoSession,34 ObjectId,35 RefName,36 RefOutcome,37 RepoExists,
962 unmodified lines
1000 { importing: 40 }1001 )1002 );1003});10041005describe("reads in one session, and Artifacts' rate limit", () => {1006 const at = Revision.Branch({ name: BranchName.make("main") });10071008 it.live(1009 "asks for one handle for every read of one session, and disposes it once",1010 () =>1011 within(({ counts }) =>1012 Effect.gen(function* () {1013 const repos = yield* RepoHost;1014 const name = RepoName.make("session");1015 const { first } = yield* seeded(name);1016 const before = { ...counts };10171018 const read = yield* inRepoSession(1019 Effect.all(1020 [1021 repos.readCommit(name, first),1022 repos.log(name, at, 5),1023 repos.readFile(name, at, RepoPath.make("a.txt")),1024 repos.readCommit(name, first),1025 ],1026 { concurrency: 4 }1027 )1028 ).pipe(Effect.orDie);10291030 expect(read[1].map(({ sha }) => sha)).toStrictEqual([first]);1031 expect([1032 counts.gets - before.gets,1033 counts.disposed - before.disposed,1034 ]).toStrictEqual([1, 1]);1035 })1036 )1037 );10381039 it.live(1040 "reads in a session inside another over the outer session's handle",1041 () =>1042 within(({ counts }) =>1043 Effect.gen(function* () {1044 const repos = yield* RepoHost;1045 const name = RepoName.make("nested");1046 const { first } = yield* seeded(name);1047 const before = { ...counts };10481049 yield* inRepoSession(1050 Effect.all([1051 repos.readCommit(name, first),1052 inRepoSession(repos.log(name, at, 5)),1053 repos.readFile(name, at, RepoPath.make("a.txt")),1054 ])1055 ).pipe(Effect.orDie);10561057 expect([1058 counts.gets - before.gets,1059 counts.disposed - before.disposed,1060 ]).toStrictEqual([1, 1]);1061 })1062 )1063 );10641065 it.effect(1066 "asks again after each of four rate-limited reads, then reads",1067 () =>1068 within(1069 () =>1070 Effect.gen(function* () {1071 const repos = yield* RepoHost;1072 const name = RepoName.make("limited");1073 const { first } = yield* seeded(name);1074 const read = yield* onTestClock(repos.readCommit(name, first));10751076 expect(1077 Exit.map(1078 read,1079 Option.map(({ sha }) => sha)1080 )1081 ).toStrictEqual(Exit.succeed(Option.some(first)));1082 }),1083 { rateLimited: 4 }1084 )1085 );10861087 it.effect(1088 "fails the read once four asks after the first were all rate limited",1089 () =>1090 within(1091 () =>1092 Effect.gen(function* () {1093 const repos = yield* RepoHost;1094 const name = RepoName.make("throttled");1095 const { first } = yield* seeded(name);1096 const read = yield* onTestClock(repos.readCommit(name, first));10971098 expect(Exit.hasDies(read)).toBeTruthy();1099 }),1100 { rateLimited: 5 }1101 )1102 );1103});
modified:packages/project/src/code/cache.ts+80 added-1 removed
added:packages/project/src/code/history.ts+168 added
1/**2 * Code history kept by immutable ids: what a why or a3 * path's log computed from a commit, which that commit's content fixes for4 * good, so any isolate reads it back instead of walking history again.5 *6 * Keys: `<repo>/<kind>/v<version>/<commit>/<scan>/<sha256(path)>`, where7 * `kind` is `why` (version `WHY_VERSION`) or `path-log` (version8 * `LOG_VERSION`), `commit` is a commit id (never `main` or a tag's name:9 * those resolve first), `scan` is how many first-parent commits the walk10 * took, and the path is hashed so a key stays under the store's 1,02411 * bytes. Only a project's canonical repo is ever keyed (principle 7). A12 * version moves when its algorithm changes, so an old value is never read13 * as a new one.14 *15 * Values: ids and ranges, encoded with Schema; never a file's text, and16 * never a landing (each view asks the project's record for those, so a17 * later landing shows at once). A value that fails to decode is a miss.18 *19 * Read order: the isolate's `CodeCache` (with the heavy reads: a why's20 * ranges grow with its file), then the `CodeStore`, then the walk; what a21 * walk computed is put in both. A walk may start from what is22 * kept at a first-parent ancestor at most `INCREMENT_REACH` commits back,23 * so a new landing on main costs a handful of reads.24 */25import { WhyRange } from "@repo/protocol/domain/code";26import { BlobSha, CommitSha } from "@repo/protocol/ids";27import type { RepoName, RepoPath } from "@repo/protocol/ids";28import { Effect, Option, Schema } from "effect";2930import { CodeStore } from "../code-store.ts";31import { CodeCache } from "./cache.ts";3233/** The why walk's algorithm version, in its keys. */34export const WHY_VERSION = 1;3536/** The path log's algorithm version, in its keys. */37export const LOG_VERSION = 1;3839/** How many first-parent commits back a walk looks for a kept result to start from. */40export const INCREMENT_REACH = 16;4142/**43 * Why each line is there at a commit: the path's blob there, the ranges,44 * the commits they name (newest first), and where the walk stopped.45 */46export const StoredWhy = Schema.Struct({47 blob: BlobSha,48 ranges: Schema.Array(WhyRange),49 shas: Schema.Array(CommitSha),50 stoppedAt: Schema.optionalKey(CommitSha),51});5253export type StoredWhy = typeof StoredWhy.Type;5455/**56 * A path's history from a commit: the first-parent commits of the scan57 * that changed it, newest first, and whether the scan reached the root.58 */59export const StoredPathLog = Schema.Struct({60 reachedRoot: Schema.Boolean,61 shas: Schema.Array(CommitSha),62});6364export type StoredPathLog = typeof StoredPathLog.Type;6566/** The lowercase hex SHA-256 of `text`. */67const sha256 = (text: string) =>68 Effect.map(69 Effect.promise(() =>70 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))71 ),72 (digest) =>73 [...new Uint8Array(digest)]74 .map((byte) => byte.toString(16).padStart(2, "0"))75 .join("")76 );7778/** One kind of kept history: its key's kind and version, and its value. */79export interface Kept<A> {80 readonly kind: string;81 readonly version: number;82 readonly schema: Schema.Codec<A, unknown>;83}8485export const whyKept: Kept<StoredWhy> = {86 kind: "why",87 schema: StoredWhy,88 version: WHY_VERSION,89};9091export const pathLogKept: Kept<StoredPathLog> = {92 kind: "path-log",93 schema: StoredPathLog,94 version: LOG_VERSION,95};9697/** Where `kept` is kept for `path` from `commit`, scanning `scan` commits. */98export const keyOf = <A>(99 kept: Kept<A>,100 at: {101 readonly repo: RepoName;102 readonly commit: CommitSha;103 readonly scan: number;104 readonly path: RepoPath;105 }106) =>107 Effect.map(108 sha256(at.path),109 (hash) =>110 `${at.repo}/${kept.kind}/v${kept.version}/${at.commit}/${at.scan}/${hash}`111 );112113/**114 * What is kept under `key`: the isolate's cache first, then the store. A115 * miss is never cached, so a value another isolate keeps later is found.116 */117export const recall = <A>(118 kept: Kept<A>,119 key: string120): Effect.Effect<Option.Option<A>> =>121 Effect.gen(function* () {122 const cache = yield* CodeCache;123 const store = yield* CodeStore;124125 const decode = Schema.decodeUnknownOption(126 Schema.fromJsonString(kept.schema)127 );128129 return yield* cache.through(130 key,131 Effect.map(store.get(key), Option.flatMap(decode)),132 { heavy: true, keep: Option.isSome }133 );134 });135136/** `value` kept under `key`, in the isolate's cache and in the store. */137export const remember = <A>(138 kept: Kept<A>,139 key: string,140 value: A141): Effect.Effect<void> =>142 Effect.gen(function* () {143 const cache = yield* CodeCache;144 const store = yield* CodeStore;145146 const encoded = yield* Schema.encodeEffect(147 Schema.fromJsonString(kept.schema)148 )(value).pipe(Effect.orDie);149150 yield* store.put(key, encoded);151 yield* cache.through(key, Effect.succeedSome(value), { heavy: true });152 });153154/**155 * What is kept under `key`, else `compute` run and its value kept: a156 * failure is never kept.157 */158export const throughHistory = <A, E, R>(159 kept: Kept<A>,160 key: string,161 compute: Effect.Effect<A, E, R>162): Effect.Effect<A, E, R> =>163 Effect.flatMap(recall(kept, key), (found) =>164 Option.match(found, {165 onNone: () => Effect.tap(compute, (value) => remember(kept, key, value)),166 onSome: Effect.succeed,167 })168 );
modified:packages/project/src/code/log.ts+161 added-56 removed
3 unmodified lines
4 * only where the project's record has one, so a trailer in an imported5 * commit never reads as a landing. With a path, only the commits whose6 * first-parent change touched it, scanning at most 200 commits a call;7 * `next` is where the scan stopped, so the next page resumes it.8 *9 * A path's history from the scan's first commit is kept by immutable ids10 * (`history.ts`) under `<repo>/path-log/v<LOG_VERSION>/<commit>/<scan>/11 * <sha256(path)>`: the commits of the scan that changed the path, newest12 * first, and whether the scan reached the root; pages are cut from it.13 * Kept nowhere yet, it is the history kept at the nearest first-parent14 * ancestor within `INCREMENT_REACH` commits plus the commits between that15 * changed the path, cut to the scan; else each commit of the scan has its16 * entry looked up once (`READS_AT_ONCE` under way, in one ordered pass),17 * and neighbours compared.18 */9import { Revision, RepoHost } from "@repo/artifacts/repo-host";19import { inRepoSession, Revision, RepoHost } from "@repo/artifacts/repo-host";20import type {21 Commit,22 RepoNotFound,23 TreeEntry,
6 unmodified lines
30import type { UnknownRevision } from "@repo/protocol/refusal";31import { Array, DateTime, Effect, Equal, Option } from "effect";3233import type { CodeProject } from "../code.ts";24import { CodeCache } from "./cache.ts";34import { asOneView, CodeCache } from "./cache.ts";35import {36 INCREMENT_REACH,37 keyOf,38 pathLogKept,39 recall,40 throughHistory,41} from "./history.ts";42import type { StoredPathLog } from "./history.ts";43import { commitAt, resolveRev } from "./revision.ts";44import { entryAt, READS_AT_ONCE } from "./tree.ts";4546/** The most commits one page holds. */
59 unmodified lines
106/**107 * `count` first-parent commits from `sha`, the first `from` skipped: a108 * commit's history never changes, so the page is kept by its start.109 */92const pageOf = (110export const pageOf = (111 repo: RepoName,112 sha: CommitSha,113 from: number,114 count: number
31 unmodified lines
146 onNone: () => ({ commits }),147 onSome: (at) => ({ commits, next: at }),148 });149150/** What sits at `path` in each commit of `commits`, in order: one lookup each. */151const idsOf = (152 repo: RepoName,153 path: RepoPath,154 commits: readonly Commit[]155): Effect.Effect<readonly Option.Option<string>[], RepoNotFound, RepoHost> =>156 Effect.forEach(commits, ({ tree }) => idAt(repo, tree, path), {157 concurrency: READS_AT_ONCE,158 });159160/**161 * The commits among the first `count` of `scan` that changed `path` from162 * their first parent, newest first. The log is first parents, so each163 * commit's parent is the next in `scan`; only past it (or should the log164 * ever say otherwise) is a parent read on its own.165 */166const changedIn = (167 repo: RepoName,168 path: RepoPath,169 scan: readonly Commit[],170 count: number171): Effect.Effect<readonly CommitSha[], RepoNotFound, RepoHost> =>172 Effect.gen(function* () {173 const looked = scan.slice(0, count + 1);174 const ids = yield* idsOf(repo, path, looked);175176 const changed = yield* Effect.forEach(177 looked.slice(0, count),178 (commit, at) =>179 Effect.gen(function* () {180 const parent = Option.fromUndefinedOr(commit.parents[0]);181 const after = looked[at + 1];182183 const before = yield* Option.match(parent, {184 onNone: () => Effect.succeedNone,185 onSome: (first) =>186 after !== undefined && after.sha === first187 ? Effect.succeed(ids[at + 1] ?? Option.none())188 : commitAt(repo, first).pipe(189 Effect.flatMap(190 Option.match({191 onNone: () => Effect.succeedNone,192 onSome: ({ tree }) => idAt(repo, tree, path),193 })194 )195 ),196 });197198 return Equal.equals(ids[at] ?? Option.none(), before)199 ? Option.none()200 : Option.some(commit.sha);201 }),202 { concurrency: READS_AT_ONCE }203 );204205 return Array.getSomes(changed);206 });207208/** The path's history from `scan[0]`, kept at the nearest ancestor within reach. */209const nearestKept = (repo: RepoName, path: RepoPath, scan: readonly Commit[]) =>210 Effect.map(211 Effect.forEach(212 scan.slice(1, INCREMENT_REACH + 1),213 ({ sha }) =>214 Effect.flatMap(215 keyOf(pathLogKept, { commit: sha, path, repo, scan: PATH_SCAN }),216 (key) => recall(pathLogKept, key)217 ),218 { concurrency: INCREMENT_REACH }219 ),220 (found) =>221 Array.findFirst(found, (kept, at) =>222 Option.map(kept, (value) => ({ back: at + 1, kept: value }))223 )224 );225226/** The path's history over `scan` (at most `PATH_SCAN` commits and the parent of its last). */227const historyOf = (228 repo: RepoName,229 path: RepoPath,230 scan: readonly Commit[]231): Effect.Effect<StoredPathLog, RepoNotFound, RepoHost> =>232 Effect.gen(function* () {233 const scanned = scan.slice(0, PATH_SCAN);234 const reachedRoot = scan.length <= PATH_SCAN;235 const kept = yield* nearestKept(repo, path, scan);236237 if (Option.isNone(kept)) {238 return {239 reachedRoot,240 shas: yield* changedIn(repo, path, scan, scanned.length),241 };242 }243244 const { back } = kept.value;245 const inScan = new Set<string>(scanned.map(({ sha }) => sha));246 const between = yield* changedIn(repo, path, scan, back);247248 return {249 reachedRoot,250 shas: [251 ...between,252 ...kept.value.kept.shas.filter((sha) => inScan.has(sha)),253 ],254 };255 });256257/** A page of first-parent commits from `at`, each landing with its record. */258export const logPage = (259 project: CodeProject,260 input: {
26 unmodified lines
287 const scan = yield* pageOf(repo, sha, from, PATH_SCAN + 1).pipe(288 Effect.orDie289 );290166 const scanned = scan.slice(0, PATH_SCAN);167 const touched: Commit[] = [];291 const [start] = scan;292169 /** Whether the commit at `at` in the scan changed `path` from its first parent. */170 const changedAt = (at: number, commit: Commit) =>171 Effect.gen(function* () {172 const parent = Option.fromUndefinedOr(commit.parents[0]);173 const after = Option.fromUndefinedOr(scan[at + 1]);293 if (start === undefined) {294 return pageWith([], Option.none());295 }296175 // The log is first parents, so the next commit in it is this one's176 // parent; only past the scan is the parent read on its own.177 const parentCommit = yield* Option.match(parent, {178 onNone: () => Effect.succeedNone,179 onSome: (first) =>180 Option.exists(after, ({ sha: next }) => next === first)181 ? Effect.succeed(after)182 : commitAt(repo, first),183 });297 const key = yield* keyOf(pathLogKept, {298 commit: start.sha,299 path,300 repo,301 scan: PATH_SCAN,302 });303185 const parentTree = Option.map(parentCommit, ({ tree }) => tree);304 const { shas } = yield* throughHistory(305 pathLogKept,306 key,307 asOneView(historyOf(repo, path, scan))308 ).pipe(Effect.orDie);309187 const [now, before] = yield* Effect.all(188 [189 idAt(repo, commit.tree, path),190 Option.match(parentTree, {191 onNone: () => Effect.succeedNone,192 onSome: (tree) => idAt(repo, tree, path),193 }),194 ],195 { concurrency: 2 }196 );310 const at = new Map(scan.map((commit, index) => [commit.sha, index]));311198 return !Equal.equals(now, before);199 }).pipe(Effect.orDie);312 const touched = shas.slice(0, limit).flatMap((changed) => {313 const commit = scan[at.get(changed) ?? scan.length];314201 // Each batch is read together, then walked in order, so a page that202 // fills stops the scan where its last commit is.203 for (const batch of Array.chunksOf([...scanned.entries()], READS_AT_ONCE)) {204 const changed = yield* Effect.forEach(205 batch,206 ([at, commit]) => changedAt(at, commit),207 { concurrency: READS_AT_ONCE }208 );315 return commit === undefined ? [] : [commit];316 });317210 for (const [[at, commit], touches] of Array.zip(batch, changed)) {211 if (touches) {212 touched.push(commit);213 }318 const commits = yield* commitViews(project, touched);319 const newest = touched.at(-1);320 const last = newest === undefined ? undefined : at.get(newest.sha);321215 if (touched.length === limit) {216 const commits = yield* commitViews(project, touched);217218 return pageWith(219 commits,220 at + 1 < scan.length ? Option.some(from + at + 1) : Option.none()221 );322 // A page that fills stops the scan at its last commit.323 if (touched.length === limit && last !== undefined) {324 return pageWith(325 commits,326 last + 1 < scan.length ? Option.some(from + last + 1) : Option.none()327 );222 }223 }328 }329226 const commits = yield* commitViews(project, touched);227330 return pageWith(331 commits,332 scan.length > PATH_SCAN ? Option.some(from + PATH_SCAN) : Option.none()333 );232 });334 }).pipe(335 // The scan and the walk over it: one session, one handle.336 inRepoSession337 );
modified:packages/project/src/code/tree.ts+8 added-5 removed
17 unmodified lines
18import { commitAt, resolveRev } from "./revision.ts";1920/**21 * How many commits a walk over history (a path's log, why each line is22 * there) reads at once. A live store answers each read in tens of23 * milliseconds, so one at a time a 200-commit walk took a minute on24 * dev-oscabriel; sixteen at once stays far under the store's 2,00025 * requests per 10 s per repo.22 * there) has under way at once, in one ordered pass with no batch to wait23 * on. A live store answers each read in tens to hundreds of milliseconds,24 * and a path four folders deep chains five reads per commit, so one at a25 * time a 200-commit walk took a minute on dev-oscabriel and sixteen at26 * once in batches still 14-28 s. Forty-eight at once, at a few27 * hundred milliseconds each, stays under the store's 2,000 requests per28 * 10 s per repo for one viewer.29 */27export const READS_AT_ONCE = 16;30export const READS_AT_ONCE = 48;3132/** The entries of the tree `id`; a tree a commit or a tree names is always there. */33export const entriesOf = (34 repo: RepoName,
163 unmodified lines
modified:packages/project/src/code/why.ts+405 added-118 removed
1/**2 * Why each line of a file is there (ADR 0019): a first-parent blame from3 * a revision. The walk takes at most `WHY_SCAN` first-parent commits from4 * the log and the path's blob at each (trees kept by id through5 * `CodeCache`, `READS_AT_ONCE` commits read together), keeps the commits6 * where the blob changed, then reads those blobs newest first, a batch at7 * a time, only until every line has its commit (`@repo/git/blame`). Each commit a line points at comes back as a reader8 * sees it, and the landings among them come from the project's record in9 * one batch, so an imported commit never reads as a landing. Lines older10 * than the walk reached point at the commit it stopped at, named11 * `stoppedAt`. A binary file, or one past 1 MiB, has no ranges. The whole12 * view is kept by `(at, path)`: what a commit holds never changes.3 * a revision, kept by immutable ids (`history.ts`): the path's blob at the4 * commit, the ranges, the commits they name and where the walk stopped,5 * under `<repo>/why/v<WHY_VERSION>/<commit>/<scan>/<sha256(path)>`. Each6 * view reads the commits it names (kept by id) and asks the project's7 * record for their landings in one batch, so an imported commit never8 * reads as a landing and a later landing shows at once.9 *10 * Kept nowhere yet, the why is computed from the nearest first-parent11 * ancestor within `INCREMENT_REACH` commits that has one: each line is12 * carried forward through the file's versions between them (a line diff13 * per change), and a line a version inserted goes to the commit that made14 * it. Otherwise the walk takes at most `WHY_SCAN` first-parent commits from15 * the log, looks up the path's blob in each (`READS_AT_ONCE` under way, in16 * order, with no batch to wait on, until the file's first commit), then17 * reads the changed versions newest first only until every line has its18 * commit (`@repo/git/blame`). Lines older than the walk reached point at19 * the commit it stopped at, named `stoppedAt`. A binary file, or one past20 * 1 MiB, has no ranges.21 */14import { ObjectId, Revision, RepoHost } from "@repo/artifacts/repo-host";22import { inRepoSession, ObjectId, RepoHost } from "@repo/artifacts/repo-host";23import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";16import { blameFrom, isSettled, settle, traceBack } from "@repo/git/blame";17import type { Rev, WhyView } from "@repo/protocol/domain/code";24import {25 blameFrom,26 isSettled,27 linesOf,28 settle,29 traceBack,30} from "@repo/git/blame";31import { Edit, lineDiff } from "@repo/git/line-diff";32import type { Rev, WhyRange, WhyView } from "@repo/protocol/domain/code";33import { BlobSha } from "@repo/protocol/ids";34import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";35import { UnknownPath } from "@repo/protocol/refusal";36import type { UnknownRevision } from "@repo/protocol/refusal";22import { Array, Effect, Option } from "effect";37import { Array, Effect, Option, Ref, Stream } from "effect";3839import type { CodeProject } from "../code.ts";40import { MAX_LANDINGS } from "../project.ts";26import { CodeCache } from "./cache.ts";41import { asOneView } from "./cache.ts";42import { contentsOf, contentsOfBytes, unlessTooLarge } from "./file.ts";43import {44 INCREMENT_REACH,45 keyOf,46 recall,47 throughHistory,48 whyKept,49} from "./history.ts";50import type { StoredWhy } from "./history.ts";28import { commitViews } from "./log.ts";51import { commitViews, pageOf } from "./log.ts";52import { commitAt, resolveRev } from "./revision.ts";53import { entryAt, READS_AT_ONCE } from "./tree.ts";5455/** The most first-parent commits one view walks. */
4 unmodified lines
60 readonly blob: BlobSha;61 readonly commit: Commit;62}6364/** The file's versions newest first, and whether the walk stopped short of its first commit. */65interface Versions {66 readonly versions: readonly Version[];67 readonly stopped: boolean;68}6970/** The file's blob at `path` in `commit`, if a file is there. */71const blobAt = (repo: RepoName, commit: Commit, path: RepoPath) =>72 Effect.map(73 entryAt(repo, commit.tree, path),
4 unmodified lines
78 )79 );8081/**53 * The file's versions newest first, from the commits of `log` (first54 * parents, newest first, starting with the blob `newest`), and whether the55 * walk stopped short of the file's first commit.82 * The file's blob in each of `commits` (first parents, newest first), up to83 * the first commit without the file. One pass with `READS_AT_ONCE` lookups84 * under way and no barrier: a slow lookup holds up only itself, not the85 * ones after it. Once a commit without the file is found, lookups further86 * back are skipped.87 */57const versionsOf = (58 repo: RepoName,59 path: RepoPath,60 log: readonly Commit[],61 newest: Version62): Effect.Effect<63 { readonly versions: readonly Version[]; readonly stopped: boolean },64 RepoNotFound,65 RepoHost66> =>88const lookups = (repo: RepoName, path: RepoPath, commits: readonly Commit[]) =>89 Effect.gen(function* () {68 const versions: Version[] = [];69 let current = newest;90 // Where the file was found missing: no lookup past it is needed.91 const missingAt = yield* Ref.make(commits.length);9271 // Each batch's blobs are read together, then walked in order.72 for (const batch of Array.chunksOf(log.slice(1), READS_AT_ONCE)) {73 const blobs = yield* Effect.forEach(74 batch,75 (commit) => blobAt(repo, commit, path),76 { concurrency: READS_AT_ONCE }77 );93 const found = yield* Effect.forEach(94 commits,95 (commit, at) =>96 Effect.gen(function* () {97 if (at > (yield* Ref.get(missingAt))) {98 return Option.none();99 }10079 for (const [commit, blob] of Array.zip(batch, blobs)) {80 if (Option.contains(blob, current.blob)) {81 current = { blob: current.blob, commit };82 } else {83 versions.push(current);101 const blob = yield* blobAt(repo, commit, path);102103 if (Option.isNone(blob)) {86 // The file was born in the commit after this one.87 return { stopped: false, versions };104 yield* Ref.update(missingAt, (was) => Math.min(was, at));105 }10690 current = { blob: blob.value, commit };91 }107 return Option.some({ blob, commit });108 }),109 { concurrency: READS_AT_ONCE }110 );111112 const looked = Array.getSomes(found);113 const missing = looked.findIndex(({ blob }) => Option.isNone(blob));114115 return missing === -1 ? looked : looked.slice(0, missing + 1);116 });117118/**119 * The file's versions newest first, from `newest` and the blobs `found` in120 * the commits before it, and whether the walk stopped short of the file's121 * first commit.122 */123const versionsOf = (124 newest: Version,125 found: readonly {126 readonly blob: Option.Option<BlobSha>;127 readonly commit: Commit;128 }[]129): Versions => {130 const versions: Version[] = [];131 let current = newest;132133 for (const { blob, commit } of found) {134 if (Option.contains(blob, current.blob)) {135 current = { blob: current.blob, commit };136 } else {137 versions.push(current);138139 if (Option.isNone(blob)) {140 // The file was born in the commit after this one.141 return { stopped: false, versions };142 }143144 current = { blob: blob.value, commit };145 }146 }14795 versions.push(current);148 versions.push(current);14997 return {98 stopped: current.commit.parents.length > 0,99 versions,100 };101 });150 return {151 stopped: current.commit.parents.length > 0,152 versions,153 };154};155156/**157 * An older version's text as the blame reads it, empty for a binary or too158 * large one. Read past the cache: old versions are seldom viewed, and
13 unmodified lines
172 Effect.forEach(Array.chunksOf(shas, MAX_LANDINGS), project.landings),173 Array.flatten174 );175123/** The view, read: `at` is a commit of the canonical repo. */124const read = (125 project: CodeProject,126 at: CommitSha,176/** Each line's commit, from ranges of consecutive lines numbered from 1. */177const ownersOf = (ranges: readonly WhyRange[]): readonly CommitSha[] =>178 ranges.flatMap(({ end, sha, start }) =>179 Array.makeBy(end - start + 1, () => sha)180 );181182/** Each line's commit as ranges of consecutive lines, numbered from 1. */183const rangesOf = (owners: readonly CommitSha[]): readonly WhyRange[] => {184 const ranges: WhyRange[] = [];185186 for (const [index, sha] of owners.entries()) {187 const last = ranges.at(-1);188 const line = index + 1;189190 if (last !== undefined && last.sha === sha && last.end === index) {191 ranges[ranges.length - 1] = { ...last, end: line };192 } else {193 ranges.push({ end: line, sha, start: line });194 }195 }196197 return ranges;198};199200/**201 * Each line of `after`'s commit, carried forward from `before`'s: a line202 * the diff keeps keeps its commit, and a line `after` inserted goes to203 * `sha`, the commit that made `after`.204 */205const carried = (206 before: { readonly text: string; readonly owners: readonly CommitSha[] },207 after: string,208 sha: CommitSha209): readonly CommitSha[] => {210 const lines = linesOf(after);211 const owners: CommitSha[] = lines.map(() => sha);212213 for (const edit of lineDiff(linesOf(before.text), lines)) {214 if (Edit.$is("Equal")(edit)) {215 for (let at = 0; at < edit.count; at += 1) {216 owners[edit.newStart + at] = before.owners[edit.oldStart + at] ?? sha;217 }218 }219 }220221 return owners;222};223224/** The why kept at `log[at]`'s nearest ancestor within reach, and how far back. */225const nearestKept = (226 repo: RepoName,227 path: RepoPath,228 log: readonly Commit[],229 scan: number230) =>231 Effect.map(232 Effect.forEach(233 log.slice(1, INCREMENT_REACH + 1),234 ({ sha }) =>235 Effect.flatMap(236 keyOf(whyKept, { commit: sha, path, repo, scan }),237 (key) => recall(whyKept, key)238 ),239 { concurrency: INCREMENT_REACH }240 ),241 (found) =>242 Array.findFirst(found, (kept, at) =>243 Option.map(kept, (value) => ({ back: at + 1, kept: value }))244 )245 );246247/**248 * The why at `log[0]`, whose blob is `newest`, carried forward from `kept`249 * at `log[back]` through the blobs `between` them; none when the file is250 * missing in a commit between (its history starts again there, so the251 * whole walk answers).252 */253const forward = (254 repo: RepoName,255 log: readonly Commit[],256 newest: BlobSha,257 between: readonly Option.Option<BlobSha>[],258 from: { readonly back: number; readonly kept: StoredWhy }129): Effect.Effect<WhyView, UnknownPath | RepoNotFound, RepoHost> =>259): Effect.Effect<Option.Option<StoredWhy>, RepoNotFound, RepoHost> =>260 Effect.gen(function* () {131 const { repo } = project;261 if (!between.every(Option.isSome)) {262 return Option.none();263 }264133 const head = yield* commitAt(repo, at).pipe(134 Effect.flatMap(Effect.fromOption),135 Effect.orDie265 const blobs = [newest, ...between.map(Option.getOrThrow)];266267 // Each version the commits made, oldest first: where a commit's blob268 // differs from its parent's.269 const changes = blobs270 .flatMap((blob, at) => {271 const parent = blobs[at + 1] ?? from.kept.blob;272 const commit = log[at];273274 return blob === parent || commit === undefined275 ? []276 : [{ blob, sha: commit.sha }];277 })278 .toReversed();279280 if (changes.length === 0) {281 return Option.some(from.kept);282 }283284 const newestContents = yield* contentsOf(repo, newest);285286 if (287 Option.isNone(newestContents) ||288 Option.isNone(newestContents.value.text)289 ) {290 return Option.some({ blob: newest, ranges: [], shas: [] });291 }292293 const newestText = newestContents.value.text.value;294295 const [base, ...texts] = yield* Effect.forEach(296 [{ blob: from.kept.blob }, ...changes],297 ({ blob }) =>298 blob === newest ? Effect.succeed(newestText) : textOf(repo, blob),299 { concurrency: READS_AT_ONCE }300 );301138 const blob = yield* blobAt(repo, head, path);302 let tracing = {303 owners: ownersOf(from.kept.ranges),304 text: base ?? "",305 };306140 if (Option.isNone(blob)) {141 return yield* new UnknownPath({ commit: at, path });307 for (const [{ sha }, text] of Array.zip(changes, texts)) {308 tracing = { owners: carried(tracing, text, sha), text };309 }310144 const none: WhyView = { at, commits: [], landings: [], path, ranges: [] };311 const named = new Set<string>(tracing.owners);312 const added = changes.map(({ sha }) => sha).toReversed();313146 const contents = yield* contentsOf(repo, blob.value);314 const shas = [...added, ...from.kept.shas].filter(315 (sha, at, all) => named.has(sha) && all.indexOf(sha) === at316 );317318 const stoppedAt = Option.filter(319 Option.fromUndefinedOr(from.kept.stoppedAt),320 (sha) => named.has(sha)321 );322323 return Option.some({324 blob: newest,325 ranges: rangesOf(tracing.owners),326 shas,327 ...Option.match(stoppedAt, {328 onNone: () => ({}),329 onSome: (sha) => ({ stoppedAt: sha }),330 }),331 });332 });333334/**335 * The why at `log[0]` by the whole walk. The head's blob and text are read336 * beside the other commits' lookups, so nothing waits on the head's337 * folders before the pass starts.338 */339const walked = (340 repo: RepoName,341 at: CommitSha,342 path: RepoPath,343 log: readonly Commit[],344 head: Commit345): Effect.Effect<StoredWhy, UnknownPath | RepoNotFound, RepoHost> =>346 Effect.gen(function* () {347 const [headSide, found] = yield* Effect.all(348 [349 Effect.gen(function* () {350 const blob = yield* blobAt(repo, head, path);351352 if (Option.isNone(blob)) {353 return yield* new UnknownPath({ commit: at, path });354 }355356 return {357 blob: blob.value,358 contents: yield* contentsOf(repo, blob.value),359 };360 }),361 lookups(repo, path, log.slice(1)),362 ],363 { concurrency: 2 }364 );365366 const newest = headSide.blob;367 const { contents } = headSide;368 const none: StoredWhy = { blob: newest, ranges: [], shas: [] };369370 if (Option.isNone(contents) || Option.isNone(contents.value.text)) {371 return none;372 }373152 const log = yield* RepoHost.use((host) =>153 host.log(repo, Revision.Commit({ sha: at }), Math.max(1, scan))374 const { stopped, versions } = versionsOf(375 { blob: newest, commit: head },376 found377 );378156 const { stopped, versions } = yield* versionsOf(repo, path, log, {157 blob: blob.value,158 commit: head,159 });379 const [first = { blob: newest, commit: head }, ...older] = versions;380 const text = contents.value.text.value;381161 const [newest = { blob: blob.value, commit: head }, ...older] = versions;382 // The newest version is the file as read: its text is at hand. The383 // older ones are read in order, `READS_AT_ONCE` under way, only until384 // every line has its commit.385 const tracing = yield* Stream.fromIterable(older).pipe(386 Stream.mapEffect(387 (version) =>388 Effect.map(textOf(repo, version.blob), (read) => ({389 sha: version.commit.sha,390 text: read,391 })),392 { concurrency: READS_AT_ONCE }393 ),394 Stream.scan(() => blameFrom({ sha: first.commit.sha, text }), traceBack),395 Stream.takeUntil(isSettled),396 Stream.runLast,397 Effect.map(Option.getOrThrow)398 );399163 // The newest version is the file as read: its text is at hand.164 let tracing = blameFrom({165 sha: newest.commit.sha,166 text: contents.value.text.value,167 });400 const { ranges, reachedEnd } = settle(tracing);401 const named = new Set<string>(ranges.map(({ sha }) => sha));402169 // Each batch of older versions is read together, then traced in170 // order, until every line has its commit.171 for (const batch of Array.chunksOf(older, READS_AT_ONCE)) {172 if (isSettled(tracing)) {173 break;174 }403 const shas = versions404 .map(({ commit }) => commit.sha)405 .filter((sha) => named.has(sha));406176 const texts = yield* Effect.forEach(177 batch,178 (version) => textOf(repo, version.blob),407 const last = versions.at(-1);408409 // Lines the walk did not see brought: they point at where it stopped.410 return stopped && reachedEnd && last !== undefined411 ? { ...none, ranges, shas, stoppedAt: last.commit.sha }412 : { ...none, ranges, shas };413 });414415/** The why at `at`, computed: from a kept ancestor's when one is in reach. */416const computed = (417 repo: RepoName,418 at: CommitSha,419 path: RepoPath,420 scan: number421): Effect.Effect<StoredWhy, UnknownPath | RepoNotFound, RepoHost> =>422 Effect.gen(function* () {423 const log = yield* pageOf(repo, at, 0, Math.max(1, scan));424 const [head] = log;425426 if (head === undefined) {427 return yield* Effect.die(`${repo} has no log from ${at}`);428 }429430 const kept = yield* nearestKept(repo, path, log, scan);431432 if (Option.isSome(kept)) {433 const [newest, ...between] = yield* Effect.forEach(434 log.slice(0, kept.value.back),435 (commit) => blobAt(repo, commit, path),436 { concurrency: READS_AT_ONCE }437 );438182 for (const [version, text] of Array.zip(batch, texts)) {183 if (isSettled(tracing)) {184 break;185 }439 if (newest === undefined || Option.isNone(newest)) {440 return yield* new UnknownPath({ commit: at, path });441 }442187 tracing = traceBack(tracing, { sha: version.commit.sha, text });443 const carriedForward = yield* forward(444 repo,445 log,446 newest.value,447 between,448 kept.value449 );450451 if (Option.isSome(carriedForward)) {452 return carriedForward.value;453 }454 }455191 const { ranges, reachedEnd } = settle(tracing);192 const named = new Set<string>(ranges.map(({ sha }) => sha));456 return yield* walked(repo, at, path, log, head);457 });458194 const commits = versions195 .map(({ commit }) => commit)196 .filter(({ sha }) => named.has(sha));459/** The view of `kept`: each commit it names as a reader sees it, and their landings. */460const viewOf = (461 project: CodeProject,462 at: CommitSha,463 path: RepoPath,464 kept: StoredWhy465): Effect.Effect<WhyView, RepoNotFound, RepoHost> =>466 Effect.gen(function* () {467 const commits = yield* Effect.forEach(468 kept.shas,469 (sha) =>470 commitAt(project.repo, sha).pipe(471 Effect.flatMap(Effect.fromOption),472 Effect.catchTag("NoSuchElementError", () =>473 Effect.die(`${project.repo} has no commit ${sha}`)474 )475 ),476 { concurrency: READS_AT_ONCE }477 );478479 const views = yield* commitViews(480 { ...project, landings: () => Effect.succeed([]) },481 commits482 );483203 const landings = yield* landingsOf(204 project,205 commits.map(({ sha }) => sha)206 );484 const landings = yield* landingsOf(project, kept.shas);485208 const found: WhyView = { ...none, commits: views, landings, ranges };209 const last = versions.at(-1);210211 // Lines the walk did not see brought: they point at where it stopped.212 return stopped && reachedEnd && last !== undefined213 ? { ...found, stoppedAt: last.commit.sha }214 : found;486 return {487 at,488 commits: views,489 landings,490 path,491 ranges: kept.ranges,492 ...Option.match(Option.fromUndefinedOr(kept.stoppedAt), {493 onNone: () => ({}),494 onSome: (stoppedAt) => ({ stoppedAt }),495 }),496 };497 });498499/** Why each line of `path` at `at` is there, walking at most `scan` commits. */500export const whyView = (
3 unmodified lines
504 scan: number = WHY_SCAN505): Effect.Effect<WhyView, UnknownRevision | UnknownPath, RepoHost> =>506 Effect.gen(function* () {507 const commit = yield* resolveRev(project, at);226 const cache = yield* CodeCache;508 const { repo } = project;509 const key = yield* keyOf(whyKept, { commit, path, repo, scan });510228 return yield* cache229 .through(230 `${project.repo}:why:${commit}:${scan}:${path}`,231 read(project, commit, path, scan),232 { heavy: true }233 )234 .pipe(Effect.catchTag("RepoNotFound", Effect.die));235 });511 const kept = yield* throughHistory(512 whyKept,513 key,514 asOneView(computed(repo, commit, path, scan))515 );516517 return yield* viewOf(project, commit, path, kept);518 }).pipe(519 // The walk and the commits it names: one session, one handle.520 inRepoSession,521 Effect.catchTag("RepoNotFound", Effect.die)522 );
added:packages/project/test/code-history.test.ts+700 added
1/**2 * Code history kept by immutable ids, over the memory repo3 * host behind a wrapper that counts the trees and blobs read, the memory4 * code store, and a fresh `CodeCacheLive` for each isolate: a why and a5 * path's log computed on one isolate are read back on another without a6 * walk; one landing past a kept result costs a handful of reads and agrees7 * with the whole walk; landings are always asked fresh; a cold walk keeps8 * many reads under way and looks each commit's entry up once; a value9 * that no longer decodes is computed again and replaced.10 */11import { describe, expect, it } from "@effect/vitest";12import { RepoHost, RepoSession } from "@repo/artifacts/repo-host";13import type { RepoSessionApi } from "@repo/artifacts/repo-host";14import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";15import type { LandingView } from "@repo/protocol/domain/landing";16import {17 AskId,18 Handle,19 LandedSha,20 ProjectName,21 RepoName,22 RepoPath,23} from "@repo/protocol/ids";24import type { CommitSha } from "@repo/protocol/ids";25import { DateTime, Duration, Effect, Layer, Option, Ref, Schema } from "effect";2627import { CodeStore } from "../src/code-store.ts";28import { CodeStoreCounts, CodeStoreMemory } from "../src/code-store/memory.ts";29import { logOf, whyOf } from "../src/code.ts";30import type { CodeProject } from "../src/code.ts";31import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";32import type { CodeReads } from "../src/code/cache.ts";33import { keyOf, StoredWhy, whyKept } from "../src/code/history.ts";34import { WHY_SCAN } from "../src/code/why.ts";35import { Content, writer } from "./code-fixtures.ts";36import type { Tree } from "./code-fixtures.ts";3738const project = ProjectName.make("histkit");3940const repo = RepoName.make(project);4142const format = RepoPath.make("src/format.ts");4344const text = (value: string) => Content.Text({ text: value });4546/**47 * What the counting host saw: trees and blobs read, the most under way at48 * once, and each read's start (`+<id>`) and end (`-<id>`) in order.49 */50interface Seen {51 readonly trees: number;52 readonly blobs: number;53 readonly peak: number;54 readonly events: readonly string[];55}5657const none: Seen = { blobs: 0, events: [], peak: 0, trees: 0 };5859/** How long a read of the object `id` takes, once a test sets it. */60type Delay = Option.Option<(id: string) => Duration.Duration>;6162/**63 * The memory store, each tree and blob read counted in `seen` and, once64 * `delay` is set, taking as long as it says: a live store answers each65 * read in tens to hundreds of milliseconds.66 */67const counted = (seen: Ref.Ref<Seen>, delay: Ref.Ref<Delay>) =>68 Layer.effect(69 RepoHost,70 Effect.gen(function* () {71 const host = yield* RepoHost;72 const under = yield* Ref.make(0);7374 const timed = <A, E>(75 kind: "blobs" | "trees",76 id: string,77 read: Effect.Effect<A, E>78 ) =>79 Effect.gen(function* () {80 const now = yield* Ref.updateAndGet(under, (count) => count + 1);8182 yield* Ref.update(seen, (was) => ({83 ...was,84 events: [...was.events, `+${id}`],85 [kind]: was[kind] + 1,86 peak: Math.max(was.peak, now),87 }));8889 const wait = yield* Ref.get(delay);9091 if (Option.isSome(wait)) {92 yield* Effect.sleep(wait.value(id));93 }9495 return yield* read;96 }).pipe(97 Effect.ensuring(98 Effect.andThen(99 Ref.update(under, (count) => count - 1),100 Ref.update(seen, (was) => ({101 ...was,102 events: [...was.events, `-${id}`],103 }))104 )105 )106 );107108 return RepoHost.of({109 ...host,110 readBlob: (name, id) => timed("blobs", id, host.readBlob(name, id)),111 readTree: (name, id) => timed("trees", id, host.readTree(name, id)),112 });113 })114 ).pipe(Layer.provide(RepoHostMemory));115116const landingOf = (sha: CommitSha, ask: string): LandingView => ({117 ask: AskId.make(ask),118 assisted: [],119 author: Handle.make("bob"),120 credits: [],121 landedAt: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),122 project,123 sha: LandedSha.make(sha),124});125126/** A project's record whose landings a test may add to, each batch asked for counted. */127const recordOf = (head: CommitSha) =>128 Effect.gen(function* () {129 const landed = yield* Ref.make<readonly LandingView[]>([]);130 const asked = yield* Ref.make(0);131132 const code: CodeProject = {133 forks: Effect.succeed([]),134 head: Effect.succeedSome(LandedSha.make(head)),135 landings: (shas) =>136 Effect.gen(function* () {137 yield* Ref.update(asked, (count) => count + 1);138139 return (yield* Ref.get(landed)).filter(({ sha }) =>140 shas.includes(sha)141 );142 }),143 project,144 repo,145 };146147 return { asked, code, landed };148 });149150/** histkit's tree: its README and `src/format.ts`. */151const filesOf = (formatted: string, readme: string): Tree => [152 ["README.md", text(readme)],153 ["src/format.ts", text(formatted)],154];155156/**157 * histkit: `src/format.ts` grows over four commits (one leaves it alone),158 * then two children of the fourth: `grown` inserts two lines and changes159 * one, `still` changes only the README.160 */161const history = Effect.gen(function* () {162 const git = yield* writer;163164 const c1 = yield* git.commit("Adopt", filesOf("a\nb\n", "# one\n"), [], 1);165 const c2 = yield* git.commit("Readme", filesOf("a\nb\n", "# two\n"), [c1], 2);166167 const c3 = yield* git.commit(168 "Land iso",169 filesOf("a\niso\nb\n", "# two\n"),170 [c2],171 3172 );173174 const c4 = yield* git.commit(175 "Land week",176 filesOf("a\niso\nb\nweek\n", "# two\n"),177 [c3],178 4179 );180181 const grown = yield* git.commit(182 "Land more",183 filesOf("a\nx\ny\niso, changed\nb\nweek\n", "# two\n"),184 [c4],185 5186 );187188 const still = yield* git.commit(189 "Readme again",190 filesOf("a\niso\nb\nweek\n", "# three\n"),191 [c4],192 6193 );194195 yield* git.push(repo, [196 ["refs/heads/main", grown],197 ["refs/heads/still", still],198 ]);199200 return { c1, c3, c4, grown, still };201});202203/** `effect` on a fresh isolate: a code cache of its own. */204const onIsolate = <A, E, R>(effect: Effect.Effect<A, E, R>) =>205 Effect.provide(effect, CodeCacheLive(100));206207/** `effect` with a store of its own, empty: the whole walk, from nothing. */208const fromNothing = <A, E, R>(effect: Effect.Effect<A, E, R>) =>209 onIsolate(Effect.provide(effect, CodeStoreMemory));210211/** A view's ranges, the commits it names and where it stopped. */212const whyOfView = (view: {213 readonly ranges: readonly unknown[];214 readonly commits: readonly { readonly sha: CommitSha }[];215 readonly stoppedAt?: CommitSha;216}) => ({217 commits: view.commits.map(({ sha }) => sha),218 ranges: view.ranges,219 stoppedAt: view.stoppedAt,220});221222/** A test body over the counting host and one store every isolate shares. */223const within = <A, E>(224 body: (counts: {225 readonly seen: Ref.Ref<Seen>;226 readonly delay: Ref.Ref<Delay>;227 }) => Effect.Effect<A, E, RepoHost | CodeStoreCounts>228) =>229 Effect.gen(function* () {230 const seen = yield* Ref.make(none);231 const delay = yield* Ref.make<Delay>(Option.none());232233 return yield* body({ delay, seen }).pipe(234 Effect.provide(Layer.merge(counted(seen, delay), CodeStoreMemory))235 );236 });237238const long = { timeout: 30_000 };239240describe("code history kept across isolates", () => {241 it.effect(242 "reads a why another isolate computed without a tree or a blob, asking only for its landings",243 () =>244 within(({ seen }) =>245 Effect.gen(function* () {246 const { grown } = yield* history;247 const { asked, code } = yield* recordOf(grown);248 const first = yield* onIsolate(whyOf(code, Option.none(), format));249250 yield* Ref.set(seen, none);251 yield* Ref.set(asked, 0);252253 const again = yield* onIsolate(whyOf(code, Option.none(), format));254255 expect(again).toStrictEqual(first);256 expect(yield* Ref.get(seen)).toStrictEqual(none);257 expect(yield* Ref.get(asked)).toBe(1);258 })259 )260 );261262 it.effect(263 "reads a path's log page another isolate computed without a tree or a blob",264 () =>265 within(({ seen }) =>266 Effect.gen(function* () {267 const { grown } = yield* history;268 const { code } = yield* recordOf(grown);269270 const page = {271 at: Option.none(),272 from: 0,273 limit: 2,274 path: Option.some(format),275 };276277 const first = yield* onIsolate(logOf(code, page));278279 yield* Ref.set(seen, none);280281 const again = yield* onIsolate(logOf(code, page));282283 expect(again).toStrictEqual(first);284 expect(first.commits).toHaveLength(2);285 expect(yield* Ref.get(seen)).toStrictEqual(none);286 })287 )288 );289});290291/** The first page of `src/format.ts`'s log from `from`. */292const formatLog = (from: CommitSha) => ({293 at: Option.some(from),294 from: 0,295 limit: 30,296 path: Option.some(format),297});298299describe("code history one landing past a kept result", () => {300 it.effect(301 "reads only the two versions' blobs for a why, and agrees with the whole walk",302 () =>303 within(({ seen }) =>304 Effect.gen(function* () {305 const { c4, grown } = yield* history;306 const { code } = yield* recordOf(grown);307308 yield* onIsolate(whyOf(code, Option.some(c4), format));309 yield* Ref.set(seen, none);310311 const next = yield* onIsolate(312 whyOf(code, Option.some(grown), format)313 );314315 const counts = yield* Ref.get(seen);316 const whole = yield* fromNothing(whyOf(code, Option.none(), format));317318 expect(counts.blobs).toBeLessThanOrEqual(2);319 expect(whyOfView(next)).toStrictEqual(whyOfView(whole));320 expect(whyOfView(next).commits).toContain(grown);321 })322 )323 );324325 it.effect(326 "reads no blob for a why when the landing left the file alone",327 () =>328 within(({ seen }) =>329 Effect.gen(function* () {330 const { c4, grown, still } = yield* history;331 const { code } = yield* recordOf(grown);332 const kept = yield* onIsolate(whyOf(code, Option.some(c4), format));333334 yield* Ref.set(seen, none);335336 const next = yield* onIsolate(337 whyOf(code, Option.some(still), format)338 );339340 expect((yield* Ref.get(seen)).blobs).toBe(0);341 expect(whyOfView(next)).toStrictEqual(whyOfView(kept));342 expect(next.at).toBe(still);343 })344 )345 );346347 it.effect(348 "reads only the new commits' entries for a path's log, and agrees with the whole scan",349 () =>350 within(({ seen }) =>351 Effect.gen(function* () {352 const { c4, grown } = yield* history;353 const { code } = yield* recordOf(grown);354355 yield* onIsolate(logOf(code, formatLog(c4)));356 yield* Ref.set(seen, none);357358 const next = yield* onIsolate(logOf(code, formatLog(grown)));359 const counts = yield* Ref.get(seen);360 const whole = yield* fromNothing(logOf(code, formatLog(grown)));361362 // `src/format.ts` two folders down, in `grown` and in `c4`.363 expect(counts.trees).toBeLessThanOrEqual(4);364 expect(next).toStrictEqual(whole);365 expect(next.commits.map(({ sha }) => sha)[0]).toBe(grown);366 })367 )368 );369});370371describe("landings beside kept history", () => {372 it.effect("show on the next view once the record has them", () =>373 within(() =>374 Effect.gen(function* () {375 const { c1, grown } = yield* history;376 const { code, landed } = yield* recordOf(grown);377378 // One isolate, so the second view finds the first's history kept.379 const [before, after] = yield* onIsolate(380 Effect.gen(function* () {381 const first = yield* whyOf(code, Option.none(), format);382383 yield* Ref.set(landed, [landingOf(c1, "adopt")]);384385 return [first, yield* whyOf(code, Option.none(), format)] as const;386 })387 );388389 expect(before.landings).toStrictEqual([]);390 expect(after.landings.map(({ ask, sha }) => [sha, ask])).toStrictEqual([391 [c1, "adopt"],392 ]);393 })394 )395 );396});397398/**399 * `count` commits: each changes `count.txt` at the root and leaves400 * `a/b/c/d/deep.txt` alone, so the commits' root trees all differ and the401 * folders under them never do.402 */403const deepHistory = (count: number) =>404 Effect.gen(function* () {405 const git = yield* writer;406 const shas: CommitSha[] = [];407408 for (let at = 1; at <= count; at += 1) {409 shas.push(410 yield* git.commit(411 `Commit ${at}`,412 [413 ["a/b/c/d/deep.txt", text("deep\n")],414 ["count.txt", text(`${at}\n`)],415 ],416 shas.slice(-1),417 at418 )419 );420 }421422 const head = shas.at(-1);423424 if (head === undefined) {425 return yield* Effect.die("no commits");426 }427428 yield* git.push(repo, [["refs/heads/main", head]]);429430 return { head, shas };431 });432433describe("a cold walk", () => {434 it.live(435 "keeps at least 40 reads under way when each takes 50 ms",436 () =>437 within(({ delay, seen }) =>438 Effect.gen(function* () {439 const { head, shas } = yield* deepHistory(64);440 const { code } = yield* recordOf(head);441442 yield* Ref.set(seen, none);443 yield* Ref.set(444 delay,445 Option.some(() => Duration.millis(50))446 );447448 const view = yield* whyOf(449 code,450 Option.none(),451 RepoPath.make("a/b/c/d/deep.txt")452 );453454 expect(view.ranges).toStrictEqual([455 { end: 1, sha: shas[0], start: 1 },456 ]);457 expect((yield* Ref.get(seen)).peak).toBeGreaterThanOrEqual(40);458 })459 ),460 long461 );462463 // Counted, not timed: a batch of 16 waits for its slowest read, so while464 // one commit's folder takes a second, at most its 15 neighbours finish;465 // with no barrier, every other commit does. Wall time under a loaded466 // machine says less than this count (the walk took about a quarter of467 // the batched walk's 1,250 ms when each read took 50 ms).468 it.live(469 "goes on past a slow read: every other commit's folder is read while one takes a second",470 () =>471 within(({ delay, seen }) =>472 Effect.gen(function* () {473 const { head, shas } = yield* deepHistory(64);474 const { code } = yield* recordOf(head);475476 const roots = yield* Effect.forEach(shas, (sha) =>477 RepoHost.use((host) => host.readCommit(repo, sha)).pipe(478 Effect.flatMap(Effect.fromOption),479 Effect.map(({ tree }) => tree),480 Effect.orDie481 )482 );483484 // The commit after the head: the first the pass looks up.485 const slow = roots[62] ?? "";486487 yield* Ref.set(seen, none);488 yield* Ref.set(489 delay,490 Option.some((id) => Duration.millis(id === slow ? 1000 : 10))491 );492493 yield* whyOf(code, Option.none(), RepoPath.make("a/b/c/d/deep.txt"));494495 const { events } = yield* Ref.get(seen);496497 const during = events.slice(498 events.indexOf(`+${slow}`),499 events.indexOf(`-${slow}`)500 );501502 const others = new Set(roots.slice(0, 62).map((tree) => `-${tree}`));503504 expect(505 during.filter((event) => others.has(event)).length506 ).toBeGreaterThanOrEqual(60);507 })508 ),509 long510 );511512 it.effect(513 "looks each commit's entry up once in a path's log",514 () =>515 within(({ seen }) =>516 Effect.gen(function* () {517 const { head } = yield* deepHistory(200);518 const { code } = yield* recordOf(head);519520 yield* Ref.set(seen, none);521522 const { commits } = yield* logOf(code, {523 at: Option.none(),524 from: 0,525 limit: 30,526 path: Option.some(RepoPath.make("count.txt")),527 });528529 expect(commits).toHaveLength(30);530 // Each commit's root tree read once from the store. The view531 // shares a tree read under way among its fibers, so this count532 // holds the store's reads, not how often the walk asked.533 expect((yield* Ref.get(seen)).trees).toBe(200);534 })535 ),536 long537 );538});539540describe("a kept value that no longer decodes", () => {541 it.effect("is computed again and replaced", () =>542 within(({ seen }) =>543 Effect.gen(function* () {544 const { grown } = yield* history;545 const { code } = yield* recordOf(grown);546 const store = yield* CodeStore;547548 const key = yield* keyOf(whyKept, {549 commit: grown,550 path: format,551 repo,552 scan: WHY_SCAN,553 });554555 yield* store.put(key, '{"blob":"not an id"}');556557 const view = yield* onIsolate(whyOf(code, Option.none(), format));558 const replaced = yield* store.get(key);559560 expect((yield* Ref.get(seen)).blobs).toBeGreaterThan(0);561 expect(view.ranges.length).toBeGreaterThan(0);562 expect(563 Option.flatMap(564 replaced,565 Schema.decodeUnknownOption(Schema.fromJsonString(StoredWhy))566 ).pipe(Option.map(({ ranges }) => ranges))567 ).toStrictEqual(Option.some(view.ranges));568 expect(569 (yield* CodeStoreCounts.use(({ counts }) => counts)).puts570 ).toBeGreaterThanOrEqual(2);571 })572 )573 );574});575576/**577 * The memory store, the session each commit, tree, blob and log read ran578 * in noted in `sessions`, in order.579 */580const sessioned = (581 sessions: Ref.Ref<readonly Option.Option<RepoSessionApi>[]>582) => {583 const noted = <A, E>(read: Effect.Effect<A, E>) =>584 Effect.flatMap(RepoSession, (session) =>585 Effect.andThen(586 Ref.update(sessions, (was) => [...was, session]),587 read588 )589 );590591 return Layer.effect(592 RepoHost,593 Effect.gen(function* () {594 const host = yield* RepoHost;595596 return RepoHost.of({597 ...host,598 log: (name, at, limit, offset) =>599 noted(host.log(name, at, limit, offset)),600 readBlob: (name, id) => noted(host.readBlob(name, id)),601 readCommit: (name, sha) => noted(host.readCommit(name, sha)),602 readTree: (name, id) => noted(host.readTree(name, id)),603 });604 })605 ).pipe(Layer.provide(RepoHostMemory));606};607608/** How many sessions `sessions` names, and whether a read ran in none. */609const sessionsIn = (sessions: readonly Option.Option<RepoSessionApi>[]) => ({610 outside: sessions.some(Option.isNone),611 sessions: new Set(sessions.flatMap(Option.toArray)).size,612});613614describe("one view's reads", () => {615 it.effect("of a cold why all run in one session", () =>616 Effect.gen(function* () {617 const sessions = yield* Ref.make<618 readonly Option.Option<RepoSessionApi>[]619 >([]);620621 yield* Effect.gen(function* () {622 const { grown } = yield* history;623 const { code } = yield* recordOf(grown);624625 yield* Ref.set(sessions, []);626 yield* onIsolate(whyOf(code, Option.none(), format));627 }).pipe(628 Effect.provide(Layer.merge(sessioned(sessions), CodeStoreMemory))629 );630631 expect(sessionsIn(yield* Ref.get(sessions))).toStrictEqual({632 outside: false,633 sessions: 1,634 });635 })636 );637638 it.effect("of a cold path's log page all run in one session", () =>639 Effect.gen(function* () {640 const sessions = yield* Ref.make<641 readonly Option.Option<RepoSessionApi>[]642 >([]);643644 yield* Effect.gen(function* () {645 const { grown } = yield* history;646 const { code } = yield* recordOf(grown);647648 yield* Ref.set(sessions, []);649 yield* onIsolate(logOf(code, formatLog(grown)));650 }).pipe(651 Effect.provide(Layer.merge(sessioned(sessions), CodeStoreMemory))652 );653654 expect(sessionsIn(yield* Ref.get(sessions))).toStrictEqual({655 outside: false,656 sessions: 1,657 });658 })659 );660});661662describe("kept history in the isolate's cache", () => {663 it.effect(664 "is kept with the heavy reads: a why's ranges grow with its file",665 () =>666 within(() =>667 Effect.gen(function* () {668 const { grown } = yield* history;669 const { code } = yield* recordOf(grown);670671 const seen = yield* Ref.make<readonly (readonly [string, boolean])[]>(672 []673 );674675 const spy: CodeReads = {676 through: (key, read, keeping = {}) =>677 Effect.andThen(678 Ref.update(seen, (was) => [679 ...was,680 [key, keeping.heavy === true] as const,681 ]),682 read683 ),684 };685686 yield* Effect.all([687 whyOf(code, Option.none(), format),688 logOf(code, formatLog(grown)),689 ]).pipe(Effect.provideService(CodeCache, spy));690691 const kept = (yield* Ref.get(seen)).filter(([key]) =>692 /\/(?:why|path-log)\/v\d+\//u.test(key)693 );694695 expect(kept.length).toBeGreaterThan(0);696 expect(kept.filter(([, heavy]) => !heavy)).toStrictEqual([]);697 })698 )699 );700});
modified:packages/project/test/code-why.test.ts+7 added-4 removed
23 unmodified lines
2425import { whyOf } from "../src/code.ts";26import type { CodeProject } from "../src/code.ts";27import { CodeCacheLive } from "../src/code/cache.ts";28import { READS_AT_ONCE } from "../src/code/tree.ts";29import { whyView } from "../src/code/why.ts";30import {31 Content,32 growingHistory,
249 unmodified lines
282283 expect(ranges).toStrictEqual([{ end: 1, sha: shas[0], start: 1 }]);284 }).pipe(Effect.provide(overlappingTrees(reading, peak)));285286 // `READS_AT_ONCE` lookups under way, and the head's own beside them.285 expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(8);286 expect(yield* Ref.get(peak)).toBeLessThanOrEqual(16);287 expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);288 expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE + 1);289 }),290 { timeout: 30_000 }291 );292
21 unmodified lines
314 shas.map((sha, at) => ({ end: at + 1, sha, start: at + 1 }))315 );316 }).pipe(Effect.provide(overlappingTrees(reading, peak, "blob")));317318 // `READS_AT_ONCE` lookups under way, and the head's own beside them.316 expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(8);317 expect(yield* Ref.get(peak)).toBeLessThanOrEqual(16);319 expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);320 expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE + 1);321 }),322 { timeout: 30_000 }323 );324
30 unmodified lines
modified:packages/project/test/code.test.ts+5 added-4 removed
28 unmodified lines
29} from "../src/code.ts";30import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";31import { filesUnder } from "../src/code/paths.ts";32import { compareTags } from "../src/code/refs.ts";33import { READS_AT_ONCE } from "../src/code/tree.ts";34import {35 big,36 datekit,37 fork,
417 unmodified lines
455456 expect(commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);457 }).pipe(Effect.provide(overlappingTrees(reading, peak)));458458 // 64 commits, two trees each: one at a time a live store took a459 // minute for 200; sixteen commits at once, each its two trees.460 expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(8);461 expect(yield* Ref.get(peak)).toBeLessThanOrEqual(32);459 // 64 commits, each its one root tree: one at a time a live store460 // took a minute for 200; `READS_AT_ONCE` commits at once now.461 expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);462 expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE);463 }),464 long465 );466});
175 unmodified lines
modified:packages/testkit/src/fake-artifacts-binding.ts+34 added-6 removed
7 unmodified lines
8 * - under load, a fork answers HTTP 500 after making the repo, and the retry9 * answers 409: pass `{ forkFailures: n }`;10 * - reads by ref resolve short branch names and commit ids only, never11 * `refs/heads/main`;12 * - `info().lastPushAt` stays `null` after pushes.12 * - `info().lastPushAt` stays `null` after pushes;13 * - past 2,000 requests per 10 s a repo's reads are refused as rate limited:14 * pass `{ rateLimited: n }` to refuse the next `n` reads (ASSUMPTION: the15 * refusal names the limit in its message, as an HTTP 429's "Too Many16 * Requests" does; no live one has been seen yet).17 *18 * It takes its host structurally (`HostLike`), so `@repo/testkit` depends on19 * no adapter package: a `RepoHost` service value satisfies `HostLike`. Each20 * call runs the host's Effect with `Effect.runPromise`, since the binding is
160 unmodified lines
181 * `IMPORT_IN_PROGRESS`: an import Artifacts is still copying after182 * `import()` returned, as a large one is.183 */184 readonly importing?: number;185 /** How many of the next reads (a blob, a tree, a commit, a log) are refused as rate limited. */186 readonly rateLimited?: number;187}188189/** A refusal the binding throws, before it becomes the thrown error. */190class Refused extends Data.TaggedError("Refused")<{
132 unmodified lines
323 options: FakeOptions = {}324): Artifacts => {325 const kept = new Map<RepoName, Kept>();326 let forkFailures = options.forkFailures ?? 0;327 let rateLimited = options.rateLimited ?? 0;328 let made = 0;329 // Each imported repo's `get`s still to answer that the import runs on.330 const importing = new Map<RepoName, number>();331
12 unmodified lines
344 Effect.runPromise(345 Effect.mapError(effect, (failure) => thrown(refusalOf(failure)))346 );347348 /** What a read past the rate limit throws (see the module's doc). */349 const limited = () =>350 options.codeless === true351 ? new Error("ArtifactsError: Too many requests: rate limit exceeded")352 : Object.assign(new Error("Too many requests: rate limit exceeded"), {353 code: "RATE_LIMITED",354 name: "ArtifactsError" as const,355 numericCode: 0,356 });357358 /** One read, refused while the scripted rate limit lasts. */359 const read = <A>(effect: Effect.Effect<A, Refused | HostError>) => {360 if (rateLimited > 0) {361 rateLimited -= 1;362363 return Promise.reject(limited());364 }365366 return run(effect);367 };368369 const remoteOf = (name: RepoName) =>370 options.remoteBase === undefined371 ? host.remote(name)372 : host.remote(name).pipe(Effect.as(`${options.remoteBase}/${name}.git`));
149 unmodified lines
522 })523 )524 ),525 log: (logOptions) =>498 run(526 read(527 Effect.gen(function* () {528 const ref = logOptions?.ref ?? "HEAD";529 const limit = Math.min(logOptions?.limit ?? 50, 1000);530 const offset = logOptions?.offset ?? 0;
12 unmodified lines
543 return commits.slice(offset).map(metadataOf);544 })545 ),546 readBlob: (hash) =>519 run(547 read(548 objectId(hash).pipe(549 Effect.flatMap((blob) => host.readBlob(name, blob)),550 Effect.map((bytes) => Option.getOrNull(Option.map(bytes, blobOf)))551 )552 ),553 readCommit: (hash) =>526 run(554 read(555 objectId(hash).pipe(556 Effect.flatMap((sha) => host.readCommit(name, CommitSha.make(sha))),557 Effect.map((commit) =>558 Option.getOrNull(Option.map(commit, metadataOf))559 )560 )561 ),562 readFile: ({ path, ref }) =>535 run(563 read(564 Effect.gen(function* () {565 const file = decodePath(path);566 const at = revisionOf(ref);567
13 unmodified lines
581 return Option.getOrNull(Option.map(bytes, blobOf));582 })583 ),584 readTree: (hash) =>557 run(585 read(586 objectId(hash).pipe(587 Effect.flatMap((tree) => host.readTree(name, tree)),588 Effect.map((entries) =>589 Option.getOrNull(Option.map(entries, (each) => each.map(entryOf)))
128 unmodified lines