Skip to content
Myr

fake-artifacts-binding.ts

This file

Path

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

663 lines · 18.4 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

1/**2 * Keeps the surprises found in the real binding: codeless `Error`s under3 * `wrangler dev`, a fork's 500-then-409 under load, reads that resolve short4 * branch names and commit ids only, `info().lastPushAt` staying `null`, and5 * rate-limited reads (ASSUMPTION: the refusal names the limit in its message;6 * no live one has been seen yet).7 *8 * It takes its host structurally (`HostLike`), so `@repo/testkit` depends on9 * no adapter package.10 */11import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";12import {13  Data,14  DateTime,15  Duration,16  Effect,17  Match,18  Option,19  Redacted,20  Schema,21} from "effect";22import { constVoid } from "effect/Function";2324import { defaultNow } from "./clock.ts";2526export const ObjectId = Schema.String.pipe(27  Schema.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),28  Schema.brand("ObjectId")29);3031export type ObjectId = typeof ObjectId.Type;3233export const BranchName = Schema.String.pipe(34  Schema.check(35    Schema.isPattern(36      /^(?!refs\/)(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u37    )38  ),39  Schema.brand("BranchName")40);4142export type BranchName = typeof BranchName.Type;4344export type Revision = Data.TaggedEnum<{45  Branch: { readonly name: BranchName };46  Commit: { readonly sha: CommitSha };47}>;4849export const Revision = Data.taggedEnum<Revision>();5051export type HostError =52  | { readonly _tag: "RepoNotFound"; readonly name: RepoName }53  | { readonly _tag: "RepoExists"; readonly name: RepoName }54  | { readonly _tag: "ForkInProgress"; readonly name: RepoName }55  | {56      readonly _tag: "ImportRefused";57      readonly name: RepoName;58      readonly reason: string;59    }60  | { readonly _tag: "HostBusy"; readonly name: RepoName };6162interface Person {63  readonly email: string;64  readonly name: string;65}6667interface HostCommit {68  readonly author: Person;69  readonly authoredAt: number;70  readonly committedAt: number;71  readonly committer: Person;72  readonly message: string;73  readonly parents: readonly string[];74  readonly sha: string;75  readonly tree: string;76}7778interface HostTreeEntry {79  readonly mode: "100644" | "100755" | "120000" | "040000" | "160000";80  readonly name: string;81  readonly sha: string;82  readonly type: "blob" | "tree" | "commit";83}8485interface HostCreated {86  readonly name: string;87  readonly remote: string;88}8990export interface HostLike {91  readonly create: (name: RepoName) => Effect.Effect<HostCreated, HostError>;92  readonly importFrom: (93    name: RepoName,94    source: { readonly url: string; readonly branch?: BranchName }95  ) => Effect.Effect<HostCreated, HostError>;96  readonly fork: (97    base: RepoName,98    name: RepoName99  ) => Effect.Effect<HostCreated, HostError>;100  readonly remove: (name: RepoName) => Effect.Effect<boolean>;101  readonly mintToken: (102    name: RepoName,103    scope: "read" | "write",104    ttl: Duration.Duration105  ) => Effect.Effect<106    {107      readonly id: string;108      readonly secret: Redacted.Redacted;109      readonly scope: "read" | "write";110      readonly expiresAt: DateTime.Utc;111    },112    HostError113  >;114  readonly revokeToken: (115    name: RepoName,116    id: string117  ) => Effect.Effect<boolean, HostError>;118  readonly remote: (name: RepoName) => Effect.Effect<string, HostError>;119  readonly readFile: (120    name: RepoName,121    at: Revision,122    path: RepoPath123  ) => Effect.Effect<Option.Option<Uint8Array>, HostError>;124  readonly readCommit: (125    name: RepoName,126    sha: CommitSha127  ) => Effect.Effect<Option.Option<HostCommit>, HostError>;128  readonly readTree: (129    name: RepoName,130    tree: ObjectId131  ) => Effect.Effect<Option.Option<readonly HostTreeEntry[]>, HostError>;132  readonly readBlob: (133    name: RepoName,134    blob: ObjectId135  ) => Effect.Effect<Option.Option<Uint8Array>, HostError>;136  readonly log: (137    name: RepoName,138    at: Revision,139    limit: number140  ) => Effect.Effect<readonly HostCommit[], HostError>;141}142143export interface FakeOptions {144  readonly codeless?: boolean;145  readonly forkFailures?: number;146  readonly remoteBase?: string;147  readonly defaultBranch?: string;148  /**149   * How many of a just-imported repo's first `get`s answer150   * `IMPORT_IN_PROGRESS`: an import Artifacts is still copying after151   * `import()` returned, as a large one is.152   */153  readonly importing?: number;154  readonly rateLimited?: number;155}156157class Refused extends Data.TaggedError("Refused")<{158  readonly code: ArtifactsError["code"];159  readonly reason: string;160}> {}161162/**163 * The REST API's numeric code for each binding code. The probes recorded two164 * (10201 and 10400); the rest are unknown and read 0, so tests match on165 * `code`.166 */167const numericCodes = {168  ALREADY_EXISTS: 10_201,169  INTERNAL_ERROR: 10_400,170} as const;171172const numericOf = (code: ArtifactsError["code"]) =>173  Match.value(code).pipe(174    Match.when("ALREADY_EXISTS", () => numericCodes.ALREADY_EXISTS),175    Match.when("INTERNAL_ERROR", () => numericCodes.INTERNAL_ERROR),176    Match.orElse(() => 0)177  );178179const refusalOf = (error: HostError | Refused) =>180  Match.valueTags(error, {181    ForkInProgress: ({ name }) =>182      new Refused({183        code: "FORK_IN_PROGRESS",184        reason: `Fork in progress: ${name}`,185      }),186    HostBusy: () =>187      new Refused({188        code: "INTERNAL_ERROR",189        reason: "An internal error occurred.",190      }),191    ImportRefused: ({ reason }) => new Refused({ code: "INVALID_URL", reason }),192    Refused: (refused) => refused,193    RepoExists: ({ name }) =>194      new Refused({195        code: "ALREADY_EXISTS",196        reason: `repo already exists: ${name}`,197      }),198    RepoNotFound: ({ name }) =>199      new Refused({200        code: "NOT_FOUND",201        reason: `Repository not found: ${name}`,202      }),203  });204205interface Kept {206  readonly id: string;207  readonly name: RepoName;208  readonly description: string | null;209  readonly defaultBranch: string;210  readonly source: string | null;211  readonly readOnly: boolean;212  readonly tokens: Map<213    string,214    ArtifactsTokenInfo & { readonly plaintext: string }215  >;216}217218// Artifacts stamps repos with the time they were made; the fake with the219// scenarios' fixed instant, so two runs give the same values.220const stamped = DateTime.formatIso(defaultNow);221222const isObjectId = Schema.is(ObjectId);223224const decodeName = Schema.decodeUnknownOption(RepoName);225226const decodeBranch = Schema.decodeUnknownOption(BranchName);227228const decodePath = Schema.decodeUnknownOption(RepoPath);229230const revisionOf = (ref: string): Option.Option<Revision> =>231  isObjectId(ref)232    ? Option.some(Revision.Commit({ sha: CommitSha.make(ref) }))233    : Option.map(decodeBranch(ref), (name) => Revision.Branch({ name }));234235// Artifacts gives canonical modes: a folder is `40000`, not `040000`.236const typeOf = (entry: HostTreeEntry): ArtifactsTreeEntryType =>237  Match.value(entry.mode).pipe(238    Match.when("040000", () => "tree" as const),239    Match.when("100755", () => "exec" as const),240    Match.when("120000", () => "symlink" as const),241    Match.when("160000", () => "gitlink" as const),242    Match.orElse(() => "blob" as const)243  );244245const entryOf = (entry: HostTreeEntry): ArtifactsTreeEntry => ({246  hash: entry.sha,247  mode: entry.mode.replace(/^0/u, ""),248  name: entry.name,249  type: typeOf(entry),250});251252const metadataOf = (commit: HostCommit): ArtifactsCommitMetadata => ({253  author: { email: commit.author.email, name: commit.author.name },254  authoredAt: commit.authoredAt,255  committedAt: commit.committedAt,256  committer: { email: commit.committer.email, name: commit.committer.name },257  hash: commit.sha,258  message: commit.message,259  parents: [...commit.parents],260  treeHash: commit.tree,261});262263const refuse = (code: ArtifactsError["code"], reason: string) =>264  Effect.fail(new Refused({ code, reason }));265266const named = (name: string, code: ArtifactsError["code"]) =>267  Option.match(decodeName(name), {268    onNone: () => refuse(code, `Invalid repository name: ${name}`),269    onSome: Effect.succeed,270  });271272const objectId = (hash: string): Effect.Effect<ObjectId, Refused> =>273  isObjectId(hash)274    ? Effect.succeed(hash)275    : refuse("INVALID_INPUT", `Invalid object id: ${hash}`);276277const blobOf = (bytes: Uint8Array) =>278  new Blob([bytes], { type: "application/octet-stream" });279280export const fakeArtifactsBinding = (281  host: HostLike,282  options: FakeOptions = {}283): Artifacts => {284  const kept = new Map<RepoName, Kept>();285  let forkFailures = options.forkFailures ?? 0;286  let rateLimited = options.rateLimited ?? 0;287  let made = 0;288  const importing = new Map<RepoName, number>();289290  const thrown = ({ code, reason }: Refused) =>291    options.codeless === true292      ? new Error(`ArtifactsError: ${reason}`)293      : Object.assign(new Error(reason), {294          code,295          name: "ArtifactsError" as const,296          numericCode: numericOf(code),297        });298299  const run = <A>(effect: Effect.Effect<A, Refused | HostError>) =>300    Effect.runPromise(301      Effect.mapError(effect, (failure) => thrown(refusalOf(failure)))302    );303304  const limited = () =>305    options.codeless === true306      ? new Error("ArtifactsError: Too many requests: rate limit exceeded")307      : Object.assign(new Error("Too many requests: rate limit exceeded"), {308          code: "RATE_LIMITED",309          name: "ArtifactsError" as const,310          numericCode: 0,311        });312313  const read = <A>(effect: Effect.Effect<A, Refused | HostError>) => {314    if (rateLimited > 0) {315      rateLimited -= 1;316317      return Promise.reject(limited());318    }319320    return run(effect);321  };322323  const remoteOf = (name: RepoName) =>324    options.remoteBase === undefined325      ? host.remote(name)326      : host.remote(name).pipe(Effect.as(`${options.remoteBase}/${name}.git`));327328  const keep = (329    name: RepoName,330    fields: Partial<331      Pick<Kept, "description" | "defaultBranch" | "readOnly" | "source">332    >333  ) => {334    made += 1;335336    const repo: Kept = {337      defaultBranch: fields.defaultBranch ?? "main",338      description: fields.description ?? null,339      id: `repo-${String(made).padStart(6, "0")}`,340      name,341      readOnly: fields.readOnly ?? false,342      source: fields.source ?? null,343      tokens: new Map(),344    };345346    kept.set(name, repo);347348    return repo;349  };350351  const keptOf = (name: RepoName) =>352    host.remote(name).pipe(Effect.map(() => kept.get(name) ?? keep(name, {})));353354  const mint = (name: RepoName, scope: "read" | "write", seconds: number) =>355    Effect.gen(function* () {356      const token = yield* host.mintToken(357        name,358        scope,359        Duration.seconds(seconds)360      );361362      const { tokens } = yield* keptOf(name);363      const plaintext = Redacted.value(token.secret);364      const expiresAt = DateTime.formatIso(token.expiresAt);365366      tokens.set(token.id, {367        createdAt: stamped,368        expiresAt,369        id: token.id,370        plaintext,371        scope,372        state: "active",373      });374375      return { expiresAt, id: token.id, plaintext, scope: token.scope };376    });377378  const createdOf = (repo: Kept) =>379    Effect.gen(function* () {380      const remote = yield* remoteOf(repo.name);381      const token = yield* mint(repo.name, "write", 86_400);382383      return {384        defaultBranch: repo.defaultBranch,385        description: repo.description,386        id: repo.id,387        name: repo.name,388        remote,389        token: token.plaintext,390      };391    });392393  const summaryOf = (repo: Kept): Omit<ArtifactsRepoInfo, "remote"> => ({394    createdAt: stamped,395    defaultBranch: repo.defaultBranch,396    description: repo.description,397    id: repo.id,398    // Still null after pushes.399    lastPushAt: null,400    name: repo.name,401    readOnly: repo.readOnly,402    source: repo.source,403    updatedAt: stamped,404  });405406  const info = (repo: Kept) =>407    remoteOf(repo.name).pipe(408      Effect.map((remote): ArtifactsRepoInfo => ({409        ...summaryOf(repo),410        remote,411      }))412    );413414  const handle = (name: RepoName): ArtifactsRepo => ({415    createToken: (scope = "write", ttl = 86_400) =>416      run(417        ttl < 60 || ttl > 31_536_000418          ? refuse("INVALID_TTL", `ttl must be between 60 and 31536000: ${ttl}`)419          : mint(name, scope, ttl).pipe(420              Effect.map(({ expiresAt, id, plaintext }) => ({421                expiresAt,422                id,423                plaintext,424                scope,425              }))426            )427      ),428    fork: (target, forkOptions) =>429      run(430        Effect.gen(function* () {431          const fork = yield* named(target, "INVALID_REPO_NAME");432433          yield* host.fork(name, fork);434435          const repo = keep(fork, {436            description: forkOptions?.description ?? null,437            readOnly: forkOptions?.readOnly ?? false,438            source: `artifacts:fake/${name}`,439          });440441          if (forkFailures > 0) {442            forkFailures -= 1;443444            return yield* refuse(445              "INTERNAL_ERROR",446              "An internal error occurred."447            );448          }449450          return yield* createdOf(repo);451        })452      ),453    info: () => run(keptOf(name).pipe(Effect.flatMap(info))),454    listTokens: () =>455      run(456        keptOf(name).pipe(457          Effect.map((repo) => {458            const tokens = [...repo.tokens.values()].map(459              ({ createdAt, expiresAt, id, scope, state }) => ({460                createdAt,461                expiresAt,462                id,463                scope,464                state,465              })466            );467468            return { tokens, total: tokens.length };469          })470        )471      ),472    log: (logOptions) =>473      read(474        Effect.gen(function* () {475          const ref = logOptions?.ref ?? "HEAD";476          const limit = Math.min(logOptions?.limit ?? 50, 1000);477          const offset = logOptions?.offset ?? 0;478479          const at = revisionOf(480            ref === "HEAD" ? (yield* keptOf(name)).defaultBranch : ref481          );482483          if (Option.isNone(at)) {484            return [];485          }486487          const commits = yield* host.log(name, at.value, offset + limit);488489          return commits.slice(offset).map(metadataOf);490        })491      ),492    readBlob: (hash) =>493      read(494        objectId(hash).pipe(495          Effect.flatMap((blob) => host.readBlob(name, blob)),496          Effect.map((bytes) => Option.getOrNull(Option.map(bytes, blobOf)))497        )498      ),499    readCommit: (hash) =>500      read(501        objectId(hash).pipe(502          Effect.flatMap((sha) => host.readCommit(name, CommitSha.make(sha))),503          Effect.map((commit) =>504            Option.getOrNull(Option.map(commit, metadataOf))505          )506        )507      ),508    readFile: ({ path, ref }) =>509      read(510        Effect.gen(function* () {511          const file = decodePath(path);512          const at = revisionOf(ref);513514          if (ref === "" || Option.isNone(file)) {515            return yield* refuse(516              "INVALID_INPUT",517              "ref and path must not be empty"518            );519          }520521          if (Option.isNone(at)) {522            return null;523          }524525          const bytes = yield* host.readFile(name, at.value, file.value);526527          return Option.getOrNull(Option.map(bytes, blobOf));528        })529      ),530    readTree: (hash) =>531      read(532        objectId(hash).pipe(533          Effect.flatMap((tree) => host.readTree(name, tree)),534          Effect.map((entries) =>535            Option.getOrNull(Option.map(entries, (each) => each.map(entryOf)))536          )537        )538      ),539    revokeToken: (tokenOrId) =>540      run(541        Effect.gen(function* () {542          if (tokenOrId === "") {543            return yield* refuse(544              "INVALID_INPUT",545              "tokenOrId must not be empty"546            );547          }548549          const { tokens } = yield* keptOf(name);550551          const token = [...tokens.values()].find(552            ({ id, plaintext }) => id === tokenOrId || plaintext === tokenOrId553          );554555          const revoked = yield* host.revokeToken(name, token?.id ?? tokenOrId);556557          if (token !== undefined && revoked) {558            tokens.set(token.id, { ...token, state: "revoked" });559          }560561          return revoked;562        })563      ),564    [Symbol.dispose]: constVoid,565  });566567  return {568    create: (name, createOptions) =>569      run(570        Effect.gen(function* () {571          const repoName = yield* named(name, "INVALID_REPO_NAME");572573          yield* host.create(repoName);574575          return yield* createdOf(576            keep(repoName, {577              defaultBranch: createOptions?.setDefaultBranch ?? "main",578              description: createOptions?.description ?? null,579              readOnly: createOptions?.readOnly ?? false,580            })581          );582        })583      ),584    delete: (name) =>585      run(586        Effect.gen(function* () {587          const repoName = yield* named(name, "INVALID_REPO_NAME");588589          kept.delete(repoName);590591          return yield* host.remove(repoName);592        })593      ),594    get: (name) =>595      run(596        Effect.gen(function* () {597          const repoName = yield* named(name, "NOT_FOUND");598599          yield* host.remote(repoName);600601          const left = importing.get(repoName) ?? 0;602603          if (left > 0) {604            importing.set(repoName, left - 1);605606            return yield* refuse(607              "IMPORT_IN_PROGRESS",608              `Import in progress: ${repoName}`609            );610          }611612          return handle(repoName);613        })614      ),615    import: ({ source, target }) =>616      run(617        Effect.gen(function* () {618          const repoName = yield* named(target.name, "INVALID_REPO_NAME");619620          const branch = Option.fromNullishOr(source.branch).pipe(621            Option.flatMap(decodeBranch)622          );623624          yield* host.importFrom(625            repoName,626            Option.match(branch, {627              onNone: () => ({ url: source.url }),628              onSome: (name) => ({ branch: name, url: source.url }),629            })630          );631632          importing.set(repoName, options.importing ?? 0);633634          return yield* createdOf(635            keep(repoName, {636              defaultBranch: Option.getOrElse(637                branch,638                () => options.defaultBranch ?? "main"639              ),640              description: target.opts?.description ?? null,641              readOnly: target.opts?.readOnly ?? false,642              source: source.url,643            })644          );645        })646      ),647    list: (listOptions) =>648      run(649        Effect.sync(() => {650          const limit = Math.min(Math.max(listOptions?.limit ?? 50, 1), 200);651          const from = Number(listOptions?.cursor ?? "0");652          const all = [...kept.values()];653654          const repos = all.slice(from, from + limit).map(summaryOf);655          const next = from + limit;656657          return next < all.length658            ? { cursor: String(next), repos, total: all.length }659            : { repos, total: all.length };660        })661      ),662  };663};