Skip to content
Myr

seed.ts

This file

Path

scripts/seed.ts

404 lines · 10.8 KiB · TypeScript

Last changed by

Merge infra/drop-demo into mainoscabrielbefore adoptionc49b6bf

History of this file

Take it

1import { BunRuntime, BunServices } from "@effect/platform-bun";2import { Envelope } from "@repo/protocol/envelope";3import { Handle, keyOf, ProjectName } from "@repo/protocol/ids";4import {5  Array,6  Console,7  DateTime,8  Effect,9  Option,10  Path,11  Schema,12  Stdio,13} from "effect";1415import { recordCreated } from "../infra/created.ts";16import type { Created } from "../infra/created.ts";17import {18  flagValue,19  platformOrigin,20  recordedSubdomain,21  resources,22  Stage,23  stageOf,24  subdomainFile,25} from "../infra/stages.ts";26import {27  MAIN_REF,28  planSeed,29  ready,30  renameSeedPlan,31  runSeedWith,32  SeedFailed,33  seeded,34  SeedStep,35  stageTarget,36  worldOperator,37  worldTarget,38} from "./lib/seed.ts";39import type { SeededProject, SeedPlan } from "./lib/seed.ts";4041export const EXAMPLES = ["examples/datekit", "examples/burrow"] as const;4243export const SeedWhere = Schema.TaggedUnion({44  Stage: {45    stage: Stage,46    tokens: Schema.Struct({ operator: Schema.String, sessions: Schema.String }),47    url: Schema.optionalKey(Schema.String),48  },49  World: {},50});5152export type SeedWhere = typeof SeedWhere.Type;5354export interface SeedOptions {55  readonly where: SeedWhere;56  readonly only?: string;57  readonly as?: ProjectName;58  readonly json: boolean;59}6061const FLAGS = new Set([62  "--as",63  "--json",64  "--only",65  "--operator-env",66  "--stage",67  "--tokens-env",68  "--url",69  "--world",70]);7172const USAGE =73  "bun scripts/seed.ts --world node | --stage <dev-…> [--url <origin>] [--tokens-env SESSION_TOKENS] [--operator-env OPERATOR_TOKEN] [--only <project> [--as <copy>]] [--json]";7475const failed = (reason: string) => new SeedFailed({ reason });7677const stageFrom = (argv: readonly string[]) =>78  Effect.gen(function* () {79    const stage = yield* stageOf(argv).pipe(80      Effect.mapError(({ message }) => failed(message))81    );8283    if (stage === "prod") {84      return yield* failed(85        "--stage prod is the real platform: the examples are fictional, so seed them on a dev stage"86      );87    }8889    const tokens = {90      operator: Option.getOrElse(91        flagValue(argv, "--operator-env"),92        () => "OPERATOR_TOKEN"93      ),94      sessions: Option.getOrElse(95        flagValue(argv, "--tokens-env"),96        () => "SESSION_TOKENS"97      ),98    };99100    return Option.match(flagValue(argv, "--url"), {101      onNone: () => SeedWhere.cases.Stage.make({ stage, tokens }),102      onSome: (url) =>103        SeedWhere.cases.Stage.make({104          stage,105          tokens,106          url: url.replace(/\/+$/u, ""),107        }),108    });109  });110111const copyName = (name: string, only: Option.Option<string>) =>112  Effect.gen(function* () {113    if (Option.isNone(only)) {114      return yield* failed(115        `--as ${name} names one copy: add --only <example> to say which example it copies`116      );117    }118119    const spelled = name.includes("/") ? name : `${worldOperator}/${name}`;120121    const copy = yield* Schema.decodeEffect(ProjectName)(spelled).pipe(122      Effect.mapError(() =>123        failed(124          `--as ${name} is no project name: use <owner>/<name>, or a name in lowercase words joined by dashes for ${worldOperator}'s`125        )126      )127    );128129    const example = Schema.decodeOption(ProjectName)(only.value);130131    return Option.contains(example, copy)132      ? yield* failed(133          `--as ${name} is the example's own name: a copy needs a name of its own`134        )135      : copy;136  });137138export const optionsOf = (139  argv: readonly string[]140): Effect.Effect<SeedOptions, SeedFailed> =>141  Effect.gen(function* () {142    const strange = argv.filter(143      (arg) => arg.startsWith("--") && !FLAGS.has(arg.split("=")[0] ?? arg)144    );145146    if (Array.isReadonlyArrayNonEmpty(strange)) {147      return yield* failed(`unknown flag ${strange.join(", ")}: ${USAGE}`);148    }149150    const world = flagValue(argv, "--world");151    const raw = flagValue(argv, "--stage");152153    if (Option.isSome(world) && Option.isSome(raw)) {154      return yield* failed(`--world and --stage: name only one. ${USAGE}`);155    }156157    if (Option.isSome(world) && world.value !== "node") {158      return yield* failed(159        `--world ${world.value}: the seed knows only --world node`160      );161    }162163    const where = Option.isSome(world)164      ? SeedWhere.cases.World.make({})165      : yield* Option.match(raw, {166          onNone: () =>167            Effect.fail(failed(`name --world node or --stage <s>: ${USAGE}`)),168          onSome: () => stageFrom(argv),169        });170171    const json = argv.includes("--json");172    const only = flagValue(argv, "--only");173174    const as = yield* Option.match(flagValue(argv, "--as"), {175      onNone: () => Effect.succeedNone,176      onSome: (name) => Effect.asSome(copyName(name, only)),177    });178179    return {180      json,181      where,182      ...Option.match(only, {183        onNone: () => ({}),184        onSome: (one) => ({ only: one }),185      }),186      ...Option.match(as, {187        onNone: () => ({}),188        onSome: (copy) => ({ as: copy }),189      }),190    };191  });192193export const recordCopy = (stage: Stage, plan: SeedPlan, at: DateTime.Utc) => {194  const { layers, projects } = resources(stage);195  const by = "seed";196  // The project's key is both its Durable Object's id and its repo's name.197  const key = keyOf(plan.project);198199  const entries: readonly Created[] = [200    { at, by, kind: "project", name: key, stage },201    { at, by, kind: "repo", name: key, namespace: projects, stage },202    ...plan.layers.map(({ repo }): Created => ({203      at,204      by,205      kind: "repo",206      name: repo,207      namespace: layers,208      stage,209    })),210  ];211212  return Effect.forEach(entries, recordCreated, { discard: true }).pipe(213    Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))214  );215};216217const SeededSummary = Schema.Struct({218  asks: Schema.Array(Schema.String),219  decider: Handle,220  main: Schema.optionalKey(Schema.String),221  project: ProjectName,222  ratchets: Schema.Array(Schema.String),223});224225type SeededSummary = typeof SeededSummary.Type;226227export const SeedEnvelope = Envelope(228  Schema.Struct({229    projects: Schema.Array(SeededSummary),230    steps: Schema.Array(SeedStep),231  })232);233234const printEnvelope = (envelope: typeof SeedEnvelope.Type) =>235  Effect.flatMap(236    Schema.encodeEffect(Schema.fromJsonString(SeedEnvelope))(envelope),237    Console.log238  ).pipe(Effect.orDie);239240const stageOrigin = (where: (typeof SeedWhere.cases.Stage)["Type"]) =>241  Effect.gen(function* () {242    if (where.url !== undefined) {243      return where.url;244    }245246    const subdomain = yield* recordedSubdomain.pipe(247      Effect.flatMap(Effect.fromOption),248      Effect.mapError(() =>249        failed(250          `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${where.stage} first`251        )252      )253    );254255    return platformOrigin(where.stage, subdomain);256  });257258const targetFor = (where: SeedWhere, plans: readonly SeedPlan[]) =>259  SeedWhere.match(where, {260    Stage: (stage) =>261      Effect.map(stageOrigin(stage), (origin) => ({262        label: `${stage.stage} (${origin})`,263        target: stageTarget(origin, stage.tokens),264      })),265    World: () =>266      Effect.succeed({267        label: "the Node world",268        target: worldTarget(plans.map(({ decider }) => decider)),269      }),270  });271272export const stepLine = ({ _tag, result, target }: SeedStep) =>273  `${_tag} ${target}: ${result}`;274275const projectLine = ({276  asks,277  decider,278  main,279  project,280  ratchets,281}: SeededSummary) =>282  [283    `${project}: main at ${main?.slice(0, 12) ?? "nothing"}`,284    `${asks.length} open asks`,285    `decided by ${decider}`,286    ...ratchets.map((name) => `ratchet ${name}`),287  ].join(", ");288289const summaryOf = (290  plan: SeedPlan,291  held: SeededProject | undefined292): SeededSummary => {293  const summary = {294    asks: (held?.asks ?? []).map(({ ask }) => String(ask)),295    decider: plan.decider,296    project: plan.project,297    ratchets: plan.ratchets,298  };299300  const landed = held?.refs.find(([ref]) => ref === MAIN_REF)?.[1];301302  return landed === undefined ? summary : { ...summary, main: landed };303};304305export const main = (argv: readonly string[]) =>306  Effect.gen(function* () {307    const options = yield* optionsOf(argv);308    const path = yield* Path.Path;309310    const folders = EXAMPLES.filter(311      (folder) =>312        options.only === undefined || path.basename(folder) === options.only313    );314315    if (!Array.isReadonlyArrayNonEmpty(folders)) {316      return yield* failed(317        `--only ${options.only ?? ""} names no example: ${EXAMPLES.map((folder) => path.basename(folder)).join(", ")}`318      );319    }320321    const plans = yield* Effect.forEach(folders, (folder) =>322      Effect.map(planSeed(folder), (plan): SeedPlan =>323        options.as === undefined ? plan : renameSeedPlan(plan, options.as)324      )325    );326327    const { label, target } = yield* targetFor(options.where, plans);328329    const say = (line: string) =>330      options.json ? Effect.void : Console.log(line);331332    const made = (plan: SeedPlan) =>333      SeedWhere.match(options.where, {334        Stage: ({ stage }) =>335          plan.copyOf === undefined336            ? Effect.void337            : Effect.flatMap(DateTime.now, (at) => recordCopy(stage, plan, at)),338        World: () => Effect.void,339      });340341    yield* say(342      `seed: ${plans343        .map(({ copyOf, project }) =>344          copyOf === undefined ? project : `${project} (a copy of ${copyOf})`345        )346        .join(", ")} on ${label}`347    );348349    const run = Effect.gen(function* () {350      yield* ready(plans);351352      const steps = yield* Effect.forEach(plans, (plan) =>353        Effect.tap(runSeedWith(plan, made), (done) =>354          Effect.forEach(done, (each) => say(stepLine(each)), {355            discard: true,356          })357        )358      ).pipe(Effect.map((each) => each.flat()));359360      const held = yield* seeded(plans);361      const projects = plans.map((plan, at) => summaryOf(plan, held[at]));362363      yield* Effect.forEach(projects, (each) => say(projectLine(each)), {364        discard: true,365      });366367      const done = steps.filter(({ result }) => result === "done").length;368369      const count =370        projects.length === 1 ? "1 project" : `${projects.length} projects`;371372      yield* say(373        `seeded ${count} on ${label}: ${steps.length} steps, ${done} done, ${steps.length - done} already`374      );375376      if (options.json) {377        yield* printEnvelope({378          command: "seed",379          data: { projects, steps },380          ok: true,381          v: 1,382        });383      }384    });385386    return yield* run.pipe(387      Effect.provide(target),388      Effect.tapError(({ refusals }) =>389        options.json && refusals !== undefined390          ? printEnvelope({ command: "seed", ok: false, refusals, v: 1 })391          : Effect.void392      )393    );394  });395396if (import.meta.main) {397  BunRuntime.runMain(398    Effect.gen(function* () {399      const args = yield* (yield* Stdio.Stdio).args;400401      return yield* main(args);402    }).pipe(Effect.provide(BunServices.layer))403  );404}