Skip to content
Myr

Merge build/208-artifacts-local: repos live as bare git repos on local disk behind the same RepoHost port

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents fd74101, 1471bd0 · Browse files · 4 files+1122 added−324 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+1122 added−324 removed

  • tests:+218 added−0 removed
  • other:+904 added−324 removed

4 files+1122 added−324 removed

added:packages/artifacts/src/repo-host/isogit-store.ts+333 added
1import { CommitSha } from "@repo/protocol/ids";2import { Array, Data, Effect, Equal, Match, Option, Schema } from "effect";3import type { Semaphore } from "effect";4import {5 Errors,6 init,7 listRefs,8 readBlob,9 readCommit,10 readTree,11 resolveRef,12 writeBlob,13 writeCommit,14 writeRef,15 writeTree,16} from "isomorphic-git";1718import {19 ObjectId,20 RefName,21 RefOutcome,22 Revision,23 TreeEntry,24} from "../repo-host.ts";25import type {26 Commit,27 PushSource,28 RefUpdate,29 RepoHost,30 RepoName,31 RepoNotFound,32} from "../repo-host.ts";3334/**35 * A bare repo's directory on a file system isomorphic-git reads and writes:36 * the shape a push takes its objects from, so every stored repo is a source37 * too.38 */39export type GitDir = PushSource;4041/** A repo a store found by name: its directory and the lock its pushes take. */42export interface StoredRepo {43 readonly dir: GitDir;44 readonly lock: Semaphore.Semaphore;45}4647/** The ref every repo's HEAD names: Artifacts' default branch. */48export const mainRef = "refs/heads/main";4950class GitFailure extends Data.TaggedError("GitFailure")<{51 readonly cause: unknown;52}> {}5354const git = <A>(run: () => Promise<A>) =>55 Effect.tryPromise({ catch: (cause) => new GitFailure({ cause }), try: run });5657/** `None` where isomorphic-git finds no such object, ref or file. */58export const unlessMissing = <A>(59 run: () => Promise<A>60): Effect.Effect<Option.Option<A>> =>61 git(run).pipe(62 Effect.asSome,63 Effect.catchIf(64 (failure) =>65 failure.cause instanceof Errors.NotFoundError ||66 failure.cause instanceof Errors.ObjectTypeError,67 () => Effect.succeedNone68 ),69 Effect.orDie70 );7172// Each object is rewritten from its parsed form; a changed id would mean the73// copy is not the object the pusher sent.74const keep = (oid: string, write: () => Promise<string>) =>75 git(write).pipe(76 Effect.orDie,77 Effect.flatMap((written) =>78 written === oid79 ? Effect.void80 : Effect.die(`copying ${oid} produced ${written}`)81 )82 );8384/** A new, empty bare repo whose HEAD names `main`. */85export const initBare = (repo: GitDir) =>86 git(() => init({ ...repo, bare: true, defaultBranch: "main" })).pipe(87 Effect.orDie88 );8990export const tipOf = (repo: GitDir, ref: string) =>91 unlessMissing(() => resolveRef({ ...repo, ref })).pipe(92 Effect.map(Option.map((sha) => CommitSha.make(sha)))93 );9495// The copies write children before parents, so every object in a repo has96// everything it points to.97const copyBlob = (source: PushSource, into: GitDir, oid: string) =>98 Effect.gen(function* () {99 const present = yield* unlessMissing(() => readBlob({ ...into, oid }));100101 if (Option.isSome(present)) {102 return;103 }104105 const { blob } = yield* git(() => readBlob({ ...source, oid })).pipe(106 Effect.orDie107 );108109 yield* keep(oid, () => writeBlob({ ...into, blob }));110 });111112const copyTree = (113 source: PushSource,114 into: GitDir,115 oid: string116): Effect.Effect<void> =>117 Effect.gen(function* () {118 const present = yield* unlessMissing(() => readTree({ ...into, oid }));119120 if (Option.isSome(present)) {121 return;122 }123124 const { tree } = yield* git(() => readTree({ ...source, oid })).pipe(125 Effect.orDie126 );127128 // Submodule entries ("commit") point outside the repo; git copies none.129 yield* Effect.forEach(tree, (entry) =>130 Match.value(entry.type).pipe(131 Match.when("blob", () => copyBlob(source, into, entry.oid)),132 Match.when("tree", () => copyTree(source, into, entry.oid)),133 Match.when("commit", () => Effect.void),134 Match.exhaustive135 )136 );137 yield* keep(oid, () => writeTree({ ...into, tree }));138 });139140const copyCommit = (141 source: PushSource,142 into: GitDir,143 oid: string144): Effect.Effect<void> =>145 Effect.gen(function* () {146 const present = yield* unlessMissing(() => readCommit({ ...into, oid }));147148 if (Option.isSome(present)) {149 return;150 }151152 const { commit } = yield* git(() => readCommit({ ...source, oid })).pipe(153 Effect.orDie154 );155156 yield* copyTree(source, into, commit.tree);157 yield* Effect.forEach(commit.parent, (parent) =>158 copyCommit(source, into, parent)159 );160 yield* keep(oid, () => writeCommit({ ...into, commit }));161 });162163/** Sets the new repo `into`'s `ref` to `source`'s `tip`, objects first. */164export const seedRef = (165 source: PushSource,166 into: GitDir,167 ref: string,168 tip: Option.Option<CommitSha>169) =>170 Effect.gen(function* () {171 if (Option.isNone(tip)) {172 return;173 }174175 yield* copyCommit(source, into, tip.value);176 yield* git(() => writeRef({ ...into, ref, value: tip.value })).pipe(177 Effect.orDie178 );179 });180181// S1 #3 and #6: each ref is its own compare-and-swap, applied or refused182// whatever the others in the same push come to.183const apply = (into: GitDir, source: PushSource, update: RefUpdate) =>184 Effect.gen(function* () {185 const tip = yield* tipOf(into, update.ref);186187 if (!Equal.equals(tip, update.from)) {188 return RefOutcome.Stale({ ref: update.ref, tip });189 }190191 yield* copyCommit(source, into, update.to);192 yield* git(() =>193 writeRef({ ...into, force: true, ref: update.ref, value: update.to })194 ).pipe(Effect.orDie);195196 return RefOutcome.Updated({ ref: update.ref });197 });198199const resolve = (repo: GitDir, at: Revision) =>200 Revision.$match(at, {201 Branch: ({ name }) => tipOf(repo, `refs/heads/${name}`),202 Commit: ({ sha }) => Effect.succeedSome(sha),203 });204205// Artifacts drops one trailing newline from a commit message.206const commitAt = (repo: GitDir, sha: CommitSha) =>207 unlessMissing(() => readCommit({ ...repo, oid: sha })).pipe(208 Effect.map(209 Option.map(({ commit, oid }): Commit => ({210 author: { email: commit.author.email, name: commit.author.name },211 committer: {212 email: commit.committer.email,213 name: commit.committer.name,214 },215 message: commit.message.replace(/\n$/u, ""),216 parents: commit.parent.map((parent) => CommitSha.make(parent)),217 sha: CommitSha.make(oid),218 tree: ObjectId.make(commit.tree),219 }))220 )221 );222223// isomorphic-git's entries carry `path` and `oid`; the port's, `name` and `sha`.224const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));225226/**227 * The RepoHost methods that read a repo's objects and refs or push to it,228 * the same over every store whose repos are isomorphic-git directories:229 * `known` finds a repo's directory and lock by name. A push is a230 * compare-and-swap per ref under the repo's lock, never atomic across refs231 * (S1 #6); reads resolve short branch names and commit ids only (S1 #20).232 */233export const objectsAndRefs = (234 known: (name: RepoName) => Effect.Effect<StoredRepo, RepoNotFound>235): Pick<236 RepoHost["Service"],237 "log" | "push" | "readBlob" | "readCommit" | "readFile" | "readTree" | "refs"238> => ({239 log: (name, at, limit) =>240 Effect.gen(function* () {241 const { dir } = yield* known(name);242 const commits: Commit[] = [];243 let next = yield* resolve(dir, at);244245 while (Option.isSome(next) && commits.length < limit) {246 const commit = yield* commitAt(dir, next.value);247248 if (Option.isNone(commit)) {249 break;250 }251252 commits.push(commit.value);253 next = Option.fromNullishOr(commit.value.parents[0]);254 }255256 return commits;257 }),258 push: (name, source, updates) =>259 Effect.gen(function* () {260 const { dir, lock } = yield* known(name);261262 return yield* lock.withPermit(263 Effect.forEach(updates, (update) => apply(dir, source, update))264 );265 }),266 // Only a blob by its own id: no tag or commit is peeled to one.267 readBlob: (name, blob) =>268 Effect.gen(function* () {269 const { dir } = yield* known(name);270 const read = yield* unlessMissing(() => readBlob({ ...dir, oid: blob }));271272 return Option.flatMap(read, ({ blob: bytes, oid }) =>273 oid === blob ? Option.some(bytes) : Option.none()274 );275 }),276 readCommit: (name, sha) =>277 known(name).pipe(Effect.flatMap(({ dir }) => commitAt(dir, sha))),278 readFile: (name, at, path) =>279 Effect.gen(function* () {280 const { dir } = yield* known(name);281 const sha = yield* resolve(dir, at);282283 if (Option.isNone(sha)) {284 return Option.none();285 }286287 const blob = yield* unlessMissing(() =>288 readBlob({ ...dir, filepath: path, oid: sha.value })289 );290291 return Option.map(blob, ({ blob: bytes }) => bytes);292 }),293 // Only a tree by its own id: isomorphic-git peels a commit to its tree.294 readTree: (name, tree) =>295 Effect.gen(function* () {296 const { dir } = yield* known(name);297 const read = yield* unlessMissing(() => readTree({ ...dir, oid: tree }));298299 if (Option.isNone(read) || read.value.oid !== tree) {300 return Option.none();301 }302303 const entries = yield* decodeEntries(304 read.value.tree.map((entry) => ({305 mode: entry.mode,306 name: entry.path,307 sha: entry.oid,308 type: entry.type,309 }))310 ).pipe(Effect.orDie);311312 return Option.some(entries);313 }),314 refs: (name) =>315 Effect.gen(function* () {316 const { dir } = yield* known(name);317318 const names = yield* git(() =>319 listRefs({ ...dir, filepath: "refs" })320 ).pipe(Effect.orDie);321322 const listed = yield* Effect.forEach(names, (relative) =>323 Effect.gen(function* () {324 const ref = RefName.make(`refs/${relative}`);325 const tip = yield* tipOf(dir, ref);326327 return Option.map(tip, (sha) => [ref, sha] as const);328 })329 );330331 return new Map(Array.getSomes(listed));332 }),333});
added:packages/artifacts/src/repo-host/local.ts+552 added
1import * as fs from "node:fs";2import { tmpdir } from "node:os";3import { fileURLToPath } from "node:url";45import type { CommitSha } from "@repo/protocol/ids";6import {7 Data,8 DateTime,9 Effect,10 Layer,11 Match,12 Option,13 Redacted,14 Schema,15 Semaphore,16 Stream,17} from "effect";18import type { Context, Scope } from "effect";19import {20 Errors,21 addRemote,22 currentBranch,23 deleteRemote,24 fetch as fetchPack,25 hashBlob,26 writeRef,27} from "isomorphic-git";28import type {29 GitHttpRequest,30 GitHttpResponse,31 HttpClient,32} from "isomorphic-git";3334import { Fetch, FetchFailed } from "../fetch.ts";35import {36 ImportRefused,37 RepoExists,38 RepoHost,39 RepoNotFound,40} from "../repo-host.ts";41import type {42 BranchName,43 PushSource,44 RepoCreated,45 RepoName,46} from "../repo-host.ts";47import {48 initBare,49 mainRef,50 objectsAndRefs,51 seedRef,52 tipOf,53 unlessMissing,54} from "./isogit-store.ts";55import type { GitDir } from "./isogit-store.ts";5657/** A promise from isomorphic-git or the file system that rejected. */58class IoFailure extends Data.TaggedError("IoFailure")<{59 readonly cause: unknown;60}> {}6162const io = <A>(run: () => Promise<A>) =>63 Effect.tryPromise({ catch: (cause) => new IoFailure({ cause }), try: run });6465/** Whether a file-system call failed with node's error `code`. */66const failedWith = (code: "EEXIST" | "ENOENT") => (failure: IoFailure) =>67 failure.cause instanceof Error &&68 "code" in failure.cause &&69 failure.cause.code === code;7071/** Whether anything is at `path`. */72const exists = (path: string) =>73 io(() => fs.promises.stat(path)).pipe(74 Effect.as(true),75 Effect.catchIf(failedWith("ENOENT"), () => Effect.succeed(false)),76 Effect.orDie77 );7879/** Deletes `path` and everything under it; whether there was anything. */80const removeAll = (path: string) =>81 Effect.gen(function* () {82 const found = yield* exists(path);8384 yield* io(() =>85 fs.promises.rm(path, { force: true, recursive: true })86 ).pipe(Effect.orDie);8788 return found;89 });9091/** The remote an HTTP import fetches through, removed once it has. */92const importRemote = "import";9394const branchOf = (ref: string) => ref.replace(/^refs\/heads\//u, "");9596/**97 * The tokens a repo has minted, kept beside its objects so that every layer98 * over the same root sees them. `minted` counts every token ever minted, so99 * no two get the same id.100 */101const Tokens = Schema.fromJsonString(102 Schema.Struct({ live: Schema.Array(Schema.String), minted: Schema.Int })103);104105type Tokens = typeof Tokens.Type;106107const noTokens: Tokens = { live: [], minted: 0 };108109const concat = (chunks: readonly Uint8Array[]) => {110 const all = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));111 let at = 0;112113 for (const chunk of chunks) {114 all.set(chunk, at);115 at += chunk.length;116 }117118 return all;119};120121/**122 * A request body as one array. isomorphic-git types it as an async iterator123 * but sends an array of chunks, so this takes either.124 */125const bytesOf = (body: AsyncIterable<Uint8Array> | Iterable<Uint8Array>) =>126 (Symbol.asyncIterator in body127 ? Stream.fromAsyncIterable(body, (cause) => new IoFailure({ cause }))128 : Stream.fromIterable(body)129 ).pipe(Stream.runCollect, Effect.map(concat));130131/** One chunk as the async iterator isomorphic-git reads a response body from. */132const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {133 const chunks = [bytes];134135 const iterator: AsyncIterableIterator<Uint8Array> = {136 [Symbol.asyncIterator]: () => iterator,137 next: () => {138 const chunk = chunks.shift();139140 return Promise.resolve(141 chunk === undefined142 ? { done: true, value: undefined }143 : { done: false, value: chunk }144 );145 },146 };147148 return iterator;149};150151/**152 * isomorphic-git's HTTP client over a `Fetch`. isomorphic-git awaits a153 * promise, so each exchange runs as one; a `Fetch` failure rejects it as is.154 */155const httpOver = (156 fetch: Fetch["Service"]["fetch"],157 context: Context.Context<never>158): HttpClient => ({159 request: (request: GitHttpRequest) =>160 Effect.runPromiseWith(context)(161 Effect.gen(function* () {162 const body =163 request.body === undefined164 ? {}165 : { body: yield* bytesOf(request.body) };166167 const response = yield* fetch(168 new Request(request.url, {169 ...body,170 headers: request.headers ?? {},171 method: request.method ?? "GET",172 })173 );174175 const bytes = yield* io(() => response.arrayBuffer());176177 return {178 body: once(new Uint8Array(bytes)),179 headers: Object.fromEntries(response.headers.entries()),180 method: request.method,181 statusCode: response.status,182 statusMessage: response.statusText,183 url: response.url === "" ? request.url : response.url,184 } satisfies GitHttpResponse;185 })186 ),187});188189/** Why a fetch from `url` brought nothing to import. */190const fetchRefusal = (url: string, cause: unknown) =>191 Match.value(cause).pipe(192 Match.when(Schema.is(FetchFailed), (failed) => failed.reason),193 Match.when(Match.instanceOf(Error), (thrown) => thrown.message),194 Match.orElse(() => "no reason given"),195 (reason) => `${url} could not be fetched: ${reason}`196 );197198const make = (options: {199 readonly root: string;200 readonly remoteBase: string;201}) =>202 Effect.gen(function* () {203 const root = options.root.replace(/\/+$/u, "");204 const remoteBase = options.remoteBase.replace(/\/+$/u, "");205 const http = httpOver((yield* Fetch).fetch, yield* Effect.context());206 const locks = new Map<RepoName, Semaphore.Semaphore>();207208 yield* io(() => fs.promises.mkdir(root, { recursive: true })).pipe(209 Effect.orDie210 );211212 const dirOf = (name: RepoName): GitDir => ({213 fs,214 gitdir: `${root}/${name}.git`,215 });216217 const createdOf = (name: RepoName): RepoCreated => ({218 name,219 remote: `${remoteBase}/${name}.git`,220 });221222 const lockOf = (name: RepoName) =>223 Effect.sync(() => {224 const found = locks.get(name);225226 if (found !== undefined) {227 return found;228 }229230 const lock = Semaphore.makeUnsafe(1);231232 locks.set(name, lock);233234 return lock;235 });236237 /** The repo's directory and lock, if the repo exists. */238 const known = (name: RepoName) =>239 Effect.gen(function* () {240 const dir = dirOf(name);241242 if (!(yield* exists(dir.gitdir))) {243 return yield* new RepoNotFound({ name });244 }245246 return { dir, lock: yield* lockOf(name) };247 });248249 /** A new, empty bare repo; making its directory is what claims the name. */250 const open = (name: RepoName) =>251 Effect.gen(function* () {252 const dir = dirOf(name);253254 const made = yield* io(() => fs.promises.mkdir(dir.gitdir)).pipe(255 Effect.as(true),256 Effect.catchIf(failedWith("EEXIST"), () => Effect.succeed(false)),257 Effect.orDie258 );259260 if (!made) {261 return yield* new RepoExists({ name });262 }263264 yield* initBare(dir);265266 return dir;267 });268269 /** A new repo `name` holding `source`'s `ref` at `tip`, copied as it stands. */270 const seed = (271 name: RepoName,272 source: PushSource,273 ref: string,274 tip: Option.Option<CommitSha>275 ) =>276 Effect.gen(function* () {277 yield* seedRef(source, yield* open(name), ref, tip);278279 return createdOf(name);280 });281282 // Local disk's test-only meaning of a public remote: a bare repo on this283 // machine, copied object by object. Without a branch, it takes the one284 // the repo's HEAD names.285 const importFile = (286 name: RepoName,287 url: string,288 branch: BranchName | undefined289 ) =>290 Effect.gen(function* () {291 const noRepo = new ImportRefused({ name, reason: `no repo at ${url}` });292293 // A file URL that names another host is no path on this machine.294 const gitdir = yield* Effect.try({295 catch: () => noRepo,296 try: () => fileURLToPath(url),297 });298299 const head = yield* unlessMissing(() =>300 currentBranch({ fs, fullname: true, gitdir })301 );302303 if (Option.isNone(head)) {304 return yield* noRepo;305 }306307 // A detached HEAD names no branch to take.308 const ref = branch === undefined ? head.value : `refs/heads/${branch}`;309310 if (ref === undefined) {311 return yield* new ImportRefused({312 name,313 reason: `${url} has no default branch`,314 });315 }316317 const tip = yield* tipOf({ fs, gitdir }, ref);318319 if (Option.isNone(tip)) {320 return yield* new ImportRefused({321 name,322 reason: `${url} has no branch ${branchOf(ref)}`,323 });324 }325326 return yield* seed(name, { fs, gitdir }, ref, tip);327 });328329 /** One branch of a smart-HTTP remote, fetched into the empty repo `gitdir`. */330 const fetchInto = (331 name: RepoName,332 gitdir: string,333 url: string,334 branch: BranchName | undefined335 ) =>336 Effect.gen(function* () {337 // isomorphic-git's fetch files what it got under a configured remote's338 // refspec, so the repo has one for as long as the fetch runs.339 yield* io(() =>340 addRemote({ fs, gitdir, remote: importRemote, url })341 ).pipe(Effect.orDie);342343 const fetched = yield* io(() =>344 fetchPack({345 fs,346 gitdir,347 http,348 remote: importRemote,349 remoteRef: branch === undefined ? "HEAD" : `refs/heads/${branch}`,350 singleBranch: true,351 tags: false,352 })353 ).pipe(354 Effect.mapError(355 (failure) =>356 new ImportRefused({357 name,358 reason:359 failure.cause instanceof Errors.NotFoundError360 ? `${url} has no branch ${branch ?? "HEAD"}`361 : fetchRefusal(url, failure.cause),362 })363 )364 );365366 const ref =367 branch === undefined ? fetched.defaultBranch : `refs/heads/${branch}`;368369 const tip = fetched.fetchHead;370371 if (tip === null || ref === null) {372 return yield* new ImportRefused({373 name,374 reason: `${url} has no default branch`,375 });376 }377378 yield* io(() => writeRef({ fs, gitdir, ref, value: tip })).pipe(379 Effect.orDie380 );381 // No repo here has remotes or remote-tracking refs.382 yield* io(() =>383 deleteRemote({ fs, gitdir, remote: importRemote })384 ).pipe(Effect.orDie);385 yield* removeAll(`${gitdir}/refs/remotes`);386387 return createdOf(name);388 });389390 // A public remote over smart HTTP, through the `Fetch` this layer was391 // given. A failed import leaves no repo behind.392 const importHttp = (393 name: RepoName,394 url: string,395 branch: BranchName | undefined396 ) =>397 Effect.flatMap(open(name), ({ gitdir }) =>398 fetchInto(name, gitdir, url, branch).pipe(399 Effect.onError(() => removeAll(gitdir).pipe(Effect.asVoid))400 )401 );402403 /** The repo's tokens file, read and rewritten under the repo's lock. */404 const updateTokens = <A>(405 name: RepoName,406 change: (tokens: Tokens) => Effect.Effect<readonly [A, Tokens]>407 ) =>408 Effect.gen(function* () {409 const { dir, lock } = yield* known(name);410 const path = `${dir.gitdir}/tokens.json`;411412 return yield* lock.withPermit(413 Effect.gen(function* () {414 const text = yield* io(() =>415 fs.promises.readFile(path, "utf-8")416 ).pipe(417 Effect.asSome,418 Effect.catchIf(failedWith("ENOENT"), () => Effect.succeedNone),419 Effect.orDie420 );421422 const stored = Option.isNone(text)423 ? noTokens424 : yield* Schema.decodeEffect(Tokens)(text.value).pipe(425 Effect.orDie426 );427428 const [result, next] = yield* change(stored);429430 const written = yield* Schema.encodeEffect(Tokens)(next).pipe(431 Effect.orDie432 );433434 yield* io(() => fs.promises.writeFile(path, written)).pipe(435 Effect.orDie436 );437438 return result;439 })440 );441 });442443 return RepoHost.of({444 ...objectsAndRefs(known),445 create: (name) => open(name).pipe(Effect.as(createdOf(name))),446 // The default branch only, copied as it stands: later pushes to the base447 // or to a sibling never reach this fork.448 fork: (base, name) =>449 Effect.gen(function* () {450 const { dir } = yield* known(base);451 const tip = yield* tipOf(dir, mainRef);452453 return yield* seed(name, dir, mainRef, tip);454 }),455 importFrom: (name, source) =>456 Effect.gen(function* () {457 if (yield* exists(dirOf(name).gitdir)) {458 return yield* new RepoExists({ name });459 }460461 const scheme = URL.canParse(source.url)462 ? new URL(source.url).protocol463 : "";464465 return yield* Match.value(scheme).pipe(466 Match.when("file:", () =>467 importFile(name, source.url, source.branch)468 ),469 Match.whenOr("http:", "https:", () =>470 importHttp(name, source.url, source.branch)471 ),472 Match.orElse(() =>473 Effect.fail(474 new ImportRefused({475 name,476 reason: `${source.url} is not a file or HTTP URL`,477 })478 )479 )480 );481 }),482 // An id that looks random but is the same for the same repo and count.483 mintToken: (name, scope, ttl) =>484 Effect.gen(function* () {485 const now = yield* DateTime.now;486487 const id = yield* updateTokens(name, (tokens) =>488 Effect.gen(function* () {489 const minted = tokens.minted + 1;490491 const { oid } = yield* io(() =>492 hashBlob({ object: `${name}\n${minted}` })493 ).pipe(Effect.orDie);494495 return [oid, { live: [...tokens.live, oid], minted }] as const;496 })497 );498499 return {500 expiresAt: DateTime.addDuration(now, ttl),501 id,502 scope,503 secret: Redacted.make(`local-${id}`),504 };505 }),506 remote: (name) => known(name).pipe(Effect.as(createdOf(name).remote)),507 remove: (name) => removeAll(dirOf(name).gitdir),508 revokeToken: (name, id) =>509 updateTokens(name, (tokens) =>510 Effect.succeed(511 tokens.live.includes(id)512 ? ([513 true,514 {515 ...tokens,516 live: tokens.live.filter((live) => live !== id),517 },518 ] as const)519 : ([false, tokens] as const)520 )521 ),522 });523 });524525/**526 * Artifacts on local disk, for tests that need real git over HTTP and for the527 * CLI's dev mode: each repo a bare git repo `<root>/<name>.git` with default528 * branch `main`, kept across layers over the same root. A push is a529 * compare-and-swap per ref with no atomicity across refs, as S1 found530 * Artifacts. `remote(name)` is `<remoteBase>/<name>.git`, so a test can serve531 * `root` with `git http-backend` under that base and drive real git at it.532 * Tokens are recorded, never checked.533 */534export const RepoHostLocal = {535 layer: (options: {536 readonly root: string;537 readonly remoteBase: string;538 }): Layer.Layer<RepoHost, never, Fetch> =>539 Layer.effect(RepoHost, make(options)),540 /**541 * A new, empty directory for a store, deleted with everything in it when542 * the scope closes: a root for callers with no file system of their own,543 * such as this package's tests.544 */545 temporaryRoot: Effect.acquireRelease(546 io(() => fs.promises.mkdtemp(`${tmpdir()}/repo-host-`)).pipe(Effect.orDie),547 (root) =>548 io(() => fs.promises.rm(root, { force: true, recursive: true })).pipe(549 Effect.orDie550 )551 ) satisfies Effect.Effect<string, never, Scope.Scope>,552};
modified:packages/artifacts/src/repo-host/memory.ts+19 added-324 removed
1import { CommitSha } from "@repo/protocol/ids";2import {3 Array,4 Data,5 DateTime,6 Effect,7 Equal,8 Layer,9 Match,10 Option,11 Redacted,12 Schema,13 Semaphore,14} from "effect";15import {16 Errors,17 init,18 listRefs,19 readBlob,20 readCommit,21 readTree,22 resolveRef,23 writeBlob,24 writeCommit,25 writeRef,26 writeTree,27} from "isomorphic-git";1import type { CommitSha } from "@repo/protocol/ids";2import { DateTime, Effect, Layer, Option, Redacted, Semaphore } from "effect";34import {5 ImportRefused,31 ObjectId,32 RefName,33 RefOutcome,6 RepoExists,7 RepoHost,8 RepoNotFound,37 Revision,38 TreeEntry,9} from "../repo-host.ts";40import type {41 Commit,42 PushSource,43 RefUpdate,44 RepoCreated,45 RepoName,46} from "../repo-host.ts";10import type { RepoCreated, RepoName } from "../repo-host.ts";11import {12 initBare,13 mainRef,14 objectsAndRefs,15 seedRef,16 tipOf,17} from "./isogit-store.ts";18import type { StoredRepo } from "./isogit-store.ts";19import { memoryFs } from "./memory-fs.ts";2049class GitFailure extends Data.TaggedError("GitFailure")<{50 readonly cause: unknown;51}> {}5253const git = <A>(run: () => Promise<A>) =>54 Effect.tryPromise({ catch: (cause) => new GitFailure({ cause }), try: run });5556/** `None` where isomorphic-git finds no such object, ref or file. */57const unlessMissing = <A>(58 run: () => Promise<A>59): Effect.Effect<Option.Option<A>> =>60 git(run).pipe(61 Effect.asSome,62 Effect.catchIf(63 (failure) =>64 failure.cause instanceof Errors.NotFoundError ||65 failure.cause instanceof Errors.ObjectTypeError,66 () => Effect.succeedNone67 ),68 Effect.orDie69 );7071// Each object is rewritten from its parsed form; a changed id would mean the72// copy is not the object the pusher sent.73const keep = (oid: string, write: () => Promise<string>) =>74 git(write).pipe(75 Effect.orDie,76 Effect.flatMap((written) =>77 written === oid78 ? Effect.void79 : Effect.die(`copying ${oid} produced ${written}`)80 )81 );8283const mainRef = "refs/heads/main";8485// isomorphic-git's entries carry `path` and `oid`; the port's, `name` and `sha`.86const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));8721const remoteOf = (name: RepoName) => `memory://${name}.git`;2223const createdOf = (name: RepoName): RepoCreated => ({24 name,25 remote: remoteOf(name),26});2795interface Repo {96 readonly gitdir: string;97 readonly lock: Semaphore.Semaphore;28interface Repo extends StoredRepo {29 /** Token ids still live; the memory store authenticates nothing. */30 readonly tokens: Set<string>;31}32
14 unmodified lines
47 ? Effect.fail(new RepoNotFound({ name }))48 : Effect.succeed(repo);49 };50120 const tipOf = (repo: Repo, ref: string) =>121 unlessMissing(() => resolveRef({ fs, gitdir: repo.gitdir, ref })).pipe(122 Effect.map(Option.map((sha) => CommitSha.make(sha)))123 );124125 // The copies write children before parents, so every object in a repo has126 // everything it points to.127 const copyBlob = (source: PushSource, repo: Repo, oid: string) =>128 Effect.gen(function* () {129 const present = yield* unlessMissing(() =>130 readBlob({ fs, gitdir: repo.gitdir, oid })131 );132133 if (Option.isSome(present)) {134 return;135 }136137 const { blob } = yield* git(() => readBlob({ ...source, oid })).pipe(138 Effect.orDie139 );140141 yield* keep(oid, () => writeBlob({ blob, fs, gitdir: repo.gitdir }));142 });143144 const copyTree = (145 source: PushSource,146 repo: Repo,147 oid: string148 ): Effect.Effect<void> =>149 Effect.gen(function* () {150 const present = yield* unlessMissing(() =>151 readTree({ fs, gitdir: repo.gitdir, oid })152 );153154 if (Option.isSome(present)) {155 return;156 }157158 const { tree } = yield* git(() => readTree({ ...source, oid })).pipe(159 Effect.orDie160 );161162 // Submodule entries ("commit") point outside the repo; git copies none.163 yield* Effect.forEach(tree, (entry) =>164 Match.value(entry.type).pipe(165 Match.when("blob", () => copyBlob(source, repo, entry.oid)),166 Match.when("tree", () => copyTree(source, repo, entry.oid)),167 Match.when("commit", () => Effect.void),168 Match.exhaustive169 )170 );171 yield* keep(oid, () => writeTree({ fs, gitdir: repo.gitdir, tree }));172 });173174 const copyCommit = (175 source: PushSource,176 repo: Repo,177 oid: string178 ): Effect.Effect<void> =>179 Effect.gen(function* () {180 const present = yield* unlessMissing(() =>181 readCommit({ fs, gitdir: repo.gitdir, oid })182 );183184 if (Option.isSome(present)) {185 return;186 }187188 const { commit } = yield* git(() => readCommit({ ...source, oid })).pipe(189 Effect.orDie190 );191192 yield* copyTree(source, repo, commit.tree);193 yield* Effect.forEach(commit.parent, (parent) =>194 copyCommit(source, repo, parent)195 );196 yield* keep(oid, () => writeCommit({ commit, fs, gitdir: repo.gitdir }));197 });198199 const apply = (repo: Repo, source: PushSource, update: RefUpdate) =>200 Effect.gen(function* () {201 const tip = yield* tipOf(repo, update.ref);202203 if (!Equal.equals(tip, update.from)) {204 return RefOutcome.Stale({ ref: update.ref, tip });205 }206207 yield* copyCommit(source, repo, update.to);208 yield* git(() =>209 writeRef({210 force: true,211 fs,212 gitdir: repo.gitdir,213 ref: update.ref,214 value: update.to,215 })216 ).pipe(Effect.orDie);217218 return RefOutcome.Updated({ ref: update.ref });219 });220221 const resolve = (repo: Repo, at: Revision) =>222 Revision.$match(at, {223 Branch: ({ name }) => tipOf(repo, `refs/heads/${name}`),224 Commit: ({ sha }) => Effect.succeedSome(sha),225 });226227 // Artifacts drops one trailing newline from a commit message.228 const commitAt = (repo: Repo, sha: CommitSha) =>229 unlessMissing(() => readCommit({ fs, gitdir: repo.gitdir, oid: sha })).pipe(230 Effect.map(231 Option.map(({ commit, oid }): Commit => ({232 author: { email: commit.author.email, name: commit.author.name },233 committer: {234 email: commit.committer.email,235 name: commit.committer.name,236 },237 message: commit.message.replace(/\n$/u, ""),238 parents: commit.parent.map((parent) => CommitSha.make(parent)),239 sha: CommitSha.make(oid),240 tree: ObjectId.make(commit.tree),241 }))242 )243 );24451 const open = (name: RepoName) =>52 Effect.gen(function* () {53 if (repos.has(name)) {54 return yield* new RepoExists({ name });55 }5657 const repo: Repo = {252 gitdir: `/${name}.git`,58 dir: { fs, gitdir: `/${name}.git` },59 lock: Semaphore.makeUnsafe(1),60 tokens: new Set(),61 };6263 repos.set(name, repo);258 yield* git(() =>259 init({ bare: true, defaultBranch: "main", fs, gitdir: repo.gitdir })260 ).pipe(Effect.orDie);64 yield* initBare(repo.dir);6566 return repo;67 });68
6 unmodified lines
75 ) =>76 Effect.gen(function* () {77 const repo = yield* open(name);78275 if (Option.isSome(tip)) {276 yield* copyCommit({ fs, gitdir: from.gitdir }, repo, tip.value);277 yield* git(() =>278 writeRef({ fs, gitdir: repo.gitdir, ref, value: tip.value })279 ).pipe(Effect.orDie);280 }79 yield* seedRef(from.dir, repo.dir, ref, tip);8081 return createdOf(name);82 });8384 return RepoHost.of({85 ...objectsAndRefs(known),86 create: (name) => open(name).pipe(Effect.as(createdOf(name))),87 // The default branch only, copied as it stands: later pushes to the base88 // or to a sibling never reach this fork.89 fork: (base, name) =>90 Effect.gen(function* () {91 const from = yield* known(base);292 const tip = yield* tipOf(from, mainRef);92 const tip = yield* tipOf(from.dir, mainRef);9394 return yield* seed(from, name, mainRef, tip);95 }),96 // Its test-only meaning of a public remote: another repo in this store,
15 unmodified lines
112 });113 }114115 const ref = `refs/heads/${source.branch ?? "main"}`;316 const tip = yield* tipOf(from, ref);116 const tip = yield* tipOf(from.dir, ref);117118 if (Option.isNone(tip)) {119 return yield* new ImportRefused({120 name,
2 unmodified lines
123 }124125 return yield* seed(from, name, ref, tip);126 }),327 log: (name, at, limit) =>328 Effect.gen(function* () {329 const repo = yield* known(name);330 const commits: Commit[] = [];331 let next = yield* resolve(repo, at);332333 while (Option.isSome(next) && commits.length < limit) {334 const commit = yield* commitAt(repo, next.value);335336 if (Option.isNone(commit)) {337 break;338 }339340 commits.push(commit.value);341 next = Option.fromNullishOr(commit.value.parents[0]);342 }343344 return commits;345 }),127 mintToken: (name, scope, ttl) =>128 Effect.gen(function* () {129 const repo = yield* known(name);130 const now = yield* DateTime.now;
10 unmodified lines
141 scope,142 secret: Redacted.make(`memory-${id}`),143 };144 }),364 push: (name, source, updates) =>365 Effect.gen(function* () {366 const repo = yield* known(name);367368 return yield* repo.lock.withPermit(369 Effect.forEach(updates, (update) => apply(repo, source, update))370 );371 }),372 // Only a blob by its own id: no tag or commit is peeled to one.373 readBlob: (name, blob) =>374 Effect.gen(function* () {375 const repo = yield* known(name);376377 const read = yield* unlessMissing(() =>378 readBlob({ fs, gitdir: repo.gitdir, oid: blob })379 );380381 return Option.flatMap(read, ({ blob: bytes, oid }) =>382 oid === blob ? Option.some(bytes) : Option.none()383 );384 }),385 readCommit: (name, sha) =>386 known(name).pipe(Effect.flatMap((repo) => commitAt(repo, sha))),387 readFile: (name, at, path) =>388 Effect.gen(function* () {389 const repo = yield* known(name);390 const sha = yield* resolve(repo, at);391392 if (Option.isNone(sha)) {393 return Option.none();394 }395396 const blob = yield* unlessMissing(() =>397 readBlob({398 filepath: path,399 fs,400 gitdir: repo.gitdir,401 oid: sha.value,402 })403 );404405 return Option.map(blob, ({ blob: bytes }) => bytes);406 }),407 // Only a tree by its own id: isomorphic-git peels a commit to its tree.408 readTree: (name, tree) =>409 Effect.gen(function* () {410 const repo = yield* known(name);411412 const read = yield* unlessMissing(() =>413 readTree({ fs, gitdir: repo.gitdir, oid: tree })414 );415416 if (Option.isNone(read) || read.value.oid !== tree) {417 return Option.none();418 }419420 const entries = yield* decodeEntries(421 read.value.tree.map((entry) => ({422 mode: entry.mode,423 name: entry.path,424 sha: entry.oid,425 type: entry.type,426 }))427 ).pipe(Effect.orDie);428429 return Option.some(entries);430 }),431 refs: (name) =>432 Effect.gen(function* () {433 const repo = yield* known(name);434435 const names = yield* git(() =>436 listRefs({ filepath: "refs", fs, gitdir: repo.gitdir })437 ).pipe(Effect.orDie);438439 const listed = yield* Effect.forEach(names, (relative) =>440 Effect.gen(function* () {441 const ref = RefName.make(`refs/${relative}`);442 const tip = yield* tipOf(repo, ref);443444 return Option.map(tip, (sha) => [ref, sha] as const);445 })446 );447448 return new Map(Array.getSomes(listed));449 }),145 remote: (name) => known(name).pipe(Effect.as(remoteOf(name))),146 remove: (name) =>147 Effect.sync(() => {148 const repo = repos.get(name);
1 unmodified line
150 if (repo === undefined) {151 return false;152 }153459 fs.removeTree(repo.gitdir);154 fs.removeTree(repo.dir.gitdir);155156 return repos.delete(name);157 }),158 revokeToken: (name, id) =>
6 unmodified lines
added:packages/artifacts/test/local.test.ts+218 added
1import { describe, expect, it } from "@effect/vitest";2import { gitClient } from "@repo/testkit/git-client";3import { Duration, Effect, Layer, Option } from "effect";45import { Fetch, FetchFailed } from "../src/fetch.ts";6import {7 BranchName,8 ImportRefused,9 RefName,10 RepoHost,11 RepoName,12} from "../src/repo-host.ts";13import { RepoHostLocal } from "../src/repo-host/local.ts";14import { memoryFs } from "../src/repo-host/memory-fs.ts";15import { describeRepoHost } from "./repo-host-contract.ts";1617const main = RefName.make("refs/heads/main");1819/** No network: every request fails as an unreachable host's would. */20const offline = Layer.succeed(21 Fetch,22 Fetch.of({23 fetch: (request) =>24 Effect.fail(new FetchFailed({ reason: "offline", url: request.url })),25 })26);2728/** The store in `root`, whose remotes are its repos' own `file://` URLs. */29const storeAt = (root: string) =>30 RepoHostLocal.layer({ remoteBase: `file://${root}`, root }).pipe(31 Layer.provide(offline)32 );3334/** A store in a new temporary directory, removed when the test ends. */35const freshStore = Layer.unwrap(36 Effect.map(RepoHostLocal.temporaryRoot, storeAt)37);3839// Its test-only meaning of a public remote: another bare repo on disk, named40// by its `file://` URL.41describeRepoHost("local", freshStore, {42 importUrl: (name) =>43 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),44});4546describe("bare repos on local disk", () => {47 it.effect("names each repo's remote under the base it was given", () =>48 Effect.gen(function* () {49 const root = yield* RepoHostLocal.temporaryRoot;50 const name = RepoName.make("demo");5152 const remote = yield* RepoHost.use((repos) =>53 Effect.andThen(repos.create(name), repos.remote(name))54 ).pipe(55 Effect.provide(56 RepoHostLocal.layer({57 remoteBase: "http://127.0.0.1:8080/git",58 root,59 }).pipe(Layer.provide(offline))60 )61 );6263 expect(remote).toBe("http://127.0.0.1:8080/git/demo.git");64 })65 );6667 it.effect(68 "keeps repos, refs and tokens for the next layer over the same root",69 () =>70 Effect.gen(function* () {71 const root = yield* RepoHostLocal.temporaryRoot;72 const client = yield* gitClient(memoryFs());73 const first = yield* client.commit("first", [["a", "1"]]);74 const name = RepoName.make("kept");7576 const minted = yield* RepoHost.use((repos) =>77 Effect.gen(function* () {78 yield* repos.create(name);79 yield* repos.push(name, client.source, [80 { from: Option.none(), ref: main, to: first },81 ]);8283 return yield* repos.mintToken(name, "write", Duration.hours(1));84 })85 ).pipe(Effect.provide(storeAt(root)));8687 const later = yield* RepoHost.use((repos) =>88 Effect.gen(function* () {89 const refs = yield* repos.refs(name);90 const revoked = yield* repos.revokeToken(name, minted.id);9192 const next = yield* repos.mintToken(93 name,94 "read",95 Duration.hours(1)96 );9798 return { next, refs, revoked };99 })100 ).pipe(Effect.provide(storeAt(root)));101102 expect(later.refs).toStrictEqual(new Map([[main, first]]));103 expect(later.revoked).toBeTruthy();104 expect(later.next.id).not.toBe(minted.id);105 expect(106 yield* RepoHost.use((repos) =>107 Effect.all([108 repos.revokeToken(name, minted.id),109 repos.revokeToken(name, later.next.id),110 ])111 ).pipe(Effect.provide(storeAt(root)))112 ).toStrictEqual([false, true]);113 })114 );115});116117describe("importing onto local disk", () => {118 it.effect("imports the branch it names, under that name", () =>119 Effect.gen(function* () {120 const repos = yield* RepoHost;121 const client = yield* gitClient(memoryFs());122 const first = yield* client.commit("first", [["a", "1"]]);123 const release = RefName.make("refs/heads/release");124 const remote = RepoName.make("branches");125 const name = RepoName.make("from-a-branch");126127 yield* repos.create(remote);128 yield* repos.push(remote, client.source, [129 { from: Option.none(), ref: release, to: first },130 ]);131132 yield* repos.importFrom(name, {133 branch: BranchName.make("release"),134 url: yield* repos.remote(remote),135 });136137 expect(yield* repos.refs(name)).toStrictEqual(138 new Map([[release, first]])139 );140 }).pipe(Effect.provide(freshStore))141 );142143 it.effect("refuses a path that holds no repo, and makes no repo", () =>144 Effect.gen(function* () {145 const repos = yield* RepoHost;146 const name = RepoName.make("nowhere");147 const url = "file:///nonexistent/demo.git";148149 expect(yield* Effect.flip(repos.importFrom(name, { url }))).toStrictEqual(150 new ImportRefused({ name, reason: `no repo at ${url}` })151 );152 expect(yield* repos.remove(name)).toBeFalsy();153 }).pipe(Effect.provide(freshStore))154 );155156 // A file URL that names another machine is no path on this one.157 it.effect("refuses a file URL on another host, and makes no repo", () =>158 Effect.gen(function* () {159 const repos = yield* RepoHost;160 const name = RepoName.make("elsewhere");161 const url = "file://example.com/demo.git";162163 expect(yield* Effect.flip(repos.importFrom(name, { url }))).toStrictEqual(164 new ImportRefused({ name, reason: `no repo at ${url}` })165 );166 expect(yield* repos.remove(name)).toBeFalsy();167 }).pipe(Effect.provide(freshStore))168 );169170 it.effect("refuses a branch the remote lacks, and makes no repo", () =>171 Effect.gen(function* () {172 const repos = yield* RepoHost;173 const remote = RepoName.make("empty-remote");174 const name = RepoName.make("from-nothing");175176 yield* repos.create(remote);177178 const url = yield* repos.remote(remote);179180 expect(181 yield* Effect.flip(182 repos.importFrom(name, { branch: BranchName.make("absent"), url })183 )184 ).toStrictEqual(185 new ImportRefused({ name, reason: `${url} has no branch absent` })186 );187 expect(yield* repos.remove(name)).toBeFalsy();188 }).pipe(Effect.provide(freshStore))189 );190191 it.effect("refuses an HTTPS remote it cannot reach, and makes no repo", () =>192 Effect.gen(function* () {193 const repos = yield* RepoHost;194 const name = RepoName.make("unreachable");195 const url = "https://example.com/demo.git";196197 expect(yield* Effect.flip(repos.importFrom(name, { url }))).toStrictEqual(198 new ImportRefused({199 name,200 reason: `${url} could not be fetched: offline`,201 })202 );203 expect(yield* repos.remove(name)).toBeFalsy();204 }).pipe(Effect.provide(freshStore))205 );206207 it.effect("refuses a remote that is neither a file nor HTTP", () =>208 Effect.gen(function* () {209 const repos = yield* RepoHost;210 const name = RepoName.make("over-ssh");211 const url = "ssh://example.com/demo.git";212213 expect(yield* Effect.flip(repos.importFrom(name, { url }))).toStrictEqual(214 new ImportRefused({ name, reason: `${url} is not a file or HTTP URL` })215 );216 }).pipe(Effect.provide(freshStore))217 );218});