Skip to content

Concepts ​

The ideas behind @sekhmet/issue, and why issues behave the way they do. The recipes show how to put them to work, and the API reference on JSR documents each export. The decision record keeps the history behind each choice.

An issue is one occurrence ​

An Issue<T, R> describes one thing that went wrong, once. Its words are for people: a code that never changes (config/NotFound), a message, and an optional hint and docs link. Its value, of type T, is for code: the typed facts about the problem, such as the path that was missing.

The issue doesn't say how bad it is. Whether to panic, log, retry or fail is a property of the place that treats the issue, not of the issue itself: the same missing file is fatal to one program and routine to another.

Handling yields a residue, in place ​

An issue is either Unhandled(value) or Handled(residue). The residue, of type R, is what handling yields: for a missing config, the config to use instead. Handling switches the issue's state in place, once, and it never switches back. Everyone holding the issue sees the switch, and nobody needs a new value threaded back to them.

Handling drops the value: a handled issue holds its residue only. So value() is Some only while the issue is unhandled, and residue() only once it is handled. state() reads a snapshot, which handling leaves as it was.

Narrow the state, not the issue ​

issue.isUnhandled() and issue.isHandled() return a plain boolean, not a type guard. TypeScript keeps a narrowing on a const across awaits and calls, but an attempt can switch the issue in between, so a guard on the issue would go stale and let you read a value it no longer holds.

A state read with state() is an immutable IssueState: handling gives the issue a new state and never changes an old one. So the state's own isUnhandled and isHandled (from @sekhmet/issue/state) are type guards, and their narrowing stays true. IssueState is structured like Option: the Unhandled and Handled constructors build one, value and residue read it as an Option, and expectResidue, unwrapResidue, residueOr and residueOrElse (for a Handled state) and expectValue, unwrapValue, valueOr and valueOrElse (for an Unhandled one) unwrap it, with the issue's own names.

ts
import { union } from "@sekhmet/enum/core/mini";
import { issue } from "@sekhmet/issue/issue";
import { assertEquals } from "@std/assert";

const notFound = issue<string, number>({
	value: "app.json",
	code: "config/NotFound",
	message: "No config file.",
});
const before = notFound.state();
notFound.handle(8080);

assertEquals(notFound.isHandled(), true, "the issue should now be handled");

if (before.isUnhandled()) {
	const path: string = union(before); // still true: the snapshot didn't change

	assertEquals(path, "app.json", "the earlier snapshot should keep its path");
}

The …And forms (isUnhandledAnd, isHandledAnd) follow the same split: a boolean on the issue, and on the state a guard that narrows the variant. Their predicate is a plain boolean test, since a state is invariant like its issue, so T and R can't be narrowed.

A guard's false branch removes the guarded type, so on a state already narrowed to Unhandled, a guard isUnhandledAnd whose predicate fails would leave never, though the state is still Unhandled. So the …And forms are overloaded: on a state already narrowed to their variant they return a plain boolean, and the state stays as it was in both branches; on any other state they narrow. The narrowing of the true branch stays true, as the snapshot never changes; the false branch says only that the whole test failed. Attempt's …And forms work the same way.

Why an issue is invariant ​

Most Sekhmet enums, like Result and Attempt, are covariant: an Attempt<number, never> fits where an Attempt<number, string> is expected. An issue can't be, because it changes in place. If an Issue<Path, Config> could be viewed as an Issue<Path, unknown>, handling it through that view could write any residue, and the holder of the original would read something that isn't a Config. So Issue is invariant in both T and R (written in out), and the widening doesn't type-check. Rust makes &mut T invariant for the same reason; see #98 for the same hole in Option and Latch.

The main Issue has one gap left. TypeScript checks a method's parameters bivariantly, so a structural type with a wider residue still accepts a main issue, and handling through it writes the wrong residue:

ts
import { issue } from "@sekhmet/issue/issue";
import { assertEquals } from "@std/assert";

const notFound = issue<string, { readonly port: number }>({
	value: "app.json",
	code: "config/NotFound",
	message: "No config file.",
});
const view: { handle(residue: unknown): unknown } = notFound; // type-checks
view.handle("not a config");

const port: number = notFound.unwrapResidue().port; // typed number…

// …but the residue is a string
assertEquals(port, undefined, "the view should have written a non-config");

So don't hand an issue around as a structural type with its methods; pass the Issue class, or use the mini free functions, which take it and have no such gap. The fix belongs in gen-main, and is tracked under #98.

A recovery is a typed repair ​

A Recovery<T, R, E> wraps (value: T) => Vow<Outcome<R, E, unknown>>: it settles Ok with a residue, Err with an error, or Panicked with the payload of a bug (an Outcome is what a panic boundary returns). Its type says which issues it fits: those whose value is a T and whose residue is an R. So it never needs to look at an issue and decline at runtime; the compiler already checked that it applies.

A recovery can be sync or async. A sync one returns an already-resolved Vow, so attempting it settles at once, in the same call stack, with no microtask. sync, succeed and fail build sync ones; fromPromise builds an async one under a panic boundary, and carries a rejection as an Err, so a rejection is never unhandled. A rejection with a Panic is a bug, not a failed repair: the boundary's hook reports it once, and the recovery settles as Panicked. Every combinator stops there (or and orElse try no fallback, firstOf no further recovery, retry no further run), and when and the transforms pass it through.

A throw from a callback (a repair, or a step, builder, test or mapping a combinator runs) is a bug too, and nothing turns it into an outcome. In a chain that is still sync, it propagates to whoever ran the recovery. Once an async recovery has run before it, as when or runs a sync fallback after a fromPromise recovery fails, the callback runs inside a vow dependent: the throw reaches the panic hook unchanged, reported once, and that attempt never settles: a vow derived from a throwing callback has no state for the throw in place of a value (#127).

Recoveries compose like Results do, with Rust's and @sekhmet/enum's naming: or takes the next recovery itself, and orElse builds it lazily from what failed. or tries the next when one fails and drops the first error, like Result::or; orElse hands the error to a function that returns the recovery to try, like Result::or_else. firstOf behaves as or folded over a list, and retry runs one again, keeping the last error. Both run their recoveries in a loop that doesn't nest the stack, so a long list or a large times is safe, sync or async. map, mapErr and andThen change what it yields, and mapInput changes what it repairs.

or, orElse and firstOf take the wider residue of the recoveries they join, with no union. A recovery is covariant in its residue, and one built with fail yields none (never), so fail("…").or(succeed(config)) is a Config recovery with no annotation, and so is the reverse order. Residues with no wider one but a union, such as number and Config, don't type-check: a union of residues couldn't be told apart again.

How an attempt ends ​

attempt(issue, recovery) returns a Vow<Attempt<R, E>>:

  • Handled(residue): this attempt handled the issue, which switched in place;
  • AlreadyHandled(residue): the issue was handled before this attempt, or by another attempt that finished first;
  • Failed(error): the recovery failed, and the issue stays unhandled;
  • Panicked(payload): the recovery panicked (a Panic in an async repair; see fromPromise, whose hook reports it once; a hand-built Panicked outcome is not reported), and this attempt didn't handle the issue (another attempt may have). It isn't isResolved, and every unwrap throws the payload again. (A first cut left such an attempt pending for good; it settles now, since a vow that never settles means no answer has come.)

A handled issue doesn't run the recovery at all. An unhandled one runs it on its value and, when it settles, reads the state again. Between attempts running at the same time, the first to finish wins: a later success reports AlreadyHandled with the winner's residue, and so does a later failure, since the issue is handled either way. An attempt whose recovery panicked reports Panicked even once another attempt has handled the issue: a bug is never hidden behind AlreadyHandled.

handle(issue, residue) is an attempt with no recovery: Handled, or AlreadyHandled if the issue already was.

A cause lives in the value ​

An issue has no cause field. An issue caused by another holds it in its value, as in Issue<{ readonly cause: Issue<Path, Config> }, Config>. The cause is then typed like any other fact, recoveries can reach it, and an issue with no cause pays nothing for the possibility. wrap builds that shape, starting a new, unhandled issue whatever the state of its cause, and render follows a cause that is an issue down the chain while each issue is unhandled, printing each issue once.

Handling a wrapper never handles its cause, or the other way round. To recover a wrapper through its cause, attempt the cause inside the wrapper's recovery and hand its residue up (see the recipes).

Unwrapping panics ​

expectResidue and unwrapResidue (and an attempt's expect, unwrap, expectFailed and unwrapFailed) throw a Panic from @sekhmet/panic when the value isn't there, with the issue or attempt as its cause. A panic means a broken invariant: use them where handling is guaranteed, and residueOr, residueOrElse or toResult everywhere else.