Skip to content
Myr

Share one isomorphic-git store between the memory and local RepoHosts, and refuse a file URL on another host

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

- Review of 208. local.ts had copied about 200 lines from memory.ts (the object copies, the per-ref CAS, tipOf, resolve, commitAt and the read, log and refs bodies), well past the "small CAS loop" the anti-job allows copying. They now live once in src/repo-host/isogit-store.ts, the file the anti-job names: objectsAndRefs(known) gives log, push, readBlob, readCommit, readFile, readTree and refs over any store that finds a repo's {dir, lock} by name, plus initBare, seedRef, tipOf, unlessMissing and mainRef. Both adapters spread it into RepoHost.of. - memory.ts keeps its behaviour: the same calls in the same order, its Repo now holding a GitDir in place of a bare gitdir string. test/memory.test.ts and the contract suite are untouched and green. - importFrom of a file:// URL naming another host (file://example.com/…) died with node's TypeError from fileURLToPath; it is now ImportRefused{"no repo at <url>"} and makes no repo. - Tests: local.test.ts gains "refuses a file URL on another host, and makes no repo" (red first: the TypeError defect). - Checked again, not committed: from a throwaway test in packages/git/test (deleted), a real git clone of remote("demo") served by @repo/testkit/http-backend checks out the pushed file, a real push back reads through the port, git fsck --strict is clean on a stored, a forked and an HTTPS-imported repo, and the import keeps a non-main default branch under its own name. - Left for 299 (root files): @effect/platform-node in artifacts' devDependencies and effect/http in artifacts' test override, then the it.live clone case from the issue's Comments.

authored by oscabriel · committed by oscabriel · parent 05f24eb · Browse files · 4 files+414 added−628 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+414 added−628 removed

  • tests:+14 added−0 removed
  • other:+400 added−628 removed

4 files+414 added−628 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});
modified:packages/artifacts/src/repo-host/local.ts+48 added-304 removed
1import * as fs from "node:fs";2import { tmpdir } from "node:os";3import { fileURLToPath } from "node:url";45import { CommitSha } from "@repo/protocol/ids";5import type { CommitSha } from "@repo/protocol/ids";6import {7 Array,7 Data,8 DateTime,9 Effect,11 Equal,10 Layer,11 Match,12 Option,13 Redacted,
8 unmodified lines
22 currentBranch,23 deleteRemote,24 fetch as fetchPack,25 hashBlob,28 init,29 listRefs,30 readBlob,31 readCommit,32 readTree,33 resolveRef,34 writeBlob,35 writeCommit,26 writeRef,37 writeTree,27} from "isomorphic-git";28import type {29 GitHttpRequest,30 GitHttpResponse,
2 unmodified lines
3334import { Fetch, FetchFailed } from "../fetch.ts";35import {36 ImportRefused,48 ObjectId,49 RefName,50 RefOutcome,37 RepoExists,38 RepoHost,39 RepoNotFound,54 Revision,55 TreeEntry,40} from "../repo-host.ts";41import type {42 BranchName,59 Commit,43 PushSource,61 RefUpdate,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;
7 unmodified lines
67 failure.cause instanceof Error &&68 "code" in failure.cause &&69 failure.cause.code === code;7080/** `None` where isomorphic-git finds no such object, ref or file. */81const 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 );9471/** Whether anything is at `path`. */72const exists = (path: string) =>73 io(() => fs.promises.stat(path)).pipe(74 Effect.as(true),
12 unmodified lines
8788 return found;89 });90115// Each object is rewritten from its parsed form; a changed id would mean the116// copy is not the object the pusher sent.117const 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 );126127const mainRef = "refs/heads/main";12891/** The remote an HTTP import fetches through, removed once it has. */92const importRemote = "import";9394const branchOf = (ref: string) => ref.replace(/^refs\/heads\//u, "");95134const tipOf = (gitdir: string, ref: string) =>135 unlessMissing(() => resolveRef({ fs, gitdir, ref })).pipe(136 Effect.map(Option.map((sha) => CommitSha.make(sha)))137 );138139// The copies write children before parents, so every object in a repo has140// everything it points to.141const copyBlob = (source: PushSource, gitdir: string, oid: string) =>142 Effect.gen(function* () {143 const present = yield* unlessMissing(() => readBlob({ fs, gitdir, oid }));144145 if (Option.isSome(present)) {146 return;147 }148149 const { blob } = yield* io(() => readBlob({ ...source, oid })).pipe(150 Effect.orDie151 );152153 yield* keep(oid, () => writeBlob({ blob, fs, gitdir }));154 });155156const 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 }));163164 if (Option.isSome(present)) {165 return;166 }167168 const { tree } = yield* io(() => readTree({ ...source, oid })).pipe(169 Effect.orDie170 );171172 // 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 });183184const 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 }));191192 if (Option.isSome(present)) {193 return;194 }195196 const { commit } = yield* io(() => readCommit({ ...source, oid })).pipe(197 Effect.orDie198 );199200 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 });206207// S1 #3 and #6: each ref is its own compare-and-swap, applied or refused208// whatever the others in the same push come to.209const apply = (gitdir: string, source: PushSource, update: RefUpdate) =>210 Effect.gen(function* () {211 const tip = yield* tipOf(gitdir, update.ref);212213 if (!Equal.equals(tip, update.from)) {214 return RefOutcome.Stale({ ref: update.ref, tip });215 }216217 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);221222 return RefOutcome.Updated({ ref: update.ref });223 });224225const resolve = (gitdir: string, at: Revision) =>226 Revision.$match(at, {227 Branch: ({ name }) => tipOf(gitdir, `refs/heads/${name}`),228 Commit: ({ sha }) => Effect.succeedSome(sha),229 });230231// Artifacts drops one trailing newline from a commit message.232const 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 );248249// isomorphic-git's entries carry `path` and `oid`; the port's, `name` and `sha`.250const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));25196/**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.
108 unmodified lines
208 yield* io(() => fs.promises.mkdir(root, { recursive: true })).pipe(209 Effect.orDie210 );211368 const gitdirOf = (name: RepoName) => `${root}/${name}.git`;212 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`,
13 unmodified lines
233234 return lock;235 });236390 /** 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 );237 /** 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* () {401 const gitdir = gitdirOf(name);252 const dir = dirOf(name);253403 const made = yield* io(() => fs.promises.mkdir(gitdir)).pipe(254 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 );
1 unmodified line
260 if (!made) {261 return yield* new RepoExists({ name });262 }263413 yield* io(() =>414 init({ bare: true, defaultBranch: "main", fs, gitdir })415 ).pipe(Effect.orDie);264 yield* initBare(dir);265417 return gitdir;266 return dir;267 });268269 /** A new repo `name` holding `source`'s `ref` at `tip`, copied as it stands. */270 const seed = (
2 unmodified lines
273 ref: string,274 tip: Option.Option<CommitSha>275 ) =>276 Effect.gen(function* () {428 const gitdir = yield* open(name);277 yield* seedRef(source, yield* open(name), ref, tip);278430 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 }436279 return createdOf(name);280 });281282 // Local disk's test-only meaning of a public remote: a bare repo on this
4 unmodified lines
287 url: string,288 branch: BranchName | undefined289 ) =>290 Effect.gen(function* () {449 const gitdir = fileURLToPath(url);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)) {456 return yield* new ImportRefused({457 name,458 reason: `no repo at ${url}`,459 });304 return yield* noRepo;305 }306307 // A detached HEAD names no branch to take.308 const ref = branch === undefined ? head.value : `refs/heads/${branch}`;
4 unmodified lines
313 reason: `${url} has no default branch`,314 });315 }316472 const tip = yield* tipOf(gitdir, ref);317 const tip = yield* tipOf({ fs, gitdir }, ref);318319 if (Option.isNone(tip)) {320 return yield* new ImportRefused({321 name,
71 unmodified lines
393 name: RepoName,394 url: string,395 branch: BranchName | undefined396 ) =>552 Effect.flatMap(open(name), (gitdir) =>397 Effect.flatMap(open(name), ({ gitdir }) =>398 fetchInto(name, gitdir, url, branch).pipe(399 Effect.onError(() => removeAll(gitdir).pipe(Effect.asVoid))400 )401 );
3 unmodified lines
405 name: RepoName,406 change: (tokens: Tokens) => Effect.Effect<readonly [A, Tokens]>407 ) =>408 Effect.gen(function* () {564 const gitdir = yield* known(name);565 const path = `${gitdir}/tokens.json`;566 const lock = yield* lockOf(name);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(() =>
25 unmodified lines
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* () {605 const from = yield* known(base);606 const tip = yield* tipOf(from, mainRef);450 const { dir } = yield* known(base);451 const tip = yield* tipOf(dir, mainRef);452608 return yield* seed(name, { fs, gitdir: from }, mainRef, tip);453 return yield* seed(name, dir, mainRef, tip);454 }),455 importFrom: (name, source) =>456 Effect.gen(function* () {612 if (yield* exists(gitdirOf(name))) {457 if (yield* exists(dirOf(name).gitdir)) {458 return yield* new RepoExists({ name });459 }460461 const scheme = URL.canParse(source.url)
16 unmodified lines
478 )479 )480 );481 }),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);642643 while (Option.isSome(next) && commits.length < limit) {644 const commit = yield* commitAt(gitdir, next.value);645646 if (Option.isNone(commit)) {647 break;648 }649650 commits.push(commit.value);651 next = Option.fromNullishOr(commit.value.parents[0]);652 }653654 return commits;655 }),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;
16 unmodified lines
502 scope,503 secret: Redacted.make(`local-${id}`),504 };505 }),680 push: (name, source, updates) =>681 Effect.gen(function* () {682 const gitdir = yield* known(name);683 const lock = yield* lockOf(name);684685 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);693694 const read = yield* unlessMissing(() =>695 readBlob({ fs, gitdir, oid: blob })696 );697698 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);708709 if (Option.isNone(sha)) {710 return Option.none();711 }712713 const blob = yield* unlessMissing(() =>714 readBlob({ filepath: path, fs, gitdir, oid: sha.value })715 );716717 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);723724 const read = yield* unlessMissing(() =>725 readTree({ fs, gitdir, oid: tree })726 );727728 if (Option.isNone(read) || read.value.oid !== tree) {729 return Option.none();730 }731732 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);740741 return Option.some(entries);742 }),743 refs: (name) =>744 Effect.gen(function* () {745 const gitdir = yield* known(name);746747 const names = yield* io(() =>748 listRefs({ filepath: "refs", fs, gitdir })749 ).pipe(Effect.orDie);750751 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);755756 return Option.map(tip, (sha) => [ref, sha] as const);757 })758 );759760 return new Map(Array.getSomes(listed));761 }),506 remote: (name) => known(name).pipe(Effect.as(createdOf(name).remote)),763 remove: (name) => removeAll(gitdirOf(name)),507 remove: (name) => removeAll(dirOf(name).gitdir),508 revokeToken: (name, id) =>509 updateTokens(name, (tokens) =>510 Effect.succeed(511 tokens.live.includes(id)
41 unmodified lines
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
modified:packages/artifacts/test/local.test.ts+14 added
151 unmodified lines
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");
45 unmodified lines