Merge perf/code-store into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The code store keeps commits, trees, blobs, log pages and path pointers by id. Its five lint findings and the compare-type errors are fixed: the file module's imports first, the cache's told fields typed, rawOf before rawFor, countedIn before its use, and the folder-name sorts over a defined segment.
authored by oscabriel · committed by oscabriel · parents 29b0353, dec332c · Browse files · 15 files·+767 added−206 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+767 added−206 removed
- tests:+262 added−3 removed
- other:+505 added−203 removed
Provenance
- Commit
ef0ddbd- Tree
06ce9c3- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
29b0353- Parent 2
dec332c
15 files changed+767 added−206 removed
modified:apps/web/src/dev/server.ts+5 added-1 removed
123456746 unmodified lines54555657565859606162636439 unmodified linesimport { RepoHost } from "@repo/artifacts/repo-host";import { CodeStore } from "@repo/project/code-store";import { CodeCache } from "@repo/project/code/cache";import { rawFor } from "@repo/project/code/raw";import { Projects } from "@repo/project/projects";import { Contracts } from "@repo/protocol/contracts";import { ProjectName } from "@repo/protocol/ids";46 unmodified lines
const raw = Layer.unwrap( Effect.gen(function* () { const services = Context.make(RepoHost, yield* RepoHost).pipe( Context.add(Projects, yield* Projects) Context.add(Projects, yield* Projects), Context.add(CodeCache, yield* CodeCache), Context.add(CodeStore, yield* CodeStore) );
const answer = Effect.gen(function* () { const params = yield* HttpRouter.params;39 unmodified linesmodified:apps/web/src/dev/world.ts+8 added
3 unmodified lines4567891011121311 unmodified lines25262728293031323334353637383940414236 unmodified lines3 unmodified linesimport { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";import { cannedDrafter } from "@repo/drafting/draft-runs/canned";import { withDraftRunsInline } from "@repo/drafting/draft-runs/inline";import { AlarmsMemory } from "@repo/project/alarms/memory";import { CodeStoreMemory } from "@repo/project/code-store/memory";import { CodeCacheLive } from "@repo/project/code/cache";import { ProjectDescriptionsMemory } from "@repo/project/description/memory";import type { FrontPage } from "@repo/project/front-page";import type { Lander } from "@repo/project/lander";import { FinishersFromChecks } from "@repo/project/project";11 unmodified linesimport { DevFrontPage } from "./front-page.ts";import { DevLander } from "./lander.ts";import { DevProjection } from "./projection.ts";
// Objects kept as the platform keeps them (`apps/platform/src/ports.ts`), so a// page's second read of a commit, a tree or a blob reaches the host no more.const CODE_READS_KEPT = { heavy: 40, light: 2000 };
const ports = Layer.mergeAll( AlarmsMemory, DevAnswerRunsLayer, cannedDrafter, CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy), CodeStoreMemory, DevProjection, RulesEvaluatorJson.pipe(Layer.provide(FinishersFromChecks))).pipe( Layer.provideMerge(Layer.mergeAll(DevChecker, DevLander)),36 unmodified linesadded:packages/project/src/code/blob.ts+81 added
1+/** A blob's contents by its id, kept in the isolate and the store while its text is under the cap. */2+import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";3+import type { RepoNotFound } from "@repo/artifacts/repo-host";4+import type { BlobSha, RepoName } from "@repo/protocol/ids";5+import { Effect, Option, Schema } from "effect";6+7+import { blobKept, objectKey, throughStore } from "./objects.ts";8+9+export const TEXT_CAP = 1024 * 1024;10+11+// git's own test: a NUL among the first bytes means the blob is not text.12+const SNIFF = 8192;13+14+const KEPT_TEXT = 256 * 1024;15+16+export const isBinary = (bytes: Uint8Array) =>17+ bytes.subarray(0, SNIFF).includes(0);18+19+export interface Contents {20+ readonly size: number;21+ readonly binary: boolean;22+ readonly truncated: boolean;23+ readonly text: Option.Option<string>;24+}25+26+const MemoryLimit = Schema.Struct({ code: Schema.Literal("MEMORY_LIMIT") });27+28+const isMemoryLimit = Schema.is(MemoryLimit);29+30+/** Artifacts' binding throws a too-large blob as a defect, which here is an answer. */31+export const unlessTooLarge = <A, E, R>(32+ read: Effect.Effect<A, E, R>,33+ tooLarge: () => A34+): Effect.Effect<A, E, R> =>35+ Effect.catchDefect(read, (defect) =>36+ isMemoryLimit(defect) ? Effect.succeed(tooLarge()) : Effect.die(defect)37+ );38+39+export const contentsOfBytes = (bytes: Uint8Array): Contents => {40+ const binary = isBinary(bytes);41+ const truncated = !binary && bytes.length > TEXT_CAP;42+43+ return {44+ binary,45+ size: bytes.length,46+ text:47+ binary || truncated48+ ? Option.none()49+ : Option.some(new TextDecoder().decode(bytes)),50+ truncated,51+ };52+};53+54+/** Kept by its id, in the isolate and the store, while its text is under the cap. */55+export const keepContents = ({ text }: Contents) =>56+ Option.match(text, {57+ onNone: () => true,58+ onSome: (read) => read.length <= KEPT_TEXT,59+ });60+61+export const contentsOf = (62+ repo: RepoName,63+ blob: BlobSha64+): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>65+ throughStore(66+ blobKept,67+ objectKey(blobKept, repo, blob),68+ unlessTooLarge(69+ RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(70+ Effect.map(Option.map(contentsOfBytes))71+ ),72+ () =>73+ Option.some({74+ binary: false,75+ size: 0,76+ text: Option.none(),77+ truncated: true,78+ })79+ ),80+ { heavy: true, keep: keepContents }81+ );modified:packages/project/src/code/file.ts+86 added-108 removed
1-import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2-import type { RepoNotFound } from "@repo/artifacts/repo-host";1+import type { RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";2 import type { FileView, Rev } from "@repo/protocol/domain/code";3 import { BlobSha } from "@repo/protocol/ids";4 import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";5 import { UnknownPath } from "@repo/protocol/refusal";6 import type { UnknownRevision } from "@repo/protocol/refusal";8-import { Effect, Option, Schema } from "effect";7+import { Effect, Option } from "effect";8 9 import type { CodeProject } from "../code.ts";11-import { CodeCache } from "./cache.ts";10+import {11+ contentsOf,12+ contentsOfBytes,13+ keepContents,14+ unlessTooLarge,15+} from "./blob.ts";16+import type { Contents } from "./blob.ts";17 import { versionAt } from "./file-walk.ts";18+import { keptOnlyIfCanonical } from "./history.ts";19+import {20+ blobKept,21+ fileKept,22+ fileKey,23+ keepObject,24+ objectKey,25+ throughStore,26+} from "./objects.ts";27 import { commitAt, resolveAt } from "./revision.ts";28+import type { Resolved } from "./revision.ts";29 import { entryAt } from "./tree.ts";30 16-export const TEXT_CAP = 1024 * 1024;31+export {32+ contentsOf,33+ contentsOfBytes,34+ isBinary,35+ TEXT_CAP,36+ unlessTooLarge,37+} from "./blob.ts";38 18-// git's own test: a NUL among the first bytes means the blob is not text.19-const SNIFF = 8192;39+export type { Contents } from "./blob.ts";40 21-const KEPT_TEXT = 256 * 1024;22-23-export const isBinary = (bytes: Uint8Array) =>24- bytes.subarray(0, SNIFF).includes(0);25-26-export interface Contents {27- readonly size: number;28- readonly binary: boolean;29- readonly truncated: boolean;30- readonly text: Option.Option<string>;31-}32-33-const MemoryLimit = Schema.Struct({ code: Schema.Literal("MEMORY_LIMIT") });34-35-const isMemoryLimit = Schema.is(MemoryLimit);36-37-/** Artifacts' binding throws a too-large blob as a defect, which here is an answer. */38-export const unlessTooLarge = <A, E, R>(39- read: Effect.Effect<A, E, R>,40- tooLarge: () => A41-): Effect.Effect<A, E, R> =>42- Effect.catchDefect(read, (defect) =>43- isMemoryLimit(defect) ? Effect.succeed(tooLarge()) : Effect.die(defect)44- );45-46-export const contentsOfBytes = (bytes: Uint8Array): Contents => {47- const binary = isBinary(bytes);48- const truncated = !binary && bytes.length > TEXT_CAP;49-50- return {51- binary,52- size: bytes.length,53- text:54- binary || truncated55- ? Option.none()56- : Option.some(new TextDecoder().decode(bytes)),57- truncated,58- };59-};60-61-export const contentsOf = (62- repo: RepoName,63- blob: BlobSha64-): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>65- Effect.gen(function* () {66- const cache = yield* CodeCache;67-68- return yield* cache.through(69- `${repo}:text:${blob}`,70- unlessTooLarge(71- RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(72- Effect.map(Option.map(contentsOfBytes))73- ),74- () =>75- Option.some({76- binary: false,77- size: 0,78- text: Option.none(),79- truncated: true,80- })81- ),82- {83- heavy: true,84- keep: (contents) =>85- Option.match(contents, {86- onNone: () => false,87- onSome: ({ text }) =>88- Option.match(text, {89- onNone: () => true,90- onSome: (read) => read.length <= KEPT_TEXT,91- }),92- }),93- }94- );95- });96-41 const viewOf = (42 commit: CommitSha,43 path: RepoPath,44 sha: BlobSha,10 unmodified lines55 onSome: (text) => ({ text }),56 }),57 });58 115-/** ASSUMPTION: Artifacts' `readFile` gives a symlink's own blob, as the tree does, rather than following it. */116-const wholeAt = (repo: RepoName, commit: CommitSha, path: RepoPath) =>59+interface Whole {60+ readonly blob: BlobSha;61+ readonly contents: Contents;62+}63+64+/**65+ * The file in one host call, kept as the blob its path names at the commit66+ * and that blob's contents, each by its id: a kept file is read from the67+ * store alone. ASSUMPTION: Artifacts' `readFile` gives a symlink's own blob,68+ * as the tree does, rather than following it.69+ */70+const wholeAt = (71+ repo: RepoName,72+ commit: CommitSha,73+ path: RepoPath74+): Effect.Effect<Option.Option<Whole>, RepoNotFound, RepoHost> =>75 Effect.gen(function* () {118- const cache = yield* CodeCache;76+ const key = yield* fileKey(repo, commit, path);77 120- return yield* cache.through(121- `${repo}:file:${commit}:${path}`,122- unlessTooLarge(versionAt(repo, commit, path), Option.none),123- {124- heavy: true,125- keep: (read) =>126- Option.match(read, {127- onNone: () => false,128- onSome: ({ bytes }) => bytes.byteLength <= KEPT_TEXT,129- }),78+ const named = yield* throughStore(fileKept, key, Effect.succeedNone);79+80+ if (Option.isSome(named)) {81+ const kept = yield* contentsOf(repo, named.value.blob);82+83+ if (Option.isSome(kept)) {84+ return Option.some({ blob: named.value.blob, contents: kept.value });85 }86+ }87+88+ const read = yield* unlessTooLarge(89+ versionAt(repo, commit, path),90+ Option.none91 );92+93+ if (Option.isNone(read)) {94+ return Option.none();95+ }96+97+ const { blob, bytes } = read.value;98+ const contents = contentsOfBytes(bytes);99+100+ yield* keepObject(fileKept, key, { blob });101+ yield* keepObject(blobKept, objectKey(blobKept, repo, blob), contents, {102+ heavy: true,103+ keep: keepContents,104+ });105+106+ return Option.some({ blob, contents });107 });108 134-export const fileView = (135- project: CodeProject,136- at: Option.Option<Rev>,109+const fileAtCommit = (110+ { commit, repo }: Resolved,111 path: RepoPath138-): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>112+): Effect.Effect<FileView, UnknownPath, RepoHost> =>113 Effect.gen(function* () {140- const { commit, repo } = yield* resolveAt(project, at);141-114 const whole = yield* wholeAt(repo, commit, path).pipe(Effect.orDie);115 116 if (Option.isSome(whole)) {145- return viewOf(146- commit,147- path,148- whole.value.blob,149- contentsOfBytes(whole.value.bytes)150- );117+ return viewOf(commit, path, whole.value.blob, whole.value.contents);118 }119 120 const { tree } = yield* commitAt(repo, commit).pipe(121 Effect.flatMap(Effect.fromOption),15 unmodified lines137 );138 139 return viewOf(commit, path, sha, contents);140 });141+142+export const fileView = (143+ project: CodeProject,144+ at: Option.Option<Rev>,145+ path: RepoPath146+): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>147+ Effect.gen(function* () {148+ const resolved = yield* resolveAt(project, at);149+150+ return yield* keptOnlyIfCanonical(resolved, fileAtCommit(resolved, path));151+ });modified:packages/project/src/code/history.ts+3 added-2 removed
33 unmodified lines34 });35 36 export type StoredPathLog = typeof StoredPathLog.Type;37 38-const sha256 = (text: string) =>38+/** A path's SHA-256 in hex, so a key stays under the store's limit and names no path. */39+export const hashOf = (text: string) =>40 Effect.map(41 Effect.promise(() =>42 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))43 ),30 unmodified lines74 readonly path: RepoPath;75 }76 ) =>77 Effect.map(77- sha256(at.path),78+ hashOf(at.path),79 (hash) =>80 `${at.repo}/${kept.kind}/v${kept.version}/${at.commit}/${at.scan}/${hash}`81 );82 58 unmodified linesmodified:packages/project/src/code/log.ts+32 added-16 removed
11 unmodified lines12 import type { UnknownRevision } from "@repo/protocol/refusal";13 import { Array, DateTime, Effect, Equal, Option } from "effect";14 15 import type { CodeProject } from "../code.ts";16-import { asOneView, CodeCache } from "./cache.ts";16+import { asOneView } from "./cache.ts";17 import { versionAt, walkableAt } from "./file-walk.ts";18 import {19 INCREMENT_REACH,20 keyOf,2 unmodified lines23 recall,24 throughHistory,25 } from "./history.ts";26 import type { StoredPathLog } from "./history.ts";27+import { logKept, logKey, throughStore } from "./objects.ts";28 import { commitAt, resolveAt } from "./revision.ts";29+import type { Resolved } from "./revision.ts";30 import { entryAt, READS_AT_ONCE } from "./tree.ts";31 32 export const LOG_LIMIT = 100;33 56 unmodified lines90 sha: CommitSha,91 from: number,92 count: number93 ): Effect.Effect<readonly Commit[], RepoNotFound, RepoHost> =>92- Effect.gen(function* () {93- const cache = yield* CodeCache;94+ throughStore(95+ logKept,96+ logKey(repo, sha, from, count),97+ RepoHost.use((host) =>98+ host.log(repo, Revision.Commit({ sha }), count, from)99+ ).pipe(Effect.asSome),100+ { heavy: true }101+ ).pipe(Effect.map(Option.getOrElse(() => [])));102 95- return yield* cache.through(96- `${repo}:log:${sha}:${from}:${count}`,97- RepoHost.use((host) =>98- host.log(repo, Revision.Commit({ sha }), count, from)99- ),100- { heavy: true }101- );102- });103-103 const idAt = (repo: RepoName, tree: string, path: RepoPath) =>104 Effect.map(105 entryAt(repo, tree, path),106 Option.map(({ mode, sha }: TreeEntry) => `${mode} ${sha}`)142 unmodified lines249 ],250 };251 });252 254-export const logPage = (253+const pageFrom = (254 project: CodeProject,255+ resolved: Resolved,256 input: {257- readonly at: Option.Option<Rev>;257 readonly path: Option.Option<RepoPath>;258 readonly from: number;259 readonly limit: number;260 }262-): Effect.Effect<LogPage, UnknownRevision, RepoHost> =>261+): Effect.Effect<LogPage, never, RepoHost> =>262 Effect.gen(function* () {264- const resolved = yield* resolveAt(project, input.at);263 const { commit: sha, repo } = resolved;264 const from = Math.max(0, Math.floor(input.from));265 const limit = Math.min(LOG_LIMIT, Math.max(1, Math.floor(input.limit)));266 56 unmodified lines323 return pageWith(324 commits,325 scan.length > PATH_SCAN ? Option.some(from + PATH_SCAN) : Option.none()326 );327+ });328+329+export const logPage = (330+ project: CodeProject,331+ input: {332+ readonly at: Option.Option<Rev>;333+ readonly path: Option.Option<RepoPath>;334+ readonly from: number;335+ readonly limit: number;336+ }337+): Effect.Effect<LogPage, UnknownRevision, RepoHost> =>338+ Effect.gen(function* () {339+ const resolved = yield* resolveAt(project, input.at);340+341+ return yield* keptOnlyIfCanonical(342+ resolved,343+ pageFrom(project, resolved, input)344+ );345 }).pipe(inRepoSession);added:packages/project/src/code/objects.ts+199 added
1+/**2+ * Objects kept by their id across isolates: a commit, a tree's entries, a3+ * blob's contents, a log page from a commit and the blob a path names at a4+ * commit. What an id names never changes, so a kept object is read from the5+ * store before the host, with the isolate's cache in front. Keys follow6+ * history's: `<repo>/<kind>/v<version>/<id>`, and only a canonical repo is7+ * ever keyed (`keptOnlyIfCanonical`). A store that cannot answer is a miss,8+ * and a kept value that no longer decodes is read again and replaced.9+ */10+import { Commit, TreeEntry } from "@repo/artifacts/repo-host";11+import { BlobSha } from "@repo/protocol/ids";12+import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";13+import { Data, Effect, Option, Schema } from "effect";14+15+import { CodeStore } from "../code-store.ts";16+import { CodeCache } from "./cache.ts";17+import type { Keeping } from "./cache.ts";18+import { hashOf } from "./history.ts";19+20+/** Bump when what is kept changes. */21+export const OBJECT_VERSION = 1;22+23+export const StoredBlob = Schema.Struct({24+ binary: Schema.Boolean,25+ size: Schema.Int,26+ text: Schema.OptionFromOptionalKey(Schema.String),27+ truncated: Schema.Boolean,28+});29+30+export type StoredBlob = typeof StoredBlob.Type;31+32+/** The blob a path names at a commit: an id alone, whose contents are kept by it. */33+export const StoredFile = Schema.Struct({ blob: BlobSha });34+35+export type StoredFile = typeof StoredFile.Type;36+37+/** A kind of kept object, its codec built once: a read decodes and keeps thousands of them. */38+export interface KeptObject<A> {39+ readonly kind: string;40+ readonly version: number;41+ readonly decode: (text: string) => Option.Option<A>;42+ readonly encode: (value: A) => Effect.Effect<string, Schema.SchemaError>;43+}44+45+const keptObject = <A>(46+ kind: string,47+ schema: Schema.Codec<A, unknown>48+): KeptObject<A> => {49+ const json = Schema.fromJsonString(schema);50+51+ return {52+ decode: Schema.decodeUnknownOption(json),53+ encode: Schema.encodeEffect(json),54+ kind,55+ version: OBJECT_VERSION,56+ };57+};58+59+export const commitKept = keptObject("commit-object", Commit);60+61+export const treeKept = keptObject("tree", Schema.Array(TreeEntry));62+63+export const blobKept = keptObject("blob", StoredBlob);64+65+export const logKept = keptObject("log", Schema.Array(Commit));66+67+export const fileKept = keptObject("file", StoredFile);68+69+export const objectKey = <A>(kept: KeptObject<A>, repo: RepoName, id: string) =>70+ `${repo}/${kept.kind}/v${kept.version}/${id}`;71+72+/** A log page from a commit is immutable too: first parents never move. */73+export const logKey = (74+ repo: RepoName,75+ sha: CommitSha,76+ from: number,77+ count: number78+) => objectKey(logKept, repo, `${sha}/${from}/${count}`);79+80+/** The path is hashed, as history hashes it, to keep the key under the store's limit. */81+export const fileKey = (repo: RepoName, commit: CommitSha, path: RepoPath) =>82+ Effect.map(hashOf(path), (hash) =>83+ objectKey(fileKept, repo, `${commit}/${hash}`)84+ );85+86+export interface KeepingObject<A> {87+ readonly heavy?: boolean;88+ /** Whether a value is worth keeping, in the isolate and the store alike. */89+ readonly keep?: (value: A) => boolean;90+ /** Whether a kept value is the one its key names; one that is not is read again. */91+ readonly fits?: (value: A) => boolean;92+}93+94+class ObjectMissing extends Data.TaggedError("ObjectMissing") {}95+96+const always = () => true;97+98+interface Told<A> {99+ heavy?: boolean;100+ keep?: (value: A) => boolean;101+}102+103+/** What the isolate's cache is told: only the fields given, since an absent one means the default. */104+const cacheKeeping = <A>(keeping: KeepingObject<A>): Keeping<A> => {105+ const told: Told<A> = {};106+107+ if (keeping.heavy !== undefined) {108+ told.heavy = keeping.heavy;109+ }110+111+ if (keeping.keep !== undefined) {112+ told.keep = keeping.keep;113+ }114+115+ return told;116+};117+118+const putKept = <A>(kept: KeptObject<A>, key: string, value: A) =>119+ Effect.gen(function* () {120+ const store = yield* CodeStore;121+122+ yield* kept.encode(value).pipe(123+ Effect.flatMap((text) => store.put(key, text)),124+ Effect.catch((error) => Effect.logWarning(`${key} was not kept`, error))125+ );126+ });127+128+/**129+ * An object read by another call, kept under its own key: in the store, and130+ * in the isolate's cache past any view's dedupe, so a view that missed the131+ * key first still finds it.132+ */133+export const keepObject = <A>(134+ kept: KeptObject<A>,135+ key: string,136+ value: A,137+ keeping: KeepingObject<A> = {}138+): Effect.Effect<void> =>139+ Effect.gen(function* () {140+ const cache = yield* CodeCache;141+ const keep = keeping.keep ?? always;142+143+ if (!keep(value)) {144+ return;145+ }146+147+ yield* putKept(kept, key, value);148+ yield* cache.through(key, Effect.succeed(value), {149+ ...cacheKeeping(keeping),150+ keep,151+ });152+ });153+154+/**155+ * An object by its key: the isolate's cache, then the store, then `compute`.156+ * A miss (`None`) is kept nowhere, since the object may yet be pushed.157+ */158+export const throughStore = <A, E, R>(159+ kept: KeptObject<A>,160+ key: string,161+ compute: Effect.Effect<Option.Option<A>, E, R>,162+ keeping: KeepingObject<A> = {}163+): Effect.Effect<Option.Option<A>, E, R> =>164+ Effect.gen(function* () {165+ const cache = yield* CodeCache;166+ const store = yield* CodeStore;167+ const keep = keeping.keep ?? always;168+ const fits = keeping.fits ?? always;169+170+ const read: Effect.Effect<A, E | ObjectMissing, R> = Effect.gen(171+ function* () {172+ const found = Option.filter(173+ Option.flatMap(yield* store.get(key), kept.decode),174+ fits175+ );176+177+ if (Option.isSome(found)) {178+ return found.value;179+ }180+181+ const computed = yield* compute;182+183+ if (Option.isNone(computed)) {184+ return yield* new ObjectMissing();185+ }186+187+ if (keep(computed.value)) {188+ yield* putKept(kept, key, computed.value);189+ }190+191+ return computed.value;192+ }193+ );194+195+ return yield* cache.through(key, read, cacheKeeping(keeping)).pipe(196+ Effect.asSome,197+ Effect.catchTag("ObjectMissing", () => Effect.succeedNone)198+ );199+ });modified:packages/project/src/code/paths.ts+13 added-5 removed
10 unmodified lines11 import { Array, Effect, Order } from "effect";12 13 import type { CodeProject } from "../code.ts";14 import { CodeCache } from "./cache.ts";15+import { keptOnlyIfCanonical } from "./history.ts";16 import { commitAt, resolveAt } from "./revision.ts";17+import type { Resolved } from "./revision.ts";18 import { entriesOf } from "./tree.ts";19 20 export const PATHS_CAP = 50_000;21 61 unmodified lines83 truncated: all.length > cap || depth.length > 0,84 };85 });86 85-export const pathList = (86- project: CodeProject,87- at: Option.Option<Rev>88-): Effect.Effect<PathList, UnknownRevision, RepoHost> =>87+const pathsAt = ({ commit, repo }: Resolved) =>88 Effect.gen(function* () {90- const { commit, repo } = yield* resolveAt(project, at);89 const cache = yield* CodeCache;90 91 const { tree } = yield* commitAt(repo, commit).pipe(92 Effect.flatMap(Effect.fromOption),8 unmodified lines101 .pipe(Effect.orDie);102 103 return { at: commit, paths: files.map(({ path }) => path), truncated };104 });105+106+export const pathList = (107+ project: CodeProject,108+ at: Option.Option<Rev>109+): Effect.Effect<PathList, UnknownRevision, RepoHost> =>110+ Effect.gen(function* () {111+ const resolved = yield* resolveAt(project, at);112+113+ return yield* keptOnlyIfCanonical(resolved, pathsAt(resolved));114+ });modified:packages/project/src/code/raw.ts+23 added-10 removed
1 import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2+import type { RepoNotFound } from "@repo/artifacts/repo-host";3 import { Rev } from "@repo/protocol/domain/code";4 import { BlobSha, RepoPath } from "@repo/protocol/ids";5 import type { ProjectName } from "@repo/protocol/ids";6 import { Effect, Option, Schema } from "effect";1 unmodified line8 import { codeProjectOf } from "../code.ts";9 import type { CodeProject } from "../code.ts";10 import { Projects } from "../projects.ts";11 import { isBinary, unlessTooLarge } from "./file.ts";12+import { keptOnlyIfCanonical } from "./history.ts";13 import { commitAt, isFullSha, resolveAt } from "./revision.ts";14+import type { Resolved } from "./revision.ts";15 import { entryAt, segmentsOf } from "./tree.ts";16 17 /** Both origins hold a session cookie, so no raw file may run as script: every answer, a refusal too, carries `nosniff` and this CSP. */18 const SANDBOX =50 unmodified lines69 const notFound = () => new Response(null, { headers: SAFE, status: 404 });70 71 const tooLarge = () => new Response(null, { headers: SAFE, status: 413 });72 70-export const rawOf = (71- project: CodeProject,73+const rawAt = (74+ { commit, repo }: Resolved,75 rev: Rev,76 path: RepoPath74-): Effect.Effect<Response, never, RepoHost> =>77+): Effect.Effect<Response, RepoNotFound, RepoHost> =>78 Effect.gen(function* () {76- const { commit, repo } = yield* resolveAt(project, Option.some(rev));77-79 const { tree } = yield* commitAt(repo, commit).pipe(80 Effect.flatMap(Effect.fromOption)81 );82 23 unmodified lines106 }),107 });108 }).pipe(109 (read) => unlessTooLarge(read, tooLarge),109- Effect.catchTags({110- NoSuchElementError: () => Effect.succeed(notFound()),111- RepoNotFound: () => Effect.succeed(notFound()),112- UnknownRevision: () => Effect.succeed(notFound()),113- })110+ Effect.catchTag("NoSuchElementError", () => Effect.succeed(notFound()))111 );112 113 const decodeRev = Schema.decodeUnknownOption(Rev);114 30 unmodified lines145 146 return segments[2] === "raw" ? segments.slice(3).join("/") : "";147 };148 149+export const rawOf = (150+ project: CodeProject,151+ rev: Rev,152+ path: RepoPath153+): Effect.Effect<Response, never, RepoHost> =>154+ Effect.gen(function* () {155+ const resolved = yield* resolveAt(project, Option.some(rev));156+157+ return yield* keptOnlyIfCanonical(resolved, rawAt(resolved, rev, path));158+ }).pipe(159+ Effect.catchTags({160+ RepoNotFound: () => Effect.succeed(notFound()),161+ UnknownRevision: () => Effect.succeed(notFound()),162+ })163+ );164+165 export const rawFor = (166 project: ProjectName,167 url: string168 ): Effect.Effect<Response, never, RepoHost | Projects> =>8 unmodified linesmodified:packages/project/src/code/revision.ts+10 added-17 removed
14 unmodified lines15 import { UnknownRevision } from "@repo/protocol/refusal";16 import { Array, Effect, Option } from "effect";17 18 import type { CodeProject } from "../code.ts";19-import { CodeCache } from "./cache.ts";19+import { keptOnlyIfCanonical } from "./history.ts";20+import { commitKept, objectKey, throughStore } from "./objects.ts";21 22 const FULL_SHA = /^[0-9a-f]{40}$/u;23 24 export const isFullSha = (rev: string) => FULL_SHA.test(rev);16 unmodified lines41 export const commitAt = (42 repo: RepoName,43 sha: CommitSha44 ): Effect.Effect<Option.Option<Commit>, RepoNotFound, RepoHost> =>44- Effect.gen(function* () {45- const cache = yield* CodeCache;45+ throughStore(46+ commitKept,47+ objectKey(commitKept, repo, sha),48+ RepoHost.use((host) => host.readCommit(repo, sha)),49+ { fits: (commit) => commit.sha === sha }50+ );51 47- return yield* cache48- .through(49- `${repo}:commit:${sha}`,50- RepoHost.use((host) => host.readCommit(repo, sha)).pipe(51- Effect.flatMap(Effect.fromOption)52- )53- )54- .pipe(55- Effect.asSome,56- Effect.catchTag("NoSuchElementError", () => Effect.succeedNone)57- );58- });59-52 /**53 * Where a revision resolved: the commit, and the repo that holds it. Only the54 * canonical repo's reads are kept in the code store; a fork's stay out of it.55 */39 unmodified lines95 )96 ),97 Effect.catchTag("RepoNotFound", () => Effect.succeedNone)98 ),99+ // A fork's commit is read before the address resolves, so it is kept in no store here.100 Commit: ({ sha }) =>108- commitAt(repo, sha).pipe(101+ keptOnlyIfCanonical({ canonical: false }, commitAt(repo, sha)).pipe(102 Effect.map(Option.map((found) => found.sha)),103 Effect.catchTag("RepoNotFound", () => Effect.succeedNone)104 ),105 });108 unmodified linesmodified:packages/project/src/code/tree.ts+37 added-37 removed
6 unmodified lines7 import type { UnknownRevision } from "@repo/protocol/refusal";8 import { Array, Effect, Match, Option, Order } from "effect";9 10 import type { CodeProject } from "../code.ts";11-import { CodeCache } from "./cache.ts";11+import { contentsOf } from "./blob.ts";12+import { keptOnlyIfCanonical } from "./history.ts";13+import { objectKey, throughStore, treeKept } from "./objects.ts";14 import { commitAt, resolveAt } from "./revision.ts";15+import type { Resolved } from "./revision.ts";16 17 /** Live store reads take 0.1-0.5 s and chain per path segment; 48 at once keeps a walk fast and under the store's 2,000 requests per 10 s per repo. */18 export const READS_AT_ONCE = 48;19 20 export const entriesOf = (21 repo: RepoName,22 id: string23 ): Effect.Effect<readonly TreeEntry[], RepoNotFound, RepoHost> =>21- Effect.gen(function* () {22- const cache = yield* CodeCache;24+ throughStore(25+ treeKept,26+ objectKey(treeKept, repo, id),27+ RepoHost.use((host) => host.readTree(repo, ObjectId.make(id)))28+ ).pipe(29+ Effect.flatMap(30+ Option.match({31+ onNone: () => Effect.die(`${repo} has no tree ${id}`),32+ onSome: Effect.succeed,33+ })34+ )35+ );36 24- return yield* cache.through(25- `${repo}:tree:${id}`,26- RepoHost.use((host) => host.readTree(repo, ObjectId.make(id))).pipe(27- Effect.flatMap(28- Option.match({29- onNone: () => Effect.die(`${repo} has no tree ${id}`),30- onSome: Effect.succeed,31- })32- )33- )34- );35- });36-37 export const segmentsOf = (path: string): Option.Option<readonly string[]> => {38 const segments = path.split("/");39 40 return segments.every(80 unmodified lines121 };122 123 const LINK_TARGET_MAX = 4096;124 125+/** A link's blob is kept as any blob is, by its id. */126 const linkTextOf = (repo: RepoName, link: string) =>126- Effect.gen(function* () {127- const cache = yield* CodeCache;127+ Effect.map(128+ contentsOf(repo, BlobSha.make(link)),129+ Option.flatMap(({ size, text }) =>130+ size > LINK_TARGET_MAX ? Option.none() : text131+ )132+ );133 129- return yield* cache.through(130- `${repo}:link:${link}`,131- RepoHost.use((host) => host.readBlob(repo, ObjectId.make(link))).pipe(132- Effect.map(133- Option.flatMap((bytes) =>134- bytes.length > LINK_TARGET_MAX135- ? Option.none()136- : Option.some(new TextDecoder().decode(bytes))137- )138- )139- )140- );141- });142-134 /** One link followed, never a chain; a link's entry is a blob too, so its kind is asked, not its type. */135 const linkedFile = (136 repo: RepoName,137 root: Effect.Effect<string, never, RepoHost>,83 unmodified lines221 RepoNotFound: Effect.die,222 })223 );224 234-export const listing = (235- project: CodeProject,236- at: Option.Option<Rev>,225+const folderListing = (226+ { commit, repo }: Resolved,227 path: Option.Option<RepoPath>238-): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>228+): Effect.Effect<TreeListing, UnknownPath, RepoHost> =>229 Effect.gen(function* () {240- const { commit, repo } = yield* resolveAt(project, at);230 const tree = yield* folderAt(repo, commit, path);231 232 const prefix = Option.match(path, {233 onNone: () => "",38 unmodified lines272 onSome: (found) => ({ readme: found }),273 }),274 };275 });276+277+export const listing = (278+ project: CodeProject,279+ at: Option.Option<Rev>,280+ path: Option.Option<RepoPath>281+): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>282+ Effect.gen(function* () {283+ const resolved = yield* resolveAt(project, at);284+285+ return yield* keptOnlyIfCanonical(resolved, folderListing(resolved, path));286+ });modified:packages/project/src/code/why.ts+8 added-7 removed
525 unmodified lines526 const resolved = yield* resolveAt(project, at);527 const { commit, repo } = resolved;528 const key = yield* keyOf(whyKept, { commit, path, repo, scan });529 530- const kept = yield* keptOnlyIfCanonical(530+ return yield* keptOnlyIfCanonical(531 resolved,532+ Effect.flatMap(532- throughHistory(533- whyKept,534- key,535- asOneView(computed(repo, commit, path, scan))533+ throughHistory(534+ whyKept,535+ key,536+ asOneView(computed(repo, commit, path, scan))537+ ),538+ (kept) => viewOf(project, repo, commit, path, kept, scan)539 )540 );538-539- return yield* viewOf(project, repo, commit, path, kept, scan);541 }).pipe(inRepoSession, Effect.catchTag("RepoNotFound", Effect.die));modified:packages/project/test/code-history.test.ts+2 added-2 removed
246 unmodified lines247 const again = yield* onIsolate(whyOf(code, Option.none(), format));248 const { blobs, commits, files, logs, trees } = yield* Ref.get(seen);249 250 expect(again).toStrictEqual(first);251- // The commits it names come from one page of the log, not one read each.251+ // The commits it names come from the kept page of the log, not one read each.252 expect({ blobs, commits, files, logs, trees }).toStrictEqual({253 blobs: 0,254 commits: 0,255 files: 0,256- logs: 1,256+ logs: 0,257 trees: 0,258 });259 expect(yield* Ref.get(asked)).toBe(1);260 })654 unmodified linesmodified:packages/project/test/code-store.test.ts+65 added
1 import { describe, expect, it } from "@effect/vitest";2+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3+import { RepoPath } from "@repo/protocol/ids";4 import { Effect, Exit, Layer, Logger, Option } from "effect";5 6 import { CodeStore } from "../src/code-store.ts";7 import { CodeStoreR2 } from "../src/code-store/binding.ts";8 import type { BucketLike } from "../src/code-store/binding.ts";9 import { CodeStoreCounts, CodeStoreMemory } from "../src/code-store/memory.ts";10+import { fileOf, treeOf } from "../src/code.ts";11+import { datekit } from "./code-fixtures.ts";12 13 const key = "datekit/why/v1/1111111111111111111111111111111111111111/main/ab";14 15 /** A key one byte past R2's limit of 1,024. */131 unmodified lines147 ]).toStrictEqual([true, true, false]);148 }).pipe(Effect.provide(layer))149 );150 });151+152+const folderAndReadme = Effect.gen(function* () {153+ const { code } = yield* datekit;154+155+ return yield* Effect.all([156+ treeOf(code, Option.none(), Option.none()),157+ fileOf(code, Option.none(), RepoPath.make("README.md")),158+ ]);159+});160+161+describe("the code reads over the code store", () => {162+ it.effect(163+ "answer a folder and a file over R2 that is down as over a store that keeps nothing, and log it",164+ () =>165+ Effect.gen(function* () {166+ const plain = yield* folderAndReadme.pipe(167+ Effect.provide(RepoHostMemory)168+ );169+170+ const { exit, messages } = yield* logged(171+ folderAndReadme.pipe(172+ Effect.provide(173+ Layer.merge(174+ RepoHostMemory,175+ CodeStoreR2(bucketOf({ get: true, put: true }))176+ )177+ )178+ )179+ );180+181+ expect(exit).toStrictEqual(Exit.succeed(plain));182+ expect(messages.length).toBeGreaterThan(0);183+ })184+ );185+186+ it.effect("keep a folder's and a file's objects over R2 that is up", () =>187+ Effect.gen(function* () {188+ const objects = new Map<string, string>();189+ const bucket = bucketOf({});190+191+ const kept = {192+ ...bucket,193+ put: (name: string, value: string) => {194+ objects.set(name, value);195+196+ return bucket.put(name, value);197+ },198+ };199+200+ yield* folderAndReadme.pipe(201+ Effect.provide(Layer.merge(RepoHostMemory, CodeStoreR2(kept)))202+ );203+204+ expect(205+ [...objects.keys()]206+ .map((name) => name.split("/").at(1) ?? "")207+ .toSorted((one, other) => one.localeCompare(other))208+ ).toStrictEqual(["blob", "commit-object", "file", "tree"]);209+ })210+ );211+});modified:packages/project/test/code.test.ts+195 added-1 removed
1 unmodified line2 import { RepoHost } from "@repo/artifacts/repo-host";3 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4 import { Brand } from "@repo/brand";5 import { CommitDiff } from "@repo/protocol/domain/code";6-import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";6+import { CommitSha, LandedSha, RepoName, RepoPath } from "@repo/protocol/ids";7 import {8 UnknownCommit,9 UnknownPath,10 UnknownRevision,22 unmodified lines33 whyOf,34 } from "../src/code.ts";35 import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";36 import { commitKey, DIFF_TEXT } from "../src/code/commit.ts";37+import { commitKept, objectKey } from "../src/code/objects.ts";38 import { filesUnder } from "../src/code/paths.ts";39 import { compareTags } from "../src/code/refs.ts";40 import { READS_AT_ONCE } from "../src/code/tree.ts";41 import {1019 unmodified lines1061 expect(yield* Fiber.join(next)).toStrictEqual(Option.some("read"));1062 }).pipe(Effect.provide(CodeCacheLive(10, 10)))1063 );1064 });1065+1066+const 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));1070+1071+const hostCountedBy = (reads: Ref.Ref<number>) =>1072+ Layer.effect(1073+ RepoHost,1074+ Effect.gen(function* () {1075+ const host = yield* RepoHost;1076+ const counted = countedIn(reads);1077+1078+ 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));1089+1090+const onIsolate = <A, E, R>(effect: Effect.Effect<A, E, R>) =>1091+ Effect.provide(effect, CodeCacheLive(100));1092+1093+const byText = (one: string, other: string) => one.localeCompare(other);1094+1095+const readme = RepoPath.make("README.md");1096+1097+describe("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);1103+1104+ yield* Effect.gen(function* () {1105+ const { c4, code } = yield* datekit;1106+1107+ 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+ ]);1114+1115+ const first = yield* onIsolate(views);1116+ const counted = yield* Ref.get(reads);1117+1118+ expect(counted).toBeGreaterThan(0);1119+1120+ const again = yield* onIsolate(views);1121+1122+ 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+ );1129+1130+ 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);1137+1138+ const moving = {1139+ ...code,1140+ head: Ref.update(asked, (count) => count + 1).pipe(1141+ Effect.andThen(Ref.get(head))1142+ ),1143+ };1144+1145+ const before = yield* treeOf(moving, main, Option.none());1146+1147+ yield* Ref.set(head, Option.some(LandedSha.make(c4)));1148+1149+ const after = yield* treeOf(moving, main, Option.none());1150+1151+ 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+ );1162+1163+ 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);1168+1169+ yield* Effect.gen(function* () {1170+ const { c3, c4, code } = yield* datekit;1171+ const store = yield* CodeStore;1172+ const key = objectKey(commitKept, code.repo, c4);1173+1174+ const fresh = yield* onIsolate(treeOf(code, main, Option.none()));1175+1176+ yield* onIsolate(treeOf(code, revision(c3), Option.none()));1177+1178+ const kept = yield* store.get(key);1179+1180+ const other = yield* store.get(objectKey(commitKept, code.repo, c3));1181+1182+ expect([Option.isSome(kept), Option.isSome(other)]).toStrictEqual([1183+ true,1184+ true,1185+ ]);1186+1187+ 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);1193+1194+ 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+ );1205+1206+ 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());1211+1212+ 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+ });1220+1221+ const repo = yield* Effect.gen(function* () {1222+ const { c4, code } = yield* datekit;1223+1224+ yield* treeOf(code, main, Option.none());1225+ yield* fileOf(code, main, readme);1226+ yield* logOf(code, page);1227+ yield* commitOf(code, c4);1228+1229+ return code.repo;1230+ }).pipe(Effect.provide(Layer.merge(RepoHostMemory, recording)));1231+1232+ const all = [...(yield* Ref.get(kept))];1233+1234+ const ownKey = new RegExp(1235+ `^${repo}/(blob|commit|commit-object|file|log|tree)/v[1-9]\\d*/`,1236+ "u"1237+ );1238+1239+ 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+});