Skip to content
Myr

Add RepoHost over the Workers Artifacts binding, with git smart HTTP through Fetch and the spikes' surprises typed

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

- src/repo-host/binding.ts: RepoHostBinding.layer(binding). Each thrown value is read once at the promise boundary into its code, or the code its message names when it has none (S1 #22: wrangler dev's plain Errors): not found, already exists, fork in progress, internal error. fromArtifactsError maps them to RepoNotFound, RepoExists and ForkInProgress; anything else is a defect with the error as its cause. - fork retries a 500 once; an already-exists or a second 500 after it may be the fork the first made (S7), so it is confirmed with get plus a ref listing that has main, else ForkInProgress for the caller to retry. - Reads use the binding's own methods with short branch names or commit ids (S1 #20); readTree at a blob's id is None though Artifacts throws INTERNAL_ERROR there; tree modes 40000 become 040000; log pages past 1000. import maps INVALID_INPUT, INVALID_URL, REMOTE_AUTH_REQUIRED, UPSTREAM_UNAVAILABLE, MEMORY_LIMIT and NOT_FOUND to ImportRefused. - refs and push mint a token for the one call (5 min), send it only as Authorization: Bearer to the remote's own origin, as the live S1 and S2 runs did, and revoke it before the handle is disposed. Every handle is acquired and released in a scope. mintToken clamps the ttl to Artifacts' 60 s to a year and reports the earlier of the two clocks' expiries. - src/repo-host/smart-http.ts (shared with /rest, 218): listRefs, pushRefs and fetchInto over an isomorphic-git HTTP client built on Fetch. One non-force push per ref, in order; the push's own discovery is the compare-and-swap check (onPrePush), so the old value sent is the one checked and a stale ref is Stale before any pack is built. A receive-pack "stale ref", "incorrect old value provided" (git 2.56, seen in the race test) or non-fast-forward is Stale at a fresh tip; a side-band 3 artifacts_git_receive_pack_busy is HostBusy (S2 #9); a 404 is RepoNotFound. Nothing is retried. - Departures, each in the issue's Comments: listRefs fails with RepoNotFound only; fetchInto returns Option (None for an absent ref); no separate preflight listing; fromArtifactsError takes the decoded Thrown and is private. - Outside the territory, for the Check: @effect/platform-node 4.0.1 as an artifacts devDependency (already in bun.lock), so its tests get a ChildProcessSpawner for real git http-backend. It is the dependency half of 208's item 1 for 299. - Tests: binding.test.ts (red first against a stub whose methods all fail RepoNotFound) runs describeRepoHost over the binding on testkit's fake over RepoHostLocal, served by git http-backend, import cases included; plus code-less RepoNotFound and RepoExists, fork 500 then already-exists with and without codes leaving one repo, FORK_IN_PROGRESS, busy without moving a ref, a ref moved mid-push, no forced non-fast-forward, no tree at a blob's id, every token sent only to the repo's remote and revoked, every handle disposed after success and failure, and smart HTTP on its own. Planted bugs (no confirmation, no message mapping, no dispose, no CAS check, no busy check, no revoke) each failed by assertion. - binding-live.test.ts: opt-in (LIVE_ARTIFACTS=1 plus a harness module path), never in verify; fresh prefix per test, deletes what it made, refuses the witness namespace. The harness (getPlatformProxy's binding and fetch) lives outside the repo, per spec 7.4. - ASSUMPTION: Artifacts answers 404 over smart HTTP for a repo it lacks; getPlatformProxy serves artifacts remote bindings as wrangler dev does.

authored by oscabriel · committed by oscabriel · parent 7b4ffd5 · Browse files · 6 files+1885 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+1885 added−0 removed

  • tests:+874 added−0 removed
  • other:+1011 added−0 removed

6 files+1885 added−0 removed

added:packages/artifacts/src/repo-host/binding.ts+534 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 */18import {19 Data,20 DateTime,21 Duration,22 Effect,23 Layer,24 Match,25 Option,26 Predicate,27 Redacted,28 Schema,29} from "effect";3031import { Fetch } from "../fetch.ts";32import {33 Commit,34 ForkInProgress,35 ImportRefused,36 RefName,37 RepoExists,38 RepoHost,39 RepoNotFound,40 Revision,41 TreeEntry,42} from "../repo-host.ts";43import type { RepoName, RepoToken, TokenScope } from "../repo-host.ts";44import { listRefs, pushRefs } from "./smart-http.ts";4546const 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]);6162type Code = typeof Code.Type;6364const isCode = Schema.is(Code);6566/**67 * The codes a message names when the error carries none (S1 #22): Artifacts'68 * words, the fake's, and the code itself.69 */70const 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])[];7677/**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 */81class Thrown extends Data.TaggedError("Thrown")<{82 readonly code: Option.Option<Code>;83 readonly message: string;84 readonly error: unknown;85}> {}8687/** An `INTERNAL_ERROR` from a fork, which may still have made the repo (S7 #2). */88class Internal extends Data.TaggedError("Internal")<{89 readonly thrown: Thrown;90}> {}9192/** A promise of the binding's, failing with what it threw, read. */93const attempt = <A>(run: () => Promise<A>) =>94 Effect.tryPromise({95 catch: (error) => {96 const message = error instanceof Error ? error.message : String(error);9798 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 );104105 return new Thrown({ code, error, message });106 },107 try: run,108 });109110const threw =111 (code: Code) =>112 (thrown: Thrown): boolean =>113 Option.contains(thrown.code, code);114115/**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 */119const 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 );135136/** A call about the repo `name`, its errors read as the port's. */137const call = <A>(name: RepoName, run: () => Promise<A>) =>138 attempt(run).pipe(139 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))140 );141142const asDefect = ({ error }: Thrown) => Effect.die(error);143144/** The port's reads and token calls fail only with `RepoNotFound`. */145const 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 );151152const main = RefName.make("refs/heads/main");153154/** How long a token minted for one call lives; it is revoked after the call. */155const CALL_TOKEN_TTL = Duration.minutes(5);156157// Artifacts takes a token's ttl in whole seconds, from a minute to a year.158const MIN_TTL_SECONDS = 60;159160const MAX_TTL_SECONDS = 31_536_000;161162const secondsOf = (ttl: Duration.Duration) =>163 Math.min(164 Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),165 MAX_TTL_SECONDS166 );167168/** `log` reads at most this many commits per call. */169const LOG_PAGE = 1000;170171/** The codes `import` refuses a source with: not git, not public, not reachable, too big. */172const 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]);180181/** The binding's name for a revision: never `refs/…` (S1 #20). */182const refOf = (at: Revision) =>183 Revision.$match(at, {184 Branch: ({ name }) => name,185 Commit: ({ sha }) => sha,186 });187188const bytesOf = (blob: Blob) =>189 attempt(() => blob.arrayBuffer()).pipe(190 Effect.map((buffer) => new Uint8Array(buffer)),191 Effect.catchTag("Thrown", asDefect)192 );193194const decodeCommit = Schema.decodeUnknownEffect(Commit);195196const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));197198const 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);207208// Artifacts gives canonical modes: a folder is `40000`, as git stores it, not209// `040000`, as `ls-tree` prints it and the port has it.210const entriesOf = (entries: readonly ArtifactsTreeEntry[]) =>211 decodeEntries(212 entries.map((entry) => {213 const mode = entry.mode.padStart(6, "0");214215 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);227228/** `use` over a handle to `name`, disposed after, whatever `use` came to. */229const 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 );243244/**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 */248const access = (name: RepoName, repo: ArtifactsRepo, scope: TokenScope) =>249 Effect.gen(function* () {250 const { remote } = yield* call(name, () => repo.info());251252 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 );256257 return { remote, token: Redacted.make(token.plaintext) };258 });259260const refsOf = (name: RepoName, repo: ArtifactsRepo) =>261 Effect.scoped(262 Effect.gen(function* () {263 const { remote, token } = yield* access(name, repo, "read");264265 return yield* listRefs(remote, token);266 })267 );268269/**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 */274const confirmed = (binding: Artifacts, name: RepoName) =>275 withRepo(binding, name, (repo) =>276 Effect.gen(function* () {277 const refs = yield* refsOf(name, repo);278279 if (!refs.has(main)) {280 return yield* new ForkInProgress({ name });281 }282283 const { remote } = yield* call(name, () => repo.info());284285 return { name, remote };286 })287 ).pipe(288 Effect.catchTags({289 RepoExists: Effect.die,290 RepoNotFound: () => Effect.fail(new ForkInProgress({ name })),291 })292 );293294/**295 * One fork call. The base's absence names the base; any other refusal names296 * the target, and a 500 is `Internal`, since it may have made the target.297 */298const 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 Internal({ 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 );315316/** Artifacts throws `INTERNAL_ERROR` for an object that is no tree (workers-types). */317const treeAt = (name: RepoName, repo: ArtifactsRepo, tree: string) =>318 attempt(() => repo.readTree(tree)).pipe(319 Effect.flatMap((found) =>320 found === null ? Effect.succeedNone : Effect.asSome(entriesOf(found))321 ),322 // A blob's id names no tree, as on the other stores; any other failure323 // stays one.324 Effect.catchIf(threw("INTERNAL_ERROR"), ({ error }) =>325 call(name, () => repo.readBlob(tree)).pipe(326 Effect.flatMap((blob) =>327 blob === null ? Effect.die(error) : Effect.succeedNone328 )329 )330 ),331 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))332 );333334const importFrom = (335 binding: Artifacts,336 name: RepoName,337 source: { readonly url: string; readonly branch?: string }338) =>339 attempt(() =>340 binding.import({341 source:342 source.branch === undefined343 ? { url: source.url }344 : { branch: source.branch, url: source.url },345 target: { name },346 })347 ).pipe(348 Effect.map(({ remote }) => ({ name, remote })),349 Effect.catchTag("Thrown", (thrown) =>350 Match.value(thrown).pipe(351 Match.when(threw("ALREADY_EXISTS"), () =>352 Effect.fail(new RepoExists({ name }))353 ),354 Match.when(355 ({ code }) =>356 Option.exists(code, (refused) => IMPORT_REFUSALS.has(refused)),357 ({ message }) =>358 Effect.fail(new ImportRefused({ name, reason: message }))359 ),360 Match.orElse(asDefect)361 )362 )363 );364365const log = (366 name: RepoName,367 repo: ArtifactsRepo,368 at: Revision,369 limit: number370) =>371 Effect.gen(function* () {372 const ref = refOf(at);373 const commits: Commit[] = [];374375 while (commits.length < limit) {376 const asked = Math.min(limit - commits.length, LOG_PAGE);377378 const page = yield* call(name, () =>379 repo.log({ limit: asked, offset: commits.length, ref })380 );381382 for (const metadata of page) {383 commits.push(yield* commitOf(metadata));384 }385386 if (page.length < asked) {387 break;388 }389 }390391 return commits;392 });393394const mintToken = (395 name: RepoName,396 repo: ArtifactsRepo,397 scope: TokenScope,398 ttl: Duration.Duration399) =>400 Effect.gen(function* () {401 const seconds = secondsOf(ttl);402 const now = yield* DateTime.now;403 const token = yield* call(name, () => repo.createToken(scope, seconds));404 const asked = DateTime.add(now, { seconds });405406 // Never later than either clock says: the ttl asked for, from before the407 // call, or the store's own expiry.408 const expiresAt = Option.match(DateTime.make(token.expiresAt), {409 onNone: () => asked,410 onSome: (stated) => DateTime.min(asked, stated),411 });412413 return {414 expiresAt,415 id: token.id,416 scope,417 secret: Redacted.make(token.plaintext),418 } satisfies RepoToken;419 });420421const make = (binding: Artifacts) =>422 Effect.gen(function* () {423 // The service alone: the layer's whole context would carry its Scope, and424 // every call's finalizers would wait for the layer's end.425 const fetch = yield* Fetch;426427 /** A read of `name`'s, failing only with `RepoNotFound`. */428 const read = <A>(429 name: RepoName,430 use: (431 repo: ArtifactsRepo432 ) => Effect.Effect<A, RepoNotFound | RepoExists | ForkInProgress, Fetch>433 ) =>434 onlyNotFound(withRepo(binding, name, use)).pipe(435 Effect.provideService(Fetch, fetch)436 );437438 return RepoHost.of({439 create: (name) =>440 call(name, () => binding.create(name)).pipe(441 Effect.map(({ remote }) => ({ name, remote })),442 Effect.catchTags({443 ForkInProgress: Effect.die,444 RepoNotFound: Effect.die,445 })446 ),447 // S7: a 500 is tried once more; an already-exists or a second 500 after448 // it may be the fork the first made, so it is confirmed, not trusted.449 fork: (base, name) =>450 forkOnce(binding, base, name).pipe(451 Effect.catchTag("Internal", () =>452 forkOnce(binding, base, name).pipe(453 Effect.catchTags({454 Internal: () => confirmed(binding, name),455 RepoExists: () => confirmed(binding, name),456 })457 )458 ),459 Effect.provideService(Fetch, fetch)460 ),461 importFrom: (name, source) => importFrom(binding, name, source),462 log: (name, at, limit) =>463 read(name, (repo) => log(name, repo, at, limit)),464 mintToken: (name, scope, ttl) =>465 read(name, (repo) => mintToken(name, repo, scope, ttl)),466 push: (name, source, updates) =>467 withRepo(binding, name, (repo) =>468 Effect.scoped(469 Effect.gen(function* () {470 const { remote, token } = yield* access(name, repo, "write");471472 return yield* pushRefs({ remote, source, token, updates });473 })474 )475 ).pipe(476 Effect.catchTags({477 ForkInProgress: Effect.die,478 RepoExists: Effect.die,479 }),480 Effect.provideService(Fetch, fetch)481 ),482 readBlob: (name, blob) =>483 read(name, (repo) =>484 call(name, () => repo.readBlob(blob)).pipe(485 Effect.flatMap((found) =>486 found === null487 ? Effect.succeedNone488 : Effect.asSome(bytesOf(found))489 )490 )491 ),492 readCommit: (name, sha) =>493 read(name, (repo) =>494 call(name, () => repo.readCommit(sha)).pipe(495 Effect.flatMap((found) =>496 found === null497 ? Effect.succeedNone498 : Effect.asSome(commitOf(found))499 )500 )501 ),502 readFile: (name, at, path) =>503 read(name, (repo) =>504 call(name, () => repo.readFile({ path, ref: refOf(at) })).pipe(505 Effect.flatMap((found) =>506 found === null507 ? Effect.succeedNone508 : Effect.asSome(bytesOf(found))509 )510 )511 ),512 readTree: (name, tree) => read(name, (repo) => treeAt(name, repo, tree)),513 refs: (name) => read(name, (repo) => refsOf(name, repo)),514 remote: (name) =>515 read(name, (repo) =>516 call(name, () => repo.info()).pipe(Effect.map(({ remote }) => remote))517 ),518 remove: (name) =>519 attempt(() => binding.delete(name)).pipe(520 Effect.catchTag("Thrown", asDefect)521 ),522 revokeToken: (name, id) =>523 read(name, (repo) => call(name, () => repo.revokeToken(id))),524 });525 });526527/**528 * Artifacts through the Workers binding, the platform's `RepoHost` in529 * production. Refs and pushes go over git smart HTTP through `Fetch`.530 */531export const RepoHostBinding = {532 layer: (binding: Artifacts): Layer.Layer<RepoHost, never, Fetch> =>533 Layer.effect(RepoHost, make(binding)),534};
added:packages/artifacts/src/repo-host/smart-http.ts+475 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 */10import { CommitSha } from "@repo/protocol/ids";11import {12 Data,13 Effect,14 FiberSet,15 Match,16 Option,17 Redacted,18 Schema,19 Stream,20} from "effect";21import type { Array } from "effect";22import {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";33import type {34 FsClient,35 GitHttpRequest,36 GitHttpResponse,37 HttpClient,38} from "isomorphic-git";3940import { Fetch } from "../fetch.ts";41import {42 HostBusy,43 RefName,44 RefOutcome,45 RepoName,46 RepoNotFound,47} from "../repo-host.ts";48import type { PushSource, RefUpdate } from "../repo-host.ts";4950/** What isomorphic-git or a response body threw, before it is read. */51class GitFailure extends Data.TaggedError("GitFailure")<{52 readonly cause: unknown;53}> {}5455/** isomorphic-git's no-commit id: a ref that is absent. */56const ABSENT = "0".repeat(40);5758// 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 that refuses to rewind a ref.60// `fetch first` is git's client-side word and never reaches a server.61const MOVED = ["stale ref", "incorrect old value provided", "non-fast-forward"];6263// Artifacts' whole reply to a push it is too busy for: one side-band 364// (fatal) packet and no report (S2 #9).65const BUSY = "artifacts_git_receive_pack_busy";6667// 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.69const PUSH_REMOTE = "repo-host-push";7071const FETCH_REMOTE = "repo-host-fetch";7273const decodeRepo = Schema.decodeUnknownOption(RepoName);7475const decodeRef = Schema.decodeUnknownOption(RefName);7677const decodeSha = Schema.decodeUnknownOption(CommitSha);7879/** The repo a remote names: its last path segment, less `.git`. */80const 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 );9495const concat = (chunks: readonly Uint8Array[]) => {96 const all = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));97 let at = 0;9899 for (const chunk of chunks) {100 all.set(chunk, at);101 at += chunk.length;102 }103104 return all;105};106107/**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 */111const 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));116117/** One chunk as the async iterator isomorphic-git reads a response body from. */118const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {119 const chunks = [bytes];120121 const iterator: AsyncIterableIterator<Uint8Array> = {122 [Symbol.asyncIterator]: () => iterator,123 next: () => {124 const chunk = chunks.shift();125126 return Promise.resolve(127 chunk === undefined128 ? { done: true, value: undefined }129 : { done: false, value: chunk }130 );131 },132 };133134 return iterator;135};136137/** The side-band 3 (fatal) messages in a reply's top-level packet lines. */138const fatalMessages = (bytes: Uint8Array) => {139 const messages: string[] = [];140 const text = new TextDecoder();141 let at = 0;142143 while (at + 4 <= bytes.length) {144 const length = Number.parseInt(text.decode(bytes.slice(at, at + 4)), 16);145146 if (Number.isNaN(length)) {147 break;148 }149150 // A flush (`0000`) or a delimiter carries no payload.151 if (length < 4) {152 at += 4;153 continue;154 }155156 if (bytes[at + 4] === 3) {157 messages.push(text.decode(bytes.slice(at + 5, at + length)));158 }159160 at += length;161 }162163 return messages;164};165166const isReceivePack = (url: string) =>167 new URL(url).pathname.endsWith("/git-receive-pack");168169/**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 */175const 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);179180 const exchange = (request: GitHttpRequest) =>181 Effect.gen(function* () {182 const headers = new Headers(request.headers ?? {});183184 if (new URL(request.url).origin === origin) {185 headers.set("authorization", `Bearer ${Redacted.value(token)}`);186 }187188 const method = request.method ?? "GET";189190 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 );199200 // 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 }205206 const bytes = new Uint8Array(207 yield* Effect.tryPromise({208 catch: (cause) => new GitFailure({ cause }),209 try: () => response.arrayBuffer(),210 })211 );212213 if (214 isReceivePack(request.url) &&215 fatalMessages(bytes).some((message) => message.includes(BUSY))216 ) {217 return yield* new HostBusy({ name });218 }219220 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 });229230 return {231 request: (request: GitHttpRequest) => run(exchange(request)),232 } satisfies HttpClient;233 });234235/**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 */240const 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 });253254/** Every ref the remote lists, custom refs included; never `HEAD` or a peeled tag. */255const 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 );274275/**276 * Every ref the remote lists, as `ls-remote` lists them: what reads by name277 * cannot reach (S1 #20).278 */279export 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);286287 return yield* refsAt(remote, yield* httpFor(remote, token, name));288 })289 );290291const isMoved = (reason: string) =>292 MOVED.some((moved) => reason.includes(moved));293294/** Whether a push of `ref` was refused because the ref moved. */295const refusedAsMoved = ({ cause }: GitFailure, ref: RefName) =>296 Match.value(cause).pipe(297 Match.when(Match.instanceOf(Errors.PushRejectedError), () => true),298 Match.when(Match.instanceOf(Errors.GitPushError), (failed) =>299 isMoved(failed.data.result.refs[ref]?.error ?? "")300 ),301 Match.orElse(() => false)302 );303304/**305 * One ref's compare-and-swap. The push's own ref discovery is the check: if306 * the tip it finds is not `from`, the push stops there, before any pack is307 * built, so the old value the push names is the one checked. It never forces:308 * a push that is not a fast-forward, or a ref that moved after the check, is309 * `Stale` at the tip a fresh listing shows.310 */311const 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;320321 const pushed = yield* git((signal) =>322 push({323 ...source,324 http,325 onPrePush: ({ remoteRef }) => {326 found = remoteRef.oid;327328 return found === expected;329 },330 ref: update.to,331 remote: PUSH_REMOTE,332 remoteRef: update.ref,333 signal,334 url: remote,335 })336 ).pipe(337 Effect.as(RefOutcome.Updated({ ref: update.ref })),338 Effect.catchTag("GitFailure", (failure) =>339 Match.value(failure).pipe(340 Match.when(341 ({ cause }) => cause instanceof Errors.UserCanceledError,342 () =>343 Effect.succeed(344 RefOutcome.Stale({345 ref: update.ref,346 tip: Option.filter(decodeSha(found), (sha) => sha !== ABSENT),347 })348 )349 ),350 Match.when(351 (refused) => refusedAsMoved(refused, update.ref),352 () =>353 refsAt(remote, http).pipe(354 Effect.map((refs) =>355 RefOutcome.Stale({356 ref: update.ref,357 tip: Option.fromNullishOr(refs.get(update.ref)),358 })359 )360 )361 ),362 Match.orElse(({ cause }) => Effect.die(cause))363 )364 )365 );366367 // isomorphic-git files a pushed ref under the push's remote in the source.368 yield* git(() =>369 deleteRef({370 ...source,371 ref: `refs/remotes/${PUSH_REMOTE}/${update.ref.replace(/^refs\/heads\//u, "")}`,372 })373 ).pipe(Effect.ignore);374375 return pushed;376 });377378/**379 * Pushes each update in order, one ref per push, since Artifacts has no380 * atomic push (S1 #6): each ref is updated or `Stale` on its own. Nothing is381 * retried; a `Stale` ref is the caller's to decide on. A busy store fails the382 * whole call with `HostBusy`, and refs before the busy one may have moved.383 */384export const pushRefs = (input: {385 readonly remote: string;386 readonly token: Redacted.Redacted;387 readonly source: PushSource;388 readonly updates: Array.NonEmptyReadonlyArray<RefUpdate>;389}): Effect.Effect<readonly RefOutcome[], RepoNotFound | HostBusy, Fetch> =>390 Effect.scoped(391 Effect.gen(function* () {392 const name = yield* repoOf(input.remote);393 const http = yield* httpFor(input.remote, input.token, name);394395 return yield* Effect.forEach(input.updates, (update) =>396 pushOne(input.remote, http, input.source, update)397 );398 })399 );400401/**402 * Fetches one ref of the remote into the repo `gitdir` in `fs` (made if403 * absent), `depth` commits deep when given; its tip, or `None` when the remote404 * has no such ref. The ref is a branch name or a full ref. The repo keeps the405 * objects and no ref, remote or tracking ref of the fetch's own.406 */407export const fetchInto = (input: {408 readonly remote: string;409 readonly token: Redacted.Redacted;410 readonly fs: FsClient;411 readonly gitdir: string;412 readonly ref: string;413 readonly depth?: number;414}): Effect.Effect<Option.Option<CommitSha>, RepoNotFound, Fetch> =>415 Effect.scoped(416 Effect.gen(function* () {417 const name = yield* repoOf(input.remote);418 const http = yield* httpFor(input.remote, input.token, name);419 const repo = { fs: input.fs, gitdir: input.gitdir };420421 yield* git(() => init({ ...repo, bare: true })).pipe(Effect.orDie);422423 // isomorphic-git files what it fetched under a configured remote's424 // refspec, so the repo has one, and its tracking refs, for as long as425 // the fetch runs.426 yield* Effect.acquireRelease(427 git(() =>428 addRemote({429 ...repo,430 force: true,431 remote: FETCH_REMOTE,432 url: input.remote,433 })434 ).pipe(Effect.orDie),435 () =>436 Effect.gen(function* () {437 const tracking = yield* git(() =>438 localRefs({ ...repo, filepath: `refs/remotes/${FETCH_REMOTE}` })439 );440441 yield* Effect.forEach(tracking, (ref) =>442 git(() =>443 deleteRef({444 ...repo,445 ref: `refs/remotes/${FETCH_REMOTE}/${ref}`,446 })447 )448 );449 yield* git(() => deleteRemote({ ...repo, remote: FETCH_REMOTE }));450 }).pipe(Effect.ignore)451 );452453 return yield* git(() =>454 fetchPack({455 ...repo,456 depth: input.depth,457 http,458 remote: FETCH_REMOTE,459 remoteRef: input.ref,460 singleBranch: true,461 tags: false,462 })463 ).pipe(464 Effect.map(({ fetchHead }) => decodeSha(fetchHead)),465 Effect.catchTags({466 GitFailure: ({ cause }) =>467 cause instanceof Errors.NotFoundError468 ? Effect.succeedNone469 : Effect.die(cause),470 // Only a push is ever busy.471 HostBusy: Effect.die,472 })473 );474 })475 );
added:packages/artifacts/test/binding-live.test.ts+176 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 */20import { describe } from "@effect/vitest";21import { Data, Effect, FiberSet, Layer, Predicate, Schema } from "effect";2223import { Fetch, FetchFailed } from "../src/fetch.ts";24import { RepoHostBinding } from "../src/repo-host/binding.ts";25import { describeRepoHost } from "./repo-host-contract.ts";2627/** The namespace another project owns (spec §4.4). */28const FORBIDDEN = "witness";2930const harnessPath = process.env.LIVE_ARTIFACTS_HARNESS;3132const live = process.env.LIVE_ARTIFACTS === "1" && harnessPath !== undefined;3334// The harness's functions, taken on trust as its doc comment types them:35// a function's signature cannot be checked at run time.3637const Start = Schema.declare((input): input is () => Promise<object> =>38 Predicate.isFunction(input)39);4041const Dispose = Schema.declare((input): input is () => Promise<void> =>42 Predicate.isFunction(input)43);4445const Send = Schema.declare(46 (input): input is (request: Request) => Promise<Response> =>47 Predicate.isFunction(input)48);4950/** What the harness's module exports. */51const HarnessModule = Schema.Struct({ live: Start });5253/** What `live()` resolves to. */54const 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});7172type Harness = typeof Harness.Type;7374class HarnessFailed extends Data.TaggedError("HarnessFailed")<{75 readonly reason: string;76}> {}7778/** The harness's `live()`, run once per test and disposed after it. */79const 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)));8687 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 );9495/** A fresh prefix: the suite's fixed names, unique to this test. */96const freshPrefix = () =>97 `live-${crypto98 .getRandomValues(new Uint32Array(2))99 .reduce((text, word) => text + word.toString(36), "")}-`;100101/**102 * The live binding with every name prefixed, and every repo made through it103 * deleted when the scope closes.104 */105const prefixed = (binding: Artifacts) =>106 Effect.gen(function* () {107 const prefix = freshPrefix();108 const run = yield* FiberSet.makeRuntimePromise();109 const made = new Set<string>();110111 const named = (name: string) => {112 made.add(`${prefix}${name}`);113114 return `${prefix}${name}`;115 };116117 yield* Effect.addFinalizer(() =>118 Effect.forEach(made, (name) =>119 Effect.tryPromise(() => binding.delete(name)).pipe(Effect.ignore)120 )121 );122123 return {124 ...binding,125 create: (name, options) => binding.create(named(name), options),126 delete: (name) => binding.delete(`${prefix}${name}`),127 get: (name) =>128 run(129 Effect.promise(() => binding.get(`${prefix}${name}`)).pipe(130 Effect.map((repo): ArtifactsRepo => ({131 ...repo,132 fork: (target, options) => repo.fork(named(target), options),133 [Symbol.dispose]: () => {134 repo[Symbol.dispose]();135 },136 }))137 )138 ),139 import: ({ source, target }) =>140 binding.import({141 source,142 target: { ...target, name: named(target.name) },143 }),144 } satisfies Artifacts;145 });146147/** The live store's `Fetch`: the harness's fetch, failing as no response. */148const fetchOver = (send: Harness["fetch"]) =>149 Fetch.of({150 fetch: (request) =>151 Effect.tryPromise({152 catch: (cause) =>153 new FetchFailed({154 reason: cause instanceof Error ? cause.message : "no response",155 url: request.url,156 }),157 try: () => send(request),158 }),159 });160161describe.runIf(live)("against live Artifacts", () => {162 // Artifacts imports only public HTTPS remotes, and its own refuse anonymous163 // reads (S1 #10), so the import cases do not run here.164 describeRepoHost(165 "binding (live)",166 Layer.unwrap(167 Effect.gen(function* () {168 const { binding, fetch } = yield* harness(harnessPath ?? "");169170 return RepoHostBinding.layer(yield* prefixed(binding)).pipe(171 Layer.provide(Layer.succeed(Fetch, fetchOver(fetch)))172 );173 })174 )175 );176});
added:packages/artifacts/test/binding.test.ts+698 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { RepoPath } from "@repo/protocol/ids";4import type { CommitSha } from "@repo/protocol/ids";5import { fakeArtifactsBinding } from "@repo/testkit/fake-artifacts-binding";6import type {7 FakeOptions,8 HostLike,9} from "@repo/testkit/fake-artifacts-binding";10import { gitClient } from "@repo/testkit/git-client";11import { httpBackend } from "@repo/testkit/http-backend";12import {13 Duration,14 Effect,15 FiberSet,16 Layer,17 Option,18 Redacted,19 Ref,20} from "effect";21import type { Scope } from "effect";22import type { ChildProcessSpawner } from "effect/process";23import { readCommit } from "isomorphic-git";2425import { Fetch, FetchFailed } from "../src/fetch.ts";26import {27 BranchName,28 ForkInProgress,29 HostBusy,30 RefName,31 RefOutcome,32 RepoExists,33 RepoHost,34 RepoName,35 RepoNotFound,36 Revision,37} from "../src/repo-host.ts";38import { RepoHostBinding } from "../src/repo-host/binding.ts";39import { RepoHostLocal } from "../src/repo-host/local.ts";40import { memoryFs } from "../src/repo-host/memory-fs.ts";41import { fetchInto, listRefs, pushRefs } from "../src/repo-host/smart-http.ts";42import { describeRepoHost } from "./repo-host-contract.ts";4344const main = RefName.make("refs/heads/main");4546/** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */47const remoteBase = "https://artifacts.test/git/projects";4849/** A packet-line holding one side-band 3 (fatal) message. */50const fatal = (message: string) => {51 const payload = new TextEncoder().encode(`\u0003${message}`);52 const length = (payload.length + 4).toString(16).padStart(4, "0");5354 return new Uint8Array([...new TextEncoder().encode(length), ...payload]);55};5657/** Artifacts' whole reply to a push it is too busy for (S2 #9): no report, no flush. */58const busyReply = () =>59 new Response(fatal("artifacts_git_receive_pack_busy\n"), {60 headers: { "content-type": "application/x-git-receive-pack-result" },61 });6263/** What one request to the store carried, as the test's `Fetch` saw it. */64interface Seen {65 readonly url: string;66 readonly authorization: string | null;67}6869/** What a test may do to the next receive-pack call before git sees it. */70type Intercept = (request: Request) => Effect.Effect<Option.Option<Response>>;7172/**73 * The binding over a fake Artifacts on local disk: a `RepoHostLocal` in a74 * temporary directory, wrapped by testkit's fake binding, whose remotes a75 * `Fetch` serves with real `git http-backend` over the same directory.76 * Every handle the binding opens is counted, and every token it mints is77 * recorded, so a test can check both came back.78 */79const world = (80 options: FakeOptions & { readonly wrap?: (host: HostLike) => HostLike } = {}81) =>82 Effect.gen(function* () {83 const root = yield* RepoHostLocal.temporaryRoot;8485 const spawner =86 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();8788 const backend = httpBackend(root);89 const seen = yield* Ref.make<readonly Seen[]>([]);90 const intercept = yield* Ref.make<Option.Option<Intercept>>(Option.none());9192 const fetch = Fetch.of({93 fetch: (request) =>94 Effect.gen(function* () {95 if (!request.url.startsWith(`${remoteBase}/`)) {96 return yield* new FetchFailed({97 reason: "no route to host",98 url: request.url,99 });100 }101102 yield* Ref.update(seen, (all) => [103 ...all,104 {105 authorization: request.headers.get("authorization"),106 url: request.url,107 },108 ]);109110 const once = yield* Ref.getAndSet(intercept, Option.none());111112 if (113 Option.isSome(once) &&114 request.url.endsWith("/git-receive-pack")115 ) {116 const reply = yield* once.value(request);117118 if (Option.isSome(reply)) {119 return reply.value;120 }121 } else if (Option.isSome(once)) {122 yield* Ref.set(intercept, once);123 }124125 return yield* Effect.scoped(backend(request)).pipe(126 Effect.provide(spawner)127 );128 }),129 });130131 const store = yield* RepoHost.pipe(132 Effect.provide(133 RepoHostLocal.layer({ remoteBase, root }).pipe(134 Layer.provide(Layer.succeed(Fetch, fetch))135 )136 )137 );138139 const fake = fakeArtifactsBinding(140 options.wrap === undefined ? store : options.wrap(store),141 options142 );143144 // The fake's handles dispose as a no-op; this wrapper counts each handle145 // `get` gave out against the disposals, and keeps each token minted.146 const run = yield* FiberSet.makeRuntimePromise();147 const counts = { disposed: 0, gets: 0 };148 const tokens: { id: string; plaintext: string }[] = [];149150 const binding: Artifacts = {151 ...fake,152 get: (name) =>153 run(154 Effect.promise(() => fake.get(name)).pipe(155 Effect.map((repo): ArtifactsRepo => {156 counts.gets += 1;157158 return {159 ...repo,160 createToken: (scope, ttl) =>161 run(162 Effect.promise(() => repo.createToken(scope, ttl)).pipe(163 Effect.tap((token) =>164 Effect.sync(() => tokens.push(token))165 )166 )167 ),168 [Symbol.dispose]: () => {169 counts.disposed += 1;170 repo[Symbol.dispose]();171 },172 };173 })174 )175 ),176 };177178 return {179 binding,180 counts,181 fake,182 fetch,183 intercept,184 layer: RepoHostBinding.layer(binding).pipe(185 Layer.provide(Layer.succeed(Fetch, fetch))186 ),187 seen,188 store,189 tokens,190 };191 });192193type World = Effect.Success<ReturnType<typeof world>>;194195/** A test body over a fresh world, with the binding's `RepoHost` in scope. */196const within = <A, E>(197 body: (198 world: World199 ) => Effect.Effect<200 A,201 E,202 RepoHost | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner203 >,204 options?: Parameters<typeof world>[0]205) =>206 Effect.gen(function* () {207 const made = yield* world(options);208209 return yield* body(made).pipe(Effect.provide(made.layer));210 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));211212describeRepoHost(213 "binding",214 Layer.unwrap(Effect.map(world(), ({ layer }) => layer)).pipe(215 Layer.provide(NodeServices.layer)216 ),217 {218 importUrl: (name) =>219 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),220 }221);222223/** A repo `name` with one commit on `main`, and the client that made it. */224const seeded = (name: RepoName) =>225 Effect.gen(function* () {226 const repos = yield* RepoHost;227 const client = yield* gitClient(memoryFs());228 const first = yield* client.commit("first", [["a.txt", "1"]]);229230 yield* repos.create(name).pipe(Effect.orDie);231 yield* repos232 .push(name, client.source, [233 { from: Option.none(), ref: main, to: first },234 ])235 .pipe(Effect.orDie);236237 return { client, first };238 });239240describe("the Workers binding's surprises, typed", () => {241 // S1 #22: under `wrangler dev`, the binding throws plain `Error`s.242 it.live(243 "reads a missing repo as RepoNotFound when errors carry no code",244 () =>245 within(246 () =>247 Effect.gen(function* () {248 const repos = yield* RepoHost;249 const missing = RepoName.make("missing");250 const taken = RepoName.make("taken");251252 yield* repos.create(taken).pipe(Effect.orDie);253254 expect(255 yield* Effect.flip(256 repos.readFile(257 missing,258 Revision.Branch({ name: BranchName.make("main") }),259 RepoPath.make("a.txt")260 )261 )262 ).toStrictEqual(new RepoNotFound({ name: missing }));263 expect(yield* Effect.flip(repos.refs(missing))).toStrictEqual(264 new RepoNotFound({ name: missing })265 );266 expect(yield* Effect.flip(repos.create(taken))).toStrictEqual(267 new RepoExists({ name: taken })268 );269 expect(yield* Effect.flip(repos.fork(taken, taken))).toStrictEqual(270 new RepoExists({ name: taken })271 );272 }),273 { codeless: true }274 )275 );276277 // S7 #2: under load a fork answers 500 after making the repo, and a retry278 // answers 409. The fork's name is the claim's, so the retry converges.279 it.live.each([280 { codeless: false, label: "with codes" },281 { codeless: true, label: "without codes" },282 ])(283 "forks once through a 500 then an already-exists, $label",284 ({ codeless }) =>285 within(286 ({ fake }) =>287 Effect.gen(function* () {288 const repos = yield* RepoHost;289 const base = RepoName.make("demo");290 const name = RepoName.make("demo--fix--alice");291 const { first } = yield* seeded(base);292293 const created = yield* repos.fork(base, name).pipe(Effect.orDie);294 const listed = yield* Effect.promise(() => fake.list());295296 expect(created).toStrictEqual({297 name,298 remote: `${remoteBase}/${name}.git`,299 });300 expect(301 listed.repos.map((repo) => repo.name).toSorted()302 ).toStrictEqual([base, name]);303 expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(304 new Map([[main, first]])305 );306 }),307 { codeless, forkFailures: 1 }308 )309 );310311 it.live("reads a fork still in progress as ForkInProgress", () =>312 within(313 () =>314 Effect.gen(function* () {315 const repos = yield* RepoHost;316 const base = RepoName.make("demo");317 const name = RepoName.make("demo--fix--bob");318319 yield* seeded(base);320321 expect(yield* Effect.flip(repos.fork(base, name))).toStrictEqual(322 new ForkInProgress({ name })323 );324 }),325 {326 wrap: (host) => ({327 ...host,328 fork: (_base, name) => Effect.fail(new ForkInProgress({ name })),329 }),330 }331 )332 );333334 // S2 #9: one side-band 3 packet and no report.335 it.live("reads a busy receive-pack as HostBusy, and moves nothing", () =>336 within(({ intercept }) =>337 Effect.gen(function* () {338 const repos = yield* RepoHost;339 const name = RepoName.make("busy");340 const { client, first } = yield* seeded(name);341342 const second = yield* client.commit(343 "second",344 [["a.txt", "2"]],345 [first]346 );347348 const update = { from: Option.some(first), ref: main, to: second };349350 yield* Ref.set(351 intercept,352 Option.some(() => Effect.succeedSome(busyReply()))353 );354355 expect(356 yield* Effect.flip(repos.push(name, client.source, [update]))357 ).toStrictEqual(new HostBusy({ name }));358 expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(359 new Map([[main, first]])360 );361 expect(362 yield* repos.push(name, client.source, [update]).pipe(Effect.orDie)363 ).toStrictEqual([RefOutcome.Updated({ ref: main })]);364 })365 )366 );367368 // git's receive-pack checks the old value the push names (spec §7.4).369 it.live(370 "reports a ref that moved during the push as Stale at its new tip",371 () =>372 within(({ intercept, store }) =>373 Effect.gen(function* () {374 const repos = yield* RepoHost;375 const name = RepoName.make("raced");376 const { client, first } = yield* seeded(name);377 const ours = yield* client.commit("ours", [["a.txt", "2"]], [first]);378379 const theirs = yield* client.commit(380 "theirs",381 [["a.txt", "3"]],382 [first]383 );384385 yield* Ref.set(386 intercept,387 Option.some(() =>388 store389 .push(name, client.source, [390 { from: Option.some(first), ref: main, to: theirs },391 ])392 .pipe(Effect.orDie, Effect.as(Option.none()))393 )394 );395396 expect(397 yield* repos398 .push(name, client.source, [399 { from: Option.some(first), ref: main, to: ours },400 ])401 .pipe(Effect.orDie)402 ).toStrictEqual([403 RefOutcome.Stale({ ref: main, tip: Option.some(theirs) }),404 ]);405 })406 )407 );408409 it.live(410 "never forces a ref: a push that is not a fast-forward is Stale",411 () =>412 within(() =>413 Effect.gen(function* () {414 const repos = yield* RepoHost;415 const name = RepoName.make("no-force");416 const { client, first } = yield* seeded(name);417 const unrelated = yield* client.commit("unrelated", [["b.txt", "1"]]);418419 expect(420 yield* repos421 .push(name, client.source, [422 { from: Option.some(first), ref: main, to: unrelated },423 ])424 .pipe(Effect.orDie)425 ).toStrictEqual([426 RefOutcome.Stale({ ref: main, tip: Option.some(first) }),427 ]);428 expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(429 new Map([[main, first]])430 );431 })432 )433 );434435 // Artifacts' `readTree` throws `INTERNAL_ERROR` for an object that is no tree.436 it.live("reads no tree at a blob's id", () =>437 within(438 () =>439 Effect.gen(function* () {440 const repos = yield* RepoHost;441 const name = RepoName.make("kinds");442 const { first } = yield* seeded(name);443444 const commit = yield* repos445 .readCommit(name, first)446 .pipe(Effect.orDie);447448 const tree = Option.getOrThrow(449 Option.map(commit, (read) => read.tree)450 );451452 const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);453 const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;454455 expect(blob).not.toBe(tree);456 expect(457 yield* repos.readTree(name, blob).pipe(Effect.orDie)458 ).toStrictEqual(Option.none());459 }),460 {461 wrap: (host) => ({462 ...host,463 readTree: (repo, sha) =>464 Effect.flatMap(host.readBlob(repo, sha), (bytes) =>465 Option.isSome(bytes)466 ? Effect.die(467 Object.assign(new Error("An internal error occurred."), {468 code: "INTERNAL_ERROR",469 name: "ArtifactsError",470 numericCode: 10_400,471 })472 )473 : host.readTree(repo, sha)474 ),475 }),476 }477 )478 );479});480481describe("tokens and handles the binding takes", () => {482 it.live(483 "sends each minted token only to the repo's own remote, then revokes it",484 () =>485 within(({ fake, seen, tokens }) =>486 Effect.gen(function* () {487 const repos = yield* RepoHost;488 const name = RepoName.make("tokens");489 const { client, first } = yield* seeded(name);490491 const second = yield* client.commit(492 "second",493 [["a.txt", "2"]],494 [first]495 );496497 yield* Ref.set(seen, []);498 tokens.length = 0;499500 yield* repos501 .push(name, client.source, [502 { from: Option.some(first), ref: main, to: second },503 ])504 .pipe(Effect.orDie);505 yield* repos.refs(name).pipe(Effect.orDie);506507 const requests = yield* Ref.get(seen);508509 const repo = yield* Effect.acquireRelease(510 Effect.promise(() => fake.get(name)),511 (handle) =>512 Effect.sync(() => {513 handle[Symbol.dispose]();514 })515 );516517 const revoked = yield* Effect.forEach(tokens, ({ id }) =>518 Effect.promise(() => repo.revokeToken(id))519 );520521 expect(tokens.length).toBeGreaterThan(0);522 expect(requests.length).toBeGreaterThan(0);523 expect(524 requests.every(525 ({ authorization, url }) =>526 url.startsWith(`${remoteBase}/${name}.git/`) &&527 tokens.some(528 ({ plaintext }) => authorization === `Bearer ${plaintext}`529 )530 )531 ).toBeTruthy();532 // Revoked already: a second revoke finds nothing.533 expect(revoked.every((again) => !again)).toBeTruthy();534 })535 )536 );537538 it.live(539 "disposes every repo handle it opened, after success or failure",540 () =>541 within(({ counts, intercept }) =>542 Effect.gen(function* () {543 const repos = yield* RepoHost;544 const name = RepoName.make("handles");545 const missing = RepoName.make("missing");546 const { client, first } = yield* seeded(name);547548 const second = yield* client.commit(549 "second",550 [["a.txt", "2"]],551 [first]552 );553554 const at = Revision.Branch({ name: BranchName.make("main") });555556 yield* repos557 .push(name, client.source, [558 { from: Option.some(first), ref: main, to: second },559 ])560 .pipe(Effect.orDie);561 yield* repos.refs(name).pipe(Effect.orDie);562 yield* repos.remote(name).pipe(Effect.orDie);563 yield* repos564 .readFile(name, at, RepoPath.make("a.txt"))565 .pipe(Effect.orDie);566 yield* repos.log(name, at, 5).pipe(Effect.orDie);567 yield* repos.readCommit(name, second).pipe(Effect.orDie);568569 const token = yield* repos570 .mintToken(name, "read", Duration.minutes(5))571 .pipe(Effect.orDie);572573 yield* repos.revokeToken(name, token.id).pipe(Effect.orDie);574 yield* repos575 .fork(name, RepoName.make("handles--fork"))576 .pipe(Effect.orDie);577 yield* Ref.set(578 intercept,579 Option.some(() => Effect.succeedSome(busyReply()))580 );581582 const third = yield* client.commit(583 "third",584 [["a.txt", "3"]],585 [second]586 );587588 expect(589 yield* Effect.flip(590 repos.push(name, client.source, [591 { from: Option.some(second), ref: main, to: third },592 ])593 )594 ).toStrictEqual(new HostBusy({ name }));595 expect(yield* Effect.flip(repos.refs(missing))).toStrictEqual(596 new RepoNotFound({ name: missing })597 );598 expect(counts.gets).toBeGreaterThan(5);599 expect(counts.disposed).toBe(counts.gets);600 })601 )602 );603});604605describe("git smart HTTP over the Fetch port", () => {606 const token = Redacted.make("test-token");607608 it.live(609 "lists refs, pushes one compare-and-swap per ref, and fetches a ref",610 () =>611 within(({ fetch, store }) =>612 Effect.gen(function* () {613 const name = RepoName.make("wire");614 const client = yield* gitClient(memoryFs());615 const first = yield* client.commit("first", [["a.txt", "1"]]);616617 const second = yield* client.commit(618 "second",619 [["a.txt", "2"]],620 [first]621 );622623 const landed = RefName.make("refs/asked/landed");624 const remote = `${remoteBase}/${name}.git`;625626 yield* store.create(name).pipe(Effect.orDie);627628 const outcomes = yield* pushRefs({629 remote,630 source: client.source,631 token,632 updates: [633 { from: Option.none(), ref: main, to: second },634 { from: Option.some(first), ref: landed, to: second },635 ],636 });637638 const fs = memoryFs();639640 const fetched = yield* fetchInto({641 depth: 1,642 fs,643 gitdir: "/scratch.git",644 ref: "main",645 remote,646 token,647 });648649 const absent = yield* fetchInto({650 fs,651 gitdir: "/scratch.git",652 ref: "absent",653 remote,654 token,655 });656657 const read = yield* Effect.promise(() =>658 readCommit({ fs, gitdir: "/scratch.git", oid: second })659 );660661 expect(outcomes).toStrictEqual([662 RefOutcome.Updated({ ref: main }),663 RefOutcome.Stale({ ref: landed, tip: Option.none() }),664 ]);665 expect(yield* listRefs(remote, token)).toStrictEqual(666 new Map<RefName, CommitSha>([[main, second]])667 );668 expect(fetched).toStrictEqual(Option.some(second));669 expect(absent).toStrictEqual(Option.none());670 expect(read.commit.message).toBe("second\n");671 }).pipe(Effect.provideService(Fetch, fetch))672 )673 );674675 it.live("names the repo a remote does not serve", () =>676 within(({ fetch }) =>677 Effect.gen(function* () {678 const name = RepoName.make("nowhere");679 const remote = `${remoteBase}/${name}.git`;680681 expect(yield* Effect.flip(listRefs(remote, token))).toStrictEqual(682 new RepoNotFound({ name })683 );684 expect(685 yield* Effect.flip(686 fetchInto({687 fs: memoryFs(),688 gitdir: "/x.git",689 ref: "main",690 remote,691 token,692 })693 )694 ).toStrictEqual(new RepoNotFound({ name }));695 }).pipe(Effect.provideService(Fetch, fetch))696 )697 );698});
modified:packages/artifacts/package.json+1 added
modified:bun.lock+1 added
59 unmodified lines
60 "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