Skip to content
Myr

Import any default branch, adopt on a retry, and add import-examples

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

- adopt() takes main's tip, else the named branch's, else the one refs/heads/* the import made, so `init --import` of a master-default repo (anyhow, stb, fuzzel) adopts without --branch; mainAt makes main. - adopt() treats RepoExists as this project's earlier, unfinished import (it runs only while the DO has no row): it waits for the repo and adopts it, instead of answering ProjectExists. A project that exists still answers ProjectExists. ASSUMPTION: the retry names the same remote. - The binding waits for IMPORT_IN_PROGRESS up to 16 more asks (about 176 s, exponential from 250 ms, each sleep capped at 16 s); CREATE_IN_PROGRESS keeps its 7 (31.75 s). - The memory and local file imports take HEAD's branch, else the remote's one branch (`defaultRefOf` in isogit-store.ts, beside the two adapters that share it). Over smart HTTP a dangling HEAD cannot be fetched by isomorphic-git, so the contract's master case runs on memory and local, and the binding test imports an HTTP remote whose HEAD names master. - testkit's fake binding: `importing` (an import's first n gets answer IMPORT_IN_PROGRESS) and `defaultBranch` (what an import reports). - scripts/import-examples.ts: the eight repos as data, anyhow first; --stage (refuses demo before building anything) or --world node; --only; --dry-run; skips listed projects; /rpc as the operator (OPERATOR_TOKEN); heads and tags counts from anonymous ls-remote; two ledger lines per new import, by "import". --tags fetches the source's tags into a temp bare repo and pushes refs/tags/* only, with a ten-minute write token from RepoHostRest carried in git's env as an http.extraHeader, revoked in Effect.ensuring; a backfill appends a repo line noting "tags backfilled". Tags are fetched rather than `clone --mirror`, which would bring every refs/pull/* GitHub keeps. - The ledger accepts by: "import" and an optional note; teardown lists imports as "kept import" and never selects them or their forks; infra/stages.md §3 says so. - Tests: project/test/import.test.ts (master adopts, a died import adopts on retry, ProjectExists stays); artifacts contract master case, binding.test.ts (master HEAD over HTTP, 12 busy answers, create budget unchanged, past the wait then RepoExists then a read); config import-examples.test.ts (plan, skip, ledger, dry run, demo refused, backfill commands and token never shown) and teardown.test.ts (imports kept). Live: `--world node --only anyhow` imported anyhow (master) with 2 heads, 0 tags.

authored by oscabriel · committed by oscabriel · parent bbe1442 · Browse files · 20 files+2039 added−43 removed
This commit

State

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

Diff stats

20 files+2039 added−43 removed

  • tests:+841 added−0 removed
  • other:+1198 added−43 removed

20 files+2039 added−43 removed

modified:infra/lib/teardown.ts+24 added-7 removed
9 unmodified lines
10 * (`projects-<s>`, `layers-<s>`), and the seeded examples it keeps (`datekit`11 * with its maintainers layer, and `burrow`) with every fork of them, since a12 * claim on demo's burrow during the take is recorded and must outlive it. Nor13 * is anything in `witness`, which belongs to another project and is never even14 * read. Workers, D1, KV and14 * read. The imported preview repos (`by: "import"`) are kept like the seeded15 * examples, with every fork of them: listed as "kept imports", never16 * selected; deleting one is a person's Cloudflare delete. Workers, D1, KV and17 * R2 are not Artifacts, so no listing names them and no plan can hold them. A18 * project entry is a Durable Object and a front-page row: teardown leaves both19 * (they are harmless, and not billed at this size), and says so.20 *
63 unmodified lines
84 /** Projects whose repos stay (`--keep`): the project's repo and every `<project>--…`. */85 readonly keep?: readonly string[];86}8788/** The projects the ledger records as kept imports, on any stage. */89const importsOf = (ledger: readonly Created[]): ReadonlySet<string> =>90 new Set(ledger.flatMap(({ by, name }) => (by === "import" ? [name] : [])));9192/** Whether a ledger entry is a namespace or repo teardown may ever delete. */87const deletable = (entry: Created, guarded: ReadonlySet<string>) =>93const deletable = (94 entry: Created,95 guarded: ReadonlySet<string>,96 imported: ReadonlySet<string>97) =>98 !guarded.has(entry.name) &&99 !examples.some((example) => ofProject(entry.name, example)) &&100 ![...imported].some((kept) => ofProject(entry.name, kept)) &&101 (entry.kind === "namespace" ||102 (entry.kind === "repo" &&103 entry.namespace !== undefined &&104 entry.namespace !== witness));
5 unmodified lines
110 * `witness`, and not kept.111 */112const candidatesOf = (scope: Scope): readonly Created[] => {113 const guarded = protectedNames([...declared, ...scope.stages]);114 const imported = importsOf(scope.ledger);115116 return scope.ledger.filter(117 (entry) =>118 entry.deletedAt === undefined &&119 scope.stages.some((stage) => stage === entry.stage) &&108 deletable(entry, guarded) &&120 deletable(entry, guarded, imported) &&121 !(scope.keep ?? []).some((kept) => ofProject(entry.name, kept))122 );123};124
197 unmodified lines
322 const there = new Set(listed.map(keyOf));323 const live = entries.filter(({ deletedAt }) => deletedAt === undefined);324 const chosen = new Set(candidates.map(keyOf));325 const guarded = protectedNames([...declared, stage]);326 const imported = importsOf(ledger);327328 const kept = live.filter(329 (entry) =>317 deletable(entry, guarded) &&330 deletable(entry, guarded, imported) &&331 options.keep.some((name) => ofProject(entry.name, name))332 );333334 const keptImports = live.filter(({ by }) => by === "import");335336 const never = live.filter(337 (entry) =>338 entry.kind !== "project" &&339 !chosen.has(keyOf(entry)) &&325 !kept.includes(entry)340 !kept.includes(entry) &&341 !keptImports.includes(entry)342 );343328 const projects = live.flatMap(({ kind, name }) =>329 kind === "project" ? [name] : []344 const projects = live.flatMap(({ by, kind, name }) =>345 kind === "project" && by !== "import" ? [name] : []346 );347348 yield* Console.log(349 `teardown on ${stage}: ${entries.length} ledger entries, ${plan.length} to delete`
5 unmodified lines
355 ...unique.flatMap((entry) =>356 there.has(keyOf(entry)) ? [] : [` gone already: ${shown(entry)}`]357 ),358 ...kept.map((entry) => ` kept by --keep: ${shown(entry)}`),359 ...keptImports.map((entry) => ` kept import: ${shown(entry)}`),360 ...never.map((entry) => ` never selectable: ${shown(entry)}`),361 ...(projects.length === 0362 ? []363 : [
81 unmodified lines
modified:infra/created.ts+11 added-3 removed
modified:infra/stages.md+2 added
103 unmodified lines
104- The secret `S8B_PROBE` on `platform-dev-oscabriel`.105- The test accounts `w3tester-muyk9zdx` and `w5web-muz3airr` in `front-page-dev-oscabriel` (no identity or credit rows), and their OAuth grants in `oauth-dev-oscabriel`: one for `w5web-muz3airr` and two for `w3tester-muyk9zdx`.106- The Project Durable Objects and front-page rows of those test projects. They are harmless and are not deleted.107108Imported projects (kept). `bun scripts/import-examples.ts --stage dev-oscabriel` imports the open-source repos the code browser is previewed on (anyhow, ky, gum, click, awesome, changesets, stb and fuzzel), one at a time, and records each in the ledger with `by: "import"`: one `project` line and one `repo` line in `projects-dev-oscabriel`, plus a `tags backfilled` note when `--tags` pushed their tags. They are not throwaways: teardown lists them as "kept imports" and never selects them, nor any fork of them, as it keeps the seeded examples. Deleting one is a person's Cloudflare delete. The script refuses `demo`.109110`demo` has no throwaways: `projects-demo` holds `datekit` and `burrow`, and `layers-demo` holds `datekit--maintainers`. Nothing that makes throwaways is meant to run there before the take: the core-loop smoke and the swarm's rehearsals run on the dev stage, the swarm on a `seed --as` copy. The take's swarm on demo's `burrow` will record its claim forks in the ledger; teardown never selects them (section 4).111112## 4. Teardown policy113
185 unmodified lines
modified:packages/artifacts/src/repo-host/binding.ts+29 added-10 removed
15 unmodified lines
16 * after it; the token goes nowhere but the `Authorization` header of the17 * adapter's own requests. The day-long write token a create, a fork or an18 * import hands back is revoked at once: any write token can force-push19 * `main`, and no caller needs it. A repo still being20 * created or imported is asked for again, from 250 ms apart, up to eight21 * times. Every repo handle is disposed after use.20 * created is asked for again, from 250 ms apart, up to seven more times21 * (about 32 s); one still being imported up to sixteen (about 3 minutes),22 * each sleep at most 16 s. Every repo handle is disposed after use.23 */24import {25 Data,26 DateTime,
170 unmodified lines
197 };198 })199 ).pipe(Effect.orDie);200200/** Whether `get` found the repo still being created or imported. */201const stillMaking = (thrown: Thrown) =>202 threw("CREATE_IN_PROGRESS")(thrown) || threw("IMPORT_IN_PROGRESS")(thrown);201/**202 * How many times `get` is asked again while the repo is still being made:203 * a create about 32 s in all, and an import, which copies a whole history204 * and may outlast `import()` itself, about 3 minutes. Anything else is205 * never asked again.206 */207const asksWhileMaking = (thrown: Thrown) =>208 Match.value(thrown).pipe(209 Match.when(threw("CREATE_IN_PROGRESS"), () => 7),210 Match.when(threw("IMPORT_IN_PROGRESS"), () => 16),211 Match.orElse(() => 0)212 );213214/**215 * From 250 ms apart, doubling, each sleep at most 16 s: 250 ms … 16 s for a216 * create's seven asks (31.75 s), then 16 s apart for an import's nine more217 * (175.75 s in all).218 */219const whileMaking = Schedule.min([220 Schedule.exponential(Duration.millis(250)),221 Schedule.spaced(Duration.seconds(16)),222]).pipe(223 Schedule.setInputType<Thrown>(),224 Schedule.while(({ attempt: asked, input }) => asked <= asksWhileMaking(input))225);226227/** A handle to `name`, asked for again while the repo is still being made. */228const handleOf = (binding: Artifacts, name: RepoName) =>229 attempt(() => binding.get(name)).pipe(207 Effect.retry({208 schedule: Schedule.exponential(Duration.millis(250)),209 times: 7,210 while: stillMaking,211 }),230 Effect.retry(whileMaking),231 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))232 );233234/** `use` over a handle to `name`, disposed after, whatever `use` came to. */
358 unmodified lines
modified:packages/artifacts/src/repo-host/isogit-store.ts+37 added-1 removed
1import { CommitSha } from "@repo/protocol/ids";2import { Array, Data, Effect, Equal, Match, Option, Schema } from "effect";2import {3 Array,4 Data,5 Effect,6 Equal,7 Match,8 Option,9 Predicate,10 Schema,11} from "effect";12import type { Semaphore } from "effect";13import {14 Errors,15 currentBranch,16 init,17 listBranches,18 listRefs,19 readBlob,20 readCommit,21 readTag,
82 unmodified lines
104 unlessMissing(() => resolveRef({ ...repo, ref })).pipe(105 Effect.map(Option.map((sha) => CommitSha.make(sha)))106 );107108/**109 * The ref a remote's import takes when none is named: the branch its HEAD110 * names, or, when HEAD names a branch it lacks (a store made here names111 * `main`), its one branch, as a remote whose default is `master` has it.112 * Otherwise what HEAD names, even a branch it lacks; `None` only for a113 * detached HEAD.114 */115export const defaultRefOf = (repo: GitDir) =>116 Effect.gen(function* () {117 const head = Option.filter(118 yield* unlessMissing(() => currentBranch({ ...repo, fullname: true })),119 Predicate.isString120 );121122 if (Option.isSome(head) && Option.isSome(yield* tipOf(repo, head.value))) {123 return head;124 }125126 const branches = yield* git(() => listBranches(repo)).pipe(Effect.orDie);127128 return branches.length === 1129 ? Option.some(`refs/heads/${branches[0]}`)130 : head;131 });132133// The copies write children before parents, so every object in a repo has134// everything it points to.135const copyBlob = (source: PushSource, into: GitDir, oid: string) =>136 Effect.gen(function* () {
301 unmodified lines
modified:packages/artifacts/src/repo-host/local.ts+11 added-3 removed
42 unmodified lines
43 RepoCreated,44 RepoName,45} from "../repo-host.ts";46import {47 defaultRefOf,48 initBare,49 mainRef,50 objectsAndRefs,51 seedRef,
251 unmodified lines
303 if (Option.isNone(head)) {304 return yield* noRepo;305 }306306 // A detached HEAD names no branch to take.307 const ref = branch === undefined ? head.value : `refs/heads/${branch}`;307 // Without a branch, what HEAD names, or the one branch when HEAD308 // names none it has (`main` on a repo whose only branch is309 // `master`). A detached HEAD with several branches names none.310 const named =311 branch === undefined312 ? yield* defaultRefOf({ fs, gitdir })313 : Option.some(`refs/heads/${branch}`);314309 if (ref === undefined) {315 if (Option.isNone(named)) {316 return yield* new ImportRefused({317 name,318 reason: `${url} has no default branch`,319 });320 }321322 const ref = named.value;323324 const tip = yield* tipOf({ fs, gitdir }, ref);325326 if (Option.isNone(tip)) {327 return yield* new ImportRefused({
220 unmodified lines
modified:packages/artifacts/src/repo-host/memory.ts+19 added-2 removed
7 unmodified lines
8 RepoNotFound,9} from "../repo-host.ts";10import type { RepoCreated, RepoName } from "../repo-host.ts";11import {12 defaultRefOf,13 initBare,14 mainRef,15 objectsAndRefs,16 seedRef,
3 unmodified lines
20import { memoryFs } from "./memory-fs.ts";2122const remoteOf = (name: RepoName) => `memory://${name}.git`;2324const branchOf = (ref: string) => ref.replace(/^refs\/heads\//u, "");2526const createdOf = (name: RepoName): RepoCreated => ({27 name,28 remote: remoteOf(name),29});
84 unmodified lines
114 reason: `no repo at ${source.url}`,115 });116 }117115 const ref = `refs/heads/${source.branch ?? "main"}`;118 // Without a branch, the remote's default: what its HEAD names, or119 // its one branch, as `master` is on a remote that has only that.120 const named =121 source.branch === undefined122 ? yield* defaultRefOf(from.dir)123 : Option.some(`refs/heads/${source.branch}`);124125 if (Option.isNone(named)) {126 return yield* new ImportRefused({127 name,128 reason: `${source.url} has no default branch`,129 });130 }131132 const ref = named.value;133 const tip = yield* tipOf(from.dir, ref);134135 if (Option.isNone(tip)) {136 return yield* new ImportRefused({137 name,121 reason: `${source.url} has no branch ${source.branch ?? "main"}`,138 reason: `${source.url} has no branch ${branchOf(ref)}`,139 });140 }141142 return yield* seed(from, name, ref, tip);
39 unmodified lines
modified:packages/artifacts/test/binding.test.ts+168 added
10 unmodified lines
11import {12 Duration,13 Effect,14 Exit,15 Fiber,16 FiberSet,17 FileSystem,18 Layer,19 Option,20 Redacted,21 Ref,22} from "effect";23import type { Scope } from "effect";24import type { ChildProcessSpawner } from "effect/process";25import { TestClock } from "effect/testing";26import { readCommit } from "isomorphic-git";2728import { Fetch, FetchFailed } from "../src/fetch.ts";29import {
179 unmodified lines
209 intercept,210 layer: RepoHostBinding.layer(binding).pipe(211 Layer.provide(Layer.succeed(Fetch, fetch))212 ),213 root,214 seen,215 store,216 tokens,217 };
617 unmodified lines
835 }).pipe(Effect.provideService(Fetch, fetch))836 )837 );838});839840/**841 * `effect` run to its end on the TestClock: the clock moves on by the842 * longest sleep the binding takes between asks while the effect runs, so843 * a wait of minutes passes at once, whatever real I/O it does between.844 */845const onTestClock = <A, E, R>(effect: Effect.Effect<A, E, R>) =>846 Effect.gen(function* () {847 const fiber = yield* Effect.forkChild(effect);848849 while (fiber.pollUnsafe() === undefined) {850 yield* TestClock.adjust(Duration.seconds(16));851 yield* Effect.yieldNow;852 }853854 return yield* Fiber.await(fiber);855 });856857/** How many tokens on `name` are still live, as the fake lists them. */858const liveTokens = (fake: Artifacts, name: RepoName) =>859 Effect.acquireUseRelease(860 Effect.promise(() => fake.get(name)),861 (repo) =>862 Effect.promise(() => repo.listTokens()).pipe(863 Effect.map(864 ({ tokens: listed }) =>865 listed.filter(({ state }) => state === "active").length866 )867 ),868 (repo) =>869 Effect.sync(() => {870 repo[Symbol.dispose]();871 })872 );873874describe("an import Artifacts is still copying", () => {875 const master = RefName.make("refs/heads/master");876877 // A remote whose default branch is `master`, as anyhow's is: its HEAD878 // names `master`, and the import takes that branch under its own name.879 it.live(880 "imports a remote whose default branch is master without being told",881 () =>882 within(883 ({ root }) =>884 Effect.gen(function* () {885 const repos = yield* RepoHost;886 const client = yield* gitClient(memoryFs());887 const first = yield* client.commit("first", [["a", "1"]]);888 const remote = RepoName.make("upstream-master");889 const name = RepoName.make("adopted-master");890891 yield* repos.create(remote).pipe(Effect.orDie);892 yield* repos893 .push(remote, client.source, [894 { from: Option.none(), ref: master, to: first },895 ])896 .pipe(Effect.orDie);897 yield* FileSystem.FileSystem.use((fs) =>898 fs.writeFileString(899 `${root}/${remote}.git/HEAD`,900 "ref: refs/heads/master\n"901 )902 ).pipe(Effect.provide(NodeServices.layer), Effect.orDie);903904 yield* repos905 .importFrom(name, {906 url: yield* repos.remote(remote).pipe(Effect.orDie),907 })908 .pipe(Effect.orDie);909910 expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(911 new Map([[master, first]])912 );913 }),914 { defaultBranch: "master" }915 )916 );917918 // Seven asks (about 32 s) were too few for a large import; the binding919 // now asks for about three minutes, so twelve busy answers pass.920 it.effect(921 "waits through twelve IMPORT_IN_PROGRESS answers, then revokes the import's token and reads it",922 () =>923 within(924 ({ fake }) =>925 Effect.gen(function* () {926 const repos = yield* RepoHost;927 const name = RepoName.make("slow-import");928 const { first } = yield* seeded(RepoName.make("slow-source"));929930 const imported = yield* onTestClock(931 repos.importFrom(name, {932 url: yield* repos933 .remote(RepoName.make("slow-source"))934 .pipe(Effect.orDie),935 })936 );937938 const read = yield* onTestClock(repos.refs(name));939940 expect(Exit.isSuccess(imported)).toBeTruthy();941 expect(read).toStrictEqual(Exit.succeed(new Map([[main, first]])));942 // Revoked by the import's own wait, which outlasted all twelve.943 expect(yield* liveTokens(fake, name)).toBe(0);944 }),945 { importing: 12 }946 )947 );948949 it.effect("still gives a repo being created seven asks, no more", () =>950 within(951 ({ fake }) =>952 Effect.gen(function* () {953 const repos = yield* RepoHost;954 const name = RepoName.make("slow-create");955956 // The create's own wait asks eight times and gives up, leaving957 // its write token live; the read after it waits out the ninth.958 const created = yield* onTestClock(repos.create(name));959 const read = yield* onTestClock(repos.refs(name));960961 expect(Exit.isSuccess(created)).toBeTruthy();962 expect(read).toStrictEqual(Exit.succeed(new Map()));963 expect(yield* liveTokens(fake, name)).toBe(1);964 }),965 { making: { code: "CREATE_IN_PROGRESS", gets: 9 } }966 )967 );968969 // Past the wait, the read dies with the repo made; the project's retry970 // meets `RepoExists`, and a read once the import is done finds it.971 it.effect(972 "dies past the wait, then answers RepoExists to the retry and reads the repo once it is copied",973 () =>974 within(975 ({ fake }) =>976 Effect.gen(function* () {977 const repos = yield* RepoHost;978 const name = RepoName.make("stuck-import");979 const source = RepoName.make("stuck-source");980 const { first } = yield* seeded(source);981 const url = yield* repos.remote(source).pipe(Effect.orDie);982983 const imported = yield* onTestClock(984 repos.importFrom(name, { url })985 );986987 const died = yield* onTestClock(repos.refs(name));988 const again = yield* onTestClock(repos.importFrom(name, { url }));989 const read = yield* onTestClock(repos.refs(name));990991 expect(Exit.isSuccess(imported)).toBeTruthy();992 expect(Exit.hasDies(died)).toBeTruthy();993 expect(again).toStrictEqual(Exit.fail(new RepoExists({ name })));994 expect(read).toStrictEqual(Exit.succeed(new Map([[main, first]])));995 // The import's day-long write token outlived the wait; nothing996 // was handed it, and it expires.997 expect(yield* liveTokens(fake, name)).toBe(1);998 }),999 { importing: 40 }1000 )1001 );1002});
modified:packages/artifacts/test/local.test.ts+1 added
70 unmodified lines
7172// Its test-only meaning of a public remote: another bare repo on disk, named73// by its `file://` URL.74describeRepoHost("local", freshStore, {75 danglingHead: true,76 importUrl: (name) =>77 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),78});79
213 unmodified lines
modified:packages/artifacts/test/memory.test.ts+1 added
14 unmodified lines
15import { describeRepoHost } from "./repo-host-contract.ts";1617// Its test-only meaning of a public remote: another repo in the same store.18describeRepoHost("memory", RepoHostMemory, {19 danglingHead: true,20 importUrl: (name) =>21 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),22});23
67 unmodified lines
modified:packages/artifacts/test/repo-host-contract.ts+36 added
113 unmodified lines
114 */115 readonly importUrl?: (116 name: RepoName117 ) => Effect.Effect<string, never, RepoHost>;118 /**119 * Whether an import reads a remote made here whose HEAD names a branch it120 * lacks. Over smart HTTP such a remote advertises no HEAD, which121 * isomorphic-git cannot fetch at all, while a real remote whose default122 * is `master` advertises HEAD → master: `binding.test.ts` imports one.123 */124 readonly danglingHead?: boolean;125}126127/**128 * What every RepoHost adapter must do, written against the port. `/memory`,
155 unmodified lines
284 ).toMatchObject([{ sha: second }, { sha: first }]);285 }).pipe(Effect.provide(host))286 );287288 if (suite.danglingHead === true) {289 // A remote whose default branch is `master`, as anyhow's and stb's are:290 // a store made here names `main` in its HEAD, so the import takes the291 // remote's one branch, and keeps its name, as Artifacts does.292 it.effect(293 "imports a remote whose only branch is master, under its own name",294 () =>295 Effect.gen(function* () {296 const repos = yield* RepoHost;297 const client = yield* gitClient(memoryFs());298 const first = yield* client.commit("first", [["a", "1"]]);299 const remote = RepoName.make("import-master");300 const name = RepoName.make("imported-master");301 const master = RefName.make("refs/heads/master");302303 yield* repos.create(remote);304 yield* repos.push(remote, client.source, [305 { from: Option.none(), ref: master, to: first },306 ]);307308 yield* repos.importFrom(name, { url: yield* importUrl(remote) });309310 expect(yield* repos.refs(name)).toStrictEqual(311 new Map([[master, first]])312 );313 }).pipe(Effect.provide(host))314 );315 }316317 it.effect("refuses to import over a repo that exists", () =>318 Effect.gen(function* () {319 const repos = yield* RepoHost;320 const remote = RepoName.make("import-remote");
391 unmodified lines
added:packages/config/test/import-examples.test.ts+409 added
1/**2 * `bun scripts/import-examples.ts`: the open-source repos the code browser3 * is previewed on, imported one at a time as the operator, skipped once a4 * platform lists them, recorded in the ledger as kept imports, never on5 * `demo`; and `--tags`' backfill, which pushes tags only and never shows6 * its token.7 */8import { NodeServices } from "@effect/platform-node";9import { describe, expect, it } from "@effect/vitest";10import {11 Console,12 Effect,13 FileSystem,14 Layer,15 Option,16 Path,17 Redacted,18 Ref,19 Result,20} from "effect";2122import { LedgerFile, readLedger } from "../../../infra/created.ts";23import {24 examples,25 planImports,26 shownCommand,27 tagBackfillCommands,28} from "../../../scripts/lib/import/plan.ts";29import type { ImportExample } from "../../../scripts/lib/import/plan.ts";30import {31 ImportExamplesFailed,32 importExamples,33 ImportTarget,34 TagBackfill,35} from "../../../scripts/lib/import/run.ts";36import { ProjectName } from "../../protocol/src/ids.ts";3738const project = (name: string) => ProjectName.make(name);3940const names = (planned: readonly ImportExample[]) =>41 planned.map(({ project: name }) => name);4243describe("the import plan", () => {44 it("holds the eight repos of the preview, anyhow first, each master repo on its branch", () => {45 expect(46 examples.map(({ branch, project: name, url }) => [name, branch, url])47 ).toStrictEqual([48 ["anyhow", "master", "https://github.com/dtolnay/anyhow"],49 ["ky", "main", "https://github.com/sindresorhus/ky"],50 ["gum", "main", "https://github.com/charmbracelet/gum"],51 ["click", "main", "https://github.com/pallets/click"],52 ["awesome", "main", "https://github.com/sindresorhus/awesome"],53 ["changesets", "main", "https://github.com/changesets/changesets"],54 ["stb", "master", "https://github.com/nothings/stb"],55 ["fuzzel", "master", "https://codeberg.org/dnkl/fuzzel"],56 ]);57 });5859 it("skips a project the platform lists already, and keeps only the one --only names", () => {60 expect({61 all: names(62 planImports(63 examples,64 new Set([project("ky"), project("stb")]),65 Option.none()66 )67 ),68 listed: names(69 planImports(70 examples,71 new Set([project("anyhow")]),72 Option.some(project("anyhow"))73 )74 ),75 only: names(76 planImports(examples, new Set(), Option.some(project("gum")))77 ),78 }).toStrictEqual({79 all: ["anyhow", "gum", "click", "awesome", "changesets", "fuzzel"],80 listed: [],81 only: ["gum"],82 });83 });84});8586describe("the tag backfill's commands", () => {87 const token = Redacted.make("artifacts-write-token-0123456789abcdef");8889 const commands = tagBackfillCommands({90 mirror: "/tmp/import-tags/anyhow.git",91 remote: {92 token,93 url: "https://acct.artifacts.cloudflare.net/git/projects-dev-oscabriel/anyhow.git",94 },95 source: "https://github.com/dtolnay/anyhow",96 });9798 it("fetches the source's tags into a local bare repo, then pushes refs/tags/* and nothing else", () => {99 expect(commands.map(shownCommand)).toStrictEqual([100 "git init --bare --quiet /tmp/import-tags/anyhow.git",101 "git --git-dir /tmp/import-tags/anyhow.git fetch --quiet --no-tags https://github.com/dtolnay/anyhow refs/tags/*:refs/tags/*",102 "git --git-dir /tmp/import-tags/anyhow.git push --quiet https://acct.artifacts.cloudflare.net/git/projects-dev-oscabriel/anyhow.git refs/tags/*:refs/tags/*",103 ]);104105 const pushes = commands.filter(({ argv }) => argv.includes("push"));106107 expect(108 pushes.map(({ argv }) => argv.filter((arg) => arg.includes(":")))109 ).toStrictEqual([110 [111 "https://acct.artifacts.cloudflare.net/git/projects-dev-oscabriel/anyhow.git",112 "refs/tags/*:refs/tags/*",113 ],114 ]);115 expect(116 pushes.flatMap(({ argv }) =>117 argv.filter((arg) => /--force|--all|--mirror|main|heads/u.test(arg))118 )119 ).toStrictEqual([]);120 });121122 it("never prints the token: it rides in git's env as a header, redacted, not in an argument or a URL", () => {123 const printed = [124 ...commands.map(shownCommand),125 JSON.stringify(commands),126 JSON.stringify(commands.map(({ env }) => env)),127 ].join("\n");128129 expect(printed.includes(Redacted.value(token))).toBeFalsy();130 expect(131 commands.map(({ env = {} }) =>132 Object.entries(env).map(([name, value]) => [133 name,134 Redacted.value(value),135 ])136 )137 ).toStrictEqual([138 [],139 [],140 [141 ["GIT_CONFIG_COUNT", "1"],142 ["GIT_CONFIG_KEY_0", "http.extraHeader"],143 [144 "GIT_CONFIG_VALUE_0",145 "Authorization: Bearer artifacts-write-token-0123456789abcdef",146 ],147 ],148 ]);149 });150});151152/** A platform in memory: the projects it lists, and every call made to it. */153const fakePlatform = (listed: readonly string[]) =>154 Effect.gen(function* () {155 const calls = yield* Ref.make<readonly string[]>([]);156 const have = new Set(listed.map(project));157 const note = (call: string) => Ref.update(calls, (all) => [...all, call]);158159 const target = ImportTarget.of({160 counts: (name) =>161 note(`ls-remote ${name}`).pipe(Effect.as({ heads: 2, tags: 0 })),162 initProject: (example) =>163 note(`init ${example.project} ${example.branch}`).pipe(164 Effect.tap(() => Effect.sync(() => have.add(example.project))),165 Effect.as({ landed: "a".repeat(40) })166 ),167 label: "dev-oscabriel (https://platform.test)",168 listProjects: note("listProjects").pipe(169 Effect.andThen(Effect.sync(() => new Set(have)))170 ),171 });172173 const backfill = TagBackfill.of({174 backfill: (example) =>175 note(`tags ${example.project}`).pipe(Effect.as(105)),176 });177178 return {179 calls: Ref.get(calls),180 layer: Layer.mergeAll(181 Layer.succeed(ImportTarget, target),182 Layer.succeed(TagBackfill, backfill)183 ),184 };185 });186187/** `importExamples(argv)` over `layer`, with the ledger in a temp folder: how it ended, and what it printed. */188const ran = (189 argv: readonly string[],190 layer: Layer.Layer<ImportTarget | TagBackfill>191) =>192 Effect.gen(function* () {193 const fs = yield* FileSystem.FileSystem;194 const path = yield* Path.Path;195 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "import-913-" });196 const ledgerFile = path.join(dir, "created.jsonl");197 const printed: string[] = [];198199 const captured: Console.Console = {200 ...console,201 log: (...args: readonly unknown[]) => {202 printed.push(args.map(String).join(" "));203 },204 };205206 const result = yield* importExamples(argv, () => layer).pipe(207 Effect.provideService(LedgerFile, ledgerFile),208 Effect.provideService(Console.Console, captured),209 Effect.result210 );211212 const ledger = yield* readLedger.pipe(213 Effect.provideService(LedgerFile, ledgerFile)214 );215216 return { ledger, printed, result };217 });218219const onDev = (...flags: readonly string[]) => [220 "--stage",221 "dev-oscabriel",222 "--url",223 "https://platform.test",224 ...flags,225];226227describe("bun scripts/import-examples.ts", () => {228 it.live(229 "refuses --stage demo before it builds a target or calls anything",230 () =>231 Effect.gen(function* () {232 let built = 0;233234 const result = yield* importExamples(["--stage", "demo"], () => {235 built += 1;236237 return Layer.mergeAll(238 Layer.effect(ImportTarget, Effect.die("a target was built")),239 Layer.effect(TagBackfill, Effect.die("a backfill was built"))240 );241 }).pipe(Effect.result);242243 expect({ built, result }).toStrictEqual({244 built: 0,245 result: Result.fail(246 new ImportExamplesFailed({247 reason:248 "--stage demo is the recording stage: the imports go on a dev stage only",249 })250 ),251 });252 }).pipe(Effect.provide(NodeServices.layer))253 );254255 it.live(256 "imports each project the platform doesn't list, one at a time, with its counts, and records each in the ledger as a kept import",257 () =>258 Effect.gen(function* () {259 const platform = yield* fakePlatform(["ky", "stb", "click", "gum"]);260 const { ledger, printed, result } = yield* ran(onDev(), platform.layer);261262 expect({263 calls: yield* platform.calls,264 ledger: ledger.map(({ by, kind, name, namespace, stage }) => ({265 by,266 kind,267 name,268 namespace,269 stage,270 })),271 printed,272 result: Result.isSuccess(result),273 }).toStrictEqual({274 calls: [275 "listProjects",276 "init anyhow master",277 "ls-remote anyhow",278 "init awesome main",279 "ls-remote awesome",280 "init changesets main",281 "ls-remote changesets",282 "init fuzzel master",283 "ls-remote fuzzel",284 ],285 ledger: ["anyhow", "awesome", "changesets", "fuzzel"].flatMap(286 (name) => [287 {288 by: "import",289 kind: "project",290 name,291 namespace: undefined,292 stage: "dev-oscabriel",293 },294 {295 by: "import",296 kind: "repo",297 name,298 namespace: "projects-dev-oscabriel",299 stage: "dev-oscabriel",300 },301 ]302 ),303 printed: [304 "import-examples on dev-oscabriel (https://platform.test): 4 to import, 4 listed already",305 " skip ky: listed already",306 " skip gum: listed already",307 " skip click: listed already",308 " skip stb: listed already",309 "imported anyhow (Rust crate, master): main at aaaaaaaaaaaa, 2 heads, 0 tags",310 "imported awesome (Markdown list, main): main at aaaaaaaaaaaa, 2 heads, 0 tags",311 "imported changesets (TypeScript monorepo, main): main at aaaaaaaaaaaa, 2 heads, 0 tags",312 "imported fuzzel (C on Codeberg, master): main at aaaaaaaaaaaa, 2 heads, 0 tags",313 "imported 4 of 4, each recorded in infra/created.jsonl as a kept import",314 ],315 result: true,316 });317 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))318 );319320 it.live("--dry-run prints the plan and imports and records nothing", () =>321 Effect.gen(function* () {322 const platform = yield* fakePlatform(["ky"]);323324 const { ledger, printed } = yield* ran(325 onDev("--dry-run", "--only", "anyhow"),326 platform.layer327 );328329 expect({ calls: yield* platform.calls, ledger, printed }).toStrictEqual({330 calls: ["listProjects"],331 ledger: [],332 printed: [333 "import-examples on dev-oscabriel (https://platform.test): 1 to import, 0 listed already",334 " would import anyhow from https://github.com/dtolnay/anyhow (master)",335 "dry run: nothing imported, nothing recorded",336 ],337 });338 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))339 );340341 it.live(342 "--tags backfills an import that came with no tags, and the ledger says so",343 () =>344 Effect.gen(function* () {345 const platform = yield* fakePlatform([]);346347 const { ledger, printed } = yield* ran(348 onDev("--only", "anyhow", "--tags"),349 platform.layer350 );351352 expect({353 calls: yield* platform.calls,354 ledger: ledger.map(({ kind, name, note }) => [kind, name, note]),355 printed: printed.filter((line) => line.includes("tags")),356 }).toStrictEqual({357 calls: [358 "listProjects",359 "init anyhow master",360 "ls-remote anyhow",361 "tags anyhow",362 ],363 ledger: [364 ["project", "anyhow", undefined],365 ["repo", "anyhow", undefined],366 ["repo", "anyhow", "tags backfilled"],367 ],368 printed: [369 "imported anyhow (Rust crate, master): main at aaaaaaaaaaaa, 2 heads, 0 tags",370 " anyhow: 105 tags backfilled from https://github.com/dtolnay/anyhow",371 ],372 });373 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))374 );375376 it.live(377 "--tags backfills an earlier import the ledger records, and never a listed project it doesn't",378 () =>379 Effect.gen(function* () {380 const fs = yield* FileSystem.FileSystem;381 const path = yield* Path.Path;382383 const dir = yield* fs.makeTempDirectoryScoped({384 prefix: "import-913-",385 });386387 const ledgerFile = path.join(dir, "created.jsonl");388 const platform = yield* fakePlatform(["anyhow", "ky"]);389390 // An earlier run imported anyhow; ky is someone else's project.391 yield* fs.writeFileString(392 ledgerFile,393 `${JSON.stringify({ at: "2026-10-08T20:00:00.000Z", by: "import", kind: "project", name: "anyhow", stage: "dev-oscabriel" })}\n`394 );395396 yield* importExamples(onDev("--tags"), () => platform.layer).pipe(397 Effect.provideService(LedgerFile, ledgerFile),398 Effect.provideService(Console.Console, {399 ...console,400 log: () => {},401 })402 );403404 expect(405 (yield* platform.calls).filter((call) => /ky|anyhow/u.test(call))406 ).toStrictEqual(["ls-remote anyhow", "tags anyhow"]);407 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))408 );409});
modified:packages/config/test/teardown.test.ts+63 added
105 unmodified lines
106 namespace("layers-demo"),107 namespace("witness"),108];109110/** Two imports of the preview repos, kept: each one's project and repo line. */111const imports: readonly Created[] = [112 made("import", "project", "anyhow"),113 made("import", "repo", "anyhow", projects),114 made("import", "project", "ky"),115 made("import", "repo", "ky", projects),116];117118describe("the teardown plan", () => {119 it("never selects an import, nor a fork of one, even with every line in the ledger and the listing", () => {120 expect(121 teardownPlan({122 ledger: [123 ...imports,124 made("smoke", "repo", "anyhow--fix-backtrace--bram", projects),125 ...ledger,126 ],127 listed: [128 ...listed,129 repo("anyhow"),130 repo("ky"),131 repo("anyhow--fix-backtrace--bram"),132 ],133 stages: [dev],134 })135 ).toStrictEqual([136 repo("datekit-805--maintainers", layers),137 repo("burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol"),138 repo("burrow-swarm-1"),139 repo("smoke-r1--parse-year--bram"),140 repo("smoke-r1"),141 ]);142 });143144 it("selects a smoke run's repos and a swarm copy's repos that are in both the ledger and the listing, forks before what they fork", () => {145 expect(teardownPlan({ ledger, listed, stages: [dev] })).toStrictEqual([146 repo("datekit-805--maintainers", layers),147 repo("burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol"),
499 unmodified lines
647 });648 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))649 );650651 it.live(652 "lists the kept imports apart, never in the plan, and deletes none of them with --apply",653 () =>654 Effect.gen(function* () {655 const files = yield* tempRoot([...devLedger, ...imports]);656657 const fake = yield* memoryAccount({658 ...devRepos,659 [projects]: [...devRepos[projects], "anyhow", "ky"],660 });661662 const { printed } = yield* tornDown(["--apply"], fake.account, files);663664 expect({665 kept: printed.filter((line) => /anyhow|\bky\b/u.test(line)),666 standing: yield* fake.standing(projects, ["anyhow", "ky"]),667 total: printed[0],668 }).toStrictEqual({669 kept: [670 " kept import: project anyhow",671 " kept import: repo projects-dev-oscabriel/anyhow",672 " kept import: project ky",673 " kept import: repo projects-dev-oscabriel/ky",674 ],675 standing: ["anyhow", "ky"],676 total: "teardown on dev-oscabriel: 13 ledger entries, 5 to delete",677 });678 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))679 );680681 it.live("--keep leaves a copy's repos and forks out of the plan", () =>682 Effect.gen(function* () {683 const files = yield* tempRoot(devLedger);684 const fake = yield* memoryAccount(devRepos);
35 unmodified lines
modified:packages/project/src/project.ts+22 added-8 removed
2785 unmodified lines
2786 });27872788 /**2789 * An imported repo adopted: its tip becomes the first landed SHA, on a2790 * `main` of its own when the imported branch had another name.2790 * `main` of its own when the imported branch had another name. The tip2791 * is `main`'s, else the named branch's, else the one branch the import2792 * made (the remote's default, `master` or any other).2793 *2794 * `adopt` runs only while the project has no row, so a repo that exists2795 * is this project's earlier import, which died after Artifacts made the2796 * repo (a slow import outlasting the binding's wait): it is waited for2797 * and adopted, as `initBody` keeps an empty repo a failed `create` left.2798 * ASSUMPTION: the retry names the same remote; the repo holds what the2799 * first import copied.2800 */2801 const adopt = (from: { readonly branch?: string; readonly url: string }) =>2802 Effect.gen(function* () {2803 const branch = Option.map(
18 unmodified lines
2822 new ImportFailed({2823 reason: reason === "" ? "the import was refused" : reason,2824 })2825 ),2817 RepoExists: () =>2818 Effect.fail(new ProjectExists({ project: name })),2826 RepoExists: () => Effect.void,2827 })2828 );28292830 const refs = yield* host.refs(repo).pipe(Effect.orDie);28312824 const imported = RefName.make(2825 `refs/heads/${Option.getOrElse(named, () => "main")}`2832 const branches = [...refs].filter(([ref]) =>2833 ref.startsWith("refs/heads/")2834 );28352828 const tip = Option.fromNullishOr(2829 refs.get(mainRef) ?? refs.get(imported)2830 );2836 const tip = Option.firstSomeOf([2837 Option.fromNullishOr(refs.get(mainRef)),2838 Option.flatMap(named, (given) =>2839 Option.fromNullishOr(refs.get(RefName.make(`refs/heads/${given}`)))2840 ),2841 Option.isNone(named) && branches.length === 12842 ? Option.fromNullishOr(branches[0]?.[1])2843 : Option.none(),2844 ]);28452846 if (Option.isNone(tip)) {2847 return yield* new ImportFailed({2848 reason: `${from.url} has no commits`,
2857 unmodified lines
added:packages/project/test/import.test.ts+163 added
1/**2 * A project adopted from a public repo, whatever its default branch, and3 * adopted again by a retry when the first import died after Artifacts made4 * the repo.5 */6import { describe, expect, it } from "@effect/vitest";7import { RefName, RepoHost } from "@repo/artifacts/repo-host";8import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";9import { LandedSha, RepoName } from "@repo/protocol/ids";10import { Person } from "@repo/protocol/principal";11import { ProjectExists } from "@repo/protocol/refusal";12import { advanceTo } from "@repo/testkit/clock";13import { gitClient } from "@repo/testkit/git-client";14import { aProject } from "@repo/testkit/scenarios";15import { Effect, Exit, Option, Ref } from "effect";1617import { ProjectStore } from "../src/project-store.ts";18import { projectService } from "../src/project.ts";19import { worldOf } from "./world.ts";2021const scenario = aProject({ people: ["bob"] });2223const { project } = scenario;2425const repo = RepoName.make(project);2627const alice = Person.make({ handle: scenario.initializer });2829const mainRef = RefName.make("refs/heads/main");3031const masterRef = RefName.make("refs/heads/master");3233/**34 * A public remote `upstream` whose only branch is `master`, as anyhow's35 * and stb's are; the world reads `https://example.com/upstream.git` as it.36 */37const upstreamOnMaster = Effect.gen(function* () {38 const host = yield* RepoHost;39 const upstream = RepoName.make("upstream");40 const client = yield* gitClient(memoryFs());4142 const tip = yield* client.commit("Start", [43 ["Cargo.toml", '[package]\nname = "upstream"\n'],44 ["src/lib.rs", "pub fn parse() {}\n"],45 ]);4647 yield* host.create(upstream).pipe(Effect.orDie);48 yield* host49 .push(upstream, client.source, [50 { from: Option.none(), ref: masterRef, to: tip },51 ])52 .pipe(Effect.orDie);5354 return { tip, url: "https://example.com/upstream.git" };55});5657/** What the project holds after its imports: its head, its row, and its repo's refs. */58const settled = Effect.gen(function* () {59 const api = yield* projectService(project);60 const snapshot = yield* ProjectStore.use((store) => store.load());61 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);6263 return {64 head: (yield* api.head()).landed,65 main: refs.get(mainRef),66 state: Option.map(snapshot.project, (row) => row.state),67 };68});6970/**71 * The world's `RepoHost`, standing in for the binding past its wait: until72 * the import is copied, a read of the imported repo dies as the binding's73 * does when Artifacts still answers `IMPORT_IN_PROGRESS` (the binding's74 * own half is `packages/artifacts/test/binding.test.ts`). The first read75 * after an import dies; every later one works.76 */77const stillCopying = Effect.gen(function* () {78 const host = yield* RepoHost;79 const copying = yield* Ref.make(false);8081 return RepoHost.of({82 ...host,83 importFrom: (name, source) =>84 host85 .importFrom(name, source)86 .pipe(Effect.tap(() => Ref.set(copying, true))),87 refs: (name) =>88 Effect.flatMap(Ref.getAndSet(copying, false), (busy) =>89 busy90 ? Effect.die(new Error(`Import in progress: ${name}`))91 : host.refs(name)92 ),93 });94});9596describe("importing a public repo", () => {97 it.effect(98 "adopts a remote whose only branch is master, with no branch given, on a main at its tip",99 () =>100 Effect.gen(function* () {101 yield* advanceTo("2026-10-08T12:00:00Z");102103 const { tip, url } = yield* upstreamOnMaster;104 const api = yield* projectService(project);105 const made = yield* api.initProject(alice, { import: { url } });106107 expect(made.landed).toStrictEqual(LandedSha.make(tip));108 expect(yield* settled).toStrictEqual({109 head: LandedSha.make(tip),110 main: tip,111 state: Option.some("live"),112 });113 }).pipe(Effect.provide(worldOf(scenario, "memory")))114 );115116 it.effect(117 "adopts on a retry the repo a first import left when it died, not ProjectExists",118 () =>119 Effect.gen(function* () {120 yield* advanceTo("2026-10-08T12:00:00Z");121122 const { tip, url } = yield* upstreamOnMaster;123 const host = yield* stillCopying;124125 const api = yield* projectService(project).pipe(126 Effect.provideService(RepoHost, host)127 );128129 const first = yield* Effect.exit(130 api.initProject(alice, { import: { url } })131 );132133 const retried = yield* Effect.exit(134 api.initProject(alice, { import: { url } })135 );136137 expect(Exit.hasDies(first)).toBeTruthy();138 expect(Exit.map(retried, ({ landed }) => landed)).toStrictEqual(139 Exit.succeed(LandedSha.make(tip))140 );141 expect(yield* settled).toStrictEqual({142 head: LandedSha.make(tip),143 main: tip,144 state: Option.some("live"),145 });146 }).pipe(Effect.provide(worldOf(scenario, "memory")))147 );148149 it.effect("still answers ProjectExists for a project that exists", () =>150 Effect.gen(function* () {151 yield* advanceTo("2026-10-08T12:00:00Z");152153 const { url } = yield* upstreamOnMaster;154 const api = yield* projectService(project);155156 yield* api.initProject(alice, { import: { url } });157158 expect(159 yield* Effect.flip(api.initProject(alice, { import: { url } }))160 ).toStrictEqual(new ProjectExists({ project }));161 }).pipe(Effect.provide(worldOf(scenario, "memory")))162 );163});
modified:packages/testkit/src/fake-artifacts-binding.ts+30 added
165 unmodified lines
166 /** How many forks fail with a 500 after making the repo, as under load. */167 readonly forkFailures?: number;168 /** Remotes are `<remoteBase>/<name>.git`, for a git server the test runs; else the host's. */169 readonly remoteBase?: string;170 /**171 * The default branch an import that names none reports, as the remote's172 * own: `master` for a remote like anyhow's. `main` when not given.173 */174 readonly defaultBranch?: string;175 /**176 * How many of a just-imported repo's first `get`s answer177 * `IMPORT_IN_PROGRESS`: an import Artifacts is still copying after178 * `import()` returned, as a large one is.179 */180 readonly importing?: number;181}182183/** A refusal the binding throws, before it becomes the thrown error. */184class Refused extends Data.TaggedError("Refused")<{
133 unmodified lines
318): Artifacts => {319 const kept = new Map<RepoName, Kept>();320 let forkFailures = options.forkFailures ?? 0;321 let made = 0;322 // Each imported repo's `get`s still to answer that the import runs on.323 const importing = new Map<RepoName, number>();324325 /** The thrown error: an `ArtifactsError`, or a plain one when codeless. */326 const thrown = ({ code, reason }: Refused) =>327 options.codeless === true
295 unmodified lines
623 const repoName = yield* named(name, "NOT_FOUND");624625 yield* host.remote(repoName);626627 const left = importing.get(repoName) ?? 0;628629 if (left > 0) {630 importing.set(repoName, left - 1);631632 return yield* refuse(633 "IMPORT_IN_PROGRESS",634 `Import in progress: ${repoName}`635 );636 }637638 return handle(repoName);639 })640 ),641 import: ({ source, target }) =>
12 unmodified lines
654 onSome: (name) => ({ branch: name, url: source.url }),655 })656 );657658 importing.set(repoName, options.importing ?? 0);659660 return yield* createdOf(661 keep(repoName, {662 defaultBranch: Option.getOrElse(663 branch,664 () => options.defaultBranch ?? "main"665 ),666 description: target.opts?.description ?? null,667 readOnly: target.opts?.readOnly ?? false,668 source: source.url,669 })
20 unmodified lines
added:scripts/lib/import/live.ts+414 added
1/**2 * The import run's real target and backfill: a platform over `/rpc` as the3 * operator, git's `ls-remote` anonymously through the gateway, and the tag4 * backfill through `@repo/artifacts`' REST adapter with the ops5 * credentials, as `infra/teardown.ts` reaches Artifacts. No token is ever6 * printed: the operator's goes only into the `Authorization` header of7 * `/rpc` calls, and the backfill's write token only into git's env.8 */9import { Fetch, FetchFailed } from "@repo/artifacts/fetch";10import { RepoHost, RepoName } from "@repo/artifacts/repo-host";11import { RepoHostRest } from "@repo/artifacts/repo-host/rest";12import { Client, Contracts } from "@repo/protocol/contracts";13import type { ProjectName } from "@repo/protocol/ids";14import { Refusal } from "@repo/protocol/refusal";15import { explain } from "@repo/protocol/render";16import {17 Config,18 Context,19 Duration,20 Effect,21 FileSystem,22 Layer,23 Redacted,24 Schedule,25 Schema,26 Stream,27} from "effect";28import type { Path } from "effect";29import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";30import { ChildProcess, ChildProcessSpawner } from "effect/process";31import { RpcClient, RpcSerialization } from "effect/rpc";3233import {34 platformOrigin,35 recordedSubdomain,36 resources,37 subdomainFile,38} from "../../../infra/stages.ts";39import type { Stage } from "../../../infra/stages.ts";40import { servedWorld, worldOperator } from "../seed.ts";41import { shownCommand, tagBackfillCommands } from "./plan.ts";42import type { Command } from "./plan.ts";43import { ImportExamplesFailed, ImportTarget, TagBackfill } from "./run.ts";4445const failed = (reason: string) => new ImportExamplesFailed({ reason });4647const isRefusal = Schema.is(Refusal);4849/** A call the platform refused, said as `explain` says it; or one it never answered. */50const failedCall =51 (call: string) =>52 (error: { readonly _tag: string; readonly message: string }) =>53 isRefusal(error)54 ? failed(55 `${call} was refused: ${explain([error])56 .map((line) => line.trim())57 .join("; ")}`58 )59 : failed(`${call} got no answer from the platform: ${error.message}`);6061/** git's env for a run of its own: no machine config, no prompt. */62const GIT_ENV = {63 GIT_CONFIG_GLOBAL: "/dev/null",64 GIT_CONFIG_NOSYSTEM: "1",65 GIT_TERMINAL_PROMPT: "0",66 LC_ALL: "C",67};6869const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>70 bytes.pipe(Stream.decodeText(), Stream.mkString);7172/**73 * `command` run to its end; what it printed when it ended well. A failure74 * says what git said, with every secret of the command's env cut out.75 */76const runCommand = (77 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],78 command: Command79) =>80 Effect.scoped(81 Effect.gen(function* () {82 const [file = "git", ...args] = command.argv;83 const secrets = Object.values(command.env ?? {}).map(Redacted.value);8485 const scrub = (text: string) => {86 let said = text;8788 for (const secret of secrets) {89 said = said.replaceAll(secret, "<token>");90 }9192 return said;93 };9495 const child = yield* spawner96 .spawn(97 ChildProcess.make(file, args, {98 env: {99 ...GIT_ENV,100 ...Object.fromEntries(101 Object.entries(command.env ?? {}).map(([name, value]) => [102 name,103 Redacted.value(value),104 ])105 ),106 },107 extendEnv: true,108 })109 )110 .pipe(111 Effect.mapError(({ message }) =>112 failed(`${shownCommand(command)} didn't run: ${scrub(message)}`)113 )114 );115116 const [stdout, stderr, code] = yield* Effect.all(117 [streamText(child.stdout), streamText(child.stderr), child.exitCode],118 { concurrency: "unbounded" }119 ).pipe(120 Effect.mapError(({ message }) =>121 failed(`${shownCommand(command)} failed: ${scrub(message)}`)122 )123 );124125 return Number(code) === 0126 ? stdout127 : yield* failed(128 `${shownCommand(command)} exited ${Number(code)}: ${scrub(stderr.trim())}`129 );130 })131 );132133/** The refs `git ls-remote` lists, counted: branches, and tags without their peeled lines. */134const countsOf = (listed: string) => {135 const refs = listed136 .split("\n")137 .map((line) => line.split("\t")[1] ?? "")138 .filter((ref) => ref.length > 0);139140 return {141 heads: refs.filter((ref) => ref.startsWith("refs/heads/")).length,142 tags: refs.filter(143 (ref) => ref.startsWith("refs/tags/") && !ref.endsWith("^{}")144 ).length,145 };146};147148/** The contracts over HTTP at `origin`'s `/rpc`, with `token` as the bearer. */149const clientAt = (150 origin: string,151 token: Redacted.Redacted152): Layer.Layer<Client> =>153 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(154 Layer.provide(155 RpcClient.layerProtocolHttp({156 transformClient: HttpClient.mapRequest(157 HttpClientRequest.bearerToken(token)158 ),159 url: `${origin}/rpc`,160 })161 ),162 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])163 );164165/**166 * An import that got no answer is asked again, a little later: a large167 * one can outlast the edge's request timeout, and the platform adopts the168 * repo the first call left. A refusal is never asked again.169 */170const AGAIN = Schedule.spaced(Duration.seconds(30));171172/** The platform at `origin`, reached as the operator with `token`. */173export const platformTarget = (input: {174 readonly origin: string;175 readonly token: Redacted.Redacted;176 readonly label: string;177}): Layer.Layer<ImportTarget, never, ChildProcessSpawner.ChildProcessSpawner> =>178 Layer.effect(179 ImportTarget,180 Effect.gen(function* () {181 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;182 const client = yield* Client;183184 return ImportTarget.of({185 counts: (project) =>186 runCommand(spawner, {187 argv: ["git", "ls-remote", `${input.origin}/${project}.git`],188 }).pipe(Effect.map(countsOf)),189 initProject: ({ branch, project, url }) =>190 client.initProject({ import: { branch, url }, project }).pipe(191 Effect.retry({192 schedule: AGAIN,193 times: 3,194 while: (error) => !isRefusal(error),195 }),196 Effect.mapError(failedCall(`initProject ${project}`))197 ),198 label: input.label,199 listProjects: client.listProjects({}).pipe(200 Effect.map(201 ({ projects }): ReadonlySet<ProjectName> =>202 new Set(projects.map(({ project }) => project))203 ),204 Effect.mapError(failedCall("listProjects"))205 ),206 });207 })208 ).pipe(Layer.provide(clientAt(input.origin, input.token)));209210/**211 * A deployed dev stage at `url`, or at the workers.dev origin bootstrap212 * recorded, as the operator: `OPERATOR_TOKEN` from the env213 * (`bunx varlock run --path apps/platform/ -- …`), never printed.214 */215export const stageTarget = (216 stage: Stage,217 url: string | undefined218): Layer.Layer<219 ImportTarget,220 ImportExamplesFailed,221 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path222> =>223 Layer.unwrap(224 Effect.gen(function* () {225 const token = yield* Config.Redacted("OPERATOR_TOKEN").pipe(226 Effect.mapError(() =>227 failed(228 "no OPERATOR_TOKEN in the environment: run under `bunx varlock run --path apps/platform/ --`"229 )230 )231 );232233 const origin =234 url ??235 platformOrigin(236 stage,237 yield* recordedSubdomain.pipe(238 Effect.flatMap(Effect.fromOption),239 Effect.mapError(() =>240 failed(241 `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain`242 )243 )244 )245 );246247 return platformTarget({ label: `${stage} (${origin})`, origin, token });248 })249 );250251/** The operator's token in the Node world: no secret, never leaves this machine. */252const worldToken = Redacted.make(253 "operator-import-world-token-0123456789abcdef"254);255256/** The Node world, served for as long as the layer lasts, with the operator's session. */257export const worldTarget: Layer.Layer<258 ImportTarget,259 ImportExamplesFailed,260 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path261> = Layer.unwrap(262 servedWorld(new Map([[worldOperator, worldToken]])).pipe(263 Effect.mapError(({ reason }) => failed(reason)),264 Effect.map((origin) =>265 platformTarget({266 label: `the Node world (${origin})`,267 origin,268 token: worldToken,269 })270 )271 )272);273274/** The `Fetch` port over the runtime's own fetch, as effect/http finds it. */275const RuntimeFetch = Layer.effect(276 Fetch,277 Effect.gen(function* () {278 const send = yield* FetchHttpClient.Fetch;279280 return Fetch.of({281 fetch: (request) =>282 Effect.tryPromise({283 catch: () =>284 new FetchFailed({285 reason: "the request got no response",286 url: new URL(request.url).origin,287 }),288 try: () => send(request),289 }),290 });291 })292);293294/** How long the backfill's write token lives: one backfill, at most. */295const TOKEN_TTL = Duration.minutes(10);296297/**298 * The backfill on `stage`: its public namespace's repos through299 * `RepoHostRest`, with the ops credentials (`CLOUDFLARE_ACCOUNT_ID`,300 * `CLOUDFLARE_API_TOKEN`, from `bunx varlock run --path infra/ -- …`).301 * Each backfill mints a write token on the canonical repo for at most ten302 * minutes, fetches the source's tags into a temporary bare repo, pushes303 * `refs/tags/*` only, and revokes the token, whatever came of the push.304 */305export const restBackfill = (306 stage: Stage307): Layer.Layer<308 TagBackfill,309 ImportExamplesFailed,310 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem311> =>312 Layer.effect(313 TagBackfill,314 Effect.gen(function* () {315 const { accountId, token } = yield* Config.all({316 accountId: Config.String("CLOUDFLARE_ACCOUNT_ID"),317 token: Config.Redacted("CLOUDFLARE_API_TOKEN"),318 }).pipe(319 Effect.mapError(() =>320 failed(321 "--tags needs the ops credentials: run under `bunx varlock run --path infra/ --`"322 )323 )324 );325326 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;327 const fs = yield* FileSystem.FileSystem;328329 const host = Context.get(330 yield* Layer.build(331 RepoHostRest.layer({332 accountId,333 namespace: resources(stage).projects,334 token,335 }).pipe(336 Layer.provide(RuntimeFetch),337 Layer.provide(FetchHttpClient.layer)338 )339 ),340 RepoHost341 );342343 return TagBackfill.of({344 backfill: ({ project, url }) =>345 Effect.scoped(346 Effect.gen(function* () {347 const name = RepoName.make(project);348349 const notFound = () =>350 failed(351 `${project} has no repo in ${resources(stage).projects}`352 );353354 const dir = yield* fs355 .makeTempDirectoryScoped({ prefix: "import-tags-" })356 .pipe(357 Effect.mapError(() => failed("can't make a temporary folder"))358 );359360 const mirror = `${dir}/${project}.git`;361362 const remote = yield* host363 .remote(name)364 .pipe(Effect.mapError(notFound));365366 const minted = yield* host367 .mintToken(name, "write", TOKEN_TTL)368 .pipe(Effect.mapError(notFound));369370 const pushed = Effect.gen(function* () {371 yield* Effect.forEach(372 tagBackfillCommands({373 mirror,374 remote: { token: minted.secret, url: remote },375 source: url,376 }),377 (command) => runCommand(spawner, command),378 { discard: true }379 );380381 return countsOf(382 (yield* runCommand(spawner, {383 argv: [384 "git",385 "--git-dir",386 mirror,387 "for-each-ref",388 "--format=%(objectname)\t%(refname)",389 "refs/tags",390 ],391 })).trim()392 ).tags;393 });394395 // Revoked whatever came of the push; a revoke that fails is396 // said, and the token still expires within ten minutes.397 return yield* pushed.pipe(398 Effect.ensuring(399 host400 .revokeToken(name, minted.id)401 .pipe(402 Effect.catch(() =>403 Effect.logWarning(404 `the backfill's write token on ${project} was not revoked; it expires in ten minutes`405 )406 )407 )408 )409 );410 })411 ),412 });413 })414 );
added:scripts/lib/import/plan.ts+165 added
1/**2 * What `scripts/import-examples.ts` imports, and the commands its `--tags`3 * backfill runs: pure, so a test reads both without a network.4 *5 * Eight repos, each picked for a shape the code browser must render: a Rust crate with6 * a `master` default and 105 annotated tags first, then a TypeScript7 * library, a Go CLI, a Python package with a long merge history, a8 * Markdown list, a deep monorepo with 740 scoped tags, large single-file C9 * headers, and a repo off GitHub with a submodule.10 */11import { ProjectName } from "@repo/protocol/ids";12import { Option, Redacted } from "effect";1314/** One repo to import: the project it becomes, where it is, its branch, and what it exercises. */15export interface ImportExample {16 readonly project: ProjectName;17 readonly url: string;18 /** The remote's default branch, named so the import never guesses. */19 readonly branch: string;20 /** What kind of repo it is, said for a person. */21 readonly kind: string;22}2324const example = (25 project: string,26 url: string,27 branch: string,28 kind: string29): ImportExample => ({ branch, kind, project: ProjectName.make(project), url });3031/** The repos, in the order they import: anyhow first, the probe for `master` and tags. */32export const examples: readonly ImportExample[] = [33 example(34 "anyhow",35 "https://github.com/dtolnay/anyhow",36 "master",37 "Rust crate"38 ),39 example(40 "ky",41 "https://github.com/sindresorhus/ky",42 "main",43 "TypeScript library"44 ),45 example("gum", "https://github.com/charmbracelet/gum", "main", "Go CLI"),46 example(47 "click",48 "https://github.com/pallets/click",49 "main",50 "Python package"51 ),52 example(53 "awesome",54 "https://github.com/sindresorhus/awesome",55 "main",56 "Markdown list"57 ),58 example(59 "changesets",60 "https://github.com/changesets/changesets",61 "main",62 "TypeScript monorepo"63 ),64 example(65 "stb",66 "https://github.com/nothings/stb",67 "master",68 "C single-file headers"69 ),70 example(71 "fuzzel",72 "https://codeberg.org/dnkl/fuzzel",73 "master",74 "C on Codeberg"75 ),76];7778/**79 * The imports still to run: `only`'s example when it names one, else every80 * example, less each project the platform lists already. A name it lists81 * is never imported again, whatever repo it came from.82 */83export const planImports = (84 all: readonly ImportExample[],85 listed: ReadonlySet<ProjectName>,86 only: Option.Option<ProjectName>87): readonly ImportExample[] =>88 all.filter(89 ({ project }) =>90 Option.match(only, {91 onNone: () => true,92 onSome: (named) => named === project,93 }) && !listed.has(project)94 );9596/** A git remote and the token that writes to it, kept apart so the URL can be shown. */97export interface RedactedUrl {98 readonly url: string;99 readonly token: Redacted.Redacted;100}101102/**103 * One command a run spawns: its argv, which may be printed, and env values104 * of its own, which never are.105 */106export interface Command {107 readonly argv: readonly string[];108 readonly env?: Readonly<Record<string, Redacted.Redacted>>;109}110111/** How a command is shown: its argv alone, never its env. */112export const shownCommand = ({ argv }: Command) => argv.join(" ");113114/** Every tag, under its own name: the one refspec the backfill pushes. */115const TAGS = "refs/tags/*:refs/tags/*";116117/**118 * The backfill of an import that came without its tags: fetch the119 * source's tags into the bare repo `mirror`, then push those tags, and120 * only those, to `remote`. The write token goes to git as an121 * `Authorization` header through git's `GIT_CONFIG_*` env, so it is in no122 * argument, no URL and no printed line. Nothing pushes a branch: `main`123 * moves only by a landing.124 *125 * Only the tags are fetched (not `clone --mirror`, which would bring every126 * `refs/pull/*` GitHub keeps): the canonical repo already has the history127 * they point into, so the push sends the tag objects and little else.128 */129export const tagBackfillCommands = (input: {130 readonly source: string;131 readonly mirror: string;132 readonly remote: RedactedUrl;133}): readonly Command[] => [134 { argv: ["git", "init", "--bare", "--quiet", input.mirror] },135 {136 argv: [137 "git",138 "--git-dir",139 input.mirror,140 "fetch",141 "--quiet",142 "--no-tags",143 input.source,144 TAGS,145 ],146 },147 {148 argv: [149 "git",150 "--git-dir",151 input.mirror,152 "push",153 "--quiet",154 input.remote.url,155 TAGS,156 ],157 env: {158 GIT_CONFIG_COUNT: Redacted.make("1"),159 GIT_CONFIG_KEY_0: Redacted.make("http.extraHeader"),160 GIT_CONFIG_VALUE_0: Redacted.make(161 `Authorization: Bearer ${Redacted.value(input.remote.token)}`162 ),163 },164 },165];
added:scripts/lib/import/run.ts+377 added
1/**2 * The import run: reads the flags, asks the platform what it lists, imports3 * the rest of the examples one at a time, prints each one's heads and tags,4 * records each new import on a stage in the ledger as kept, and with5 * `--tags` backfills the tags of an import that came without them.6 *7 * The platform and the backfill are services (`ImportTarget`,8 * `TagBackfill`), so a test runs the whole run over fakes; `live.ts` holds9 * the real ones.10 */11import { ProjectName } from "@repo/protocol/ids";12import {13 Array,14 Console,15 Context,16 DateTime,17 Effect,18 Option,19 Schema,20} from "effect";21import type { FileSystem, Layer, PlatformError } from "effect";2223import {24 isRecorded,25 ledgerPath,26 readLedger,27 recordCreated,28} from "../../../infra/created.ts";29import type { Created } from "../../../infra/created.ts";30import { flagValue, resources, Stage, stageOf } from "../../../infra/stages.ts";31import { examples, planImports } from "./plan.ts";32import type { ImportExample } from "./plan.ts";3334/** Why the run stopped, said for a person; never a token. */35export class ImportExamplesFailed extends Schema.TaggedError<ImportExamplesFailed>()(36 "ImportExamplesFailed",37 { reason: Schema.String }38) {39 override get message() {40 return this.reason;41 }42}4344const failed = (reason: string) => new ImportExamplesFailed({ reason });4546/** Where the imports go: a dev stage, or the Node world on this machine. */47export const ImportWhere = Schema.TaggedUnion({48 Stage: { stage: Stage, url: Schema.optionalKey(Schema.String) },49 World: {},50});5152export type ImportWhere = typeof ImportWhere.Type;5354/** What `bun scripts/import-examples.ts` was asked to do. */55export interface ImportOptions {56 readonly where: ImportWhere;57 /** The one example to import, when not all. */58 readonly only: Option.Option<ProjectName>;59 /** Print the plan, import and record nothing. */60 readonly dryRun: boolean;61 /** Backfill the tags of an import that has none. */62 readonly tags: boolean;63}6465/** The platform the imports go to, as the operator. */66export class ImportTarget extends Context.Service<67 ImportTarget,68 {69 /** Where it is, said for a person: `dev-oscabriel (https://…)`. */70 readonly label: string;71 readonly listProjects: Effect.Effect<72 ReadonlySet<ProjectName>,73 ImportExamplesFailed74 >;75 /** One `initProject` importing `example`: main's first landed SHA. */76 readonly initProject: (77 example: ImportExample78 ) => Effect.Effect<{ readonly landed?: string }, ImportExamplesFailed>;79 /** How many branches and tags the project's repo serves, anonymously. */80 readonly counts: (81 project: ProjectName82 ) => Effect.Effect<83 { readonly heads: number; readonly tags: number },84 ImportExamplesFailed85 >;86 }87>()("scripts/ImportTarget") {}8889/**90 * Pushes an import's tags from its source to its canonical repo: the one91 * write that skips the gateway, tags only, by the operator. How many tags92 * it pushed.93 */94export class TagBackfill extends Context.Service<95 TagBackfill,96 {97 readonly backfill: (98 example: ImportExample99 ) => Effect.Effect<number, ImportExamplesFailed>;100 }101>()("scripts/TagBackfill") {}102103const USAGE =104 "bun scripts/import-examples.ts --world node | --stage <dev-…> [--url <origin>] [--only <project>] [--tags] [--dry-run]";105106/** The flags the command takes; any other is a typo, refused. */107const FLAGS = new Set([108 "--dry-run",109 "--only",110 "--stage",111 "--tags",112 "--url",113 "--world",114]);115116const decodeProject = Schema.decodeUnknownOption(ProjectName);117118/** The command's flags, read; `--stage demo` is refused before anything runs. */119export const optionsOf = (120 argv: readonly string[]121): Effect.Effect<ImportOptions, ImportExamplesFailed> =>122 Effect.gen(function* () {123 const strange = argv.filter(124 (arg) => arg.startsWith("--") && !FLAGS.has(arg.split("=")[0] ?? arg)125 );126127 if (Array.isReadonlyArrayNonEmpty(strange)) {128 return yield* failed(`unknown flag ${strange.join(", ")}: ${USAGE}`);129 }130131 const world = flagValue(argv, "--world");132 const raw = flagValue(argv, "--stage");133134 if (Option.isSome(world) === Option.isSome(raw)) {135 return yield* failed(`name one of --world node or --stage <s>: ${USAGE}`);136 }137138 if (Option.isSome(world) && world.value !== "node") {139 return yield* failed(140 `--world ${world.value}: the imports know only --world node`141 );142 }143144 if (Option.contains(raw, "demo")) {145 return yield* failed(146 "--stage demo is the recording stage: the imports go on a dev stage only"147 );148 }149150 const tags = argv.includes("--tags");151152 if (tags && Option.isSome(world)) {153 return yield* failed(154 "--tags backfills through Artifacts' REST API, so on a stage only"155 );156 }157158 const where = Option.isSome(world)159 ? ImportWhere.cases.World.make({})160 : yield* stageOf(argv).pipe(161 Effect.mapError(({ message }) => failed(message)),162 Effect.map((stage) =>163 Option.match(flagValue(argv, "--url"), {164 onNone: () => ImportWhere.cases.Stage.make({ stage }),165 onSome: (url) =>166 ImportWhere.cases.Stage.make({167 stage,168 url: url.replace(/\/+$/u, ""),169 }),170 })171 )172 );173174 const only = yield* Option.match(flagValue(argv, "--only"), {175 onNone: () => Effect.succeedNone,176 onSome: (named) =>177 Option.match(178 Option.filter(decodeProject(named), (project) =>179 examples.some((one) => one.project === project)180 ),181 {182 onNone: () =>183 Effect.fail(184 failed(185 `--only ${named} names no example: ${examples.map(({ project }) => project).join(", ")}`186 )187 ),188 onSome: Effect.succeedSome,189 }190 ),191 });192193 return { dryRun: argv.includes("--dry-run"), only, tags, where };194 });195196/** The ledger's line for an import's repo, in the stage's public namespace. */197const repoLine = (198 stage: Stage,199 project: ProjectName,200 at: DateTime.Utc201): Created => ({202 at,203 by: "import",204 kind: "repo",205 name: project,206 namespace: resources(stage).projects,207 stage,208});209210/** The ledger's two lines for a new import on `stage`: its project, and its repo. */211const importLines = (212 stage: Stage,213 project: ProjectName,214 at: DateTime.Utc215): readonly Created[] => [216 { at, by: "import", kind: "project", name: project, stage },217 repoLine(stage, project, at),218];219220const ledgerFailed = ({ message }: PlatformError.PlatformError) =>221 failed(`the ledger (${ledgerPath}): ${message}`);222223/** Appends `entries` to the ledger. */224const record = (entries: readonly Created[]) =>225 Effect.forEach(entries, recordCreated, { discard: true }).pipe(226 Effect.mapError(ledgerFailed)227 );228229/** The stage the run records on, if it runs on one. */230const stageOfWhere = (where: ImportWhere) =>231 ImportWhere.match(where, {232 Stage: ({ stage }) => Option.some(stage),233 World: () => Option.none<Stage>(),234 });235236/**237 * `--tags` on one import: its tags pushed from its source when its repo238 * serves none, the ledger told, and a line printed.239 */240const backfillOne = (241 example: ImportExample,242 tagCount: number,243 stage: Option.Option<Stage>244) =>245 Effect.gen(function* () {246 if (tagCount > 0) {247 return;248 }249250 const pushed = yield* TagBackfill.use((tags) => tags.backfill(example));251 const at = yield* DateTime.now;252253 yield* Option.match(stage, {254 onNone: () => Effect.void,255 onSome: (on) =>256 record([257 { ...repoLine(on, example.project, at), note: "tags backfilled" },258 ]),259 });260261 yield* Console.log(262 ` ${example.project}: ${pushed} tags backfilled from ${example.url}`263 );264 });265266/** The run itself, over a target and a backfill. */267const run = (options: ImportOptions) =>268 Effect.gen(function* () {269 const target = yield* ImportTarget;270 const listed = yield* target.listProjects;271 const stage = stageOfWhere(options.where);272273 const asked = planImports(examples, new Set(), options.only);274 const plan = planImports(examples, listed, options.only);275 const skipped = asked.filter(({ project }) => listed.has(project));276277 yield* Console.log(278 `import-examples on ${target.label}: ${plan.length} to import, ${skipped.length} listed already`279 );280 yield* Effect.forEach(281 skipped,282 ({ project }) => Console.log(` skip ${project}: listed already`),283 { discard: true }284 );285286 if (options.dryRun) {287 yield* Effect.forEach(288 plan,289 ({ branch, project, url }) =>290 Console.log(` would import ${project} from ${url} (${branch})`),291 { discard: true }292 );293 yield* Console.log("dry run: nothing imported, nothing recorded");294295 return;296 }297298 // One at a time: each import is a whole history copied into Artifacts.299 yield* Effect.forEach(300 plan,301 (example) =>302 Effect.gen(function* () {303 const made = yield* target.initProject(example);304 const at = yield* DateTime.now;305306 // Recorded as soon as the platform made it, before anything else307 // can fail.308 yield* Option.match(stage, {309 onNone: () => Effect.void,310 onSome: (on) => record(importLines(on, example.project, at)),311 });312313 const { heads, tags } = yield* target.counts(example.project);314315 yield* Console.log(316 `imported ${example.project} (${example.kind}, ${example.branch}): main at ${made.landed?.slice(0, 12) ?? "nothing"}, ${heads} heads, ${tags} tags`317 );318319 if (options.tags) {320 yield* backfillOne(example, tags, stage);321 }322 }),323 { discard: true }324 );325326 // An import from an earlier run that this run skipped is backfilled327 // too, if the ledger holds it as an import of this stage.328 if (options.tags && Option.isSome(stage)) {329 const ledger = yield* readLedger.pipe(330 Effect.mapError((error) =>331 failed(`the ledger (${ledgerPath}): ${error.message}`)332 )333 );334335 const imported = ledger.filter(({ by }) => by === "import");336337 const earlier = skipped.filter(({ project }) =>338 isRecorded(imported, {339 kind: "project",340 name: project,341 stage: stage.value,342 })343 );344345 yield* Effect.forEach(346 earlier,347 (example) =>348 Effect.flatMap(target.counts(example.project), ({ tags }) =>349 backfillOne(example, tags, stage)350 ),351 { discard: true }352 );353 }354355 yield* Console.log(356 Option.isSome(stage)357 ? `imported ${plan.length} of ${plan.length}, each recorded in ${ledgerPath} as a kept import`358 : `imported ${plan.length} of ${plan.length} into the Node world (not recorded: the ledger is for stages)`359 );360 });361362/**363 * `bun scripts/import-examples.ts …`: reads the flags (refusing `demo`364 * before anything is built or called), then runs over the target and365 * backfill `layersOf` gives for them.366 */367export const importExamples = <E, R>(368 argv: readonly string[],369 layersOf: (370 options: ImportOptions371 ) => Layer.Layer<ImportTarget | TagBackfill, E, R>372): Effect.Effect<void, ImportExamplesFailed | E, R | FileSystem.FileSystem> =>373 Effect.gen(function* () {374 const options = yield* optionsOf(argv);375376 return yield* run(options).pipe(Effect.provide(layersOf(options)));377 });
modified:scripts/import-examples.ts+57 added-9 removed
1/**2 * `bun run import-examples`: imports the open-source repos the code browser3 * is previewed on, one at a time, onto a stage (never `demo`), recording4 * each in the ledger as kept. A stub until 913 builds it: it says so and5 * fails.3 * is previewed on (anyhow first, then ky, gum, click, awesome,4 * changesets, stb and fuzzel), one at a time, as the operator, onto a dev5 * stage or the Node world; never `demo`.6 *7 * bun scripts/import-examples.ts --world node [--only anyhow]8 * bunx varlock run --path apps/platform/ -- \9 * bun scripts/import-examples.ts --stage dev-<user> [--only <p>] [--dry-run]10 * bunx varlock run --path apps/platform/ -- bunx varlock run --path infra/ -- \11 * bun scripts/import-examples.ts --stage dev-<user> --tags12 *13 * A project the platform lists already is skipped. After each import it14 * prints the repo's branch and tag counts (`git ls-remote`, anonymously).15 * Each new import on a stage is recorded in `infra/created.jsonl` with16 * `by: "import"` (its project and its repo): kept, never torn down.17 *18 * `--tags` backfills `refs/tags/*` for an import whose repo serves none:19 * the source's tags fetched into a temporary bare repo, then pushed to the20 * canonical repo with a write token minted over Artifacts' REST API for at21 * most ten minutes and revoked after, even on failure. It is the one write22 * that skips the gateway: tags only, by the operator, never `main`. The23 * core is `lib/import/`.24 */7import { BunRuntime } from "@effect/platform-bun";8import { Console, Effect } from "effect";25import { BunRuntime, BunServices } from "@effect/platform-bun";26import { Effect, Layer, Stdio } from "effect";2728import { worldTarget, restBackfill, stageTarget } from "./lib/import/live.ts";29import {30 ImportWhere,31 importExamples,32 ImportExamplesFailed,33 TagBackfill,34} from "./lib/import/run.ts";35import type { ImportOptions } from "./lib/import/run.ts";3637/** No backfill: the run was not asked for `--tags`, so nothing calls it. */38const noBackfill = Layer.succeed(39 TagBackfill,40 TagBackfill.of({41 backfill: () =>42 Effect.fail(new ImportExamplesFailed({ reason: "--tags was not given" })),43 })44);4546/** The real target and backfill for what the flags ask. */47const layersOf = (options: ImportOptions) =>48 ImportWhere.match(options.where, {49 Stage: ({ stage, url }) =>50 Layer.mergeAll(51 stageTarget(stage, url),52 options.tags ? restBackfill(stage) : noBackfill53 ),54 World: () => Layer.mergeAll(worldTarget, noBackfill),55 });5657if (import.meta.main) {58 BunRuntime.runMain(12 Console.error("not built: 913").pipe(13 Effect.andThen(Effect.die("not built: 913"))14 ),15 { disableErrorReporting: true }59 Effect.gen(function* () {60 const args = yield* (yield* Stdio.Stdio).args;6162 return yield* importExamples(args, layersOf);63 }).pipe(Effect.scoped, Effect.provide(BunServices.layer))64 );65}