Skip to content
Myr

Merge branch 'build/913-import-any-branch-and-examples'

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

authored by oscabriel · committed by oscabriel · parents 635c3c7, 612935b · Browse files · 20 files+2169 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+2169 added−43 removed

  • tests:+931 added−0 removed
  • other:+1238 added−43 removed

20 files+2169 added−43 removed

modified:infra/lib/teardown.ts+31 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 // Each kept import once, though a `--tags` backfill records its repo again.335 const keptImports = [336 ...new Map(337 live.flatMap((entry) =>338 entry.by === "import" ? [[keyOf(entry), entry] as const] : []339 )340 ).values(),341 ];342343 const never = live.filter(344 (entry) =>345 entry.kind !== "project" &&346 !chosen.has(keyOf(entry)) &&325 !kept.includes(entry)347 !kept.includes(entry) &&348 entry.by !== "import"349 );350328 const projects = live.flatMap(({ kind, name }) =>329 kind === "project" ? [name] : []351 const projects = live.flatMap(({ by, kind, name }) =>352 kind === "project" && by !== "import" ? [name] : []353 );354355 yield* Console.log(356 `teardown on ${stage}: ${entries.length} ledger entries, ${plan.length} to delete`
5 unmodified lines
362 ...unique.flatMap((entry) =>363 there.has(keyOf(entry)) ? [] : [` gone already: ${shown(entry)}`]364 ),365 ...kept.map((entry) => ` kept by --keep: ${shown(entry)}`),366 ...keptImports.map((entry) => ` kept import: ${shown(entry)}`),367 ...never.map((entry) => ` never selectable: ${shown(entry)}`),368 ...(projects.length === 0369 ? []370 : [
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+491 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 { ProjectExists } from "@repo/protocol/refusal";11import {12 Console,13 Data,14 Duration,15 Effect,16 Fiber,17 FileSystem,18 Layer,19 Option,20 Path,21 Redacted,22 Exit,23 Ref,24 Result,25} from "effect";26import { TestClock } from "effect/testing";2728import { LedgerFile, readLedger } from "../../../infra/created.ts";29import {30 examples,31 planImports,32 shownCommand,33 tagBackfillCommands,34} from "../../../scripts/lib/import/plan.ts";35import type { ImportExample } from "../../../scripts/lib/import/plan.ts";36import {37 ImportExamplesFailed,38 importExamples,39 ImportTarget,40 initUntilAnswered,41 TagBackfill,42} from "../../../scripts/lib/import/run.ts";43import { ProjectName } from "../../protocol/src/ids.ts";4445const project = (name: string) => ProjectName.make(name);4647const names = (planned: readonly ImportExample[]) =>48 planned.map(({ project: name }) => name);4950describe("the import plan", () => {51 it("holds the eight repos of the preview, anyhow first, each master repo on its branch", () => {52 expect(53 examples.map(({ branch, project: name, url }) => [name, branch, url])54 ).toStrictEqual([55 ["anyhow", "master", "https://github.com/dtolnay/anyhow"],56 ["ky", "main", "https://github.com/sindresorhus/ky"],57 ["gum", "main", "https://github.com/charmbracelet/gum"],58 ["click", "main", "https://github.com/pallets/click"],59 ["awesome", "main", "https://github.com/sindresorhus/awesome"],60 ["changesets", "main", "https://github.com/changesets/changesets"],61 ["stb", "master", "https://github.com/nothings/stb"],62 ["fuzzel", "master", "https://codeberg.org/dnkl/fuzzel"],63 ]);64 });6566 it("skips a project the platform lists already, and keeps only the one --only names", () => {67 expect({68 all: names(69 planImports(70 examples,71 new Set([project("ky"), project("stb")]),72 Option.none()73 )74 ),75 listed: names(76 planImports(77 examples,78 new Set([project("anyhow")]),79 Option.some(project("anyhow"))80 )81 ),82 only: names(83 planImports(examples, new Set(), Option.some(project("gum")))84 ),85 }).toStrictEqual({86 all: ["anyhow", "gum", "click", "awesome", "changesets", "fuzzel"],87 listed: [],88 only: ["gum"],89 });90 });91});9293describe("the tag backfill's commands", () => {94 const token = Redacted.make("artifacts-write-token-0123456789abcdef");9596 const commands = tagBackfillCommands({97 mirror: "/tmp/import-tags/anyhow.git",98 remote: {99 token,100 url: "https://acct.artifacts.cloudflare.net/git/projects-dev-oscabriel/anyhow.git",101 },102 source: "https://github.com/dtolnay/anyhow",103 });104105 it("fetches the source's tags into a local bare repo, then pushes refs/tags/* and nothing else", () => {106 expect(commands.map(shownCommand)).toStrictEqual([107 "git init --bare --quiet /tmp/import-tags/anyhow.git",108 "git --git-dir /tmp/import-tags/anyhow.git fetch --quiet --no-tags https://github.com/dtolnay/anyhow refs/tags/*:refs/tags/*",109 "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/*",110 ]);111112 const pushes = commands.filter(({ argv }) => argv.includes("push"));113114 expect(115 pushes.map(({ argv }) => argv.filter((arg) => arg.includes(":")))116 ).toStrictEqual([117 [118 "https://acct.artifacts.cloudflare.net/git/projects-dev-oscabriel/anyhow.git",119 "refs/tags/*:refs/tags/*",120 ],121 ]);122 expect(123 pushes.flatMap(({ argv }) =>124 argv.filter((arg) => /--force|--all|--mirror|main|heads/u.test(arg))125 )126 ).toStrictEqual([]);127 });128129 it("never prints the token: it rides in git's env as a header, redacted, not in an argument or a URL", () => {130 const printed = [131 ...commands.map(shownCommand),132 JSON.stringify(commands),133 JSON.stringify(commands.map(({ env }) => env)),134 ].join("\n");135136 expect(printed.includes(Redacted.value(token))).toBeFalsy();137 expect(138 commands.map(({ env = {} }) =>139 Object.entries(env).map(([name, value]) => [140 name,141 Redacted.value(value),142 ])143 )144 ).toStrictEqual([145 [],146 [],147 [148 ["GIT_CONFIG_COUNT", "1"],149 ["GIT_CONFIG_KEY_0", "http.extraHeader"],150 [151 "GIT_CONFIG_VALUE_0",152 "Authorization: Bearer artifacts-write-token-0123456789abcdef",153 ],154 ],155 ]);156 });157});158159/** A platform in memory: the projects it lists, and every call made to it. */160const fakePlatform = (listed: readonly string[]) =>161 Effect.gen(function* () {162 const calls = yield* Ref.make<readonly string[]>([]);163 const have = new Set(listed.map(project));164 const note = (call: string) => Ref.update(calls, (all) => [...all, call]);165166 const target = ImportTarget.of({167 counts: (name) =>168 note(`ls-remote ${name}`).pipe(Effect.as({ heads: 2, tags: 0 })),169 initProject: (example) =>170 note(`init ${example.project} ${example.branch}`).pipe(171 Effect.tap(() => Effect.sync(() => have.add(example.project))),172 Effect.as({ landed: "a".repeat(40) })173 ),174 label: "dev-oscabriel (https://platform.test)",175 listProjects: note("listProjects").pipe(176 Effect.andThen(Effect.sync(() => new Set(have)))177 ),178 });179180 const backfill = TagBackfill.of({181 backfill: (example) =>182 note(`tags ${example.project}`).pipe(Effect.as(105)),183 });184185 return {186 calls: Ref.get(calls),187 layer: Layer.mergeAll(188 Layer.succeed(ImportTarget, target),189 Layer.succeed(TagBackfill, backfill)190 ),191 };192 });193194/** `importExamples(argv)` over `layer`, with the ledger in a temp folder: how it ended, and what it printed. */195const ran = (196 argv: readonly string[],197 layer: Layer.Layer<ImportTarget | TagBackfill>198) =>199 Effect.gen(function* () {200 const fs = yield* FileSystem.FileSystem;201 const path = yield* Path.Path;202 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "import-913-" });203 const ledgerFile = path.join(dir, "created.jsonl");204 const printed: string[] = [];205206 const captured: Console.Console = {207 ...console,208 log: (...args: readonly unknown[]) => {209 printed.push(args.map(String).join(" "));210 },211 };212213 const result = yield* importExamples(argv, () => layer).pipe(214 Effect.provideService(LedgerFile, ledgerFile),215 Effect.provideService(Console.Console, captured),216 Effect.result217 );218219 const ledger = yield* readLedger.pipe(220 Effect.provideService(LedgerFile, ledgerFile)221 );222223 return { ledger, printed, result };224 });225226const onDev = (...flags: readonly string[]) => [227 "--stage",228 "dev-oscabriel",229 "--url",230 "https://platform.test",231 ...flags,232];233234describe("bun scripts/import-examples.ts", () => {235 it.live(236 "refuses --stage demo before it builds a target or calls anything",237 () =>238 Effect.gen(function* () {239 let built = 0;240241 const result = yield* importExamples(["--stage", "demo"], () => {242 built += 1;243244 return Layer.mergeAll(245 Layer.effect(ImportTarget, Effect.die("a target was built")),246 Layer.effect(TagBackfill, Effect.die("a backfill was built"))247 );248 }).pipe(Effect.result);249250 expect({ built, result }).toStrictEqual({251 built: 0,252 result: Result.fail(253 new ImportExamplesFailed({254 reason:255 "--stage demo is the recording stage: the imports go on a dev stage only",256 })257 ),258 });259 }).pipe(Effect.provide(NodeServices.layer))260 );261262 it.live(263 "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",264 () =>265 Effect.gen(function* () {266 const platform = yield* fakePlatform(["ky", "stb", "click", "gum"]);267 const { ledger, printed, result } = yield* ran(onDev(), platform.layer);268269 expect({270 calls: yield* platform.calls,271 ledger: ledger.map(({ by, kind, name, namespace, stage }) => ({272 by,273 kind,274 name,275 namespace,276 stage,277 })),278 printed,279 result: Result.isSuccess(result),280 }).toStrictEqual({281 calls: [282 "listProjects",283 "init anyhow master",284 "ls-remote anyhow",285 "init awesome main",286 "ls-remote awesome",287 "init changesets main",288 "ls-remote changesets",289 "init fuzzel master",290 "ls-remote fuzzel",291 ],292 ledger: ["anyhow", "awesome", "changesets", "fuzzel"].flatMap(293 (name) => [294 {295 by: "import",296 kind: "project",297 name,298 namespace: undefined,299 stage: "dev-oscabriel",300 },301 {302 by: "import",303 kind: "repo",304 name,305 namespace: "projects-dev-oscabriel",306 stage: "dev-oscabriel",307 },308 ]309 ),310 printed: [311 "import-examples on dev-oscabriel (https://platform.test): 4 to import, 4 listed already",312 " skip ky: listed already",313 " skip gum: listed already",314 " skip click: listed already",315 " skip stb: listed already",316 "imported anyhow (Rust crate, master): main at aaaaaaaaaaaa, 2 heads, 0 tags",317 "imported awesome (Markdown list, main): main at aaaaaaaaaaaa, 2 heads, 0 tags",318 "imported changesets (TypeScript monorepo, main): main at aaaaaaaaaaaa, 2 heads, 0 tags",319 "imported fuzzel (C on Codeberg, master): main at aaaaaaaaaaaa, 2 heads, 0 tags",320 "imported 4 of 4, each recorded in infra/created.jsonl as a kept import",321 ],322 result: true,323 });324 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))325 );326327 it.live("--dry-run prints the plan and imports and records nothing", () =>328 Effect.gen(function* () {329 const platform = yield* fakePlatform(["ky"]);330331 const { ledger, printed } = yield* ran(332 onDev("--dry-run", "--only", "anyhow"),333 platform.layer334 );335336 expect({ calls: yield* platform.calls, ledger, printed }).toStrictEqual({337 calls: ["listProjects"],338 ledger: [],339 printed: [340 "import-examples on dev-oscabriel (https://platform.test): 1 to import, 0 listed already",341 " would import anyhow from https://github.com/dtolnay/anyhow (master)",342 "dry run: nothing imported, nothing recorded",343 ],344 });345 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))346 );347348 it.live(349 "--tags backfills an import that came with no tags, and the ledger says so",350 () =>351 Effect.gen(function* () {352 const platform = yield* fakePlatform([]);353354 const { ledger, printed } = yield* ran(355 onDev("--only", "anyhow", "--tags"),356 platform.layer357 );358359 expect({360 calls: yield* platform.calls,361 ledger: ledger.map(({ kind, name, note }) => [kind, name, note]),362 printed: printed.filter((line) => line.includes("tags")),363 }).toStrictEqual({364 calls: [365 "listProjects",366 "init anyhow master",367 "ls-remote anyhow",368 "tags anyhow",369 ],370 ledger: [371 ["project", "anyhow", undefined],372 ["repo", "anyhow", undefined],373 ["repo", "anyhow", "tags backfilled"],374 ],375 printed: [376 "imported anyhow (Rust crate, master): main at aaaaaaaaaaaa, 2 heads, 0 tags",377 " anyhow: 105 tags backfilled from https://github.com/dtolnay/anyhow",378 ],379 });380 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))381 );382383 it.live(384 "--tags backfills an earlier import the ledger records, and never a listed project it doesn't",385 () =>386 Effect.gen(function* () {387 const fs = yield* FileSystem.FileSystem;388 const path = yield* Path.Path;389390 const dir = yield* fs.makeTempDirectoryScoped({391 prefix: "import-913-",392 });393394 const ledgerFile = path.join(dir, "created.jsonl");395 const platform = yield* fakePlatform(["anyhow", "ky"]);396397 // An earlier run imported anyhow; ky is someone else's project.398 yield* fs.writeFileString(399 ledgerFile,400 `${JSON.stringify({ at: "2026-10-08T20:00:00.000Z", by: "import", kind: "project", name: "anyhow", stage: "dev-oscabriel" })}\n`401 );402403 yield* importExamples(onDev("--tags"), () => platform.layer).pipe(404 Effect.provideService(LedgerFile, ledgerFile),405 Effect.provideService(Console.Console, {406 ...console,407 log: () => {},408 })409 );410411 expect(412 (yield* platform.calls).filter((call) => /ky|anyhow/u.test(call))413 ).toStrictEqual(["ls-remote anyhow", "tags anyhow"]);414 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))415 );416});417418/** A call the platform never answered, as an edge timeout leaves it. */419class NoAnswer extends Data.TaggedError("NoAnswer")<{420 readonly after: string;421}> {}422423/**424 * `initUntilAnswered` over calls that answer `answers` in turn, the clock425 * moved past its waits: how it ended, and how many calls it made.426 */427const askedAgain = (428 answers: readonly Effect.Effect<429 { readonly landed?: string },430 NoAnswer | ProjectExists431 >[]432) =>433 Effect.gen(function* () {434 const made = yield* Ref.make(0);435436 const call = Effect.flatMap(437 Ref.getAndUpdate(made, (count) => count + 1),438 (count) => answers[count] ?? Effect.die("asked once too often")439 );440441 const fiber = yield* Effect.forkChild(442 initUntilAnswered(call, (error) => !(error instanceof NoAnswer))443 );444445 yield* TestClock.adjust(Duration.minutes(2));446447 return { calls: yield* Ref.get(made), ended: yield* Fiber.await(fiber) };448 });449450describe("an import's initProject, asked again", () => {451 const anyhow = project("anyhow");452453 it.effect(454 "takes ProjectExists after a call that got no answer as that call's project, made",455 () =>456 Effect.gen(function* () {457 expect(458 yield* askedAgain([459 Effect.fail(new NoAnswer({ after: "100 s" })),460 Effect.fail(new ProjectExists({ project: anyhow })),461 ])462 ).toStrictEqual({ calls: 2, ended: Exit.succeed({}) });463 })464 );465466 it.effect(467 "answers ProjectExists on the first call, and asks nothing again",468 () =>469 Effect.gen(function* () {470 expect(471 yield* askedAgain([472 Effect.fail(new ProjectExists({ project: anyhow })),473 ])474 ).toStrictEqual({475 calls: 1,476 ended: Exit.fail(new ProjectExists({ project: anyhow })),477 });478 })479 );480481 it.effect("gives up after three more calls with no answer", () =>482 Effect.gen(function* () {483 const lost = Effect.fail(new NoAnswer({ after: "100 s" }));484485 expect(yield* askedAgain([lost, lost, lost, lost])).toStrictEqual({486 calls: 4,487 ended: Exit.fail(new NoAnswer({ after: "100 s" })),488 });489 })490 );491});
modified:packages/config/test/teardown.test.ts+71 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, each once, never in the plan, and deletes none of them with --apply",653 () =>654 Effect.gen(function* () {655 // A `--tags` backfill records anyhow's repo a second time.656 const files = yield* tempRoot([657 ...devLedger,658 ...imports,659 {660 ...made("import", "repo", "anyhow", projects),661 note: "tags backfilled",662 },663 ]);664665 const fake = yield* memoryAccount({666 ...devRepos,667 [projects]: [...devRepos[projects], "anyhow", "ky"],668 });669670 const { printed } = yield* tornDown(["--apply"], fake.account, files);671672 expect({673 kept: printed.filter((line) => /anyhow|\bky\b/u.test(line)),674 standing: yield* fake.standing(projects, ["anyhow", "ky"]),675 total: printed[0],676 }).toStrictEqual({677 kept: [678 " kept import: project anyhow",679 " kept import: repo projects-dev-oscabriel/anyhow",680 " kept import: project ky",681 " kept import: repo projects-dev-oscabriel/ky",682 ],683 standing: ["anyhow", "ky"],684 total: "teardown on dev-oscabriel: 14 ledger entries, 5 to delete",685 });686 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))687 );688689 it.live("--keep leaves a copy's repos and forks out of the plan", () =>690 Effect.gen(function* () {691 const files = yield* tempRoot(devLedger);692 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+407 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 Schema,25 Stream,26} from "effect";27import type { Path } from "effect";28import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";29import { ChildProcess, ChildProcessSpawner } from "effect/process";30import { RpcClient, RpcSerialization } from "effect/rpc";3132import {33 platformOrigin,34 recordedSubdomain,35 resources,36 subdomainFile,37} from "../../../infra/stages.ts";38import type { Stage } from "../../../infra/stages.ts";39import { servedWorld, worldOperator } from "../seed.ts";40import { shownCommand, tagBackfillCommands } from "./plan.ts";41import type { Command } from "./plan.ts";42import {43 ImportExamplesFailed,44 ImportTarget,45 initUntilAnswered,46 TagBackfill,47} from "./run.ts";4849const failed = (reason: string) => new ImportExamplesFailed({ reason });5051const isRefusal = Schema.is(Refusal);5253/** A call the platform refused, said as `explain` says it; or one it never answered. */54const failedCall =55 (call: string) =>56 (error: { readonly _tag: string; readonly message: string }) =>57 isRefusal(error)58 ? failed(59 `${call} was refused: ${explain([error])60 .map((line) => line.trim())61 .join("; ")}`62 )63 : failed(`${call} got no answer from the platform: ${error.message}`);6465/** git's env for a run of its own: no machine config, no prompt. */66const GIT_ENV = {67 GIT_CONFIG_GLOBAL: "/dev/null",68 GIT_CONFIG_NOSYSTEM: "1",69 GIT_TERMINAL_PROMPT: "0",70 LC_ALL: "C",71};7273const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>74 bytes.pipe(Stream.decodeText(), Stream.mkString);7576/**77 * `command` run to its end; what it printed when it ended well. A failure78 * says what git said, with every secret of the command's env cut out.79 */80const runCommand = (81 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],82 command: Command83) =>84 Effect.scoped(85 Effect.gen(function* () {86 const [file = "git", ...args] = command.argv;87 const secrets = Object.values(command.env ?? {}).map(Redacted.value);8889 const scrub = (text: string) => {90 let said = text;9192 for (const secret of secrets) {93 said = said.replaceAll(secret, "<token>");94 }9596 return said;97 };9899 const child = yield* spawner100 .spawn(101 ChildProcess.make(file, args, {102 env: {103 ...GIT_ENV,104 ...Object.fromEntries(105 Object.entries(command.env ?? {}).map(([name, value]) => [106 name,107 Redacted.value(value),108 ])109 ),110 },111 extendEnv: true,112 })113 )114 .pipe(115 Effect.mapError(({ message }) =>116 failed(`${shownCommand(command)} didn't run: ${scrub(message)}`)117 )118 );119120 const [stdout, stderr, code] = yield* Effect.all(121 [streamText(child.stdout), streamText(child.stderr), child.exitCode],122 { concurrency: "unbounded" }123 ).pipe(124 Effect.mapError(({ message }) =>125 failed(`${shownCommand(command)} failed: ${scrub(message)}`)126 )127 );128129 return Number(code) === 0130 ? stdout131 : yield* failed(132 `${shownCommand(command)} exited ${Number(code)}: ${scrub(stderr.trim())}`133 );134 })135 );136137/** The refs `git ls-remote` lists, counted: branches, and tags without their peeled lines. */138const countsOf = (listed: string) => {139 const refs = listed140 .split("\n")141 .map((line) => line.split("\t")[1] ?? "")142 .filter((ref) => ref.length > 0);143144 return {145 heads: refs.filter((ref) => ref.startsWith("refs/heads/")).length,146 tags: refs.filter(147 (ref) => ref.startsWith("refs/tags/") && !ref.endsWith("^{}")148 ).length,149 };150};151152/** The contracts over HTTP at `origin`'s `/rpc`, with `token` as the bearer. */153const clientAt = (154 origin: string,155 token: Redacted.Redacted156): Layer.Layer<Client> =>157 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(158 Layer.provide(159 RpcClient.layerProtocolHttp({160 transformClient: HttpClient.mapRequest(161 HttpClientRequest.bearerToken(token)162 ),163 url: `${origin}/rpc`,164 })165 ),166 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])167 );168169/** The platform at `origin`, reached as the operator with `token`. */170export const platformTarget = (input: {171 readonly origin: string;172 readonly token: Redacted.Redacted;173 readonly label: string;174}): Layer.Layer<ImportTarget, never, ChildProcessSpawner.ChildProcessSpawner> =>175 Layer.effect(176 ImportTarget,177 Effect.gen(function* () {178 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;179 const client = yield* Client;180181 return ImportTarget.of({182 counts: (project) =>183 runCommand(spawner, {184 argv: ["git", "ls-remote", `${input.origin}/${project}.git`],185 }).pipe(Effect.map(countsOf)),186 initProject: ({ branch, project, url }) =>187 initUntilAnswered(188 client.initProject({ import: { branch, url }, project }),189 isRefusal190 ).pipe(Effect.mapError(failedCall(`initProject ${project}`))),191 label: input.label,192 listProjects: client.listProjects({}).pipe(193 Effect.map(194 ({ projects }): ReadonlySet<ProjectName> =>195 new Set(projects.map(({ project }) => project))196 ),197 Effect.mapError(failedCall("listProjects"))198 ),199 });200 })201 ).pipe(Layer.provide(clientAt(input.origin, input.token)));202203/**204 * A deployed dev stage at `url`, or at the workers.dev origin bootstrap205 * recorded, as the operator: `OPERATOR_TOKEN` from the env206 * (`bunx varlock run --path apps/platform/ -- …`), never printed.207 */208export const stageTarget = (209 stage: Stage,210 url: string | undefined211): Layer.Layer<212 ImportTarget,213 ImportExamplesFailed,214 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path215> =>216 Layer.unwrap(217 Effect.gen(function* () {218 const token = yield* Config.Redacted("OPERATOR_TOKEN").pipe(219 Effect.mapError(() =>220 failed(221 "no OPERATOR_TOKEN in the environment: run under `bunx varlock run --path apps/platform/ --`"222 )223 )224 );225226 const origin =227 url ??228 platformOrigin(229 stage,230 yield* recordedSubdomain.pipe(231 Effect.flatMap(Effect.fromOption),232 Effect.mapError(() =>233 failed(234 `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain`235 )236 )237 )238 );239240 return platformTarget({ label: `${stage} (${origin})`, origin, token });241 })242 );243244/** The operator's token in the Node world: no secret, never leaves this machine. */245const worldToken = Redacted.make(246 "operator-import-world-token-0123456789abcdef"247);248249/** The Node world, served for as long as the layer lasts, with the operator's session. */250export const worldTarget: Layer.Layer<251 ImportTarget,252 ImportExamplesFailed,253 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path254> = Layer.unwrap(255 servedWorld(new Map([[worldOperator, worldToken]])).pipe(256 Effect.mapError(({ reason }) => failed(reason)),257 Effect.map((origin) =>258 platformTarget({259 label: `the Node world (${origin})`,260 origin,261 token: worldToken,262 })263 )264 )265);266267/** The `Fetch` port over the runtime's own fetch, as effect/http finds it. */268const RuntimeFetch = Layer.effect(269 Fetch,270 Effect.gen(function* () {271 const send = yield* FetchHttpClient.Fetch;272273 return Fetch.of({274 fetch: (request) =>275 Effect.tryPromise({276 catch: () =>277 new FetchFailed({278 reason: "the request got no response",279 url: new URL(request.url).origin,280 }),281 try: () => send(request),282 }),283 });284 })285);286287/** How long the backfill's write token lives: one backfill, at most. */288const TOKEN_TTL = Duration.minutes(10);289290/**291 * The backfill on `stage`: its public namespace's repos through292 * `RepoHostRest`, with the ops credentials (`CLOUDFLARE_ACCOUNT_ID`,293 * `CLOUDFLARE_API_TOKEN`, from `bunx varlock run --path infra/ -- …`).294 * Each backfill mints a write token on the canonical repo for at most ten295 * minutes, fetches the source's tags into a temporary bare repo, pushes296 * `refs/tags/*` only, and revokes the token, whatever came of the push.297 */298export const restBackfill = (299 stage: Stage300): Layer.Layer<301 TagBackfill,302 ImportExamplesFailed,303 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem304> =>305 Layer.effect(306 TagBackfill,307 Effect.gen(function* () {308 const { accountId, token } = yield* Config.all({309 accountId: Config.String("CLOUDFLARE_ACCOUNT_ID"),310 token: Config.Redacted("CLOUDFLARE_API_TOKEN"),311 }).pipe(312 Effect.mapError(() =>313 failed(314 "--tags needs the ops credentials: run under `bunx varlock run --path infra/ --`"315 )316 )317 );318319 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;320 const fs = yield* FileSystem.FileSystem;321322 const host = Context.get(323 yield* Layer.build(324 RepoHostRest.layer({325 accountId,326 namespace: resources(stage).projects,327 token,328 }).pipe(329 Layer.provide(RuntimeFetch),330 Layer.provide(FetchHttpClient.layer)331 )332 ),333 RepoHost334 );335336 return TagBackfill.of({337 backfill: ({ project, url }) =>338 Effect.scoped(339 Effect.gen(function* () {340 const name = RepoName.make(project);341342 const notFound = () =>343 failed(344 `${project} has no repo in ${resources(stage).projects}`345 );346347 const dir = yield* fs348 .makeTempDirectoryScoped({ prefix: "import-tags-" })349 .pipe(350 Effect.mapError(() => failed("can't make a temporary folder"))351 );352353 const mirror = `${dir}/${project}.git`;354355 const remote = yield* host356 .remote(name)357 .pipe(Effect.mapError(notFound));358359 const minted = yield* host360 .mintToken(name, "write", TOKEN_TTL)361 .pipe(Effect.mapError(notFound));362363 const pushed = Effect.gen(function* () {364 yield* Effect.forEach(365 tagBackfillCommands({366 mirror,367 remote: { token: minted.secret, url: remote },368 source: url,369 }),370 (command) => runCommand(spawner, command),371 { discard: true }372 );373374 return countsOf(375 (yield* runCommand(spawner, {376 argv: [377 "git",378 "--git-dir",379 mirror,380 "for-each-ref",381 "--format=%(objectname)\t%(refname)",382 "refs/tags",383 ],384 })).trim()385 ).tags;386 });387388 // Revoked whatever came of the push; a revoke that fails is389 // said, and the token still expires within ten minutes.390 return yield* pushed.pipe(391 Effect.ensuring(392 host393 .revokeToken(name, minted.id)394 .pipe(395 Effect.catch(() =>396 Effect.logWarning(397 `the backfill's write token on ${project} was not revoked; it expires in ten minutes`398 )399 )400 )401 )402 );403 })404 ),405 });406 })407 );
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+417 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 { ProjectExists } from "@repo/protocol/refusal";13import {14 Array,15 Console,16 Context,17 DateTime,18 Duration,19 Effect,20 Option,21 Ref,22 Schedule,23 Schema,24} from "effect";25import type { FileSystem, Layer, PlatformError } from "effect";2627import {28 isRecorded,29 ledgerPath,30 readLedger,31 recordCreated,32} from "../../../infra/created.ts";33import type { Created } from "../../../infra/created.ts";34import { flagValue, resources, Stage, stageOf } from "../../../infra/stages.ts";35import { examples, planImports } from "./plan.ts";36import type { ImportExample } from "./plan.ts";3738/** Why the run stopped, said for a person; never a token. */39export class ImportExamplesFailed extends Schema.TaggedError<ImportExamplesFailed>()(40 "ImportExamplesFailed",41 { reason: Schema.String }42) {43 override get message() {44 return this.reason;45 }46}4748const failed = (reason: string) => new ImportExamplesFailed({ reason });4950/** Where the imports go: a dev stage, or the Node world on this machine. */51export const ImportWhere = Schema.TaggedUnion({52 Stage: { stage: Stage, url: Schema.optionalKey(Schema.String) },53 World: {},54});5556export type ImportWhere = typeof ImportWhere.Type;5758/** What `bun scripts/import-examples.ts` was asked to do. */59export interface ImportOptions {60 readonly where: ImportWhere;61 /** The one example to import, when not all. */62 readonly only: Option.Option<ProjectName>;63 /** Print the plan, import and record nothing. */64 readonly dryRun: boolean;65 /** Backfill the tags of an import that has none. */66 readonly tags: boolean;67}6869/** The platform the imports go to, as the operator. */70export class ImportTarget extends Context.Service<71 ImportTarget,72 {73 /** Where it is, said for a person: `dev-oscabriel (https://…)`. */74 readonly label: string;75 readonly listProjects: Effect.Effect<76 ReadonlySet<ProjectName>,77 ImportExamplesFailed78 >;79 /** One `initProject` importing `example`: main's first landed SHA. */80 readonly initProject: (81 example: ImportExample82 ) => Effect.Effect<{ readonly landed?: string }, ImportExamplesFailed>;83 /** How many branches and tags the project's repo serves, anonymously. */84 readonly counts: (85 project: ProjectName86 ) => Effect.Effect<87 { readonly heads: number; readonly tags: number },88 ImportExamplesFailed89 >;90 }91>()("scripts/ImportTarget") {}9293/**94 * Pushes an import's tags from its source to its canonical repo: the one95 * write that skips the gateway, tags only, by the operator. How many tags96 * it pushed.97 */98export class TagBackfill extends Context.Service<99 TagBackfill,100 {101 readonly backfill: (102 example: ImportExample103 ) => Effect.Effect<number, ImportExamplesFailed>;104 }105>()("scripts/TagBackfill") {}106107const isProjectExists = Schema.is(ProjectExists);108109/**110 * One import's `initProject`, asked again 30 s apart, up to three more111 * times, while it got no answer (`answered` false): a large import can112 * outlast the edge's request timeout, and the platform adopts the repo the113 * first call left. A refusal is never asked again. `ProjectExists` after a114 * call that got no answer is that call's project, made after its answer115 * was lost: this run's import, its landed SHA not known here.116 */117export const initUntilAnswered = <A extends { readonly landed?: string }, E>(118 call: Effect.Effect<A, E>,119 answered: (error: E) => boolean120): Effect.Effect<{ readonly landed?: string }, E> =>121 Effect.gen(function* () {122 const unanswered = yield* Ref.make(false);123124 return yield* call.pipe(125 Effect.catch((error) =>126 Effect.flatMap(Ref.get(unanswered), (earlier) =>127 earlier && isProjectExists(error)128 ? Effect.succeed({})129 : Effect.fail(error)130 )131 ),132 Effect.tapError((error) =>133 answered(error) ? Effect.void : Ref.set(unanswered, true)134 ),135 Effect.retry({136 schedule: Schedule.spaced(Duration.seconds(30)),137 times: 3,138 while: (error) => !answered(error),139 })140 );141 });142143const USAGE =144 "bun scripts/import-examples.ts --world node | --stage <dev-…> [--url <origin>] [--only <project>] [--tags] [--dry-run]";145146/** The flags the command takes; any other is a typo, refused. */147const FLAGS = new Set([148 "--dry-run",149 "--only",150 "--stage",151 "--tags",152 "--url",153 "--world",154]);155156const decodeProject = Schema.decodeUnknownOption(ProjectName);157158/** The command's flags, read; `--stage demo` is refused before anything runs. */159export const optionsOf = (160 argv: readonly string[]161): Effect.Effect<ImportOptions, ImportExamplesFailed> =>162 Effect.gen(function* () {163 const strange = argv.filter(164 (arg) => arg.startsWith("--") && !FLAGS.has(arg.split("=")[0] ?? arg)165 );166167 if (Array.isReadonlyArrayNonEmpty(strange)) {168 return yield* failed(`unknown flag ${strange.join(", ")}: ${USAGE}`);169 }170171 const world = flagValue(argv, "--world");172 const raw = flagValue(argv, "--stage");173174 if (Option.isSome(world) === Option.isSome(raw)) {175 return yield* failed(`name one of --world node or --stage <s>: ${USAGE}`);176 }177178 if (Option.isSome(world) && world.value !== "node") {179 return yield* failed(180 `--world ${world.value}: the imports know only --world node`181 );182 }183184 if (Option.contains(raw, "demo")) {185 return yield* failed(186 "--stage demo is the recording stage: the imports go on a dev stage only"187 );188 }189190 const tags = argv.includes("--tags");191192 if (tags && Option.isSome(world)) {193 return yield* failed(194 "--tags backfills through Artifacts' REST API, so on a stage only"195 );196 }197198 const where = Option.isSome(world)199 ? ImportWhere.cases.World.make({})200 : yield* stageOf(argv).pipe(201 Effect.mapError(({ message }) => failed(message)),202 Effect.map((stage) =>203 Option.match(flagValue(argv, "--url"), {204 onNone: () => ImportWhere.cases.Stage.make({ stage }),205 onSome: (url) =>206 ImportWhere.cases.Stage.make({207 stage,208 url: url.replace(/\/+$/u, ""),209 }),210 })211 )212 );213214 const only = yield* Option.match(flagValue(argv, "--only"), {215 onNone: () => Effect.succeedNone,216 onSome: (named) =>217 Option.match(218 Option.filter(decodeProject(named), (project) =>219 examples.some((one) => one.project === project)220 ),221 {222 onNone: () =>223 Effect.fail(224 failed(225 `--only ${named} names no example: ${examples.map(({ project }) => project).join(", ")}`226 )227 ),228 onSome: Effect.succeedSome,229 }230 ),231 });232233 return { dryRun: argv.includes("--dry-run"), only, tags, where };234 });235236/** The ledger's line for an import's repo, in the stage's public namespace. */237const repoLine = (238 stage: Stage,239 project: ProjectName,240 at: DateTime.Utc241): Created => ({242 at,243 by: "import",244 kind: "repo",245 name: project,246 namespace: resources(stage).projects,247 stage,248});249250/** The ledger's two lines for a new import on `stage`: its project, and its repo. */251const importLines = (252 stage: Stage,253 project: ProjectName,254 at: DateTime.Utc255): readonly Created[] => [256 { at, by: "import", kind: "project", name: project, stage },257 repoLine(stage, project, at),258];259260const ledgerFailed = ({ message }: PlatformError.PlatformError) =>261 failed(`the ledger (${ledgerPath}): ${message}`);262263/** Appends `entries` to the ledger. */264const record = (entries: readonly Created[]) =>265 Effect.forEach(entries, recordCreated, { discard: true }).pipe(266 Effect.mapError(ledgerFailed)267 );268269/** The stage the run records on, if it runs on one. */270const stageOfWhere = (where: ImportWhere) =>271 ImportWhere.match(where, {272 Stage: ({ stage }) => Option.some(stage),273 World: () => Option.none<Stage>(),274 });275276/**277 * `--tags` on one import: its tags pushed from its source when its repo278 * serves none, the ledger told, and a line printed.279 */280const backfillOne = (281 example: ImportExample,282 tagCount: number,283 stage: Option.Option<Stage>284) =>285 Effect.gen(function* () {286 if (tagCount > 0) {287 return;288 }289290 const pushed = yield* TagBackfill.use((tags) => tags.backfill(example));291 const at = yield* DateTime.now;292293 yield* Option.match(stage, {294 onNone: () => Effect.void,295 onSome: (on) =>296 record([297 { ...repoLine(on, example.project, at), note: "tags backfilled" },298 ]),299 });300301 yield* Console.log(302 ` ${example.project}: ${pushed} tags backfilled from ${example.url}`303 );304 });305306/** The run itself, over a target and a backfill. */307const run = (options: ImportOptions) =>308 Effect.gen(function* () {309 const target = yield* ImportTarget;310 const listed = yield* target.listProjects;311 const stage = stageOfWhere(options.where);312313 const asked = planImports(examples, new Set(), options.only);314 const plan = planImports(examples, listed, options.only);315 const skipped = asked.filter(({ project }) => listed.has(project));316317 yield* Console.log(318 `import-examples on ${target.label}: ${plan.length} to import, ${skipped.length} listed already`319 );320 yield* Effect.forEach(321 skipped,322 ({ project }) => Console.log(` skip ${project}: listed already`),323 { discard: true }324 );325326 if (options.dryRun) {327 yield* Effect.forEach(328 plan,329 ({ branch, project, url }) =>330 Console.log(` would import ${project} from ${url} (${branch})`),331 { discard: true }332 );333 yield* Console.log("dry run: nothing imported, nothing recorded");334335 return;336 }337338 // One at a time: each import is a whole history copied into Artifacts.339 yield* Effect.forEach(340 plan,341 (example) =>342 Effect.gen(function* () {343 const made = yield* target.initProject(example);344 const at = yield* DateTime.now;345346 // Recorded as soon as the platform made it, before anything else347 // can fail.348 yield* Option.match(stage, {349 onNone: () => Effect.void,350 onSome: (on) => record(importLines(on, example.project, at)),351 });352353 const { heads, tags } = yield* target.counts(example.project);354355 yield* Console.log(356 `imported ${example.project} (${example.kind}, ${example.branch}): main at ${made.landed?.slice(0, 12) ?? "a SHA an earlier unanswered call landed"}, ${heads} heads, ${tags} tags`357 );358359 if (options.tags) {360 yield* backfillOne(example, tags, stage);361 }362 }),363 { discard: true }364 );365366 // An import from an earlier run that this run skipped is backfilled367 // too, if the ledger holds it as an import of this stage.368 if (options.tags && Option.isSome(stage)) {369 const ledger = yield* readLedger.pipe(370 Effect.mapError((error) =>371 failed(`the ledger (${ledgerPath}): ${error.message}`)372 )373 );374375 const imported = ledger.filter(({ by }) => by === "import");376377 const earlier = skipped.filter(({ project }) =>378 isRecorded(imported, {379 kind: "project",380 name: project,381 stage: stage.value,382 })383 );384385 yield* Effect.forEach(386 earlier,387 (example) =>388 Effect.flatMap(target.counts(example.project), ({ tags }) =>389 backfillOne(example, tags, stage)390 ),391 { discard: true }392 );393 }394395 yield* Console.log(396 Option.isSome(stage)397 ? `imported ${plan.length} of ${plan.length}, each recorded in ${ledgerPath} as a kept import`398 : `imported ${plan.length} of ${plan.length} into the Node world (not recorded: the ledger is for stages)`399 );400 });401402/**403 * `bun scripts/import-examples.ts …`: reads the flags (refusing `demo`404 * before anything is built or called), then runs over the target and405 * backfill `layersOf` gives for them.406 */407export const importExamples = <E, R>(408 argv: readonly string[],409 layersOf: (410 options: ImportOptions411 ) => Layer.Layer<ImportTarget | TagBackfill, E, R>412): Effect.Effect<void, ImportExamplesFailed | E, R | FileSystem.FileSystem> =>413 Effect.gen(function* () {414 const options = yield* optionsOf(argv);415416 return yield* run(options).pipe(Effect.provide(layersOf(options)));417 });
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}