run.ts
This file
Path
scripts/lib/import/run.ts
469 lines · 13.0 KiB · TypeScript
Last changed by
Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
History of this fileTake it
Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
line 1why, one step back1import { ProjectName } from "@repo/protocol/ids";Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 2why, one step back2import type { ProjectKey } from "@repo/protocol/ids";Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 3–51why, one step back3import { ProjectExists } from "@repo/protocol/refusal";4import {5 Array,6 Console,7 Context,8 DateTime,9 Duration,10 Effect,11 Option,12 Ref,13 Schedule,14 Schema,15} from "effect";16import type { FileSystem, Layer, PlatformError } from "effect";1718import {19 isRecorded,20 ledgerPath,21 readLedger,22 recordCreated,23} from "../../../infra/created.ts";24import type { Created } from "../../../infra/created.ts";25import { flagValue, resources, Stage, stageOf } from "../../../infra/stages.ts";26import { examples, planImports } from "./plan.ts";27import type { ImportExample } from "./plan.ts";2829export class ImportExamplesFailed extends Schema.TaggedError<ImportExamplesFailed>()(30 "ImportExamplesFailed",31 { reason: Schema.String }32) {33 override get message() {34 return this.reason;35 }36}3738const failed = (reason: string) => new ImportExamplesFailed({ reason });3940export const ImportWhere = Schema.TaggedUnion({41 Stage: { stage: Stage, url: Schema.optionalKey(Schema.String) },42 World: {},43});4445export type ImportWhere = typeof ImportWhere.Type;4647export interface ImportOptions {48 readonly where: ImportWhere;49 readonly only: Option.Option<ProjectName>;50 readonly dryRun: boolean;51 readonly tags: boolean;Merge build/imported-from into mainoscabrielbefore adoptionf224a14
line 52why, one step back52 readonly sources: boolean;Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 53–54why, one step back53 readonly warm: boolean;54 readonly web: Option.Option<string>;Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 55–76why, one step back55}5657export class ImportTarget extends Context.Service<58 ImportTarget,59 {60 readonly label: string;61 readonly listProjects: Effect.Effect<62 ReadonlySet<ProjectName>,63 ImportExamplesFailed64 >;65 readonly initProject: (66 example: ImportExample67 ) => Effect.Effect<{ readonly landed?: string }, ImportExamplesFailed>;68 readonly counts: (69 project: ProjectName70 ) => Effect.Effect<71 { readonly heads: number; readonly tags: number },72 ImportExamplesFailed73 >;74 }75>()("scripts/ImportTarget") {}76Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 77why, one step back77/** The one write that skips the gateway: tags only, by the operator. */Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 78–86why, one step back78export class TagBackfill extends Context.Service<79 TagBackfill,80 {81 readonly backfill: (82 example: ImportExample83 ) => Effect.Effect<number, ImportExamplesFailed>;84 }85>()("scripts/TagBackfill") {}86Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 87–92why, one step back87export interface WarmRead {88 readonly path: string;89 readonly ok: boolean;90 readonly said: string;91}92Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 93why, one step back93// A failed read is reported, never a failure: warming is a courtesy.Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 94–100why, one step back94export class Warmer extends Context.Service<95 Warmer,96 {97 readonly warm: (project: ProjectName) => Effect.Effect<readonly WarmRead[]>;98 }99>()("scripts/Warmer") {}100Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 101–103why, one step back101const isProjectExists = Schema.is(ProjectExists);102103/**Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
lines 104–106why, one step back104 * A large import can outlast the edge's request timeout; the platform adopts105 * the repo the first call left, so a call with no answer is asked again. A106 * `ProjectExists` after such a call is that call's own project.Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 107–134why, one step back107 */108export const initUntilAnswered = <A extends { readonly landed?: string }, E>(109 call: Effect.Effect<A, E>,110 answered: (error: E) => boolean111): Effect.Effect<{ readonly landed?: string }, E> =>112 Effect.gen(function* () {113 const unanswered = yield* Ref.make(false);114115 return yield* call.pipe(116 Effect.catch((error) =>117 Effect.flatMap(Ref.get(unanswered), (earlier) =>118 earlier && isProjectExists(error)119 ? Effect.succeed({})120 : Effect.fail(error)121 )122 ),123 Effect.tapError((error) =>124 answered(error) ? Effect.void : Ref.set(unanswered, true)125 ),126 Effect.retry({127 schedule: Schedule.spaced(Duration.seconds(30)),128 times: 3,129 while: (error) => !answered(error),130 })131 );132 });133134const USAGE =Merge build/imports-onto-demo into mainoscabrielbefore adoption873046e
line 135why, one step back135 "bun scripts/import-examples.ts --world node | --stage <stage> [--url <origin>] [--web <origin>] [--only <project>] [--tags] [--sources] [--warm] [--dry-run]";Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 136–139why, one step back136137const FLAGS = new Set([138 "--dry-run",139 "--only",Merge build/imported-from into mainoscabrielbefore adoptionf224a14
line 140why, one step back140 "--sources",Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 141–143why, one step back141 "--stage",142 "--tags",143 "--url",Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 144–145why, one step back144 "--warm",145 "--web",Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 146–204why, one step back146 "--world",147]);148149const decodeProject = Schema.decodeUnknownOption(ProjectName);150151export const optionsOf = (152 argv: readonly string[]153): Effect.Effect<ImportOptions, ImportExamplesFailed> =>154 Effect.gen(function* () {155 const strange = argv.filter(156 (arg) => arg.startsWith("--") && !FLAGS.has(arg.split("=")[0] ?? arg)157 );158159 if (Array.isReadonlyArrayNonEmpty(strange)) {160 return yield* failed(`unknown flag ${strange.join(", ")}: ${USAGE}`);161 }162163 const world = flagValue(argv, "--world");164 const raw = flagValue(argv, "--stage");165166 if (Option.isSome(world) === Option.isSome(raw)) {167 return yield* failed(`name one of --world node or --stage <s>: ${USAGE}`);168 }169170 if (Option.isSome(world) && world.value !== "node") {171 return yield* failed(172 `--world ${world.value}: the imports know only --world node`173 );174 }175176 const tags = argv.includes("--tags");177178 if (tags && Option.isSome(world)) {179 return yield* failed(180 "--tags backfills through Artifacts' REST API, so on a stage only"181 );182 }183184 const where = Option.isSome(world)185 ? ImportWhere.cases.World.make({})186 : yield* stageOf(argv).pipe(187 Effect.mapError(({ message }) => failed(message)),188 Effect.map((stage) =>189 Option.match(flagValue(argv, "--url"), {190 onNone: () => ImportWhere.cases.Stage.make({ stage }),191 onSome: (url) =>192 ImportWhere.cases.Stage.make({193 stage,194 url: url.replace(/\/+$/u, ""),195 }),196 })197 )198 );199200 const only = yield* Option.match(flagValue(argv, "--only"), {201 onNone: () => Effect.succeedNone,202 onSome: (named) =>203 Option.match(204 Option.filter(decodeProject(named), (project) =>Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 205why, one step back205 examples.some((one) => one.name === project)Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 206–210why, one step back206 ),207 {208 onNone: () =>209 Effect.fail(210 failed(Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 211why, one step back211 `--only ${named} names no example: ${examples.map(({ name }) => name).join(", ")}`Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 212–218why, one step back212 )213 ),214 onSome: Effect.succeedSome,215 }216 ),217 });218Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 219–221why, one step back219 return {220 dryRun: argv.includes("--dry-run"),221 only,Merge build/imported-from into mainoscabrielbefore adoptionf224a14
line 222why, one step back222 sources: argv.includes("--sources"),Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 223–229why, one step back223 tags,224 warm: argv.includes("--warm"),225 web: Option.map(flagValue(argv, "--web"), (web) =>226 web.replace(/\/+$/u, "")227 ),228 where,229 };Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 230–233why, one step back230 });231232const repoLine = (233 stage: Stage,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 234why, one step back234 key: ProjectKey,Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 235–239why, one step back235 at: DateTime.Utc236): Created => ({237 at,238 by: "import",239 kind: "repo",Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 240why, one step back240 name: key,Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 241–246why, one step back241 namespace: resources(stage).projects,242 stage,243});244245const importLines = (246 stage: Stage,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 247why, one step back247 key: ProjectKey,Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 248–249why, one step back248 at: DateTime.Utc249): readonly Created[] => [Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 250–251why, one step back250 { at, by: "import", kind: "project", name: key, stage },251 repoLine(stage, key, at),Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 252–283why, one step back252];253254const ledgerFailed = ({ message }: PlatformError.PlatformError) =>255 failed(`the ledger (${ledgerPath}): ${message}`);256257const record = (entries: readonly Created[]) =>258 Effect.forEach(entries, recordCreated, { discard: true }).pipe(259 Effect.mapError(ledgerFailed)260 );261262const stageOfWhere = (where: ImportWhere) =>263 ImportWhere.match(where, {264 Stage: ({ stage }) => Option.some(stage),265 World: () => Option.none<Stage>(),266 });267268const backfillOne = (269 example: ImportExample,270 tagCount: number,271 stage: Option.Option<Stage>272) =>273 Effect.gen(function* () {274 if (tagCount > 0) {275 return;276 }277278 const pushed = yield* TagBackfill.use((tags) => tags.backfill(example));279 const at = yield* DateTime.now;280281 yield* Option.match(stage, {282 onNone: () => Effect.void,283 onSome: (on) =>Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 284why, one step back284 record([{ ...repoLine(on, example.key, at), note: "tags backfilled" }]),Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 285–287why, one step back285 });286287 yield* Console.log(Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 288why, one step back288 ` ${example.name}: ${pushed} tags backfilled from ${example.url}`Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 289–291why, one step back289 );290 });291Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 292–306why, one step back292const warmOne = (project: ProjectName) =>293 Effect.gen(function* () {294 const reads = yield* Warmer.use((warmer) => warmer.warm(project));295 const failures = reads.filter(({ ok }) => !ok);296297 yield* Console.log(298 Array.isReadonlyArrayNonEmpty(reads)299 ? [300 ` warmed ${project}: ${reads.length - failures.length} of ${reads.length} pages read`,301 ...failures.map(({ path, said }) => `${path}: ${said}`),302 ].join("; ")303 : ` warm ${project}: no web to read through`304 );305 });306Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 307why, one step back307// An import the ledger records but the platform does not list is still never imported again.Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 308–322why, one step back308const recordedImports = (stage: Option.Option<Stage>) =>309 Effect.gen(function* () {310 if (Option.isNone(stage)) {311 return new Set<ProjectName>();312 }313314 const ledger = yield* readLedger.pipe(315 Effect.mapError((error) =>316 failed(`the ledger (${ledgerPath}): ${error.message}`)317 )318 );319320 const imported = ledger.filter(({ by }) => by === "import");321322 return new Set(Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 323why, one step back323 examples.flatMap(({ key, name }) =>Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 324–325why, one step back324 isRecorded(imported, {325 kind: "project",Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 326why, one step back326 name: key,Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 327–328why, one step back327 stage: stage.value,328 })Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 329why, one step back329 ? [name]Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 330–334why, one step back330 : []331 )332 );333 });334Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 335why, one step back335// A repeated `initProject` with the same source makes the platform keep that source.Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 336–344why, one step back336const sourceOne = (example: ImportExample) =>337 Effect.gen(function* () {338 const target = yield* ImportTarget;339340 const outcome = yield* target.initProject(example).pipe(341 Effect.map(() => `source kept: ${example.url} (${example.branch})`),342 Effect.catch(({ reason }) => Effect.succeed(`source not kept: ${reason}`))343 );344Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 345why, one step back345 yield* Console.log(` ${example.name}: ${outcome}`);Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 346–347why, one step back346 });347Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 348–352why, one step back348const run = (options: ImportOptions) =>349 Effect.gen(function* () {350 const target = yield* ImportTarget;351 const listed = yield* target.listProjects;352 const stage = stageOfWhere(options.where);Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 353–354why, one step back353 const recorded = yield* recordedImports(stage);354 const known = new Set([...listed, ...recorded]);Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 355–356why, one step back355356 const asked = planImports(examples, new Set(), options.only);Merge build/imported-from into mainoscabrielbefore adoptionf224a14
line 357why, one step back357 const plan = planImports(examples, known, options.only);Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 358why, one step back358 const skipped = asked.filter(({ name }) => known.has(name));Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
line 359why, one step back359Merge build/imported-from into mainoscabrielbefore adoptionf224a14
line 360why, one step back360 const earlier = skipped.filter(Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 361why, one step back361 ({ name }) => Option.isNone(stage) || recorded.has(name)Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 362–363why, one step back362 );363Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 364–368why, one step back364 yield* Console.log(365 `import-examples on ${target.label}: ${plan.length} to import, ${skipped.length} listed already`366 );367 yield* Effect.forEach(368 skipped,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 369why, one step back369 ({ name }) =>Merge build/imported-from into mainoscabrielbefore adoptionf224a14
line 370why, one step back370 Console.log(Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 371–373why, one step back371 listed.has(name)372 ? ` skip ${name}: listed already`373 : ` skip ${name}: imported already, as the ledger records`Merge build/imported-from into mainoscabrielbefore adoptionf224a14
line 374why, one step back374 ),Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 375–380why, one step back375 { discard: true }376 );377378 if (options.dryRun) {379 yield* Effect.forEach(380 plan,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 381–382why, one step back381 ({ branch, name, url }) =>382 Console.log(` would import ${name} from ${url} (${branch})`),Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 383–384why, one step back383 { discard: true }384 );Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 385–388why, one step back385386 if (options.sources) {387 yield* Effect.forEach(388 earlier,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 389why, one step back389 ({ branch, name, url }) =>Merge build/imported-from into mainoscabrielbefore adoptionf224a14
line 390why, one step back390 Console.log(Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 391why, one step back391 ` would keep the source of ${name}: ${url} (${branch})`Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 392–396why, one step back392 ),393 { discard: true }394 );395 }396Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 397–409why, one step back397 yield* Console.log("dry run: nothing imported, nothing recorded");398399 return;400 }401402 // One at a time: each import is a whole history copied into Artifacts.403 yield* Effect.forEach(404 plan,405 (example) =>406 Effect.gen(function* () {407 const made = yield* target.initProject(example);408 const at = yield* DateTime.now;409Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 410why, one step back410 // Recorded before anything else can fail.Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 411–412why, one step back411 yield* Option.match(stage, {412 onNone: () => Effect.void,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 413why, one step back413 onSome: (on) => record(importLines(on, example.key, at)),Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 414–415why, one step back414 });415Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 416why, one step back416 const { heads, tags } = yield* target.counts(example.name);Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 417–418why, one step back417418 yield* Console.log(Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 419why, one step back419 `imported ${example.name} (${example.kind}, ${example.branch}): main at ${made.landed?.slice(0, 12) ?? "a SHA an earlier unanswered call landed"}, ${heads} heads, ${tags} tags`Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 420–424why, one step back420 );421422 if (options.tags) {423 yield* backfillOne(example, tags, stage);424 }Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 425why, one step back425Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 426why, one step back426 yield* warmOne(example.name);Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 427–434why, one step back427 }),428 { discard: true }429 );430431 if (options.tags && Option.isSome(stage)) {432 yield* Effect.forEach(433 earlier,434 (example) =>Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 435why, one step back435 Effect.flatMap(target.counts(example.name), ({ tags }) =>Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 436–439why, one step back436 backfillOne(example, tags, stage)437 ),438 { discard: true }439 );Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 440–443why, one step back440 }441442 if (options.sources) {443 yield* Effect.forEach(earlier, sourceOne, { discard: true });Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 444–445why, one step back444 }445Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 446why, one step back446 if (options.warm) {Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 447why, one step back447 yield* Effect.forEach(skipped, ({ name }) => warmOne(name), {Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 448–451why, one step back448 discard: true,449 });450 }451Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 452–462why, one step back452 yield* Console.log(453 Option.isSome(stage)454 ? `imported ${plan.length} of ${plan.length}, each recorded in ${ledgerPath} as a kept import`455 : `imported ${plan.length} of ${plan.length} into the Node world (not recorded: the ledger is for stages)`456 );457 });458459export const importExamples = <E, R>(460 argv: readonly string[],461 layersOf: (462 options: ImportOptionsMerge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 463why, one step back463 ) => Layer.Layer<ImportTarget | TagBackfill | Warmer, E, R>Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 464–469why, one step back464): Effect.Effect<void, ImportExamplesFailed | E, R | FileSystem.FileSystem> =>465 Effect.gen(function* () {466 const options = yield* optionsOf(argv);467468 return yield* run(options).pipe(Effect.provide(layersOf(options)));469 });