Merge build/218-artifacts-rest: scripts and the bench can drive Artifacts over its REST API, behind the same port
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 4ede6c4, 3069167 · Browse files · 3 files·+2159 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
3 files+2159 added−0 removed
- tests:+1271 added−0 removed
- other:+888 added−0 removed
Provenance
- Commit
f6ffedb- Tree
42539e6- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
4ede6c4- Parent 2
3069167
3 files changed+2159 added−0 removed
added:packages/artifacts/src/repo-host/rest.ts+888 added
1+/**2+ * `RepoHost` over the Artifacts REST API, with a Cloudflare API token: for3+ * code that runs outside a Worker, such as infra scripts, the bench and the4+ * seed script. It passes the contract the binding passes, and types the same5+ * surprises (S1, S7):6+ *7+ * - a fork names its target (`{name, default_branch_only: true}`), which8+ * cf's `artifacts namespaces repos fork` cannot do (cf #180);9+ * - a fork that answers 500 (code 10400) is tried once more, and an10+ * already-exists or a second 500 after that may be the fork the first11+ * made: it is, if it lists `main` (S7), as on the binding;12+ * - `refs` and `push` have no REST route, so they go over git smart HTTP to13+ * the repo's `remote` (`smart-http.ts`), with a repo token this layer mints.14+ *15+ * Every route is under `<base>/accounts/<accountId>/artifacts/namespaces/16+ * <namespace>` and carries the API token as `Authorization: Bearer`, and17+ * nowhere else. Each was confirmed with `bun run ops -- schema artifacts18+ * namespaces <command>` (cf 1.0.0-beta.12, read-only), and against19+ * Artifacts' REST docs (developers.cloudflare.com/artifacts/api/rest-api),20+ * which spell bodies in snake case where cf's flags use kebab case:21+ *22+ * | Port | Route | `<command>` | Body or query |23+ * | --- | --- | --- | --- |24+ * | `create` | `POST /repos` | `repos create` | `{name}` |25+ * | `remote`, and whether a repo exists | `GET /repos/{name}` | `repos get` | |26+ * | `remove` | `DELETE /repos/{name}` | `repos delete` | |27+ * | `fork` | `POST /repos/{base}/fork` | `repos fork` | `{name, default_branch_only: true}`: the docs and the probes (S1 #9, S7) send `name`; cf's schema lacks it (cf #180) |28+ * | `importFrom` | `POST /repos/{name}/import` | `repos import` | `{url, branch?}` |29+ * | `mintToken`, and the git calls' tokens | `POST /tokens` | `tokens create` | `{repo, scope, ttl}` |30+ * | `revokeToken` | `DELETE /tokens/{id}` | `tokens revoke` | |31+ * | `readCommit` | `GET /repos/{name}/commit/{hash}` | `repos commits get` | |32+ * | `readTree` | `GET /repos/{name}/tree/{hash}` | `repos trees get` | |33+ * | `readBlob` | `GET /repos/{name}/blob/{hash}` | `repos blobs get` | raw bytes back |34+ * | `readFile` | `GET /repos/{name}/file` | `repos files get` | `?ref&path`; raw bytes back |35+ * | `log` | `GET /repos/{name}/log` | `repos logs get` | `?ref&limit&offset` |36+ *37+ * cf's schema gives no reply shapes. From the docs: every JSON reply, and38+ * every refusal, is Cloudflare's v4 envelope, `{success, errors: [{code,39+ * message}], messages, result}`; blob and file replies are raw bytes; create,40+ * fork, import and a repo's info carry `remote`; a minted token is `{id,41+ * plaintext, scope, expires_at}`; a repo still being imported or forked42+ * answers 409 (cf's generated client declares 409 for a repo's info and a43+ * token's mint too); errors carry Artifacts' numeric codes (its errors44+ * page), which the binding's `numericCode` matches (workers-types), and S745+ * saw 10201 and 10400 live. A refusal that names no code at all, such as a46+ * proxy's, is read by its status: 404 is not found, 5xx internal. One that47+ * names only Cloudflare's own codes (7000, an unknown route) is a defect.48+ * ASSUMPTIONs, for a live run (W3 308, W7's bench) to settle:49+ *50+ * - a commit is the binding's metadata, spelled in snake case51+ * (`tree_hash`) as the API's other fields are, or in camel case as the52+ * binding's; a tree's `result` is the binding's entries, and a log's is a53+ * list of commit metadata;54+ * - a 404 from a read is the object's absence once the repo is found to55+ * exist, and a tree read at another kind of object fails as the binding's56+ * does (500), so the adapter asks whether it is a blob or a commit;57+ * - a log page may hold fewer commits than asked before the history ends58+ * (a server cap), so only an empty page ends it.59+ *60+ * A token id resolves through an eventually consistent index, so revoking it61+ * within about a second of its mint can be 404 (cf's help for `tokens62+ * revoke`): a 404 for a token this layer minted less than two seconds ago is63+ * tried once more when they have passed. Git calls share one token per repo64+ * and scope, minted on first use, minted again near its expiry, and revoked65+ * when the layer closes. The day-long write token create, fork and import66+ * return (S1 #2) is dropped, as the binding drops it.67+ */68+import { CommitSha } from "@repo/protocol/ids";69+import {70+ Data,71+ DateTime,72+ Duration,73+ Effect,74+ Layer,75+ Match,76+ Option,77+ Redacted,78+ Ref,79+ Schema,80+} from "effect";81+82+import { Fetch } from "../fetch.ts";83+import {84+ ForkInProgress,85+ ImportRefused,86+ ObjectId,87+ RefName,88+ RepoExists,89+ RepoHost,90+ RepoNotFound,91+ Revision,92+ TreeEntry,93+} from "../repo-host.ts";94+import type { Commit, RepoName, RepoToken, TokenScope } from "../repo-host.ts";95+import { listRefs, pushRefs } from "./smart-http.ts";96+97+/** The binding's names for Artifacts' errors (`ArtifactsError.code`). */98+type Code =99+ | "ALREADY_EXISTS"100+ | "NOT_FOUND"101+ | "CREATE_IN_PROGRESS"102+ | "IMPORT_IN_PROGRESS"103+ | "FORK_IN_PROGRESS"104+ | "INVALID_INPUT"105+ | "INVALID_REPO_NAME"106+ | "INVALID_TTL"107+ | "INVALID_URL"108+ | "REMOTE_AUTH_REQUIRED"109+ | "UPSTREAM_UNAVAILABLE"110+ | "MEMORY_LIMIT"111+ | "INTERNAL_ERROR";112+113+/**114+ * Each REST `errors[].code` by the binding's name for it, from Artifacts'115+ * errors page. The page gives `CREATE_IN_PROGRESS` no number.116+ */117+const NUMBERED: ReadonlyMap<number, Code> = new Map<number, Code>([118+ [10_100, "INVALID_INPUT"],119+ [10_101, "INVALID_REPO_NAME"],120+ [10_103, "INVALID_TTL"],121+ [10_104, "INVALID_URL"],122+ [10_106, "REMOTE_AUTH_REQUIRED"],123+ [10_200, "NOT_FOUND"],124+ [10_201, "ALREADY_EXISTS"],125+ [10_302, "IMPORT_IN_PROGRESS"],126+ [10_303, "FORK_IN_PROGRESS"],127+ [10_400, "INTERNAL_ERROR"],128+ [10_401, "UPSTREAM_UNAVAILABLE"],129+ [10_402, "MEMORY_LIMIT"],130+]);131+132+/** A refusal that names no code at all, such as a proxy's, read by status. */133+const byStatus = (status: number): Option.Option<Code> =>134+ Match.value(status).pipe(135+ Match.when(404, () => Option.some<Code>("NOT_FOUND")),136+ Match.when(137+ (code) => code >= 500,138+ () => Option.some<Code>("INTERNAL_ERROR")139+ ),140+ Match.orElse(() => Option.none())141+ );142+143+/** A reply that was no success: its status, the code it names, its messages. */144+class Refused extends Data.TaggedError("Refused")<{145+ readonly status: number;146+ readonly code: Option.Option<Code>;147+ readonly message: string;148+}> {}149+150+/** A fork that answered 500, which may still have made the repo (S7 #2). */151+class MaybeForked extends Data.TaggedError("MaybeForked")<{152+ readonly refused: Refused;153+}> {}154+155+const Problem = Schema.Struct({ code: Schema.Int, message: Schema.String });156+157+const Failure = Schema.fromJsonString(158+ Schema.Struct({ errors: Schema.Array(Problem) })159+);160+161+const decodeFailure = Schema.decodeOption(Failure);162+163+/**164+ * A refused reply read: by the first code Artifacts names, or by its status165+ * when it names no code at all. One that names only codes Artifacts does not166+ * own, such as Cloudflare's 7000 for a route it does not know, reads as no167+ * code, so a wrong route, account or namespace is a defect and never passes168+ * for a missing repo or object.169+ */170+const refusedBy = (status: number, text: string) => {171+ const problems = Option.match(decodeFailure(text), {172+ onNone: () => [],173+ onSome: ({ errors }) => errors,174+ });175+176+ return new Refused({177+ code:178+ problems.length === 0179+ ? byStatus(status)180+ : Option.firstSomeOf(181+ problems.map(({ code }) => Option.fromNullishOr(NUMBERED.get(code)))182+ ),183+ message:184+ problems.map(({ message }) => message).join("; ") || `HTTP ${status}`,185+ status,186+ });187+};188+189+const is =190+ (...codes: readonly Code[]) =>191+ (refused: Refused): boolean =>192+ Option.exists(refused.code, (code) => codes.includes(code));193+194+/** Cloudflare's v4 envelope around a success's `result`. */195+const Envelope = <S extends Schema.Top>(result: S) =>196+ Schema.fromJsonString(197+ Schema.Struct({ result, success: Schema.Literal(true) })198+ );199+200+const Remote = Envelope(Schema.Struct({ remote: Schema.String }));201+202+const Minted = Envelope(203+ Schema.Struct({204+ expires_at: Schema.String,205+ id: Schema.String,206+ plaintext: Schema.String,207+ })208+);209+210+const Person = Schema.Struct({ email: Schema.String, name: Schema.String });211+212+const commitFields = {213+ author: Person,214+ committer: Person,215+ hash: CommitSha,216+ message: Schema.String,217+ parents: Schema.Array(CommitSha),218+};219+220+const Metadata = Schema.Union([221+ Schema.Struct({ ...commitFields, tree_hash: ObjectId }),222+ Schema.Struct({ ...commitFields, treeHash: ObjectId }),223+]);224+225+type Metadata = typeof Metadata.Type;226+227+const CommitReply = Envelope(Metadata);228+229+const LogReply = Envelope(Schema.Array(Metadata));230+231+const TreeReply = Envelope(232+ Schema.Array(233+ Schema.Struct({ hash: ObjectId, mode: Schema.String, name: Schema.String })234+ )235+);236+237+const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));238+239+const commitOf = (metadata: Metadata): Commit => ({240+ author: metadata.author,241+ committer: metadata.committer,242+ message: metadata.message,243+ parents: metadata.parents,244+ sha: metadata.hash,245+ tree: "tree_hash" in metadata ? metadata.tree_hash : metadata.treeHash,246+});247+248+// Artifacts gives canonical modes: a folder is `40000`, as git stores it, not249+// `040000`, as `ls-tree` prints it and the port has it.250+const entriesOf = (entries: typeof TreeReply.Type.result) =>251+ decodeEntries(252+ entries.map((entry) => {253+ const mode = entry.mode.padStart(6, "0");254+255+ return {256+ mode,257+ name: entry.name,258+ sha: entry.hash,259+ type: Match.value(mode).pipe(260+ Match.when("040000", () => "tree"),261+ Match.when("160000", () => "commit"),262+ Match.orElse(() => "blob")263+ ),264+ };265+ })266+ ).pipe(Effect.orDie);267+268+/** The API's name for a revision: a short branch name or a commit id (S1 #20). */269+const refOf = (at: Revision) =>270+ Revision.$match(at, {271+ Branch: ({ name }) => name,272+ Commit: ({ sha }) => sha,273+ });274+275+const repoPath = (name: RepoName) => `/repos/${encodeURIComponent(name)}`;276+277+const textOf = (response: Response) => Effect.promise(() => response.text());278+279+const refusal = (response: Response) =>280+ textOf(response).pipe(281+ Effect.flatMap((text) => Effect.fail(refusedBy(response.status, text)))282+ );283+284+/** A success's envelope, decoded at the boundary, or what refused it. */285+const decoded =286+ <A>(codec: Schema.Codec<A, string>) =>287+ (response: Response) =>288+ response.ok289+ ? textOf(response).pipe(290+ Effect.flatMap(Schema.decodeEffect(codec)),291+ Effect.orDie292+ )293+ : refusal(response);294+295+/** A success's raw bytes, or what refused it. */296+const bytesOf = (response: Response) =>297+ response.ok298+ ? Effect.promise(() => response.arrayBuffer()).pipe(299+ Effect.map((buffer) => new Uint8Array(buffer))300+ )301+ : refusal(response);302+303+const accepted = (response: Response) =>304+ response.ok ? Effect.void : refusal(response);305+306+const main = RefName.make("refs/heads/main");307+308+/** `log` asks for at most this many commits per request, as the binding does. */309+const LOG_PAGE = 1000;310+311+// Artifacts takes a token's ttl in whole seconds, from a minute to a year.312+const MIN_TTL_SECONDS = 60;313+314+const MAX_TTL_SECONDS = 31_536_000;315+316+const secondsOf = (ttl: Duration.Duration) =>317+ Math.min(318+ Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),319+ MAX_TTL_SECONDS320+ );321+322+/** How long a token for git calls lives, and how near its expiry it is replaced. */323+const CALL_TOKEN_TTL = Duration.minutes(30);324+325+const CALL_TOKEN_MARGIN = Duration.minutes(5);326+327+/** How long a token id may be unknown to the index after its mint. */328+const REVOKE_LAG = Duration.seconds(2);329+330+/** A token this layer minted and has not revoked. */331+interface Token {332+ readonly name: RepoName;333+ readonly at: DateTime.Utc;334+ /** Minted for the layer's own git calls, and revoked when it closes. */335+ readonly forCalls: boolean;336+}337+338+/** What a git call to a repo needs: its remote, and a token. */339+interface Access {340+ readonly name: RepoName;341+ readonly remote: string;342+ readonly token: Redacted.Redacted;343+ readonly expiresAt: DateTime.Utc;344+}345+346+const keeping = <K, V>(347+ map: ReadonlyMap<K, V>,348+ keep: (value: V, key: K) => boolean349+): ReadonlyMap<K, V> =>350+ new Map([...map].filter(([key, value]) => keep(value, key)));351+352+/** The import refusals that say the source is no repo to take (the binding's). */353+const NO_SOURCE = [354+ "INVALID_INPUT",355+ "INVALID_URL",356+ "MEMORY_LIMIT",357+ "NOT_FOUND",358+ "REMOTE_AUTH_REQUIRED",359+ "UPSTREAM_UNAVAILABLE",360+] as const satisfies readonly Code[];361+362+/** A repo that exists but is still being made answers its info and mints 409. */363+const BEING_MADE = [364+ "CREATE_IN_PROGRESS",365+ "FORK_IN_PROGRESS",366+ "IMPORT_IN_PROGRESS",367+] as const satisfies readonly Code[];368+369+/** What a create or an import refuses a name with: one taken, or being made. */370+const TAKEN = [371+ "ALREADY_EXISTS",372+ ...BEING_MADE,373+] as const satisfies readonly Code[];374+375+const make = (options: {376+ readonly accountId: string;377+ readonly namespace: string;378+ readonly token: Redacted.Redacted;379+ readonly base?: string;380+}) =>381+ Effect.gen(function* () {382+ // The service alone: the layer's whole context would carry its Scope, and383+ // every call's finalizers would wait for the layer's end (217).384+ const fetch = yield* Fetch;385+386+ const root = [387+ (options.base ?? "https://api.cloudflare.com/client/v4").replace(388+ /\/+$/u,389+ ""390+ ),391+ "accounts",392+ encodeURIComponent(options.accountId),393+ "artifacts/namespaces",394+ encodeURIComponent(options.namespace),395+ ].join("/");396+397+ const minted = yield* Ref.make<ReadonlyMap<string, Token>>(new Map());398+ const access = yield* Ref.make<ReadonlyMap<string, Access>>(new Map());399+400+ const authorization = () => `Bearer ${Redacted.value(options.token)}`;401+402+ /** One request to the API; one that got no response is a defect. */403+ const send = (request: Request) => fetch.fetch(request).pipe(Effect.orDie);404+405+ const httpGet = (path: string) =>406+ send(407+ new Request(`${root}${path}`, {408+ headers: { accept: "*/*", authorization: authorization() },409+ method: "GET",410+ })411+ );412+413+ const httpDelete = (path: string) =>414+ send(415+ new Request(`${root}${path}`, {416+ headers: {417+ accept: "application/json",418+ authorization: authorization(),419+ },420+ method: "DELETE",421+ })422+ );423+424+ const httpPost = (425+ path: string,426+ body:427+ | { readonly name: RepoName }428+ | { readonly default_branch_only: true; readonly name: RepoName }429+ | { readonly branch?: string; readonly url: string }430+ | {431+ readonly repo: RepoName;432+ readonly scope: TokenScope;433+ readonly ttl: number;434+ }435+ ) =>436+ send(437+ new Request(`${root}${path}`, {438+ body: JSON.stringify(body),439+ headers: {440+ accept: "application/json",441+ authorization: authorization(),442+ "content-type": "application/json",443+ },444+ method: "POST",445+ })446+ );447+448+ /** A repo's remote; a 409 there is a repo still being made. */449+ const infoOf = (name: RepoName) =>450+ httpGet(repoPath(name)).pipe(451+ Effect.flatMap(decoded(Remote)),452+ Effect.map(({ result }) => result.remote),453+ Effect.catchTag("Refused", (refused) =>454+ Match.value(refused).pipe(455+ Match.when(is("NOT_FOUND"), () =>456+ Effect.fail(new RepoNotFound({ name }))457+ ),458+ Match.when(is(...BEING_MADE), () =>459+ Effect.fail(new ForkInProgress({ name }))460+ ),461+ Match.orElse(Effect.die)462+ )463+ )464+ );465+466+ const remoteOf = (name: RepoName) =>467+ infoOf(name).pipe(Effect.catchTag("ForkInProgress", Effect.die));468+469+ /**470+ * A read whose 404 is the object's absence once the repo is found to471+ * exist; any other refusal is a defect.472+ */473+ const optional = <A>(name: RepoName, read: Effect.Effect<A, Refused>) =>474+ read.pipe(475+ Effect.asSome,476+ Effect.catchTag("Refused", (refused) =>477+ is("NOT_FOUND")(refused)478+ ? remoteOf(name).pipe(Effect.as(Option.none<A>()))479+ : Effect.die(refused)480+ )481+ );482+483+ const mint = (484+ name: RepoName,485+ scope: TokenScope,486+ seconds: number,487+ forCalls: boolean488+ ) =>489+ Effect.gen(function* () {490+ const at = yield* DateTime.now;491+492+ const { result } = yield* httpPost("/tokens", {493+ repo: name,494+ scope,495+ ttl: seconds,496+ }).pipe(497+ Effect.flatMap(decoded(Minted)),498+ Effect.catchTag("Refused", (refused) =>499+ Match.value(refused).pipe(500+ Match.when(is("NOT_FOUND"), () =>501+ Effect.fail(new RepoNotFound({ name }))502+ ),503+ Match.when(is(...BEING_MADE), () =>504+ Effect.fail(new ForkInProgress({ name }))505+ ),506+ Match.orElse(Effect.die)507+ )508+ )509+ );510+511+ yield* Ref.update(minted, (all) =>512+ new Map(all).set(result.id, { at, forCalls, name })513+ );514+515+ // Never later than either clock says: the ttl asked for, from before516+ // the request, or the store's own expiry.517+ const asked = DateTime.add(at, { seconds });518+519+ const expiresAt = Option.match(DateTime.make(result.expires_at), {520+ onNone: () => asked,521+ onSome: (stated) => DateTime.min(asked, stated),522+ });523+524+ return {525+ expiresAt,526+ id: result.id,527+ scope,528+ secret: Redacted.make(result.plaintext),529+ } satisfies RepoToken;530+ });531+532+ const revokeOnce = (id: string) =>533+ httpDelete(`/tokens/${encodeURIComponent(id)}`).pipe(534+ Effect.flatMap(accepted),535+ Effect.as(true),536+ Effect.catchTag("Refused", (refused) =>537+ is("NOT_FOUND")(refused) ? Effect.succeed(false) : Effect.die(refused)538+ )539+ );540+541+ /**542+ * Revokes the token `id`, once more when the index may not know it yet;543+ * whether it was revoked. The layer forgets the token either way.544+ */545+ const revoke = (id: string) =>546+ Effect.gen(function* () {547+ const token = (yield* Ref.get(minted)).get(id);548+ const revoked = yield* revokeOnce(id);549+ const now = yield* DateTime.now;550+551+ const known = Option.filter(552+ Option.map(Option.fromNullishOr(token), ({ at }) =>553+ DateTime.addDuration(at, REVOKE_LAG)554+ ),555+ (settled) => DateTime.isLessThan(now, settled)556+ );557+558+ const again =559+ revoked || Option.isNone(known)560+ ? revoked561+ : yield* Effect.sleep(DateTime.distance(now, known.value)).pipe(562+ Effect.andThen(revokeOnce(id))563+ );564+565+ yield* Ref.update(minted, (all) =>566+ keeping(all, (_, key) => key !== id)567+ );568+569+ return again;570+ });571+572+ /** The remote and token a git call to `name` uses, minted on first use. */573+ const accessOf = (name: RepoName, scope: TokenScope) =>574+ Effect.gen(function* () {575+ const key = `${scope}:${name}`;576+ const now = yield* DateTime.now;577+ const kept = (yield* Ref.get(access)).get(key);578+579+ if (580+ kept !== undefined &&581+ DateTime.isLessThan(582+ DateTime.addDuration(now, CALL_TOKEN_MARGIN),583+ kept.expiresAt584+ )585+ ) {586+ return kept;587+ }588+589+ const remote = yield* infoOf(name);590+ const token = yield* mint(name, scope, secondsOf(CALL_TOKEN_TTL), true);591+592+ const fresh: Access = {593+ expiresAt: token.expiresAt,594+ name,595+ remote,596+ token: token.secret,597+ };598+599+ yield* Ref.update(access, (all) => new Map(all).set(key, fresh));600+601+ return fresh;602+ });603+604+ /** A removed repo's tokens are gone with it (workers-types). */605+ const forget = (name: RepoName) =>606+ Effect.all([607+ Ref.update(minted, (all) =>608+ keeping(all, (token) => token.name !== name)609+ ),610+ Ref.update(access, (all) => keeping(all, (kept) => kept.name !== name)),611+ ]);612+613+ yield* Effect.addFinalizer(() =>614+ Ref.get(minted).pipe(615+ Effect.flatMap((all) =>616+ Effect.forEach(617+ [...all].filter(([, token]) => token.forCalls),618+ ([id]) => Effect.exit(revoke(id)),619+ { concurrency: "unbounded", discard: true }620+ )621+ )622+ )623+ );624+625+ /**626+ * After a 500 and then an already-exists or a second 500, the fork may be627+ * made (S7): it is, if it lists `main`. Otherwise it is still being made,628+ * or was undone; either way the caller tries again later.629+ */630+ const confirmed = (name: RepoName) =>631+ Effect.gen(function* () {632+ const { remote, token } = yield* accessOf(name, "read");633+ const refs = yield* listRefs(remote, token);634+635+ if (!refs.has(main)) {636+ return yield* new ForkInProgress({ name });637+ }638+639+ return { name, remote };640+ }).pipe(641+ Effect.catchTag("RepoNotFound", () =>642+ Effect.fail(new ForkInProgress({ name }))643+ ),644+ Effect.provideService(Fetch, fetch)645+ );646+647+ /**648+ * One fork request. The base's absence names the base; any other refusal649+ * names the target, and a 500 is `MaybeForked`, since it may have made it.650+ */651+ const forkOnce = (from: RepoName, name: RepoName) =>652+ httpPost(`${repoPath(from)}/fork`, {653+ default_branch_only: true,654+ name,655+ }).pipe(656+ Effect.flatMap(decoded(Remote)),657+ Effect.map(({ result }) => ({ name, remote: result.remote })),658+ Effect.catchTag("Refused", (refused) =>659+ Match.value(refused).pipe(660+ Match.when(is("INTERNAL_ERROR"), () =>661+ Effect.fail(new MaybeForked({ refused }))662+ ),663+ Match.when(is("NOT_FOUND"), () =>664+ Effect.fail(new RepoNotFound({ name: from }))665+ ),666+ Match.when(is("ALREADY_EXISTS"), () =>667+ Effect.fail(new RepoExists({ name }))668+ ),669+ Match.when(is("FORK_IN_PROGRESS"), () =>670+ Effect.fail(new ForkInProgress({ name }))671+ ),672+ Match.orElse(Effect.die)673+ )674+ )675+ );676+677+ /** Whether the repo holds `id` as a blob or a commit, as a tree read refused it. */678+ const blobOrCommit = (name: RepoName, id: ObjectId) =>679+ optional(680+ name,681+ httpGet(`${repoPath(name)}/blob/${id}`).pipe(Effect.flatMap(bytesOf))682+ ).pipe(683+ Effect.flatMap((blob) =>684+ Option.isSome(blob)685+ ? Effect.succeed(true)686+ : httpGet(`${repoPath(name)}/commit/${id}`).pipe(687+ Effect.flatMap(accepted),688+ Effect.as(true),689+ Effect.catchTag("Refused", (refused) =>690+ is("NOT_FOUND", "INTERNAL_ERROR")(refused)691+ ? Effect.succeed(false)692+ : Effect.die(refused)693+ )694+ )695+ )696+ );697+698+ const readTree = (name: RepoName, tree: ObjectId) =>699+ httpGet(`${repoPath(name)}/tree/${tree}`).pipe(700+ Effect.flatMap(decoded(TreeReply)),701+ Effect.flatMap(({ result }) => entriesOf(result)),702+ Effect.asSome,703+ Effect.catchTag("Refused", (refused) =>704+ Match.value(refused).pipe(705+ Match.when(is("NOT_FOUND"), () =>706+ remoteOf(name).pipe(Effect.as(Option.none()))707+ ),708+ // A blob's or a commit's id names no tree, as on the other stores709+ // (202 Comment 5); any other failure stays one.710+ Match.when(is("INTERNAL_ERROR"), () =>711+ blobOrCommit(name, tree).pipe(712+ Effect.flatMap((other) =>713+ other ? Effect.succeedNone : Effect.die(refused)714+ )715+ )716+ ),717+ Match.orElse(Effect.die)718+ )719+ )720+ );721+722+ /** One page of a log; a ref that names nothing logs nothing, as the binding's. */723+ const page = (name: RepoName, ref: string, offset: number, limit: number) =>724+ httpGet(725+ `${repoPath(name)}/log?${new URLSearchParams({726+ limit: String(limit),727+ offset: String(offset),728+ ref,729+ }).toString()}`730+ ).pipe(731+ Effect.flatMap(decoded(LogReply)),732+ Effect.map(({ result }) => result.map(commitOf)),733+ Effect.catchTag("Refused", (refused) =>734+ is("NOT_FOUND")(refused)735+ ? remoteOf(name).pipe(Effect.as([]))736+ : Effect.die(refused)737+ )738+ );739+740+ const log = (name: RepoName, at: Revision, limit: number) =>741+ Effect.gen(function* () {742+ const commits: Commit[] = [];743+744+ while (commits.length < limit) {745+ const more = yield* page(746+ name,747+ refOf(at),748+ commits.length,749+ Math.min(limit - commits.length, LOG_PAGE)750+ );751+752+ if (more.length === 0) {753+ break;754+ }755+756+ commits.push(...more);757+ }758+759+ return commits.slice(0, limit);760+ });761+762+ return RepoHost.of({763+ // A repo of that name still being made is a name already taken.764+ create: (name) =>765+ httpPost("/repos", { name }).pipe(766+ Effect.flatMap(decoded(Remote)),767+ Effect.map(({ result }) => ({ name, remote: result.remote })),768+ Effect.catchTag("Refused", (refused) =>769+ is(...TAKEN)(refused)770+ ? Effect.fail(new RepoExists({ name }))771+ : Effect.die(refused)772+ )773+ ),774+ // S7: a 500 is tried once more; an already-exists or a second 500 after775+ // it may be the fork the first made, so it is confirmed, not trusted.776+ fork: (base, name) =>777+ forkOnce(base, name).pipe(778+ Effect.catchTag("MaybeForked", () =>779+ forkOnce(base, name).pipe(780+ Effect.catchTags({781+ MaybeForked: () => confirmed(name),782+ RepoExists: () => confirmed(name),783+ })784+ )785+ )786+ ),787+ importFrom: (name, source) =>788+ httpPost(789+ `${repoPath(name)}/import`,790+ source.branch === undefined791+ ? { url: source.url }792+ : { branch: source.branch, url: source.url }793+ ).pipe(794+ Effect.flatMap(decoded(Remote)),795+ Effect.map(({ result }) => ({ name, remote: result.remote })),796+ Effect.catchTag("Refused", (refused) =>797+ Match.value(refused).pipe(798+ Match.when(is(...TAKEN), () =>799+ Effect.fail(new RepoExists({ name }))800+ ),801+ Match.when(is(...NO_SOURCE), ({ message }) =>802+ Effect.fail(new ImportRefused({ name, reason: message }))803+ ),804+ Match.orElse(Effect.die)805+ )806+ )807+ ),808+ log,809+ mintToken: (name, scope, ttl) =>810+ mint(name, scope, secondsOf(ttl), false).pipe(811+ Effect.catchTag("ForkInProgress", Effect.die)812+ ),813+ push: (name, source, updates) =>814+ accessOf(name, "write").pipe(815+ Effect.flatMap(({ remote, token }) =>816+ pushRefs({ remote, source, token, updates })817+ ),818+ Effect.catchTag("ForkInProgress", Effect.die),819+ Effect.provideService(Fetch, fetch)820+ ),821+ readBlob: (name, blob) =>822+ optional(823+ name,824+ httpGet(`${repoPath(name)}/blob/${blob}`).pipe(825+ Effect.flatMap(bytesOf)826+ )827+ ),828+ readCommit: (name, sha) =>829+ optional(830+ name,831+ httpGet(`${repoPath(name)}/commit/${sha}`).pipe(832+ Effect.flatMap(decoded(CommitReply)),833+ Effect.map(({ result }) => commitOf(result))834+ )835+ ),836+ readFile: (name, at, path) =>837+ optional(838+ name,839+ httpGet(840+ `${repoPath(name)}/file?${new URLSearchParams({841+ path,842+ ref: refOf(at),843+ }).toString()}`844+ ).pipe(Effect.flatMap(bytesOf))845+ ),846+ readTree,847+ refs: (name) =>848+ accessOf(name, "read").pipe(849+ Effect.flatMap(({ remote, token }) => listRefs(remote, token)),850+ Effect.catchTag("ForkInProgress", Effect.die),851+ Effect.provideService(Fetch, fetch)852+ ),853+ remote: remoteOf,854+ remove: (name) =>855+ httpDelete(repoPath(name)).pipe(856+ Effect.flatMap(accepted),857+ Effect.as(true),858+ Effect.catchTag("Refused", (refused) =>859+ is("NOT_FOUND")(refused)860+ ? Effect.succeed(false)861+ : Effect.die(refused)862+ ),863+ Effect.tap(() => forget(name))864+ ),865+ // The route takes the id alone; the repo is checked to exist, as the866+ // binding's `get` does.867+ revokeToken: (name, id) =>868+ remoteOf(name).pipe(Effect.andThen(revoke(id))),869+ });870+ });871+872+/**873+ * Artifacts over its REST API, for scripts and the bench: the same `RepoHost`874+ * the platform reaches through the binding. The API token is the caller's875+ * (scripts get it from `varlock run`), and goes only into the876+ * `Authorization` header of requests to the API. Delete only repos the877+ * caller made with it.878+ */879+export const RepoHostRest = {880+ layer: (options: {881+ readonly accountId: string;882+ readonly namespace: string;883+ readonly token: Redacted.Redacted;884+ /** Defaults to `https://api.cloudflare.com/client/v4`. */885+ readonly base?: string;886+ }): Layer.Layer<RepoHost, never, Fetch> =>887+ Layer.effect(RepoHost, make(options)),888+};added:packages/artifacts/test/fake-rest.ts+574 added
1+/**2+ * An in-process fake of the Artifacts REST API over a `RepoHost` (in tests,3+ * `RepoHostLocal`), for `/rest`'s tests. It serves the routes4+ * `src/repo-host/rest.ts` lists, under5+ * `<base>/accounts/<accountId>/artifacts/namespaces/<namespace>`, and answers6+ * in Cloudflare's v4 envelope, `{success, errors: [{code, message}],7+ * messages, result}`. A repo's `remote` is the host's, for a git server the8+ * test runs there (`@repo/testkit/http-backend`).9+ *10+ * It keeps what Artifacts' REST docs and the probes say of the real API:11+ *12+ * - only `Authorization: Bearer <api token>` authenticates; anything else is13+ * 401 (Cloudflare's code 10000);14+ * - errors carry Artifacts' numeric codes (its errors page): 10200 not15+ * found, 10201 already exists, 10303 fork in progress, 10100 invalid16+ * input, 10103 invalid ttl, 10104 invalid url, 10400 internal;17+ * - a fork names its target in the body, `{name, default_branch_only}`, a18+ * field cf's schema lacks (cf #180); a body without `name` is refused;19+ * - create, fork and import answer with the new repo's `remote` and a20+ * day-long write token (S1 #2); a token's mint answers `{id, plaintext,21+ * scope, expires_at}`; a delete answers 202;22+ * - under load, a fork answers HTTP 500 with code 10400 after making the23+ * repo, and a retry answers 409 with code 10201 (S7 #2):24+ * `{ forkFailures: n }`; `{ forkLost: true }` makes those forks make25+ * nothing;26+ * - revoking a token within about a second of its mint can be 404 (cf's27+ * help for `tokens revoke`): `{ revokeLag: n }` makes the first `n`28+ * revocations of each token 404;29+ * - blobs and files are raw bytes; every other reply is JSON.30+ *31+ * And, as ASSUMPTIONs nobody has seen live, what the docs leave out:32+ *33+ * - commit metadata is the binding's, in snake case (`tree_hash`) as the34+ * API's other fields are, or in camel case: `{ casing: "camel" }`;35+ * - a tree or a log is the binding's list, as the envelope's `result`;36+ * - a tree or a commit read at an object of another kind is 500 (10400), as37+ * the binding throws `INTERNAL_ERROR` there;38+ * - a ref is a short branch name or a commit id, as the binding's (S1 #20),39+ * and a log at a ref that names nothing is 404.40+ */41+import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";42+import {43+ Data,44+ DateTime,45+ Duration,46+ Effect,47+ Match,48+ Option,49+ Redacted,50+ Ref,51+ Schema,52+} from "effect";53+54+import { BranchName, ObjectId, Revision } from "../src/repo-host.ts";55+import type {56+ Commit,57+ ForkInProgress,58+ ImportRefused,59+ RepoExists,60+ RepoHost,61+ RepoNotFound,62+ TokenScope,63+ TreeEntry,64+} from "../src/repo-host.ts";65+66+export interface FakeRestOptions {67+ readonly accountId: string;68+ readonly namespace: string;69+ /** The API token it takes, as a bearer token. */70+ readonly token: string;71+ /** Defaults to `https://api.cloudflare.com/client/v4`. */72+ readonly base?: string;73+ /** How many fork calls answer 500 (code 10400), as under load. */74+ readonly forkFailures?: number;75+ /** Whether those forks make nothing; by default each makes the repo first. */76+ readonly forkLost?: boolean;77+ /** How commit metadata spells its fields; snake case by default. */78+ readonly casing?: "camel" | "snake";79+ /** How many revocations of each token answer 404 before one takes. */80+ readonly revokeLag?: number;81+}82+83+/** Artifacts' error codes, from its errors page. */84+const Codes = {85+ alreadyExists: 10_201,86+ forkInProgress: 10_303,87+ internal: 10_400,88+ invalidInput: 10_100,89+ invalidTtl: 10_103,90+ invalidUrl: 10_104,91+ notFound: 10_200,92+} as const;93+94+/** Cloudflare's own codes for a bad API token and an unknown route. */95+const UNAUTHENTICATED = 10_000;96+97+const NO_ROUTE = 7000;98+99+const DAY_SECONDS = 86_400;100+101+const ok = (result: Schema.Json, status = 200) =>102+ Response.json(103+ { errors: [], messages: [], result, success: true },104+ { status }105+ );106+107+const failed = (status: number, code: number, message: string) =>108+ Response.json(109+ { errors: [{ code, message }], messages: [], result: null, success: false },110+ { status }111+ );112+113+const raw = (bytes: Uint8Array) =>114+ new Response(new Uint8Array(bytes), {115+ headers: { "content-type": "application/octet-stream" },116+ });117+118+const notFound = (what: string) =>119+ failed(404, Codes.notFound, `${what} not found`);120+121+const internal = () =>122+ failed(500, Codes.internal, "An internal error occurred.");123+124+/** A reply decided before the host was asked: a refusal of the request itself. */125+class Answered extends Data.TaggedError("Answered")<{126+ readonly response: Response;127+}> {}128+129+const invalid = (code: number, message: string) =>130+ new Answered({ response: failed(400, code, message) });131+132+/** What a route's handler fails with: the host's errors, or a reply. */133+type Failure =134+ | Answered135+ | ForkInProgress136+ | ImportRefused137+ | RepoExists138+ | RepoNotFound;139+140+const CreateBody = Schema.fromJsonString(Schema.Struct({ name: RepoName }));141+142+const ForkBody = Schema.fromJsonString(143+ Schema.Struct({144+ default_branch_only: Schema.optionalKey(Schema.Boolean),145+ name: RepoName,146+ })147+);148+149+const ImportBody = Schema.fromJsonString(150+ Schema.Struct({ branch: Schema.optionalKey(BranchName), url: Schema.String })151+);152+153+const TokenBody = Schema.fromJsonString(154+ Schema.Struct({155+ repo: RepoName,156+ scope: Schema.optionalKey(Schema.Literals(["read", "write"])),157+ ttl: Schema.optionalKey(Schema.Int),158+ })159+);160+161+const decodeName = Schema.decodeUnknownOption(RepoName);162+163+const decodeObject = Schema.decodeUnknownOption(ObjectId);164+165+const decodeBranch = Schema.decodeUnknownOption(BranchName);166+167+const decodePath = Schema.decodeUnknownOption(RepoPath);168+169+/** A request's JSON body, decoded, or a 400. */170+const bodyOf = <A>(request: Request, codec: Schema.Codec<A, string>) =>171+ Effect.promise(() => request.text()).pipe(172+ Effect.flatMap(Schema.decodeEffect(codec)),173+ Effect.mapError(() => invalid(Codes.invalidInput, "invalid request body"))174+ );175+176+const repoNamed = (name: string) =>177+ Effect.fromOption(decodeName(name)).pipe(178+ Effect.mapError(() =>179+ invalid(Codes.invalidInput, `invalid repo name: ${name}`)180+ )181+ );182+183+const objectNamed = (id: string) =>184+ Effect.fromOption(decodeObject(id)).pipe(185+ Effect.mapError(() => invalid(Codes.invalidInput, `invalid hash: ${id}`))186+ );187+188+/** A short branch name or a commit id; anything else names nothing (S1 #20). */189+const revisionOf = (ref: string): Option.Option<Revision> =>190+ Option.match(decodeObject(ref), {191+ onNone: () =>192+ Option.map(decodeBranch(ref), (name) => Revision.Branch({ name })),193+ onSome: (sha) => Option.some(Revision.Commit({ sha: CommitSha.make(sha) })),194+ });195+196+// Artifacts gives canonical modes, a folder as `40000`, and a kind derived197+// from the mode (workers-types' `ArtifactsTreeEntry`).198+const entryOf = (entry: TreeEntry) => ({199+ hash: entry.sha,200+ mode: entry.mode.replace(/^0/u, ""),201+ name: entry.name,202+ type: Match.value(entry.mode).pipe(203+ Match.when("040000", () => "tree"),204+ Match.when("100755", () => "exec"),205+ Match.when("120000", () => "symlink"),206+ Match.when("160000", () => "gitlink"),207+ Match.orElse(() => "blob")208+ ),209+});210+211+/** Whether the repo holds `id` as an object of any kind. */212+const holds = (host: RepoHost["Service"], name: RepoName, id: ObjectId) =>213+ Effect.all([214+ host.readBlob(name, id),215+ host.readTree(name, id),216+ host.readCommit(name, CommitSha.make(id)),217+ ]).pipe(218+ Effect.map(219+ ([blob, tree, commit]) =>220+ Option.isSome(blob) || Option.isSome(tree) || Option.isSome(commit)221+ )222+ );223+224+/** A repo's info, as `GET /repos/{name}` gives it. */225+const infoOf = (name: RepoName, remote: string) =>226+ ok({227+ created_at: "2026-10-07T00:00:00.000Z",228+ default_branch: "main",229+ description: null,230+ id: `repo-${name}`,231+ last_push_at: null,232+ name,233+ read_only: false,234+ remote,235+ source: null,236+ updated_at: "2026-10-07T00:00:00.000Z",237+ });238+239+/** Whose a token is, and how many more revocations of it miss. */240+interface Minted {241+ readonly repo: RepoName;242+ readonly misses: number;243+}244+245+/** A route's path parameters, the request, and its URL. */246+interface Call {247+ readonly name: string;248+ readonly id: string;249+ readonly request: Request;250+ readonly url: URL;251+}252+253+type Handler = (call: Call) => Effect.Effect<Response, Failure>;254+255+/** The fake API over `host`: a handler for the test's `Fetch` to route to. */256+export const fakeRest = (257+ host: RepoHost["Service"],258+ options: FakeRestOptions259+): Effect.Effect<(request: Request) => Effect.Effect<Response>> =>260+ Effect.gen(function* () {261+ const apiBase = options.base ?? "https://api.cloudflare.com/client/v4";262+ const prefix = `${apiBase}/accounts/${options.accountId}/artifacts/namespaces/${options.namespace}`;263+ const forkFailures = yield* Ref.make(options.forkFailures ?? 0);264+ const tokens = yield* Ref.make<ReadonlyMap<string, Minted>>(new Map());265+266+ // `RepoHost`'s commits carry no times, so the fake reports the epoch.267+ const metadataOf = (commit: Commit) => {268+ const fields = {269+ author: commit.author,270+ committer: commit.committer,271+ hash: commit.sha,272+ message: commit.message,273+ parents: commit.parents,274+ };275+276+ return options.casing === "camel"277+ ? { ...fields, authoredAt: 0, committedAt: 0, treeHash: commit.tree }278+ : {279+ ...fields,280+ authored_at: 0,281+ committed_at: 0,282+ tree_hash: commit.tree,283+ };284+ };285+286+ const mint = (repo: RepoName, scope: TokenScope, seconds: number) =>287+ Effect.gen(function* () {288+ const token = yield* host.mintToken(289+ repo,290+ scope,291+ Duration.seconds(seconds)292+ );293+294+ yield* Ref.update(tokens, (all) =>295+ new Map(all).set(token.id, { misses: options.revokeLag ?? 0, repo })296+ );297+298+ return {299+ expires_at: DateTime.formatIso(token.expiresAt),300+ id: token.id,301+ plaintext: Redacted.value(token.secret),302+ scope,303+ };304+ });305+306+ /** A new repo's reply, with its day-long write token (S1 #2). */307+ const made = (name: RepoName, remote: string) =>308+ mint(name, "write", DAY_SECONDS).pipe(309+ Effect.map(({ plaintext }) => ({310+ default_branch: "main",311+ description: null,312+ id: `repo-${name}`,313+ name,314+ remote,315+ token: plaintext,316+ }))317+ );318+319+ const create: Handler = ({ request }) =>320+ bodyOf(request, CreateBody).pipe(321+ Effect.flatMap(({ name }) => host.create(name)),322+ Effect.flatMap(({ name, remote }) => made(name, remote)),323+ Effect.map((result) => ok(result))324+ );325+326+ const info: Handler = (call) =>327+ repoNamed(call.name).pipe(328+ Effect.flatMap((name) =>329+ host.remote(name).pipe(Effect.map((remote) => infoOf(name, remote)))330+ )331+ );332+333+ const remove: Handler = (call) =>334+ repoNamed(call.name).pipe(335+ Effect.flatMap((name) =>336+ host337+ .remove(name)338+ .pipe(339+ Effect.map((removed) =>340+ removed ? ok({ id: `repo-${name}` }, 202) : notFound("repo")341+ )342+ )343+ )344+ );345+346+ const fork: Handler = (call) =>347+ Effect.gen(function* () {348+ const base = yield* repoNamed(call.name);349+ const { name } = yield* bodyOf(call.request, ForkBody);350+351+ const failing = yield* Ref.modify(352+ forkFailures,353+ (left) => [left > 0, Math.max(left - 1, 0)] as const354+ );355+356+ // S7 #2: the 500 comes after the repo is made, unless it is lost.357+ if (failing) {358+ if (options.forkLost !== true) {359+ yield* host.fork(base, name).pipe(Effect.ignore);360+ }361+362+ return internal();363+ }364+365+ const { remote } = yield* host.fork(base, name);366+367+ return ok({ ...(yield* made(name, remote)), objects: 0 });368+ });369+370+ const importFrom: Handler = (call) =>371+ Effect.gen(function* () {372+ const name = yield* repoNamed(call.name);373+ const body = yield* bodyOf(call.request, ImportBody);374+ const { remote } = yield* host.importFrom(name, body);375+376+ return ok(yield* made(name, remote));377+ });378+379+ /** A commit or a tree; another kind of object at the id is a 500. */380+ const object =381+ <A>(382+ read: (383+ name: RepoName,384+ id: ObjectId385+ ) => Effect.Effect<Option.Option<A>, RepoNotFound>,386+ reply: (found: A) => Response387+ ): Handler =>388+ (call) =>389+ Effect.gen(function* () {390+ const name = yield* repoNamed(call.name);391+ const id = yield* objectNamed(call.id);392+ const found = yield* read(name, id);393+394+ if (Option.isSome(found)) {395+ return reply(found.value);396+ }397+398+ return (yield* holds(host, name, id))399+ ? internal()400+ : notFound("object");401+ });402+403+ const commit = object(404+ (name, id) => host.readCommit(name, CommitSha.make(id)),405+ (found) => ok(metadataOf(found))406+ );407+408+ const tree = object(host.readTree, (entries) => ok(entries.map(entryOf)));409+410+ const blob: Handler = (call) =>411+ Effect.gen(function* () {412+ const name = yield* repoNamed(call.name);413+ const id = yield* objectNamed(call.id);414+415+ return Option.match(yield* host.readBlob(name, id), {416+ onNone: () => notFound("object"),417+ onSome: raw,418+ });419+ });420+421+ /** A file at a ref that is a short branch name or a commit id. */422+ const file: Handler = (call) =>423+ Effect.gen(function* () {424+ const name = yield* repoNamed(call.name);425+ const at = revisionOf(call.url.searchParams.get("ref") ?? "");426+ const path = decodePath(call.url.searchParams.get("path"));427+428+ if (Option.isNone(path)) {429+ return yield* invalid(Codes.invalidInput, "path is required");430+ }431+432+ if (Option.isNone(at)) {433+ yield* host.remote(name);434+435+ return notFound("File");436+ }437+438+ return Option.match(yield* host.readFile(name, at.value, path.value), {439+ onNone: () => notFound("File"),440+ onSome: raw,441+ });442+ });443+444+ const log: Handler = (call) =>445+ Effect.gen(function* () {446+ const name = yield* repoNamed(call.name);447+ const ref = call.url.searchParams.get("ref") ?? "HEAD";448+ const at = revisionOf(ref === "HEAD" ? "main" : ref);449+ const offset = Number(call.url.searchParams.get("offset") ?? 0);450+ const limit = Number(call.url.searchParams.get("limit") ?? 50);451+452+ if (Option.isNone(at)) {453+ yield* host.remote(name);454+455+ return notFound("ref");456+ }457+458+ const commits = yield* host.log(name, at.value, offset + limit);459+460+ return ok(commits.slice(offset).map(metadataOf));461+ });462+463+ const token: Handler = ({ request }) =>464+ Effect.gen(function* () {465+ const body = yield* bodyOf(request, TokenBody);466+ const ttl = body.ttl ?? DAY_SECONDS;467+468+ if (ttl < 60 || ttl > 31_536_000) {469+ return yield* invalid(Codes.invalidTtl, `invalid ttl: ${ttl}`);470+ }471+472+ return ok(yield* mint(body.repo, body.scope ?? "write", ttl));473+ });474+475+ const revoke: Handler = ({ id }) =>476+ Effect.gen(function* () {477+ const minted = (yield* Ref.get(tokens)).get(id);478+479+ if (minted === undefined) {480+ return notFound("token");481+ }482+483+ if (minted.misses > 0) {484+ yield* Ref.update(tokens, (all) =>485+ new Map(all).set(id, { ...minted, misses: minted.misses - 1 })486+ );487+488+ return notFound("token");489+ }490+491+ const revoked = yield* host492+ .revokeToken(minted.repo, id)493+ .pipe(Effect.catchTag("RepoNotFound", () => Effect.succeed(false)));494+495+ return revoked ? ok({ id }) : notFound("token");496+ });497+498+ const routes: readonly (readonly [string, RegExp, Handler])[] = [499+ ["POST", /^\/repos$/u, create],500+ ["GET", /^\/repos\/(?<name>[^/]+)$/u, info],501+ ["DELETE", /^\/repos\/(?<name>[^/]+)$/u, remove],502+ ["POST", /^\/repos\/(?<name>[^/]+)\/fork$/u, fork],503+ ["POST", /^\/repos\/(?<name>[^/]+)\/import$/u, importFrom],504+ ["GET", /^\/repos\/(?<name>[^/]+)\/commit\/(?<id>[^/]+)$/u, commit],505+ ["GET", /^\/repos\/(?<name>[^/]+)\/tree\/(?<id>[^/]+)$/u, tree],506+ ["GET", /^\/repos\/(?<name>[^/]+)\/blob\/(?<id>[^/]+)$/u, blob],507+ ["GET", /^\/repos\/(?<name>[^/]+)\/file$/u, file],508+ ["GET", /^\/repos\/(?<name>[^/]+)\/log$/u, log],509+ ["POST", /^\/tokens$/u, token],510+ ["DELETE", /^\/tokens\/(?<id>[^/]+)$/u, revoke],511+ ];512+513+ /** The handler for a request, and the call it is given. */514+ const routed = (request: Request) => {515+ const url = new URL(request.url);516+ const path = `${url.origin}${url.pathname}`;517+518+ if (!path.startsWith(`${prefix}/`)) {519+ return Option.none();520+ }521+522+ return Option.firstSomeOf(523+ routes.map(([method, pattern, handler]) => {524+ const found = pattern.exec(path.slice(prefix.length));525+526+ return method === request.method && found !== null527+ ? Option.some({528+ call: {529+ id: decodeURIComponent(found.groups?.id ?? ""),530+ name: decodeURIComponent(found.groups?.name ?? ""),531+ request,532+ url,533+ },534+ handler,535+ })536+ : Option.none();537+ })538+ );539+ };540+541+ return (request: Request) => {542+ if (request.headers.get("authorization") !== `Bearer ${options.token}`) {543+ return Effect.succeed(544+ failed(401, UNAUTHENTICATED, "Authentication error")545+ );546+ }547+548+ return Option.match(routed(request), {549+ onNone: () =>550+ Effect.succeed(failed(404, NO_ROUTE, "No route for that URI")),551+ onSome: ({ call, handler }) =>552+ handler(call).pipe(553+ Effect.catchTags({554+ Answered: ({ response }) => Effect.succeed(response),555+ ForkInProgress: ({ name }) =>556+ Effect.succeed(557+ failed(409, Codes.forkInProgress, `fork in progress: ${name}`)558+ ),559+ ImportRefused: ({ reason }) =>560+ Effect.succeed(failed(400, Codes.invalidUrl, reason)),561+ RepoExists: ({ name }) =>562+ Effect.succeed(563+ failed(564+ 409,565+ Codes.alreadyExists,566+ `repo already exists: ${name}`567+ )568+ ),569+ RepoNotFound: () => Effect.succeed(notFound("repo")),570+ })571+ ),572+ });573+ };574+ });added:packages/artifacts/test/rest.test.ts+697 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { RepoPath } from "@repo/protocol/ids";4+import type { CommitSha } from "@repo/protocol/ids";5+import { gitClient } from "@repo/testkit/git-client";6+import { httpBackend } from "@repo/testkit/http-backend";7+import {8+ Duration,9+ Effect,10+ Exit,11+ Layer,12+ Option,13+ Redacted,14+ Ref,15+ Schema,16+} from "effect";17+import type { Scope } from "effect";18+import type { ChildProcessSpawner } from "effect/process";19+import { readCommit } from "isomorphic-git";20+21+import { Fetch, FetchFailed } from "../src/fetch.ts";22+import {23+ BranchName,24+ ForkInProgress,25+ ImportRefused,26+ ObjectId,27+ RefName,28+ RepoExists,29+ RepoHost,30+ RepoName,31+ RepoNotFound,32+ Revision,33+} from "../src/repo-host.ts";34+import type { PushSource } from "../src/repo-host.ts";35+import { RepoHostLocal } from "../src/repo-host/local.ts";36+import { memoryFs } from "../src/repo-host/memory-fs.ts";37+import { RepoHostRest } from "../src/repo-host/rest.ts";38+import { fakeRest } from "./fake-rest.ts";39+import type { FakeRestOptions } from "./fake-rest.ts";40+import { describeRepoHost } from "./repo-host-contract.ts";41+42+const main = RefName.make("refs/heads/main");43+44+const accountId = "0123456789abcdef0123456789abcdef";45+46+const namespace = "projects-test";47+48+const api = `https://api.cloudflare.com/client/v4/accounts/${accountId}/artifacts/namespaces/${namespace}`;49+50+/** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */51+const remoteBase = `https://${accountId}.artifacts.test/git/${namespace}`;52+53+const apiToken = "cf-api-token-for-the-rest-tests";54+55+/** One request as the test's `Fetch` saw it, with its reply. */56+interface Seen {57+ readonly method: string;58+ readonly url: string;59+ readonly headers: readonly (readonly [string, string])[];60+ readonly body: string;61+ readonly status: number;62+ readonly reply: string;63+}64+65+const textOf = (message: Request | Response) =>66+ Effect.promise(() => message.clone().arrayBuffer()).pipe(67+ Effect.map((buffer) => new TextDecoder().decode(buffer))68+ );69+70+const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));71+72+/** What a token's mint answered, as far as these tests read it. */73+const decodeMinted = Schema.decodeEffect(74+ Schema.fromJsonString(75+ Schema.Struct({76+ result: Schema.Struct({ id: Schema.String, plaintext: Schema.String }),77+ })78+ )79+);80+81+/**82+ * The REST adapter over a fake API on local disk: a `RepoHostLocal` in a83+ * temporary directory, behind `fakeRest`, with its remotes served by real84+ * `git http-backend` over the same directory. Every request and reply the85+ * adapter's `Fetch` carries is recorded.86+ */87+const world = (88+ options: Omit<FakeRestOptions, "accountId" | "namespace" | "token"> = {}89+) =>90+ Effect.gen(function* () {91+ const root = yield* RepoHostLocal.temporaryRoot;92+93+ const spawner =94+ yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();95+96+ const backend = httpBackend(root);97+ const seen = yield* Ref.make<readonly Seen[]>([]);98+99+ const git = (request: Request) =>100+ Effect.scoped(backend(request)).pipe(Effect.provide(spawner));101+102+ const store = yield* RepoHost.pipe(103+ Effect.provide(104+ RepoHostLocal.layer({ remoteBase, root }).pipe(105+ Layer.provide(Layer.succeed(Fetch, Fetch.of({ fetch: git })))106+ )107+ )108+ );109+110+ const serve = yield* fakeRest(store, {111+ ...options,112+ accountId,113+ namespace,114+ token: apiToken,115+ });116+117+ const route = (request: Request) => {118+ if (request.url.startsWith(`${api}/`)) {119+ return serve(request);120+ }121+122+ if (request.url.startsWith(`${remoteBase}/`)) {123+ return git(request);124+ }125+126+ return Effect.fail(127+ new FetchFailed({ reason: "no route to host", url: request.url })128+ );129+ };130+131+ const fetch = Fetch.of({132+ fetch: (request) =>133+ Effect.gen(function* () {134+ const body = yield* textOf(request);135+ const response = yield* route(request);136+ const reply = yield* textOf(response);137+138+ yield* Ref.update(seen, (all) => [139+ ...all,140+ {141+ body,142+ headers: [...request.headers.entries()],143+ method: request.method,144+ reply,145+ status: response.status,146+ url: request.url,147+ },148+ ]);149+150+ return response;151+ }),152+ });153+154+ return {155+ layer: RepoHostRest.layer({156+ accountId,157+ namespace,158+ token: Redacted.make(apiToken),159+ }).pipe(Layer.provide(Layer.succeed(Fetch, fetch))),160+ seen,161+ store,162+ };163+ });164+165+type World = Effect.Success<ReturnType<typeof world>>;166+167+/** The REST adapter over a `Fetch` that gives every request the same reply. */168+const answering = (reply: () => Response) =>169+ RepoHostRest.layer({170+ accountId,171+ namespace,172+ token: Redacted.make(apiToken),173+ }).pipe(174+ Layer.provide(175+ Layer.succeed(Fetch, Fetch.of({ fetch: () => Effect.sync(reply) }))176+ )177+ );178+179+/** A refusal in Cloudflare's v4 envelope. */180+const refused = (status: number, code: number, message: string) => () =>181+ Response.json(182+ { errors: [{ code, message }], messages: [], result: null, success: false },183+ { status }184+ );185+186+/** A test body over a fresh world, with the REST adapter's `RepoHost` in scope. */187+const within = <A, E>(188+ body: (189+ world: World190+ ) => Effect.Effect<191+ A,192+ E,193+ RepoHost | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner194+ >,195+ options?: Parameters<typeof world>[0]196+) =>197+ Effect.gen(function* () {198+ const made = yield* world(options);199+200+ return yield* body(made).pipe(Effect.provide(made.layer));201+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));202+203+describeRepoHost(204+ "rest",205+ Layer.unwrap(Effect.map(world(), ({ layer }) => layer)).pipe(206+ Layer.provide(NodeServices.layer)207+ ),208+ {209+ importUrl: (name) =>210+ RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),211+ }212+);213+214+/** A repo `name` with one commit on `main`, and the client that made it. */215+const seeded = (name: RepoName) =>216+ Effect.gen(function* () {217+ const repos = yield* RepoHost;218+ const client = yield* gitClient(memoryFs());219+ const first = yield* client.commit("first", [["a.txt", "1"]]);220+221+ yield* repos.create(name).pipe(Effect.orDie);222+ yield* repos223+ .push(name, client.source, [224+ { from: Option.none(), ref: main, to: first },225+ ])226+ .pipe(Effect.orDie);227+228+ return { client, first };229+ });230+231+/** The requests to one REST route, by method and path under the namespace. */232+const requestsTo = (233+ seen: Ref.Ref<readonly Seen[]>,234+ method: string,235+ path: string236+) =>237+ Ref.get(seen).pipe(238+ Effect.map((all) =>239+ all.filter(240+ (request) =>241+ request.method === method && request.url === `${api}${path}`242+ )243+ )244+ );245+246+/** A commit's tree, read from the client that wrote it. */247+const treeOf = (source: PushSource, oid: CommitSha) =>248+ Effect.promise(() => readCommit({ ...source, oid })).pipe(249+ Effect.map(({ commit }) => ObjectId.make(commit.tree))250+ );251+252+const authorizationOf = ({ headers }: Seen) =>253+ headers.find(([name]) => name === "authorization")?.[1] ?? "";254+255+describe("forks over REST, which name their target", () => {256+ // cf's schema has no `name` for a fork (cf #180); the REST API takes one.257+ it.live("forks the default branch only, to the name it was given", () =>258+ within(({ seen }) =>259+ Effect.gen(function* () {260+ const repos = yield* RepoHost;261+ const base = RepoName.make("demo");262+ const name = RepoName.make("demo--fix--alice");263+ const { first } = yield* seeded(base);264+ const created = yield* repos.fork(base, name).pipe(Effect.orDie);265+ const forks = yield* requestsTo(seen, "POST", `/repos/${base}/fork`);266+267+ expect(created).toStrictEqual({268+ name,269+ remote: `${remoteBase}/${name}.git`,270+ });271+ expect(272+ yield* Effect.forEach(forks, ({ body }) => decodeJson(body))273+ ).toStrictEqual([{ default_branch_only: true, name }]);274+ expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(275+ new Map([[main, first]])276+ );277+ })278+ )279+ );280+281+ // S7 #2: under load a fork answers 500 (code 10400) after making the repo,282+ // and a retry answers 409 (code 10201), or 500 again.283+ it.live.each([284+ { failures: 1, retry: "an already-exists" },285+ { failures: 2, retry: "a second 500" },286+ ])(287+ "makes one fork through a 500 with code 10400 and then $retry",288+ ({ failures }) =>289+ within(290+ ({ seen, store }) =>291+ Effect.gen(function* () {292+ const repos = yield* RepoHost;293+ const base = RepoName.make("demo");294+ const name = RepoName.make("demo--fix--bob");295+ const { first } = yield* seeded(base);296+ const created = yield* repos.fork(base, name).pipe(Effect.orDie);297+298+ const forks = yield* requestsTo(299+ seen,300+ "POST",301+ `/repos/${base}/fork`302+ );303+304+ expect(created).toStrictEqual({305+ name,306+ remote: `${remoteBase}/${name}.git`,307+ });308+ expect(forks.map(({ status }) => status)).toStrictEqual(309+ failures === 1 ? [500, 409] : [500, 500]310+ );311+ expect(312+ yield* Effect.forEach(forks.slice(0, 1), ({ reply }) =>313+ decodeJson(reply)314+ )315+ ).toMatchObject([{ errors: [{ code: 10_400 }], success: false }]);316+ expect(yield* store.refs(name).pipe(Effect.orDie)).toStrictEqual(317+ new Map([[main, first]])318+ );319+ }),320+ { forkFailures: failures }321+ )322+ );323+324+ it.live("reads a fork that two 500s left unmade as ForkInProgress", () =>325+ within(326+ ({ seen, store }) =>327+ Effect.gen(function* () {328+ const repos = yield* RepoHost;329+ const base = RepoName.make("demo");330+ const name = RepoName.make("demo--fix--carol");331+332+ yield* seeded(base);333+334+ expect(yield* Effect.flip(repos.fork(base, name))).toStrictEqual(335+ new ForkInProgress({ name })336+ );337+ expect(338+ yield* requestsTo(seen, "POST", `/repos/${base}/fork`)339+ ).toHaveLength(2);340+ expect(yield* Effect.flip(store.remote(name))).toStrictEqual(341+ new RepoNotFound({ name })342+ );343+ }),344+ { forkFailures: 2, forkLost: true }345+ )346+ );347+});348+349+describe("the tokens the REST adapter carries", () => {350+ it.live(351+ "sends the API token to the API and repo tokens to git, each only as Authorization: Bearer",352+ () =>353+ within(({ seen }) =>354+ Effect.gen(function* () {355+ const repos = yield* RepoHost;356+ const name = RepoName.make("tokens");357+ const at = Revision.Branch({ name: BranchName.make("main") });358+ const { client, first } = yield* seeded(name);359+360+ const second = yield* client.commit(361+ "second",362+ [["a.txt", "2"]],363+ [first]364+ );365+366+ yield* repos367+ .push(name, client.source, [368+ { from: Option.some(first), ref: main, to: second },369+ ])370+ .pipe(Effect.orDie);371+ yield* repos.refs(name).pipe(Effect.orDie);372+ yield* repos.readFile(name, at, RepoPath.make("a.txt"));373+ yield* repos.log(name, at, 5);374+ yield* repos.fork(name, RepoName.make("tokens--fork"));375+376+ const minted = yield* repos.mintToken(377+ name,378+ "read",379+ Duration.minutes(5)380+ );381+382+ yield* repos.revokeToken(name, minted.id);383+384+ const requests = yield* Ref.get(seen);385+ const toApi = requests.filter(({ url }) => url.startsWith(api));386+387+ const toGit = requests.filter(({ url }) =>388+ url.startsWith(remoteBase)389+ );390+391+ const repoTokens = yield* Effect.forEach(392+ yield* requestsTo(seen, "POST", "/tokens"),393+ ({ reply }) =>394+ decodeMinted(reply).pipe(395+ Effect.map(({ result }) => result.plaintext)396+ )397+ );398+399+ const secrets = [apiToken, ...repoTokens];400+401+ const leaks = requests.flatMap(({ body, headers, url }) =>402+ secrets.filter(403+ (secret) =>404+ url.includes(secret) ||405+ body.includes(secret) ||406+ headers.some(407+ ([header, value]) =>408+ header !== "authorization" && value.includes(secret)409+ )410+ )411+ );412+413+ expect(new Set(toApi.map(authorizationOf))).toStrictEqual(414+ new Set([`Bearer ${apiToken}`])415+ );416+ expect(toGit).not.toHaveLength(0);417+ expect(418+ toGit.filter(419+ (request) =>420+ !repoTokens421+ .map((token) => `Bearer ${token}`)422+ .includes(authorizationOf(request))423+ )424+ ).toStrictEqual([]);425+ expect(leaks).toStrictEqual([]);426+ })427+ )428+ );429+430+ it.live(431+ "revokes the tokens it minted for its own git calls when it closes",432+ () =>433+ Effect.gen(function* () {434+ const made = yield* world();435+ const name = RepoName.make("closing");436+437+ yield* Effect.gen(function* () {438+ const repos = yield* RepoHost;439+ const { client, first } = yield* seeded(name);440+441+ const second = yield* client.commit(442+ "second",443+ [["a.txt", "2"]],444+ [first]445+ );446+447+ yield* repos448+ .push(name, client.source, [449+ { from: Option.some(first), ref: main, to: second },450+ ])451+ .pipe(Effect.orDie);452+ yield* repos.refs(name).pipe(Effect.orDie);453+ }).pipe(Effect.provide(made.layer));454+455+ const used = new Set(456+ (yield* Ref.get(made.seen))457+ .filter(({ url }) => url.startsWith(remoteBase))458+ .map(authorizationOf)459+ );460+461+ const ids = yield* Effect.forEach(462+ yield* requestsTo(made.seen, "POST", "/tokens"),463+ ({ reply }) => decodeMinted(reply)464+ ).pipe(465+ Effect.map((all) =>466+ all467+ .filter(({ result }) => used.has(`Bearer ${result.plaintext}`))468+ .map(({ result }) => result.id)469+ )470+ );471+472+ const revoked = yield* Effect.forEach(ids, (id) =>473+ requestsTo(made.seen, "DELETE", `/tokens/${id}`)474+ );475+476+ const live = yield* Effect.forEach(ids, (id) =>477+ made.store.revokeToken(name, id).pipe(Effect.orDie)478+ );479+480+ expect(ids).toHaveLength(2);481+ expect(ids).toHaveLength(used.size);482+ expect(revoked.map((requests) => requests.length)).toStrictEqual([483+ 1, 1,484+ ]);485+ expect(live).toStrictEqual([false, false]);486+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))487+ );488+489+ // cf's help for `tokens revoke`: ids resolve through an eventually490+ // consistent index, so a revocation within about a second of the mint can491+ // be 404.492+ it.live("tries a revocation again when the token index lags its mint", () =>493+ within(494+ ({ seen }) =>495+ Effect.gen(function* () {496+ const repos = yield* RepoHost;497+ const name = RepoName.make("lagging");498+499+ yield* repos.create(name).pipe(Effect.orDie);500+501+ const token = yield* repos502+ .mintToken(name, "read", Duration.minutes(5))503+ .pipe(Effect.orDie);504+505+ expect(506+ yield* repos.revokeToken(name, token.id).pipe(Effect.orDie)507+ ).toBeTruthy();508+ expect(509+ yield* requestsTo(seen, "DELETE", `/tokens/${token.id}`)510+ ).toHaveLength(2);511+ expect(512+ yield* repos.revokeToken(name, token.id).pipe(Effect.orDie)513+ ).toBeFalsy();514+ }),515+ { revokeLag: 1 }516+ )517+ );518+519+ // A removed repo's tokens go with it (workers-types), so git calls to a520+ // repo made again under its name need a token of the new repo's.521+ it.live(522+ "mints a fresh token for git calls to a repo made again under a removed one's name",523+ () =>524+ within(({ seen }) =>525+ Effect.gen(function* () {526+ const repos = yield* RepoHost;527+ const name = RepoName.make("again");528+529+ yield* repos.create(name).pipe(Effect.orDie);530+ yield* repos.refs(name).pipe(Effect.orDie);531+ yield* repos.remove(name);532+ yield* repos.create(name).pipe(Effect.orDie);533+ yield* repos.refs(name).pipe(Effect.orDie);534+535+ // The fake's tokens repeat across a repo's lives, so count mints.536+ const mints = yield* Effect.forEach(537+ yield* requestsTo(seen, "POST", "/tokens"),538+ ({ body }) => decodeJson(body)539+ );540+541+ expect(mints).toMatchObject([542+ { repo: name, scope: "read" },543+ { repo: name, scope: "read" },544+ ]);545+ })546+ )547+ );548+});549+550+describe("Artifacts' error codes, read as the port's errors", () => {551+ // 10104 is "the source URL does not point to a valid git repository", and552+ // 10200 "the repository or remote resource does not exist" (errors page).553+ it.live("refuses an import from no repo, and a token for no repo", () =>554+ within(() =>555+ Effect.gen(function* () {556+ const repos = yield* RepoHost;557+ const name = RepoName.make("imported");558+ const missing = RepoName.make("missing");559+ const url = "file:///nowhere/at/all.git";560+561+ expect(562+ yield* Effect.flip(repos.importFrom(name, { url }))563+ ).toStrictEqual(564+ new ImportRefused({ name, reason: `no repo at ${url}` })565+ );566+ expect(567+ yield* Effect.flip(568+ repos.mintToken(missing, "read", Duration.minutes(5))569+ )570+ ).toStrictEqual(new RepoNotFound({ name: missing }));571+ })572+ )573+ );574+575+ // 10302 is "an import is in progress for this repository", 10303 "a fork576+ // is in progress" (errors page): the name is taken, as `importFrom` reads it.577+ it.effect.each([578+ { code: 10_302, making: "an import" },579+ { code: 10_303, making: "a fork" },580+ ])(581+ "refuses to create a repo while $making of that name is in progress",582+ ({ code, making }) =>583+ Effect.gen(function* () {584+ const repos = yield* RepoHost;585+ const name = RepoName.make("being-made");586+587+ expect(yield* Effect.exit(repos.create(name))).toStrictEqual(588+ Exit.fail(new RepoExists({ name }))589+ );590+ }).pipe(591+ Effect.provide(answering(refused(409, code, `${making} in progress`)))592+ )593+ );594+595+ // A proxy's or an edge's reply carries no envelope: its status is all it says.596+ it.effect("reads a refusal that names no code by its status", () =>597+ Effect.gen(function* () {598+ const repos = yield* RepoHost;599+ const name = RepoName.make("unseen");600+601+ expect(yield* Effect.exit(repos.remote(name))).toStrictEqual(602+ Exit.fail(new RepoNotFound({ name }))603+ );604+ }).pipe(605+ Effect.provide(606+ answering(() => new Response("Not Found", { status: 404 }))607+ )608+ )609+ );610+611+ // Cloudflare's own codes, such as 7000 for a route it does not know, say the612+ // adapter asked for the wrong thing. Read by status, a wrong route, account613+ // or namespace would pass for a missing repo, and a remove for a done one.614+ it.effect(615+ "fails as a defect on a refusal that names only Cloudflare's own codes",616+ () =>617+ Effect.gen(function* () {618+ const repos = yield* RepoHost;619+ const name = RepoName.make("unrouted");620+621+ const died = [622+ Exit.hasDies(yield* Effect.exit(repos.remote(name))),623+ Exit.hasDies(yield* Effect.exit(repos.remove(name))),624+ Exit.hasDies(625+ yield* Effect.exit(626+ repos.readBlob(name, ObjectId.make("0".repeat(40)))627+ )628+ ),629+ ];630+631+ expect(died).toStrictEqual([true, true, true]);632+ }).pipe(633+ Effect.provide(answering(refused(404, 7000, "No route for that URI")))634+ )635+ );636+});637+638+describe("reads whose replies the REST docs do not show", () => {639+ it.live.each([{ casing: "snake" as const }, { casing: "camel" as const }])(640+ "reads a commit and a log whose metadata is in $casing case",641+ ({ casing }) =>642+ within(643+ () =>644+ Effect.gen(function* () {645+ const repos = yield* RepoHost;646+ const name = RepoName.make("metadata");647+ const { client, first } = yield* seeded(name);648+ const written = yield* treeOf(client.source, first);649+650+ const commit = yield* repos651+ .readCommit(name, first)652+ .pipe(Effect.orDie);653+654+ expect(commit).toStrictEqual(655+ Option.some({656+ author: { email: "answerer@example.com", name: "Answerer" },657+ committer: { email: "answerer@example.com", name: "Answerer" },658+ message: "first",659+ parents: [],660+ sha: first,661+ tree: written,662+ })663+ );664+ expect(665+ yield* repos666+ .log(name, Revision.Commit({ sha: first }), 10)667+ .pipe(Effect.orDie)668+ ).toStrictEqual(Option.toArray(commit));669+ }),670+ { casing }671+ )672+ );673+674+ // The binding throws `INTERNAL_ERROR` for a read of the wrong kind; the675+ // fake's REST API answers 500 there (an ASSUMPTION), and the other stores676+ // read no tree (202 Comment 5).677+ it.live("reads no tree at a blob's id or a commit's id", () =>678+ within(() =>679+ Effect.gen(function* () {680+ const repos = yield* RepoHost;681+ const name = RepoName.make("kinds");682+ const { client, first } = yield* seeded(name);683+ const tree = yield* treeOf(client.source, first);684+ const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);685+ const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;686+687+ expect(blob).not.toBe(tree);688+ expect(yield* Effect.exit(repos.readTree(name, blob))).toStrictEqual(689+ Exit.succeed(Option.none())690+ );691+ expect(692+ yield* Effect.exit(repos.readTree(name, ObjectId.make(first)))693+ ).toStrictEqual(Exit.succeed(Option.none()));694+ })695+ )696+ );697+});