Merge build/217-artifacts-binding: the platform keeps its repos in Artifacts through the Workers binding, and its surprises are typed
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents bc76f1a, 4e8e008 · Browse files · 6 files·+1971 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+1971 added−0 removed
- tests:+938 added−0 removed
- other:+1033 added−0 removed
Provenance
- Commit
c5f1296- Tree
7ec6038- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
bc76f1a- Parent 2
4e8e008
6 files changed+1971 added−0 removed
added:packages/artifacts/src/repo-host/binding.ts+555 added
1+/**2+ * `RepoHost` over the Workers `Artifacts` binding: how the deployed platform3+ * keeps its repos. The binding's surprises (S1, S2, S7) come back typed:4+ *5+ * - errors are read by `code`, and by message when there is none, as under6+ * `wrangler dev` remote bindings (S1 #22);7+ * - a fork that answers 500 is tried once more, and an already-exists or a8+ * second 500 after that may be the fork the first made: it is, if it lists9+ * `main` (S7);10+ * - reads name a branch by its short name and a commit by its id, never11+ * `refs/…` (S1 #20), so `refs` and `push` go over git smart HTTP instead;12+ * - a busy receive-pack is `HostBusy` (S2 #9).13+ *14+ * Refs and pushes use a token the adapter mints for the one call and revokes15+ * after it; the token goes nowhere but the `Authorization` header of the16+ * adapter's own requests. Every repo handle is disposed after use.17+ */18+import {19+ Data,20+ DateTime,21+ Duration,22+ Effect,23+ Layer,24+ Match,25+ Option,26+ Predicate,27+ Redacted,28+ Schema,29+} from "effect";30+31+import { Fetch } from "../fetch.ts";32+import {33+ Commit,34+ ForkInProgress,35+ ImportRefused,36+ RefName,37+ RepoExists,38+ RepoHost,39+ RepoNotFound,40+ Revision,41+ TreeEntry,42+} from "../repo-host.ts";43+import type { RepoName, RepoToken, TokenScope } from "../repo-host.ts";44+import { listRefs, pushRefs } from "./smart-http.ts";45+46+const Code = Schema.Literals([47+ "ALREADY_EXISTS",48+ "NOT_FOUND",49+ "CREATE_IN_PROGRESS",50+ "IMPORT_IN_PROGRESS",51+ "FORK_IN_PROGRESS",52+ "INVALID_INPUT",53+ "INVALID_REPO_NAME",54+ "INVALID_TTL",55+ "INVALID_URL",56+ "REMOTE_AUTH_REQUIRED",57+ "UPSTREAM_UNAVAILABLE",58+ "MEMORY_LIMIT",59+ "INTERNAL_ERROR",60+]);61+62+type Code = typeof Code.Type;63+64+const isCode = Schema.is(Code);65+66+/**67+ * The codes a message names when the error carries none (S1 #22): Artifacts'68+ * words, the fake's, and the code itself.69+ */70+const MESSAGES = [71+ [/not found/iu, "NOT_FOUND"],72+ [/already exists/iu, "ALREADY_EXISTS"],73+ [/fork[_ ]in[_ ]progress|still forking/iu, "FORK_IN_PROGRESS"],74+ [/internal error/iu, "INTERNAL_ERROR"],75+] as const satisfies readonly (readonly [RegExp, Code])[];76+77+/**78+ * What a call to the binding threw, read once: its `code`, or the one its79+ * message names when it has none, and the error itself as the cause.80+ */81+class Thrown extends Data.TaggedError("Thrown")<{82+ readonly code: Option.Option<Code>;83+ readonly message: string;84+ readonly error: unknown;85+}> {}86+87+/** A fork that answered `INTERNAL_ERROR`, which may still have made the repo (S7 #2). */88+class MaybeForked extends Data.TaggedError("MaybeForked")<{89+ readonly thrown: Thrown;90+}> {}91+92+/** A promise of the binding's, failing with what it threw, read. */93+const attempt = <A>(run: () => Promise<A>) =>94+ Effect.tryPromise({95+ catch: (error) => {96+ const message = error instanceof Error ? error.message : String(error);97+98+ const code =99+ Predicate.hasProperty(error, "code") && isCode(error.code)100+ ? Option.some(error.code)101+ : Option.fromNullishOr(102+ MESSAGES.find(([pattern]) => pattern.test(message))?.[1]103+ );104+105+ return new Thrown({ code, error, message });106+ },107+ try: run,108+ });109+110+const threw =111+ (code: Code) =>112+ (thrown: Thrown): boolean =>113+ Option.contains(thrown.code, code);114+115+/**116+ * An error the binding threw, as the port's: by `code` first, by message117+ * when there is none. Anything else is a defect, with the error as its cause.118+ */119+const fromArtifactsError = (120+ name: RepoName,121+ thrown: Thrown122+): Effect.Effect<never, RepoNotFound | RepoExists | ForkInProgress> =>123+ Match.value(thrown).pipe(124+ Match.when(threw("NOT_FOUND"), () =>125+ Effect.fail(new RepoNotFound({ name }))126+ ),127+ Match.when(threw("ALREADY_EXISTS"), () =>128+ Effect.fail(new RepoExists({ name }))129+ ),130+ Match.when(threw("FORK_IN_PROGRESS"), () =>131+ Effect.fail(new ForkInProgress({ name }))132+ ),133+ Match.orElse(({ error }) => Effect.die(error))134+ );135+136+/** A call about the repo `name`, its errors read as the port's. */137+const call = <A>(name: RepoName, run: () => Promise<A>) =>138+ attempt(run).pipe(139+ Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))140+ );141+142+const asDefect = ({ error }: Thrown) => Effect.die(error);143+144+/** The port's reads and token calls fail only with `RepoNotFound`. */145+const onlyNotFound = <A, R>(146+ effect: Effect.Effect<A, RepoNotFound | RepoExists | ForkInProgress, R>147+) =>148+ effect.pipe(149+ Effect.catchTags({ ForkInProgress: Effect.die, RepoExists: Effect.die })150+ );151+152+const main = RefName.make("refs/heads/main");153+154+/** How long a token minted for one call lives; it is revoked after the call. */155+const CALL_TOKEN_TTL = Duration.minutes(5);156+157+// Artifacts takes a token's ttl in whole seconds, from a minute to a year.158+const MIN_TTL_SECONDS = 60;159+160+const MAX_TTL_SECONDS = 31_536_000;161+162+const secondsOf = (ttl: Duration.Duration) =>163+ Math.min(164+ Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),165+ MAX_TTL_SECONDS166+ );167+168+/** `log` reads at most this many commits per call. */169+const LOG_PAGE = 1000;170+171+/** The codes `import` refuses a source with: not git, not public, not reachable, too big. */172+const IMPORT_REFUSALS: ReadonlySet<Code> = new Set([173+ "INVALID_INPUT",174+ "INVALID_URL",175+ "MEMORY_LIMIT",176+ "NOT_FOUND",177+ "REMOTE_AUTH_REQUIRED",178+ "UPSTREAM_UNAVAILABLE",179+]);180+181+/** The binding's name for a revision: never `refs/…` (S1 #20). */182+const refOf = (at: Revision) =>183+ Revision.$match(at, {184+ Branch: ({ name }) => name,185+ Commit: ({ sha }) => sha,186+ });187+188+const bytesOf = (blob: Blob) =>189+ attempt(() => blob.arrayBuffer()).pipe(190+ Effect.map((buffer) => new Uint8Array(buffer)),191+ Effect.catchTag("Thrown", asDefect)192+ );193+194+const decodeCommit = Schema.decodeUnknownEffect(Commit);195+196+const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));197+198+const commitOf = (metadata: ArtifactsCommitMetadata) =>199+ decodeCommit({200+ author: metadata.author,201+ committer: metadata.committer,202+ message: metadata.message,203+ parents: metadata.parents,204+ sha: metadata.hash,205+ tree: metadata.treeHash,206+ }).pipe(Effect.orDie);207+208+// Artifacts gives canonical modes: a folder is `40000`, as git stores it, not209+// `040000`, as `ls-tree` prints it and the port has it.210+const entriesOf = (entries: readonly ArtifactsTreeEntry[]) =>211+ decodeEntries(212+ entries.map((entry) => {213+ const mode = entry.mode.padStart(6, "0");214+215+ return {216+ mode,217+ name: entry.name,218+ sha: entry.hash,219+ type: Match.value(mode).pipe(220+ Match.when("040000", () => "tree"),221+ Match.when("160000", () => "commit"),222+ Match.orElse(() => "blob")223+ ),224+ };225+ })226+ ).pipe(Effect.orDie);227+228+/** `use` over a handle to `name`, disposed after, whatever `use` came to. */229+const withRepo = <A, E, R>(230+ binding: Artifacts,231+ name: RepoName,232+ use: (repo: ArtifactsRepo) => Effect.Effect<A, E, R>233+) =>234+ Effect.scoped(235+ Effect.acquireRelease(236+ call(name, () => binding.get(name)),237+ (repo) =>238+ Effect.sync(() => {239+ repo[Symbol.dispose]();240+ })241+ ).pipe(Effect.flatMap(use))242+ );243+244+/**245+ * A token for one call, revoked when the scope closes, and the repo's246+ * remote: what a smart-HTTP call to the repo needs.247+ */248+const access = (name: RepoName, repo: ArtifactsRepo, scope: TokenScope) =>249+ Effect.gen(function* () {250+ const { remote } = yield* call(name, () => repo.info());251+252+ const token = yield* Effect.acquireRelease(253+ call(name, () => repo.createToken(scope, secondsOf(CALL_TOKEN_TTL))),254+ ({ id }) => attempt(() => repo.revokeToken(id)).pipe(Effect.ignore)255+ );256+257+ return { remote, token: Redacted.make(token.plaintext) };258+ });259+260+const refsOf = (name: RepoName, repo: ArtifactsRepo) =>261+ Effect.scoped(262+ Effect.gen(function* () {263+ const { remote, token } = yield* access(name, repo, "read");264+265+ return yield* listRefs(remote, token);266+ })267+ );268+269+/**270+ * After a 500 and then an already-exists or a second 500, the fork may be271+ * made (S7): it is, if it lists `main`. Otherwise it is still being made, or272+ * was undone; either way the caller tries again later.273+ */274+const confirmed = (binding: Artifacts, name: RepoName) =>275+ withRepo(binding, name, (repo) =>276+ Effect.gen(function* () {277+ const refs = yield* refsOf(name, repo);278+279+ if (!refs.has(main)) {280+ return yield* new ForkInProgress({ name });281+ }282+283+ const { remote } = yield* call(name, () => repo.info());284+285+ return { name, remote };286+ })287+ ).pipe(288+ Effect.catchTags({289+ RepoExists: Effect.die,290+ RepoNotFound: () => Effect.fail(new ForkInProgress({ name })),291+ })292+ );293+294+/**295+ * One fork call. The base's absence names the base; any other refusal names296+ * the target, and a 500 is `MaybeForked`, since it may have made the target.297+ */298+const forkOnce = (binding: Artifacts, base: RepoName, name: RepoName) =>299+ withRepo(binding, base, (repo) =>300+ attempt(() => repo.fork(name)).pipe(301+ Effect.map(({ remote }) => ({ name, remote })),302+ Effect.catchTag("Thrown", (thrown) =>303+ Match.value(thrown).pipe(304+ Match.when(threw("INTERNAL_ERROR"), () =>305+ Effect.fail(new MaybeForked({ thrown }))306+ ),307+ Match.when(threw("NOT_FOUND"), () =>308+ Effect.fail(new RepoNotFound({ name: base }))309+ ),310+ Match.orElse(() => fromArtifactsError(name, thrown))311+ )312+ )313+ )314+ );315+316+/**317+ * Whether the repo holds `id` as a blob or a commit: `readBlob` answers318+ * `null` for any other kind, and `readCommit` throws for a non-commit.319+ */320+const blobOrCommit = (name: RepoName, repo: ArtifactsRepo, id: string) =>321+ call(name, () => repo.readBlob(id)).pipe(322+ Effect.flatMap((blob) =>323+ blob === null324+ ? attempt(() => repo.readCommit(id)).pipe(325+ Effect.map((commit) => commit !== null),326+ Effect.catchIf(threw("INTERNAL_ERROR"), () =>327+ Effect.succeed(false)328+ ),329+ Effect.catchTag("Thrown", (thrown) =>330+ fromArtifactsError(name, thrown)331+ )332+ )333+ : Effect.succeed(true)334+ )335+ );336+337+/** Artifacts throws `INTERNAL_ERROR` for an object that is no tree (workers-types). */338+const treeAt = (name: RepoName, repo: ArtifactsRepo, tree: string) =>339+ attempt(() => repo.readTree(tree)).pipe(340+ Effect.flatMap((found) =>341+ found === null ? Effect.succeedNone : Effect.asSome(entriesOf(found))342+ ),343+ // A blob's or a commit's id names no tree, as on the other stores (202344+ // Comment 5); any other failure stays one.345+ Effect.catchIf(threw("INTERNAL_ERROR"), ({ error }) =>346+ blobOrCommit(name, repo, tree).pipe(347+ Effect.flatMap((other) =>348+ other ? Effect.succeedNone : Effect.die(error)349+ )350+ )351+ ),352+ Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))353+ );354+355+const importFrom = (356+ binding: Artifacts,357+ name: RepoName,358+ source: { readonly url: string; readonly branch?: string }359+) =>360+ attempt(() =>361+ binding.import({362+ source:363+ source.branch === undefined364+ ? { url: source.url }365+ : { branch: source.branch, url: source.url },366+ target: { name },367+ })368+ ).pipe(369+ Effect.map(({ remote }) => ({ name, remote })),370+ Effect.catchTag("Thrown", (thrown) =>371+ Match.value(thrown).pipe(372+ Match.when(threw("ALREADY_EXISTS"), () =>373+ Effect.fail(new RepoExists({ name }))374+ ),375+ Match.when(376+ ({ code }) =>377+ Option.exists(code, (refused) => IMPORT_REFUSALS.has(refused)),378+ ({ message }) =>379+ Effect.fail(new ImportRefused({ name, reason: message }))380+ ),381+ Match.orElse(asDefect)382+ )383+ )384+ );385+386+const log = (387+ name: RepoName,388+ repo: ArtifactsRepo,389+ at: Revision,390+ limit: number391+) =>392+ Effect.gen(function* () {393+ const ref = refOf(at);394+ const commits: Commit[] = [];395+396+ while (commits.length < limit) {397+ const asked = Math.min(limit - commits.length, LOG_PAGE);398+399+ const page = yield* call(name, () =>400+ repo.log({ limit: asked, offset: commits.length, ref })401+ );402+403+ for (const metadata of page) {404+ commits.push(yield* commitOf(metadata));405+ }406+407+ if (page.length < asked) {408+ break;409+ }410+ }411+412+ return commits;413+ });414+415+const mintToken = (416+ name: RepoName,417+ repo: ArtifactsRepo,418+ scope: TokenScope,419+ ttl: Duration.Duration420+) =>421+ Effect.gen(function* () {422+ const seconds = secondsOf(ttl);423+ const now = yield* DateTime.now;424+ const token = yield* call(name, () => repo.createToken(scope, seconds));425+ const asked = DateTime.add(now, { seconds });426+427+ // Never later than either clock says: the ttl asked for, from before the428+ // call, or the store's own expiry.429+ const expiresAt = Option.match(DateTime.make(token.expiresAt), {430+ onNone: () => asked,431+ onSome: (stated) => DateTime.min(asked, stated),432+ });433+434+ return {435+ expiresAt,436+ id: token.id,437+ scope,438+ secret: Redacted.make(token.plaintext),439+ } satisfies RepoToken;440+ });441+442+const make = (binding: Artifacts) =>443+ Effect.gen(function* () {444+ // The service alone: the layer's whole context would carry its Scope, and445+ // every call's finalizers would wait for the layer's end.446+ const fetch = yield* Fetch;447+448+ /** A read of `name`'s, failing only with `RepoNotFound`. */449+ const read = <A>(450+ name: RepoName,451+ use: (452+ repo: ArtifactsRepo453+ ) => Effect.Effect<A, RepoNotFound | RepoExists | ForkInProgress, Fetch>454+ ) =>455+ onlyNotFound(withRepo(binding, name, use)).pipe(456+ Effect.provideService(Fetch, fetch)457+ );458+459+ return RepoHost.of({460+ create: (name) =>461+ call(name, () => binding.create(name)).pipe(462+ Effect.map(({ remote }) => ({ name, remote })),463+ Effect.catchTags({464+ ForkInProgress: Effect.die,465+ RepoNotFound: Effect.die,466+ })467+ ),468+ // S7: a 500 is tried once more; an already-exists or a second 500 after469+ // it may be the fork the first made, so it is confirmed, not trusted.470+ fork: (base, name) =>471+ forkOnce(binding, base, name).pipe(472+ Effect.catchTag("MaybeForked", () =>473+ forkOnce(binding, base, name).pipe(474+ Effect.catchTags({475+ MaybeForked: () => confirmed(binding, name),476+ RepoExists: () => confirmed(binding, name),477+ })478+ )479+ ),480+ Effect.provideService(Fetch, fetch)481+ ),482+ importFrom: (name, source) => importFrom(binding, name, source),483+ log: (name, at, limit) =>484+ read(name, (repo) => log(name, repo, at, limit)),485+ mintToken: (name, scope, ttl) =>486+ read(name, (repo) => mintToken(name, repo, scope, ttl)),487+ push: (name, source, updates) =>488+ withRepo(binding, name, (repo) =>489+ Effect.scoped(490+ Effect.gen(function* () {491+ const { remote, token } = yield* access(name, repo, "write");492+493+ return yield* pushRefs({ remote, source, token, updates });494+ })495+ )496+ ).pipe(497+ Effect.catchTags({498+ ForkInProgress: Effect.die,499+ RepoExists: Effect.die,500+ }),501+ Effect.provideService(Fetch, fetch)502+ ),503+ readBlob: (name, blob) =>504+ read(name, (repo) =>505+ call(name, () => repo.readBlob(blob)).pipe(506+ Effect.flatMap((found) =>507+ found === null508+ ? Effect.succeedNone509+ : Effect.asSome(bytesOf(found))510+ )511+ )512+ ),513+ readCommit: (name, sha) =>514+ read(name, (repo) =>515+ call(name, () => repo.readCommit(sha)).pipe(516+ Effect.flatMap((found) =>517+ found === null518+ ? Effect.succeedNone519+ : Effect.asSome(commitOf(found))520+ )521+ )522+ ),523+ readFile: (name, at, path) =>524+ read(name, (repo) =>525+ call(name, () => repo.readFile({ path, ref: refOf(at) })).pipe(526+ Effect.flatMap((found) =>527+ found === null528+ ? Effect.succeedNone529+ : Effect.asSome(bytesOf(found))530+ )531+ )532+ ),533+ readTree: (name, tree) => read(name, (repo) => treeAt(name, repo, tree)),534+ refs: (name) => read(name, (repo) => refsOf(name, repo)),535+ remote: (name) =>536+ read(name, (repo) =>537+ call(name, () => repo.info()).pipe(Effect.map(({ remote }) => remote))538+ ),539+ remove: (name) =>540+ attempt(() => binding.delete(name)).pipe(541+ Effect.catchTag("Thrown", asDefect)542+ ),543+ revokeToken: (name, id) =>544+ read(name, (repo) => call(name, () => repo.revokeToken(id))),545+ });546+ });547+548+/**549+ * Artifacts through the Workers binding, the platform's `RepoHost` in550+ * production. Refs and pushes go over git smart HTTP through `Fetch`.551+ */552+export const RepoHostBinding = {553+ layer: (binding: Artifacts): Layer.Layer<RepoHost, never, Fetch> =>554+ Layer.effect(RepoHost, make(binding)),555+};added:packages/artifacts/src/repo-host/smart-http.ts+476 added
1+/**2+ * Git smart HTTP over the `Fetch` port, for adapters whose store serves git3+ * at a remote URL with a bearer token: `/binding` and `/rest`. It takes a4+ * `remote` (`…/<repo>.git`, Artifacts' shape) and a token, and nothing about5+ * how either was got.6+ *7+ * The token goes only into the `Authorization` header of requests to the8+ * remote's own origin; everywhere else it stays `Redacted`.9+ */10+import { CommitSha } from "@repo/protocol/ids";11+import {12+ Data,13+ Effect,14+ FiberSet,15+ Match,16+ Option,17+ Redacted,18+ Schema,19+ Stream,20+} from "effect";21+import type { Array } from "effect";22+import {23+ Errors,24+ addRemote,25+ deleteRef,26+ deleteRemote,27+ fetch as fetchPack,28+ init,29+ listRefs as localRefs,30+ listServerRefs,31+ push,32+} from "isomorphic-git";33+import type {34+ FsClient,35+ GitHttpRequest,36+ GitHttpResponse,37+ HttpClient,38+} from "isomorphic-git";39+40+import { Fetch } from "../fetch.ts";41+import {42+ HostBusy,43+ RefName,44+ RefOutcome,45+ RepoName,46+ RepoNotFound,47+} from "../repo-host.ts";48+import type { PushSource, RefUpdate } from "../repo-host.ts";49+50+/** What isomorphic-git or a response body threw, before it is read. */51+class GitFailure extends Data.TaggedError("GitFailure")<{52+ readonly cause: unknown;53+}> {}54+55+/** isomorphic-git's no-commit id: a ref that is absent. */56+const ABSENT = "0".repeat(40);57+58+// What a receive-pack says when a ref moved under a push: Artifacts (S1 #5),59+// git's own receive-pack (2.56), and a server set to refuse rewinding a ref.60+// `fetch first` is git's client-side word and never reaches a server.61+const MOVED = ["stale ref", "incorrect old value provided", "non-fast-forward"];62+63+// Artifacts' whole reply to a push it is too busy for: one side-band 364+// (fatal) packet and no report (S2 #9).65+const BUSY = "artifacts_git_receive_pack_busy";66+67+// The remote names isomorphic-git files a push's and a fetch's tracking refs68+// under; each is removed again, so a source keeps no trace of the store.69+const PUSH_REMOTE = "repo-host-push";70+71+const FETCH_REMOTE = "repo-host-fetch";72+73+const decodeRepo = Schema.decodeUnknownOption(RepoName);74+75+const decodeRef = Schema.decodeUnknownOption(RefName);76+77+const decodeSha = Schema.decodeUnknownOption(CommitSha);78+79+/** The repo a remote names: its last path segment, less `.git`. */80+const repoOf = (remote: string) =>81+ Option.match(82+ decodeRepo(83+ (URL.canParse(remote) ? new URL(remote).pathname : remote)84+ .replace(/\/+$/u, "")85+ .split("/")86+ .at(-1)87+ ?.replace(/\.git$/u, "")88+ ),89+ {90+ onNone: () => Effect.die(`${remote} names no repo as <name>.git`),91+ onSome: Effect.succeed,92+ }93+ );94+95+const concat = (chunks: readonly Uint8Array[]) => {96+ const all = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));97+ let at = 0;98+99+ for (const chunk of chunks) {100+ all.set(chunk, at);101+ at += chunk.length;102+ }103+104+ return all;105+};106+107+/**108+ * A request body as one array. isomorphic-git types it as an async iterator109+ * but sends an array of chunks, so this takes either.110+ */111+const bytesOf = (body: AsyncIterable<Uint8Array> | Iterable<Uint8Array>) =>112+ (Symbol.asyncIterator in body113+ ? Stream.fromAsyncIterable(body, (cause) => new GitFailure({ cause }))114+ : Stream.fromIterable(body)115+ ).pipe(Stream.runCollect, Effect.map(concat));116+117+/** One chunk as the async iterator isomorphic-git reads a response body from. */118+const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {119+ const chunks = [bytes];120+121+ const iterator: AsyncIterableIterator<Uint8Array> = {122+ [Symbol.asyncIterator]: () => iterator,123+ next: () => {124+ const chunk = chunks.shift();125+126+ return Promise.resolve(127+ chunk === undefined128+ ? { done: true, value: undefined }129+ : { done: false, value: chunk }130+ );131+ },132+ };133+134+ return iterator;135+};136+137+/** The side-band 3 (fatal) messages in a reply's top-level packet lines. */138+const fatalMessages = (bytes: Uint8Array) => {139+ const messages: string[] = [];140+ const text = new TextDecoder();141+ let at = 0;142+143+ while (at + 4 <= bytes.length) {144+ const length = Number.parseInt(text.decode(bytes.slice(at, at + 4)), 16);145+146+ if (Number.isNaN(length)) {147+ break;148+ }149+150+ // A flush (`0000`) or a delimiter carries no payload.151+ if (length < 4) {152+ at += 4;153+ continue;154+ }155+156+ if (bytes[at + 4] === 3) {157+ messages.push(text.decode(bytes.slice(at + 5, at + length)));158+ }159+160+ at += length;161+ }162+163+ return messages;164+};165+166+const isReceivePack = (url: string) =>167+ new URL(url).pathname.endsWith("/git-receive-pack");168+169+/**170+ * isomorphic-git's HTTP client over `Fetch`, for one repo. It adds the token171+ * to requests to the remote's origin, and reads a 404 as `RepoNotFound` and a172+ * busy receive-pack as `HostBusy`, failing the exchange with them, so the173+ * promise isomorphic-git awaits rejects with the typed error itself.174+ */175+const httpFor = (remote: string, token: Redacted.Redacted, name: RepoName) =>176+ Effect.gen(function* () {177+ const run = yield* FiberSet.makeRuntimePromise<Fetch>();178+ const { origin } = new URL(remote);179+180+ const exchange = (request: GitHttpRequest) =>181+ Effect.gen(function* () {182+ const headers = new Headers(request.headers ?? {});183+184+ if (new URL(request.url).origin === origin) {185+ headers.set("authorization", `Bearer ${Redacted.value(token)}`);186+ }187+188+ const method = request.method ?? "GET";189+190+ const response = yield* (yield* Fetch).fetch(191+ request.body === undefined192+ ? new Request(request.url, { headers, method })193+ : new Request(request.url, {194+ body: yield* bytesOf(request.body),195+ headers,196+ method,197+ })198+ );199+200+ // ASSUMPTION: Artifacts answers 404 for a repo it lacks, as `git201+ // http-backend` does.202+ if (response.status === 404) {203+ return yield* new RepoNotFound({ name });204+ }205+206+ const bytes = new Uint8Array(207+ yield* Effect.tryPromise({208+ catch: (cause) => new GitFailure({ cause }),209+ try: () => response.arrayBuffer(),210+ })211+ );212+213+ if (214+ isReceivePack(request.url) &&215+ fatalMessages(bytes).some((message) => message.includes(BUSY))216+ ) {217+ return yield* new HostBusy({ name });218+ }219+220+ return {221+ body: once(bytes),222+ headers: Object.fromEntries(response.headers.entries()),223+ method: request.method,224+ statusCode: response.status,225+ statusMessage: response.statusText,226+ url: response.url === "" ? request.url : response.url,227+ } satisfies GitHttpResponse;228+ });229+230+ return {231+ request: (request: GitHttpRequest) => run(exchange(request)),232+ } satisfies HttpClient;233+ });234+235+/**236+ * Runs an isomorphic-git call. The typed errors the HTTP client failed with237+ * come back as new values (isomorphic-git stamps a `caller` onto what it238+ * rethrows); anything else it threw is a `GitFailure` for the caller to read.239+ */240+const git = <A>(run: (signal: AbortSignal) => Promise<A>) =>241+ Effect.tryPromise({242+ catch: (cause) =>243+ Match.value(cause).pipe(244+ Match.when(245+ Schema.is(RepoNotFound),246+ ({ name }) => new RepoNotFound({ name })247+ ),248+ Match.when(Schema.is(HostBusy), ({ name }) => new HostBusy({ name })),249+ Match.orElse(() => new GitFailure({ cause }))250+ ),251+ try: run,252+ });253+254+/** Every ref the remote lists, custom refs included; never `HEAD` or a peeled tag. */255+const refsAt = (remote: string, http: HttpClient) =>256+ git(() => listServerRefs({ http, protocolVersion: 1, url: remote })).pipe(257+ Effect.catchTags({258+ GitFailure: ({ cause }) => Effect.die(cause),259+ // Only a push is ever busy.260+ HostBusy: Effect.die,261+ }),262+ Effect.map(263+ (refs) =>264+ new Map(265+ refs.flatMap(({ oid, ref }) =>266+ Option.match(Option.all([decodeRef(ref), decodeSha(oid)]), {267+ onNone: () => [],268+ onSome: (pair) => [pair],269+ })270+ )271+ )272+ )273+ );274+275+/**276+ * Every ref the remote lists, as `ls-remote` lists them: what reads by name277+ * cannot reach (S1 #20).278+ */279+export const listRefs = (280+ remote: string,281+ token: Redacted.Redacted282+): Effect.Effect<ReadonlyMap<RefName, CommitSha>, RepoNotFound, Fetch> =>283+ Effect.scoped(284+ Effect.gen(function* () {285+ const name = yield* repoOf(remote);286+287+ return yield* refsAt(remote, yield* httpFor(remote, token, name));288+ })289+ );290+291+const isMoved = (reason: string) =>292+ MOVED.some((moved) => reason.includes(moved));293+294+/** Whether the store refused a push of `ref` because the ref moved. */295+const refusedAsMoved = ({ cause }: GitFailure, ref: RefName) =>296+ cause instanceof Errors.GitPushError &&297+ isMoved(cause.data.result.refs[ref]?.error ?? "");298+299+/**300+ * One ref's compare-and-swap. The push's own ref discovery is the check: if301+ * the tip it finds is not `from`, the push stops there, before any pack is302+ * built, so the old value the push names is the one checked, and the store303+ * checks it again as it moves the ref. A ref that moved after the check is304+ * `Stale` at the tip a fresh listing shows.305+ *306+ * The old value is the only check, as on every store: `to` need not descend307+ * from `from` (Artifacts takes such an update, S1 #4). So isomorphic-git's308+ * own fast-forward test is off (`force`), which also spares it walking the309+ * history of `to` in a source that holds only the new objects.310+ */311+const pushOne = (312+ remote: string,313+ http: HttpClient,314+ source: PushSource,315+ update: RefUpdate316+) =>317+ Effect.gen(function* () {318+ const expected = Option.getOrElse(update.from, () => ABSENT);319+ let found = ABSENT;320+321+ const pushed = yield* git((signal) =>322+ push({323+ ...source,324+ force: true,325+ http,326+ onPrePush: ({ remoteRef }) => {327+ found = remoteRef.oid;328+329+ return found === expected;330+ },331+ ref: update.to,332+ remote: PUSH_REMOTE,333+ remoteRef: update.ref,334+ signal,335+ url: remote,336+ })337+ ).pipe(338+ Effect.as(RefOutcome.Updated({ ref: update.ref })),339+ Effect.catchTag("GitFailure", (failure) =>340+ Match.value(failure).pipe(341+ Match.when(342+ ({ cause }) => cause instanceof Errors.UserCanceledError,343+ () =>344+ Effect.succeed(345+ RefOutcome.Stale({346+ ref: update.ref,347+ tip: Option.filter(decodeSha(found), (sha) => sha !== ABSENT),348+ })349+ )350+ ),351+ Match.when(352+ (refused) => refusedAsMoved(refused, update.ref),353+ () =>354+ refsAt(remote, http).pipe(355+ Effect.map((refs) =>356+ RefOutcome.Stale({357+ ref: update.ref,358+ tip: Option.fromNullishOr(refs.get(update.ref)),359+ })360+ )361+ )362+ ),363+ Match.orElse(({ cause }) => Effect.die(cause))364+ )365+ )366+ );367+368+ // isomorphic-git files a pushed ref under the push's remote in the source.369+ yield* git(() =>370+ deleteRef({371+ ...source,372+ ref: `refs/remotes/${PUSH_REMOTE}/${update.ref.replace(/^refs\/heads\//u, "")}`,373+ })374+ ).pipe(Effect.ignore);375+376+ return pushed;377+ });378+379+/**380+ * Pushes each update in order, one ref per push, since Artifacts has no381+ * atomic push (S1 #6): each ref is updated or `Stale` on its own. Nothing is382+ * retried; a `Stale` ref is the caller's to decide on. A busy store fails the383+ * whole call with `HostBusy`, and refs before the busy one may have moved.384+ */385+export const pushRefs = (input: {386+ readonly remote: string;387+ readonly token: Redacted.Redacted;388+ readonly source: PushSource;389+ readonly updates: Array.NonEmptyReadonlyArray<RefUpdate>;390+}): Effect.Effect<readonly RefOutcome[], RepoNotFound | HostBusy, Fetch> =>391+ Effect.scoped(392+ Effect.gen(function* () {393+ const name = yield* repoOf(input.remote);394+ const http = yield* httpFor(input.remote, input.token, name);395+396+ return yield* Effect.forEach(input.updates, (update) =>397+ pushOne(input.remote, http, input.source, update)398+ );399+ })400+ );401+402+/**403+ * Fetches one ref of the remote into the repo `gitdir` in `fs` (made if404+ * absent), `depth` commits deep when given; its tip, or `None` when the remote405+ * has no such ref. The ref is a branch name or a full ref. The repo keeps the406+ * objects and no ref, remote or tracking ref of the fetch's own.407+ */408+export const fetchInto = (input: {409+ readonly remote: string;410+ readonly token: Redacted.Redacted;411+ readonly fs: FsClient;412+ readonly gitdir: string;413+ readonly ref: string;414+ readonly depth?: number;415+}): Effect.Effect<Option.Option<CommitSha>, RepoNotFound, Fetch> =>416+ Effect.scoped(417+ Effect.gen(function* () {418+ const name = yield* repoOf(input.remote);419+ const http = yield* httpFor(input.remote, input.token, name);420+ const repo = { fs: input.fs, gitdir: input.gitdir };421+422+ yield* git(() => init({ ...repo, bare: true })).pipe(Effect.orDie);423+424+ // isomorphic-git files what it fetched under a configured remote's425+ // refspec, so the repo has one, and its tracking refs, for as long as426+ // the fetch runs.427+ yield* Effect.acquireRelease(428+ git(() =>429+ addRemote({430+ ...repo,431+ force: true,432+ remote: FETCH_REMOTE,433+ url: input.remote,434+ })435+ ).pipe(Effect.orDie),436+ () =>437+ Effect.gen(function* () {438+ const tracking = yield* git(() =>439+ localRefs({ ...repo, filepath: `refs/remotes/${FETCH_REMOTE}` })440+ );441+442+ yield* Effect.forEach(tracking, (ref) =>443+ git(() =>444+ deleteRef({445+ ...repo,446+ ref: `refs/remotes/${FETCH_REMOTE}/${ref}`,447+ })448+ )449+ );450+ yield* git(() => deleteRemote({ ...repo, remote: FETCH_REMOTE }));451+ }).pipe(Effect.ignore)452+ );453+454+ return yield* git(() =>455+ fetchPack({456+ ...repo,457+ depth: input.depth,458+ http,459+ remote: FETCH_REMOTE,460+ remoteRef: input.ref,461+ singleBranch: true,462+ tags: false,463+ })464+ ).pipe(465+ Effect.map(({ fetchHead }) => decodeSha(fetchHead)),466+ Effect.catchTags({467+ GitFailure: ({ cause }) =>468+ cause instanceof Errors.NotFoundError469+ ? Effect.succeedNone470+ : Effect.die(cause),471+ // Only a push is ever busy.472+ HostBusy: Effect.die,473+ })474+ );475+ })476+ );added:packages/artifacts/test/binding-live.test.ts+187 added
1+/**2+ * The binding against live Artifacts. Opt-in, never in `verify`: it runs only3+ * with `LIVE_ARTIFACTS=1` and `LIVE_ARTIFACTS_HARNESS` naming, by absolute4+ * path, a harness module outside this repo (spec §7.4: live-harness code lives5+ * in wanted-explainer). The harness exports `live()`, which resolves to6+ *7+ * ```ts8+ * {9+ * namespace: string; // a namespace this build made10+ * binding: Artifacts; // `getPlatformProxy({ remoteBindings: true })`'s `env.ARTIFACTS`11+ * fetch: (request: Request) => Promise<Response>;12+ * dispose: () => Promise<void>; // the proxy's13+ * }14+ * ```15+ *16+ * Every repo name gets a fresh prefix per test, since the contract suite uses17+ * fixed names, and every repo a test made is deleted when it ends. It never18+ * runs against the `witness` namespace.19+ */20+import { describe } from "@effect/vitest";21+import { Data, Effect, FiberSet, Layer, Predicate, Schema } from "effect";22+23+import { Fetch, FetchFailed } from "../src/fetch.ts";24+import { RepoHostBinding } from "../src/repo-host/binding.ts";25+import { describeRepoHost } from "./repo-host-contract.ts";26+27+/** The namespace another project owns (spec §4.4). */28+const FORBIDDEN = "witness";29+30+const harnessPath = process.env.LIVE_ARTIFACTS_HARNESS;31+32+const live = process.env.LIVE_ARTIFACTS === "1" && harnessPath !== undefined;33+34+// The harness's functions, taken on trust as its doc comment types them:35+// a function's signature cannot be checked at run time.36+37+const Start = Schema.declare((input): input is () => Promise<object> =>38+ Predicate.isFunction(input)39+);40+41+const Dispose = Schema.declare((input): input is () => Promise<void> =>42+ Predicate.isFunction(input)43+);44+45+const Send = Schema.declare(46+ (input): input is (request: Request) => Promise<Response> =>47+ Predicate.isFunction(input)48+);49+50+/** What the harness's module exports. */51+const HarnessModule = Schema.Struct({ live: Start });52+53+/** What `live()` resolves to. */54+const Harness = Schema.Struct({55+ binding: Schema.declare(56+ (input): input is Artifacts =>57+ Predicate.hasProperty(input, "get") && Predicate.isFunction(input.get)58+ ),59+ dispose: Dispose,60+ fetch: Send,61+ namespace: Schema.NonEmptyString.pipe(62+ Schema.check(63+ Schema.makeFilter((namespace) =>64+ namespace === FORBIDDEN65+ ? `${FORBIDDEN} belongs to another project (spec §4.4)`66+ : undefined67+ )68+ )69+ ),70+});71+72+type Harness = typeof Harness.Type;73+74+class HarnessFailed extends Data.TaggedError("HarnessFailed")<{75+ readonly reason: string;76+}> {}77+78+/** The harness's `live()`, run once per test and disposed after it. */79+const harness = (path: string) =>80+ Effect.acquireRelease(81+ Effect.gen(function* () {82+ const module = yield* Effect.tryPromise({83+ catch: () => new HarnessFailed({ reason: `cannot import ${path}` }),84+ try: () => import(path),85+ }).pipe(Effect.flatMap(Schema.decodeUnknownEffect(HarnessModule)));86+87+ return yield* Effect.tryPromise({88+ catch: () => new HarnessFailed({ reason: "live() rejected" }),89+ try: () => module.live(),90+ }).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Harness)));91+ }).pipe(Effect.orDie),92+ ({ dispose }) => Effect.tryPromise(() => dispose()).pipe(Effect.ignore)93+ );94+95+/** A fresh prefix: the suite's fixed names, unique to this test. */96+const freshPrefix = () =>97+ `live-${crypto98+ .getRandomValues(new Uint32Array(2))99+ .reduce((text, word) => text + word.toString(36), "")}-`;100+101+/**102+ * The live binding with every name prefixed, and every repo made through it103+ * deleted when the scope closes. Each method is forwarded by name: a binding104+ * and its handles are RPC stubs, whose methods a spread would not copy.105+ */106+const prefixed = (binding: Artifacts) =>107+ Effect.gen(function* () {108+ const prefix = freshPrefix();109+ const run = yield* FiberSet.makeRuntimePromise();110+ const made = new Set<string>();111+112+ const named = (name: string) => {113+ made.add(`${prefix}${name}`);114+115+ return `${prefix}${name}`;116+ };117+118+ yield* Effect.addFinalizer(() =>119+ Effect.forEach(made, (name) =>120+ Effect.tryPromise(() => binding.delete(name)).pipe(Effect.ignore)121+ )122+ );123+124+ const handle = (repo: ArtifactsRepo): ArtifactsRepo => ({125+ createToken: (scope, ttl) => repo.createToken(scope, ttl),126+ fork: (target, options) => repo.fork(named(target), options),127+ info: () => repo.info(),128+ listTokens: () => repo.listTokens(),129+ log: (options) => repo.log(options),130+ readBlob: (hash) => repo.readBlob(hash),131+ readCommit: (hash) => repo.readCommit(hash),132+ readFile: (args) => repo.readFile(args),133+ readTree: (hash) => repo.readTree(hash),134+ revokeToken: (tokenOrId) => repo.revokeToken(tokenOrId),135+ [Symbol.dispose]: () => {136+ repo[Symbol.dispose]();137+ },138+ });139+140+ return {141+ create: (name, options) => binding.create(named(name), options),142+ delete: (name) => binding.delete(`${prefix}${name}`),143+ get: (name) =>144+ run(145+ Effect.promise(() => binding.get(`${prefix}${name}`)).pipe(146+ Effect.map(handle)147+ )148+ ),149+ import: ({ source, target }) =>150+ binding.import({151+ source,152+ target: { ...target, name: named(target.name) },153+ }),154+ list: (options) => binding.list(options),155+ } satisfies Artifacts;156+ });157+158+/** The live store's `Fetch`: the harness's fetch, failing as no response. */159+const fetchOver = (send: Harness["fetch"]) =>160+ Fetch.of({161+ fetch: (request) =>162+ Effect.tryPromise({163+ catch: (cause) =>164+ new FetchFailed({165+ reason: cause instanceof Error ? cause.message : "no response",166+ url: request.url,167+ }),168+ try: () => send(request),169+ }),170+ });171+172+describe.runIf(live)("against live Artifacts", () => {173+ // Artifacts imports only public HTTPS remotes, and its own refuse anonymous174+ // reads (S1 #10), so the import cases do not run here.175+ describeRepoHost(176+ "binding (live)",177+ Layer.unwrap(178+ Effect.gen(function* () {179+ const { binding, fetch } = yield* harness(harnessPath ?? "");180+181+ return RepoHostBinding.layer(yield* prefixed(binding)).pipe(182+ Layer.provide(Layer.succeed(Fetch, fetchOver(fetch)))183+ );184+ })185+ )186+ );187+});added:packages/artifacts/test/binding.test.ts+751 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { CommitSha, RepoPath } from "@repo/protocol/ids";4+import { fakeArtifactsBinding } from "@repo/testkit/fake-artifacts-binding";5+import type {6+ FakeOptions,7+ HostLike,8+} from "@repo/testkit/fake-artifacts-binding";9+import { gitClient } from "@repo/testkit/git-client";10+import { httpBackend } from "@repo/testkit/http-backend";11+import {12+ Duration,13+ Effect,14+ Exit,15+ FiberSet,16+ Layer,17+ Option,18+ Redacted,19+ Ref,20+} from "effect";21+import type { Scope } from "effect";22+import type { ChildProcessSpawner } from "effect/process";23+import { readCommit } from "isomorphic-git";24+25+import { Fetch, FetchFailed } from "../src/fetch.ts";26+import {27+ BranchName,28+ ForkInProgress,29+ HostBusy,30+ ObjectId,31+ RefName,32+ RefOutcome,33+ RepoExists,34+ RepoHost,35+ RepoName,36+ RepoNotFound,37+ Revision,38+} from "../src/repo-host.ts";39+import { RepoHostBinding } from "../src/repo-host/binding.ts";40+import { RepoHostLocal } from "../src/repo-host/local.ts";41+import { memoryFs } from "../src/repo-host/memory-fs.ts";42+import { fetchInto, listRefs, pushRefs } from "../src/repo-host/smart-http.ts";43+import { describeRepoHost } from "./repo-host-contract.ts";44+45+const main = RefName.make("refs/heads/main");46+47+const landed = RefName.make("refs/asked/landed");48+49+/** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */50+const remoteBase = "https://artifacts.test/git/projects";51+52+/** A packet-line holding one side-band 3 (fatal) message. */53+const fatal = (message: string) => {54+ const payload = new TextEncoder().encode(`\u0003${message}`);55+ const length = (payload.length + 4).toString(16).padStart(4, "0");56+57+ return new Uint8Array([...new TextEncoder().encode(length), ...payload]);58+};59+60+/** Artifacts' whole reply to a push it is too busy for (S2 #9): no report, no flush. */61+const busyReply = () =>62+ new Response(fatal("artifacts_git_receive_pack_busy\n"), {63+ headers: { "content-type": "application/x-git-receive-pack-result" },64+ });65+66+/** What one request to the store carried, as the test's `Fetch` saw it. */67+interface Seen {68+ readonly url: string;69+ readonly authorization: string | null;70+}71+72+/** What a test may do to the next receive-pack call before git sees it. */73+type Intercept = (request: Request) => Effect.Effect<Option.Option<Response>>;74+75+/**76+ * The binding over a fake Artifacts on local disk: a `RepoHostLocal` in a77+ * temporary directory, wrapped by testkit's fake binding, whose remotes a78+ * `Fetch` serves with real `git http-backend` over the same directory.79+ * Every handle the binding opens is counted, and every token it mints is80+ * recorded, so a test can check both came back.81+ */82+const world = (83+ options: FakeOptions & { readonly wrap?: (host: HostLike) => HostLike } = {}84+) =>85+ Effect.gen(function* () {86+ const root = yield* RepoHostLocal.temporaryRoot;87+88+ const spawner =89+ yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();90+91+ const backend = httpBackend(root);92+ const seen = yield* Ref.make<readonly Seen[]>([]);93+ const intercept = yield* Ref.make<Option.Option<Intercept>>(Option.none());94+95+ const fetch = Fetch.of({96+ fetch: (request) =>97+ Effect.gen(function* () {98+ if (!request.url.startsWith(`${remoteBase}/`)) {99+ return yield* new FetchFailed({100+ reason: "no route to host",101+ url: request.url,102+ });103+ }104+105+ yield* Ref.update(seen, (all) => [106+ ...all,107+ {108+ authorization: request.headers.get("authorization"),109+ url: request.url,110+ },111+ ]);112+113+ const once = yield* Ref.getAndSet(intercept, Option.none());114+115+ if (116+ Option.isSome(once) &&117+ request.url.endsWith("/git-receive-pack")118+ ) {119+ const reply = yield* once.value(request);120+121+ if (Option.isSome(reply)) {122+ return reply.value;123+ }124+ } else if (Option.isSome(once)) {125+ yield* Ref.set(intercept, once);126+ }127+128+ return yield* Effect.scoped(backend(request)).pipe(129+ Effect.provide(spawner)130+ );131+ }),132+ });133+134+ const store = yield* RepoHost.pipe(135+ Effect.provide(136+ RepoHostLocal.layer({ remoteBase, root }).pipe(137+ Layer.provide(Layer.succeed(Fetch, fetch))138+ )139+ )140+ );141+142+ const fake = fakeArtifactsBinding(143+ options.wrap === undefined ? store : options.wrap(store),144+ options145+ );146+147+ // The fake's handles dispose as a no-op; this wrapper counts each handle148+ // `get` gave out against the disposals, and keeps each token minted.149+ const run = yield* FiberSet.makeRuntimePromise();150+ const counts = { disposed: 0, gets: 0 };151+ const tokens: { id: string; plaintext: string }[] = [];152+153+ const binding: Artifacts = {154+ ...fake,155+ get: (name) =>156+ run(157+ Effect.promise(() => fake.get(name)).pipe(158+ Effect.map((repo): ArtifactsRepo => {159+ counts.gets += 1;160+161+ return {162+ ...repo,163+ createToken: (scope, ttl) =>164+ run(165+ Effect.promise(() => repo.createToken(scope, ttl)).pipe(166+ Effect.tap((token) =>167+ Effect.sync(() => tokens.push(token))168+ )169+ )170+ ),171+ [Symbol.dispose]: () => {172+ counts.disposed += 1;173+ repo[Symbol.dispose]();174+ },175+ };176+ })177+ )178+ ),179+ };180+181+ return {182+ binding,183+ counts,184+ fake,185+ fetch,186+ intercept,187+ layer: RepoHostBinding.layer(binding).pipe(188+ Layer.provide(Layer.succeed(Fetch, fetch))189+ ),190+ seen,191+ store,192+ tokens,193+ };194+ });195+196+type World = Effect.Success<ReturnType<typeof world>>;197+198+/** A test body over a fresh world, with the binding's `RepoHost` in scope. */199+const within = <A, E>(200+ body: (201+ world: World202+ ) => Effect.Effect<203+ A,204+ E,205+ RepoHost | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner206+ >,207+ options?: Parameters<typeof world>[0]208+) =>209+ Effect.gen(function* () {210+ const made = yield* world(options);211+212+ return yield* body(made).pipe(Effect.provide(made.layer));213+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));214+215+describeRepoHost(216+ "binding",217+ Layer.unwrap(Effect.map(world(), ({ layer }) => layer)).pipe(218+ Layer.provide(NodeServices.layer)219+ ),220+ {221+ importUrl: (name) =>222+ RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),223+ }224+);225+226+/** A repo `name` with one commit on `main`, and the client that made it. */227+const seeded = (name: RepoName) =>228+ Effect.gen(function* () {229+ const repos = yield* RepoHost;230+ const client = yield* gitClient(memoryFs());231+ const first = yield* client.commit("first", [["a.txt", "1"]]);232+233+ yield* repos.create(name).pipe(Effect.orDie);234+ yield* repos235+ .push(name, client.source, [236+ { from: Option.none(), ref: main, to: first },237+ ])238+ .pipe(Effect.orDie);239+240+ return { client, first };241+ });242+243+describe("the Workers binding's surprises, typed", () => {244+ // S1 #22: under `wrangler dev`, the binding throws plain `Error`s.245+ it.live(246+ "reads a missing repo as RepoNotFound when errors carry no code",247+ () =>248+ within(249+ () =>250+ Effect.gen(function* () {251+ const repos = yield* RepoHost;252+ const missing = RepoName.make("missing");253+ const taken = RepoName.make("taken");254+255+ yield* repos.create(taken).pipe(Effect.orDie);256+257+ expect(258+ yield* Effect.flip(259+ repos.readFile(260+ missing,261+ Revision.Branch({ name: BranchName.make("main") }),262+ RepoPath.make("a.txt")263+ )264+ )265+ ).toStrictEqual(new RepoNotFound({ name: missing }));266+ expect(yield* Effect.flip(repos.refs(missing))).toStrictEqual(267+ new RepoNotFound({ name: missing })268+ );269+ expect(yield* Effect.flip(repos.create(taken))).toStrictEqual(270+ new RepoExists({ name: taken })271+ );272+ expect(yield* Effect.flip(repos.fork(taken, taken))).toStrictEqual(273+ new RepoExists({ name: taken })274+ );275+ }),276+ { codeless: true }277+ )278+ );279+280+ // S7 #2: under load a fork answers 500 after making the repo, and a retry281+ // answers 409. The fork's name is the claim's, so the retry converges.282+ it.live.each([283+ { codeless: false, label: "with codes" },284+ { codeless: true, label: "without codes" },285+ ])(286+ "forks once through a 500 then an already-exists, $label",287+ ({ codeless }) =>288+ within(289+ ({ fake }) =>290+ Effect.gen(function* () {291+ const repos = yield* RepoHost;292+ const base = RepoName.make("demo");293+ const name = RepoName.make("demo--fix--alice");294+ const { first } = yield* seeded(base);295+296+ const created = yield* repos.fork(base, name).pipe(Effect.orDie);297+ const listed = yield* Effect.promise(() => fake.list());298+299+ expect(created).toStrictEqual({300+ name,301+ remote: `${remoteBase}/${name}.git`,302+ });303+ expect(304+ listed.repos.map((repo) => repo.name).toSorted()305+ ).toStrictEqual([base, name]);306+ expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(307+ new Map([[main, first]])308+ );309+ }),310+ { codeless, forkFailures: 1 }311+ )312+ );313+314+ it.live("reads a fork still in progress as ForkInProgress", () =>315+ within(316+ () =>317+ Effect.gen(function* () {318+ const repos = yield* RepoHost;319+ const base = RepoName.make("demo");320+ const name = RepoName.make("demo--fix--bob");321+322+ yield* seeded(base);323+324+ expect(yield* Effect.flip(repos.fork(base, name))).toStrictEqual(325+ new ForkInProgress({ name })326+ );327+ }),328+ {329+ wrap: (host) => ({330+ ...host,331+ fork: (_base, name) => Effect.fail(new ForkInProgress({ name })),332+ }),333+ }334+ )335+ );336+337+ // S2 #9: one side-band 3 packet and no report.338+ it.live("reads a busy receive-pack as HostBusy, and moves nothing", () =>339+ within(({ intercept }) =>340+ Effect.gen(function* () {341+ const repos = yield* RepoHost;342+ const name = RepoName.make("busy");343+ const { client, first } = yield* seeded(name);344+345+ const second = yield* client.commit(346+ "second",347+ [["a.txt", "2"]],348+ [first]349+ );350+351+ const update = { from: Option.some(first), ref: main, to: second };352+353+ yield* Ref.set(354+ intercept,355+ Option.some(() => Effect.succeedSome(busyReply()))356+ );357+358+ expect(359+ yield* Effect.flip(repos.push(name, client.source, [update]))360+ ).toStrictEqual(new HostBusy({ name }));361+ expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(362+ new Map([[main, first]])363+ );364+ expect(365+ yield* repos.push(name, client.source, [update]).pipe(Effect.orDie)366+ ).toStrictEqual([RefOutcome.Updated({ ref: main })]);367+ })368+ )369+ );370+371+ // git's receive-pack checks the old value the push names (spec §7.4).372+ it.live(373+ "reports a ref that moved during the push as Stale at its new tip",374+ () =>375+ within(({ intercept, store }) =>376+ Effect.gen(function* () {377+ const repos = yield* RepoHost;378+ const name = RepoName.make("raced");379+ const { client, first } = yield* seeded(name);380+ const ours = yield* client.commit("ours", [["a.txt", "2"]], [first]);381+382+ const theirs = yield* client.commit(383+ "theirs",384+ [["a.txt", "3"]],385+ [first]386+ );387+388+ yield* Ref.set(389+ intercept,390+ Option.some(() =>391+ store392+ .push(name, client.source, [393+ { from: Option.some(first), ref: main, to: theirs },394+ ])395+ .pipe(Effect.orDie, Effect.as(Option.none()))396+ )397+ );398+399+ expect(400+ yield* repos401+ .push(name, client.source, [402+ { from: Option.some(first), ref: main, to: ours },403+ ])404+ .pipe(Effect.orDie)405+ ).toStrictEqual([406+ RefOutcome.Stale({ ref: main, tip: Option.some(theirs) }),407+ ]);408+ })409+ )410+ );411+412+ // S1 #4: Artifacts takes any update whose old value matches, and `/memory`413+ // and `/local` apply it too: the compare-and-swap is the only check.414+ it.live(415+ "moves a ref whose tip is `from` to a `to` that is not a fast-forward",416+ () =>417+ within(() =>418+ Effect.gen(function* () {419+ const repos = yield* RepoHost;420+ const name = RepoName.make("rewound");421+ const { client, first } = yield* seeded(name);422+ const unrelated = yield* client.commit("unrelated", [["b.txt", "1"]]);423+424+ expect(425+ yield* Effect.exit(426+ repos.push(name, client.source, [427+ { from: Option.some(first), ref: main, to: unrelated },428+ ])429+ )430+ ).toStrictEqual(Exit.succeed([RefOutcome.Updated({ ref: main })]));431+ expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(432+ new Map([[main, unrelated]])433+ );434+ })435+ )436+ );437+438+ // The Lander moves its mirror ref to a landing the store already holds,439+ // pushing from a scratch repo that holds none of its objects.440+ it.live(441+ "moves a ref to a commit the store has, from a source that has none of it",442+ () =>443+ within(() =>444+ Effect.gen(function* () {445+ const repos = yield* RepoHost;446+ const name = RepoName.make("mirrored");447+ const { client, first } = yield* seeded(name);448+ const empty = yield* gitClient(memoryFs());449+450+ const second = yield* client.commit(451+ "second",452+ [["a.txt", "2"]],453+ [first]454+ );455+456+ yield* repos457+ .push(name, client.source, [458+ { from: Option.none(), ref: landed, to: first },459+ { from: Option.some(first), ref: main, to: second },460+ ])461+ .pipe(Effect.orDie);462+463+ expect(464+ yield* Effect.exit(465+ repos.push(name, empty.source, [466+ { from: Option.some(first), ref: landed, to: second },467+ ])468+ )469+ ).toStrictEqual(Exit.succeed([RefOutcome.Updated({ ref: landed })]));470+ expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(471+ new Map([472+ [landed, second],473+ [main, second],474+ ])475+ );476+ })477+ )478+ );479+480+ // Artifacts' `readTree` throws `INTERNAL_ERROR` for an object that is no481+ // tree; the other stores read no tree there (202 Comment 5).482+ it.live("reads no tree at a blob's id or a commit's id", () =>483+ within(484+ () =>485+ Effect.gen(function* () {486+ const repos = yield* RepoHost;487+ const name = RepoName.make("kinds");488+ const { first } = yield* seeded(name);489+490+ const commit = yield* repos491+ .readCommit(name, first)492+ .pipe(Effect.orDie);493+494+ const tree = Option.getOrThrow(495+ Option.map(commit, (read) => read.tree)496+ );497+498+ const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);499+ const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;500+501+ expect(blob).not.toBe(tree);502+ expect(yield* Effect.exit(repos.readTree(name, blob))).toStrictEqual(503+ Exit.succeed(Option.none())504+ );505+ expect(506+ yield* Effect.exit(repos.readTree(name, ObjectId.make(first)))507+ ).toStrictEqual(Exit.succeed(Option.none()));508+ }),509+ {510+ wrap: (host) => ({511+ ...host,512+ readTree: (repo, sha) =>513+ Effect.gen(function* () {514+ const tree = yield* host.readTree(repo, sha);515+ const blob = yield* host.readBlob(repo, sha);516+ const commit = yield* host.readCommit(repo, CommitSha.make(sha));517+518+ return Option.isNone(tree) &&519+ (Option.isSome(blob) || Option.isSome(commit))520+ ? yield* Effect.die(521+ Object.assign(new Error("An internal error occurred."), {522+ code: "INTERNAL_ERROR",523+ name: "ArtifactsError",524+ numericCode: 10_400,525+ })526+ )527+ : tree;528+ }),529+ }),530+ }531+ )532+ );533+});534+535+describe("tokens and handles the binding takes", () => {536+ it.live(537+ "sends each minted token only to the repo's own remote, then revokes it",538+ () =>539+ within(({ fake, seen, tokens }) =>540+ Effect.gen(function* () {541+ const repos = yield* RepoHost;542+ const name = RepoName.make("tokens");543+ const { client, first } = yield* seeded(name);544+545+ const second = yield* client.commit(546+ "second",547+ [["a.txt", "2"]],548+ [first]549+ );550+551+ yield* Ref.set(seen, []);552+ tokens.length = 0;553+554+ yield* repos555+ .push(name, client.source, [556+ { from: Option.some(first), ref: main, to: second },557+ ])558+ .pipe(Effect.orDie);559+ yield* repos.refs(name).pipe(Effect.orDie);560+561+ const requests = yield* Ref.get(seen);562+563+ const repo = yield* Effect.acquireRelease(564+ Effect.promise(() => fake.get(name)),565+ (handle) =>566+ Effect.sync(() => {567+ handle[Symbol.dispose]();568+ })569+ );570+571+ const revoked = yield* Effect.forEach(tokens, ({ id }) =>572+ Effect.promise(() => repo.revokeToken(id))573+ );574+575+ expect(tokens.length).toBeGreaterThan(0);576+ expect(requests.length).toBeGreaterThan(0);577+ expect(578+ requests.every(579+ ({ authorization, url }) =>580+ url.startsWith(`${remoteBase}/${name}.git/`) &&581+ tokens.some(582+ ({ plaintext }) => authorization === `Bearer ${plaintext}`583+ )584+ )585+ ).toBeTruthy();586+ // Revoked already: a second revoke finds nothing.587+ expect(revoked.every((again) => !again)).toBeTruthy();588+ })589+ )590+ );591+592+ it.live(593+ "disposes every repo handle it opened, after success or failure",594+ () =>595+ within(({ counts, intercept }) =>596+ Effect.gen(function* () {597+ const repos = yield* RepoHost;598+ const name = RepoName.make("handles");599+ const missing = RepoName.make("missing");600+ const { client, first } = yield* seeded(name);601+602+ const second = yield* client.commit(603+ "second",604+ [["a.txt", "2"]],605+ [first]606+ );607+608+ const at = Revision.Branch({ name: BranchName.make("main") });609+610+ yield* repos611+ .push(name, client.source, [612+ { from: Option.some(first), ref: main, to: second },613+ ])614+ .pipe(Effect.orDie);615+ yield* repos.refs(name).pipe(Effect.orDie);616+ yield* repos.remote(name).pipe(Effect.orDie);617+ yield* repos618+ .readFile(name, at, RepoPath.make("a.txt"))619+ .pipe(Effect.orDie);620+ yield* repos.log(name, at, 5).pipe(Effect.orDie);621+ yield* repos.readCommit(name, second).pipe(Effect.orDie);622+623+ const token = yield* repos624+ .mintToken(name, "read", Duration.minutes(5))625+ .pipe(Effect.orDie);626+627+ yield* repos.revokeToken(name, token.id).pipe(Effect.orDie);628+ yield* repos629+ .fork(name, RepoName.make("handles--fork"))630+ .pipe(Effect.orDie);631+ yield* Ref.set(632+ intercept,633+ Option.some(() => Effect.succeedSome(busyReply()))634+ );635+636+ const third = yield* client.commit(637+ "third",638+ [["a.txt", "3"]],639+ [second]640+ );641+642+ expect(643+ yield* Effect.flip(644+ repos.push(name, client.source, [645+ { from: Option.some(second), ref: main, to: third },646+ ])647+ )648+ ).toStrictEqual(new HostBusy({ name }));649+ expect(yield* Effect.flip(repos.refs(missing))).toStrictEqual(650+ new RepoNotFound({ name: missing })651+ );652+ expect(counts.gets).toBeGreaterThan(5);653+ expect(counts.disposed).toBe(counts.gets);654+ })655+ )656+ );657+});658+659+describe("git smart HTTP over the Fetch port", () => {660+ const token = Redacted.make("test-token");661+662+ it.live(663+ "lists refs, pushes one compare-and-swap per ref, and fetches a ref",664+ () =>665+ within(({ fetch, store }) =>666+ Effect.gen(function* () {667+ const name = RepoName.make("wire");668+ const client = yield* gitClient(memoryFs());669+ const first = yield* client.commit("first", [["a.txt", "1"]]);670+671+ const second = yield* client.commit(672+ "second",673+ [["a.txt", "2"]],674+ [first]675+ );676+677+ const remote = `${remoteBase}/${name}.git`;678+679+ yield* store.create(name).pipe(Effect.orDie);680+681+ const outcomes = yield* pushRefs({682+ remote,683+ source: client.source,684+ token,685+ updates: [686+ { from: Option.none(), ref: main, to: second },687+ { from: Option.some(first), ref: landed, to: second },688+ ],689+ });690+691+ const fs = memoryFs();692+693+ const fetched = yield* fetchInto({694+ depth: 1,695+ fs,696+ gitdir: "/scratch.git",697+ ref: "main",698+ remote,699+ token,700+ });701+702+ const absent = yield* fetchInto({703+ fs,704+ gitdir: "/scratch.git",705+ ref: "absent",706+ remote,707+ token,708+ });709+710+ const read = yield* Effect.promise(() =>711+ readCommit({ fs, gitdir: "/scratch.git", oid: second })712+ );713+714+ expect(outcomes).toStrictEqual([715+ RefOutcome.Updated({ ref: main }),716+ RefOutcome.Stale({ ref: landed, tip: Option.none() }),717+ ]);718+ expect(yield* listRefs(remote, token)).toStrictEqual(719+ new Map<RefName, CommitSha>([[main, second]])720+ );721+ expect(fetched).toStrictEqual(Option.some(second));722+ expect(absent).toStrictEqual(Option.none());723+ expect(read.commit.message).toBe("second\n");724+ }).pipe(Effect.provideService(Fetch, fetch))725+ )726+ );727+728+ it.live("names the repo a remote does not serve", () =>729+ within(({ fetch }) =>730+ Effect.gen(function* () {731+ const name = RepoName.make("nowhere");732+ const remote = `${remoteBase}/${name}.git`;733+734+ expect(yield* Effect.flip(listRefs(remote, token))).toStrictEqual(735+ new RepoNotFound({ name })736+ );737+ expect(738+ yield* Effect.flip(739+ fetchInto({740+ fs: memoryFs(),741+ gitdir: "/x.git",742+ ref: "main",743+ remote,744+ token,745+ })746+ )747+ ).toStrictEqual(new RepoNotFound({ name }));748+ }).pipe(Effect.provideService(Fetch, fetch))749+ )750+ );751+});modified:packages/artifacts/package.json+1 added
22 unmodified lines2324252627282930314 unmodified lines22 unmodified lines "isomorphic-git": "1.43.0" }, "devDependencies": { "@cloudflare/workers-types": "5.20261006.1", "@effect/platform-node": "4.0.1", "@effect/vitest": "catalog:", "@repo/config": "workspace:*", "@repo/testkit": "workspace:*", "@types/node": "26.6.4",4 unmodified linesmodified:bun.lock+1 added
59 unmodified lines60 "isomorphic-git": "1.43.0",61 },62 "devDependencies": {63 "@cloudflare/workers-types": "5.20261006.1",64+ "@effect/platform-node": "4.0.1",65 "@effect/vitest": "catalog:",66 "@repo/config": "workspace:*",67 "@repo/testkit": "workspace:*",68 "@types/node": "26.6.4",1013 unmodified lines