Keep repos as bare git repos on local disk behind RepoHost, importing from file:// and over Fetch
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- packages/artifacts/src/repo-host/local.ts: RepoHostLocal.layer({root, remoteBase}) needs only Fetch. Each repo is <root>/<name>.git, a bare repo with default branch main, initialised by isomorphic-git over node:fs. Disk is the truth, so a second layer over the same root sees every repo, ref and token. Making the repo's directory claims its name (EEXIST -> RepoExists). remote(name) is <remoteBase>/<name>.git, so a test can serve root with git http-backend under that base. - Push is a compare-and-swap per ref under one Semaphore per repo, applying the others when one is Stale{tip} (S1 #3, #6). Fork copies refs/heads/main and its objects only. The object copies, the CAS and the reads are memory.ts's, copied with a gitdir parameter (anti-job: memory.ts is not moved or touched). - Decision: tokens.json in each repo holds {live, minted}, rewritten under the repo's lock, and ids are hashBlob("<name>\n<count>"). They look random and are deterministic, and the count lives on disk, not in a Ref, so two layers over one root never mint the same id (a per-layer Ref would, and revokeToken would then revoke the wrong one). - importFrom: file:// (this adapter's test-only public remote) copies the branch the source HEAD names, or the named branch, from any bare repo on disk. http(s):// fetches one branch with isomorphic-git through the layer's Fetch, via a remote the repo has only while the fetch runs (isomorphic-git needs its refspec), then drops the remote and its tracking refs. A failed import removes the repo it made. Reasons match /memory's ("no repo at <url>", "<url> has no branch <b>"). isomorphic-git sends request bodies as arrays of chunks despite its typings, so the HTTP bridge takes either kind of iterable. - RepoHostLocal.temporaryRoot (beyond the Interface): a scoped temp directory, because artifacts' tests have no FileSystem layer (no @effect/platform-node dev dependency); local.ts is the one file allowed node:fs. - Tests: test/local.test.ts runs describeRepoHost("local", ...) over a fresh temporary root per case, with file:// remotes so the shared import cases run; plus remote() under a given base, persistence of repos, refs and tokens across layers, a named-branch import, and refusals (no repo at a path, absent branch, unreachable HTTPS through an offline Fetch, an ssh:// URL), each making no repo. 21 tests; red first against a stub whose methods fail RepoNotFound. - Not landed (outside the territory, in the issue's Comments): the it.live real-git clone through @repo/testkit/http-backend needs @effect/platform-node in artifacts' devDependencies and effect/http in artifacts' test override. A throwaway run from packages/git/test (deleted) passed it, plus a real push read back through the port, git fsck --strict, and HTTPS imports of a default (trunk) and a named branch over a Fetch answered by http-backend. - ASSUMPTION: an imported repo keeps HEAD on main whatever branch it holds, as /memory does; Artifacts' behaviour here was not read.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+1012 added−0 removed
- tests:+204 added−0 removed
- other:+808 added−0 removed
Provenance
- Commit
05f24eb- Tree
429abca- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
3d5870c
2 files changed+1012 added−0 removed
added:packages/artifacts/src/repo-host/local.ts+808 added
1+import * as fs from "node:fs";2+import { tmpdir } from "node:os";3+import { fileURLToPath } from "node:url";4+5+import { CommitSha } from "@repo/protocol/ids";6+import {7+ Array,8+ Data,9+ DateTime,10+ Effect,11+ Equal,12+ Layer,13+ Match,14+ Option,15+ Redacted,16+ Schema,17+ Semaphore,18+ Stream,19+} from "effect";20+import type { Context, Scope } from "effect";21+import {22+ Errors,23+ addRemote,24+ currentBranch,25+ deleteRemote,26+ fetch as fetchPack,27+ hashBlob,28+ init,29+ listRefs,30+ readBlob,31+ readCommit,32+ readTree,33+ resolveRef,34+ writeBlob,35+ writeCommit,36+ writeRef,37+ writeTree,38+} from "isomorphic-git";39+import type {40+ GitHttpRequest,41+ GitHttpResponse,42+ HttpClient,43+} from "isomorphic-git";44+45+import { Fetch, FetchFailed } from "../fetch.ts";46+import {47+ ImportRefused,48+ ObjectId,49+ RefName,50+ RefOutcome,51+ RepoExists,52+ RepoHost,53+ RepoNotFound,54+ Revision,55+ TreeEntry,56+} from "../repo-host.ts";57+import type {58+ BranchName,59+ Commit,60+ PushSource,61+ RefUpdate,62+ RepoCreated,63+ RepoName,64+} from "../repo-host.ts";65+66+/** A promise from isomorphic-git or the file system that rejected. */67+class IoFailure extends Data.TaggedError("IoFailure")<{68+ readonly cause: unknown;69+}> {}70+71+const io = <A>(run: () => Promise<A>) =>72+ Effect.tryPromise({ catch: (cause) => new IoFailure({ cause }), try: run });73+74+/** Whether a file-system call failed with node's error `code`. */75+const failedWith = (code: "EEXIST" | "ENOENT") => (failure: IoFailure) =>76+ failure.cause instanceof Error &&77+ "code" in failure.cause &&78+ failure.cause.code === code;79+80+/** `None` where isomorphic-git finds no such object, ref or file. */81+const unlessMissing = <A>(82+ run: () => Promise<A>83+): Effect.Effect<Option.Option<A>> =>84+ io(run).pipe(85+ Effect.asSome,86+ Effect.catchIf(87+ (failure) =>88+ failure.cause instanceof Errors.NotFoundError ||89+ failure.cause instanceof Errors.ObjectTypeError,90+ () => Effect.succeedNone91+ ),92+ Effect.orDie93+ );94+95+/** Whether anything is at `path`. */96+const exists = (path: string) =>97+ io(() => fs.promises.stat(path)).pipe(98+ Effect.as(true),99+ Effect.catchIf(failedWith("ENOENT"), () => Effect.succeed(false)),100+ Effect.orDie101+ );102+103+/** Deletes `path` and everything under it; whether there was anything. */104+const removeAll = (path: string) =>105+ Effect.gen(function* () {106+ const found = yield* exists(path);107+108+ yield* io(() =>109+ fs.promises.rm(path, { force: true, recursive: true })110+ ).pipe(Effect.orDie);111+112+ return found;113+ });114+115+// Each object is rewritten from its parsed form; a changed id would mean the116+// copy is not the object the pusher sent.117+const keep = (oid: string, write: () => Promise<string>) =>118+ io(write).pipe(119+ Effect.orDie,120+ Effect.flatMap((written) =>121+ written === oid122+ ? Effect.void123+ : Effect.die(`copying ${oid} produced ${written}`)124+ )125+ );126+127+const mainRef = "refs/heads/main";128+129+/** The remote an HTTP import fetches through, removed once it has. */130+const importRemote = "import";131+132+const branchOf = (ref: string) => ref.replace(/^refs\/heads\//u, "");133+134+const tipOf = (gitdir: string, ref: string) =>135+ unlessMissing(() => resolveRef({ fs, gitdir, ref })).pipe(136+ Effect.map(Option.map((sha) => CommitSha.make(sha)))137+ );138+139+// The copies write children before parents, so every object in a repo has140+// everything it points to.141+const copyBlob = (source: PushSource, gitdir: string, oid: string) =>142+ Effect.gen(function* () {143+ const present = yield* unlessMissing(() => readBlob({ fs, gitdir, oid }));144+145+ if (Option.isSome(present)) {146+ return;147+ }148+149+ const { blob } = yield* io(() => readBlob({ ...source, oid })).pipe(150+ Effect.orDie151+ );152+153+ yield* keep(oid, () => writeBlob({ blob, fs, gitdir }));154+ });155+156+const copyTree = (157+ source: PushSource,158+ gitdir: string,159+ oid: string160+): Effect.Effect<void> =>161+ Effect.gen(function* () {162+ const present = yield* unlessMissing(() => readTree({ fs, gitdir, oid }));163+164+ if (Option.isSome(present)) {165+ return;166+ }167+168+ const { tree } = yield* io(() => readTree({ ...source, oid })).pipe(169+ Effect.orDie170+ );171+172+ // Submodule entries ("commit") point outside the repo; git copies none.173+ yield* Effect.forEach(tree, (entry) =>174+ Match.value(entry.type).pipe(175+ Match.when("blob", () => copyBlob(source, gitdir, entry.oid)),176+ Match.when("tree", () => copyTree(source, gitdir, entry.oid)),177+ Match.when("commit", () => Effect.void),178+ Match.exhaustive179+ )180+ );181+ yield* keep(oid, () => writeTree({ fs, gitdir, tree }));182+ });183+184+const copyCommit = (185+ source: PushSource,186+ gitdir: string,187+ oid: string188+): Effect.Effect<void> =>189+ Effect.gen(function* () {190+ const present = yield* unlessMissing(() => readCommit({ fs, gitdir, oid }));191+192+ if (Option.isSome(present)) {193+ return;194+ }195+196+ const { commit } = yield* io(() => readCommit({ ...source, oid })).pipe(197+ Effect.orDie198+ );199+200+ yield* copyTree(source, gitdir, commit.tree);201+ yield* Effect.forEach(commit.parent, (parent) =>202+ copyCommit(source, gitdir, parent)203+ );204+ yield* keep(oid, () => writeCommit({ commit, fs, gitdir }));205+ });206+207+// S1 #3 and #6: each ref is its own compare-and-swap, applied or refused208+// whatever the others in the same push come to.209+const apply = (gitdir: string, source: PushSource, update: RefUpdate) =>210+ Effect.gen(function* () {211+ const tip = yield* tipOf(gitdir, update.ref);212+213+ if (!Equal.equals(tip, update.from)) {214+ return RefOutcome.Stale({ ref: update.ref, tip });215+ }216+217+ yield* copyCommit(source, gitdir, update.to);218+ yield* io(() =>219+ writeRef({ force: true, fs, gitdir, ref: update.ref, value: update.to })220+ ).pipe(Effect.orDie);221+222+ return RefOutcome.Updated({ ref: update.ref });223+ });224+225+const resolve = (gitdir: string, at: Revision) =>226+ Revision.$match(at, {227+ Branch: ({ name }) => tipOf(gitdir, `refs/heads/${name}`),228+ Commit: ({ sha }) => Effect.succeedSome(sha),229+ });230+231+// Artifacts drops one trailing newline from a commit message.232+const commitAt = (gitdir: string, sha: CommitSha) =>233+ unlessMissing(() => readCommit({ fs, gitdir, oid: sha })).pipe(234+ Effect.map(235+ Option.map(({ commit, oid }): Commit => ({236+ author: { email: commit.author.email, name: commit.author.name },237+ committer: {238+ email: commit.committer.email,239+ name: commit.committer.name,240+ },241+ message: commit.message.replace(/\n$/u, ""),242+ parents: commit.parent.map((parent) => CommitSha.make(parent)),243+ sha: CommitSha.make(oid),244+ tree: ObjectId.make(commit.tree),245+ }))246+ )247+ );248+249+// isomorphic-git's entries carry `path` and `oid`; the port's, `name` and `sha`.250+const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));251+252+/**253+ * The tokens a repo has minted, kept beside its objects so that every layer254+ * over the same root sees them. `minted` counts every token ever minted, so255+ * no two get the same id.256+ */257+const Tokens = Schema.fromJsonString(258+ Schema.Struct({ live: Schema.Array(Schema.String), minted: Schema.Int })259+);260+261+type Tokens = typeof Tokens.Type;262+263+const noTokens: Tokens = { live: [], minted: 0 };264+265+const concat = (chunks: readonly Uint8Array[]) => {266+ const all = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));267+ let at = 0;268+269+ for (const chunk of chunks) {270+ all.set(chunk, at);271+ at += chunk.length;272+ }273+274+ return all;275+};276+277+/**278+ * A request body as one array. isomorphic-git types it as an async iterator279+ * but sends an array of chunks, so this takes either.280+ */281+const bytesOf = (body: AsyncIterable<Uint8Array> | Iterable<Uint8Array>) =>282+ (Symbol.asyncIterator in body283+ ? Stream.fromAsyncIterable(body, (cause) => new IoFailure({ cause }))284+ : Stream.fromIterable(body)285+ ).pipe(Stream.runCollect, Effect.map(concat));286+287+/** One chunk as the async iterator isomorphic-git reads a response body from. */288+const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {289+ const chunks = [bytes];290+291+ const iterator: AsyncIterableIterator<Uint8Array> = {292+ [Symbol.asyncIterator]: () => iterator,293+ next: () => {294+ const chunk = chunks.shift();295+296+ return Promise.resolve(297+ chunk === undefined298+ ? { done: true, value: undefined }299+ : { done: false, value: chunk }300+ );301+ },302+ };303+304+ return iterator;305+};306+307+/**308+ * isomorphic-git's HTTP client over a `Fetch`. isomorphic-git awaits a309+ * promise, so each exchange runs as one; a `Fetch` failure rejects it as is.310+ */311+const httpOver = (312+ fetch: Fetch["Service"]["fetch"],313+ context: Context.Context<never>314+): HttpClient => ({315+ request: (request: GitHttpRequest) =>316+ Effect.runPromiseWith(context)(317+ Effect.gen(function* () {318+ const body =319+ request.body === undefined320+ ? {}321+ : { body: yield* bytesOf(request.body) };322+323+ const response = yield* fetch(324+ new Request(request.url, {325+ ...body,326+ headers: request.headers ?? {},327+ method: request.method ?? "GET",328+ })329+ );330+331+ const bytes = yield* io(() => response.arrayBuffer());332+333+ return {334+ body: once(new Uint8Array(bytes)),335+ headers: Object.fromEntries(response.headers.entries()),336+ method: request.method,337+ statusCode: response.status,338+ statusMessage: response.statusText,339+ url: response.url === "" ? request.url : response.url,340+ } satisfies GitHttpResponse;341+ })342+ ),343+});344+345+/** Why a fetch from `url` brought nothing to import. */346+const fetchRefusal = (url: string, cause: unknown) =>347+ Match.value(cause).pipe(348+ Match.when(Schema.is(FetchFailed), (failed) => failed.reason),349+ Match.when(Match.instanceOf(Error), (thrown) => thrown.message),350+ Match.orElse(() => "no reason given"),351+ (reason) => `${url} could not be fetched: ${reason}`352+ );353+354+const make = (options: {355+ readonly root: string;356+ readonly remoteBase: string;357+}) =>358+ Effect.gen(function* () {359+ const root = options.root.replace(/\/+$/u, "");360+ const remoteBase = options.remoteBase.replace(/\/+$/u, "");361+ const http = httpOver((yield* Fetch).fetch, yield* Effect.context());362+ const locks = new Map<RepoName, Semaphore.Semaphore>();363+364+ yield* io(() => fs.promises.mkdir(root, { recursive: true })).pipe(365+ Effect.orDie366+ );367+368+ const gitdirOf = (name: RepoName) => `${root}/${name}.git`;369+370+ const createdOf = (name: RepoName): RepoCreated => ({371+ name,372+ remote: `${remoteBase}/${name}.git`,373+ });374+375+ const lockOf = (name: RepoName) =>376+ Effect.sync(() => {377+ const found = locks.get(name);378+379+ if (found !== undefined) {380+ return found;381+ }382+383+ const lock = Semaphore.makeUnsafe(1);384+385+ locks.set(name, lock);386+387+ return lock;388+ });389+390+ /** The repo's git directory, if the repo exists. */391+ const known = (name: RepoName): Effect.Effect<string, RepoNotFound> =>392+ Effect.flatMap(exists(gitdirOf(name)), (found) =>393+ found394+ ? Effect.succeed(gitdirOf(name))395+ : Effect.fail(new RepoNotFound({ name }))396+ );397+398+ /** A new, empty bare repo; making its directory is what claims the name. */399+ const open = (name: RepoName) =>400+ Effect.gen(function* () {401+ const gitdir = gitdirOf(name);402+403+ const made = yield* io(() => fs.promises.mkdir(gitdir)).pipe(404+ Effect.as(true),405+ Effect.catchIf(failedWith("EEXIST"), () => Effect.succeed(false)),406+ Effect.orDie407+ );408+409+ if (!made) {410+ return yield* new RepoExists({ name });411+ }412+413+ yield* io(() =>414+ init({ bare: true, defaultBranch: "main", fs, gitdir })415+ ).pipe(Effect.orDie);416+417+ return gitdir;418+ });419+420+ /** A new repo `name` holding `source`'s `ref` at `tip`, copied as it stands. */421+ const seed = (422+ name: RepoName,423+ source: PushSource,424+ ref: string,425+ tip: Option.Option<CommitSha>426+ ) =>427+ Effect.gen(function* () {428+ const gitdir = yield* open(name);429+430+ if (Option.isSome(tip)) {431+ yield* copyCommit(source, gitdir, tip.value);432+ yield* io(() => writeRef({ fs, gitdir, ref, value: tip.value })).pipe(433+ Effect.orDie434+ );435+ }436+437+ return createdOf(name);438+ });439+440+ // Local disk's test-only meaning of a public remote: a bare repo on this441+ // machine, copied object by object. Without a branch, it takes the one442+ // the repo's HEAD names.443+ const importFile = (444+ name: RepoName,445+ url: string,446+ branch: BranchName | undefined447+ ) =>448+ Effect.gen(function* () {449+ const gitdir = fileURLToPath(url);450+451+ const head = yield* unlessMissing(() =>452+ currentBranch({ fs, fullname: true, gitdir })453+ );454+455+ if (Option.isNone(head)) {456+ return yield* new ImportRefused({457+ name,458+ reason: `no repo at ${url}`,459+ });460+ }461+462+ // A detached HEAD names no branch to take.463+ const ref = branch === undefined ? head.value : `refs/heads/${branch}`;464+465+ if (ref === undefined) {466+ return yield* new ImportRefused({467+ name,468+ reason: `${url} has no default branch`,469+ });470+ }471+472+ const tip = yield* tipOf(gitdir, ref);473+474+ if (Option.isNone(tip)) {475+ return yield* new ImportRefused({476+ name,477+ reason: `${url} has no branch ${branchOf(ref)}`,478+ });479+ }480+481+ return yield* seed(name, { fs, gitdir }, ref, tip);482+ });483+484+ /** One branch of a smart-HTTP remote, fetched into the empty repo `gitdir`. */485+ const fetchInto = (486+ name: RepoName,487+ gitdir: string,488+ url: string,489+ branch: BranchName | undefined490+ ) =>491+ Effect.gen(function* () {492+ // isomorphic-git's fetch files what it got under a configured remote's493+ // refspec, so the repo has one for as long as the fetch runs.494+ yield* io(() =>495+ addRemote({ fs, gitdir, remote: importRemote, url })496+ ).pipe(Effect.orDie);497+498+ const fetched = yield* io(() =>499+ fetchPack({500+ fs,501+ gitdir,502+ http,503+ remote: importRemote,504+ remoteRef: branch === undefined ? "HEAD" : `refs/heads/${branch}`,505+ singleBranch: true,506+ tags: false,507+ })508+ ).pipe(509+ Effect.mapError(510+ (failure) =>511+ new ImportRefused({512+ name,513+ reason:514+ failure.cause instanceof Errors.NotFoundError515+ ? `${url} has no branch ${branch ?? "HEAD"}`516+ : fetchRefusal(url, failure.cause),517+ })518+ )519+ );520+521+ const ref =522+ branch === undefined ? fetched.defaultBranch : `refs/heads/${branch}`;523+524+ const tip = fetched.fetchHead;525+526+ if (tip === null || ref === null) {527+ return yield* new ImportRefused({528+ name,529+ reason: `${url} has no default branch`,530+ });531+ }532+533+ yield* io(() => writeRef({ fs, gitdir, ref, value: tip })).pipe(534+ Effect.orDie535+ );536+ // No repo here has remotes or remote-tracking refs.537+ yield* io(() =>538+ deleteRemote({ fs, gitdir, remote: importRemote })539+ ).pipe(Effect.orDie);540+ yield* removeAll(`${gitdir}/refs/remotes`);541+542+ return createdOf(name);543+ });544+545+ // A public remote over smart HTTP, through the `Fetch` this layer was546+ // given. A failed import leaves no repo behind.547+ const importHttp = (548+ name: RepoName,549+ url: string,550+ branch: BranchName | undefined551+ ) =>552+ Effect.flatMap(open(name), (gitdir) =>553+ fetchInto(name, gitdir, url, branch).pipe(554+ Effect.onError(() => removeAll(gitdir).pipe(Effect.asVoid))555+ )556+ );557+558+ /** The repo's tokens file, read and rewritten under the repo's lock. */559+ const updateTokens = <A>(560+ name: RepoName,561+ change: (tokens: Tokens) => Effect.Effect<readonly [A, Tokens]>562+ ) =>563+ Effect.gen(function* () {564+ const gitdir = yield* known(name);565+ const path = `${gitdir}/tokens.json`;566+ const lock = yield* lockOf(name);567+568+ return yield* lock.withPermit(569+ Effect.gen(function* () {570+ const text = yield* io(() =>571+ fs.promises.readFile(path, "utf-8")572+ ).pipe(573+ Effect.asSome,574+ Effect.catchIf(failedWith("ENOENT"), () => Effect.succeedNone),575+ Effect.orDie576+ );577+578+ const stored = Option.isNone(text)579+ ? noTokens580+ : yield* Schema.decodeEffect(Tokens)(text.value).pipe(581+ Effect.orDie582+ );583+584+ const [result, next] = yield* change(stored);585+586+ const written = yield* Schema.encodeEffect(Tokens)(next).pipe(587+ Effect.orDie588+ );589+590+ yield* io(() => fs.promises.writeFile(path, written)).pipe(591+ Effect.orDie592+ );593+594+ return result;595+ })596+ );597+ });598+599+ return RepoHost.of({600+ create: (name) => open(name).pipe(Effect.as(createdOf(name))),601+ // The default branch only, copied as it stands: later pushes to the base602+ // or to a sibling never reach this fork.603+ fork: (base, name) =>604+ Effect.gen(function* () {605+ const from = yield* known(base);606+ const tip = yield* tipOf(from, mainRef);607+608+ return yield* seed(name, { fs, gitdir: from }, mainRef, tip);609+ }),610+ importFrom: (name, source) =>611+ Effect.gen(function* () {612+ if (yield* exists(gitdirOf(name))) {613+ return yield* new RepoExists({ name });614+ }615+616+ const scheme = URL.canParse(source.url)617+ ? new URL(source.url).protocol618+ : "";619+620+ return yield* Match.value(scheme).pipe(621+ Match.when("file:", () =>622+ importFile(name, source.url, source.branch)623+ ),624+ Match.whenOr("http:", "https:", () =>625+ importHttp(name, source.url, source.branch)626+ ),627+ Match.orElse(() =>628+ Effect.fail(629+ new ImportRefused({630+ name,631+ reason: `${source.url} is not a file or HTTP URL`,632+ })633+ )634+ )635+ );636+ }),637+ log: (name, at, limit) =>638+ Effect.gen(function* () {639+ const gitdir = yield* known(name);640+ const commits: Commit[] = [];641+ let next = yield* resolve(gitdir, at);642+643+ while (Option.isSome(next) && commits.length < limit) {644+ const commit = yield* commitAt(gitdir, next.value);645+646+ if (Option.isNone(commit)) {647+ break;648+ }649+650+ commits.push(commit.value);651+ next = Option.fromNullishOr(commit.value.parents[0]);652+ }653+654+ return commits;655+ }),656+ // An id that looks random but is the same for the same repo and count.657+ mintToken: (name, scope, ttl) =>658+ Effect.gen(function* () {659+ const now = yield* DateTime.now;660+661+ const id = yield* updateTokens(name, (tokens) =>662+ Effect.gen(function* () {663+ const minted = tokens.minted + 1;664+665+ const { oid } = yield* io(() =>666+ hashBlob({ object: `${name}\n${minted}` })667+ ).pipe(Effect.orDie);668+669+ return [oid, { live: [...tokens.live, oid], minted }] as const;670+ })671+ );672+673+ return {674+ expiresAt: DateTime.addDuration(now, ttl),675+ id,676+ scope,677+ secret: Redacted.make(`local-${id}`),678+ };679+ }),680+ push: (name, source, updates) =>681+ Effect.gen(function* () {682+ const gitdir = yield* known(name);683+ const lock = yield* lockOf(name);684+685+ return yield* lock.withPermit(686+ Effect.forEach(updates, (update) => apply(gitdir, source, update))687+ );688+ }),689+ // Only a blob by its own id: no tag or commit is peeled to one.690+ readBlob: (name, blob) =>691+ Effect.gen(function* () {692+ const gitdir = yield* known(name);693+694+ const read = yield* unlessMissing(() =>695+ readBlob({ fs, gitdir, oid: blob })696+ );697+698+ return Option.flatMap(read, ({ blob: bytes, oid }) =>699+ oid === blob ? Option.some(bytes) : Option.none()700+ );701+ }),702+ readCommit: (name, sha) =>703+ known(name).pipe(Effect.flatMap((gitdir) => commitAt(gitdir, sha))),704+ readFile: (name, at, path) =>705+ Effect.gen(function* () {706+ const gitdir = yield* known(name);707+ const sha = yield* resolve(gitdir, at);708+709+ if (Option.isNone(sha)) {710+ return Option.none();711+ }712+713+ const blob = yield* unlessMissing(() =>714+ readBlob({ filepath: path, fs, gitdir, oid: sha.value })715+ );716+717+ return Option.map(blob, ({ blob: bytes }) => bytes);718+ }),719+ // Only a tree by its own id: isomorphic-git peels a commit to its tree.720+ readTree: (name, tree) =>721+ Effect.gen(function* () {722+ const gitdir = yield* known(name);723+724+ const read = yield* unlessMissing(() =>725+ readTree({ fs, gitdir, oid: tree })726+ );727+728+ if (Option.isNone(read) || read.value.oid !== tree) {729+ return Option.none();730+ }731+732+ const entries = yield* decodeEntries(733+ read.value.tree.map((entry) => ({734+ mode: entry.mode,735+ name: entry.path,736+ sha: entry.oid,737+ type: entry.type,738+ }))739+ ).pipe(Effect.orDie);740+741+ return Option.some(entries);742+ }),743+ refs: (name) =>744+ Effect.gen(function* () {745+ const gitdir = yield* known(name);746+747+ const names = yield* io(() =>748+ listRefs({ filepath: "refs", fs, gitdir })749+ ).pipe(Effect.orDie);750+751+ const listed = yield* Effect.forEach(names, (relative) =>752+ Effect.gen(function* () {753+ const ref = RefName.make(`refs/${relative}`);754+ const tip = yield* tipOf(gitdir, ref);755+756+ return Option.map(tip, (sha) => [ref, sha] as const);757+ })758+ );759+760+ return new Map(Array.getSomes(listed));761+ }),762+ remote: (name) => known(name).pipe(Effect.as(createdOf(name).remote)),763+ remove: (name) => removeAll(gitdirOf(name)),764+ revokeToken: (name, id) =>765+ updateTokens(name, (tokens) =>766+ Effect.succeed(767+ tokens.live.includes(id)768+ ? ([769+ true,770+ {771+ ...tokens,772+ live: tokens.live.filter((live) => live !== id),773+ },774+ ] as const)775+ : ([false, tokens] as const)776+ )777+ ),778+ });779+ });780+781+/**782+ * Artifacts on local disk, for tests that need real git over HTTP and for the783+ * CLI's dev mode: each repo a bare git repo `<root>/<name>.git` with default784+ * branch `main`, kept across layers over the same root. A push is a785+ * compare-and-swap per ref with no atomicity across refs, as S1 found786+ * Artifacts. `remote(name)` is `<remoteBase>/<name>.git`, so a test can serve787+ * `root` with `git http-backend` under that base and drive real git at it.788+ * Tokens are recorded, never checked.789+ */790+export const RepoHostLocal = {791+ layer: (options: {792+ readonly root: string;793+ readonly remoteBase: string;794+ }): Layer.Layer<RepoHost, never, Fetch> =>795+ Layer.effect(RepoHost, make(options)),796+ /**797+ * A new, empty directory for a store, deleted with everything in it when798+ * the scope closes: a root for callers with no file system of their own,799+ * such as this package's tests.800+ */801+ temporaryRoot: Effect.acquireRelease(802+ io(() => fs.promises.mkdtemp(`${tmpdir()}/repo-host-`)).pipe(Effect.orDie),803+ (root) =>804+ io(() => fs.promises.rm(root, { force: true, recursive: true })).pipe(805+ Effect.orDie806+ )807+ ) satisfies Effect.Effect<string, never, Scope.Scope>,808+};added:packages/artifacts/test/local.test.ts+204 added
1+import { describe, expect, it } from "@effect/vitest";2+import { gitClient } from "@repo/testkit/git-client";3+import { Duration, Effect, Layer, Option } from "effect";4+5+import { Fetch, FetchFailed } from "../src/fetch.ts";6+import {7+ BranchName,8+ ImportRefused,9+ RefName,10+ RepoHost,11+ RepoName,12+} from "../src/repo-host.ts";13+import { RepoHostLocal } from "../src/repo-host/local.ts";14+import { memoryFs } from "../src/repo-host/memory-fs.ts";15+import { describeRepoHost } from "./repo-host-contract.ts";16+17+const main = RefName.make("refs/heads/main");18+19+/** No network: every request fails as an unreachable host's would. */20+const offline = Layer.succeed(21+ Fetch,22+ Fetch.of({23+ fetch: (request) =>24+ Effect.fail(new FetchFailed({ reason: "offline", url: request.url })),25+ })26+);27+28+/** The store in `root`, whose remotes are its repos' own `file://` URLs. */29+const storeAt = (root: string) =>30+ RepoHostLocal.layer({ remoteBase: `file://${root}`, root }).pipe(31+ Layer.provide(offline)32+ );33+34+/** A store in a new temporary directory, removed when the test ends. */35+const freshStore = Layer.unwrap(36+ Effect.map(RepoHostLocal.temporaryRoot, storeAt)37+);38+39+// Its test-only meaning of a public remote: another bare repo on disk, named40+// by its `file://` URL.41+describeRepoHost("local", freshStore, {42+ importUrl: (name) =>43+ RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),44+});45+46+describe("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");51+52+ 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+ );62+63+ expect(remote).toBe("http://127.0.0.1:8080/git/demo.git");64+ })65+ );66+67+ 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");75+76+ 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+ ]);82+83+ return yield* repos.mintToken(name, "write", Duration.hours(1));84+ })85+ ).pipe(Effect.provide(storeAt(root)));86+87+ 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);91+92+ const next = yield* repos.mintToken(93+ name,94+ "read",95+ Duration.hours(1)96+ );97+98+ return { next, refs, revoked };99+ })100+ ).pipe(Effect.provide(storeAt(root)));101+102+ 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+});116+117+describe("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");126+127+ yield* repos.create(remote);128+ yield* repos.push(remote, client.source, [129+ { from: Option.none(), ref: release, to: first },130+ ]);131+132+ yield* repos.importFrom(name, {133+ branch: BranchName.make("release"),134+ url: yield* repos.remote(remote),135+ });136+137+ expect(yield* repos.refs(name)).toStrictEqual(138+ new Map([[release, first]])139+ );140+ }).pipe(Effect.provide(freshStore))141+ );142+143+ 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";148+149+ 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+ );155+156+ it.effect("refuses a branch the remote lacks, and makes no repo", () =>157+ Effect.gen(function* () {158+ const repos = yield* RepoHost;159+ const remote = RepoName.make("empty-remote");160+ const name = RepoName.make("from-nothing");161+162+ yield* repos.create(remote);163+164+ const url = yield* repos.remote(remote);165+166+ expect(167+ yield* Effect.flip(168+ repos.importFrom(name, { branch: BranchName.make("absent"), url })169+ )170+ ).toStrictEqual(171+ new ImportRefused({ name, reason: `${url} has no branch absent` })172+ );173+ expect(yield* repos.remove(name)).toBeFalsy();174+ }).pipe(Effect.provide(freshStore))175+ );176+177+ it.effect("refuses an HTTPS remote it cannot reach, and makes no repo", () =>178+ Effect.gen(function* () {179+ const repos = yield* RepoHost;180+ const name = RepoName.make("unreachable");181+ const url = "https://example.com/demo.git";182+183+ expect(yield* Effect.flip(repos.importFrom(name, { url }))).toStrictEqual(184+ new ImportRefused({185+ name,186+ reason: `${url} could not be fetched: offline`,187+ })188+ );189+ expect(yield* repos.remove(name)).toBeFalsy();190+ }).pipe(Effect.provide(freshStore))191+ );192+193+ it.effect("refuses a remote that is neither a file nor HTTP", () =>194+ Effect.gen(function* () {195+ const repos = yield* RepoHost;196+ const name = RepoName.make("over-ssh");197+ const url = "ssh://example.com/demo.git";198+199+ expect(yield* Effect.flip(repos.importFrom(name, { url }))).toStrictEqual(200+ new ImportRefused({ name, reason: `${url} is not a file or HTTP URL` })201+ );202+ }).pipe(Effect.provide(freshStore))203+ );204+});