pure-effect 0.12.0 → 0.14.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/CHANGELOG.md +192 -0
- package/README.md +328 -121
- package/index.d.ts +1129 -138
- package/index.js +757 -207
- package/package.json +32 -2
- package/.prettierrc +0 -12
- package/CLAUDE.md +0 -205
- package/examples/opentelemetry-example.js +0 -164
- package/examples/recording-example.js +0 -104
- package/jsconfig.json +0 -13
- package/test/all.js +0 -2446
- package/test/types.test-d.ts +0 -335
package/package.json
CHANGED
|
@@ -1,25 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pure-effect",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "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.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"effect",
|
|
7
|
+
"effect-system",
|
|
8
|
+
"functional-core",
|
|
9
|
+
"imperative-shell",
|
|
10
|
+
"time-travel",
|
|
11
|
+
"replay",
|
|
12
|
+
"tracing",
|
|
13
|
+
"testing",
|
|
14
|
+
"zero-dependencies",
|
|
15
|
+
"typescript"
|
|
16
|
+
],
|
|
5
17
|
"type": "module",
|
|
6
18
|
"exports": "./index.js",
|
|
7
19
|
"types": "./index.d.ts",
|
|
20
|
+
"files": [
|
|
21
|
+
"index.js",
|
|
22
|
+
"index.d.ts",
|
|
23
|
+
"CHANGELOG.md"
|
|
24
|
+
],
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=18"
|
|
28
|
+
},
|
|
8
29
|
"scripts": {
|
|
9
30
|
"test": "mocha && tsd && tsc -p jsconfig.json",
|
|
10
|
-
"format": "prettier --write index.js index.d.ts examples/*.js test/all.js test/types.test-d.ts README.md CLAUDE.md"
|
|
31
|
+
"format": "prettier --write index.js index.d.ts examples/*.js test/all.js test/types.test-d.ts README.md CLAUDE.md CHANGELOG.md CONTRIBUTING.md"
|
|
11
32
|
},
|
|
12
33
|
"tsd": {
|
|
13
34
|
"directory": "test"
|
|
14
35
|
},
|
|
15
36
|
"author": "Aycan Gulez",
|
|
16
37
|
"homepage": "https://pure-effect.org",
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/aycangulez/pure-effect.git"
|
|
41
|
+
},
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/aycangulez/pure-effect/issues"
|
|
44
|
+
},
|
|
17
45
|
"license": "MIT",
|
|
18
46
|
"devDependencies": {
|
|
19
47
|
"@opentelemetry/api": "^1.9.1",
|
|
20
48
|
"@opentelemetry/exporter-trace-otlp-proto": "^0.221.0",
|
|
21
49
|
"@opentelemetry/sdk-node": "^0.221.0",
|
|
22
50
|
"@opentelemetry/sdk-trace-base": "^2.10.0",
|
|
51
|
+
"@stryker-mutator/core": "^10.0.0",
|
|
52
|
+
"@stryker-mutator/mocha-runner": "^10.0.0",
|
|
23
53
|
"@types/mocha": "^10.0.10",
|
|
24
54
|
"@types/node": "^24.10.1",
|
|
25
55
|
"mocha": "^11.3.0",
|
package/.prettierrc
DELETED
package/CLAUDE.md
DELETED
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
# CLAUDE.md
|
|
2
|
-
|
|
3
|
-
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
4
|
-
|
|
5
|
-
## Commands
|
|
6
|
-
|
|
7
|
-
```bash
|
|
8
|
-
npm test # run all tests
|
|
9
|
-
npx mocha test/all.js --grep "pattern" # run a single test by name
|
|
10
|
-
npm run format # Prettier over index.js, index.d.ts, examples/*.js, test/all.js, test/types.test-d.ts, README.md, CLAUDE.md
|
|
11
|
-
npx tsd # type-level gate over test/types.test-d.ts
|
|
12
|
-
npx tsc -p jsconfig.json # strict tsc over index.js, test/all.js, test/types.test-d.ts, and examples/*.js, reading index.d.ts as a consumer; the same config VS Code uses
|
|
13
|
-
npx esbuild index.js --minify --format=esm | gzip -9 | wc -c # the size the README claims
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
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.
|
|
17
|
-
|
|
18
|
-
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.
|
|
19
|
-
|
|
20
|
-
**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.
|
|
21
|
-
|
|
22
|
-
**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.
|
|
23
|
-
|
|
24
|
-
**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`.
|
|
25
|
-
|
|
26
|
-
## Architecture
|
|
27
|
-
|
|
28
|
-
**pure-effect** is a zero-dependency effect system for JavaScript implementing the "Functional Core, Imperative Shell" pattern. Business logic returns plain data structures instead of executing side effects, enabling testing without mocks. The same property makes runs recordable and replayable: because a flow is inert data until the interpreter walks it, a recorded run can be fed back through the interpreter with no I/O at all.
|
|
29
|
-
|
|
30
|
-
### Core abstractions (all in `index.js`)
|
|
31
|
-
|
|
32
|
-
| Export | Shape | Purpose |
|
|
33
|
-
| --- | --- | --- |
|
|
34
|
-
| `Success(value)` | `{ type: 'Success', value }` | Wraps a successful result |
|
|
35
|
-
| `Failure(error, initialInput)` | `{ type: 'Failure', error, initialInput }` | Short-circuits the pipeline |
|
|
36
|
-
| `Command(cmdFn, nextFn, meta)` | `{ type: 'Command', cmd, next, meta }` | Defers a side effect for the interpreter; `meta.name` sets the Command's identity |
|
|
37
|
-
| `Ask(nextFn)` | `{ type: 'Ask', next }` | Reads the `context` passed to `runEffect`; passes it to `nextFn` |
|
|
38
|
-
| `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 |
|
|
39
|
-
| `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 |
|
|
40
|
-
| `effectPipe(...fns)` | n/a | Composes functions into a sequential pipeline via `chain` |
|
|
41
|
-
| `runEffect(effect, context, callConfig?)` | async | Interpreter: traverses the effect tree, executes Commands; resolves `Ask` and `Retry`; per-call `callConfig` overrides global defaults |
|
|
42
|
-
| `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` |
|
|
43
|
-
|
|
44
|
-
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.
|
|
45
|
-
|
|
46
|
-
`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.
|
|
47
|
-
|
|
48
|
-
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.
|
|
49
|
-
|
|
50
|
-
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, 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.
|
|
51
|
-
|
|
52
|
-
Anything that is not an Effect is rejected by `asEffect` / `effectTypeError` with a message naming its source, and the distinction they encode is deliberate: a malformed flow is a bug and throws, while a Command that rejects is a domain outcome and becomes a `Failure`. The interpreter's catch rethrows `EffectTypeError` specifically so a flow bug cannot masquerade as a business error. Two details are important. `chain` validates the return of each pipeline step, which is the only place the offending step's name is known (`fn.name`), so that is where the useful message comes from. And the interpreter's `while` condition guards on `eff &&` before reading `eff.type`, because a continuation returning `undefined` otherwise threw a bare TypeError from the condition itself, outside any handler.
|
|
53
|
-
|
|
54
|
-
Before this, every one of those mistakes was silent or cryptic: forgetting `Success()` gave `Cannot read properties of undefined (reading 'type')` with no step named, a continuation returning a plain value made `runEffect` resolve to that value so `result.type === 'Success'` quietly took the else branch, and `runEffect(flow)` without an input resolved to the function itself.
|
|
55
|
-
|
|
56
|
-
### Recording and replay (all in `index.js`)
|
|
57
|
-
|
|
58
|
-
| Export | Purpose |
|
|
59
|
-
| --- | --- |
|
|
60
|
-
| `recorder(options?)` | Returns `{ onStep, entries, toTrace }`; the `onStep` hook records every Command's result or error. Options: `redact`, `maxEntries`, `stack` |
|
|
61
|
-
| `recordEffect(flowFn, initialInput, opts?)` | Runs a flow for real while recording; returns `{ result, trace }`. Convenience for tests and scripts |
|
|
62
|
-
| `replayEffect(effect, traceOrResolver, opts?)` | Replays a tree, feeding recorded outcomes to Commands instead of executing them. Takes a trace or a `Resolver`; returns `{ result, unreached }` for a trace and `{ result }` for a `Resolver`. Options: `context`, `fastRetry`, `hooks`, `onMissing`, `onResolved` |
|
|
63
|
-
| `timeTravel(flowFn, traceLog, options?)` | Narrated replay: rebuilds the flow from the recorded input, logs each step, warns on version mismatch and names any unreached steps; returns the bare outcome, since narration is its job |
|
|
64
|
-
|
|
65
|
-
`fromTrace(traceLog, { onEntry })`, which builds a `Resolver` over the reference trace format, is **internal**, and `replayEffect` is its only caller. Deliberately not exported: a caller whose traces live in another shape writes a `Resolver` instead, and a caller who only wants to watch a replay uses `onResolved`. The `onEntry` observer is how `replayEffect` learns which entries were handed out; it subtracts those from the trace after the run to produce `unreached`, which is why that field exists for a trace and is absent for a `Resolver`. Between them those cover every known need, so exporting it would only widen the public surface. The one thing neither covers is _rewriting_ outcomes from a reference-format trace (substituting one step's result, or chaining a fallback), since `onResolved` is an observer whose return value is ignored. Export it again if that comes up; nothing depends on it staying private.
|
|
66
|
-
|
|
67
|
-
See **Time-travel debugging** below for the invariants these depend on, and the README for each option in full.
|
|
68
|
-
|
|
69
|
-
### Data flow
|
|
70
|
-
|
|
71
|
-
```
|
|
72
|
-
effectPipe(f1, f2, f3)(input)
|
|
73
|
-
→ returns tree of Success / Failure / Command / Ask / Retry / Parallel values
|
|
74
|
-
→ f1 runs eagerly here; initialInput is threaded through chain so every
|
|
75
|
-
node in the tree carries it without post-construction mutation
|
|
76
|
-
|
|
77
|
-
runEffect(tree, context, callConfig?)
|
|
78
|
-
→ per-call callConfig merges over global configureEffect defaults
|
|
79
|
-
→ executes Commands async, passes results into next(result), repeats
|
|
80
|
-
→ resolves Ask by calling next(context), continues
|
|
81
|
-
→ resolves Retry via an inner execute() loop (not recursive runEffect),
|
|
82
|
-
so onRun fires exactly once per runEffect call regardless of attempts;
|
|
83
|
-
on exhaustion returns Failure({ retryExhausted: true, lastError, attempts }),
|
|
84
|
-
unless a per-use onExhausted returns a fallback Effect: it executes under the
|
|
85
|
-
retry's `f` path prefix, its success feeds next, its failure propagates
|
|
86
|
-
unwrapped, and a cancelled Parallel branch skips it
|
|
87
|
-
→ resolves Parallel by running all effects via Promise.all with the same
|
|
88
|
-
context; if any effect returns Failure, returns the first Failure by
|
|
89
|
-
array index and skips next; otherwise calls next with the array of
|
|
90
|
-
unwrapped success values
|
|
91
|
-
→ resolves to final Success or Failure
|
|
92
|
-
|
|
93
|
-
replayEffect(tree, traceOrResolver, options?)
|
|
94
|
-
→ a trace goes through fromTrace(trace, { onEntry }); a function is used as the
|
|
95
|
-
Resolver as-is (typeof check: an entries array is data, so it takes the
|
|
96
|
-
trace path); a malformed trace rejects with a ReplayError
|
|
97
|
-
→ installs an onStep that answers each step from resolve(step) instead of
|
|
98
|
-
calling op(), so eff.cmd is never applied and its I/O never happens
|
|
99
|
-
→ { result } → handed to the Command's next(result)
|
|
100
|
-
→ { error } → thrown, so the interpreter produces a Failure
|
|
101
|
-
→ undefined → throws a ReplayError unless onMissing: 'execute'
|
|
102
|
-
→ otherwise delegates to runEffect, so Ask / Retry / Parallel behave
|
|
103
|
-
exactly as they do in production
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
The `chain` combinator (internal) drives composition: `Success` passes its value to the next function, `Failure` short-circuits, `Command` defers execution, `Ask` wraps its continuation so the chain propagates through it, `Retry` wraps its continuation via object spread (same pattern as `Ask`). `chain` accepts an optional `initialInput` parameter; `effectPipe` passes the pipeline's starting value through every `chain` call so that `initialInput` is stamped on all nodes, including mid-pipeline `Failure`s, without mutation. `runEffect` loops through the tree with a `while` loop rather than recursion.
|
|
107
|
-
|
|
108
|
-
`configureEffect` options (all overridable per-call via `runEffect`'s third argument):
|
|
109
|
-
|
|
110
|
-
- `onStep`: fires on every Command execution; wraps the `cmd` call (use for per-command tracing)
|
|
111
|
-
- `onRun`: fires once per `runEffect` call; wraps the whole workflow (use for top-level spans); receives `context.flowName` as the third argument; does **not** fire again for Retry attempts
|
|
112
|
-
- `onBeforeCommand`: intercepts each Command before execution; receives the Command and the `context` passed to `runEffect`
|
|
113
|
-
- `retry`: global Retry defaults `{ attempts, delay, backoff }`; per-use options passed to `Retry(effect, options)` merge on top (defaults: `attempts: 3`, `delay: 100ms`, `backoff: 1` flat)
|
|
114
|
-
|
|
115
|
-
There is one slot per hook, and `configureEffect` merges the configurations of a single call but does not accumulate across calls: a later call replaces the previous wiring, an unset key returns that slot to its default, and calling it with nothing resets everything. A per-call `callConfig.onStep` likewise displaces the global one for that run, which is why `recordEffect` records without tracing. Recording and tracing both want `onStep`, so they go into one call: `configureEffect(telemetryHooks(), recordingHooks({ sink }))`. Anything that installs hooks on a caller's behalf will silently clobber whatever was there, which is why recording is a reference file rather than a library export. Note the asymmetry: `runEffect`'s third argument takes a single configuration, so merging is only available on the global path. That was the accepted cost of folding the merge into `configureEffect` rather than exporting it.
|
|
116
|
-
|
|
117
|
-
The raw hooks are powerful: a hook decides whether the Command runs at all, which is how replay suppresses I/O, and anything it throws becomes the flow's outcome. That power is wrong for anything that only watches, and it caused two real bugs here: the tracing example serialized its input before calling `pipeline()`, so a cyclic input left flows unexecuted, and `recorder` let a throwing `redact` turn a successful run into a `Failure` carrying the redaction bug while recording an entry that claimed the Command had thrown. The internal `observeSteps(handler)` now holds that contract in one place: `op` always runs, its result is always returned, its error always propagates, and anything the observer throws is dropped. Keep it minimal and unexported. `recorder` is its only caller and needs only `onStep`, so there is no `onRun` branch and no error-reporting channel, and an exported second route to the raw hooks would widen the surface for integrations nobody has written. It briefly was exported, as `observe`, with both branches; that cost 270 bytes gzipped for one internal call site and no consumer, which is the same argument that removed `tap`.
|
|
118
|
-
|
|
119
|
-
Trace entries carry `durationMs`, rounded to microseconds, because `observeSteps` measures the span around `op` anyway and nothing else recorded timings. `timeTravel` narrates it, looking the entry up by path, or by position for a trace that carries none.
|
|
120
|
-
|
|
121
|
-
`configureEffect` returns a function that restores the wiring in place when it was called, captured as a snapshot of the resolved runners rather than of the options, and it reverts only while that wiring is still installed. The guard matters because the first version reverted unconditionally: two callers installing and releasing in interleaved order silently discarded each other's hooks, which is the same class of silent clobbering the restore function was added to prevent. It exists because the global was otherwise write-only: there is no getter, so anything that installed hooks clobbered its host permanently and could not put things back, which made the global unusable from a test, a scoped experiment, or a library wrapping this one. Restoring is a snapshot and not a stack, so a restore that runs after a later `configureEffect` reverts to the older wiring and discards the newer one. The two are not interchangeable: `restore()` returns to whatever was installed before, while a bare `configureEffect()` asserts a known-clean slate. Suites here want the clean slate, so they reset; `restore()` is for code that installs hooks over someone else's wiring and has to hand it back.
|
|
122
|
-
|
|
123
|
-
That global state is also why the test suite needs care. Hooks outlive a suite, so every `describe` that could inherit another's wiring guards with `beforeEach`. The `Core` suite went unguarded for a while and was safe only because it is declared first, which is positional luck rather than isolation: a suite added above it, or a future split into several files, would silently change what it runs with.
|
|
124
|
-
|
|
125
|
-
The internal `chainHooks` does that merging, and it relies on `onStep` and `onRun` being wrappers around an `op`: nesting them composes, with the first configuration outermost, so a thrown Command unwinds from the last back to the first. `onBeforeCommand` is an observer, so interceptors run in sequence instead. Keep those semantics if the hook shapes ever change. It was briefly exported; folding it into `configureEffect` removed an export and reads better at the call site, since a merge is only ever useful on the way into a configuration.
|
|
126
|
-
|
|
127
|
-
### Sharp edges pinned by tests
|
|
128
|
-
|
|
129
|
-
Three semantics are surprising enough that `Documented sharp edges` in the test suite exists to keep them from changing silently, and each has a Limitations entry.
|
|
130
|
-
|
|
131
|
-
`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.
|
|
132
|
-
|
|
133
|
-
`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.
|
|
134
|
-
|
|
135
|
-
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.
|
|
136
|
-
|
|
137
|
-
`redact` therefore has to see everything a trace holds, and for a while it did not. It covered Command results only, so a caller who installed a correct redact still shipped `initialInput` verbatim, the `context` verbatim, and any custom property on a thrown error: in the registration flow that is the plaintext password in two places and the auth token in a third. It now receives results, serialized errors, and the trace's own `initialInput` and `context`, with a `kind` argument of `'result'`, `'error'`, `'initialInput'`, or `'context'` to tell them apart. Keep that coverage complete if the trace format grows another field, since a field redact cannot see is a field that leaks. An absent `initialInput` or `context` is left `undefined` rather than passed through, so a redact that spreads its argument cannot turn nothing into an empty object.
|
|
138
|
-
|
|
139
|
-
### Time-travel debugging
|
|
140
|
-
|
|
141
|
-
Because a flow is data, a production run can be recorded and replayed later. Recording is just an `onStep` hook, so it needs no change at call sites: install `recorder().onStep` via `configureEffect`, or pass it as per-call config. It shares the slot with tracing, so pass both configurations to one `configureEffect` call when both are wanted. `recordEffect` is the convenience wrapper for tests and scripts.
|
|
142
|
-
|
|
143
|
-
Four invariants hold the design together; breaking any of them breaks replay in a way tests may not catch:
|
|
144
|
-
|
|
145
|
-
- **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.
|
|
146
|
-
- **Path matching, with positional matching for traces that carry no paths.** 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. Duplicate paths throw, since a collision would reintroduce the failure paths exist to prevent. A trace whose entries carry no path (recorded before paths existed, or written by hand) is consumed positionally, each entry checked against the Command the flow asks for; exact for sequential flows, and unable to tell `Parallel` branches apart. There is no matching option any more. `strict` used to choose between that positional mode and a per-Command name-queue mode, which was the only way to replay `Parallel` before paths, and **the name-queue mode was 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`. Once paths made it unnecessary the option was removed rather than left as a footgun; a `Resolver` remains the way to match by any other rule. The positional resolver refuses a step whose path shows it is inside a `Parallel` (a `p` segment), with a `ReplayError` that says to add paths, because a positional answer there would be right only when the replay happened to finish in production's order, and silently wrong otherwise.
|
|
147
|
-
|
|
148
|
-
- **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`.
|
|
149
|
-
- **`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.
|
|
150
|
-
- **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.
|
|
151
|
-
|
|
152
|
-
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. `reviveError` defines `name` and `cause` as non-enumerable own properties, matching where a native Error keeps them, because the README's determinism check is `assert.deepEqual(replayed, result)` and Node compares own enumerable keys: assigning `e.name = ...` made every revived error carry an extra key and the check failed for every `Failure` while passing for every `Success`, which is exactly the half of the check that matters. A subclass instance still revives as a plain `Error` (the trace carries a name, not a prototype), so the check is documented as holding for plain errors.
|
|
153
|
-
|
|
154
|
-
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.
|
|
155
|
-
|
|
156
|
-
`TraceLog` is the reference trace format, not a contract: `replayEffect` also takes a `Resolver`, so any storage shape works by writing one.
|
|
157
|
-
|
|
158
|
-
`timeTravel` narrates through `replayEffect`'s `onResolved` hook rather than by wrapping a `Resolver`, which is why it can pass the trace straight through and why `fromTrace` needs no public export. Keep that split: `onResolved` is the seam for _observing_ a replay (logging, counting, step assertions), and a `Resolver` is the seam for _supplying_ outcomes. `replayEffect` returns `{ result, unreached }` rather than the bare state, mirroring `recordEffect`'s `{ result, trace }`; `timeTravel` narrates the same list and returns the bare outcome, because narration is its whole job and a caller who wants the entries as data has `replayEffect`. `unreached` exists because a flow that stops issuing Commands early mismatches nothing: no `TimeParadox` fires, the replay ends in `Success`, and the recorded steps it never asked for are the only evidence of the divergence. A regression test for a fix that deliberately skips a step asserts which step; every other recording asserts the list is empty. It rides beside the result rather than on it so the flow's outcome stays exactly what production would have returned, and rather than behind an observer option (which it briefly was) because a value handed to a callback exactly once after completion is a return value in disguise, and the `let unreached` it forced into every test was the tell. It is absent, not empty, for a `Resolver`: an empty list would claim knowledge the replay does not have. `timeTravel` still narrates the list, but not after a `TimeParadox` or `ReplayError`, since the flow never got past the divergence and the error already names it. Narration that reaches for a `Resolver` is a sign the wrong seam is being used.
|
|
159
|
-
|
|
160
|
-
### TypeScript
|
|
161
|
-
|
|
162
|
-
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`.
|
|
163
|
-
|
|
164
|
-
`index.d.ts` is hand-maintained beside `index.js`, so the two can drift. Three mechanisms guard the drift: the `Declaration parity` test pins the export lists to each other in both directions; `tsd` checks the declarations against `test/types.test-d.ts`; and `npm test` runs `tsc -p jsconfig.json`, strict `checkJs` over `index.js`, `test/all.js`, and `examples/*.js`. That last leg reads the declarations too, not only the JSDoc: `test/all.js` imports `../index.js`, and TypeScript resolves that to the sibling `index.d.ts` before it considers the JavaScript, so the test suite is checked as a strict consumer of the public types. The 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. It then had to be widened twice for the same reason. The config listed `index.js` alone while `test/all.js` opened with `// @ts-check` and was annotated to typecheck, so an editor showed errors there that the gate never saw. And it ran without `strict`, while VS Code checks JavaScript with `strictNullChecks` and `strictFunctionTypes` by default and consults only `tsconfig.json` or `jsconfig.json`, so it ignored the old `tsconfig.check.json` and reported errors against a green gate. The file is named `jsconfig.json` and is strict precisely so that the editor and the gate read one configuration; keep both properties, and add any checked JavaScript that lives in this repo to its `include` list. `test/types.test-d.ts` is in the list too, which is possible only because its deliberate errors are `@ts-expect-error` directives rather than `expectError` calls (see below). **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.
|
|
165
|
-
|
|
166
|
-
Deliberate type errors in `test/types.test-d.ts` are written as `// @ts-expect-error` directives, never as `tsd`'s `expectError(...)`. Both assert that the next expression fails to typecheck, but only the directive is understood by the compiler itself: `expectError` leaves a real diagnostic in the file that `tsd` swallows and every other tool reports, so with it the file showed ten red lines in VS Code and could not be part of the `tsc` gate, which is how a green `tsd` and a red editor coexisted for a while. With the directive, TypeScript suppresses the error and reports `Unused '@ts-expect-error' directive` if it ever stops occurring, and `tsd` fails on that diagnostic, so the assertion is as strong as before (verified by making a suppressed line valid and watching `tsd` fail). What is given up is `expectError`'s check that the error is one of a few specific codes: a directive is satisfied by any error on the line, so keep each suppressed expression small enough that only the intended mistake can fail it, and give every directive a reason. The directive covers exactly one line, so a suppressed expression stays on one line.
|
|
167
|
-
|
|
168
|
-
`Effect<T, E, Ctx>` carries three type parameters: value type, error union, and context type. `Ctx` flows through `AskState`, `CommandState`, `RetryState`, and all `effectPipe` overloads. `Ask<T, E, Ctx>` types the context callback parameter, and `runEffect<T, E, Ctx>` enforces that the supplied context matches. `Ctx` defaults to `unknown` so existing code without context typing is unaffected.
|
|
169
|
-
|
|
170
|
-
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.
|
|
171
|
-
|
|
172
|
-
`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.
|
|
173
|
-
|
|
174
|
-
Every state type declares `next` as a method signature (`next(result: R): Effect<...>`) rather than a function-typed property, and that is load-bearing under `strictFunctionTypes`. A property's parameter is checked contravariantly, so a `CommandState<never, ...>`, which is what `Command` infers for a function that only throws or returns `Promise.reject(...)`, could not be assigned to `Effect`, whose member is `CommandState<any, ...>`: `any` is not assignable to `never`. Method parameters are checked bivariantly, so the same node is accepted. Nothing is lost, since `Effect` already erases the result type to `any`; what changed is that the throwing Commands in `test/all.js` stopped being type errors under a strict editor. The `tsd` Command section pins a throwing thunk as assignable to `Effect`, directly, under `Retry`, and through `effectPipe`, so a tidy-up that turns the methods back into properties fails the gate.
|
|
175
|
-
|
|
176
|
-
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.
|
|
177
|
-
|
|
178
|
-
### Observability
|
|
179
|
-
|
|
180
|
-
`examples/opentelemetry-example.js` wires OpenTelemetry spans into `configureEffect`'s hooks: `onRun` opens one span per run, `onStep` a child span per Command. It is reference code, not part of the library, and it follows the same shape as the recording example: `telemetryHooks(options)` returns a configuration, `enableTelemetry(options)` installs it, and `startTelemetrySdk(options)` stands up an exporter. Nothing happens on import, which is deliberate: the SDK used to start and register a SIGTERM handler at module scope, so merely importing the file opened an exporter and every test run tried to reach `localhost:4318`.
|
|
181
|
-
|
|
182
|
-
Spans carry names, timings, and status; values belong in a trace. That split is why the example puts no Command input or output on a span: a trace already holds every result keyed by Command name, `redact` strips it before it leaves the process, and what remains can be replayed, whereas a span attribute can be redacted neither after the fact nor before an initial input carrying a password reaches the backend. Removing that recording also removed everything that had to guard it, which is what shrank the file from 94 code lines to 69.
|
|
183
|
-
|
|
184
|
-
Two constraints in that file are load-bearing. Telemetry must never decide whether business logic runs: the old version called `JSON.stringify(effect.initialInput)` before `pipeline()`, so an input holding a cycle, which any request object or database client has, threw out of `onRun` and left the flow unexecuted while `runEffect` rejected instead of resolving. And `onStep` must `await op()` and return its result, since returning without calling `op` is precisely how replay suppresses I/O, so the same mistake in a tracing hook would silently stop every Command.
|
|
185
|
-
|
|
186
|
-
`examples/recording-example.js` is the same kind of file for production recording: one recorder per run held in an `AsyncLocalStorage` scope, with `onBeforeCommand` capturing the context so a replay can resolve `Ask`. It stays out of the library for two reasons worth preserving. `node:async_hooks` would be the library's only import and a Node-only one, where `index.js` currently imports nothing and runs anywhere, and the policy it encodes (what to keep, where the sink is, what `redact` strips) belongs to the application. It exports `recordingHooks`, which returns a configuration, plus `enableRecording`, which installs it; the returning form is the composable one, since a self-installing helper would replace hooks the app already set. Both examples are covered by tests, so a change to the hook contract breaks them rather than letting them rot silently, and neither should be edited without running `npm test`.
|
|
187
|
-
|
|
188
|
-
### Tests
|
|
189
|
-
|
|
190
|
-
`test/all.js` contains all runtime tests and uses a user-registration domain as the running example. Tests assert on the _returned data structures_ (Commands, Failures) rather than on side effects, which is the core usage pattern to preserve. `registerUserFlow` is the same shape as the README's Quick Start, on purpose: `ensureEmailIsAvailable` is a `Command` whose `next` returns `Success(input)`, so the tests and the documentation cannot drift into demonstrating different idioms.
|
|
191
|
-
|
|
192
|
-
The `Recording and replay` suite builds flows whose Commands count their own invocations, which is how it asserts that a replay performs **zero** I/O, including a case that exercises every primitive at once. It also covers duplicate Command names, recorded-context `Ask`, retry replay and exhaustion, `Parallel` replaying by path in either finishing order, replaying a trace directly and as a bare entries array, malformed traces rejecting with a `ReplayError`, divergence and exhausted traces, `unreached` (a shortened flow, full consumption, a paradox mid-replay, legacy and bare-array traces, and absence under a `Resolver`), a path-less `Parallel` trace refused, `onMissing`, redaction, `maxEntries` with `dropped`, recorder independence, and `timeTravel`'s narration, including a `Parallel` narration case and a paradox that suppresses the unreached warning.
|
|
193
|
-
|
|
194
|
-
The `Malformed flows` suite covers the guard: the offending step named, a missing return called what it usually is, a continuation returning a plain value, a flow passed without its input, a flow bug thrown rather than folded into a `Failure`, and a thrown Command still becoming one. The `Command identity` suite pins the resolution order: `meta.name` winning over a named thunk, an inline arrow becoming identifiable through `meta.name`, both fallbacks, non-object and non-string metas ignored, and `meta.name` surviving the rebuild that `chain` performs on every pipe step so it reaches both a trace and a replay. The `Recorded step timings` suite reaches `observeSteps` through its only public consumer rather than testing an internal directly: durations recorded for both successful and thrown Commands, rounding, timings not disturbing replay, and an observation failure leaving the outcome alone. The `examples/opentelemetry-example.js` suite injects a stub tracer through the `tracer` option, which is why that option exists, and covers the cyclic input, values never reaching spans, span naming and nesting, error status on a thrown Command, and composition with recording. The `configureEffect merging` suite pins the composition semantics behaviourally rather than by inspecting a merged object: wrapper nesting order, unwind order on a thrown Command, interceptors all running, `retry` merging where attempts come from one configuration and the delay from another, slots left at their defaults, no accumulation across calls, a bare call resetting everything, and the restore function putting back a previous wiring, returning to no hooks, and reverting `retry` defaults. The `examples/recording-example.js` suite runs the reference wiring itself, covering a trace reaching the sink on failure, successes staying out of it, concurrent runs keeping separate traces, redaction before the sink, and recording composing with a telemetry hook.
|
|
195
|
-
|
|
196
|
-
`test/types.test-d.ts` contains type-level tests using `tsd`, verifying that generic type parameters flow correctly through `effectPipe` and `runEffect`. Its negative cases are `@ts-expect-error` directives rather than `expectError` calls, for the reason given in the TypeScript section.
|
|
197
|
-
|
|
198
|
-
### Example code in the README
|
|
199
|
-
|
|
200
|
-
README snippets are code readers copy, and no test covers them. Verify them by extracting the fenced blocks and running them against a stub `db`, not by reading them. A broken example survived review here precisely because it looked right: the flow ended in a bare `saveUser` after a guard that resolved to `Success(true)`, so `db.saveUser(true)` was called, the registration data never reached the database, and the run still reported `Success`. The tree-walking assertions in **Testing Without Mocks** passed the whole time, because `cmd.name` checks the shape and Command arguments live in a closure where nothing can assert on them.
|
|
201
|
-
|
|
202
|
-
Two shape rules keep documented pipelines honest, and the Quick Start is written to both:
|
|
203
|
-
|
|
204
|
-
- **Every step accepts and returns the piped value.** The email guard is a `Command` whose `next` returns `Success(input)` rather than `Success(true)`, so `saveUser` receives the registration data and the pipeline matches the sentence above it. Threading the value through a guard's own continuation costs nothing when the guard is already a Command, which is why no combinator is needed for it.
|
|
205
|
-
- **Prefer threading the value over `() => f(outer)`, but do not present it as a rule.** Closing over an outer variable runs correctly in JavaScript and costs nothing there, so the README says so plainly rather than implying breakage. The real cost is TypeScript: a step that ignores its parameter constrains nothing about what produced it, so changing an upstream output from `User` to `string` raises no error in that form and a compile error when a step consumes the value. Documented examples still thread the value, because that is what keeps a typed pipeline checked end to end, and because it reads as data flow. Note that JavaScript examples have no type safety net at all, which is how the `Success(true)` bug shipped: the equivalent TypeScript is rejected with `'boolean' is not assignable to 'User'`.
|
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
// @ts-check
|
|
2
|
-
|
|
3
|
-
import { trace, SpanStatusCode } from '@opentelemetry/api';
|
|
4
|
-
import { configureEffect } from '../index.js';
|
|
5
|
-
|
|
6
|
-
/** @import { Tracer } from "@opentelemetry/api" */
|
|
7
|
-
/** @import { EffectConfiguration, RunWrapper, StepRunner } from "../index.js" */
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Reference wiring for OpenTelemetry spans
|
|
11
|
-
*
|
|
12
|
-
* `onRun` opens one span per `runEffect` call and `onStep` opens a child span per Command,
|
|
13
|
-
* which is the whole integration: the hooks already sit exactly where spans want to start
|
|
14
|
-
* and end.
|
|
15
|
-
*
|
|
16
|
-
* Importing this file does nothing on its own. Call `startTelemetrySdk()` to stand up an
|
|
17
|
-
* exporter, and `enableTelemetry()` to install the hooks, or `telemetryHooks()` to get them
|
|
18
|
-
* as a configuration you can merge with others.
|
|
19
|
-
*
|
|
20
|
-
* No Command input or output is put on a span, deliberately. Spans carry names, timings, and
|
|
21
|
-
* status; values belong in a trace, where `recorder`'s `redact` strips them before they leave the
|
|
22
|
-
* process and what remains can be replayed. Copying values onto spans would duplicate them into
|
|
23
|
-
* the one place they cannot be redacted after the fact, and an initial input routinely holds a
|
|
24
|
-
* password, a token, or a card number.
|
|
25
|
-
*
|
|
26
|
-
* These hooks use the raw `onStep` and `onRun` rather than `observe`, because a span has to wrap
|
|
27
|
-
* `op`: `startActiveSpan` is what makes each Command span a child of the run's span. An integration
|
|
28
|
-
* that only watches, such as metrics or logging, should use `observe` instead and cannot break a
|
|
29
|
-
* flow by throwing.
|
|
30
|
-
*/
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* @typedef {Object} TelemetryOptions
|
|
34
|
-
* @property {string} [tracerName] - Defaults to `'pure-effect'`.
|
|
35
|
-
* @property {Tracer} [tracer] - Supply a tracer directly instead of resolving one by name. Useful in tests.
|
|
36
|
-
*/
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* A span status message, without putting a Command's data on the span.
|
|
40
|
-
*
|
|
41
|
-
* Only a string error or an Error's message is used. A structured error object can hold the very
|
|
42
|
-
* values this file keeps off spans, and `String(someObject)` would say nothing useful anyway.
|
|
43
|
-
*
|
|
44
|
-
* @param {any} error
|
|
45
|
-
* @returns {string | undefined}
|
|
46
|
-
*/
|
|
47
|
-
const statusMessage = (error) =>
|
|
48
|
-
error instanceof Error ? error.message : typeof error === 'string' ? error : undefined;
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Builds the tracing hooks without installing them.
|
|
52
|
-
*
|
|
53
|
-
* Returning a configuration rather than calling `configureEffect` is what lets tracing coexist with
|
|
54
|
-
* recording: there is one slot per hook, so both concerns go into a single `configureEffect` call,
|
|
55
|
-
* which merges them. A helper that installed itself would silently replace whatever was there.
|
|
56
|
-
*
|
|
57
|
-
* @param {TelemetryOptions} [options]
|
|
58
|
-
* @returns {EffectConfiguration}
|
|
59
|
-
*/
|
|
60
|
-
export function telemetryHooks(options = {}) {
|
|
61
|
-
const { tracerName = 'pure-effect', tracer = trace.getTracer(tracerName) } = options;
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* The root span is named after the flow, so traces are distinguishable in a UI. Every span
|
|
65
|
-
* ends in a `finally`, so a thrown Command cannot leak one.
|
|
66
|
-
* @type {RunWrapper}
|
|
67
|
-
*/
|
|
68
|
-
const onRun = (effect, pipeline, flowName) =>
|
|
69
|
-
tracer.startActiveSpan(flowName || 'Effect Pipeline', async (rootSpan) => {
|
|
70
|
-
rootSpan.setAttribute('effect.flow', flowName || '');
|
|
71
|
-
try {
|
|
72
|
-
const result = await pipeline();
|
|
73
|
-
if (result.type === 'Failure') {
|
|
74
|
-
rootSpan.setStatus({ code: SpanStatusCode.ERROR, message: statusMessage(result.error) });
|
|
75
|
-
} else {
|
|
76
|
-
rootSpan.setStatus({ code: SpanStatusCode.OK });
|
|
77
|
-
}
|
|
78
|
-
return result;
|
|
79
|
-
} catch (/** @type any */ err) {
|
|
80
|
-
rootSpan.recordException(err);
|
|
81
|
-
rootSpan.setStatus({ code: SpanStatusCode.ERROR, message: err?.message });
|
|
82
|
-
throw err;
|
|
83
|
-
} finally {
|
|
84
|
-
rootSpan.end();
|
|
85
|
-
}
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* `op` has to be awaited and its result returned. Returning a value without calling `op` is how
|
|
90
|
-
* replay suppresses I/O, so a hook that forgot to call it would silently stop every Command.
|
|
91
|
-
* @type {StepRunner}
|
|
92
|
-
*/
|
|
93
|
-
const onStep = (name, type, op) =>
|
|
94
|
-
tracer.startActiveSpan(name, async (span) => {
|
|
95
|
-
span.setAttribute('effect.type', type);
|
|
96
|
-
try {
|
|
97
|
-
const result = await op();
|
|
98
|
-
span.setStatus({ code: SpanStatusCode.OK });
|
|
99
|
-
return result;
|
|
100
|
-
} catch (/** @type any */ err) {
|
|
101
|
-
span.recordException(err);
|
|
102
|
-
span.setStatus({ code: SpanStatusCode.ERROR, message: err?.message });
|
|
103
|
-
throw err;
|
|
104
|
-
} finally {
|
|
105
|
-
span.end();
|
|
106
|
-
}
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
return { onRun, onStep };
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Installs tracing on its own. Pass `telemetryHooks()` to `configureEffect` alongside anything else
|
|
114
|
-
* that needs the hooks instead, since a bare call here replaces whatever was configured before.
|
|
115
|
-
*
|
|
116
|
-
* @param {TelemetryOptions} [options]
|
|
117
|
-
*/
|
|
118
|
-
export function enableTelemetry(options) {
|
|
119
|
-
configureEffect(telemetryHooks(options));
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Starts a Node SDK exporting over OTLP, and returns it so a caller can shut it down.
|
|
124
|
-
*
|
|
125
|
-
* Kept out of module scope on purpose: importing a reference file should not open exporters, spawn
|
|
126
|
-
* background work, or register process handlers. The SDK is imported dynamically so the hooks above
|
|
127
|
-
* stay usable wherever `@opentelemetry/api` runs, without pulling the Node SDK in behind them.
|
|
128
|
-
*
|
|
129
|
-
* @param {Object} [options]
|
|
130
|
-
* @param {string} [options.serviceName]
|
|
131
|
-
* @param {string} [options.url] - OTLP HTTP endpoint.
|
|
132
|
-
* @param {boolean} [options.handleSigterm] - Flush and exit on SIGTERM. Off by default, since
|
|
133
|
-
* installing a process handler is the application's decision, not a library's.
|
|
134
|
-
*/
|
|
135
|
-
export async function startTelemetrySdk(options = {}) {
|
|
136
|
-
const { serviceName = 'pure-effect', url = 'http://localhost:4318/v1/traces', handleSigterm = false } = options;
|
|
137
|
-
const [{ NodeSDK }, { OTLPTraceExporter }, { SimpleSpanProcessor }] = await Promise.all([
|
|
138
|
-
import('@opentelemetry/sdk-node'),
|
|
139
|
-
import('@opentelemetry/exporter-trace-otlp-proto'),
|
|
140
|
-
import('@opentelemetry/sdk-trace-base')
|
|
141
|
-
]);
|
|
142
|
-
|
|
143
|
-
const traceExporter = new OTLPTraceExporter({ url });
|
|
144
|
-
// `spanProcessors` replaced the deprecated singular `spanProcessor`, and passing an exporter
|
|
145
|
-
// alongside a processor that already wraps it was redundant.
|
|
146
|
-
const sdk = new NodeSDK({
|
|
147
|
-
serviceName,
|
|
148
|
-
spanProcessors: [new SimpleSpanProcessor(traceExporter)],
|
|
149
|
-
instrumentations: []
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
sdk.start();
|
|
153
|
-
|
|
154
|
-
if (handleSigterm) {
|
|
155
|
-
process.on('SIGTERM', () => {
|
|
156
|
-
sdk.shutdown()
|
|
157
|
-
.then(() => console.log('Tracing terminated'))
|
|
158
|
-
.catch((error) => console.log('Error terminating tracing', error))
|
|
159
|
-
.finally(() => process.exit(0));
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
return sdk;
|
|
164
|
-
}
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
// @ts-check
|
|
2
|
-
|
|
3
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
4
|
-
import { configureEffect, recorder } from '../index.js';
|
|
5
|
-
|
|
6
|
-
/** @import { EffectConfiguration, RunWrapper, StepRunner, CommandInterceptor, TraceLog, SuccessState, FailureState } from "../index.js" */
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Example wiring for recording every run of an application.
|
|
10
|
-
* `recordEffect` covers tests and scripts, where one call site holds the whole run. This
|
|
11
|
-
* exists for the other case: recording without touching any call site.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* @typedef {Object} RecordingStore
|
|
16
|
-
* @property {ReturnType<typeof recorder>} rec
|
|
17
|
-
* @property {string} [flowName]
|
|
18
|
-
* @property {any} initialInput
|
|
19
|
-
* @property {any} context
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* @typedef {Object} RecordingOptions
|
|
24
|
-
* @property {(trace: TraceLog) => Promise<void> | void} [sink] - Receives a finished trace. Writing to
|
|
25
|
-
* S3 or a database fit here. Prefer not to await slow I/O inside
|
|
26
|
-
* a request: hand the trace to a queue or a background task instead.
|
|
27
|
-
* @property {(value: any, name: string, kind: string) => any} [redact] - Runs before any value enters the
|
|
28
|
-
* trace, so nothing sensitive reaches the sink even in memory. It sees results, serialized errors,
|
|
29
|
-
* and the `initialInput` and `context` the trace stores, distinguished by `kind`.
|
|
30
|
-
* @property {number} [maxEntries] - Caps trace length; the overflow count is reported as `dropped`.
|
|
31
|
-
* @property {boolean} [stack] - Records stack traces for thrown errors.
|
|
32
|
-
* @property {(result: SuccessState<any> | FailureState<any>) => boolean} [keep] - Decides which runs
|
|
33
|
-
* reach the sink. Defaults to failures only. Return `true` always to keep everything, or
|
|
34
|
-
* sample successes with a probability check.
|
|
35
|
-
*/
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Builds the three hooks that record each run, without installing them.
|
|
39
|
-
*
|
|
40
|
-
* Returning a configuration rather than calling `configureEffect` is what lets recording coexist
|
|
41
|
-
* with tracing: there is one slot per hook, so both concerns go into a single `configureEffect` call,
|
|
42
|
-
* which merges them. A helper that installed itself would silently replace whatever was there.
|
|
43
|
-
*
|
|
44
|
-
* @param {RecordingOptions} [options]
|
|
45
|
-
* @returns {EffectConfiguration}
|
|
46
|
-
*/
|
|
47
|
-
export function recordingHooks(options = {}) {
|
|
48
|
-
const {
|
|
49
|
-
sink = async () => {},
|
|
50
|
-
redact,
|
|
51
|
-
maxEntries = 500,
|
|
52
|
-
stack,
|
|
53
|
-
keep = (result) => result.type === 'Failure'
|
|
54
|
-
} = options;
|
|
55
|
-
/** @type {AsyncLocalStorage<RecordingStore>} */
|
|
56
|
-
const scope = new AsyncLocalStorage();
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* One recorder per run, held in async-local scope so `onStep` can find the right one without a
|
|
60
|
-
* recorder being threaded through any business-logic signature. A single module-level recorder
|
|
61
|
-
* would interleave the steps of concurrent runs into one trace.
|
|
62
|
-
* @type {RunWrapper}
|
|
63
|
-
*/
|
|
64
|
-
const onRun = async (effect, pipeline, flowName) => {
|
|
65
|
-
const rec = recorder({ redact, maxEntries, stack });
|
|
66
|
-
/** @type {RecordingStore} */
|
|
67
|
-
const store = { rec, flowName, initialInput: /** @type {any} */ (effect).initialInput, context: undefined };
|
|
68
|
-
return scope.run(store, async () => {
|
|
69
|
-
const result = await pipeline();
|
|
70
|
-
if (keep(result)) await sink(rec.toTrace(store));
|
|
71
|
-
return result;
|
|
72
|
-
});
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Outside a recorded run there is no store, so the Command runs untouched.
|
|
77
|
-
* @type {StepRunner}
|
|
78
|
-
*/
|
|
79
|
-
const onStep = async (name, type, op) => {
|
|
80
|
-
const store = scope.getStore();
|
|
81
|
-
return store ? await store.rec.onStep(name, type, op) : await op();
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* `onRun` never sees the context, so it is captured from the first Command of the run.
|
|
86
|
-
* @type {CommandInterceptor}
|
|
87
|
-
*/
|
|
88
|
-
const onBeforeCommand = async (command, context) => {
|
|
89
|
-
const store = scope.getStore();
|
|
90
|
-
if (store && store.context === undefined) store.context = context;
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
return { onRun, onStep, onBeforeCommand };
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Installs recording on its own. Pass `recordingHooks()` to `configureEffect` alongside anything else
|
|
98
|
-
* that needs the hooks instead, since a bare call here replaces whatever was configured before.
|
|
99
|
-
*
|
|
100
|
-
* @param {RecordingOptions} [options]
|
|
101
|
-
*/
|
|
102
|
-
export function enableRecording(options) {
|
|
103
|
-
configureEffect(recordingHooks(options));
|
|
104
|
-
}
|
package/jsconfig.json
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"allowJs": true,
|
|
4
|
-
"checkJs": true,
|
|
5
|
-
"strict": true,
|
|
6
|
-
"noEmit": true,
|
|
7
|
-
"target": "es2022",
|
|
8
|
-
"module": "nodenext",
|
|
9
|
-
"moduleResolution": "nodenext",
|
|
10
|
-
"lib": ["es2022", "dom"]
|
|
11
|
-
},
|
|
12
|
-
"include": ["index.js", "test/all.js", "test/types.test-d.ts", "examples/*.js"]
|
|
13
|
-
}
|