Skip to content
Myr

fake-artifacts-binding.test.ts

This file

Path

packages/testkit/test/fake-artifacts-binding.test.ts

461 lines · 13.7 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1–40why, one step back
1import { describe, expect, it } from "@effect/vitest";
2import type { RepoName } from "@repo/protocol/ids";3import { CommitSha } from "@repo/protocol/ids";4import { Data, DateTime, Effect, Match, Option, Redacted } from "effect";56import {7 fakeArtifactsBinding,8 ObjectId,9} from "../src/fake-artifacts-binding.ts";10import type { HostLike } from "../src/fake-artifacts-binding.ts";1112class RepoNotFound extends Data.TaggedError("RepoNotFound")<{13 readonly name: RepoName;14}> {}1516class RepoExists extends Data.TaggedError("RepoExists")<{17 readonly name: RepoName;18}> {}1920class ImportRefused extends Data.TaggedError("ImportRefused")<{21 readonly name: RepoName;22 readonly reason: string;23}> {}2425class Thrown extends Data.TaggedError("Thrown")<{ readonly error: Error }> {}2627const commit = CommitSha.make("c".repeat(40));2829const tree = ObjectId.make("d".repeat(40));3031const subtree = ObjectId.make("e".repeat(40));3233const blob = ObjectId.make("f".repeat(40));3435const hello = new TextEncoder().encode("hello\n");3637const answerer = { email: "answerer@example.com", name: "Answerer" };3839const firstCommit = {40 author: answerer,

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d

lines 41–42why, one step back
41 authoredAt: 1_791_300_000,
42 committedAt: 1_791_300_060,

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 43–212why, one step back
43 committer: answerer,
44 message: "first",45 parents: [],46 sha: commit,47 tree,48};4950const tinyHost = (): HostLike => {51 const repos = new Set<RepoName>();52 let minted = 0;5354 const known = (name: RepoName): Effect.Effect<void, RepoNotFound> =>55 repos.has(name) ? Effect.void : Effect.fail(new RepoNotFound({ name }));5657 const make = (name: RepoName) =>58 repos.has(name)59 ? Effect.fail(new RepoExists({ name }))60 : Effect.sync(() => {61 repos.add(name);6263 return { name, remote: `memory://${name}.git` };64 });6566 return {67 create: make,68 fork: (base, name) => known(base).pipe(Effect.andThen(make(name))),69 importFrom: (name, source) =>70 Effect.fail(71 new ImportRefused({ name, reason: `no repo at ${source.url}` })72 ),73 log: (name, at) =>74 known(name).pipe(75 Effect.as(76 Match.valueTags(at, {77 Branch: ({ name: branch }) => branch === "main",78 Commit: ({ sha }) => sha === commit,79 })80 ? [firstCommit]81 : []82 )83 ),84 mintToken: (name, scope, ttl) =>85 known(name).pipe(86 Effect.map(() => {87 minted += 1;8889 return {90 expiresAt: DateTime.addDuration(91 DateTime.makeUnsafe("2026-10-07T12:00:00Z"),92 ttl93 ),94 id: `token-${minted}`,95 scope,96 secret: Redacted.make(`secret-${minted}`),97 };98 })99 ),100 readBlob: (name, sha) =>101 known(name).pipe(102 Effect.as(sha === blob ? Option.some(hello) : Option.none())103 ),104 readCommit: (name, sha) =>105 known(name).pipe(106 Effect.as(sha === commit ? Option.some(firstCommit) : Option.none())107 ),108 readFile: (name, at, path) =>109 known(name).pipe(110 Effect.as(111 Match.valueTags(at, {112 Branch: ({ name: branch }) => branch === "main",113 Commit: ({ sha }) => sha === commit,114 }) && path === "a.txt"115 ? Option.some(hello)116 : Option.none()117 )118 ),119 readTree: (name, sha) =>120 known(name).pipe(121 Effect.as(122 sha === tree123 ? Option.some([124 {125 mode: "100644" as const,126 name: "a.txt",127 sha: blob,128 type: "blob" as const,129 },130 {131 mode: "040000" as const,132 name: "src",133 sha: subtree,134 type: "tree" as const,135 },136 ])137 : Option.none()138 )139 ),140 remote: (name) => known(name).pipe(Effect.as(`memory://${name}.git`)),141 remove: (name) => Effect.sync(() => repos.delete(name)),142 revokeToken: (name) => known(name).pipe(Effect.as(true)),143 };144};145146const call = <A>(run: () => Promise<A>) =>147 Effect.tryPromise({148 catch: (error) =>149 new Thrown({150 error: error instanceof Error ? error : new Error(String(error)),151 }),152 try: run,153 });154155const thrown = <A>(run: () => Promise<A>) =>156 call(run).pipe(157 Effect.match({158 onFailure: ({ error }) => error,159 onSuccess: (value) => new Error(`resolved with ${String(value)}`),160 })161 );162163const text = (bytes: Blob | null) =>164 bytes === null ? Effect.succeed(null) : call(() => bytes.text());165166const described = (error: Error) => ({167 code: "code" in error ? error.code : undefined,168 isError: error instanceof Error,169 message: error.message,170 name: error.name,171 numericCode: "numericCode" in error ? error.numericCode : undefined,172});173174const withDatekit = (175 options: Parameters<typeof fakeArtifactsBinding>[1] = {}176) =>177 Effect.gen(function* () {178 const binding = fakeArtifactsBinding(tinyHost(), options);179 const created = yield* call(() => binding.create("datekit"));180 const repo = yield* call(() => binding.get("datekit"));181182 return { binding, created, repo };183 });184185describe("the fake Artifacts binding", () => {186 it.effect("creates a repo with a remote and a write token", () =>187 Effect.gen(function* () {188 const { created } = yield* withDatekit();189190 expect(created).toMatchObject({191 defaultBranch: "main",192 description: null,193 name: "datekit",194 remote: "memory://datekit.git",195 token: "secret-1",196 });197 })198 );199200 it.effect("hands back a repo whose reads by object id go to the host", () =>201 Effect.gen(function* () {202 const { repo } = yield* withDatekit();203204 expect(yield* call(() => repo.readTree(tree))).toStrictEqual([205 { hash: blob, mode: "100644", name: "a.txt", type: "blob" },206 { hash: subtree, mode: "40000", name: "src", type: "tree" },207 ]);208 expect(yield* text(yield* call(() => repo.readBlob(blob)))).toBe(209 "hello\n"210 );211 expect(yield* call(() => repo.readCommit(commit))).toStrictEqual({212 author: answerer,

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d

lines 213–214why, one step back
213 authoredAt: 1_791_300_000,
214 committedAt: 1_791_300_060,

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 215–461why, one step back
215 committer: answerer,
216 hash: commit,217 message: "first",218 parents: [],219 treeHash: tree,220 });221 })222 );223224 it.effect("reads null for an object the host doesn't have", () =>225 Effect.gen(function* () {226 const { repo } = yield* withDatekit();227228 expect(yield* call(() => repo.readTree(subtree))).toBeNull();229 expect(yield* call(() => repo.readBlob(tree))).toBeNull();230 expect(yield* call(() => repo.readCommit(blob))).toBeNull();231 })232 );233234 it.effect(235 "throws NOT_FOUND, as an ArtifactsError, for a repo it doesn't have",236 () =>237 Effect.gen(function* () {238 const error = yield* thrown(() =>239 fakeArtifactsBinding(tinyHost()).get("nobody")240 );241242 expect(described(error)).toStrictEqual({243 code: "NOT_FOUND",244 isError: true,245 message: "Repository not found: nobody",246 name: "ArtifactsError",247 numericCode: 0,248 });249 })250 );251252 it.effect(253 "throws plain Errors with no code when codeless, as wrangler dev's remote bindings do (S1 #22)",254 () =>255 Effect.gen(function* () {256 const { binding } = yield* withDatekit({ codeless: true });257 const missing = yield* thrown(() => binding.get("nobody"));258 const again = yield* thrown(() => binding.create("datekit"));259260 expect(described(missing)).toStrictEqual({261 code: undefined,262 isError: true,263 message: "ArtifactsError: Repository not found: nobody",264 name: "Error",265 numericCode: undefined,266 });267 expect(described(again)).toMatchObject({268 code: undefined,269 message: "ArtifactsError: repo already exists: datekit",270 });271 })272 );273274 it.effect(275 "answers a fork under load with a 500 after making it, then a 409 on the retry (S7)",276 () =>277 Effect.gen(function* () {278 const { binding, repo } = yield* withDatekit({ forkFailures: 1 });279 const first = yield* thrown(() => repo.fork("datekit--fix--bob"));280 const made = yield* call(() => binding.get("datekit--fix--bob"));281 const retry = yield* thrown(() => repo.fork("datekit--fix--bob"));282 const next = yield* call(() => repo.fork("datekit--fix--carol"));283284 expect(described(first)).toStrictEqual({285 code: "INTERNAL_ERROR",286 isError: true,287 message: "An internal error occurred.",288 name: "ArtifactsError",289 numericCode: 10_400,290 });291 // The fork was made all the same.292 expect(yield* text(yield* call(() => made.readBlob(blob)))).toBe(293 "hello\n"294 );295 expect(described(retry)).toStrictEqual({296 code: "ALREADY_EXISTS",297 isError: true,298 message: "repo already exists: datekit--fix--bob",299 name: "ArtifactsError",300 numericCode: 10_201,301 });302 expect(next).toMatchObject({ name: "datekit--fix--carol" });303 })304 );305306 it.effect(307 "resolves only short branch names and commit ids in reads by ref (S1 #20)",308 () =>309 Effect.gen(function* () {310 const { repo } = yield* withDatekit();311312 const read = (ref: string) =>313 call(() => repo.readFile({ path: "a.txt", ref })).pipe(314 Effect.flatMap(text)315 );316317 expect(yield* read("refs/heads/main")).toBeNull();318 expect(yield* read("asked/landed")).toBeNull();319 expect([yield* read("main"), yield* read(commit)]).toStrictEqual([320 "hello\n",321 "hello\n",322 ]);323 expect(324 yield* call(() => repo.log({ ref: "refs/heads/main" }))325 ).toStrictEqual([]);326 expect(327 (yield* call(() => repo.log())).map(({ hash }) => hash)328 ).toStrictEqual([commit]);329 })330 );331332 it.effect("refuses a malformed object id, an empty path or a bad name", () =>333 Effect.gen(function* () {334 const { binding, repo } = yield* withDatekit();335336 const codes = [337 yield* thrown(() => repo.readTree("HEAD")),338 yield* thrown(() => repo.readFile({ path: "", ref: "main" })),339 yield* thrown(() => binding.create("no spaces")),340 yield* thrown(() => repo.createToken("read", 59)),341 ].map((error) => described(error).code);342343 expect(codes).toStrictEqual([344 "INVALID_INPUT",345 "INVALID_INPUT",346 "INVALID_REPO_NAME",347 "INVALID_TTL",348 ]);349 })350 );351352 it.effect(353 "serves remotes under a base URL, for a git server the test runs",354 () =>355 Effect.gen(function* () {356 const { created, repo } = yield* withDatekit({357 remoteBase: "http://127.0.0.1:9000/git",358 });359360 const info = yield* call(() => repo.info());361362 expect(created.remote).toBe("http://127.0.0.1:9000/git/datekit.git");363 expect(info).toMatchObject({364 defaultBranch: "main",365 lastPushAt: null,366 name: "datekit",367 remote: "http://127.0.0.1:9000/git/datekit.git",368 source: null,369 });370 })371 );372373 it.effect("mints, lists and revokes tokens through the host", () =>374 Effect.gen(function* () {375 const { repo } = yield* withDatekit();376 const token = yield* call(() => repo.createToken("read", 60));377 const revoked = yield* call(() => repo.revokeToken("secret-2"));378 const { tokens } = yield* call(() => repo.listTokens());379380 expect(token).toStrictEqual({381 expiresAt: "2026-10-07T12:01:00.000Z",382 id: "token-2",383 plaintext: "secret-2",384 scope: "read",385 });386 expect(revoked).toBeTruthy();387 expect(tokens.map(({ id, state }) => [id, state])).toStrictEqual([388 ["token-1", "active"],389 ["token-2", "revoked"],390 ]);391 })392 );393394 it.effect("lists and deletes what it made", () =>395 Effect.gen(function* () {396 const { binding } = yield* withDatekit();397398 yield* call(() => binding.create("burrow"));399400 const listed = yield* call(() => binding.list());401 const deleted = yield* call(() => binding.delete("datekit"));402 const again = yield* call(() => binding.delete("datekit"));403 const gone = yield* thrown(() => binding.get("datekit"));404405 expect(listed).toMatchObject({ total: 2 });406 expect(listed.repos.map(({ name }) => name)).toStrictEqual([407 "datekit",408 "burrow",409 ]);410 expect([deleted, again]).toStrictEqual([true, false]);411 expect(described(gone).code).toBe("NOT_FOUND");412 })413 );414415 it.effect("reports a repo made read-only as read-only", () =>416 Effect.gen(function* () {417 const { binding, repo } = yield* withDatekit();418419 yield* call(() => binding.create("archive", { readOnly: true }));420 yield* call(() => repo.fork("datekit--mirror", { readOnly: true }));421422 const { repos } = yield* call(() => binding.list());423424 expect(repos.map(({ name, readOnly }) => [name, readOnly])).toStrictEqual(425 [426 ["datekit", false],427 ["archive", true],428 ["datekit--mirror", true],429 ]430 );431 })432 );433434 it.effect(435 "lists nothing it deleted, even after a stale handle reads the repo",436 () =>437 Effect.gen(function* () {438 const { binding, repo } = yield* withDatekit();439440 yield* call(() => binding.delete("datekit"));441442 const codes = [443 yield* thrown(() => repo.info()),444 yield* thrown(() => repo.log()),445 yield* thrown(() => repo.revokeToken("secret-1")),446 yield* thrown(() => repo.listTokens()),447 ].map((error) => described(error).code);448449 expect(codes).toStrictEqual([450 "NOT_FOUND",451 "NOT_FOUND",452 "NOT_FOUND",453 "NOT_FOUND",454 ]);455 expect(yield* call(() => binding.list())).toStrictEqual({456 repos: [],457 total: 0,458 });459 })460 );461});