Skip to content
Myr

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 file

Take it

1import { ProjectName } from "@repo/protocol/ids";2import type { ProjectKey } from "@repo/protocol/ids";3import { 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;52  readonly sources: boolean;53  readonly warm: boolean;54  readonly web: Option.Option<string>;55}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") {}7677/** The one write that skips the gateway: tags only, by the operator. */78export class TagBackfill extends Context.Service<79  TagBackfill,80  {81    readonly backfill: (82      example: ImportExample83    ) => Effect.Effect<number, ImportExamplesFailed>;84  }85>()("scripts/TagBackfill") {}8687export interface WarmRead {88  readonly path: string;89  readonly ok: boolean;90  readonly said: string;91}9293// A failed read is reported, never a failure: warming is a courtesy.94export class Warmer extends Context.Service<95  Warmer,96  {97    readonly warm: (project: ProjectName) => Effect.Effect<readonly WarmRead[]>;98  }99>()("scripts/Warmer") {}100101const isProjectExists = Schema.is(ProjectExists);102103/**104 * 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.107 */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 =135  "bun scripts/import-examples.ts --world node | --stage <stage> [--url <origin>] [--web <origin>] [--only <project>] [--tags] [--sources] [--warm] [--dry-run]";136137const FLAGS = new Set([138  "--dry-run",139  "--only",140  "--sources",141  "--stage",142  "--tags",143  "--url",144  "--warm",145  "--web",146  "--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) =>205            examples.some((one) => one.name === project)206          ),207          {208            onNone: () =>209              Effect.fail(210                failed(211                  `--only ${named} names no example: ${examples.map(({ name }) => name).join(", ")}`212                )213              ),214            onSome: Effect.succeedSome,215          }216        ),217    });218219    return {220      dryRun: argv.includes("--dry-run"),221      only,222      sources: argv.includes("--sources"),223      tags,224      warm: argv.includes("--warm"),225      web: Option.map(flagValue(argv, "--web"), (web) =>226        web.replace(/\/+$/u, "")227      ),228      where,229    };230  });231232const repoLine = (233  stage: Stage,234  key: ProjectKey,235  at: DateTime.Utc236): Created => ({237  at,238  by: "import",239  kind: "repo",240  name: key,241  namespace: resources(stage).projects,242  stage,243});244245const importLines = (246  stage: Stage,247  key: ProjectKey,248  at: DateTime.Utc249): readonly Created[] => [250  { at, by: "import", kind: "project", name: key, stage },251  repoLine(stage, key, at),252];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) =>284        record([{ ...repoLine(on, example.key, at), note: "tags backfilled" }]),285    });286287    yield* Console.log(288      `  ${example.name}: ${pushed} tags backfilled from ${example.url}`289    );290  });291292const 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  });306307// An import the ledger records but the platform does not list is still never imported again.308const 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(323      examples.flatMap(({ key, name }) =>324        isRecorded(imported, {325          kind: "project",326          name: key,327          stage: stage.value,328        })329          ? [name]330          : []331      )332    );333  });334335// A repeated `initProject` with the same source makes the platform keep that source.336const 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    );344345    yield* Console.log(`  ${example.name}: ${outcome}`);346  });347348const run = (options: ImportOptions) =>349  Effect.gen(function* () {350    const target = yield* ImportTarget;351    const listed = yield* target.listProjects;352    const stage = stageOfWhere(options.where);353    const recorded = yield* recordedImports(stage);354    const known = new Set([...listed, ...recorded]);355356    const asked = planImports(examples, new Set(), options.only);357    const plan = planImports(examples, known, options.only);358    const skipped = asked.filter(({ name }) => known.has(name));359360    const earlier = skipped.filter(361      ({ name }) => Option.isNone(stage) || recorded.has(name)362    );363364    yield* Console.log(365      `import-examples on ${target.label}: ${plan.length} to import, ${skipped.length} listed already`366    );367    yield* Effect.forEach(368      skipped,369      ({ name }) =>370        Console.log(371          listed.has(name)372            ? `  skip ${name}: listed already`373            : `  skip ${name}: imported already, as the ledger records`374        ),375      { discard: true }376    );377378    if (options.dryRun) {379      yield* Effect.forEach(380        plan,381        ({ branch, name, url }) =>382          Console.log(`  would import ${name} from ${url} (${branch})`),383        { discard: true }384      );385386      if (options.sources) {387        yield* Effect.forEach(388          earlier,389          ({ branch, name, url }) =>390            Console.log(391              `  would keep the source of ${name}: ${url} (${branch})`392            ),393          { discard: true }394        );395      }396397      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;409410          // Recorded before anything else can fail.411          yield* Option.match(stage, {412            onNone: () => Effect.void,413            onSome: (on) => record(importLines(on, example.key, at)),414          });415416          const { heads, tags } = yield* target.counts(example.name);417418          yield* Console.log(419            `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`420          );421422          if (options.tags) {423            yield* backfillOne(example, tags, stage);424          }425426          yield* warmOne(example.name);427        }),428      { discard: true }429    );430431    if (options.tags && Option.isSome(stage)) {432      yield* Effect.forEach(433        earlier,434        (example) =>435          Effect.flatMap(target.counts(example.name), ({ tags }) =>436            backfillOne(example, tags, stage)437          ),438        { discard: true }439      );440    }441442    if (options.sources) {443      yield* Effect.forEach(earlier, sourceOne, { discard: true });444    }445446    if (options.warm) {447      yield* Effect.forEach(skipped, ({ name }) => warmOne(name), {448        discard: true,449      });450    }451452    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: ImportOptions463  ) => Layer.Layer<ImportTarget | TagBackfill | Warmer, E, R>464): 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  });