Skip to content

Commit 7d7bdf2

Browse files
authored
Merge pull request #325 from taras/feat/operation-scoped-state
💥 Scope engine state to the operation that owns it
2 parents f413545 + 5ff50bb commit 7d7bdf2

28 files changed

Lines changed: 979 additions & 200 deletions

‎.oxlintrc.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
"typescript/no-redundant-type-constituents": "warn",
4343
"typescript/no-unnecessary-boolean-literal-compare": "warn",
4444

45+
"local/no-module-scoped-registry": "error",
4546
"local/no-section-divider-comments": "error",
4647
"local/no-yield-in-finally": "error",
4748
"local/prefer-effection-result": "error"

‎packages/cli/tests/props-schema.test.ts‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
*/
99
import { describe, it } from "@executablemd/test-support/bdd";
1010
import { expect } from "@executablemd/test-support/expect";
11+
import type { Operation } from "effection";
1112
import { validateProps } from "@executablemd/core";
1213
import type { PropsSchema } from "@executablemd/core";
1314
import { z } from "zod";
@@ -57,6 +58,16 @@ const SCALARS: PropsSchema = {
5758
additionalProperties: false,
5859
};
5960

61+
/** The failure an operation raised, so an assertion can read it. */
62+
function* raised(operation: () => Operation<unknown>): Operation<unknown> {
63+
try {
64+
yield* operation();
65+
} catch (error) {
66+
return error;
67+
}
68+
throw new Error("expected the operation to fail");
69+
}
70+
6071
describe("Tier PS — JSON Schema to Standard Schema", () => {
6172
it("PS1: converts every scalar form the contract names", function* () {
6273
const shape = shapeOf(SCALARS);
@@ -108,8 +119,10 @@ describe("Tier PS — JSON Schema to Standard Schema", () => {
108119
required: ["a"],
109120
additionalProperties: false,
110121
};
111-
expect(() => validateProps("x", {}, schema)).toThrow(/required property 'a'/);
112-
expect(validateProps("x", { a: "1" }, schema)).toEqual({ a: "1" });
122+
expect(String(yield* raised(() => validateProps("x", {}, schema)))).toMatch(
123+
/required property 'a'/,
124+
);
125+
expect(yield* validateProps("x", { a: "1" }, schema)).toEqual({ a: "1" });
113126
});
114127

115128
it("PS4: local references resolve — draft-7 uses definitions", function* () {
@@ -122,7 +135,7 @@ describe("Tier PS — JSON Schema to Standard Schema", () => {
122135
};
123136
const shape = shapeOf(schema);
124137
expect(shape.user.safeParse({ name: "Ada" }).success).toBe(true);
125-
expect(validateProps("x", { user: { name: "Ada" } }, schema)).toEqual({
138+
expect(yield* validateProps("x", { user: { name: "Ada" } }, schema)).toEqual({
126139
user: { name: "Ada" },
127140
});
128141
});
@@ -135,7 +148,7 @@ describe("Tier PS — JSON Schema to Standard Schema", () => {
135148
};
136149
expect(() => shapeOf(schema, "draft-7")).toThrow(/Reference not found/);
137150
expect(shapeOf(schema, "draft-2020-12").user.safeParse({ name: "Ada" }).success).toBe(true);
138-
expect(validateProps("x", { user: { name: "Ada" } }, schema)).toEqual({
151+
expect(yield* validateProps("x", { user: { name: "Ada" } }, schema)).toEqual({
139152
user: { name: "Ada" },
140153
});
141154
});
@@ -159,7 +172,7 @@ describe("Tier PS — JSON Schema to Standard Schema", () => {
159172
data: { name: "Ada", role: "member" },
160173
});
161174
// ...whereas Ajv is the layer entitled to do so.
162-
expect(validateProps("x", { user: { name: "Ada" } }, schema)).toEqual({
175+
expect(yield* validateProps("x", { user: { name: "Ada" } }, schema)).toEqual({
163176
user: { name: "Ada", role: "member" },
164177
});
165178
});
@@ -171,8 +184,8 @@ describe("Tier PS — JSON Schema to Standard Schema", () => {
171184
success: true,
172185
data: { a: "x", extra: 1 },
173186
});
174-
expect(() => validateProps("x", { closed: { a: "y", extra: 1 } }, SCALARS)).toThrow(
175-
/must NOT have additional properties/,
176-
);
187+
expect(
188+
String(yield* raised(() => validateProps("x", { closed: { a: "y", extra: 1 } }, SCALARS))),
189+
).toMatch(/must NOT have additional properties/);
177190
});
178191
});

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

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,28 @@ import type { ComponentFailure, ErrorSegment, FunctionComponent } from "./types.
1919
import type { Operation } from "effection";
2020

2121
/**
22-
* Components that continue after failing, remembered by function identity.
22+
* The declaration a component wears to say it continues after failing.
2323
*
24-
* Identity rather than name: a repository component that happens to share a
25-
* registered component's name is a different function and inherits nothing.
24+
* This is the one thing about a component that is not run state. `printErrors(fn)`
25+
* runs while a component module is evaluated — outside any operation, with no run
26+
* to own a table and no scope to reach — and what it records is what an author
27+
* declared about a function the author owns. So it lives on that function, which
28+
* is where its lifetime already is.
29+
*
30+
* Module-private rather than `Symbol.for`, so nothing outside this module can
31+
* forge the declaration, and non-enumerable, so a component that is copied,
32+
* wrapped, or inspected does not carry it along by accident. Identity is what
33+
* carries it either way: a repository component that happens to share a
34+
* registered component's name is a different function object and inherits
35+
* nothing.
2636
*/
27-
const printing = new WeakSet<FunctionComponent>();
37+
const PRINTS_ERRORS = Symbol("executablemd.core.printsErrors");
2838

2939
/**
3040
* Continue after this component fails, reporting the failure as a printed error.
3141
*
32-
* The component is returned unchanged — marking is membership, not wrapping —
33-
* so its identity and type survive:
42+
* The component is returned unchanged — declaring is marking, not wrapping — so
43+
* its identity and type survive:
3444
*
3545
* ```ts
3646
* export default printErrors(function* (props) {
@@ -43,12 +53,12 @@ const printing = new WeakSet<FunctionComponent>();
4353
* projects is inside it.
4454
*/
4555
export function printErrors<T extends FunctionComponent>(component: T): T {
46-
printing.add(component);
56+
Object.defineProperty(component, PRINTS_ERRORS, { value: true, enumerable: false });
4757
return component;
4858
}
4959

5060
export function printsErrors(component: FunctionComponent): boolean {
51-
return printing.has(component);
61+
return Object.hasOwn(component, PRINTS_ERRORS);
5262
}
5363

5464
/**
@@ -80,7 +90,7 @@ export function* usePrintErrors(): Operation<void> {
8090
message: `Function component ${failure.name} error: ${failure.error.message}`,
8191
source: failure.name,
8292
};
83-
attributeCause(segment, failure.error);
93+
yield* attributeCause(segment, failure.error);
8494
return yield* raise(segment);
8595
},
8696
});

‎packages/core/src/components/Elicit.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export const props = {
7171
export const returns = { $schema: "http://json-schema.org/draft-07/schema#" };
7272

7373
export default function* Elicit(props: Record<string, Json>): Operation<Json> {
74-
const prepared = prepareElicitation(props.schema);
74+
const prepared = yield* prepareElicitation(props.schema);
7575

7676
const message = yield* content();
7777

‎packages/core/src/components/Parse.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ export const props = {
4444
export const returns = { $schema: "http://json-schema.org/draft-07/schema#" };
4545

4646
export default printErrors(function* (props: Record<string, Json>): Operation<Json> {
47-
const validate = compileParseSchema("Parse", props.schema);
47+
const validate = yield* compileParseSchema("Parse", props.schema);
4848

4949
const text = yield* content();
5050

‎packages/core/src/components/SafeParse.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export const returns = {
7171
};
7272

7373
export default printErrors(function* (props: Record<string, Json>): Operation<Json> {
74-
const validate = compileParseSchema("SafeParse", props.schema);
74+
const validate = yield* compileParseSchema("SafeParse", props.schema);
7575

7676
const text = yield* content();
7777

‎packages/core/src/components/parse-schema.ts‎

Lines changed: 42 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,23 +12,46 @@
1212

1313
import { Ajv } from "ajv";
1414
import type { ValidateFunction } from "ajv";
15-
import { Err, Ok } from "effection";
16-
import type { Result } from "effection";
15+
import { createContext, Err, Ok } from "effection";
16+
import type { Context, Operation, Result } from "effection";
1717
import { SchemaValidationError, normalizeIssues } from "../validate.ts";
1818
import type { NormalizedIssue } from "../validate.ts";
1919
import { parseJson, parseJsonObject } from "../json.ts";
2020
import type { Json, JsonObject } from "../types.ts";
2121

22-
const ajv = new Ajv({
23-
strict: true,
24-
allErrors: true,
25-
validateSchema: true,
26-
useDefaults: false,
27-
coerceTypes: false,
28-
removeAdditional: false,
29-
addUsedSchema: false,
30-
validateFormats: false,
31-
});
22+
function createParseCompiler(): Ajv {
23+
return new Ajv({
24+
strict: true,
25+
allErrors: true,
26+
validateSchema: true,
27+
useDefaults: false,
28+
coerceTypes: false,
29+
removeAdditional: false,
30+
addUsedSchema: false,
31+
validateFormats: false,
32+
});
33+
}
34+
35+
/**
36+
* The compiler one execution parses with.
37+
*
38+
* Scoped for the same reason the props compiler is (see `validate.ts`): Ajv
39+
* remembers every compile in a `Map` keyed by the schema object, so an instance
40+
* that outlived a run would accumulate a run's worth of schemas per run and
41+
* answer a mutated schema object with the previous run's validator. A document
42+
* brings fresh schema objects every time.
43+
*/
44+
const ParseCompiler: Context<Ajv | undefined> = createContext<Ajv | undefined>(
45+
"component.parseCompiler",
46+
undefined,
47+
);
48+
49+
/** Open the parse compiler for one execution. */
50+
export function* useParseCompiler(): Operation<Ajv> {
51+
const compiler = createParseCompiler();
52+
yield* ParseCompiler.set(compiler);
53+
return compiler;
54+
}
3255

3356
/** A schema that could not be read or compiled. Raised before any child runs. */
3457
export class ParseSchemaError extends Error {
@@ -65,8 +88,14 @@ function headline(componentName: string, issues: NormalizedIssue[]): string {
6588
* draft-07 compilation, so a document can hold its schema in a code fence or in
6689
* a binding and get identical behavior.
6790
*/
68-
export function compileParseSchema(componentName: string, schema: Json): ValidateFunction {
91+
export function* compileParseSchema(
92+
componentName: string,
93+
schema: Json,
94+
): Operation<ValidateFunction> {
6995
const declaration = readSchema(componentName, schema);
96+
// Without a run there is nothing to reclaim: the compiler lives exactly as
97+
// long as this call.
98+
const ajv = (yield* ParseCompiler.get()) ?? createParseCompiler();
7099

71100
// Ajv does not reject an async schema — it compiles a validator that returns
72101
// a promise. Reject it before and after compiling so validation stays

‎packages/core/src/components/registration.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,9 @@ export function* registerComponents(
201201
`the registration for "${name}" needs an origin naming where it came from`,
202202
);
203203
}
204-
compilePropsSchema(props);
204+
yield* compilePropsSchema(props);
205205
if (returns !== undefined) {
206-
compileReturnsSchema(returns);
206+
yield* compileReturnsSchema(returns);
207207
}
208208
assertUsableCaptures(name, registration.captures, props);
209209

‎packages/core/src/definition.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { Operation } from "effection";
12
import type { ComponentDefinition } from "./types.ts";
23
import { parseFrontmatter } from "./frontmatter.ts";
34
import { compilePropsSchema, compileReturnsSchema } from "./validate.ts";
@@ -20,16 +21,16 @@ export function isFunctionComponentPath(path: string): boolean {
2021
* drift: both compile the props and return schemas, so a malformed schema
2122
* fails the same way whether the document runs or is only described.
2223
*/
23-
export function parseMarkdownDefinition(
24+
export function* parseMarkdownDefinition(
2425
name: string,
2526
path: string,
2627
content: string,
27-
): ComponentDefinition {
28+
): Operation<ComponentDefinition> {
2829
const parsed = matter(content);
2930
const { meta, props, returns } = parseFrontmatter(parsed.data);
30-
compilePropsSchema(props);
31+
yield* compilePropsSchema(props);
3132
if (returns !== undefined) {
32-
compileReturnsSchema(returns);
33+
yield* compileReturnsSchema(returns);
3334
}
3435
// The markdown body is a verbatim suffix of the raw file, so the body start
3536
// is computed by length — never by content search, which could false-match

‎packages/core/src/elicit.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,16 +62,16 @@ export interface PreparedElicitation {
6262
* Synchronous and effect-free: it either produces a question that can be asked
6363
* or throws, and a caller that has not yet begun anything can still stop.
6464
*/
65-
export function prepareElicitation(
65+
export function* prepareElicitation(
6666
schema: Json,
6767
label: string = DEFAULT_LABEL,
68-
): PreparedElicitation {
68+
): Operation<PreparedElicitation> {
6969
const declaration = readParseSchema(label, schema);
7070

7171
refuseUnsupportedNames(label, declaration);
7272
refuseExternalReferences(label, declaration);
7373

74-
return { schema: declaration, validate: compileParseSchema(label, declaration), label };
74+
return { schema: declaration, validate: yield* compileParseSchema(label, declaration), label };
7575
}
7676

7777
/** Ask the configured provider, and judge what it returns. */
@@ -94,12 +94,15 @@ export function* runPreparedElicitation(
9494
}
9595

9696
/** Compile and ask in one step, for a host with no ordering of its own. */
97-
export function elicit(request: {
97+
export function* elicit(request: {
9898
message: string;
9999
schema: Json;
100100
label?: string;
101101
}): Operation<Json> {
102-
return runPreparedElicitation(prepareElicitation(request.schema, request.label), request.message);
102+
return yield* runPreparedElicitation(
103+
yield* prepareElicitation(request.schema, request.label),
104+
request.message,
105+
);
103106
}
104107

105108
/**

0 commit comments

Comments
 (0)