worker.ts
This file
Path
packages/rules/src/rules-evaluator/worker.ts
377 lines · 11.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–8why, one step back1import { DateTime, Effect, Layer, Option, Predicate, Schema } from "effect";23import {4 Collected,5 askModules,6 fromCollected,7 projectModule,8 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 9why, one step back9 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 10–27why, one step back10} from "../config-folder.ts";11import { defaultPolicyInput } from "../defaults.ts";12import { Finishers, finishPolicy } from "../finish.ts";13import {14 mainModule,15 mainName,16 preludeModule,17 preludeName,18} from "../prelude.ts";19import type { FrozenFacts } from "../prelude.ts";20import { factsOf, RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";21import type { ConfigBundle, RuleName } from "../rules-evaluator.ts";2223export type LoaderModule =24 | { readonly js: string }25 | { readonly json: Schema.Json }26 | { readonly text: string };27Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 28why, one step back28/** No `env` (no binding reaches config code), no outbound and no subrequests. */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 29–48why, one step back29export interface LoaderCode {30 readonly compatibilityDate: string;31 readonly globalOutbound: null;32 readonly limits: { readonly cpuMs: number; readonly subRequests: number };33 readonly mainModule: string;34 readonly modules: Readonly<Record<string, LoaderModule>>;35}3637export interface LoaderEntrypoint {38 readonly fetch: (39 url: string,40 init: { readonly body: string; readonly method: "POST" }41 ) => Promise<{ readonly text: () => Promise<string> }>;42}4344export interface LoadedWorker {45 readonly getEntrypoint: () => LoaderEntrypoint;46}4748/**Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
lines 49–51why, one step back49 * Typed by the fields the adapter uses, so `rules` needs no Workers types.50 * `get` keeps a worker warm under its id and calls `getCode` only for an id it51 * doesn't hold.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 52–195why, one step back52 */53export interface LoaderBinding {54 readonly get: (id: string, getCode: () => LoaderCode) => LoadedWorker;55}5657export interface WorkerOptions {58 readonly compatibilityDate?: string;59 readonly cpuMs?: number;60 readonly timeoutMs?: number;61}6263const Output = Schema.TaggedUnion({64 Called: { result: Schema.Json },65 Collected: Collected.fields,66 Failed: {67 detail: Schema.String,68 reason: Schema.Literals(["load", "threw"]),69 },70});7172type Output = typeof Output.Type;7374const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(Output));7576type Job =77 | Readonly<Record<string, never>>78 | { readonly facts: Schema.Json; readonly rule: RuleName };7980// The address requests to a loaded worker carry; it has no network to81// reach, so any address serves.82const jobUrl = "https://rules.invalid/";8384// The clock and seed a rule call runs under, as `/bun`'s: a rule gets time85// only through the facts it is called with.86const epoch: FrozenFacts = { now: 0, seed: 0 };8788// `Symbol.dispose`, by which the runtime releases a stub. The lib this code89// compiles against (ES2023) doesn't type it, so it is read as a value.90const disposeKey: unknown = Object.getOwnPropertyDescriptor(91 Symbol,92 "dispose"93)?.value;9495// What workerd says when a worker spends its CPU limit, or hangs with96// nothing left to wait for.97const RAN_OUT =98 /\b(?:cpu time|time limit|timed out|never generate a response)\b/iu;99100// What workerd says when a module won't compile: it compiles every module101// before the worker starts, so a syntax error anywhere in the folder102// rejects the request instead of reaching the main.103const WONT_START = /^Failed to start Worker\b/u;104105const SCRIPT = /\.[cm]?[jt]s$/u;106107const loadFailed = (detail: string) =>108 new RulesFailed({ detail, reason: "load" });109110const surprised = (output: Output) =>111 new RulesFailed({112 detail: `the evaluator answered ${output._tag} to a job it was not given`,113 reason: "decode",114 });115116const fromFailed = ({ detail, reason }: Extract<Output, { _tag: "Failed" }>) =>117 new RulesFailed({ detail, reason });118119const messageOf = (cause: unknown) =>120 Predicate.isError(cause) ? cause.message : String(cause);121122const thrownBy = (cause: unknown) => {123 const message = messageOf(cause);124 const detail = `the loaded worker: ${message}`;125126 if (WONT_START.test(message)) {127 return new RulesFailed({ detail, reason: "load" });128 }129130 return new RulesFailed({131 detail,132 reason: RAN_OUT.test(message) ? "timeout" : "threw",133 });134};135136const released = (stub: LoadedWorker | LoaderEntrypoint) =>137 Effect.try(() => {138 const dispose =139 Predicate.isSymbol(disposeKey) && Predicate.hasProperty(stub, disposeKey)140 ? stub[disposeKey]141 : undefined;142143 if (Predicate.isFunction(dispose)) {144 dispose.call(stub);145 }146 }).pipe(Effect.ignore);147148const requested = (entrypoint: LoaderEntrypoint, job: Job) =>149 Effect.tryPromise({150 catch: thrownBy,151 try: () =>152 entrypoint.fetch(jobUrl, {153 body: JSON.stringify(job),154 method: "POST",155 }),156 }).pipe(157 Effect.flatMap((response) =>158 Effect.tryPromise({ catch: thrownBy, try: () => response.text() })159 ),160 Effect.flatMap((text) =>161 decodeOutput(text).pipe(162 Effect.mapError(163 (failure) =>164 new RulesFailed({165 detail: `the evaluator's result: ${failure.message}`,166 reason: "decode",167 })168 )169 )170 )171 );172173const isModulePath = (path: string) =>174 path !== mainName &&175 path !== preludeName &&176 path177 .split("/")178 .every((segment) => segment !== "" && segment !== "." && segment !== "..");179180const insideTheFolder = (bundle: ConfigBundle) => {181 const outside = Object.keys(bundle.modules).filter(182 (path) => !isModulePath(path)183 );184185 return outside.length === 0186 ? Effect.void187 : Effect.fail(188 loadFailed(189 `${outside.join(", ")}: not a module path inside the config folder`190 )191 );192};193194const parsedJson = Schema.decodeOption(Schema.fromJsonString(Schema.Json));195Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 196why, one step back196/** JSON that won't parse goes as text, which fails only if config code imports 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 197–218why, one step back197const moduleOf = (path: string, source: string): LoaderModule => {198 if (SCRIPT.test(path)) {199 return { js: source };200 }201202 const json = path.endsWith(".json") ? parsedJson(source) : Option.none();203204 return Option.match(json, {205 onNone: () => ({ text: source }),206 onSome: (data) => ({ json: data }),207 });208};209210/**211 * The Loader's id for a bundle under a clock. The landed commit and the sdk212 * version name the bundle, and the clock names the prelude, so equal ids213 * hold equal code and a warm worker serves every later request at that214 * commit.215 */216const workerIdOf = (bundle: ConfigBundle, at: string, clock: FrozenFacts) =>217 `rules:${at}:${bundle.sdkVersion}:${clock.now}:${clock.seed}`;218Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 219why, one step back219/** The adapter reads no clock: an evaluation's clock is `facts.now`, the landed commit's time. */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 220–232why, one step back220export const RulesEvaluatorWorker = (221 loader: LoaderBinding,222 options: WorkerOptions = {}223) =>224 Layer.effect(225 RulesEvaluator,226 Effect.gen(function* () {227 const finishers = yield* Finishers;228 const compatibilityDate = options.compatibilityDate ?? "2026-10-05";229 const cpuMs = options.cpuMs ?? 200;230 const timeoutMs = options.timeoutMs ?? 5000;231232 /**Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
lines 233–234why, one step back233 * The Loader asks for it only for an id it doesn't hold, so a warm234 * request builds none.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 235–246why, one step back235 */236 const codeOf = (bundle: ConfigBundle, clock: FrozenFacts): LoaderCode => {237 const modules: Record<string, LoaderModule> = {};238239 for (const [path, source] of Object.entries(bundle.modules)) {240 modules[path] = moduleOf(path, source);241 }242243 modules[mainName] = {244 js: mainModule({245 asks: askModules(bundle),246 project: projectModule(bundle),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 247why, one step back247 visibility: visibilityModule(bundle),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 248–336why, one step back248 }),249 };250251 modules[preludeName] = { js: preludeModule(clock) };252253 return {254 compatibilityDate,255 globalOutbound: null,256 limits: { cpuMs, subRequests: 0 },257 mainModule: mainName,258 modules,259 };260 };261262 const run = (263 bundle: ConfigBundle,264 at: string,265 clock: FrozenFacts,266 job: Job267 ): Effect.Effect<Output, RulesFailed> =>268 Effect.andThen(269 insideTheFolder(bundle),270 Effect.acquireUseRelease(271 Effect.try({272 catch: (cause) =>273 loadFailed(`the Worker Loader: ${messageOf(cause)}`),274 try: () =>275 loader.get(workerIdOf(bundle, at, clock), () =>276 codeOf(bundle, clock)277 ),278 }),279 (worker) =>280 Effect.acquireUseRelease(281 Effect.try({282 catch: (cause) =>283 loadFailed(`the loaded worker: ${messageOf(cause)}`),284 try: () => worker.getEntrypoint(),285 }),286 (entrypoint) => requested(entrypoint, job),287 released288 ),289 released290 )291 ).pipe(292 Effect.timeoutOrElse({293 duration: timeoutMs,294 orElse: () =>295 Effect.fail(296 new RulesFailed({297 detail: `the config folder ran past its ${timeoutMs} ms limit`,298 reason: "timeout",299 })300 ),301 })302 );303304 return RulesEvaluator.of({305 call: (input) => {306 const { at, modules, rule } = input;307 const project = projectModule(modules);308309 if (project === undefined) {310 return Effect.succeed(false);311 }312313 return factsOf(input).pipe(314 Effect.flatMap((facts) => run(modules, at, epoch, { facts, rule })),315 Effect.flatMap(316 Output.match({317 Called: ({ result }) =>318 Schema.decodeUnknownEffect(Schema.Boolean)(result).pipe(319 Effect.mapError(320 (failure) =>321 new RulesFailed({322 detail: `${project}: ${rule} gave ${failure.message}`,323 reason: "decode",324 })325 )326 ),327 Collected: (output) => Effect.fail(surprised(output)),328 Failed: (output) => Effect.fail(fromFailed(output)),329 })330 )331 );332 },333 evaluate: ({ at, facts, modules }) =>334 Effect.gen(function* () {335 const project = projectModule(modules);336 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 337why, one step back337 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 338–351why, one step back338339 const clock: FrozenFacts = {340 now: DateTime.toEpochMillis(facts.now),341 seed: facts.seed,342 };343344 // Without a project module, `policy.json` (or the defaults) is345 // the base the ask files join; with one, it is never read.346 const fallback =347 project === undefined348 ? yield* statedWithoutCode(modules)349 : defaultPolicyInput;350351 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 352–354why, one step back352 project === undefined &&353 asks.length === 0 &&354 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 355–365why, one step back355 ? fallback356 : yield* run(modules, at, clock, {}).pipe(357 Effect.flatMap(358 Output.match({359 Called: (output) => Effect.fail(surprised(output)),360 Collected: (collected) =>361 fromCollected({362 collected,363 entry: project ?? modules.entry,364 fallback,365 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 366why, one step back366 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 367–377why, one step back367 }),368 Failed: (output) => Effect.fail(fromFailed(output)),369 })370 )371 );372373 return yield* finishPolicy({ at, facts, finishers, policy });374 }),375 });376 })377 );