diff --git a/.changeset/conformance-rule-defect-outcome.md b/.changeset/conformance-rule-defect-outcome.md index 899f6b08..bd0f97ba 100644 --- a/.changeset/conformance-rule-defect-outcome.md +++ b/.changeset/conformance-rule-defect-outcome.md @@ -2,10 +2,10 @@ "@thomasfosterau/effect-jsonapi": minor --- -A `Conformance` rule that dies no longer loses the whole report. In 0.16.3 a defect in any one rule (a transport that throws, or a bug in the kit) failed `Conformance.verify` / `verifyWith` outright, so every other rule's outcome — and, with this release's write fixture, the `Report.writes` ledger of what the kit created and whether it was removed — went unreported. The rule now gets a new `Errored` outcome (`Conformance.Outcome` gains a fourth member, `{ _tag: "Errored", rule, message, defect }`), every other rule still runs and is reported in the suite's order, and `Report.writes` is still filled. That holds whether the rule dies inside its Effect or throws before returning one. Interruption is not turned into an outcome: it still stops the run. A write fixture that throws is not a defect and never was: a `create` or `update` that throws skips the rules it would have driven, and a `cleanup` that fails or throws is recorded in `Report.writes` as `cleanup-failed`. +A `Conformance` rule that dies no longer loses the whole report. In 0.16.3 a defect in any one rule (a transport that throws, or a bug in the kit) failed `Conformance.verify` / `verifyWith` outright, so every other rule's outcome — and, with this release's write fixture, the `Report.writes` ledger of what the kit created and whether it was removed — went unreported. The rule now gets a new `Errored` outcome (`Conformance.Outcome` gains a fourth member, `{ _tag: "Errored", rule, message, defect }`), every other rule still runs and is reported in the suite's order, and `Report.writes` is still filled. That holds whether the rule dies inside its Effect or throws before returning one. Interruption is not turned into an outcome: it still stops the run. A write fixture that throws a value the kit can render is not a defect: a `create` or `update` that throws one skips the rules it would have driven, and a `cleanup` that fails with or throws one is recorded in `Report.writes` as `cleanup-failed`. One that throws a value the kit can't render (a revoked `Proxy`, say) is still reported as `Errored` until #271. **Behaviour change:** before, a dying rule failed the whole run; now the run succeeds with an `Errored` outcome, so a caller who gates on `summarise(report).failed`, `findings(report)` or `_tag === "Failed"` passes silently. If you gate on `failed`/`findings` rather than `Conformance.assert`, also check `summarise(report).errored === 0`. -`format` prints such a rule first in its tier, marked `DIED` with the defect's message (an `Error` as `Name: message`, any other thrown value as itself), and adds `· N died` to the tier and summary lines when one did (a run in which nothing died prints as before); `summarise` gains an `errored` count. `assert` dies on the first `Errored` outcome — with a defect tagged `RuleDied` (match it with `Predicate.isTagged(defect, "RuleDied")`) carrying the rule's id, a message naming the rule and the defect, and the original defect as its `cause` — before looking at failures, so the gate stays as strict as when the defect killed the run. +`format` prints such a rule first in its tier, marked `DIED` with the defect's message (an `Error` as `Name: message`, any other thrown value as itself; capped at 500 UTF-16 code units, a longer one ending in `…`; and `[unrenderable defect]` for a value that throws when inspected — a revoked `Proxy`, say — which still leaves the run complete), and adds `· N died` to the tier and summary lines when one did (a run in which nothing died prints as before); `summarise` gains an `errored` count. `assert` dies on the first `Errored` outcome — with a defect tagged `RuleDied` (match it with `Predicate.isTagged(defect, "RuleDied")`) carrying the rule's id, a message naming the rule and the defect, and the original defect as its `cause` — before looking at failures, so the gate stays as strict as when the defect killed the run. A `switch` over `Outcome._tag` that relies on exhaustiveness needs an `Errored` case. diff --git a/README.md b/README.md index 25dc0e2f..1eaba122 100644 --- a/README.md +++ b/README.md @@ -1926,7 +1926,7 @@ Two tiers, separately runnable. `spec` is JSON:API v1.1 alone; `profile` is this **It says what it did not check.** Every rule that could not run reports why — no endpoint of that shape, no sample id, no write fixture, a mutating probe not opted into — and `Conformance.gaps` declares the areas the kit does not cover at all (filter _evaluation_ semantics, pagination-link and sort-ordering correctness, the write rules beyond the success responses, atomic processing), each with its reason and tracking issue. Both are printed in every report, and skips are counted separately from passes, so a run that proved little cannot read as a clean bill of health. -**A rule that dies does not cost you the report.** A defect in one rule — a transport that throws, or a bug in the kit — becomes that rule's `Errored` outcome (printed as `DIED`, with the defect's message, and counted as `errored` by `Conformance.summarise`); every other rule still runs and is reported, and so is `report.writes`. Interruption is not caught: it still stops the run, after the cleanup of whatever the interrupted rule created. A write fixture that throws is not a defect: a `create` or `update` that throws skips the rules it would have driven, and a `cleanup` that fails is recorded in `report.writes`. +**A rule that dies does not cost you the report.** A defect in one rule — a transport that throws, or a bug in the kit — becomes that rule's `Errored` outcome (printed as `DIED`, with the defect's message, and counted as `errored` by `Conformance.summarise`); every other rule still runs and is reported, and so is `report.writes`. Interruption is not caught: it still stops the run, after the cleanup of whatever the interrupted rule created. A write fixture that throws a value the kit can render is not a defect: a `create` or `update` that throws one skips the rules it would have driven, and a `cleanup` that fails with one is recorded in `report.writes`. One that throws a value the kit can't render (a revoked `Proxy`, say) is still reported as `Errored` until [#271](https://github.com/thomasfosterau/effect-jsonapi/issues/271). Use `Conformance.assert(report)` as a gate: it fails with a `ContractViolation` carrying the rule, its requirement, its citation and the request that decided it. A rule that died is not a finding about your server, but the run could not decide it either, so `assert` dies on it — with a defect tagged `RuleDied` naming the rule and the defect, the original as its `cause` — rather than passing. If you gate on `summarise(report).failed` or `findings(report)` instead of `assert`, also check `summarise(report).errored === 0`. diff --git a/docs/conformance.md b/docs/conformance.md index 65ba413f..bcab834f 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -93,7 +93,7 @@ Conformance.verify(api, { What the kit promises in return: - **It refuses an id it evidently did not create.** Every write rule creates its own disposable target from `create` — the update rule PATCHes it, the delete rule DELETEs it — and acts on the id the server's create response named only after checking it: the response must name a resource of the type `create` returned (`data.type`, or `atomic:results[0].data.type` for an `add`), under an id that is a URL path segment of its own (not `""`, `.` or `..`, which `encodeURIComponent` leaves alone and URL normalisation turns into the collection or `/`, nor a lone surrogate, which no URL can carry), that is not an `ids` sample, that no successful `GET` earlier in the run returned (as primary data, in `included`, or as a relationship's linkage) unless the kit had already taken it from a create of its own, and that the run does not already hold a resource for that has not been removed (two live resources cannot share an id, so one of the two answers is wrong). Any other id is recorded as `left`, with `detail` naming what was named — "named `people:1`, which the kit did not create … — not touched" — and is never PATCHed, DELETEd or handed to `cleanup`; the rules that would have acted on it skip, saying so. An id the server hands out again once the kit has removed its first holder — a `size + 1` store, a SQLite rowid — is accepted, because refusing it would leave every later resource behind. (Before the fixture, `mutating: true` made the delete rule delete the `ids` sample.) Every rule that creates nothing (the profile tier's included) runs before the first rule that creates, so a create is checked against everything the run reads; the report keeps the suite's order. The read check can refuse falsely: linkage can name a resource since deleted, and a server that reuses ids may hand that id to the kit's create. That fails safe — the resource is recorded as `left` with a `detail` saying why, and the rules that would have acted on it skip. -- **Cleanup runs however the rule ends.** Each target is created inside `Effect.acquireUseRelease`, so `cleanup` runs after the rule that made it whether that rule passed, failed or died. A cleanup that fails is recorded, not propagated, so one bad cleanup cannot cost the run its report. +- **Cleanup runs however the rule ends.** Each target is created inside `Effect.acquireUseRelease`, so `cleanup` runs after the rule that made it whether that rule passed, failed or died. A cleanup that fails with a value the kit can render is recorded, not propagated, so one bad cleanup cannot cost the run its report; one that fails with a value the kit can't render (a revoked `Proxy`, say) is still reported as its rule's `Errored` outcome until [#271](https://github.com/thomasfosterau/effect-jsonapi/issues/271). - **The run is auditable.** `Report.writes` lists every resource the kit created, the rule that created it and what became of it — `deleted` by the kit's own DELETE, `cleaned-up`, `cleanup-failed` with the cause, or `left`. `format` prints them under `WRITES`, with the count still in place. - **Each sub-key gates only its own rules.** A type with no `create` skips every write rule naming `writes[""].create`, exactly as a missing `ids` entry does; a create-only type omits `update` and skips only the update rule. Never a vacuous pass. - **A rejected payload is not a verdict.** If the server does not accept `create` (a 4xx, say), the rules it was for report `Skipped` with the status and body — the fixture is wrong or the server is, and the kit cannot tell which. diff --git a/src/Conformance.test.ts b/src/Conformance.test.ts index a665d4d3..ceca5610 100644 --- a/src/Conformance.test.ts +++ b/src/Conformance.test.ts @@ -126,15 +126,22 @@ const cannedClient = (serve: (request: CannedRequest) => Canned): HttpClient.Htt }), ); -/** A run of `target` against the canned server `serve`. */ +/** + * A run of `target` against the canned server `serve`, through `client` — the + * canned client as it is, unless a test wraps it. + */ const verifyOver = ( target: HttpApi.HttpApi, ) => - (serve: (request: CannedRequest) => Canned, options?: Conformance.Options) => + ( + serve: (request: CannedRequest) => Canned, + options?: Conformance.Options, + client: (canned: HttpClient.HttpClient) => HttpClient.HttpClient = (canned) => canned, + ) => Effect.runPromise( Conformance.verifyWith(target, { - client: cannedClient(serve), + client: client(cannedClient(serve)), baseUrl: "http://fixture.test", ids: { articles: "1" }, ...options, @@ -1180,17 +1187,22 @@ describe("Conformance: the write fixture", () => { /** * A conformant run over a fresh store, with `change` applied to every * answer. `seen` is every request as `METHOD /path`, `cleaned` every id the - * fixture's `cleanup` was called with. + * fixture's `cleanup` was called with. `server.client`, when given, wraps the + * client the run sends through. */ const run = async ( change: (canned: Canned, request: CannedRequest) => Canned = (canned) => canned, options?: (store: Store, cleaned: Array) => Conformance.Options, - server: { readonly reuseIds?: boolean } = {}, + server: { + readonly reuseIds?: boolean; + readonly client?: (canned: HttpClient.HttpClient) => HttpClient.HttpClient; + } = {}, ) => { const store: Store = MutableHashMap.empty(); const cleaned: Array = []; const seen: Array = []; - const serve = writeServer(store, server); + const { client, ...served } = server; + const serve = writeServer(store, served); const report = await verifyWrites( (request) => { seen.push(`${request.method} ${request.path}`); @@ -1201,6 +1213,7 @@ describe("Conformance: the write fixture", () => { writes: { articles: fixture(store, cleaned) }, ...options?.(store, cleaned), }, + client, ); return { report, store, seen, cleaned, writes: report.writes ?? [] }; }; @@ -1365,6 +1378,17 @@ describe("Conformance: the write fixture", () => { new TransportRefused({ message: "connection refused" }), "TransportRefused: connection refused", ], + // `name` is the error's own to set; a number still renders, through the template. + [ + "an error named by a number", + Object.assign(new TransportRefused({ message: "" }), { name: 42 }), + "42", + ], + [ + "an error named by a number, with a message", + Object.assign(new TransportRefused({ message: "refused" }), { name: 42 }), + "42: refused", + ], ])("renders %s a rule dies with as itself", async (_, defect, message) => { const { report } = await run( (canned, request) => { @@ -1378,6 +1402,117 @@ describe("Conformance: the write fixture", () => { ]); }); + it("marks an error whose name cannot become a string as unrenderable", async () => { + const defect = Object.assign(new TransportRefused({ message: "refused" }), { + name: Symbol("odd"), + }); + const { report } = await run( + (canned, request) => { + if (request.method === "PATCH") throw defect; + return canned; + }, + () => ({ only: ["spec/status/update-response"] }), + ); + expect(report.outcomes).toEqual([ + expect.objectContaining({ _tag: "Errored", message: "[unrenderable defect]", defect }), + ]); + }); + + /** A value every inspection of throws: `instanceof`, `String`, a property read. */ + const revoked = ((): object => { + const { proxy, revoke } = Proxy.revocable({}, {}); + revoke(); + return proxy; + })(); + + const onlyUpdate = { only: ["spec/status/update-response"] }; + + it.each([ + [ + "thrown by the transport", + () => + run( + (canned, request) => { + if (request.method === "PATCH") throw revoked; + return canned; + }, + () => onlyUpdate, + ), + ], + [ + "died with by the transport", + () => + run(undefined, () => onlyUpdate, { + client: (client) => + HttpClient.make((request) => + request.method === "PATCH" ? Effect.die(revoked) : client.execute(request), + ), + }), + ], + [ + "thrown before the rule's Effect", + () => + run(undefined, () => ({ + ...onlyUpdate, + writes: { + get articles(): Conformance.WriteFixture { + throw revoked; + }, + }, + })), + ], + ])("reports a defect no rendering can read, %s, as Errored", async (_, go) => { + const { report, store } = await go(); + const [outcome] = report.outcomes; + expect(report.outcomes.length).toBe(1); + expect(outcome?._tag).toBe("Errored"); + expect(Predicate.isTagged(outcome, "Errored") && outcome.message).toBe("[unrenderable defect]"); + expect(Predicate.isTagged(outcome, "Errored") && Object.is(outcome.defect, revoked)).toBe(true); + expect(Conformance.format(report)).toContain("the rule died: [unrenderable defect]"); + // What the dead rule created, if anything, was still removed. + expect(MutableHashMap.size(store)).toBe(0); + }); + + it("caps the message of a defect too long for a report line", async () => { + const { report } = await run( + (canned, request) => { + if (request.method === "PATCH") throw "x".repeat(10_000); + return canned; + }, + () => ({ only: ["spec/status/update-response"] }), + ); + const [outcome] = report.outcomes; + const message = Predicate.isTagged(outcome, "Errored") ? outcome.message : ""; + expect(message.length).toBe(500); + expect(message).toBe(`${"x".repeat(499)}…`); + // The defect itself is kept whole. + expect(Predicate.isTagged(outcome, "Errored") && outcome.defect).toBe("x".repeat(10_000)); + }); + + it("does not split a surrogate pair when it caps a message", async () => { + const { report } = await run( + (canned, request) => { + if (request.method === "PATCH") throw `${"x".repeat(498)}😀${"x".repeat(100)}`; + return canned; + }, + () => ({ only: ["spec/status/update-response"] }), + ); + const [outcome] = report.outcomes; + expect(Predicate.isTagged(outcome, "Errored") && outcome.message).toBe(`${"x".repeat(498)}…`); + }); + + it("leaves a message at the cap as it is", async () => { + const { report } = await run( + (canned, request) => { + if (request.method === "PATCH") throw "x".repeat(500); + return canned; + }, + () => ({ only: ["spec/status/update-response"] }), + ); + const [outcome] = report.outcomes; + expect(Predicate.isTagged(outcome, "Errored") && outcome.message).toBe("x".repeat(500)); + }); + it("stops at an external interrupt, cleaning up what the interrupted rule created", async () => { const store: Store = MutableHashMap.empty(); const cleaned: Array = []; @@ -1453,6 +1588,62 @@ describe("Conformance: the write fixture", () => { expect(Conformance.format(report)).toContain("CLEANUP FAILED"); }); + class FixtureBroke extends Schema.TaggedError()("FixtureBroke", { + message: Schema.String, + }) {} + + // A fixture that throws a value the kit can render is not a defect: no rule + // dies of it. One it can't render still does, until #271. + it.each([ + { + member: "create", + expected: (report: Conformance.Report, writes: ReadonlyArray) => { + everyWriteRule(report, `writes["articles"].create threw: FixtureBroke: create broke`); + expect(writes).toEqual([]); + }, + }, + { + member: "update", + expected: (report: Conformance.Report, writes: ReadonlyArray) => { + expect(outcomeFor(report, "spec/status/update-response")).toEqual( + skippedFor(`writes["articles"].update threw: FixtureBroke: update broke`), + ); + const others = WRITE_RULES.filter((id) => id !== "spec/status/update-response"); + expect(others.map((id) => outcomeFor(report, id)._tag)).toEqual(others.map(() => "Passed")); + expect(disposals(writes)).not.toContain("left"); + }, + }, + { + member: "cleanup", + expected: (report: Conformance.Report, writes: ReadonlyArray) => { + everyWriteRule(report); + const stuck = writes.filter((write) => write.disposal === "cleanup-failed"); + // Every creation but the one the kit's own DELETE removed. + expect(stuck.length).toBe(WRITE_RULES.length - 1); + expect(stuck[0]?.detail).toContain("cleanup broke"); + }, + }, + ] as const)( + "skips or records — never dies — when the fixture's $member throws", + async ({ member, expected }) => { + const { report, writes } = await run(undefined, (store, cleaned) => ({ + writes: { + articles: { + ...fixture(store, cleaned), + [member]: () => { + throw new FixtureBroke({ message: `${member} broke` }); + }, + }, + }, + })); + expect(report.outcomes.filter((outcome) => Predicate.isTagged(outcome, "Errored"))).toEqual( + [], + ); + expect(failed(report)).toEqual([]); + expected(report, writes); + }, + ); + it("leaves what it created in place without a cleanup, and says so", async () => { const { report, store, writes } = await run(undefined, (store, cleaned) => { const { cleanup: _cleanup, ...noCleanup } = fixture(store, cleaned); diff --git a/src/Conformance.ts b/src/Conformance.ts index 70ff3209..886710d5 100644 --- a/src/Conformance.ts +++ b/src/Conformance.ts @@ -228,7 +228,9 @@ export interface Finding extends Core.Finding {} * made, `Failed` with its findings, `Skipped` with the reason it could not * be decided against this target, or `Errored` when the rule died — a * transport that throws, or a bug in the kit, not a finding about the server — - * with the defect's `message` and the `defect` itself. + * with the defect's `message` (capped at 500 UTF-16 code units, a longer one + * ending in `…`; `[unrenderable defect]` for a value that throws when + * inspected) and the `defect` itself. * * `Skipped` is load-bearing. A rule that needs a write endpoint against an api * that has none, or a sample id the caller did not supply, must not be counted @@ -238,9 +240,12 @@ export interface Finding extends Core.Finding {} * rest of its report: every other rule still runs and is reported, and so is * {@link Report.writes}. It is neither a pass nor a finding — {@link assert} * dies on it. Interruption is not turned into an outcome: it still stops the - * run. A write fixture that throws is not a defect: a `create` or `update` - * that throws skips the rules it would have driven, naming the member, and a - * `cleanup` that fails or throws is recorded in {@link Report.writes}. + * run. A write fixture that throws a value the kit can render is not a + * defect: a `create` or `update` that throws one skips the rules it would have + * driven, naming the member, and a `cleanup` that fails with or throws one is + * recorded in {@link Report.writes}. One that throws a value the kit can't + * render (a revoked `Proxy`, say) is still reported as `Errored` until + * {@link https://github.com/thomasfosterau/effect-jsonapi/issues/271 #271}. * * @example * ```ts @@ -1109,7 +1114,10 @@ export const findings = (report: Report): ReadonlyArray => * `Predicate.isTagged(defect, "RuleDied")`), whose `rule` is the rule's id, * whose message names the rule and the defect's, and whose `cause` is the * original defect. That keeps the gate as strict as when a rule's defect - * killed the whole run, while the report itself stays readable. + * killed the whole run, while the report itself stays readable. Its `message` + * is always rendered, but its `cause` holds the defect as it was thrown, so a + * reporter that pretty-prints the cause can itself throw on a defect that + * cannot be inspected (a revoked `Proxy`, say). * * @example * ```ts diff --git a/src/internal/conformance/core.ts b/src/internal/conformance/core.ts index 0f324e9f..b4cca907 100644 --- a/src/internal/conformance/core.ts +++ b/src/internal/conformance/core.ts @@ -14,6 +14,7 @@ import { MutableHashSet, Option, Predicate, + Result, SchemaAST, } from "effect"; import { HttpBody, HttpClient, HttpClientRequest } from "effect/http"; @@ -82,7 +83,9 @@ export interface Skipped { /** * A rule that died — a defect, not a finding — before it reached a verdict. - * `message` renders the defect; `defect` is the value as it was thrown. + * `message` renders the defect, capped at 500 UTF-16 code units (a longer one + * ends in `…`; one that cannot be rendered is `[unrenderable defect]`); + * `defect` is the value as it was thrown. * * @internal */ @@ -539,9 +542,33 @@ export const pass = (rule: Rule, probes: number, note?: string): Passed => ({ /** @internal */ export const skip = (rule: Rule, reason: string): Skipped => ({ _tag: "Skipped", rule, reason }); -/** An `Error` as `Name: message`, or the name alone when it carries no message. */ +/** + * An `Error` as `Name: message`, or the name alone when it carries no message. + * Both go through a template, so a `name` that is not a string but coerces to + * one (a number, say) still renders; one that cannot coerce (a Symbol, or an + * object whose `toString` throws) throws here, and the defect's message falls + * back to {@link UNRENDERABLE}. + */ const errorMessage = (error: Error): string => - error.message === "" ? error.name : `${error.name}: ${error.message}`; + error.message === "" ? `${error.name}` : `${error.name}: ${error.message}`; + +/** The longest `Errored.message`, in UTF-16 code units, the marker included. */ +const MESSAGE_LIMIT = 500; + +/** + * `message` cut to {@link MESSAGE_LIMIT}, ending in `…` when it was cut. The + * cut never splits a surrogate pair: a high surrogate it would leave last is + * dropped too. + */ +const capped = (message: string): string => { + if (message.length <= MESSAGE_LIMIT) return message; + const end = MESSAGE_LIMIT - 1; + const last = message.charCodeAt(end - 1); + return `${message.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end)}…`; +}; + +/** `Errored.message` for a defect that throws when it is inspected. */ +const UNRENDERABLE = "[unrenderable defect]"; /** * Runs one rule, turning a defect into its `Errored` outcome so that one rule @@ -555,19 +582,30 @@ const errorMessage = (error: Error): string => */ export const runRule = (implementation: RuleImpl, ctx: Context): Effect.Effect => Effect.suspend(() => implementation.run(ctx)).pipe( - // The defect's message for a report line: an `Error` by its name and - // message, so a thrown tagged error with no message still says what it - // was; anything else thrown — a string, `null`, a plain object — as - // itself, not dressed up as an `Error`. Effect.catchDefect((defect) => Effect.succeed({ _tag: "Errored", rule: implementation.rule, - message: Predicate.isError(defect) - ? errorMessage(defect) - : Predicate.isString(defect) - ? defect - : Formatter.format(defect), + // The defect's message for a report line: an `Error` by its name and + // message, so a thrown tagged error with no message still says what + // it was; anything else thrown — a string, `null`, a plain object — + // as itself, not dressed up as an `Error`. Rendering is total: a + // defect that throws when inspected (a revoked `Proxy`, a getter that + // throws) gets a fixed marker rather than killing the run the + // `Errored` outcome exists to keep. + message: Result.merge( + Result.try({ + try: () => + capped( + Predicate.isError(defect) + ? errorMessage(defect) + : Predicate.isString(defect) + ? defect + : Formatter.format(defect), + ), + catch: () => UNRENDERABLE, + }), + ), defect, }), ),