fake-loader.ts
This file
Path
packages/rules/test/fake-loader.ts
170 lines · 4.5 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–36why, one step back1import { spawn } from "@repo/testkit/git";2import { Effect, FileSystem, Path, Predicate, Stream } from "effect";3import type { Context } from "effect";4import type { ChildProcessSpawner } from "effect/process";56import type {7 LoaderBinding,8 LoaderCode,9 LoaderEntrypoint,10 LoaderModule,11} from "../src/rules-evaluator/worker.ts";1213export type Answer =14 | { readonly responds: string }15 | { readonly rejects: Error }16 | { readonly hangs: true };1718export interface Load {19 readonly code: LoaderCode;20 readonly id: string;21}2223export interface FakeLoader {24 readonly binding: LoaderBinding;25 readonly handles: () => { readonly disposed: number; readonly out: number };26 readonly loads: readonly Load[];27 readonly requests: readonly string[];28}2930// `Symbol.dispose`, which the runtime calls a stub's release by; the lib the31// repo compiles against (ES2023) doesn't type it.32const disposeKey: unknown = Object.getOwnPropertyDescriptor(33 Symbol,34 "dispose"35)?.value;36Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 37why, one step back37/** Keeps workers warm by id, as the Loader does: a second `get` with a seen id calls no `getCode`. */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 38–148why, one step back38export const fakeLoader = (answer: Answer): FakeLoader => {39 const loads: Load[] = [];40 const requests: string[] = [];41 const warm = new Set<string>();42 const counts = { disposed: 0, out: 0 };4344 const handle = <A extends object>(value: A): A => {45 counts.out += 1;4647 if (Predicate.isSymbol(disposeKey)) {48 Object.defineProperty(value, disposeKey, {49 value: () => {50 counts.disposed += 1;51 },52 });53 }5455 return value;56 };5758 const entrypoint = (): LoaderEntrypoint =>59 handle({60 fetch: (_url, init) => {61 requests.push(init.body);6263 if ("responds" in answer) {64 return Promise.resolve({65 text: () => Promise.resolve(answer.responds),66 });67 }6869 return "rejects" in answer70 ? Promise.reject(answer.rejects)71 : Promise.race([]);72 },73 });7475 return {76 binding: {77 get: (id, getCode) => {78 if (!warm.has(id)) {79 warm.add(id);80 loads.push({ code: getCode(), id });81 }8283 return handle({ getEntrypoint: entrypoint });84 },85 },86 handles: () => ({ ...counts }),87 loads,88 requests,89 };90};9192const sourceOf = (module: LoaderModule) => {93 if ("js" in module) {94 return module.js;95 }9697 return "json" in module ? JSON.stringify(module.json) : module.text;98};99100const harness = `101import worker from "./main.js";102const body = await Bun.file(new URL("./request.json", import.meta.url)).text();103const response = await worker.fetch(new Request("https://rules.invalid/", { body, method: "POST" }));104process.stdout.write(await response.text());105process.exit(0);106`;107108const runInBun = (code: LoaderCode, body: string, sdk: string) =>109 Effect.scoped(110 Effect.gen(function* () {111 const fs = yield* FileSystem.FileSystem;112 const path = yield* Path.Path;113 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "loader-" });114115 const files = {116 ...Object.fromEntries(117 Object.entries(code.modules).map(([name, module]) => [118 name,119 sourceOf(module).replaceAll('"@repo/sdk"', JSON.stringify(sdk)),120 ])121 ),122 "request.json": body,123 "run.mjs": harness,124 };125126 for (const [name, source] of Object.entries(files)) {127 const file = path.join(dir, name);128129 yield* fs.makeDirectory(path.dirname(file), { recursive: true });130 yield* fs.writeFileString(file, source);131 }132133 const child = yield* spawn("bun", [path.join(dir, "run.mjs")], {134 cwd: dir,135 });136137 const [stdout, stderr] = yield* Effect.all(138 [139 child.stdout.pipe(Stream.decodeText(), Stream.mkString),140 child.stderr.pipe(Stream.decodeText(), Stream.mkString),141 ],142 { concurrency: "unbounded" }143 );144145 return stdout === "" ? `bun printed nothing: ${stderr}` : stdout;146 })147 ).pipe(Effect.orDie);148Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 149why, one step back149/** Bun stands in for workerd, so the main and the prelude run as the JavaScript they are, without workerd's limits. */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 150–170why, one step back150export const bunLoader = (151 services: Context.Context<152 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path153 >,154 sdk: string155): LoaderBinding => ({156 get: (_id, getCode) => {157 const code = getCode();158159 return {160 getEntrypoint: () => ({161 fetch: (_url, init) =>162 Effect.runPromiseWith(services)(163 Effect.map(runInBun(code, init.body, sdk), (text) => ({164 text: () => Promise.resolve(text),165 }))166 ),167 }),168 };169 },170});