Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent 07f14ad · Browse files · 15 files+761 added−207 removed
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

15 files+761 added−207 removed

modified:apps/web/src/dev/server.ts+5 added-1 removed
modified:apps/web/src/dev/world.ts+8 added
added: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. */2import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";3import type { RepoNotFound } from "@repo/artifacts/repo-host";4import type { BlobSha, RepoName } from "@repo/protocol/ids";5import { Effect, Option, Schema } from "effect";67import { blobKept, objectKey, throughStore } from "./objects.ts";89export const TEXT_CAP = 1024 * 1024;1011// git's own test: a NUL among the first bytes means the blob is not text.12const SNIFF = 8192;1314const KEPT_TEXT = 256 * 1024;1516export const isBinary = (bytes: Uint8Array) =>17 bytes.subarray(0, SNIFF).includes(0);1819export interface Contents {20 readonly size: number;21 readonly binary: boolean;22 readonly truncated: boolean;23 readonly text: Option.Option<string>;24}2526const MemoryLimit = Schema.Struct({ code: Schema.Literal("MEMORY_LIMIT") });2728const isMemoryLimit = Schema.is(MemoryLimit);2930/** Artifacts' binding throws a too-large blob as a defect, which here is an answer. */31export 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 );3839export const contentsOfBytes = (bytes: Uint8Array): Contents => {40 const binary = isBinary(bytes);41 const truncated = !binary && bytes.length > TEXT_CAP;4243 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};5354/** Kept by its id, in the isolate and the store, while its text is under the cap. */55export const keepContents = ({ text }: Contents) =>56 Option.match(text, {57 onNone: () => true,58 onSome: (read) => read.length <= KEPT_TEXT,59 });6061export 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
1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2import type { RepoNotFound } from "@repo/artifacts/repo-host";1import type { RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";2import type { FileView, Rev } from "@repo/protocol/domain/code";3import { BlobSha } from "@repo/protocol/ids";4import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";5import { UnknownPath } from "@repo/protocol/refusal";6import type { UnknownRevision } from "@repo/protocol/refusal";8import { Effect, Option, Schema } from "effect";7import { Effect, Option } from "effect";89import type { CodeProject } from "../code.ts";11import { CodeCache } from "./cache.ts";10import { contentsOf, contentsOfBytes, keepContents, unlessTooLarge } from "./blob.ts";11import type { Contents } from "./blob.ts";12import { versionAt } from "./file-walk.ts";13import { commitAt, resolveAt } from "./revision.ts";14import { entryAt } from "./tree.ts";13import { keptOnlyIfCanonical } from "./history.ts";14import {15 blobKept,16 fileKept,17 fileKey,18 keepObject,19 objectKey,20 throughStore,21} from "./objects.ts";2216export const TEXT_CAP = 1024 * 1024;23export {24 contentsOf,25 contentsOfBytes,26 isBinary,27 TEXT_CAP,28 unlessTooLarge,29} from "./blob.ts";3018// git's own test: a NUL among the first bytes means the blob is not text.19const SNIFF = 8192;31export type { Contents } from "./blob.ts";3221const KEPT_TEXT = 256 * 1024;33import { commitAt, resolveAt } from "./revision.ts";34import type { Resolved } from "./revision.ts";35import { entryAt } from "./tree.ts";3623export const isBinary = (bytes: Uint8Array) =>24 bytes.subarray(0, SNIFF).includes(0);2526export interface Contents {27 readonly size: number;28 readonly binary: boolean;29 readonly truncated: boolean;30 readonly text: Option.Option<string>;31}3233const MemoryLimit = Schema.Struct({ code: Schema.Literal("MEMORY_LIMIT") });3435const isMemoryLimit = Schema.is(MemoryLimit);3637/** Artifacts' binding throws a too-large blob as a defect, which here is an answer. */38export 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 );4546export const contentsOfBytes = (bytes: Uint8Array): Contents => {47 const binary = isBinary(bytes);48 const truncated = !binary && bytes.length > TEXT_CAP;4950 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};6061export const contentsOf = (62 repo: RepoName,63 blob: BlobSha64): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>65 Effect.gen(function* () {66 const cache = yield* CodeCache;6768 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 });9637const viewOf = (38 commit: CommitSha,39 path: RepoPath,40 sha: BlobSha,
10 unmodified lines
51 onSome: (text) => ({ text }),52 }),53});54115/** ASSUMPTION: Artifacts' `readFile` gives a symlink's own blob, as the tree does, rather than following it. */116const wholeAt = (repo: RepoName, commit: CommitSha, path: RepoPath) =>55interface Whole {56 readonly blob: BlobSha;57 readonly contents: Contents;58}5960/**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 */66const 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);73120 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);7576 if (Option.isSome(named)) {77 const kept = yield* contentsOf(repo, named.value.blob);7879 if (Option.isSome(kept)) {80 return Option.some({ blob: named.value.blob, contents: kept.value });81 }82 }8384 const read = yield* unlessTooLarge(85 versionAt(repo, commit, path),86 Option.none87 );8889 if (Option.isNone(read)) {90 return Option.none();91 }9293 const { blob, bytes } = read.value;94 const contents = contentsOfBytes(bytes);9596 yield* keepObject(fileKept, key, { blob });97 yield* keepObject(blobKept, objectKey(blobKept, repo, blob), contents, {98 heavy: true,99 keep: keepContents,100 });101102 return Option.some({ blob, contents });103 });104134export const fileView = (135 project: CodeProject,136 at: Option.Option<Rev>,105const 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);141110 const whole = yield* wholeAt(repo, commit, path).pipe(Effect.orDie);111112 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 }115116 const { tree } = yield* commitAt(repo, commit).pipe(117 Effect.flatMap(Effect.fromOption),
15 unmodified lines
133 );134135 return viewOf(commit, path, sha, contents);136 });137138export 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);145146 return yield* keptOnlyIfCanonical(resolved, fileAtCommit(resolved, path));147 });148
modified:packages/project/src/code/history.ts+3 added-2 removed
33 unmodified lines
34});3536export type StoredPathLog = typeof StoredPathLog.Type;3738const sha256 = (text: string) =>38/** A path's SHA-256 in hex, so a key stays under the store's limit and names no path. */39export const hashOf = (text: string) =>40 Effect.map(41 Effect.promise(() =>42 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))43 ),
30 unmodified lines
74 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 lines
modified:packages/project/src/code/log.ts+33 added-16 removed
11 unmodified lines
12import type { UnknownRevision } from "@repo/protocol/refusal";13import { Array, DateTime, Effect, Equal, Option } from "effect";1415import type { CodeProject } from "../code.ts";16import { asOneView, CodeCache } from "./cache.ts";16import { asOneView } from "./cache.ts";17import { versionAt, walkableAt } from "./file-walk.ts";18import {19 INCREMENT_REACH,20 keyOf,
2 unmodified lines
23 recall,24 throughHistory,25} from "./history.ts";26import type { StoredPathLog } from "./history.ts";27import { logKept, logKey, throughStore } from "./objects.ts";28import { commitAt, resolveAt } from "./revision.ts";29import type { Resolved } from "./revision.ts";30import { entryAt, READS_AT_ONCE } from "./tree.ts";3132export const LOG_LIMIT = 100;33
56 unmodified lines
90 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(() => [])));10295 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 });103103const 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 lines
249 ],250 };251 });252254export const logPage = (253const 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 lines
323 return pageWith(324 commits,325 scan.length > PATH_SCAN ? Option.some(from + PATH_SCAN) : Option.none()326 );327 });328329export 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);340341 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 */10import { Commit, TreeEntry } from "@repo/artifacts/repo-host";11import { BlobSha } from "@repo/protocol/ids";12import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";13import { Data, Effect, Option, Schema } from "effect";1415import { CodeStore } from "../code-store.ts";16import { CodeCache } from "./cache.ts";17import type { Keeping } from "./cache.ts";18import { hashOf } from "./history.ts";1920/** Bump when what is kept changes. */21export const OBJECT_VERSION = 1;2223export const StoredBlob = Schema.Struct({24 binary: Schema.Boolean,25 size: Schema.Int,26 text: Schema.OptionFromOptionalKey(Schema.String),27 truncated: Schema.Boolean,28});2930export type StoredBlob = typeof StoredBlob.Type;3132/** The blob a path names at a commit: an id alone, whose contents are kept by it. */33export const StoredFile = Schema.Struct({ blob: BlobSha });3435export type StoredFile = typeof StoredFile.Type;3637/** A kind of kept object, its codec built once: a read decodes and keeps thousands of them. */38export 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}4445const keptObject = <A>(46 kind: string,47 schema: Schema.Codec<A, unknown>48): KeptObject<A> => {49 const json = Schema.fromJsonString(schema);5051 return {52 decode: Schema.decodeUnknownOption(json),53 encode: Schema.encodeEffect(json),54 kind,55 version: OBJECT_VERSION,56 };57};5859export const commitKept = keptObject("commit-object", Commit);6061export const treeKept = keptObject("tree", Schema.Array(TreeEntry));6263export const blobKept = keptObject("blob", StoredBlob);6465export const logKept = keptObject("log", Schema.Array(Commit));6667export const fileKept = keptObject("file", StoredFile);6869export const objectKey = <A>(70 kept: KeptObject<A>,71 repo: RepoName,72 id: string73) =>74 `${repo}/${kept.kind}/v${kept.version}/${id}`;7576/** A log page from a commit is immutable too: first parents never move. */77export const logKey = (78 repo: RepoName,79 sha: CommitSha,80 from: number,81 count: number82) => objectKey(logKept, repo, `${sha}/${from}/${count}`);8384/** The path is hashed, as history hashes it, to keep the key under the store's limit. */85export const fileKey = (repo: RepoName, commit: CommitSha, path: RepoPath) =>86 Effect.map(hashOf(path), (hash) =>87 objectKey(fileKept, repo, `${commit}/${hash}`)88 );8990export 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}9798class ObjectMissing extends Data.TaggedError("ObjectMissing") {}99100const always = () => true;101102/** What the isolate's cache is told: only the fields given, since an absent one means the default. */103const cacheKeeping = <A>(keeping: KeepingObject<A>): Keeping<A> => {104 const told: { heavy?: boolean; keep?: (value: A) => boolean } = {};105106 if (keeping.heavy !== undefined) {107 told.heavy = keeping.heavy;108 }109110 if (keeping.keep !== undefined) {111 told.keep = keeping.keep;112 }113114 return told;115};116117const putKept = <A>(kept: KeptObject<A>, key: string, value: A) =>118 Effect.gen(function* () {119 const store = yield* CodeStore;120121 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 });126127/**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 */132export 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;141142 if (!keep(value)) {143 return;144 }145146 yield* putKept(kept, key, value);147 yield* cache.through(key, Effect.succeed(value), {148 ...cacheKeeping(keeping),149 keep,150 });151 });152153/**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 */157export 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;168169 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 );175176 if (Option.isSome(found)) {177 return found.value;178 }179180 const computed = yield* compute;181182 if (Option.isNone(computed)) {183 return yield* new ObjectMissing();184 }185186 if (keep(computed.value)) {187 yield* putKept(kept, key, computed.value);188 }189190 return computed.value;191 }192 );193194 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 lines
11import { Array, Effect, Order } from "effect";1213import type { CodeProject } from "../code.ts";14import { CodeCache } from "./cache.ts";15import { keptOnlyIfCanonical } from "./history.ts";16import { commitAt, resolveAt } from "./revision.ts";17import type { Resolved } from "./revision.ts";18import { entriesOf } from "./tree.ts";1920export const PATHS_CAP = 50_000;21
61 unmodified lines
83 truncated: all.length > cap || depth.length > 0,84 };85 });8685export const pathList = (86 project: CodeProject,87 at: Option.Option<Rev>88): Effect.Effect<PathList, UnknownRevision, RepoHost> =>87const pathsAt = ({ commit, repo }: Resolved) =>88 Effect.gen(function* () {90 const { commit, repo } = yield* resolveAt(project, at);89 const cache = yield* CodeCache;9091 const { tree } = yield* commitAt(repo, commit).pipe(92 Effect.flatMap(Effect.fromOption),
8 unmodified lines
101 .pipe(Effect.orDie);102103 return { at: commit, paths: files.map(({ path }) => path), truncated };104 });105106export 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);112113 return yield* keptOnlyIfCanonical(resolved, pathsAt(resolved));114 });115
modified:packages/project/src/code/raw.ts+24 added-10 removed
1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2import type { RepoNotFound } from "@repo/artifacts/repo-host";3import { Rev } from "@repo/protocol/domain/code";4import { BlobSha, RepoPath } from "@repo/protocol/ids";5import type { ProjectName } from "@repo/protocol/ids";6import { Effect, Option, Schema } from "effect";
1 unmodified line
8import { codeProjectOf } from "../code.ts";9import type { CodeProject } from "../code.ts";10import { Projects } from "../projects.ts";11import { isBinary, unlessTooLarge } from "./file.ts";12import { keptOnlyIfCanonical } from "./history.ts";13import { commitAt, isFullSha, resolveAt } from "./revision.ts";14import type { Resolved } from "./revision.ts";15import { entryAt, segmentsOf } from "./tree.ts";1617/** Both origins hold a session cookie, so no raw file may run as script: every answer, a refusal too, carries `nosniff` and this CSP. */18const SANDBOX =
50 unmodified lines
69const notFound = () => new Response(null, { headers: SAFE, status: 404 });7071const tooLarge = () => new Response(null, { headers: SAFE, status: 413 });7270export const rawOf = (71 project: CodeProject,73const 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));7779 const { tree } = yield* commitAt(repo, commit).pipe(80 Effect.flatMap(Effect.fromOption)81 );82
23 unmodified lines
106 }),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 );112113const decodeRev = Schema.decodeUnknownOption(Rev);114
42 unmodified lines
157 Effect.flatMap((api) => rawOf(codeProjectOf(api, project), rev, path)),158 Effect.catchTag("UnknownProject", () => Effect.succeed(notFound()))159 ),160 });161162export 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));169170 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 lines
15import { UnknownRevision } from "@repo/protocol/refusal";16import { Array, Effect, Option } from "effect";1718import type { CodeProject } from "../code.ts";19import { CodeCache } from "./cache.ts";19import { keptOnlyIfCanonical } from "./history.ts";20import { commitKept, objectKey, throughStore } from "./objects.ts";2122const FULL_SHA = /^[0-9a-f]{40}$/u;2324export const isFullSha = (rev: string) => FULL_SHA.test(rev);
16 unmodified lines
41export 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 );5147 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 });5952/**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 lines
95 )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 lines
modified:packages/project/src/code/tree.ts+38 added-37 removed
6 unmodified lines
7import type { UnknownRevision } from "@repo/protocol/refusal";8import { Array, Effect, Match, Option, Order } from "effect";910import type { CodeProject } from "../code.ts";11import { CodeCache } from "./cache.ts";11import { contentsOf } from "./blob.ts";12import { keptOnlyIfCanonical } from "./history.ts";13import { objectKey, throughStore, treeKept } from "./objects.ts";14import { commitAt, resolveAt } from "./revision.ts";15import type { Resolved } from "./revision.ts";1617/** 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. */18export const READS_AT_ONCE = 48;1920export 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 );3624 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 });3637export const segmentsOf = (path: string): Option.Option<readonly string[]> => {38 const segments = path.split("/");3940 return segments.every(
80 unmodified lines
121};122123const LINK_TARGET_MAX = 4096;124125/** A link's blob is kept as any blob is, by its id. */126const 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 );133129 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 });142134/** One link followed, never a chain; a link's entry is a blob too, so its kind is asked, not its type. */135const linkedFile = (136 repo: RepoName,137 root: Effect.Effect<string, never, RepoHost>,
83 unmodified lines
221 RepoNotFound: Effect.die,222 })223 );224234export const listing = (235 project: CodeProject,236 at: Option.Option<Rev>,225const 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);231232 const prefix = Option.match(path, {233 onNone: () => "",
38 unmodified lines
272 onSome: (found) => ({ readme: found }),273 }),274 };275 });276277export 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);284285 return yield* keptOnlyIfCanonical(resolved, folderListing(resolved, path));286 });287
modified:packages/project/src/code/why.ts+8 added-7 removed
525 unmodified lines
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(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 );538539 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 lines
247 const again = yield* onIsolate(whyOf(code, Option.none(), format));248 const { blobs, commits, files, logs, trees } = yield* Ref.get(seen);249250 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 lines
modified:packages/project/test/code-store.test.ts+65 added
1import { describe, expect, it } from "@effect/vitest";2import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3import { RepoPath } from "@repo/protocol/ids";4import { Effect, Exit, Layer, Logger, Option } from "effect";56import { CodeStore } from "../src/code-store.ts";7import { CodeStoreR2 } from "../src/code-store/binding.ts";8import type { BucketLike } from "../src/code-store/binding.ts";9import { CodeStoreCounts, CodeStoreMemory } from "../src/code-store/memory.ts";10import { fileOf, treeOf } from "../src/code.ts";11import { datekit } from "./code-fixtures.ts";1213const key = "datekit/why/v1/1111111111111111111111111111111111111111/main/ab";1415/** A key one byte past R2's limit of 1,024. */
131 unmodified lines
147 ]).toStrictEqual([true, true, false]);148 }).pipe(Effect.provide(layer))149 );150});151152const folderAndReadme = Effect.gen(function* () {153 const { code } = yield* datekit;154155 return yield* Effect.all([156 treeOf(code, Option.none(), Option.none()),157 fileOf(code, Option.none(), RepoPath.make("README.md")),158 ]);159});160161describe("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 );169170 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 );180181 expect(exit).toStrictEqual(Exit.succeed(plain));182 expect(messages.length).toBeGreaterThan(0);183 })184 );185186 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({});190191 const kept = {192 ...bucket,193 put: (name: string, value: string) => {194 objects.set(name, value);195196 return bucket.put(name, value);197 },198 };199200 yield* folderAndReadme.pipe(201 Effect.provide(Layer.merge(RepoHostMemory, CodeStoreR2(kept)))202 );203204 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 line
2import { RepoHost } from "@repo/artifacts/repo-host";3import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4import { Brand } from "@repo/brand";5import { CommitDiff } from "@repo/protocol/domain/code";6import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";6import { CommitSha, LandedSha, RepoName, RepoPath } from "@repo/protocol/ids";7import {8 UnknownCommit,9 UnknownPath,10 UnknownRevision,
22 unmodified lines
33 whyOf,34} from "../src/code.ts";35import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";36import { commitKey, DIFF_TEXT } from "../src/code/commit.ts";37import { commitKept, objectKey } from "../src/code/objects.ts";38import { filesUnder } from "../src/code/paths.ts";39import { compareTags } from "../src/code/refs.ts";40import { READS_AT_ONCE } from "../src/code/tree.ts";41import {
1019 unmodified lines
1061 expect(yield* Fiber.join(next)).toStrictEqual(Option.some("read"));1062 }).pipe(Effect.provide(CodeCacheLive(10, 10)))1063 );1064});10651066const hostCountedBy = (reads: Ref.Ref<number>) =>1067 Layer.effect(1068 RepoHost,1069 Effect.gen(function* () {1070 const host = yield* RepoHost;1071 const counted = countedIn(reads);10721073 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));10841085const 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));10891090const onIsolate = <A, E, R>(effect: Effect.Effect<A, E, R>) =>1091 Effect.provide(effect, CodeCacheLive(100));10921093const byText = (one: string, other: string) => one.localeCompare(other);10941095const readme = RepoPath.make("README.md");10961097describe("objects kept across isolates", () => {1098 it.effect(1099 "answer a folder, a file, a log page and a commit on a second isolate from the store, reaching the host no more",1100 () =>1101 Effect.gen(function* () {1102 const reads = yield* Ref.make(0);11031104 yield* Effect.gen(function* () {1105 const { c4, code } = yield* datekit;11061107 const views = Effect.all([1108 treeOf(code, main, Option.none()),1109 treeOf(code, main, path("src")),1110 fileOf(code, main, readme),1111 logOf(code, page),1112 commitOf(code, c4),1113 ]);11141115 const first = yield* onIsolate(views);1116 const counted = yield* Ref.get(reads);11171118 expect(counted).toBeGreaterThan(0);11191120 const again = yield* onIsolate(views);11211122 expect(again).toStrictEqual(first);1123 expect(yield* Ref.get(reads)).toBe(counted);1124 }).pipe(1125 Effect.provide(Layer.merge(hostCountedBy(reads), CodeStoreMemory))1126 );1127 })1128 );11291130 it.effect(1131 "leave main resolved every time: a landing between two reads shows in the second, store and isolate warm",1132 () =>1133 Effect.gen(function* () {1134 const { c3, c4, code } = yield* datekit;1135 const head = yield* Ref.make(Option.some(LandedSha.make(c3)));1136 const asked = yield* Ref.make(0);11371138 const moving = {1139 ...code,1140 head: Ref.update(asked, (count) => count + 1).pipe(1141 Effect.andThen(Ref.get(head))1142 ),1143 };11441145 const before = yield* treeOf(moving, main, Option.none());11461147 yield* Ref.set(head, Option.some(LandedSha.make(c4)));11481149 const after = yield* treeOf(moving, main, Option.none());11501151 expect([before.at, after.at, yield* Ref.get(asked)]).toStrictEqual([1152 c3,1153 c4,1154 2,1155 ]);1156 }).pipe(1157 Effect.provide(1158 Layer.mergeAll(RepoHostMemory, CodeStoreMemory, CodeCacheLive(100))1159 )1160 )1161 );11621163 it.effect(1164 "read again a kept object that no longer decodes, or that names another id, and replace it",1165 () =>1166 Effect.gen(function* () {1167 const reads = yield* Ref.make(0);11681169 yield* Effect.gen(function* () {1170 const { c3, c4, code } = yield* datekit;1171 const store = yield* CodeStore;1172 const key = objectKey(commitKept, code.repo, c4);11731174 const fresh = yield* onIsolate(treeOf(code, main, Option.none()));11751176 yield* onIsolate(treeOf(code, revision(c3), Option.none()));11771178 const kept = yield* store.get(key);11791180 const other = yield* store.get(objectKey(commitKept, code.repo, c3));11811182 expect([Option.isSome(kept), Option.isSome(other)]).toStrictEqual([1183 true,1184 true,1185 ]);11861187 for (const planted of [1188 '{"sha":"not a commit"}',1189 Option.getOrElse(other, () => ""),1190 ]) {1191 yield* store.put(key, planted);1192 yield* Ref.set(reads, 0);11931194 expect(1195 yield* onIsolate(treeOf(code, main, Option.none()))1196 ).toStrictEqual(fresh);1197 expect(yield* Ref.get(reads)).toBeGreaterThan(0);1198 expect(yield* store.get(key)).toStrictEqual(kept);1199 }1200 }).pipe(1201 Effect.provide(Layer.merge(hostCountedBy(reads), CodeStoreMemory))1202 );1203 })1204 );12051206 it.effect(1207 "are keyed under the project's own repo by kind, version and id, and hold no landing",1208 () =>1209 Effect.gen(function* () {1210 const kept = yield* Ref.make<ReadonlyMap<string, string>>(new Map());12111212 const recording = Layer.succeed(CodeStore, {1213 get: (key) =>1214 Effect.map(Ref.get(kept), (all) =>1215 Option.fromUndefinedOr(all.get(key))1216 ),1217 put: (key, value) =>1218 Ref.update(kept, (all) => new Map([...all, [key, value]])),1219 });12201221 const repo = yield* Effect.gen(function* () {1222 const { c4, code } = yield* datekit;12231224 yield* treeOf(code, main, Option.none());1225 yield* fileOf(code, main, readme);1226 yield* logOf(code, page);1227 yield* commitOf(code, c4);12281229 return code.repo;1230 }).pipe(Effect.provide(Layer.merge(RepoHostMemory, recording)));12311232 const all = [...(yield* Ref.get(kept))];12331234 const ownKey = new RegExp(1235 `^${repo}/(blob|commit|commit-object|file|log|tree)/v[1-9]\\d*/`,1236 "u"1237 );12381239 expect(all.filter(([key]) => !ownKey.test(key))).toStrictEqual([]);1240 expect(1241 [...new Set(all.map(([key]) => key.split("/")[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});