bun.ts
This file
Path
packages/rules/src/rules-evaluator/bun.ts
385 lines · 12.0 KiB · TypeScript
Last changed by
Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–20why, one step back1import {2 Config,3 DateTime,4 Duration,5 Effect,6 FileSystem,7 Layer,8 Path,9 Schema,10 Stream,11} from "effect";12import type { Scope } from "effect";13import { ChildProcess, ChildProcessSpawner } from "effect/process";1415import {16 Collected,17 askModules,18 fromCollected,19 projectModule,20 statedWithoutCode,Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9
line 21why, one step back21 visibilityModule,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 22–75why, one step back22} from "../config-folder.ts";23import { defaultPolicyInput } from "../defaults.ts";24import { Finishers, finishPolicy } from "../finish.ts";25import { factsOf, RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";26import type { ConfigBundle } from "../rules-evaluator.ts";27import { bunMain } from "./bun-main.ts";28import { bunPrelude, clockVariable } from "./bun-prelude.ts";2930export interface BunOptions {31 readonly bun?: string;32 /**33 * What the bun binary needs in its env beside `PATH` and the clock: a34 * compiled CLI runs itself as bun with `BUN_BE_BUN=1`. None by default.35 */36 readonly env?: Readonly<Record<string, string>>;37 readonly entry?: string;38 readonly sdk?: string;39 readonly timeout?: Duration.Input;40}4142// An import or export of the sdk by either of its names: the workspace one,43// and the published one, `<npm scope>/cli/rules`. The published name is44// matched by its shape, so `rules` never spells the brand; a config folder45// can import nothing else by a bare name anyway.46const SDK_IMPORT =47 /(?<lead>\bfrom\s*|\bimport\s*\(?\s*)(?<quote>["'])(?:@repo\/sdk|@[a-z0-9][\w.-]*\/cli\/rules)\k<quote>/gu;4849const pointSdkAt = (source: string, sdk: string) =>50 source.replaceAll(SDK_IMPORT, `$<lead>${JSON.stringify(sdk)}`);5152const Output = Schema.TaggedUnion({53 Called: { result: Schema.Json },54 Collected: Collected.fields,55 Failed: {56 detail: Schema.String,57 reason: Schema.Literals(["load", "threw"]),58 },59});6061type Output = typeof Output.Type;6263const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(Output));6465interface Written {66 readonly file: string;67 readonly path: string;68}6970interface Job {71 readonly asks: readonly Written[];72 readonly entry: string;73 readonly facts?: Schema.Json;74 readonly project?: Written;75 readonly rule?: string;Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9
line 76why, one step back76 readonly visibility?: Written;Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 77–123why, one step back77}7879interface Clock {80 readonly now: string;81 readonly seed: number;82}8384// Where the clock stands for a call: rule functions get time only through85// the facts they are called with.86const epoch: Clock = { now: "1970-01-01T00:00:00.000Z", seed: 0 };8788const loadFailed = (detail: string) =>89 new RulesFailed({ detail, reason: "load" });9091const surprised = (output: Output) =>92 new RulesFailed({93 detail: `the evaluator answered ${output._tag} to a job it was not given`,94 reason: "decode",95 });9697const fromFailed = ({ detail, reason }: Extract<Output, { _tag: "Failed" }>) =>98 new RulesFailed({ detail, reason });99100// The most of the subprocess's output the host keeps, from the end: config101// code may print without end, the result is stdout's last line, and what102// broke is told at the end of stderr.103const resultLimit = 16 * 1024 * 1024;104105const logLimit = 64 * 1024;106107const tailOf = <E>(bytes: Stream.Stream<Uint8Array, E>, limit: number) =>108 bytes.pipe(109 Stream.decodeText(),110 // Cut at twice the limit, so each character is copied only a few times.111 Stream.runFold(112 () => "",113 (kept: string, chunk: string) =>114 kept.length + chunk.length > 2 * limit115 ? `${kept}${chunk}`.slice(-limit)116 : `${kept}${chunk}`117 ),118 Effect.map((kept) => kept.slice(-limit))119 );120121const modulesOf = (122 written: ReadonlyMap<string, string>,123 project: string | undefined,Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9
lines 124–125why, one step back124 asks: readonly string[],125 visibility?: stringMerge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 126–131why, one step back126) => {127 const at = (file: string): Written => ({128 file: written.get(file) ?? file,129 path: file,130 });131Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9
lines 132–135why, one step back132 const withProject: Omit<Job, "entry"> =133 project === undefined134 ? { asks: asks.map(at) }135 : { asks: asks.map(at), project: at(project) };Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 136why, one step back136Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9
lines 137–139why, one step back137 return visibility === undefined138 ? withProject139 : { ...withProject, visibility: at(visibility) };Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 140–141why, one step back140};141Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 142why, one step back142/** The subprocess inherits no env beyond `PATH`, with frozen time and randomness and a time limit. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 143–338why, one step back143export const rulesEvaluatorBun = (options: BunOptions = {}) =>144 Layer.effect(145 RulesEvaluator,146 Effect.gen(function* () {147 const fs = yield* FileSystem.FileSystem;148 const path = yield* Path.Path;149 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;150 const finishers = yield* Finishers;151 const bun = options.bun ?? "bun";152 const timeout = Duration.fromInputUnsafe(options.timeout ?? "5 seconds");153154 const searchPath = yield* Effect.orDie(155 Config.String("PATH").pipe(156 Config.withDefault("/usr/local/bin:/usr/bin:/bin")157 )158 );159160 const fromUrl = (url: string) =>161 Effect.orDie(path.fromFileUrl(new URL(url)));162163 const entry =164 options.entry ?? (yield* fromUrl(import.meta.resolve("../entry.ts")));165166 const sdk =167 options.sdk ?? (yield* fromUrl(import.meta.resolve("@repo/sdk")));168169 const writeUnder = (root: string, file: string, source: string) => {170 const target = path.join(root, file);171 const relative = path.relative(root, target);172173 if (174 relative === "" ||175 relative.startsWith("..") ||176 path.isAbsolute(relative)177 ) {178 return Effect.fail(179 loadFailed(`${file}: not a path inside the config folder`)180 );181 }182183 return fs.makeDirectory(path.dirname(target), { recursive: true }).pipe(184 Effect.andThen(fs.writeFileString(target, source)),185 Effect.as(target),186 Effect.mapError((failure) =>187 loadFailed(`${file}: ${failure.message}`)188 )189 );190 };191192 const run = (193 bundle: ConfigBundle,194 clock: Clock,195 job: (written: ReadonlyMap<string, string>) => Omit<Job, "entry">196 ): Effect.Effect<Output, RulesFailed, Scope.Scope> =>197 Effect.gen(function* () {198 const dir = yield* fs199 .makeTempDirectoryScoped({ prefix: "rules-" })200 .pipe(Effect.mapError((failure) => loadFailed(failure.message)));201202 const root = path.join(dir, "config");203 const written = new Map<string, string>();204205 for (const [file, source] of Object.entries(bundle.modules)) {206 written.set(207 file,208 yield* writeUnder(root, file, pointSdkAt(source, sdk))209 );210 }211212 const request: Job = { ...job(written), entry };213214 yield* writeUnder(dir, "job.json", JSON.stringify(request));215 yield* writeUnder(dir, "main.mjs", bunMain);216 yield* writeUnder(dir, "prelude.mjs", bunPrelude);217218 // Details name the bundle's paths, not where they were written.219 const clean = (detail: string) =>220 detail.replaceAll(`${root}/`, "").trim();221222 const command = ChildProcess.make(223 bun,224 [225 "--preload",226 path.join(dir, "prelude.mjs"),227 path.join(dir, "main.mjs"),228 ],229 {230 cwd: dir,231 env: {232 ...options.env,233 [clockVariable]: JSON.stringify(clock),234 PATH: searchPath,235 },236 extendEnv: false,237 forceKillAfter: "1 second",238 }239 );240241 const child = yield* spawner242 .spawn(command)243 .pipe(244 Effect.mapError((failure) =>245 loadFailed(`could not start ${bun}: ${failure.message}`)246 )247 );248249 const [stdout, stderr, exitCode] = yield* Effect.all(250 [251 tailOf(child.stdout, resultLimit),252 tailOf(child.stderr, logLimit),253 child.exitCode,254 ],255 { concurrency: "unbounded" }256 ).pipe(Effect.mapError((failure) => loadFailed(failure.message)));257258 const last = stdout.trimEnd().split("\n").at(-1) ?? "";259260 if (exitCode !== 0 || last === "") {261 return yield* loadFailed(262 clean(stderr) ||263 `${bun} exited with ${exitCode} and printed no result`264 );265 }266267 const output = yield* decodeOutput(last).pipe(268 Effect.mapError(269 (failure) =>270 new RulesFailed({271 detail: `the evaluator's result: ${failure.message}`,272 reason: "decode",273 })274 )275 );276277 return Schema.is(Output.cases.Failed)(output)278 ? { ...output, detail: clean(output.detail) }279 : output;280 });281282 const limited = (283 effect: Effect.Effect<Output, RulesFailed, Scope.Scope>284 ) =>285 Effect.scoped(effect).pipe(286 Effect.timeoutOrElse({287 duration: timeout,288 orElse: () =>289 Effect.fail(290 new RulesFailed({291 detail: `the config folder ran past its ${Duration.format(timeout)} limit`,292 reason: "timeout",293 })294 ),295 })296 );297298 return RulesEvaluator.of({299 call: (input) => {300 const { modules, rule } = input;301 const project = projectModule(modules);302303 if (project === undefined) {304 return Effect.succeed(false);305 }306307 return factsOf(input).pipe(308 Effect.flatMap((facts) =>309 limited(310 run(modules, epoch, (written) => ({311 ...modulesOf(written, project, []),312 facts,313 rule,314 }))315 )316 ),317 Effect.flatMap(318 Output.match({319 Called: ({ result }) =>320 Schema.decodeUnknownEffect(Schema.Boolean)(result).pipe(321 Effect.mapError(322 (failure) =>323 new RulesFailed({324 detail: `${project}: ${rule} gave ${failure.message}`,325 reason: "decode",326 })327 )328 ),329 Collected: (output) => Effect.fail(surprised(output)),330 Failed: (output) => Effect.fail(fromFailed(output)),331 })332 )333 );334 },335 evaluate: ({ at, facts, modules }) =>336 Effect.gen(function* () {337 const project = projectModule(modules);338 const asks = askModules(modules);Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9
line 339why, one step back339 const visibility = visibilityModule(modules);Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 340–353why, one step back340341 const clock: Clock = {342 now: DateTime.formatIso(facts.now),343 seed: facts.seed,344 };345346 // Without a project module, `policy.json` (or the defaults) is the347 // base the ask files join; with one, it is never read.348 const fallback =349 project === undefined350 ? yield* statedWithoutCode(modules)351 : defaultPolicyInput;352353 const policy =Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9
lines 354–356why, one step back354 project === undefined &&355 asks.length === 0 &&356 visibility === undefinedMerge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 357–359why, one step back357 ? fallback358 : yield* limited(359 run(modules, clock, (written) =>Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9
line 360why, one step back360 modulesOf(written, project, asks, visibility)Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 361–371why, one step back361 )362 ).pipe(363 Effect.flatMap(364 Output.match({365 Called: (output) => Effect.fail(surprised(output)),366 Collected: (collected) =>367 fromCollected({368 collected,369 entry: project ?? modules.entry,370 fallback,371 initializer: facts.initializer,Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9
line 372why, one step back372 visibility,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 373–385why, one step back373 }),374 Failed: (output) => Effect.fail(fromFailed(output)),375 })376 )377 );378379 return yield* finishPolicy({ at, facts, finishers, policy });380 }),381 });382 })383 );384385export const RulesEvaluatorBun = rulesEvaluatorBun();