Take a lost import answer's project as made, and list each kept import once
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- `initUntilAnswered` (scripts/lib/import/run.ts) holds the import's retry: an `initProject` that got no answer is asked again 30 s apart, up to three more times. A retry that meets `ProjectExists` is the earlier call's project, finished after its answer was lost (the DO call outlives the edge's timeout), so it counts as made and goes in the ledger; before, the run stopped there and the import was never recorded, so `--tags` could not reach it later. `ProjectExists` on the first call stays a refusal. `live.ts` calls it in place of its inline retry. - Teardown's "kept import" lines are one per resource: a `--tags` backfill records an import's repo a second time, which listed it twice. - Tests: import-examples.test.ts gains three cases over the TestClock (ProjectExists after a lost answer is made; ProjectExists first is refused, asked once; four lost answers give up); teardown.test.ts's kept-imports case now holds a `tags backfilled` line (red by assertion on the doubled line before the fix).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+153 added−23 removed
- tests:+93 added−3 removed
- other:+60 added−20 removed
Provenance
- Commit
612935b- Tree
15bd9ac- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
2ab6eec
5 files changed+153 added−23 removed
modified:infra/lib/teardown.ts+9 added-2 removed
329 unmodified lines330 deletable(entry, guarded, imported) &&331 options.keep.some((name) => ofProject(entry.name, name))332 );333 334- const keptImports = live.filter(({ by }) => by === "import");334+ // 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+ ];342 343 const never = live.filter(344 (entry) =>345 entry.kind !== "project" &&346 !chosen.has(keyOf(entry)) &&347 !kept.includes(entry) &&341- !keptImports.includes(entry)348+ entry.by !== "import"349 );350 351 const projects = live.flatMap(({ by, kind, name }) =>352 kind === "project" && by !== "import" ? [name] : []99 unmodified linesmodified:packages/config/test/import-examples.test.ts+82 added
5 unmodified lines6 * its token.7 */8 import { NodeServices } from "@effect/platform-node";9 import { describe, expect, it } from "@effect/vitest";10+import { ProjectExists } from "@repo/protocol/refusal";11 import {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";26+import { TestClock } from "effect/testing";27 28 import { LedgerFile, readLedger } from "../../../infra/created.ts";29 import {30 examples,5 unmodified lines36 import {37 ImportExamplesFailed,38 importExamples,39 ImportTarget,40+ initUntilAnswered,41 TagBackfill,42 } from "../../../scripts/lib/import/run.ts";43 import { ProjectName } from "../../protocol/src/ids.ts";44 368 unmodified lines413 ).toStrictEqual(["ls-remote anyhow", "tags anyhow"]);414 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))415 );416 });417+418+/** A call the platform never answered, as an edge timeout leaves it. */419+class NoAnswer extends Data.TaggedError("NoAnswer")<{420+ readonly after: string;421+}> {}422+423+/**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+ */427+const 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);435+436+ const call = Effect.flatMap(437+ Ref.getAndUpdate(made, (count) => count + 1),438+ (count) => answers[count] ?? Effect.die("asked once too often")439+ );440+441+ const fiber = yield* Effect.forkChild(442+ initUntilAnswered(call, (error) => !(error instanceof NoAnswer))443+ );444+445+ yield* TestClock.adjust(Duration.minutes(2));446+447+ return { calls: yield* Ref.get(made), ended: yield* Fiber.await(fiber) };448+ });449+450+describe("an import's initProject, asked again", () => {451+ const anyhow = project("anyhow");452+453+ 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+ );465+466+ 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+ );480+481+ 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" }));484+485+ 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+11 added-3 removed
647 unmodified lines648 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))649 );650 651 it.live(652- "lists the kept imports apart, never in the plan, and deletes none of them with --apply",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.655- const files = yield* tempRoot([...devLedger, ...imports]);656+ const files = yield* tempRoot([657+ ...devLedger,658+ ...imports,659+ {660+ ...made("import", "repo", "anyhow", projects),661+ note: "tags backfilled",662+ },663+ ]);664 665 const fake = yield* memoryAccount({666 ...devRepos,667 [projects]: [...devRepos[projects], "anyhow", "ky"],12 unmodified lines680 " kept import: project ky",681 " kept import: repo projects-dev-oscabriel/ky",682 ],683 standing: ["anyhow", "ky"],676- total: "teardown on dev-oscabriel: 13 ledger entries, 5 to delete",684+ total: "teardown on dev-oscabriel: 14 ledger entries, 5 to delete",685 });686 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))687 );688 39 unmodified linesmodified:scripts/lib/import/live.ts+10 added-17 removed
19 unmodified lines20 Effect,21 FileSystem,22 Layer,23 Redacted,24- Schedule,24 Schema,25 Stream,26 } from "effect";27 import type { Path } from "effect";10 unmodified lines38 import type { Stage } from "../../../infra/stages.ts";39 import { servedWorld, worldOperator } from "../seed.ts";40 import { shownCommand, tagBackfillCommands } from "./plan.ts";41 import type { Command } from "./plan.ts";43-import { ImportExamplesFailed, ImportTarget, TagBackfill } from "./run.ts";42+import {43+ ImportExamplesFailed,44+ ImportTarget,45+ initUntilAnswered,46+ TagBackfill,47+} from "./run.ts";48 49 const failed = (reason: string) => new ImportExamplesFailed({ reason });50 51 const isRefusal = Schema.is(Refusal);113 unmodified lines165 ),166 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])167 );168 165-/**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- */170-const AGAIN = Schedule.spaced(Duration.seconds(30));171-169 /** The platform at `origin`, reached as the operator with `token`. */170 export const platformTarget = (input: {171 readonly origin: string;172 readonly token: Redacted.Redacted;10 unmodified lines183 runCommand(spawner, {184 argv: ["git", "ls-remote", `${input.origin}/${project}.git`],185 }).pipe(Effect.map(countsOf)),186 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- ),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> =>213 unmodified linesmodified:scripts/lib/import/run.ts+41 added-1 removed
7 unmodified lines8 * `TagBackfill`), so a test runs the whole run over fakes; `live.ts` holds9 * the real ones.10 */11 import { ProjectName } from "@repo/protocol/ids";12+import { ProjectExists } from "@repo/protocol/refusal";13 import {14 Array,15 Console,16 Context,17 DateTime,18+ Duration,19 Effect,20 Option,21+ Ref,22+ Schedule,23 Schema,24 } from "effect";25 import type { FileSystem, Layer, PlatformError } from "effect";26 76 unmodified lines103 ) => Effect.Effect<number, ImportExamplesFailed>;104 }105 >()("scripts/TagBackfill") {}106 107+const isProjectExists = Schema.is(ProjectExists);108+109+/**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+ */117+export 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);123+124+ 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+ });142+143 const USAGE =144 "bun scripts/import-examples.ts --world node | --stage <dev-…> [--url <origin>] [--only <project>] [--tags] [--dry-run]";145 146 /** The flags the command takes; any other is a typo, refused. */205 unmodified lines352 353 const { heads, tags } = yield* target.counts(example.project);354 355 yield* Console.log(316- `imported ${example.project} (${example.kind}, ${example.branch}): main at ${made.landed?.slice(0, 12) ?? "nothing"}, ${heads} heads, ${tags} tags`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 );358 359 if (options.tags) {360 yield* backfillOne(example, tags, stage);57 unmodified lines