Keep commits, trees, blobs, log pages and the blob a path names at a commit in the code store by their ids, under the canonical repo as history keys its values, with the isolate's cache in front (PARTIAL: lint fixes pending, see below)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
A project page on a cold isolate read each object from Artifacts again (0.1-0.5 s a call, chained commit → tree → blob), while the R2 store held only why and history values. Each kept value is decoded with Schema when read, one that no longer decodes or names another id is read again and replaced, a store that is down is a miss, a fork's reads keep nothing, and main still resolves on every read. The web's dev world wires the same cache and memory store the platform's ports do. Counted on the memory host, an overview's reads (root tree, README, log of one, refs): 5 host calls on a first isolate (commit, tree, file, log, tags), 1 on a second (tags, which move), and a folder under it 1 (its own tree); before, a second isolate repeated all 5. On the dev world the host is in-process, so a project page took 61-98 ms before and the gain shows only in the counts.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Partial: the code tests of packages/project passed before the last lint pass; `bun run check` still reports import order in packages/project/src/code/file.ts (the re-exports from blob.ts sit after an import), a widened binding `told` in objects.ts (cacheKeeping), rawOf used before defined in raw.ts (move the exported wrapper below its last use), countedIn before defined in test/code.test.ts (move it above hostCountedBy), and a toSorted compare over `string | undefined` at test/code.test.ts:1241. Not started: the README-absence keeping (scratchpad patch3) and a request-scoped memo, which the web's project.test.tsx shows is not needed on Overview (each read is already made once).
Diff stats
15 files+761 added−207 removed
- tests:+253 added−3 removed
- other:+508 added−204 removed
Provenance
- Commit
dec332c- Tree
05ba6fb- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
07f14ad
15 files changed+761 added−207 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
4 unmodified lines5678910111213148 unmodified lines23242526272829303132333435363738394029 unmodified lines4 unmodified linesimport { cannedDrafter } from "@repo/drafting/draft-runs/canned";import { withDraftRunsInline } from "@repo/drafting/draft-runs/inline";import { AlarmsMemory } from "@repo/project/alarms/memory";import { AnswerRunsInline } from "@repo/project/answer-runs/inline";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 { FinishersFromChecks } from "@repo/project/project";import type { Projects } from "@repo/project/projects";8 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, AnswerRunsInline, cannedDrafter, CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy), CodeStoreMemory, DevProjection, RulesEvaluatorJson.pipe(Layer.provide(FinishersFromChecks))).pipe( Layer.provideMerge(Layer.mergeAll(DevChecker, DevLander)),29 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+84 added-109 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 { contentsOf, contentsOfBytes, keepContents, unlessTooLarge } from "./blob.ts";11+import type { Contents } from "./blob.ts";12 import { versionAt } from "./file-walk.ts";13-import { commitAt, resolveAt } from "./revision.ts";14-import { entryAt } from "./tree.ts";13+import { keptOnlyIfCanonical } from "./history.ts";14+import {15+ blobKept,16+ fileKept,17+ fileKey,18+ keepObject,19+ objectKey,20+ throughStore,21+} from "./objects.ts";22 16-export const TEXT_CAP = 1024 * 1024;23+export {24+ contentsOf,25+ contentsOfBytes,26+ isBinary,27+ TEXT_CAP,28+ unlessTooLarge,29+} from "./blob.ts";30 18-// git's own test: a NUL among the first bytes means the blob is not text.19-const SNIFF = 8192;31+export type { Contents } from "./blob.ts";32 21-const KEPT_TEXT = 256 * 1024;33+import { commitAt, resolveAt } from "./revision.ts";34+import type { Resolved } from "./revision.ts";35+import { entryAt } from "./tree.ts";36 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-37 const viewOf = (38 commit: CommitSha,39 path: RepoPath,40 sha: BlobSha,10 unmodified lines51 onSome: (text) => ({ text }),52 }),53 });54 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) =>55+interface Whole {56+ readonly blob: BlobSha;57+ readonly contents: Contents;58+}59+60+/**61+ * The file in one host call, kept as the blob its path names at the commit62+ * and that blob's contents, each by its id: a kept file is read from the63+ * store alone. ASSUMPTION: Artifacts' `readFile` gives a symlink's own blob,64+ * as the tree does, rather than following it.65+ */66+const wholeAt = (67+ repo: RepoName,68+ commit: CommitSha,69+ path: RepoPath70+): Effect.Effect<Option.Option<Whole>, RepoNotFound, RepoHost> =>71 Effect.gen(function* () {118- const cache = yield* CodeCache;72+ const key = yield* fileKey(repo, commit, path);73 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- }),74+ const named = yield* throughStore(fileKept, key, Effect.succeedNone);75+76+ if (Option.isSome(named)) {77+ const kept = yield* contentsOf(repo, named.value.blob);78+79+ if (Option.isSome(kept)) {80+ return Option.some({ blob: named.value.blob, contents: kept.value });81 }82+ }83+84+ const read = yield* unlessTooLarge(85+ versionAt(repo, commit, path),86+ Option.none87 );88+89+ if (Option.isNone(read)) {90+ return Option.none();91+ }92+93+ const { blob, bytes } = read.value;94+ const contents = contentsOfBytes(bytes);95+96+ yield* keepObject(fileKept, key, { blob });97+ yield* keepObject(blobKept, objectKey(blobKept, repo, blob), contents, {98+ heavy: true,99+ keep: keepContents,100+ });101+102+ return Option.some({ blob, contents });103 });104 134-export const fileView = (135- project: CodeProject,136- at: Option.Option<Rev>,105+const fileAtCommit = (106+ { commit, repo }: Resolved,107 path: RepoPath138-): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>108+): Effect.Effect<FileView, UnknownPath, RepoHost> =>109 Effect.gen(function* () {140- const { commit, repo } = yield* resolveAt(project, at);141-110 const whole = yield* wholeAt(repo, commit, path).pipe(Effect.orDie);111 112 if (Option.isSome(whole)) {145- return viewOf(146- commit,147- path,148- whole.value.blob,149- contentsOfBytes(whole.value.bytes)150- );113+ return viewOf(commit, path, whole.value.blob, whole.value.contents);114 }115 116 const { tree } = yield* commitAt(repo, commit).pipe(117 Effect.flatMap(Effect.fromOption),15 unmodified lines133 );134 135 return viewOf(commit, path, sha, contents);136 });137+138+export const fileView = (139+ project: CodeProject,140+ at: Option.Option<Rev>,141+ path: RepoPath142+): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>143+ Effect.gen(function* () {144+ const resolved = yield* resolveAt(project, at);145+146+ return yield* keptOnlyIfCanonical(resolved, fileAtCommit(resolved, path));147+ });148+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+33 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);346+added:packages/project/src/code/objects.ts+200 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>(70+ kept: KeptObject<A>,71+ repo: RepoName,72+ id: string73+) =>74+ `${repo}/${kept.kind}/v${kept.version}/${id}`;75+76+/** A log page from a commit is immutable too: first parents never move. */77+export const logKey = (78+ repo: RepoName,79+ sha: CommitSha,80+ from: number,81+ count: number82+) => objectKey(logKept, repo, `${sha}/${from}/${count}`);83+84+/** The path is hashed, as history hashes it, to keep the key under the store's limit. */85+export const fileKey = (repo: RepoName, commit: CommitSha, path: RepoPath) =>86+ Effect.map(hashOf(path), (hash) =>87+ objectKey(fileKept, repo, `${commit}/${hash}`)88+ );89+90+export interface KeepingObject<A> {91+ readonly heavy?: boolean;92+ /** Whether a value is worth keeping, in the isolate and the store alike. */93+ readonly keep?: (value: A) => boolean;94+ /** Whether a kept value is the one its key names; one that is not is read again. */95+ readonly fits?: (value: A) => boolean;96+}97+98+class ObjectMissing extends Data.TaggedError("ObjectMissing") {}99+100+const always = () => true;101+102+/** What the isolate's cache is told: only the fields given, since an absent one means the default. */103+const cacheKeeping = <A>(keeping: KeepingObject<A>): Keeping<A> => {104+ const told: { heavy?: boolean; keep?: (value: A) => boolean } = {};105+106+ if (keeping.heavy !== undefined) {107+ told.heavy = keeping.heavy;108+ }109+110+ if (keeping.keep !== undefined) {111+ told.keep = keeping.keep;112+ }113+114+ return told;115+};116+117+const putKept = <A>(kept: KeptObject<A>, key: string, value: A) =>118+ Effect.gen(function* () {119+ const store = yield* CodeStore;120+121+ yield* kept.encode(value).pipe(122+ Effect.flatMap((text) => store.put(key, text)),123+ Effect.catch((error) => Effect.logWarning(`${key} was not kept`, error))124+ );125+ });126+127+/**128+ * An object read by another call, kept under its own key: in the store, and129+ * in the isolate's cache past any view's dedupe, so a view that missed the130+ * key first still finds it.131+ */132+export const keepObject = <A>(133+ kept: KeptObject<A>,134+ key: string,135+ value: A,136+ keeping: KeepingObject<A> = {}137+): Effect.Effect<void> =>138+ Effect.gen(function* () {139+ const cache = yield* CodeCache;140+ const keep = keeping.keep ?? always;141+142+ if (!keep(value)) {143+ return;144+ }145+146+ yield* putKept(kept, key, value);147+ yield* cache.through(key, Effect.succeed(value), {148+ ...cacheKeeping(keeping),149+ keep,150+ });151+ });152+153+/**154+ * An object by its key: the isolate's cache, then the store, then `compute`.155+ * A miss (`None`) is kept nowhere, since the object may yet be pushed.156+ */157+export const throughStore = <A, E, R>(158+ kept: KeptObject<A>,159+ key: string,160+ compute: Effect.Effect<Option.Option<A>, E, R>,161+ keeping: KeepingObject<A> = {}162+): Effect.Effect<Option.Option<A>, E, R> =>163+ Effect.gen(function* () {164+ const cache = yield* CodeCache;165+ const store = yield* CodeStore;166+ const keep = keeping.keep ?? always;167+ const fits = keeping.fits ?? always;168+169+ const read: Effect.Effect<A, E | ObjectMissing, R> = Effect.gen(170+ function* () {171+ const found = Option.filter(172+ Option.flatMap(yield* store.get(key), kept.decode),173+ fits174+ );175+176+ if (Option.isSome(found)) {177+ return found.value;178+ }179+180+ const computed = yield* compute;181+182+ if (Option.isNone(computed)) {183+ return yield* new ObjectMissing();184+ }185+186+ if (keep(computed.value)) {187+ yield* putKept(kept, key, computed.value);188+ }189+190+ return computed.value;191+ }192+ );193+194+ return yield* cache195+ .through(key, read, cacheKeeping(keeping))196+ .pipe(197+ Effect.asSome,198+ Effect.catchTag("ObjectMissing", () => Effect.succeedNone)199+ );200+ });modified:packages/project/src/code/paths.ts+14 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+ });115+modified:packages/project/src/code/raw.ts+24 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 42 unmodified lines157 Effect.flatMap((api) => rawOf(codeProjectOf(api, project), rev, path)),158 Effect.catchTag("UnknownProject", () => Effect.succeed(notFound()))159 ),160 });161+162+export const rawOf = (163+ project: CodeProject,164+ rev: Rev,165+ path: RepoPath166+): Effect.Effect<Response, never, RepoHost> =>167+ Effect.gen(function* () {168+ const resolved = yield* resolveAt(project, Option.some(rev));169+170+ return yield* keptOnlyIfCanonical(resolved, rawAt(resolved, rev, path));171+ }).pipe(172+ Effect.catchTags({173+ RepoNotFound: () => Effect.succeed(notFound()),174+ UnknownRevision: () => Effect.succeed(notFound()),175+ })176+ );177+modified: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+38 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+ });287+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("/")[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+186 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 hostCountedBy = (reads: Ref.Ref<number>) =>1067+ Layer.effect(1068+ RepoHost,1069+ Effect.gen(function* () {1070+ const host = yield* RepoHost;1071+ const counted = countedIn(reads);1072+1073+ return RepoHost.of({1074+ ...host,1075+ log: (name, at, limit, offset) =>1076+ counted(host.log(name, at, limit, offset)),1077+ readBlob: (name, blob) => counted(host.readBlob(name, blob)),1078+ readCommit: (name, sha) => counted(host.readCommit(name, sha)),1079+ readFile: (name, at, file) => counted(host.readFile(name, at, file)),1080+ readTree: (name, tree) => counted(host.readTree(name, tree)),1081+ });1082+ })1083+ ).pipe(Layer.provide(RepoHostMemory));1084+1085+const countedIn =1086+ (reads: Ref.Ref<number>) =>1087+ <A, E>(read: Effect.Effect<A, E>) =>1088+ Ref.update(reads, (count) => count + 1).pipe(Effect.andThen(read));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("/")[1]))].toSorted(byText)1242+ ).toStrictEqual(["blob", "commit", "commit-object", "file", "log", "tree"]);1243+ expect(1244+ all.filter(([, value]) => value.includes("landedAt"))1245+ ).toStrictEqual([]);1246+ })1247+ );1248+});