objects.ts
This file
Path
packages/project/src/code/objects.ts
199 lines · 5.9 KiB · TypeScript
Last changed by
Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd
History of this fileTake it
Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd
lines 1–199why, one step back1/**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 });