Skip to content

Commit b318c32

Browse files
committed
✨ feat: give every component invocation its own resource scope
Component invocations had no resource lifetime of their own. Each one created an eval scope via `parentEvalScope.eval(() => useEvalScope())`, which parents the child to the *parent's* loop task, and `EvalScope` exposes no way to destroy it — so nothing was ever halted. Daemons and `persist eval` resources lived until the document ended, and the spec rows that said otherwise (L3, Q5, S7) were unimplemented and untested: every lifetime test asserted only "execute completed without hanging". An invocation now creates its eval scope on its own expansion frame and runs its body inside a task that scope owns, which collapses the engine's two parallel context chains into one. Leaving it runs a single destructor with three ordered stages — halt the content scope, halt the body, halt the invocation scope — each finishing before the next, all three attempted even when one fails, on success, error and cancellation alike. `FunctionComponent` now returns `ComponentExecution<string>` (an `Operation`) rather than `Workflow`. A `.ts` component's only bridge to Effection was `ephemeral()`, whose task settles on return and destroys what it acquired — before teardown could stop projected content. The widening is backward compatible and matches what the spec always declared, so a component holds resources for its children with no wrapper: export default function*() { const directory = yield* useTempDir(); return yield* useContent(); } Reporting an error and settling it are now separate: the `Component.raise` middleware chain observes each segment once, and its default implementation settles under `AmbientErrorPolicy`, which documentation and `<Output>` set as a value. A persistent evaluation carries its source block's policy in a per-evaluation `env` facade, since it runs on a loop task that predates it. `<Test>` composes the shared boundary instead of its own private lease.
1 parent f2bf78e commit b318c32

23 files changed

Lines changed: 1336 additions & 200 deletions

‎packages/core/mod.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
*/
88

99
export type {
10+
ComponentExecution,
11+
FunctionComponent,
12+
FunctionComponentDefinition,
1013
Segment,
1114
TextSegment,
1215
ComponentElement,
@@ -66,6 +69,8 @@ export type { EvalEnv } from "./src/types.ts";
6669
export { compileBlock } from "./src/eval-context.ts";
6770

6871
export { useContent } from "./src/content-context.ts";
72+
export { InvocationTeardownError, withInvocation } from "./src/invocation.ts";
73+
export type { Invocation } from "./src/invocation.ts";
6974
export { Sample } from "./src/sample-api.ts";
7075

7176
export { evalFactory } from "./src/eval-handler.ts";

‎packages/core/src/component-api.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { type Api, createApi, type Operations } from "@effectionx/context-api";
1717
import { createContext } from "effection";
1818
import type { Context, Operation } from "effection";
1919
import type { EvalScope } from "@effectionx/scope-eval";
20+
import { settle } from "./errors.ts";
2021
import type {
2122
CodeBlockContext,
2223
CodeBlockResult,
@@ -49,9 +50,12 @@ export interface ComponentApi {
4950
importComponent(name: string): Operation<ComponentDefinition | FunctionComponentDefinition>;
5051
applyModifiers(modifiers: Modifier[], block: CodeBlockContext): Operation<CodeBlockResult>;
5152
/**
52-
* Report an ErrorSegment under the ambient error policy. The default
53-
* returns the segment for rendering; suppressed-documentation scopes
54-
* install middleware that throws instead (spec §6.9).
53+
* Report an ErrorSegment under the ambient error policy (spec §6.9).
54+
*
55+
* The middleware chain is the observation chain — a segment passes through it
56+
* once, where it is created. The default implementation settles it under
57+
* `AmbientErrorPolicy`: collected for rendering, or thrown inside
58+
* suppressed documentation.
5559
*/
5660
raise(error: ErrorSegment): Operation<ErrorSegment>;
5761
env: EvalEnv | undefined;
@@ -97,9 +101,8 @@ export const Component: Api<ComponentApi> = createApi<ComponentApi>("Component",
97101
`with Component.around({ applyModifiers }, { at: "min" }) before expansion.`,
98102
);
99103
},
100-
// deno-lint-ignore require-yield
101104
*raise(error: ErrorSegment): Operation<ErrorSegment> {
102-
return error;
105+
return yield* settle(error);
103106
},
104107
env: undefined,
105108
evalScope: undefined,

‎packages/core/src/data-uri-compiler.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ const STANDARD_IMPORTS = [
2929
'import { sleep, spawn, call, resource, useScope, createChannel, each, suspend, createSignal } from "effection";',
3030
'import { when } from "@effectionx/converge";',
3131
'import { fetch } from "@effectionx/fetch";',
32-
'import { useContent, Sample } from "@executablemd/core";',
32+
'import { Sample } from "@executablemd/core";',
3333
'import { findFreePort } from "@executablemd/runtime";',
3434
];
3535

‎packages/core/src/errors.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,37 @@
1+
import { createContext } from "effection";
2+
import type { Context, Operation } from "effection";
13
import type { ErrorSegment } from "./types.ts";
24

35
/**
4-
* Thrown by suppressed-documentation raise middleware (spec §6.9). Generic
6+
* How an ErrorSegment settles once it has been reported (spec §6.9).
7+
*
8+
* `Component.raise` is the observation chain — every segment passes through it
9+
* exactly once, where it is created. Settlement is this separate value, so an
10+
* error crossing from a component's own policy to its caller's does not emit a
11+
* second observation.
12+
*/
13+
export type ErrorPolicy = "collect" | "throw";
14+
15+
export const AmbientErrorPolicy: Context<ErrorPolicy> = createContext<ErrorPolicy>(
16+
"component.errorPolicy",
17+
"collect",
18+
);
19+
20+
/**
21+
* Settle a segment under the ambient policy: the default `Component.raise`
22+
* implementation calls this, and so does a consumer applying its own policy to
23+
* an error that already crossed a nested one.
24+
*/
25+
export function* settle(segment: ErrorSegment): Operation<ErrorSegment> {
26+
const policy = yield* AmbientErrorPolicy.get();
27+
if (policy === "throw") {
28+
throw new DocumentationError(segment);
29+
}
30+
return segment;
31+
}
32+
33+
/**
34+
* Thrown by suppressed-documentation settlement (spec §6.9). Generic
535
* catches in the engine rethrow it instead of converting it into an
636
* ErrorSegment, so documentation fail-fast is never swallowed.
737
*/

‎packages/core/src/eval-env.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* The binding environment one eval block sees (spec §4.3).
3+
*
4+
* Blocks share one bindings record — that is what lets a later block read what
5+
* an earlier one exported. But `renderChildren`, `render` and `useContent`
6+
* project content, and a projection settles its errors under the policy of the
7+
* block that started it, which differs per block. A `persist eval` block runs
8+
* on the invocation's eval-scope loop task, created long before that policy
9+
* existed, so the policy cannot come from the surrounding context.
10+
*
11+
* Each evaluation therefore gets its own facade over the shared record: the
12+
* three projecting bindings are bound to that evaluation's policy, everything
13+
* else reads and writes straight through. Nothing is swapped and nothing is
14+
* restored, so concurrent evaluations cannot race and work that outlives its
15+
* block keeps calling the closures it was given.
16+
*/
17+
18+
import type { ErrorPolicy } from "./errors.ts";
19+
20+
/**
21+
* Bindings the facade re-binds per evaluation. The shared record holds the
22+
* invocation's own versions, which carry no policy.
23+
*/
24+
const PROJECTING = ["renderChildren", "render", "useContent"];
25+
26+
/** A projection binding as it is injected into the shared record. */
27+
type Projector = (argument?: unknown, policy?: ErrorPolicy) => unknown;
28+
29+
function isProjector(value: unknown): value is Projector {
30+
return typeof value === "function";
31+
}
32+
33+
/**
34+
* Wrap `values` for one evaluation, binding the projecting operations to
35+
* `policy`. Reads of anything else, and every write, delete and enumeration,
36+
* reach the shared record — `serializeExports` and the transform's
37+
* `Object.keys` see exactly what they saw before.
38+
*/
39+
export function evaluationEnv(
40+
values: Record<string, unknown>,
41+
policy: ErrorPolicy,
42+
): Record<string, unknown> {
43+
const bound = new Map<string, unknown>();
44+
45+
return new Proxy(values, {
46+
get(target, key) {
47+
if (typeof key !== "string" || !PROJECTING.includes(key)) {
48+
return Reflect.get(target, key);
49+
}
50+
const existing = bound.get(key);
51+
if (existing) {
52+
return existing;
53+
}
54+
const projector = Reflect.get(target, key);
55+
if (!isProjector(projector)) {
56+
return projector;
57+
}
58+
const wrapper = (argument?: unknown) => projector(argument, policy);
59+
bound.set(key, wrapper);
60+
return wrapper;
61+
},
62+
set(target, key, value) {
63+
return Reflect.set(target, key, value);
64+
},
65+
deleteProperty(target, key) {
66+
return Reflect.deleteProperty(target, key);
67+
},
68+
has(target, key) {
69+
return Reflect.has(target, key);
70+
},
71+
ownKeys(target) {
72+
return Reflect.ownKeys(target);
73+
},
74+
getOwnPropertyDescriptor(target, key) {
75+
return Reflect.getOwnPropertyDescriptor(target, key);
76+
},
77+
});
78+
}

‎packages/core/src/eval-handler.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import type { Operation } from "effection";
55
import type { ModifierFactory } from "./modifiers.ts";
66
import { useCodeBlock } from "./modifiers.ts";
77
import { env, evalScope, persistent } from "./component-api.ts";
8+
import { AmbientErrorPolicy } from "./errors.ts";
9+
import { evaluationEnv } from "./eval-env.ts";
810
import { compileBlock } from "./eval-context.ts";
911
import { transformBlock, serializeExports } from "./eval-transform.ts";
1012

@@ -18,6 +20,10 @@ export const evalFactory: ModifierFactory = (_params) => (_args, _next) =>
1820
);
1921
}
2022
const persist = yield* ephemeral(persistent);
23+
// Captured here, on the expansion frame, where the block's documentation or
24+
// <Output> policy is ambient. A persist block runs on the invocation's
25+
// eval-scope loop task, which predates that policy and cannot inherit it.
26+
const policy = (yield* ephemeral(AmbientErrorPolicy.get())) ?? "collect";
2127

2228
// Inject output() function into env so eval blocks can produce
2329
// rendered output. The function is a plain synchronous call:
@@ -45,6 +51,10 @@ export const evalFactory: ModifierFactory = (_params) => (_args, _next) =>
4551
Object.assign(evalEnv.values, bindings);
4652

4753
const fn = yield* compileBlock(transformed.code, transformed.userImports ?? []);
54+
// One facade per evaluation over the shared bindings: the projecting
55+
// operations carry this block's policy, everything else — including
56+
// export write-back — reaches the same record.
57+
const blockEnv = evaluationEnv(evalEnv.values, policy);
4858

4959
if (persist) {
5060
// Persist mode: run the compiled block inside the eval scope
@@ -55,15 +65,15 @@ export const evalFactory: ModifierFactory = (_params) => (_args, _next) =>
5565
`persist eval block "${ctx.blockId}" requires a component eval scope; none is in scope.`,
5666
);
5767
}
58-
const blockResult = yield* scope.eval(() => fn(evalEnv.values));
68+
const blockResult = yield* scope.eval(() => fn(blockEnv));
5969
const returnValue = unbox(blockResult);
6070
if (!outputRef.text && returnValue != null) {
6171
outputRef.text = String(returnValue);
6272
}
6373
} else {
6474
// Normal mode: run the compiled block in the current scope.
6575
// Resources are torn down when this operation completes.
66-
const returnValue = yield* fn(evalEnv.values);
76+
const returnValue = yield* fn(blockEnv);
6777
if (!outputRef.text && returnValue != null) {
6878
outputRef.text = String(returnValue);
6979
}

‎packages/core/src/eval-transform.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,12 @@ export function transformBlock(
115115
// 3. Collect exports from top-level declarations
116116
const exports = collectExports(ast);
117117

118-
// 4. Collect imports — free variables present in env
118+
// 4. Collect imports — free variables present in env.
119+
// A name the block imports is already declared in the generated module, so
120+
// it must never also be destructured from env: that would be a redeclaration.
121+
// An explicit import therefore deliberately shadows the injected binding.
119122
const envKeySet = new Set(currentEnvKeys);
120-
const declaredNames = new Set(exports);
123+
const declaredNames = new Set([...exports, ...collectImportedNames(importNodes)]);
121124
const freeVars = collectFreeVariables(ast, declaredNames);
122125
const imports = freeVars.filter((name) => envKeySet.has(name));
123126

@@ -339,6 +342,24 @@ function extractPatternNames(pattern: AstNode): string[] {
339342
* and is not declared within the block itself. Only names that are in
340343
* the current env keys set will be injected as imports.
341344
*/
345+
/** Local names an import declaration binds — default, named and namespace. */
346+
function collectImportedNames(importNodes: AstNode[]): string[] {
347+
const names: string[] = [];
348+
for (const node of importNodes) {
349+
const specifiers = node.specifiers;
350+
if (!Array.isArray(specifiers)) {
351+
continue;
352+
}
353+
for (const specifier of specifiers) {
354+
const local = specifier.local;
355+
if (local && typeof local.name === "string") {
356+
names.push(local.name);
357+
}
358+
}
359+
}
360+
return names;
361+
}
362+
342363
function collectFreeVariables(ast: AstNode, declaredNames: Set<string>): string[] {
343364
const references = new Set<string>();
344365
const localDecls = new Set(declaredNames);

0 commit comments

Comments
 (0)