Skip to content
Myr

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

15 files+767 added−206 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+86 added-108 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 {11 contentsOf,12 contentsOfBytes,13 keepContents,14 unlessTooLarge,15} from "./blob.ts";16import type { Contents } from "./blob.ts";17import { versionAt } from "./file-walk.ts";18import { keptOnlyIfCanonical } from "./history.ts";19import {20 blobKept,21 fileKept,22 fileKey,23 keepObject,24 objectKey,25 throughStore,26} from "./objects.ts";27import { commitAt, resolveAt } from "./revision.ts";28import type { Resolved } from "./revision.ts";29import { entryAt } from "./tree.ts";3016export const TEXT_CAP = 1024 * 1024;31export {32 contentsOf,33 contentsOfBytes,34 isBinary,35 TEXT_CAP,36 unlessTooLarge,37} from "./blob.ts";3818// git's own test: a NUL among the first bytes means the blob is not text.19const SNIFF = 8192;39export type { Contents } from "./blob.ts";4021const KEPT_TEXT = 256 * 1024;2223export 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 });9641const viewOf = (42 commit: CommitSha,43 path: RepoPath,44 sha: BlobSha,
10 unmodified lines
55 onSome: (text) => ({ text }),56 }),57});58115/** 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) =>59interface Whole {60 readonly blob: BlobSha;61 readonly contents: Contents;62}6364/**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 */70const 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);77120 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);7980 if (Option.isSome(named)) {81 const kept = yield* contentsOf(repo, named.value.blob);8283 if (Option.isSome(kept)) {84 return Option.some({ blob: named.value.blob, contents: kept.value });85 }86 }8788 const read = yield* unlessTooLarge(89 versionAt(repo, commit, path),90 Option.none91 );9293 if (Option.isNone(read)) {94 return Option.none();95 }9697 const { blob, bytes } = read.value;98 const contents = contentsOfBytes(bytes);99100 yield* keepObject(fileKept, key, { blob });101 yield* keepObject(blobKept, objectKey(blobKept, repo, blob), contents, {102 heavy: true,103 keep: keepContents,104 });105106 return Option.some({ blob, contents });107 });108134export const fileView = (135 project: CodeProject,136 at: Option.Option<Rev>,109const 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);141114 const whole = yield* wholeAt(repo, commit, path).pipe(Effect.orDie);115116 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 }119120 const { tree } = yield* commitAt(repo, commit).pipe(121 Effect.flatMap(Effect.fromOption),
15 unmodified lines
137 );138139 return viewOf(commit, path, sha, contents);140 });141142export 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);149150 return yield* keptOnlyIfCanonical(resolved, fileAtCommit(resolved, path));151 });
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+32 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);
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 */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>(kept: KeptObject<A>, repo: RepoName, id: string) =>70 `${repo}/${kept.kind}/v${kept.version}/${id}`;7172/** A log page from a commit is immutable too: first parents never move. */73export const logKey = (74 repo: RepoName,75 sha: CommitSha,76 from: number,77 count: number78) => objectKey(logKept, repo, `${sha}/${from}/${count}`);7980/** The path is hashed, as history hashes it, to keep the key under the store's limit. */81export const fileKey = (repo: RepoName, commit: CommitSha, path: RepoPath) =>82 Effect.map(hashOf(path), (hash) =>83 objectKey(fileKept, repo, `${commit}/${hash}`)84 );8586export 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}9394class ObjectMissing extends Data.TaggedError("ObjectMissing") {}9596const always = () => true;9798interface Told<A> {99 heavy?: boolean;100 keep?: (value: A) => boolean;101}102103/** What the isolate's cache is told: only the fields given, since an absent one means the default. */104const cacheKeeping = <A>(keeping: KeepingObject<A>): Keeping<A> => {105 const told: Told<A> = {};106107 if (keeping.heavy !== undefined) {108 told.heavy = keeping.heavy;109 }110111 if (keeping.keep !== undefined) {112 told.keep = keeping.keep;113 }114115 return told;116};117118const putKept = <A>(kept: KeptObject<A>, key: string, value: A) =>119 Effect.gen(function* () {120 const store = yield* CodeStore;121122 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 });127128/**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 */133export 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;142143 if (!keep(value)) {144 return;145 }146147 yield* putKept(kept, key, value);148 yield* cache.through(key, Effect.succeed(value), {149 ...cacheKeeping(keeping),150 keep,151 });152 });153154/**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 */158export 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;169170 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 );176177 if (Option.isSome(found)) {178 return found.value;179 }180181 const computed = yield* compute;182183 if (Option.isNone(computed)) {184 return yield* new ObjectMissing();185 }186187 if (keep(computed.value)) {188 yield* putKept(kept, key, computed.value);189 }190191 return computed.value;192 }193 );194195 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 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 });
modified:packages/project/src/code/raw.ts+23 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
30 unmodified lines
145146 return segments[2] === "raw" ? segments.slice(3).join("/") : "";147};148149export 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));156157 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 );164165export const rawFor = (166 project: ProjectName,167 url: string168): Effect.Effect<Response, never, RepoHost | Projects> =>
8 unmodified lines
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+37 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 });
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("/").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 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 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));10701071const hostCountedBy = (reads: Ref.Ref<number>) =>1072 Layer.effect(1073 RepoHost,1074 Effect.gen(function* () {1075 const host = yield* RepoHost;1076 const counted = countedIn(reads);10771078 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));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("/").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});