seed.ts
This file
Path
scripts/seed.ts
407 lines · 11.1 KiB · TypeScript
Last changed by
Merge demo/prod-ready into mainoscabrielbefore adoption080e1fc
History of this fileTake 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 "--allow-fictional",63 "--as",64 "--json",65 "--only",66 "--operator-env",67 "--stage",68 "--tokens-env",69 "--url",70 "--world",71]);7273const USAGE =74 "bun scripts/seed.ts --world node | --stage <dev-…> | --stage prod --allow-fictional [--url <origin>] [--tokens-env SESSION_TOKENS] [--operator-env OPERATOR_TOKEN] [--only <project> [--as <copy>]] [--json]";7576const failed = (reason: string) => new SeedFailed({ reason });7778const stageFrom = (argv: readonly string[]) =>79 Effect.gen(function* () {80 const stage = yield* stageOf(argv).pipe(81 Effect.mapError(({ message }) => failed(message))82 );8384 // The examples are fictional, and their pages say so: they reach the85 // real platform only when the person running the seed says they may.86 if (stage === "prod" && !argv.includes("--allow-fictional")) {87 return yield* failed(88 "--stage prod is the real platform: the examples are fictional, so seed them on a dev stage, or add --allow-fictional to show them on prod as labelled examples"89 );90 }9192 const tokens = {93 operator: Option.getOrElse(94 flagValue(argv, "--operator-env"),95 () => "OPERATOR_TOKEN"96 ),97 sessions: Option.getOrElse(98 flagValue(argv, "--tokens-env"),99 () => "SESSION_TOKENS"100 ),101 };102103 return Option.match(flagValue(argv, "--url"), {104 onNone: () => SeedWhere.cases.Stage.make({ stage, tokens }),105 onSome: (url) =>106 SeedWhere.cases.Stage.make({107 stage,108 tokens,109 url: url.replace(/\/+$/u, ""),110 }),111 });112 });113114const copyName = (name: string, only: Option.Option<string>) =>115 Effect.gen(function* () {116 if (Option.isNone(only)) {117 return yield* failed(118 `--as ${name} names one copy: add --only <example> to say which example it copies`119 );120 }121122 const spelled = name.includes("/") ? name : `${worldOperator}/${name}`;123124 const copy = yield* Schema.decodeEffect(ProjectName)(spelled).pipe(125 Effect.mapError(() =>126 failed(127 `--as ${name} is no project name: use <owner>/<name>, or a name in lowercase words joined by dashes for ${worldOperator}'s`128 )129 )130 );131132 const example = Schema.decodeOption(ProjectName)(only.value);133134 return Option.contains(example, copy)135 ? yield* failed(136 `--as ${name} is the example's own name: a copy needs a name of its own`137 )138 : copy;139 });140141export const optionsOf = (142 argv: readonly string[]143): Effect.Effect<SeedOptions, SeedFailed> =>144 Effect.gen(function* () {145 const strange = argv.filter(146 (arg) => arg.startsWith("--") && !FLAGS.has(arg.split("=")[0] ?? arg)147 );148149 if (Array.isReadonlyArrayNonEmpty(strange)) {150 return yield* failed(`unknown flag ${strange.join(", ")}: ${USAGE}`);151 }152153 const world = flagValue(argv, "--world");154 const raw = flagValue(argv, "--stage");155156 if (Option.isSome(world) && Option.isSome(raw)) {157 return yield* failed(`--world and --stage: name only one. ${USAGE}`);158 }159160 if (Option.isSome(world) && world.value !== "node") {161 return yield* failed(162 `--world ${world.value}: the seed knows only --world node`163 );164 }165166 const where = Option.isSome(world)167 ? SeedWhere.cases.World.make({})168 : yield* Option.match(raw, {169 onNone: () =>170 Effect.fail(failed(`name --world node or --stage <s>: ${USAGE}`)),171 onSome: () => stageFrom(argv),172 });173174 const json = argv.includes("--json");175 const only = flagValue(argv, "--only");176177 const as = yield* Option.match(flagValue(argv, "--as"), {178 onNone: () => Effect.succeedNone,179 onSome: (name) => Effect.asSome(copyName(name, only)),180 });181182 return {183 json,184 where,185 ...Option.match(only, {186 onNone: () => ({}),187 onSome: (one) => ({ only: one }),188 }),189 ...Option.match(as, {190 onNone: () => ({}),191 onSome: (copy) => ({ as: copy }),192 }),193 };194 });195196export const recordCopy = (stage: Stage, plan: SeedPlan, at: DateTime.Utc) => {197 const { layers, projects } = resources(stage);198 const by = "seed";199 // The project's key is both its Durable Object's id and its repo's name.200 const key = keyOf(plan.project);201202 const entries: readonly Created[] = [203 { at, by, kind: "project", name: key, stage },204 { at, by, kind: "repo", name: key, namespace: projects, stage },205 ...plan.layers.map(({ repo }): Created => ({206 at,207 by,208 kind: "repo",209 name: repo,210 namespace: layers,211 stage,212 })),213 ];214215 return Effect.forEach(entries, recordCreated, { discard: true }).pipe(216 Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))217 );218};219220const SeededSummary = Schema.Struct({221 asks: Schema.Array(Schema.String),222 decider: Handle,223 main: Schema.optionalKey(Schema.String),224 project: ProjectName,225 ratchets: Schema.Array(Schema.String),226});227228type SeededSummary = typeof SeededSummary.Type;229230export const SeedEnvelope = Envelope(231 Schema.Struct({232 projects: Schema.Array(SeededSummary),233 steps: Schema.Array(SeedStep),234 })235);236237const printEnvelope = (envelope: typeof SeedEnvelope.Type) =>238 Effect.flatMap(239 Schema.encodeEffect(Schema.fromJsonString(SeedEnvelope))(envelope),240 Console.log241 ).pipe(Effect.orDie);242243const stageOrigin = (where: (typeof SeedWhere.cases.Stage)["Type"]) =>244 Effect.gen(function* () {245 if (where.url !== undefined) {246 return where.url;247 }248249 const subdomain = yield* recordedSubdomain.pipe(250 Effect.flatMap(Effect.fromOption),251 Effect.mapError(() =>252 failed(253 `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${where.stage} first`254 )255 )256 );257258 return platformOrigin(where.stage, subdomain);259 });260261const targetFor = (where: SeedWhere, plans: readonly SeedPlan[]) =>262 SeedWhere.match(where, {263 Stage: (stage) =>264 Effect.map(stageOrigin(stage), (origin) => ({265 label: `${stage.stage} (${origin})`,266 target: stageTarget(origin, stage.tokens),267 })),268 World: () =>269 Effect.succeed({270 label: "the Node world",271 target: worldTarget(plans.map(({ decider }) => decider)),272 }),273 });274275export const stepLine = ({ _tag, result, target }: SeedStep) =>276 `${_tag} ${target}: ${result}`;277278const projectLine = ({279 asks,280 decider,281 main,282 project,283 ratchets,284}: SeededSummary) =>285 [286 `${project}: main at ${main?.slice(0, 12) ?? "nothing"}`,287 `${asks.length} open asks`,288 `decided by ${decider}`,289 ...ratchets.map((name) => `ratchet ${name}`),290 ].join(", ");291292const summaryOf = (293 plan: SeedPlan,294 held: SeededProject | undefined295): SeededSummary => {296 const summary = {297 asks: (held?.asks ?? []).map(({ ask }) => String(ask)),298 decider: plan.decider,299 project: plan.project,300 ratchets: plan.ratchets,301 };302303 const landed = held?.refs.find(([ref]) => ref === MAIN_REF)?.[1];304305 return landed === undefined ? summary : { ...summary, main: landed };306};307308export const main = (argv: readonly string[]) =>309 Effect.gen(function* () {310 const options = yield* optionsOf(argv);311 const path = yield* Path.Path;312313 const folders = EXAMPLES.filter(314 (folder) =>315 options.only === undefined || path.basename(folder) === options.only316 );317318 if (!Array.isReadonlyArrayNonEmpty(folders)) {319 return yield* failed(320 `--only ${options.only ?? ""} names no example: ${EXAMPLES.map((folder) => path.basename(folder)).join(", ")}`321 );322 }323324 const plans = yield* Effect.forEach(folders, (folder) =>325 Effect.map(planSeed(folder), (plan): SeedPlan =>326 options.as === undefined ? plan : renameSeedPlan(plan, options.as)327 )328 );329330 const { label, target } = yield* targetFor(options.where, plans);331332 const say = (line: string) =>333 options.json ? Effect.void : Console.log(line);334335 const made = (plan: SeedPlan) =>336 SeedWhere.match(options.where, {337 Stage: ({ stage }) =>338 plan.copyOf === undefined339 ? Effect.void340 : Effect.flatMap(DateTime.now, (at) => recordCopy(stage, plan, at)),341 World: () => Effect.void,342 });343344 yield* say(345 `seed: ${plans346 .map(({ copyOf, project }) =>347 copyOf === undefined ? project : `${project} (a copy of ${copyOf})`348 )349 .join(", ")} on ${label}`350 );351352 const run = Effect.gen(function* () {353 yield* ready(plans);354355 const steps = yield* Effect.forEach(plans, (plan) =>356 Effect.tap(runSeedWith(plan, made), (done) =>357 Effect.forEach(done, (each) => say(stepLine(each)), {358 discard: true,359 })360 )361 ).pipe(Effect.map((each) => each.flat()));362363 const held = yield* seeded(plans);364 const projects = plans.map((plan, at) => summaryOf(plan, held[at]));365366 yield* Effect.forEach(projects, (each) => say(projectLine(each)), {367 discard: true,368 });369370 const done = steps.filter(({ result }) => result === "done").length;371372 const count =373 projects.length === 1 ? "1 project" : `${projects.length} projects`;374375 yield* say(376 `seeded ${count} on ${label}: ${steps.length} steps, ${done} done, ${steps.length - done} already`377 );378379 if (options.json) {380 yield* printEnvelope({381 command: "seed",382 data: { projects, steps },383 ok: true,384 v: 1,385 });386 }387 });388389 return yield* run.pipe(390 Effect.provide(target),391 Effect.tapError(({ refusals }) =>392 options.json && refusals !== undefined393 ? printEnvelope({ command: "seed", ok: false, refusals, v: 1 })394 : Effect.void395 )396 );397 });398399if (import.meta.main) {400 BunRuntime.runMain(401 Effect.gen(function* () {402 const args = yield* (yield* Stdio.Stdio).args;403404 return yield* main(args);405 }).pipe(Effect.provide(BunServices.layer))406 );407}