live.ts
This file
Path
scripts/lib/import/live.ts
451 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
lines 1–14why, one step back1import { Fetch, FetchFailed } from "@repo/artifacts/fetch";2import { RepoHost, RepoName } from "@repo/artifacts/repo-host";3import { RepoHostRest } from "@repo/artifacts/repo-host/rest";4import { Client, Contracts } from "@repo/protocol/contracts";5import type { ProjectName } from "@repo/protocol/ids";6import { Refusal } from "@repo/protocol/refusal";7import { explain } from "@repo/protocol/render";8import {9 Config,10 Context,11 Duration,12 Effect,13 FileSystem,14 Layer,Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 15why, one step back15 Option,Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 16–29why, one step back16 Redacted,17 Schema,18 Stream,19} from "effect";20import type { Path } from "effect";21import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";22import { ChildProcess, ChildProcessSpawner } from "effect/process";23import { RpcClient, RpcSerialization } from "effect/rpc";2425import {26 platformOrigin,27 recordedSubdomain,28 resources,29 subdomainFile,Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 30why, one step back30 webOrigin,Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 31–33why, one step back31} from "../../../infra/stages.ts";32import type { Stage } from "../../../infra/stages.ts";33import { servedWorld, worldOperator } from "../seed.ts";Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 34why, one step back34import { shownCommand, tagBackfillCommands, warmPaths } from "./plan.ts";Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 35–40why, one step back35import type { Command } from "./plan.ts";36import {37 ImportExamplesFailed,38 ImportTarget,39 initUntilAnswered,40 TagBackfill,Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 41why, one step back41 Warmer,Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
line 42why, one step back42} from "./run.ts";Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 43why, one step back43import type { WarmRead } from "./run.ts";Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 44–172why, one step back4445const failed = (reason: string) => new ImportExamplesFailed({ reason });4647const isRefusal = Schema.is(Refusal);4849const failedCall =50 (call: string) =>51 (error: { readonly _tag: string; readonly message: string }) =>52 isRefusal(error)53 ? failed(54 `${call} was refused: ${explain([error])55 .map((line) => line.trim())56 .join("; ")}`57 )58 : failed(`${call} got no answer from the platform: ${error.message}`);5960const GIT_ENV = {61 GIT_CONFIG_GLOBAL: "/dev/null",62 GIT_CONFIG_NOSYSTEM: "1",63 GIT_TERMINAL_PROMPT: "0",64 LC_ALL: "C",65};6667const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>68 bytes.pipe(Stream.decodeText(), Stream.mkString);6970const runCommand = (71 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],72 command: Command73) =>74 Effect.scoped(75 Effect.gen(function* () {76 const [file = "git", ...args] = command.argv;77 const secrets = Object.values(command.env ?? {}).map(Redacted.value);7879 const scrub = (text: string) => {80 let said = text;8182 for (const secret of secrets) {83 said = said.replaceAll(secret, "<token>");84 }8586 return said;87 };8889 const child = yield* spawner90 .spawn(91 ChildProcess.make(file, args, {92 env: {93 ...GIT_ENV,94 ...Object.fromEntries(95 Object.entries(command.env ?? {}).map(([name, value]) => [96 name,97 Redacted.value(value),98 ])99 ),100 },101 extendEnv: true,102 })103 )104 .pipe(105 Effect.mapError(({ message }) =>106 failed(`${shownCommand(command)} didn't run: ${scrub(message)}`)107 )108 );109110 const [stdout, stderr, code] = yield* Effect.all(111 [streamText(child.stdout), streamText(child.stderr), child.exitCode],112 { concurrency: "unbounded" }113 ).pipe(114 Effect.mapError(({ message }) =>115 failed(`${shownCommand(command)} failed: ${scrub(message)}`)116 )117 );118119 return Number(code) === 0120 ? stdout121 : yield* failed(122 `${shownCommand(command)} exited ${Number(code)}: ${scrub(stderr.trim())}`123 );124 })125 );126127const countsOf = (listed: string) => {128 const refs = listed129 .split("\n")130 .map((line) => line.split("\t")[1] ?? "")131 .filter((ref) => ref.length > 0);132133 return {134 heads: refs.filter((ref) => ref.startsWith("refs/heads/")).length,135 tags: refs.filter(136 (ref) => ref.startsWith("refs/tags/") && !ref.endsWith("^{}")137 ).length,138 };139};140141const clientAt = (142 origin: string,143 token: Redacted.Redacted144): Layer.Layer<Client> =>145 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(146 Layer.provide(147 RpcClient.layerProtocolHttp({148 transformClient: HttpClient.mapRequest(149 HttpClientRequest.bearerToken(token)150 ),151 url: `${origin}/rpc`,152 })153 ),154 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])155 );156157export const platformTarget = (input: {158 readonly origin: string;159 readonly token: Redacted.Redacted;160 readonly label: string;161}): Layer.Layer<ImportTarget, never, ChildProcessSpawner.ChildProcessSpawner> =>162 Layer.effect(163 ImportTarget,164 Effect.gen(function* () {165 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;166 const client = yield* Client;167168 return ImportTarget.of({169 counts: (project) =>170 runCommand(spawner, {171 argv: ["git", "ls-remote", `${input.origin}/${project}.git`],172 }).pipe(Effect.map(countsOf)),Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 173why, one step back173 initProject: ({ branch, name: project, url }) =>Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 174–189why, one step back174 initUntilAnswered(175 client.initProject({ import: { branch, url }, project }),176 isRefusal177 ).pipe(Effect.mapError(failedCall(`initProject ${project}`))),178 label: input.label,179 listProjects: client.listProjects({}).pipe(180 Effect.map(181 ({ projects }): ReadonlySet<ProjectName> =>182 new Set(projects.map(({ project }) => project))183 ),184 Effect.mapError(failedCall("listProjects"))185 ),186 });187 })188 ).pipe(Layer.provide(clientAt(input.origin, input.token)));189Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 190why, one step back190// A cold why on a long history takes seconds.Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 191–242why, one step back191const WARM_READ_TIMEOUT = Duration.seconds(90);192193const secondsOf = (duration: Duration.Duration) =>194 `${(Duration.toMillis(duration) / 1000).toFixed(1)} s`;195196export const webWarmer = (input: {197 readonly origin: string;198 readonly token: Redacted.Redacted;199 readonly web: string;200}): Layer.Layer<Warmer> =>201 Layer.effect(202 Warmer,203 Effect.gen(function* () {204 const client = yield* Client;205 const http = yield* HttpClient.HttpClient;206207 const read = (path: string): Effect.Effect<WarmRead> =>208 http.get(`${input.web}${path}`).pipe(209 Effect.flatMap((response) =>210 Effect.as(response.text, response.status)211 ),212 Effect.timed,213 Effect.timeout(WARM_READ_TIMEOUT),214 Effect.map(([took, status]) => ({215 ok: status === 200,216 path,217 said: `${status} in ${secondsOf(took)}`,218 })),219 Effect.orElseSucceed(() => ({ ok: false, path, said: "no answer" }))220 );221222 return Warmer.of({223 warm: (project) =>224 client.readTree({ project }).pipe(225 Effect.map(({ readme }) => Option.fromUndefinedOr(readme?.path)),226 Effect.orElseSucceed(() => Option.none<string>()),227 Effect.flatMap((readme) =>228 Effect.forEach(warmPaths(project, readme), read)229 )230 ),231 });232 })233 ).pipe(234 Layer.provide(clientAt(input.origin, input.token)),235 Layer.provide(FetchHttpClient.layer)236 );237238export const noWarmer = Layer.succeed(239 Warmer,240 Warmer.of({ warm: () => Effect.succeed([]) })241);242Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 243–244why, one step back243export const stageTarget = (244 stage: Stage,Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 245–246why, one step back245 url: string | undefined,246 web: string | undefinedMerge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
line 247why, one step back247): Layer.Layer<Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 248why, one step back248 ImportTarget | Warmer,Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 249–261why, one step back249 ImportExamplesFailed,250 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path251> =>252 Layer.unwrap(253 Effect.gen(function* () {254 const token = yield* Config.Redacted("OPERATOR_TOKEN").pipe(255 Effect.mapError(() =>256 failed(257 "no OPERATOR_TOKEN in the environment: run under `bunx varlock run --path apps/platform/ --`"258 )259 )260 );261Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 262–265why, one step back262 const subdomain = yield* recordedSubdomain.pipe(263 Effect.orElseSucceed(() => Option.none<string>())264 );265Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 266–267why, one step back266 const origin =267 url ??Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 268–269why, one step back268 Option.map(subdomain, (sub) => platformOrigin(stage, sub)).pipe(269 Option.getOrUndefinedMerge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 270–271why, one step back270 );271Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 272–292why, one step back272 if (origin === undefined) {273 return yield* failed(274 `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain`275 );276 }277278 // With --url and no --web, the stage's web can't be known: no warming.279 const webAt =280 web ??281 (url === undefined282 ? Option.getOrUndefined(283 Option.map(subdomain, (sub) => webOrigin(stage, sub))284 )285 : undefined);286287 return Layer.mergeAll(288 platformTarget({ label: `${stage} (${origin})`, origin, token }),289 webAt === undefined290 ? noWarmer291 : webWarmer({ origin, token, web: webAt })292 );Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 293–295why, one step back293 })294 );295Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 296why, one step back296// No secret: the Node world never leaves this machine.Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 297–301why, one step back297const worldToken = Redacted.make(298 "operator-import-world-token-0123456789abcdef"299);300301export const worldTarget: Layer.Layer<Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
line 302why, one step back302 ImportTarget | Warmer,Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 303–308why, one step back303 ImportExamplesFailed,304 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path305> = Layer.unwrap(306 servedWorld(new Map([[worldOperator, worldToken]])).pipe(307 Effect.mapError(({ reason }) => failed(reason)),308 Effect.map((origin) =>Merge build/1314-import-list into mainoscabrielbefore adoption33c4cac
lines 309–316why, one step back309 Layer.mergeAll(310 platformTarget({311 label: `the Node world (${origin})`,312 origin,313 token: worldToken,314 }),315 noWarmer316 )Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 317–380why, one step back317 )318 )319);320321const RuntimeFetch = Layer.effect(322 Fetch,323 Effect.gen(function* () {324 const send = yield* FetchHttpClient.Fetch;325326 return Fetch.of({327 fetch: (request) =>328 Effect.tryPromise({329 catch: () =>330 new FetchFailed({331 reason: "the request got no response",332 url: new URL(request.url).origin,333 }),334 try: () => send(request),335 }),336 });337 })338);339340const TOKEN_TTL = Duration.minutes(10);341342export const restBackfill = (343 stage: Stage344): Layer.Layer<345 TagBackfill,346 ImportExamplesFailed,347 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem348> =>349 Layer.effect(350 TagBackfill,351 Effect.gen(function* () {352 const { accountId, token } = yield* Config.all({353 accountId: Config.String("CLOUDFLARE_ACCOUNT_ID"),354 token: Config.Redacted("CLOUDFLARE_API_TOKEN"),355 }).pipe(356 Effect.mapError(() =>357 failed(358 "--tags needs the ops credentials: run under `bunx varlock run --path infra/ --`"359 )360 )361 );362363 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;364 const fs = yield* FileSystem.FileSystem;365366 const host = Context.get(367 yield* Layer.build(368 RepoHostRest.layer({369 accountId,370 namespace: resources(stage).projects,371 token,372 }).pipe(373 Layer.provide(RuntimeFetch),374 Layer.provide(FetchHttpClient.layer)375 )376 ),377 RepoHost378 );379380 return TagBackfill.of({Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 381why, one step back381 backfill: ({ key, name: project, url }) =>Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 382–383why, one step back382 Effect.scoped(383 Effect.gen(function* () {Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 384–385why, one step back384 // The repo is named by the key the project was imported under.385 const name = RepoName.make(key);Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
line 386why, one step back386Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 387–389why, one step back387 const notFound = failed(388 `${project} has no repo in ${resources(stage).projects}`389 );Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 390–396why, one step back390391 const dir = yield* fs392 .makeTempDirectoryScoped({ prefix: "import-tags-" })393 .pipe(394 Effect.mapError(() => failed("can't make a temporary folder"))395 );396Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 397why, one step back397 const mirror = `${dir}/${key}.git`;Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 398–400why, one step back398399 const remote = yield* host400 .remote(name)Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 401why, one step back401 .pipe(Effect.mapError(() => notFound));Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 402–404why, one step back402403 const minted = yield* host404 .mintToken(name, "write", TOKEN_TTL)Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 405why, one step back405 .pipe(Effect.mapError(() => notFound));Merge branch 'build/913-import-any-branch-and-examples'oscabrielbefore adoptiona4543f6
lines 406–451why, one step back406407 const pushed = Effect.gen(function* () {408 yield* Effect.forEach(409 tagBackfillCommands({410 mirror,411 remote: { token: minted.secret, url: remote },412 source: url,413 }),414 (command) => runCommand(spawner, command),415 { discard: true }416 );417418 return countsOf(419 (yield* runCommand(spawner, {420 argv: [421 "git",422 "--git-dir",423 mirror,424 "for-each-ref",425 "--format=%(objectname)\t%(refname)",426 "refs/tags",427 ],428 })).trim()429 ).tags;430 });431432 // Revoked whatever came of the push; a revoke that fails is433 // said, and the token still expires within ten minutes.434 return yield* pushed.pipe(435 Effect.ensuring(436 host437 .revokeToken(name, minted.id)438 .pipe(439 Effect.catch(() =>440 Effect.logWarning(441 `the backfill's write token on ${project} was not revoked; it expires in ten minutes`442 )443 )444 )445 )446 );447 })448 ),449 });450 })451 );