why.ts
This file
Path
packages/project/src/code/why.ts
540 lines · 14.4 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
1import { inRepoSession, ObjectId, RepoHost } from "@repo/artifacts/repo-host";2import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";3import {4 blameFrom,5 isSettled,6 linesOf,7 settle,8 traceBack,9} from "@repo/git/blame";10import { Edit, lineDiff } from "@repo/git/line-diff";11import type { Rev, WhyRange, WhyView } from "@repo/protocol/domain/code";12import { BlobSha } from "@repo/protocol/ids";13import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";14import { UnknownPath } from "@repo/protocol/refusal";15import type { UnknownRevision } from "@repo/protocol/refusal";16import { Array, Effect, Option, Ref, Stream } from "effect";1718import type { CodeProject } from "../code.ts";19import { MAX_LANDINGS } from "../project.ts";20import { asOneView } from "./cache.ts";21import { versionAt, walkableAt } from "./file-walk.ts";22import type { FileVersion } from "./file-walk.ts";23import { contentsOf, contentsOfBytes, unlessTooLarge } from "./file.ts";24import {25 INCREMENT_REACH,26 keyOf,27 keptOnlyIfCanonical,28 recall,29 throughHistory,30 whyKept,31} from "./history.ts";32import type { StoredWhy } from "./history.ts";33import { commitViews, pageOf } from "./log.ts";34import { commitAt, resolveAt } from "./revision.ts";35import { entryAt, READS_AT_ONCE } from "./tree.ts";3637export const WHY_SCAN = 200;3839interface Version {40 readonly blob: BlobSha;41 readonly commit: Commit;42}4344interface Versions {45 readonly versions: readonly Version[];46 readonly stopped: boolean;47}4849const blobAt = (repo: RepoName, commit: Commit, path: RepoPath) =>50 Effect.map(51 entryAt(repo, commit.tree, path),52 Option.flatMap((entry) =>53 entry.type === "blob"54 ? Option.some(BlobSha.make(entry.sha))55 : Option.none()56 )57 );5859const lookups = <E, R>(60 commits: readonly Commit[],61 blobOf: (commit: Commit) => Effect.Effect<Option.Option<BlobSha>, E, R>62) =>63 Effect.gen(function* () {64 const missingAt = yield* Ref.make(commits.length);6566 const found = yield* Effect.forEach(67 commits,68 (commit, at) =>69 Effect.gen(function* () {70 if (at > (yield* Ref.get(missingAt))) {71 return Option.none();72 }7374 const blob = yield* blobOf(commit);7576 if (Option.isNone(blob)) {77 yield* Ref.update(missingAt, (was) => Math.min(was, at));78 }7980 return Option.some({ blob, commit });81 }),82 { concurrency: READS_AT_ONCE }83 );8485 const looked = Array.getSomes(found);86 const missing = looked.findIndex(({ blob }) => Option.isNone(blob));8788 return missing === -1 ? looked : looked.slice(0, missing + 1);89 });9091const versionsOf = (92 newest: Version,93 found: readonly {94 readonly blob: Option.Option<BlobSha>;95 readonly commit: Commit;96 }[]97): Versions => {98 const versions: Version[] = [];99 let current = newest;100101 for (const { blob, commit } of found) {102 if (Option.contains(blob, current.blob)) {103 current = { blob: current.blob, commit };104 } else {105 versions.push(current);106107 if (Option.isNone(blob)) {108 // The file was born in the commit after this one.109 return { stopped: false, versions };110 }111112 current = { blob: blob.value, commit };113 }114 }115116 versions.push(current);117118 return {119 stopped: current.commit.parents.length > 0,120 versions,121 };122};123124// Read past the cache: old versions are seldom viewed, and keeping them would125// push out the reads a reader comes back to.126const textOf = (repo: RepoName, blob: BlobSha) =>127 unlessTooLarge(128 RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(129 Effect.map(Option.flatMap((bytes) => contentsOfBytes(bytes).text))130 ),131 Option.none132 ).pipe(Effect.map(Option.getOrElse(() => "")));133134const landingsOf = (project: CodeProject, shas: readonly CommitSha[]) =>135 Effect.map(136 Effect.forEach(Array.chunksOf(shas, MAX_LANDINGS), project.landings),137 Array.flatten138 );139140const ownersOf = (ranges: readonly WhyRange[]): readonly CommitSha[] =>141 ranges.flatMap(({ end, sha, start }) =>142 Array.makeBy(end - start + 1, () => sha)143 );144145const rangesOf = (owners: readonly CommitSha[]): readonly WhyRange[] => {146 const ranges: WhyRange[] = [];147148 for (const [index, sha] of owners.entries()) {149 const last = ranges.at(-1);150 const line = index + 1;151152 if (last !== undefined && last.sha === sha && last.end === index) {153 ranges[ranges.length - 1] = { ...last, end: line };154 } else {155 ranges.push({ end: line, sha, start: line });156 }157 }158159 return ranges;160};161162const carried = (163 before: { readonly text: string; readonly owners: readonly CommitSha[] },164 after: string,165 sha: CommitSha166): readonly CommitSha[] => {167 const lines = linesOf(after);168 const owners: CommitSha[] = lines.map(() => sha);169170 for (const edit of lineDiff(linesOf(before.text), lines)) {171 if (Edit.$is("Equal")(edit)) {172 for (let at = 0; at < edit.count; at += 1) {173 owners[edit.newStart + at] = before.owners[edit.oldStart + at] ?? sha;174 }175 }176 }177178 return owners;179};180181const nearestKept = (182 repo: RepoName,183 path: RepoPath,184 log: readonly Commit[],185 scan: number186) =>187 Effect.map(188 Effect.forEach(189 log.slice(1, INCREMENT_REACH + 1),190 ({ sha }) =>191 Effect.flatMap(192 keyOf(whyKept, { commit: sha, path, repo, scan }),193 (key) => recall(whyKept, key)194 ),195 { concurrency: INCREMENT_REACH }196 ),197 (found) =>198 Array.findFirst(found, (kept, at) =>199 Option.map(kept, (value) => ({ back: at + 1, kept: value }))200 )201 );202203const forward = (204 repo: RepoName,205 log: readonly Commit[],206 newest: BlobSha,207 between: readonly Option.Option<BlobSha>[],208 from: { readonly back: number; readonly kept: StoredWhy }209): Effect.Effect<Option.Option<StoredWhy>, RepoNotFound, RepoHost> =>210 Effect.gen(function* () {211 if (!between.every(Option.isSome)) {212 return Option.none();213 }214215 const blobs = [newest, ...between.map(Option.getOrThrow)];216217 const changes = blobs218 .flatMap((blob, at) => {219 const parent = blobs[at + 1] ?? from.kept.blob;220 const commit = log[at];221222 return blob === parent || commit === undefined223 ? []224 : [{ blob, sha: commit.sha }];225 })226 .toReversed();227228 if (changes.length === 0) {229 return Option.some(from.kept);230 }231232 const newestContents = yield* contentsOf(repo, newest);233234 if (235 Option.isNone(newestContents) ||236 Option.isNone(newestContents.value.text)237 ) {238 return Option.some({ blob: newest, ranges: [], shas: [] });239 }240241 const newestText = newestContents.value.text.value;242243 const [base, ...texts] = yield* Effect.forEach(244 [{ blob: from.kept.blob }, ...changes],245 ({ blob }) =>246 blob === newest ? Effect.succeed(newestText) : textOf(repo, blob),247 { concurrency: READS_AT_ONCE }248 );249250 let tracing = {251 owners: ownersOf(from.kept.ranges),252 text: base ?? "",253 };254255 for (const [{ sha }, text] of Array.zip(changes, texts)) {256 tracing = { owners: carried(tracing, text, sha), text };257 }258259 const named = new Set<string>(tracing.owners);260 const added = changes.map(({ sha }) => sha).toReversed();261262 const shas = [...added, ...from.kept.shas].filter(263 (sha, at, all) => named.has(sha) && all.indexOf(sha) === at264 );265266 const stoppedAt = Option.filter(267 Option.fromUndefinedOr(from.kept.stoppedAt),268 (sha) => named.has(sha)269 );270271 return Option.some({272 blob: newest,273 ranges: rangesOf(tracing.owners),274 shas,275 ...Option.match(stoppedAt, {276 onNone: () => ({}),277 onSome: (sha) => ({ stoppedAt: sha }),278 }),279 });280 });281282const blamed = <R>(283 head: Commit,284 newest: BlobSha,285 text: string,286 found: readonly {287 readonly blob: Option.Option<BlobSha>;288 readonly commit: Commit;289 }[],290 readText: (blob: BlobSha) => Effect.Effect<string, RepoNotFound, R>291): Effect.Effect<StoredWhy, RepoNotFound, R> =>292 Effect.gen(function* () {293 const none: StoredWhy = { blob: newest, ranges: [], shas: [] };294295 const { stopped, versions } = versionsOf(296 { blob: newest, commit: head },297 found298 );299300 const [first = { blob: newest, commit: head }, ...older] = versions;301302 const tracing = yield* Stream.fromIterable(older).pipe(303 Stream.mapEffect(304 (version) =>305 Effect.map(readText(version.blob), (read) => ({306 sha: version.commit.sha,307 text: read,308 })),309 { concurrency: READS_AT_ONCE }310 ),311 Stream.scan(() => blameFrom({ sha: first.commit.sha, text }), traceBack),312 Stream.takeUntil(isSettled),313 Stream.runLast,314 Effect.map(Option.getOrThrow)315 );316317 const { ranges, reachedEnd } = settle(tracing);318 const named = new Set<string>(ranges.map(({ sha }) => sha));319320 const shas = versions321 .map(({ commit }) => commit.sha)322 .filter((sha) => named.has(sha));323324 const last = versions.at(-1);325326 // Lines the walk did not see brought: they point at where it stopped.327 return stopped && reachedEnd && last !== undefined328 ? { ...none, ranges, shas, stoppedAt: last.commit.sha }329 : { ...none, ranges, shas };330 });331332const walkedByFile = (333 repo: RepoName,334 path: RepoPath,335 log: readonly Commit[],336 head: Commit,337 newest: FileVersion338): Effect.Effect<StoredWhy, RepoNotFound, RepoHost> =>339 Effect.gen(function* () {340 const { text } = contentsOfBytes(newest.bytes);341342 if (Option.isNone(text)) {343 return { blob: newest.blob, ranges: [], shas: [] };344 }345346 const texts = new Map<string, Uint8Array>([[newest.blob, newest.bytes]]);347348 const found = yield* lookups(log.slice(1), (commit) =>349 versionAt(repo, commit.sha, path).pipe(350 Effect.map(351 Option.map(({ blob, bytes }) => {352 if (!texts.has(blob)) {353 texts.set(blob, bytes);354 }355356 return blob;357 })358 )359 )360 );361362 return yield* blamed(head, newest.blob, text.value, found, (blob) => {363 const bytes = texts.get(blob);364365 return bytes === undefined366 ? textOf(repo, blob)367 : Effect.succeed(368 Option.getOrElse(contentsOfBytes(bytes).text, () => "")369 );370 });371 });372373const walked = (374 repo: RepoName,375 at: CommitSha,376 path: RepoPath,377 log: readonly Commit[],378 head: Commit379): Effect.Effect<StoredWhy, UnknownPath | RepoNotFound, RepoHost> =>380 Effect.gen(function* () {381 const whole = yield* walkableAt(repo, head.sha, path);382383 if (Option.isSome(whole)) {384 return yield* walkedByFile(repo, path, log, head, whole.value);385 }386387 const [headSide, found] = yield* Effect.all(388 [389 Effect.gen(function* () {390 const blob = yield* blobAt(repo, head, path);391392 if (Option.isNone(blob)) {393 return yield* new UnknownPath({ commit: at, path });394 }395396 return {397 blob: blob.value,398 contents: yield* contentsOf(repo, blob.value),399 };400 }),401 lookups(log.slice(1), (commit) => blobAt(repo, commit, path)),402 ],403 { concurrency: 2 }404 );405406 const newest = headSide.blob;407 const { contents } = headSide;408409 if (Option.isNone(contents) || Option.isNone(contents.value.text)) {410 return { blob: newest, ranges: [], shas: [] };411 }412413 return yield* blamed(414 head,415 newest,416 contents.value.text.value,417 found,418 (blob) => textOf(repo, blob)419 );420 });421422const computed = (423 repo: RepoName,424 at: CommitSha,425 path: RepoPath,426 scan: number427): Effect.Effect<StoredWhy, UnknownPath | RepoNotFound, RepoHost> =>428 Effect.gen(function* () {429 const log = yield* pageOf(repo, at, 0, Math.max(1, scan));430 const [head] = log;431432 if (head === undefined) {433 return yield* Effect.die(`${repo} has no log from ${at}`);434 }435436 const kept = yield* nearestKept(repo, path, log, scan);437438 if (Option.isSome(kept)) {439 const [newest, ...between] = yield* Effect.forEach(440 log.slice(0, kept.value.back),441 (commit) => blobAt(repo, commit, path),442 { concurrency: READS_AT_ONCE }443 );444445 if (newest === undefined || Option.isNone(newest)) {446 return yield* new UnknownPath({ commit: at, path });447 }448449 const carriedForward = yield* forward(450 repo,451 log,452 newest.value,453 between,454 kept.value455 );456457 if (Option.isSome(carriedForward)) {458 return carriedForward.value;459 }460 }461462 return yield* walked(repo, at, path, log, head);463 });464465const viewOf = (466 project: CodeProject,467 repo: RepoName,468 at: CommitSha,469 path: RepoPath,470 kept: StoredWhy,471 scan: number472): Effect.Effect<WhyView, RepoNotFound, RepoHost> =>473 Effect.gen(function* () {474 const log =475 kept.shas.length === 0476 ? []477 : yield* pageOf(repo, at, 0, Math.max(1, scan));478479 const bySha = new Map<string, Commit>(480 log.map((commit) => [commit.sha, commit])481 );482483 const commits = yield* Effect.forEach(484 kept.shas,485 (sha) =>486 Option.match(Option.fromUndefinedOr(bySha.get(sha)), {487 onNone: () =>488 commitAt(repo, sha).pipe(489 Effect.flatMap(Effect.fromOption),490 Effect.catchTag("NoSuchElementError", () =>491 Effect.die(`${repo} has no commit ${sha}`)492 )493 ),494 onSome: Effect.succeed,495 }),496 { concurrency: READS_AT_ONCE }497 );498499 const views = yield* commitViews(500 { ...project, landings: () => Effect.succeed([]) },501 commits502 );503504 const landings = yield* landingsOf(project, kept.shas);505506 return {507 at,508 commits: views,509 landings,510 path,511 ranges: kept.ranges,512 ...Option.match(Option.fromUndefinedOr(kept.stoppedAt), {513 onNone: () => ({}),514 onSome: (stoppedAt) => ({ stoppedAt }),515 }),516 };517 });518519export const whyView = (520 project: CodeProject,521 at: Option.Option<Rev>,522 path: RepoPath,523 scan: number = WHY_SCAN524): Effect.Effect<WhyView, UnknownRevision | UnknownPath, RepoHost> =>525 Effect.gen(function* () {526 const resolved = yield* resolveAt(project, at);527 const { commit, repo } = resolved;528 const key = yield* keyOf(whyKept, { commit, path, repo, scan });529530 const kept = yield* keptOnlyIfCanonical(531 resolved,532 throughHistory(533 whyKept,534 key,535 asOneView(computed(repo, commit, path, scan))536 )537 );538539 return yield* viewOf(project, repo, commit, path, kept, scan);540 }).pipe(inRepoSession, Effect.catchTag("RepoNotFound", Effect.die));