pure-effect 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +20 -9
- package/README.md +135 -26
- package/index.d.ts +68 -12
- package/index.js +249 -47
- package/package.json +4 -4
- package/test/all.js +472 -8
- package/test/types.test-d.ts +41 -4
- package/tsconfig.check.json +12 -0
- package/.claude/settings.local.json +0 -17
package/CLAUDE.md
CHANGED
|
@@ -14,10 +14,12 @@ npx esbuild index.js --minify --format=esm | gzip -9 | wc -c # the size the R
|
|
|
14
14
|
|
|
15
15
|
No build or lint step: the library ships as plain ES modules with no transpilation. Formatting is Prettier, configured in `.prettierrc`; match it when editing.
|
|
16
16
|
|
|
17
|
-
The README's badge and feature bullet both state a minified-and-gzipped ceiling, currently
|
|
17
|
+
The README's badge and feature bullet both state a minified-and-gzipped ceiling, currently around 4 KB. Re-measure with the command above after adding anything to `index.js`, because the badge is a static `img.shields.io/badge/` URL with the number written into it rather than a live query, so it cannot correct itself.
|
|
18
18
|
|
|
19
19
|
**Markdown prose has no hard line breaks.** Write each paragraph and each list item as one line and let the editor soft-wrap; never wrap prose at a column. Hard breaks make later edits reflow whole paragraphs, turning a one-word change into a multi-line diff. `proseWrap: never` enforces this, so `npm run format` unwraps any prose that arrives wrapped. Even so, write it unwrapped in the first place rather than relying on the sweep, since a wrapped paragraph reads as an intended shape until something reflows it. Fenced code blocks are untouched by the setting, and table rows stay one per line; only prose joins.
|
|
20
20
|
|
|
21
|
+
**No `thunk` in the README.** Reader-facing prose says the Command's function, or `cmd`. The word remains fine in this file, in JSDoc, and in code comments, where precision for maintainers matters more than approachability, but a README reader should never need to know it. `grep -n "thunk" README.md` checks a change before it lands.
|
|
22
|
+
|
|
21
23
|
**No em dashes.** The `—` character does not appear anywhere in this repository: not in `README.md`, not in this file, not in JSDoc, code comments, test names, or assertion messages. Reach for the punctuation that carries the actual relationship instead of a dash that blurs it. A colon when the second half explains or names the first. Parentheses for an aside the sentence could survive without. A semicolon between two linked independent clauses. A comma for a light pause or a trailing "which" clause. A full stop when the clause can stand on its own, which is usually the honest fix for a dash joining two complete thoughts. Nothing enforces this mechanically, so it is on the author; `grep -rn "—" --include="*.js" --include="*.ts" --include="*.md" .` checks a change before it lands. Table cells that need a "not applicable" placeholder use `n/a`.
|
|
22
24
|
|
|
23
25
|
## Architecture
|
|
@@ -32,15 +34,17 @@ The README's badge and feature bullet both state a minified-and-gzipped ceiling,
|
|
|
32
34
|
| `Failure(error, initialInput)` | `{ type: 'Failure', error, initialInput }` | Short-circuits the pipeline |
|
|
33
35
|
| `Command(cmdFn, nextFn, meta)` | `{ type: 'Command', cmd, next, meta }` | Defers a side effect for the interpreter; `meta.name` sets the Command's identity |
|
|
34
36
|
| `Ask(nextFn)` | `{ type: 'Ask', next }` | Reads the `context` passed to `runEffect`; passes it to `nextFn` |
|
|
35
|
-
| `Retry(effect, options)` | `{ type: 'Retry', effect, options, next }` | Wraps any Effect tree with retry-on-failure semantics; handled natively by the interpreter |
|
|
36
|
-
| `Parallel(effects, next)` | `{ type: 'Parallel', effects, next }` | Runs multiple Effect trees concurrently
|
|
37
|
+
| `Retry(effect, options)` | `{ type: 'Retry', effect, options, next }` | Wraps any Effect tree with retry-on-failure semantics; handled natively by the interpreter; a per-use `options.onExhausted` runs a fallback Effect when every attempt has failed |
|
|
38
|
+
| `Parallel(effects, next?)` | `{ type: 'Parallel', effects, next }` | Runs multiple Effect trees concurrently; the first branch to fail cancels its siblings and its Failure is returned; context flows into all branches |
|
|
37
39
|
| `effectPipe(...fns)` | n/a | Composes functions into a sequential pipeline via `chain` |
|
|
38
40
|
| `runEffect(effect, context, callConfig?)` | async | Interpreter: traverses the effect tree, executes Commands; resolves `Ask` and `Retry`; per-call `callConfig` overrides global defaults |
|
|
39
41
|
| `configureEffect(...configs)` | n/a | Sets process-wide telemetry hooks (`onStep`, `onRun`, `onBeforeCommand`) and global `retry` defaults; merges several configurations into one wiring; returns a restore function; overridden by per-call `callConfig` |
|
|
40
42
|
|
|
41
43
|
The recording and replay exports are a 2x2 rather than four loose helpers: `recorder` and `replayEffect` are the capabilities, at the hook and tree level, while `recordEffect` and `timeTravel` are the flow-level pair that also own trace metadata. That metadata is why the conveniences exist and should not be cut as mere sugar: `initialInput` lets a flow be rebuilt, `context` lets `Ask` resolve on replay, and `version` makes a stale trace detectable. A caller who assembles a trace by hand and forgets `context` gets one that silently diverges. `timeTravel` is presentation over `replayEffect` and could be rebuilt from `onResolved` in about ten lines, but it stays: the one-line form is what makes the feature graspable.
|
|
42
44
|
|
|
43
|
-
`Command(cmd, next, meta)` keeps that parameter list, and `next` is optional because most of Commands in this repo pass their result straight through: it defaults to `(result) => Success(result)`.
|
|
45
|
+
`Command(cmd, next, meta)` keeps that parameter list, and `next` is optional because most of Commands in this repo pass their result straight through: it defaults to `(result) => Success(result)`. `Parallel`'s `next` follows the same convention, defaulting to `(values) => Success(values)`, so a bare `Parallel(effects)` resolves to the ordered array of success values. The README's `Composing Larger Flows` section documents the composition patterns the primitives already support (sub-pipeline branching, `Parallel` fan-in, local joins that carry a minimal purpose-shaped value); those shapes need no combinators, which is why none were added. The no-accumulator guidance there is deliberate bug avoidance, not taste: a growing scope object hides which step depends on what, lets stale fields outlive their producers, and widens what carries PII, so keep the section's examples threading minimal values if they are ever reworked.
|
|
46
|
+
|
|
47
|
+
There is deliberately no catch combinator (an `Attempt` node was designed and rejected), and the README's `Which Errors Are Data` section is the guidance that replaced it: an outcome the flow handles is data (a `next` branches on the result, and a rejecting `cmd` function catches into a result shape at the boundary), while `Failure` means abort and is reserved for the shell. Fallbacks written this way are fully traced and replayed; the failed attempt is recorded as that Command's result with the error as data, so nothing is lost, only categorized as handled. Catch was rejected because it reintroduces non-local control flow into a paradigm whose point is explicit data flow, and because every motivating case except one was already expressible. The one exception, recovering from `Retry` exhaustion in-flow, is now covered by the scoped per-use option `Retry(effect, { onExhausted })`. It was added, where general catch was rejected, for three reasons worth keeping: it was the only composition with no in-library expression (the shell workaround split one logical operation across two runs and two traces); retry-then-fallback is a canonical resilience pairing (Polly, resilience4j), so demand was predictable rather than speculative; and it completes `Retry`'s own failure handling rather than adding catch semantics, since `Retry` was already the node that reacts to failures and previously abdicated on the last one. The ceiling stands: no general catch node, nothing but exhaustion is catchable, `onExhausted` is per-use only (the global `retry` defaults cannot carry one, pinned by an `expectError`), and a cancelled branch skips the fallback.
|
|
44
48
|
|
|
45
49
|
A Command's identity is resolved by the internal `commandName(eff)`: a non-empty string `meta.name`, else `cmd.name`, else `'anonymous'`. That identity is used in three places at once, which is why it has its own function rather than being inlined at the call site: trace entries are keyed on it, strict replay matching compares it against the recorded name, and telemetry spans are titled with it. `meta.name` exists because the previous rule, `cmd.name` alone, made the flagship feature depend on syntax: an inline arrow silently recorded as `'anonymous'`, and any minifier that mangles function names renamed every step of every trace. Both failures are silent, which is the worst property an identity can have. `cmd.name` remains supported and is what the examples use, since naming the thunk reads well and needs no second argument.
|
|
46
50
|
|
|
@@ -75,7 +79,10 @@ runEffect(tree, context, callConfig?)
|
|
|
75
79
|
→ resolves Ask by calling next(context), continues
|
|
76
80
|
→ resolves Retry via an inner execute() loop (not recursive runEffect),
|
|
77
81
|
so onRun fires exactly once per runEffect call regardless of attempts;
|
|
78
|
-
on exhaustion returns Failure({ retryExhausted: true, lastError, attempts })
|
|
82
|
+
on exhaustion returns Failure({ retryExhausted: true, lastError, attempts }),
|
|
83
|
+
unless a per-use onExhausted returns a fallback Effect: it executes under the
|
|
84
|
+
retry's `f` path prefix, its success feeds next, its failure propagates
|
|
85
|
+
unwrapped, and a cancelled Parallel branch skips it
|
|
79
86
|
→ resolves Parallel by running all effects via Promise.all with the same
|
|
80
87
|
context; if any effect returns Failure, returns the first Failure by
|
|
81
88
|
array index and skips next; otherwise calls next with the array of
|
|
@@ -122,7 +129,7 @@ Three semantics are surprising enough that `Documented sharp edges` in the test
|
|
|
122
129
|
|
|
123
130
|
`Retry` repeats the entire wrapped tree on every attempt, including Commands that already succeeded, because the retry loop calls `execute(eff.effect)` again rather than resuming. `Retry(effectPipe(charge, receipt))` charges three times when the receipt step fails twice, and the run still reports `Success`. The semantics are defensible, since retry means run this tree again, but the README's "wraps any Effect tree" invites exactly the dangerous construction, so both the JSDoc and the Retry section now say to wrap the failing Command instead. If this is ever changed to resume rather than repeat, the pinning test is the one to read first.
|
|
124
131
|
|
|
125
|
-
`Parallel`
|
|
132
|
+
`Parallel` cancellation is cooperative. The first branch to fail aborts an `AbortController` scoped to that `Parallel`, linked to the enclosing one so cancellation nests. Two levels of effect follow. A cancelled branch starts no further Commands, checked at the top of `execute`'s loop, which needs nothing from user code and is where most of the benefit is. Stopping the Command already in flight needs its thunk to accept the `AbortSignal` it is handed, which is why `cmd` is now called as `cmd(signal)` inside a `Parallel` and with no argument anywhere else: passing an argument only where it means something keeps a thunk written as `(x) => ...` from silently receiving one. A thunk that ignores the signal runs to completion, so a branch whose first Command is a write can still write after a sibling has failed, which is what the pinning test covers. `Parallel` still awaits every branch before returning, deliberately: returning early would leave cancelled work running unobserved after the Failure, with its rejections unhandled. The triggering branch is tracked separately from branches that failed because they were cancelled, so a cancellation never displaces the real error; when several branches fail in the same tick the first by array order wins, which is the older documented behaviour and is pinned.
|
|
126
133
|
|
|
127
134
|
Every `Failure` carries `initialInput`, stamped by `chain`, alongside the full error. Neither is trimmed and neither should be: a test asserting on a Failure and a developer reading one both need the whole thing. PII control is split deliberately. `redact` is the single mechanism for a trace, and the shell owns what reaches logs, so the guidance is to log `result.error` rather than serialize a whole Failure.
|
|
128
135
|
|
|
@@ -135,11 +142,13 @@ Because a flow is data, a production run can be recorded and replayed later. Rec
|
|
|
135
142
|
Four invariants hold the design together; breaking any of them breaks replay in a way tests may not catch:
|
|
136
143
|
|
|
137
144
|
- **Replay drives the real interpreter.** `replayEffect` calls `runEffect` rather than walking the tree itself, which is why `Ask`, `Retry`, and `Parallel` replay correctly and why replay semantics cannot drift from execution semantics. The interpreter's only execution point is `await localStepRunner(cmdName, 'Command', eff.cmd)`, which hands the Command thunk to `onStep` as `op` instead of calling it. Replay's `onStep` never invokes `op` unless `onMissing: 'execute'`, so **no side effect can occur by default**. Preserve that single-execution-point property: a Command executed anywhere else in the interpreter would be invisible to both recording and replay.
|
|
138
|
-
- **
|
|
145
|
+
- **Path matching, with the two older modes kept for legacy traces.** Every step carries a `path`: its position in the Effect tree, numbered sequentially within a subtree, with each `Parallel` branch and each `Retry` attempt opening its own prefix (`0p1/0r2/0` is branch 1, retry attempt 2, first Command; a retry's `onExhausted` fallback opens `0rf/`). A path depends only on the shape of the tree, never on the order branches finish in, so it is order-independent **and** paradox-detecting at the same time. `fromTrace` matches by path whenever every entry has one, and it does so whatever `strict` says, deliberately: a caller who passed `strict: false` to work around `Parallel` should get correct matching once their traces carry paths rather than keeping the mode that option existed to work around. Duplicate paths throw, since a collision would reintroduce the failure paths exist to prevent. The older modes remain only for traces recorded before paths existed: `strict: true` consumes entries positionally, `strict: false` resolves per-Command FIFO queues. **The name-queue mode is the bug paths fixed.** It paired a step with the next recorded entry of the same name, which is completion order, so two `Parallel` branches calling the same Command swapped results whenever replay timing differed from production, and the replay still reported `Success`. `strict` is ignored when a `Resolver` is passed, because that `Resolver` has already chosen its own matching.
|
|
146
|
+
|
|
147
|
+
- **The hook contract carries the path as a fourth parameter.** `onStep(name, type, op, path)`. Three-parameter hooks keep working, and `chainHooks` forwards the path through nested wrappers. A hand-rolled wrapper that calls `inner(name, type, op)` without forwarding `path` silently produces a trace with no paths, which then falls back to legacy positional matching: correct for sequential flows, and the old swapping bug for `Parallel`. Forward the fourth argument in anything that wraps `onStep`.
|
|
139
148
|
- **`fastRetry` exists because of merge order.** The interpreter merges per-use options over call config (`{ ...localRetryDefaults, ...eff.options }`), so a `callConfig.retry` cannot override a delay written at the call site. `zeroRetryDelays` therefore rewrites `Retry` nodes to `delay: 0, backoff: 1` lazily, through their `next` continuations; without it, replaying a flow that retried in production waits out the production backoff.
|
|
140
149
|
- **The outcome wrapper is load-bearing.** A `Resolver` returns `{ result }`, `{ error }`, or `undefined` for "not recorded". The wrapper keeps a Command that legitimately returned `undefined` (`{ result: undefined }`) distinct from having no recording, which is what makes the `onMissing` guard trustworthy.
|
|
141
150
|
|
|
142
|
-
Two further details: `hooks` defaults to `false`, so a replay cannot reach a telemetry backend or a guardrail that performs I/O; and errors cross the trace via `serializeError` / `reviveError` because `message` and `
|
|
151
|
+
Two further details: `hooks` defaults to `false`, so a replay cannot reach a telemetry backend or a guardrail that performs I/O; and errors cross the trace via `serializeError` / `reviveError` because `message`, `stack`, and `cause` are non-enumerable on `Error` and a plain `JSON.stringify` would silently drop them; `cause` is carried recursively since it is often an `Error` itself. Non-`Error` values pass through unchanged, so a Command that rejected with a string still replays as a string.
|
|
143
152
|
|
|
144
153
|
Recorded results are snapshotted by the internal `snapshot`, not stored by reference. Without it a later step that mutates a returned object rewrote what the trace said an earlier step returned, and because `toTrace` runs after the flow finishes, the mutation was already baked in by the time a sink serialized it: the trace recorded a value production never saw, and a replay fed that value back. It uses `structuredClone` where available, falls back to a JSON round trip, and falls back again to the reference for values that can be neither, since dropping the entry would be worse. Redaction runs first, so nothing sensitive is cloned before being stripped.
|
|
145
154
|
|
|
@@ -151,7 +160,7 @@ Recorded results are snapshotted by the internal `snapshot`, not stored by refer
|
|
|
151
160
|
|
|
152
161
|
Full generic type declarations are in `index.d.ts` and referenced via the `types` field in `package.json`. Type-level tests live in `test/types.test-d.ts` and run via `tsd` as part of `npm test`.
|
|
153
162
|
|
|
154
|
-
`index.d.ts` is hand-maintained beside `index.js`, so the two drift
|
|
163
|
+
`index.d.ts` is hand-maintained beside `index.js`, so the two can drift. Two mechanisms guard the drift: the `Declaration parity` test pins the export lists to each other in both directions, and `npm test` now runs `tsc -p tsconfig.check.json` (checkJs over `index.js`), which keeps the JSDoc sound; it still never opens the declarations, so signature-level drift remains `tsd`'s job. The tsc leg was added after a narrowing error in the interpreter shipped through a green gate and was found in an editor, the second time a lens existed but was not in the gate. **Check `npm test` by exit code.** `tsd` failures print neither "passing" nor "failing", so piping the output through `grep -E "passing|failing"` hides them entirely, which is how `runEffect`'s declaration stayed deleted through several edits here while every other check reported green. It was removed as collateral by a slice that targeted an adjacent block, so after any structural edit to `index.d.ts`, compare the runtime exports against the declared ones rather than trusting the diff.
|
|
155
164
|
|
|
156
165
|
Raw `tsc` over `test/types.test-d.ts` is the wrong lens and will always report errors: `expectError(...)` blocks contain deliberate type errors that `tsd` requires to be errors.
|
|
157
166
|
|
|
@@ -159,6 +168,8 @@ Raw `tsc` over `test/types.test-d.ts` is the wrong lens and will always report e
|
|
|
159
168
|
|
|
160
169
|
Error unions need explicit return annotations. A step written as `(i: User): Effect<User, 'taken'> => ...` contributes `'taken'` to the pipeline's union, but the same step left to inference from a bare `Success(x) | Failure(y)` return type yields `E = unknown`, and one `unknown` absorbs every other member of the union, so `result.error` degrades to `unknown` for the whole pipeline. Annotate `Effect<T, E>` on any step whose error type is meant to survive, and write type-level examples that way.
|
|
161
170
|
|
|
171
|
+
`Retry`'s declared error is `RetryExhaustedError<E>`, not `E`, and that is deliberate: the interpreter never lets an inner attempt's error escape unwrapped, so on exhaustion the Failure carries `{ retryExhausted, lastError, attempts }` and the inner `E` survives only as `lastError`. `RetryState`'s `effect` field is typed `Effect<T, any, Ctx>` for the same reason, since the wrapped tree's error type is consumed by the retry loop rather than exposed. The declaration previously claimed `E`, which made `result.error` lie for every flow containing a `Retry`; the tsd assertions in the Retry section pin the corrected shape. With a per-use `onExhausted` the declared error is the fallback's own error type instead, since exhaustion then never escapes; that overload comes first, and `onExhausted` is typed on the per-use options only, so a global `configureEffect` retry default cannot carry one.
|
|
172
|
+
|
|
162
173
|
The recording and replay exports are declared alongside the primitives (`ReplayStep`, `ReplayOutcome`, `Resolver`, `TraceEntry`, `TraceLog`, `RecorderOptions`, `TraceMeta`, `ReplayOptions<Ctx>`). Known gap: `test/types.test-d.ts` has no coverage for any of the replay exports; their declarations are checked only by `tsc` over the JSDoc in `index.js`. Add `tsd` assertions there when touching those types.
|
|
163
174
|
|
|
164
175
|
### Observability
|
package/README.md
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
# Pure Effect
|
|
2
2
|
|
|
3
|
-
[](https://www.npmjs.com/package/pure-effect) [](https://www.npmjs.com/package/pure-effect) [](https://bundlephobia.com/package/pure-effect) [](https://github.com/aycangulez/pure-effect/blob/main/LICENSE)
|
|
4
4
|
|
|
5
|
-
**Pure Effect**
|
|
5
|
+
**Pure Effect** records what your business logic did in production and replays it anywhere: time-travel debugging for JavaScript and TypeScript, with zero dependencies. Business logic is plain data you can test without mocks.
|
|
6
6
|
|
|
7
7
|
- Replay a production failure locally, with no database and no network
|
|
8
8
|
- No mocks needed to test async pipelines
|
|
9
9
|
- Inject context without touching function signatures
|
|
10
|
-
- Built-in retry
|
|
10
|
+
- Built-in retry, plus parallel execution that cancels sibling branches on the first failure
|
|
11
11
|
- OpenTelemetry-ready via lifecycle hooks
|
|
12
|
-
- Zero dependencies,
|
|
12
|
+
- Zero dependencies, 4 KB minified and gzipped
|
|
13
13
|
- Works in JavaScript and TypeScript (full generics, bundled `.d.ts`)
|
|
14
14
|
|
|
15
15
|
## Table of Contents
|
|
@@ -17,11 +17,14 @@
|
|
|
17
17
|
- [Installation](#installation)
|
|
18
18
|
- [Quick Start](#quick-start)
|
|
19
19
|
- [Testing Without Mocks](#testing-without-mocks)
|
|
20
|
+
- [How It Works](#how-it-works)
|
|
20
21
|
- [Time-Travel Debugging](#time-travel-debugging)
|
|
21
22
|
- [Recording in Production](#recording-in-production)
|
|
22
23
|
- [Passing Runtime Context](#passing-runtime-context)
|
|
23
24
|
- [Retrying Transient Failures](#retrying-transient-failures)
|
|
24
25
|
- [Running Effects in Parallel](#running-effects-in-parallel)
|
|
26
|
+
- [Composing Larger Flows](#composing-larger-flows)
|
|
27
|
+
- [Which Errors Are Data](#which-errors-are-data)
|
|
25
28
|
- [TypeScript: Typed Errors and Context](#typescript-typed-errors-and-context)
|
|
26
29
|
- [Why Pure Effect](#why-pure-effect)
|
|
27
30
|
- [API Reference](#api-reference)
|
|
@@ -35,7 +38,7 @@ npm install pure-effect
|
|
|
35
38
|
|
|
36
39
|
## Quick Start
|
|
37
40
|
|
|
38
|
-
A complete user registration flow. Every step receives the value the previous step produced, so the pipeline reads top-to-bottom as the flow of data:
|
|
41
|
+
A complete user registration flow. Every step receives the value the previous step produced, so the pipeline reads top-to-bottom as the flow of data. Each I/O step is a pair: the call to make, plus a `next` function that receives its answer and decides what follows.
|
|
39
42
|
|
|
40
43
|
```js
|
|
41
44
|
import { Success, Failure, Command, effectPipe, runEffect } from 'pure-effect';
|
|
@@ -47,19 +50,21 @@ const validateRegistration = (input) => {
|
|
|
47
50
|
return Success(input);
|
|
48
51
|
};
|
|
49
52
|
|
|
50
|
-
// These functions return a Command object. They do NOT call the database.
|
|
51
|
-
// Name the
|
|
53
|
+
// These following two functions return a Command object. They do NOT call the database.
|
|
54
|
+
// Name the commands since traces, replay matching, and telemetry spans are keyed on them.
|
|
52
55
|
const ensureEmailAvailable = (input) => {
|
|
53
56
|
const cmdFindUser = () => db.findUser(input.email);
|
|
54
|
-
|
|
57
|
+
const next = (found) => (found ? Failure('Email already in use.') : Success(input));
|
|
58
|
+
return Command(cmdFindUser, next);
|
|
55
59
|
};
|
|
56
60
|
|
|
57
|
-
// With no
|
|
61
|
+
// With no next function, the result passes straight through.
|
|
58
62
|
const saveUser = (input) => {
|
|
59
63
|
const cmdSaveUser = () => db.saveUser(input);
|
|
60
64
|
return Command(cmdSaveUser);
|
|
61
65
|
};
|
|
62
66
|
|
|
67
|
+
// Build the flow. Validation runs now; no I/O happens until runEffect.
|
|
63
68
|
const registerUserFlow = (input) => effectPipe(validateRegistration, ensureEmailAvailable, saveUser)(input);
|
|
64
69
|
|
|
65
70
|
// Imperative shell: this is the only place side effects run
|
|
@@ -92,6 +97,14 @@ assert.equal(step2.cmd.name, 'cmdSaveUser');
|
|
|
92
97
|
// The full flow is verified. The database was never touched.
|
|
93
98
|
```
|
|
94
99
|
|
|
100
|
+
## How It Works
|
|
101
|
+
|
|
102
|
+
A flow is a chain of pairs: an I/O call to make, plus a `next` function that receives its answer and returns whatever comes after, another Command, a Success, or a Failure. `runEffect` walks that chain in a loop.
|
|
103
|
+
|
|
104
|
+
Recording and replay attach at the single point where a Command's function is called: recording wraps that call to write down each answer, and replay substitutes the recorded answer without making the call, which is why a replayed flow performs no I/O.
|
|
105
|
+
|
|
106
|
+
Building a flow runs the pure steps immediately: `registerUserFlow(badInput)` returns the validation `Failure` synchronously, which is why the tests above do not need `runEffect`. Only the I/O inside Commands requires it.
|
|
107
|
+
|
|
95
108
|
## Time-Travel Debugging
|
|
96
109
|
|
|
97
110
|
Record what each Command returned, then feed those results back into the same flow to retrace the exact path a request took, with no database and no network attached.
|
|
@@ -125,10 +138,18 @@ it('prod incident 8f3a: a 100% promo produces a $0 charge', async () => {
|
|
|
125
138
|
});
|
|
126
139
|
```
|
|
127
140
|
|
|
128
|
-
The test verifies that the flow still takes the recorded path and handles the recorded outcomes the same way: a refactor that reorders or drops a step raises a `TimeParadox
|
|
141
|
+
The test verifies that the flow still takes the recorded path and handles the recorded outcomes the same way: a refactor that reorders or drops a step raises a `TimeParadox` naming the path it diverged at, and changed error handling fails the assertion.
|
|
129
142
|
|
|
130
143
|
**Nondeterminism belongs inside a Command.** A value that varies between runs (the current time, a random ID) is I/O as far as replay is concerned. Wrap it in a Command and it is recorded and replayed like any other response; a step that calls `Date.now()` directly computes a fresh value on every replay and silently diverges from the trace.
|
|
131
144
|
|
|
145
|
+
**A determinism check is one round trip.** Record a flow, replay it immediately, and compare the outcomes. A step that computes a fresh nondeterministic value surfaces as a `TimeParadox` when it changes which Commands run, or as a mismatch in the final value:
|
|
146
|
+
|
|
147
|
+
```js
|
|
148
|
+
const { result, trace } = await recordEffect(registerUserFlow, input);
|
|
149
|
+
const replayed = await replayEffect(registerUserFlow(input), trace);
|
|
150
|
+
assert.deepEqual(replayed, result); // fails if any step computed a fresh value
|
|
151
|
+
```
|
|
152
|
+
|
|
132
153
|
**The trace format is yours.** `replayEffect` also takes a resolver function in place of a trace, so OpenTelemetry spans, a log pipeline, or a database table work as well as the JSON that `recorder` produces.
|
|
133
154
|
|
|
134
155
|
```js
|
|
@@ -219,11 +240,25 @@ When all attempts are exhausted, `runEffect` returns a structured `Failure`:
|
|
|
219
240
|
{ retryExhausted: true, lastError: <the last error>, attempts: 3 }
|
|
220
241
|
```
|
|
221
242
|
|
|
222
|
-
|
|
243
|
+
In TypeScript, a `Retry` contributes `RetryExhaustedError<E>` to the pipeline's error union rather than the inner `E` itself, matching what the Failure actually carries: the wrapped tree's error type survives as `result.error.lastError`.
|
|
244
|
+
|
|
245
|
+
**Recover from exhaustion in-flow with `onExhausted`.** When every attempt has failed, the fallback Effect runs instead of returning the structured Failure. Its success feeds the rest of the pipeline exactly as the primary's would have, and its failure propagates unwrapped:
|
|
246
|
+
|
|
247
|
+
```js
|
|
248
|
+
const fetchPrice = (sku) =>
|
|
249
|
+
Retry(fetchLivePrice(sku), {
|
|
250
|
+
attempts: 3,
|
|
251
|
+
onExhausted: (err) => fetchCachedPrice(sku) // err = { retryExhausted, lastError, attempts }
|
|
252
|
+
});
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
Fallback steps are recorded under their own trace paths, so a replay reproduces the fallback exactly, and a fallback never starts in a `Parallel` branch that a sibling's failure has already cancelled. With `onExhausted` set, the exhaustion error never escapes, so in TypeScript the node contributes the fallback's error type to the pipeline's union instead of `RetryExhaustedError<E>`.
|
|
256
|
+
|
|
257
|
+
Every attempt is a recorded step, so a replay reproduces the exact sequence of failures. It also skips the delays.
|
|
223
258
|
|
|
224
259
|
## Running Effects in Parallel
|
|
225
260
|
|
|
226
|
-
`Parallel` runs multiple Effect trees concurrently and passes their results to `next` as an ordered array.
|
|
261
|
+
`Parallel` runs multiple Effect trees concurrently and passes their results to `next` as an ordered array. The first branch to fail cancels its siblings, `next` is not called, and that branch's `Failure` is what propagates.
|
|
227
262
|
|
|
228
263
|
```js
|
|
229
264
|
import { Success, Command, Parallel } from 'pure-effect';
|
|
@@ -232,9 +267,83 @@ const loadProfile = (userId) =>
|
|
|
232
267
|
Parallel([getUser(userId), getPermissions(userId)], ([user, permissions]) => Success({ user, permissions }));
|
|
233
268
|
```
|
|
234
269
|
|
|
270
|
+
`next` is optional, defaulting to `(values) => Success(values)` just like `Command`'s, so a bare `Parallel(effects)` resolves to the ordered array of success values.
|
|
271
|
+
|
|
235
272
|
`Ask` context flows into all parallel branches without any extra wiring.
|
|
236
273
|
|
|
237
|
-
|
|
274
|
+
**Cancellation is cooperative, and it works at two levels.** A cancelled branch starts no further Commands. For example, a three-step branch whose first step is in flight when a sibling fails runs that step and stops. Cancelling the step already in flight needs the function to accept the `AbortSignal` it is handed and pass it to whatever performs the I/O:
|
|
275
|
+
|
|
276
|
+
```js
|
|
277
|
+
// Cancellable: the request is aborted the moment a sibling branch fails.
|
|
278
|
+
const fetchProfile = (userId) => Command((signal) => fetch(`/users/${userId}`, { signal }).then((r) => r.json()));
|
|
279
|
+
|
|
280
|
+
// Not cancellable: this runs to completion even after a sibling fails.
|
|
281
|
+
const fetchProfileUncancellable = (userId) => Command(() => fetch(`/users/${userId}`).then((r) => r.json()));
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Outside a `Parallel` the function is called with no arguments at all, so nothing changes for a Command that never runs in a branch. A `Retry` inside a cancelled branch stops retrying rather than working through the rest of its backoff schedule.
|
|
285
|
+
|
|
286
|
+
## Composing Larger Flows
|
|
287
|
+
|
|
288
|
+
`effectPipe` is a straight line, but flows rarely are. Branching and fan-in work with the existing primitives. Here is how:
|
|
289
|
+
|
|
290
|
+
**A step can return a sub-pipeline.** `effectPipe(...)(value)` returns an Effect like any other, so a step can branch into a whole sub-flow, and the sub-flow's `Failure` short-circuits the outer pipeline exactly like a local one:
|
|
291
|
+
|
|
292
|
+
```js
|
|
293
|
+
const processOrder = (order) => (order.isGift ? giftFlow(order) : standardFlow(order));
|
|
294
|
+
|
|
295
|
+
const fulfillment = effectPipe(validateOrder, processOrder, scheduleShipping);
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
**Independent fan-in: `Parallel`.** When a later step needs several values that do not depend on each other, run them concurrently and join structurally. With `next` omitted, the branch results arrive as an ordered array:
|
|
299
|
+
|
|
300
|
+
```js
|
|
301
|
+
const loadCheckout = effectPipe(
|
|
302
|
+
(input) => Parallel([fetchCart(input.cartId), fetchUser(input.userId)]),
|
|
303
|
+
([cart, user]) => Success({ cart, user, total: cartTotal(cart) })
|
|
304
|
+
);
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
**Dependent fan-in: join locally.** When step B needs step A's result and step C needs both, carry both forward in a value shaped for the next step. A local sub-pipeline that closes over its own parameter makes the join without nested callbacks:
|
|
308
|
+
|
|
309
|
+
```js
|
|
310
|
+
const applyLoyaltyDiscount = (orderId) =>
|
|
311
|
+
effectPipe(
|
|
312
|
+
fetchOrder,
|
|
313
|
+
(order) => effectPipe(fetchCustomer, (customer) => Success({ order, customer }))(order.customerId),
|
|
314
|
+
({ order, customer }) => Success(discountedTotal(order, customer))
|
|
315
|
+
)(orderId);
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
**Carry exactly what downstream needs, never an accumulator.** Passing a minimal, purpose-shaped value between steps, rather than a scope object that grows with everything ever computed, is a strategy for avoiding bugs, not a style preference. Each step's input is its complete contract, so a step cannot quietly depend on a value produced far upstream, a stale field cannot outlive the step that should have replaced it, and two steps cannot collide on a key neither knows the other uses. It also keeps data alive no longer than the flow needs it, which matters when the values are credentials or PII. In TypeScript the same discipline is what keeps the pipeline checked end to end: every step consumes the value it receives, so changing what an upstream step produces is a compile error at exactly the step that reads it, instead of an `undefined` at runtime.
|
|
319
|
+
|
|
320
|
+
## Which Errors Are Data
|
|
321
|
+
|
|
322
|
+
There is no catch combinator, and that is deliberate. A flow's outcomes divide into two kinds, and the division decides how each is written.
|
|
323
|
+
|
|
324
|
+
**An outcome the flow handles is data.** A Command's `next` receives the result and can branch into any Effect, including a whole fallback sub-pipeline. When the I/O itself can reject, catch inside the Command's `cmd` function and return the miss as a value:
|
|
325
|
+
|
|
326
|
+
```js
|
|
327
|
+
const fetchCachedPrice = (sku) => {
|
|
328
|
+
const cmdFetchCachedPrice = () => cache.get(sku);
|
|
329
|
+
return Command(cmdFetchCachedPrice, (price) => Success({ ...price, stale: true }));
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
const fetchPrice = (sku) => {
|
|
333
|
+
const cmdFetchLivePrice = () =>
|
|
334
|
+
pricing
|
|
335
|
+
.get(sku)
|
|
336
|
+
.then((price) => ({ ok: true, price }))
|
|
337
|
+
.catch((error) => ({ ok: false, error }));
|
|
338
|
+
return Command(cmdFetchLivePrice, (r) => (r.ok ? Success({ ...r.price, stale: false }) : fetchCachedPrice(sku)));
|
|
339
|
+
};
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
The failed live attempt is recorded as that Command's result, error included, so a replay takes the same fallback branch and an incident trace still becomes a regression test. Nothing is hidden; the miss is simply categorized as what it is, an outcome the flow was written to handle.
|
|
343
|
+
|
|
344
|
+
**A `Failure` means abort.** It short-circuits everything and lands in the shell, which is the one place that decides what a dead flow means: an HTTP status, a queue retry, an alert. Reserving `Failure` for outcomes the flow cannot handle keeps its meaning brutally simple; a reader never has to scan up the tree for a handler, because there is none. A catch combinator would reintroduce exactly the non-local control flow that writing effects as data is meant to eliminate.
|
|
345
|
+
|
|
346
|
+
The rule of thumb: if you would handle it, return it; if you would only report it, fail with it. The one handled outcome that cannot be modeled as data is retry exhaustion, since the failing happens inside the `Retry` node; that case has its own in-flow form, the `onExhausted` option in [Retrying Transient Failures](#retrying-transient-failures).
|
|
238
347
|
|
|
239
348
|
## TypeScript: Typed Errors and Context
|
|
240
349
|
|
|
@@ -272,9 +381,9 @@ const result = await runEffect(findProduct('abc'), { tenant: 'acme', requestId:
|
|
|
272
381
|
|
|
273
382
|
## Why Pure Effect
|
|
274
383
|
|
|
275
|
-
**vs.
|
|
384
|
+
**vs. Temporal and durable execution (Restate, Inngest):** The closest relatives, because they are built on the same idea: record what every step returned, replay it deterministically. Those engines run it as a managed execution guarantee: histories persist server-side, and workflows resume automatically after a crash. The difference is who operates it. An engine stores histories and restarts dead runs for you; with Pure Effect that is your application's job, and there is no infrastructure to run.
|
|
276
385
|
|
|
277
|
-
**vs.
|
|
386
|
+
**vs. Effect-TS (and fp-ts):** A full functional programming ecosystem with fibers, streaming, schema validation, structured concurrency, and more, though it comes with a steep learning curve and a vocabulary of its own. Pure Effect borrows only the concept of effects as data, and covers a narrower scope: testable pipelines, context injection, retry, parallel execution, and replayable traces. If you need fibers, in-flight cancellation, or streaming, Effect-TS is the right tool.
|
|
278
387
|
|
|
279
388
|
**vs. plain async/await with mocks:** A mock that passes all your tests but diverges from what the real driver does is worse than no test. Business logic never executes I/O, so there is nothing to mock.
|
|
280
389
|
|
|
@@ -296,7 +405,7 @@ Returns `{ type: 'Failure', error, initialInput }`. Stops the pipeline immediate
|
|
|
296
405
|
|
|
297
406
|
Returns `{ type: 'Command', cmd, next, meta }`.
|
|
298
407
|
|
|
299
|
-
- `cmd`: A function (sync or async) that performs the side effect.
|
|
408
|
+
- `cmd`: A function (sync or async) that performs the side effect. Inside a `Parallel` branch it is called with an `AbortSignal` that fires when a sibling branch fails; elsewhere it is called with no arguments.
|
|
300
409
|
- `next`: Receives the result of `cmd` and returns the next Effect. Optional, defaulting to `(result) => Success(result)`, which is what most Commands want.
|
|
301
410
|
- `meta`: Optional metadata, passed to `onBeforeCommand`. A string `meta.name` becomes the Command's identity. Otherwise, the name of the function is used (`cmd.name`).
|
|
302
411
|
|
|
@@ -321,12 +430,13 @@ Returns `{ type: 'Retry', effect, options, next }`.
|
|
|
321
430
|
- `options.attempts`: Max retries, not counting the first try (default: `3`).
|
|
322
431
|
- `options.delay`: Ms before the first retry (default: `100`).
|
|
323
432
|
- `options.backoff`: Multiplier applied to delay on each attempt (default: `1`, flat).
|
|
433
|
+
- `options.onExhausted(error)`: Runs a fallback Effect when every attempt has failed, receiving `{ retryExhausted, lastError, attempts }`. The fallback's success feeds `next`; its failure propagates unwrapped. Per-use only. See [Retrying Transient Failures](#retrying-transient-failures).
|
|
324
434
|
|
|
325
|
-
#### `Parallel(effects, next)`
|
|
435
|
+
#### `Parallel(effects, next?)`
|
|
326
436
|
|
|
327
|
-
Returns `{ type: 'Parallel', effects, next }`. Runs all effects concurrently
|
|
437
|
+
Returns `{ type: 'Parallel', effects, next }`. Runs all effects concurrently. `next` receives the ordered array of success values and is optional, defaulting to `(values) => Success(values)` like `Command`'s. The first branch to fail cancels its siblings and its `Failure` is returned; `next` is not called. When several branches fail in the same tick, the first by array order wins. Each branch's Commands receive an `AbortSignal` as their only argument, so I/O that accepts one is cancelled in flight; see [Running Effects in Parallel](#running-effects-in-parallel).
|
|
328
438
|
|
|
329
|
-
###
|
|
439
|
+
### Building pipelines
|
|
330
440
|
|
|
331
441
|
#### `effectPipe(...functions)`
|
|
332
442
|
|
|
@@ -358,7 +468,7 @@ Commands are data, so a Command that is constructed and discarded never runs, an
|
|
|
358
468
|
|
|
359
469
|
Traverses the effect tree, executes Commands with `async/await`, resolves `Ask` with the supplied `context`, and returns the final `Success` or `Failure`.
|
|
360
470
|
|
|
361
|
-
- `context`: Passed to `Ask`
|
|
471
|
+
- `context`: Passed to `Ask`'s next function and to `onBeforeCommand`. `context.flowName` names the workflow in telemetry.
|
|
362
472
|
- `callConfig`: Per-call overrides for `onStep`, `onRun`, `onBeforeCommand`, and `retry`. Takes precedence over `configureEffect` globals.
|
|
363
473
|
- `onRun` fires exactly once per `runEffect` call. Retry attempts run inside that single span.
|
|
364
474
|
|
|
@@ -369,7 +479,7 @@ Step 'validateRegistration' returned a plain object. Return Success, Failure, Co
|
|
|
369
479
|
Retry, or Parallel: a plain value has to be wrapped, as in Success(value).
|
|
370
480
|
```
|
|
371
481
|
|
|
372
|
-
The same check catches a missing `return`, a Command
|
|
482
|
+
The same check catches a missing `return`, a Command's next function returning a plain value, and `runEffect(flow)` where `runEffect(flow(input))` was meant. A Command that throws is still a `Failure`.
|
|
373
483
|
|
|
374
484
|
#### `configureEffect(...configs)`
|
|
375
485
|
|
|
@@ -404,7 +514,7 @@ restore();
|
|
|
404
514
|
|
|
405
515
|
Returns `{ onStep, entries, toTrace }`. Pass `onStep` to `runEffect` or `configureEffect` to record what every Command returned.
|
|
406
516
|
|
|
407
|
-
Each entry is `{ command, result, durationMs }`, or `{ command, error, durationMs }` when the Command threw, so a trace also answers which step was slow. Results are snapshotted on capture, so a later step that mutates a returned object cannot rewrite what the trace says an earlier step saw. Values that cannot be structurally cloned, such as an object holding a function, are stored by reference instead. Recording cannot change a run: a `redact` that throws records `'[redaction failed]'` for that step instead of failing the flow.
|
|
517
|
+
Each entry is `{ command, path, result, durationMs }`, or `{ command, path, error, durationMs }` when the Command threw, so a trace also answers which step was slow. `path` is the Command's position in the Effect tree, which is what a replay matches on. Results are snapshotted on capture, so a later step that mutates a returned object cannot rewrite what the trace says an earlier step saw. Values that cannot be structurally cloned, such as an object holding a function, are stored by reference instead. Recording cannot change a run: a `redact` that throws records `'[redaction failed]'` for that step instead of failing the flow.
|
|
408
518
|
|
|
409
519
|
- `options.redact(value, name, kind)`: The single place PII is kept out of a trace. It sees every value a trace holds, with `kind` distinguishing them:
|
|
410
520
|
|
|
@@ -433,7 +543,6 @@ Runs a flow for real while recording, returning `{ result, trace }`. Accepts `re
|
|
|
433
543
|
Replays an effect tree, feeding recorded results to Commands instead of running them.
|
|
434
544
|
|
|
435
545
|
- `traceOrResolver`: a trace (or bare entries array) to replay directly, or a resolver function for traces stored in some other shape. A resolver returns `{ result }`, `{ error }`, or `undefined` if the step is unrecorded. A malformed trace rejects with a `ReplayError`.
|
|
436
|
-
- `options.strict` (default `true`): consume trace entries in recorded order and raise `TimeParadox` if the flow asks for a different Command. Set `false` for flows containing `Parallel`, whose branches complete out of array order, to match per-Command queues instead of positions. Ignored when a resolver was passed, since it already matches its own way.
|
|
437
546
|
- `options.context`: context for `Ask`; pass the recorded context.
|
|
438
547
|
- `options.onMissing`: `'throw'` (default) fails on an unrecorded step; `'execute'` runs the real Command, giving a recorded prefix with a live tail.
|
|
439
548
|
- `options.fastRetry` (default `true`): strip `Retry` delays.
|
|
@@ -442,14 +551,14 @@ Replays an effect tree, feeding recorded results to Commands instead of running
|
|
|
442
551
|
|
|
443
552
|
#### `timeTravel(flowFn, traceLog, options?)`
|
|
444
553
|
|
|
445
|
-
Replays a trace and narrates each step with its recorded duration, warning when recorded steps were never reached or when the trace's `version` differs from `options.version`.
|
|
554
|
+
Replays a trace and narrates each step with its recorded duration, warning when recorded steps were never reached or when the trace's `version` differs from `options.version`. Takes `options.context` to override the trace's, and `options.log` in place of `console.log`.
|
|
446
555
|
|
|
447
556
|
## Limitations
|
|
448
557
|
|
|
449
558
|
- **`Retry` repeats the whole wrapped tree.** Commands that already succeeded run again on every attempt, so wrapping a pipeline re-executes its side effects. Wrap the single Command that fails transiently unless every Command in the tree is idempotent.
|
|
450
|
-
- **`Parallel`
|
|
559
|
+
- **`Parallel` cancellation is cooperative, so it cannot stop everything.** A cancelled branch starts no further Commands, and a function that accepts the `AbortSignal` it is passed can be cut off in flight. A function that ignores the signal cannot: it runs to completion, so a branch whose _first_ Command is a write can still write after a sibling has failed. `Parallel` also waits for every branch to settle before returning, deliberately, so no cancelled work is left running unobserved after the `Failure` is returned.
|
|
451
560
|
- **A `Failure` is complete by design.** It carries the full error and the `initialInput` that `effectPipe` stamped on it, and neither is trimmed, because a test asserting on a Failure and a developer debugging one both need everything. Keeping PII out of a **trace** is `redact`'s job. Keeping it out of your **logs** is the shell's: log `result.error` rather than serializing the whole `Failure`, which for a login or registration flow holds the credentials that flow received.
|
|
452
|
-
- **Replay reproduces observed inputs, not concurrency.** A stale read replays exactly. A race between two concurrent requests does not: a trace records one flow's view
|
|
561
|
+
- **Replay reproduces observed inputs, not concurrency.** A stale read replays exactly. A race between two concurrent requests does not: a trace records one flow's view. `Parallel` branches replay with the results their own branch saw, since every step is matched by its position in the tree, but the interleaving between them is not reproduced, so a flow whose branches race each other through shared state is not something a replay can settle.
|
|
453
562
|
- **A trace records responses, not requests.** Command arguments live in a closure and are unreachable, so a trace shows what a call returned but not what was passed to it. This also bounds what a replay verifies: the flow's path and its handling of recorded outcomes. The upside is that arguments can never leak into a trace.
|
|
454
563
|
- **Global configuration is per module instance.** `configureEffect` writes to module-level state, so two copies of the library in one process, from a dual ESM and CJS resolution, two versions in a dependency tree, or a worker thread, each carry their own wiring. Code that configures one gets nothing in the other, with no error.
|
|
455
564
|
- **A Command needs an identity.** `meta.name` is stable under minification; relying on `cmd.name` instead means a mangler renames every step of every trace, so mangling has to be disabled or names preserved.
|
package/index.d.ts
CHANGED
|
@@ -19,7 +19,14 @@ export type CommandMeta = { name?: string } & Record<string, unknown>;
|
|
|
19
19
|
|
|
20
20
|
export type CommandState<R, T, E = unknown, Ctx = unknown> = {
|
|
21
21
|
type: 'Command';
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Performs the side effect. Inside a `Parallel` branch it receives an `AbortSignal` that fires when a
|
|
24
|
+
* sibling branch fails; forward it to `fetch`, a driver, or an `AbortController`-aware client to have
|
|
25
|
+
* the work cancelled in flight. Ignoring it is fine and is what every thunk written before this did:
|
|
26
|
+
* the interpreter still refuses to start any *later* Command in a cancelled branch. Outside a
|
|
27
|
+
* `Parallel` no argument is passed at all.
|
|
28
|
+
*/
|
|
29
|
+
cmd: (signal?: AbortSignal) => Promise<R> | R;
|
|
23
30
|
next: (result: R) => Effect<T, E, Ctx>;
|
|
24
31
|
meta?: CommandMeta;
|
|
25
32
|
initialInput?: unknown;
|
|
@@ -37,10 +44,15 @@ export type RetryOptions = {
|
|
|
37
44
|
backoff?: number;
|
|
38
45
|
};
|
|
39
46
|
|
|
47
|
+
/**
|
|
48
|
+
* `E` is the error the node contributes to its pipeline, which for a Retry is the exhaustion failure:
|
|
49
|
+
* the interpreter never lets an inner attempt's error escape unwrapped, so the wrapped tree's own
|
|
50
|
+
* error type is consumed by the retry loop rather than exposed here.
|
|
51
|
+
*/
|
|
40
52
|
export type RetryState<T, E = unknown, Ctx = unknown> = {
|
|
41
53
|
type: 'Retry';
|
|
42
|
-
effect: Effect<T,
|
|
43
|
-
options: RetryOptions;
|
|
54
|
+
effect: Effect<T, any, Ctx>;
|
|
55
|
+
options: RetryOptions & { onExhausted?: (error: RetryExhaustedError<any>) => Effect<T, any, Ctx> };
|
|
44
56
|
next: (value: T) => Effect<T, E, Ctx>;
|
|
45
57
|
initialInput?: unknown;
|
|
46
58
|
};
|
|
@@ -77,7 +89,7 @@ export declare function Failure<E = unknown>(error: E, initialInput?: unknown):
|
|
|
77
89
|
* and immune to minification. Without one the identity falls back to `cmd.name`, then to 'anonymous'.
|
|
78
90
|
*/
|
|
79
91
|
export declare function Command<R, T = R, E = unknown, Ctx = unknown>(
|
|
80
|
-
cmd: () => Promise<R> | R,
|
|
92
|
+
cmd: (signal?: AbortSignal) => Promise<R> | R,
|
|
81
93
|
next?: (result: R) => Effect<T, E, Ctx>,
|
|
82
94
|
meta?: CommandMeta
|
|
83
95
|
): CommandState<R, T, E, Ctx>;
|
|
@@ -86,10 +98,35 @@ export declare function Ask<T, E = unknown, Ctx = unknown>(
|
|
|
86
98
|
next: (context: Ctx) => Effect<T, E, Ctx>
|
|
87
99
|
): AskState<T, E, Ctx>;
|
|
88
100
|
|
|
101
|
+
/**
|
|
102
|
+
* With `onExhausted`, the exhaustion failure never escapes: the fallback Effect runs instead, its
|
|
103
|
+
* success feeds `next`, and its failure propagates unwrapped, so the node's declared error is the
|
|
104
|
+
* fallback's own error type. `onExhausted` is a per-use option only; the global `retry` defaults in
|
|
105
|
+
* `EffectConfiguration` deliberately cannot carry one.
|
|
106
|
+
*/
|
|
107
|
+
export declare function Retry<T, E = unknown, E2 = unknown, Ctx = unknown>(
|
|
108
|
+
effect: Effect<T, E, Ctx>,
|
|
109
|
+
options: RetryOptions & { onExhausted: (error: RetryExhaustedError<E>) => Effect<T, E2, Ctx> }
|
|
110
|
+
): RetryState<T, E2, Ctx>;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Without `onExhausted`, the declared error type is `RetryExhaustedError<E>`, because that is what
|
|
114
|
+
* a Retry's Failure actually carries: on exhaustion the interpreter returns
|
|
115
|
+
* `Failure({ retryExhausted: true, lastError, attempts })` rather than the inner error itself,
|
|
116
|
+
* so `result.error.lastError` is where the wrapped tree's `E` survives.
|
|
117
|
+
*/
|
|
89
118
|
export declare function Retry<T, E = unknown, Ctx = unknown>(
|
|
90
119
|
effect: Effect<T, E, Ctx>,
|
|
91
120
|
options?: RetryOptions
|
|
92
|
-
): RetryState<T, E
|
|
121
|
+
): RetryState<T, RetryExhaustedError<E>, Ctx>;
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* `next` is optional and defaults to `(values) => Success(values)`, same as `Command`'s default,
|
|
125
|
+
* so a bare `Parallel(effects)` resolves to the ordered array of success values.
|
|
126
|
+
*/
|
|
127
|
+
export declare function Parallel<T extends readonly unknown[], E = unknown, Ctx = unknown>(effects: {
|
|
128
|
+
[K in keyof T]: Effect<T[K], E, Ctx>;
|
|
129
|
+
}): ParallelState<[...T], [...T], E, Ctx>;
|
|
93
130
|
|
|
94
131
|
export declare function Parallel<T extends readonly unknown[], R, E = unknown, Ctx = unknown>(
|
|
95
132
|
effects: { [K in keyof T]: Effect<T[K], E, Ctx> },
|
|
@@ -231,7 +268,12 @@ export declare function effectPipe<
|
|
|
231
268
|
f8: (i: I) => Effect<J, E8, Ctx>
|
|
232
269
|
): (start: A) => Effect<J, E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8, Ctx>;
|
|
233
270
|
|
|
234
|
-
|
|
271
|
+
/**
|
|
272
|
+
* Wraps one Command execution. `path` is the Command's position in the Effect tree rather than its
|
|
273
|
+
* position in completion order, so it is the same in a replay as in the recorded run even when
|
|
274
|
+
* `Parallel` branches finish in a different order. Hooks that take three parameters are unaffected.
|
|
275
|
+
*/
|
|
276
|
+
export type StepRunner = (name: string, type: string, op: () => Promise<unknown>, path?: string) => Promise<unknown>;
|
|
235
277
|
|
|
236
278
|
export type RunWrapper = (
|
|
237
279
|
effect: Effect<unknown>,
|
|
@@ -268,12 +310,21 @@ export declare function runEffect<T, E = unknown, Ctx = unknown>(
|
|
|
268
310
|
): Promise<SuccessState<T> | FailureState<E>>;
|
|
269
311
|
|
|
270
312
|
export type ReplayStep = {
|
|
271
|
-
/**
|
|
313
|
+
/**
|
|
314
|
+
* Zero-based position in this run's completion order. Not stable for a flow containing `Parallel`,
|
|
315
|
+
* whose branches finish in whatever order they finish in. Prefer `path`.
|
|
316
|
+
*/
|
|
272
317
|
index: number;
|
|
273
318
|
/** `cmd.name`, or 'anonymous'. */
|
|
274
319
|
name: string;
|
|
275
320
|
/** Always 'Command' today; reserved. */
|
|
276
321
|
type: string;
|
|
322
|
+
/**
|
|
323
|
+
* The Command's position in the Effect tree, stable across runs: steps are numbered within a
|
|
324
|
+
* subtree, and each `Parallel` branch and `Retry` attempt opens its own prefix. This is what a
|
|
325
|
+
* replay matches on, and what a Resolver should key off. Absent on traces recorded before paths.
|
|
326
|
+
*/
|
|
327
|
+
path?: string;
|
|
277
328
|
};
|
|
278
329
|
|
|
279
330
|
/**
|
|
@@ -287,6 +338,11 @@ export type Resolver = (step: ReplayStep) => ReplayOutcome | undefined;
|
|
|
287
338
|
|
|
288
339
|
export type TraceEntry = {
|
|
289
340
|
command: string;
|
|
341
|
+
/**
|
|
342
|
+
* The Command's position in the Effect tree. Order-independent, so a replay lines a recorded step
|
|
343
|
+
* up with the step that asked for it even when `Parallel` branches finish out of order.
|
|
344
|
+
*/
|
|
345
|
+
path?: string;
|
|
290
346
|
result?: unknown;
|
|
291
347
|
error?: unknown;
|
|
292
348
|
/** How long the Command took in production, rounded to microseconds. */
|
|
@@ -351,11 +407,11 @@ export interface ReplayOptions<Ctx = unknown> {
|
|
|
351
407
|
onMissing?: 'throw' | 'execute';
|
|
352
408
|
onResolved?: (step: ReplayStep, outcome: ReplayOutcome | undefined) => void;
|
|
353
409
|
/**
|
|
354
|
-
*
|
|
355
|
-
* consumes entries positionally and raises a `TimeParadox` on divergence; `false`
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
*
|
|
410
|
+
* Legacy matching mode, used only for a trace whose entries carry no `path`. `true` (default)
|
|
411
|
+
* consumes entries positionally and raises a `TimeParadox` on divergence; `false` matches
|
|
412
|
+
* per-Command FIFO queues, which used to be required for flows containing `Parallel`. Ignored
|
|
413
|
+
* for a trace carrying paths, which is matched by path, and when a Resolver is supplied, since
|
|
414
|
+
* that Resolver has already chosen how it matches.
|
|
359
415
|
*/
|
|
360
416
|
strict?: boolean;
|
|
361
417
|
}
|