pure-effect 0.18.0 → 0.19.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 +9 -0
- package/README.md +584 -241
- package/index.d.ts +56 -3
- package/index.js +520 -23
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Pure Effect
|
|
2
2
|
|
|
3
|
-
[](https://www.npmjs.com/package/pure-effect) [](https://www.npmjs.com/package/pure-effect) [](https://github.com/aycangulez/pure-effect/actions/workflows/ci.yml) [](https://www.npmjs.com/package/pure-effect) [](https://github.com/aycangulez/pure-effect/blob/main/LICENSE)
|
|
4
4
|
|
|
5
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
|
|
|
@@ -9,17 +9,17 @@
|
|
|
9
9
|
- Inject context without touching function signatures
|
|
10
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, about
|
|
12
|
+
- Zero dependencies, about 11 KB minified and gzipped
|
|
13
13
|
- Works in JavaScript, and in TypeScript 5.1 or later (full generics, bundled `.d.ts`)
|
|
14
14
|
|
|
15
15
|
## Table of Contents
|
|
16
16
|
|
|
17
|
-
- **Getting started:** [Installation](#installation) · [Quick Start](#quick-start) · [How It Works](#how-it-works) · [Testing Without Mocks](#testing-without-mocks) · [Coming from async/await](#coming-from-asyncawait)
|
|
18
|
-
- **Recording and replay:** [Time-Travel Debugging](#time-travel-debugging) · [Recording in Production](#recording-in-production)
|
|
19
|
-
- **Building flows:** [Passing Runtime Context](#passing-runtime-context) · [Retrying Transient Failures](#retrying-transient-failures) · [Running Effects in Parallel](#running-effects-in-parallel) · [Composing Larger Flows](#composing-larger-flows) · [Which Errors Are Data](#which-errors-are-data) · [TypeScript](#typescript-typed-errors-and-context)
|
|
17
|
+
- **Getting started:** [Installation](#installation) · [Quick Start](#quick-start) · [How It Works](#how-it-works) · [Testing Without Mocks](#testing-without-mocks) · [Coming from async/await](#coming-from-asyncawait) · [Writing Flows as Generators](#writing-flows-as-generators)
|
|
18
|
+
- **Recording and replay:** [Time-Travel Debugging](#time-travel-debugging) · [Recording in Production](#recording-in-production) · [Hooks](#hooks)
|
|
19
|
+
- **Building flows:** [Passing Runtime Context](#passing-runtime-context) · [Retrying Transient Failures](#retrying-transient-failures) · [Running Effects in Parallel](#running-effects-in-parallel) · [Composing Larger Flows](#composing-larger-flows) · [Writing Loops](#writing-loops) · [Which Errors Are Data](#which-errors-are-data) · [Generator Flows in Depth](#generator-flows-in-depth) · [TypeScript](#typescript-typed-errors-and-context)
|
|
20
20
|
- **Reference:** [Why Pure Effect](#why-pure-effect) · [Load Tests](#load-tests) · [API Reference](#api-reference) · [Limitations](#limitations)
|
|
21
21
|
|
|
22
|
-
The
|
|
22
|
+
The six sections under Getting started are enough to write and test a flow. Come back to the rest when a flow needs it: recording, retries, loops, steps that run at the same time, or TypeScript.
|
|
23
23
|
|
|
24
24
|
## Installation
|
|
25
25
|
|
|
@@ -70,9 +70,21 @@ async function registerUser(input) {
|
|
|
70
70
|
}
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
+
The same flow can be written as a generator, with `yield* step(...)` where `async` code writes `await`. [Writing Flows as Generators](#writing-flows-as-generators) covers what to know.
|
|
74
|
+
|
|
75
|
+
```js
|
|
76
|
+
import { effectGen, step } from 'pure-effect';
|
|
77
|
+
|
|
78
|
+
const registerUserFlowGen = effectGen(function* (input) {
|
|
79
|
+
yield* step(validateRegistration(input));
|
|
80
|
+
yield* step(ensureEmailAvailable(input));
|
|
81
|
+
return yield* step(saveUser(input));
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
73
85
|
## How It Works
|
|
74
86
|
|
|
75
|
-
A flow is a chain of pairs: an I/O call, and a `next` function that receives its answer and returns the next Command, a Success, or a Failure. `runEffect` walks the chain in a loop.
|
|
87
|
+
A flow is a chain of pairs: an I/O call, and a `next` function that receives its answer and returns the next Command, a Success, or a Failure. `runEffect` walks the chain in a loop. A generator flow builds the same Commands: `effectGen` runs your function up to each `yield*` and continues it with the answer.
|
|
76
88
|
|
|
77
89
|
Recording and replay hook into the one place where a Command's function is called. Recording writes down each answer. Replay supplies the recorded answer instead of making the call, so a replayed flow does no I/O.
|
|
78
90
|
|
|
@@ -80,9 +92,7 @@ Building a flow runs the pure steps right away: `registerUserFlow(badInput)` ret
|
|
|
80
92
|
|
|
81
93
|
## Testing Without Mocks
|
|
82
94
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
Validation runs as soon as you build the flow, so testing it needs nothing else:
|
|
95
|
+
A flow is plain objects, so a test can check what it will do without running it. Validation runs as soon as the flow is built, so testing it needs nothing else:
|
|
86
96
|
|
|
87
97
|
```js
|
|
88
98
|
const badInput = { email: 'bad-email', password: '123' };
|
|
@@ -114,62 +124,63 @@ assert.equal(commandName(step2), 'cmdSaveUser');
|
|
|
114
124
|
// The database was never touched.
|
|
115
125
|
```
|
|
116
126
|
|
|
117
|
-
Write both kinds
|
|
127
|
+
Write both kinds: only a step test sees the value passed from one step to the next. If the email guard returned `Success(true)` instead of `Success(input)`, the step test would fail, but the flow test would still pass, since the calls and their order are unchanged, while the flow saved `true` instead of the user.
|
|
118
128
|
|
|
119
|
-
|
|
129
|
+
A walk meets a `Retry` or a `Parallel` as a step of its own. A `Retry` holds the step it repeats as `effect`, a `Parallel` holds its branches as `effects`, and the `next` of either is the rest of the flow. The walks in [Writing Loops](#writing-loops) and [Undoing what succeeded when a branch fails](#undoing-what-succeeded-when-a-branch-fails) go through each.
|
|
120
130
|
|
|
121
|
-
|
|
131
|
+
To run the whole flow instead of walking it, `Retry` and `Parallel` included, hand `replayEffect` a function that answers each Command by name. Nothing is called and no retry waits; answering `{ error }` makes that Command throw, which is how a test reaches a `Retry`'s fallback:
|
|
122
132
|
|
|
123
133
|
```js
|
|
134
|
+
import { replayEffect } from 'pure-effect';
|
|
135
|
+
|
|
124
136
|
const answers = { cmdFindUser: null, cmdSaveUser: { id: 1, ...input } };
|
|
125
137
|
const answer = (step) => (step.name in answers ? { result: answers[step.name] } : undefined);
|
|
126
138
|
const { result } = await replayEffect(registerUserFlow(input), answer);
|
|
127
139
|
assert.deepEqual(result, Success({ id: 1, ...input }));
|
|
128
140
|
```
|
|
129
141
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
**In TypeScript**, a flow is typed as any kind of step it could start with, since validation may already have returned a `Success` or a `Failure`, so `.cmd` and `.next` compile only after the test checks that the step is a Command. `node:assert`'s `assert(step.type === 'Command')` is such a check, and TypeScript follows it. Jest's and Vitest's `expect` is not, so a walk needs a check at every step, and a small helper makes that one line per step with any test framework:
|
|
142
|
+
Hand it a recorded run instead, and each Command gets what it returned the first time. That is how a run recorded in production replays on your machine, with nothing connected:
|
|
133
143
|
|
|
134
|
-
```
|
|
135
|
-
import
|
|
136
|
-
import { commandName } from 'pure-effect';
|
|
137
|
-
import type { Effect } from 'pure-effect';
|
|
144
|
+
```js
|
|
145
|
+
import { recordEffect } from 'pure-effect';
|
|
138
146
|
|
|
139
|
-
//
|
|
140
|
-
|
|
141
|
-
assert(step.type === 'Command', `expected ${name}, got ${step.type}`);
|
|
142
|
-
assert.equal(commandName(step), name);
|
|
143
|
-
return step;
|
|
144
|
-
}
|
|
147
|
+
// A real run returns its result, and a trace of what each Command returned.
|
|
148
|
+
const { result: live, trace } = await recordEffect(registerUserFlow, input);
|
|
145
149
|
|
|
146
|
-
|
|
147
|
-
|
|
150
|
+
// Anywhere else, with nothing connected, the same flow gets the same answers.
|
|
151
|
+
const { result: replayed } = await replayEffect(registerUserFlow(trace.initialInput), trace);
|
|
152
|
+
assert.deepEqual(replayed, live);
|
|
148
153
|
```
|
|
149
154
|
|
|
150
|
-
|
|
155
|
+
[Time-Travel Debugging](#time-travel-debugging) turns such a trace into a regression test, and [Recording in Production](#recording-in-production) records every run of an application.
|
|
156
|
+
|
|
157
|
+
Tests cannot see inside a Command's function without running it. If `cmdFindUser` said `db.findUser(input.name)` instead of `input.email`, every test on this page would still pass. Keep those functions to a single call, and let an integration test cover them, with the services passed in as [Passing Runtime Context](#passing-runtime-context) shows.
|
|
158
|
+
|
|
159
|
+
In TypeScript, a walk needs a check at each step that the step is a Command; [Testing a flow in TypeScript](#testing-a-flow-in-typescript) has a helper that makes that one line.
|
|
151
160
|
|
|
152
161
|
## Coming from async/await
|
|
153
162
|
|
|
154
|
-
A flow does what `async`/`await` code does, as data
|
|
163
|
+
A flow does what `async`/`await` code does, as data: instead of making a call and waiting for it, a step returns a Command that says which call to make and what to do with the answer. Each thing you would write with `async`/`await` has an equivalent:
|
|
155
164
|
|
|
156
|
-
|
|
|
157
|
-
| --- | --- |
|
|
158
|
-
| `
|
|
159
|
-
| the code after the `await
|
|
160
|
-
| an `if` on `
|
|
161
|
-
| `return value` | `Success(value)` |
|
|
162
|
-
| `throw` to stop | `Failure(error)` |
|
|
163
|
-
|
|
|
164
|
-
| a loop that retries a call | `Retry(
|
|
165
|
-
| `await Promise.all([...])` | `Parallel([...])` |
|
|
166
|
-
| a `for` loop with an `await` inside |
|
|
167
|
-
| a
|
|
168
|
-
| a
|
|
169
|
-
| a value from the request
|
|
170
|
-
| `Date.now()` or a random ID | a Command
|
|
171
|
-
|
|
172
|
-
|
|
165
|
+
| `async`/`await` | Generator flow | Pipeline |
|
|
166
|
+
| --- | --- | --- |
|
|
167
|
+
| `await db.findUser(email)` | `yield* step(findUser(email))` | `Command(() => db.findUser(email), next)` |
|
|
168
|
+
| the code after the `await` | the next `yield*` | the Command's `next` |
|
|
169
|
+
| an `if` on a result | a step that returns `Success` or `Failure` | a branch in `next` |
|
|
170
|
+
| `return value` | `return value` | `Success(value)` |
|
|
171
|
+
| `throw` to stop | a step that returns `Failure(error)` | `Failure(error)` |
|
|
172
|
+
| `try`/`catch` around a call | a catch inside the Command's function | the same |
|
|
173
|
+
| a loop that retries a call | `yield* step(Retry(...))` | `Retry(...)` |
|
|
174
|
+
| `await Promise.all([...])` | `yield* step(Parallel([...]))` | `Parallel([...])` |
|
|
175
|
+
| a `for` loop with an `await` inside | the same loop, with `yield*` | `Parallel(list.map(...), { limit: 1 })` |
|
|
176
|
+
| a loop that keeps going past a failure | `Parallel(..., { settled: true })` | the same |
|
|
177
|
+
| a call that needs two earlier results | two variables | a named step that passes both on |
|
|
178
|
+
| a value from the request | `yield* step(Ask())` | `Ask` |
|
|
179
|
+
| `Date.now()` or a random ID | a Command | a Command |
|
|
180
|
+
|
|
181
|
+
`findUser` stands for a step that returns the Command, as `ensureEmailAvailable` does in the Quick Start. A `catch` around `yield*` can log and rethrow, but it cannot recover; see [Which Errors Are Data](#which-errors-are-data).
|
|
182
|
+
|
|
183
|
+
One rule is behind both columns: each decision lives in a small step function that receives the answer it depends on and returns `Success` or `Failure`, so a test can call it directly. A pipeline joins those steps with `effectPipe`; a generator flow puts them in order with `yield*`. An `if` around a `yield*` works, but it can be tested only by walking the whole flow, so keep the body to putting steps in order. A `for` loop that runs a step for each item decides nothing, so it is fine.
|
|
173
184
|
|
|
174
185
|
The Quick Start's `registerUserFlow` is this function, translated row by row: each `await` became a Command, the code after it became that Command's `next`, and each `throw` became a `Failure`.
|
|
175
186
|
|
|
@@ -182,7 +193,7 @@ async function registerUserAsync(input) {
|
|
|
182
193
|
}
|
|
183
194
|
```
|
|
184
195
|
|
|
185
|
-
The difference shows
|
|
196
|
+
The difference shows in the tests. To reach the branch where the email is taken, a test of `registerUserAsync` has to replace the database's methods, run the function, and put them back, here with Node's built-in mocks:
|
|
186
197
|
|
|
187
198
|
```js
|
|
188
199
|
import { mock } from 'node:test';
|
|
@@ -203,9 +214,9 @@ The flow's test of the same branch hands one step the answer, with nothing to re
|
|
|
203
214
|
assert.deepEqual(ensureEmailAvailable(input).next({ id: 1 }), Failure('Email already in use.'));
|
|
204
215
|
```
|
|
205
216
|
|
|
206
|
-
|
|
217
|
+
Each step is a place a test can start, so a branch is tested by calling the step it lives in, where a test of an `async` function runs everything before the branch, with every call on the way replaced. The mocks do check one thing these tests cannot: the arguments each call received, which [Testing Without Mocks](#testing-without-mocks) leaves to an integration test.
|
|
207
218
|
|
|
208
|
-
You can switch one function at a time
|
|
219
|
+
You can switch one function at a time: keep its name and parameters, run the flow in its body, and turn a `Failure` back into a throw, so the code that calls it does not change. The mocked test above passes against this version too:
|
|
209
220
|
|
|
210
221
|
```js
|
|
211
222
|
// Callers still await registerUserAsync and catch what it throws.
|
|
@@ -219,84 +230,49 @@ async function registerUserAsync(input) {
|
|
|
219
230
|
await assert.rejects(registerUserAsync({ email: 'bad-email', password: '123' }), { message: 'Invalid email.' });
|
|
220
231
|
```
|
|
221
232
|
|
|
222
|
-
A loop
|
|
223
|
-
|
|
224
|
-
```js
|
|
225
|
-
async function payUnpaidAsync(customerId) {
|
|
226
|
-
const invoices = await billing.findUnpaid(customerId);
|
|
227
|
-
for (const invoice of invoices) {
|
|
228
|
-
const receipt = await payments.charge(invoice);
|
|
229
|
-
await mailer.sendReceipt(receipt);
|
|
230
|
-
}
|
|
231
|
-
}
|
|
233
|
+
A loop becomes a step that gets the list and a `Parallel` over it, as the table shows; [Writing Loops](#writing-loops) translates one.
|
|
232
234
|
|
|
233
|
-
|
|
234
|
-
const findUnpaidInvoices = (customerId) => {
|
|
235
|
-
const cmdFindUnpaid = () => billing.findUnpaid(customerId);
|
|
236
|
-
return Command(cmdFindUnpaid);
|
|
237
|
-
};
|
|
235
|
+
## Writing Flows as Generators
|
|
238
236
|
|
|
239
|
-
|
|
240
|
-
const chargeInvoice = (invoice) => {
|
|
241
|
-
const cmdChargeInvoice = () => payments.charge(invoice);
|
|
242
|
-
return Retry(Command(cmdChargeInvoice), { attempts: 3 });
|
|
243
|
-
};
|
|
237
|
+
A generator flow is written like `async` code, with `yield* step(...)` where `async` code writes `await`. `effectGen` turns it into the same Commands a pipeline builds, so recording, replay, `Retry`, `Parallel` and the tests above work the same for both. The Quick Start's `registerUserFlowGen` is one. The same steps in the same order record the same paths in either form, so a trace recorded from a pipeline replays against its generator version. A loop written as a `for` loop rather than a `Parallel` records differently; see [Writing Loops](#writing-loops).
|
|
244
238
|
|
|
245
|
-
|
|
246
|
-
const cmdSendReceipt = () => mailer.sendReceipt(receipt);
|
|
247
|
-
return Command(cmdSendReceipt);
|
|
248
|
-
};
|
|
239
|
+
### Where a generator helps
|
|
249
240
|
|
|
250
|
-
|
|
241
|
+
A generator earns its keep when a later step needs the results of more than one earlier step. Here the welcome email needs both the saved user and the workspace created for them, and each is a variable:
|
|
251
242
|
|
|
252
|
-
|
|
253
|
-
const
|
|
243
|
+
```js
|
|
244
|
+
const onboardUser = effectGen(function* (input) {
|
|
245
|
+
const user = yield* step(registerUserFlowGen(input));
|
|
254
246
|
|
|
255
|
-
const
|
|
247
|
+
const cmdCreateWorkspace = () => db.createWorkspace(user.id);
|
|
248
|
+
const workspace = yield* step(Command(cmdCreateWorkspace));
|
|
256
249
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
assert.equal(commandName(flow), 'cmdFindUnpaid');
|
|
260
|
-
assert.equal(flow.next([{ id: 1 }, { id: 2 }]).effects.length, 2);
|
|
250
|
+
const cmdSendWelcome = () => mailer.sendWelcome(user.email, workspace.name);
|
|
251
|
+
yield* step(Command(cmdSendWelcome));
|
|
261
252
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
assert.equal(commandName(body.effect), 'cmdChargeInvoice');
|
|
265
|
-
assert.equal(commandName(body.next({ id: 'receipt_1' })), 'cmdSendReceipt');
|
|
253
|
+
return { user, workspace };
|
|
254
|
+
});
|
|
266
255
|
|
|
267
|
-
|
|
268
|
-
assert.
|
|
256
|
+
const onboarded = await runEffect(onboardUser(input));
|
|
257
|
+
assert.equal(onboarded.value.workspace.ownerId, onboarded.value.user.id);
|
|
269
258
|
```
|
|
270
259
|
|
|
271
|
-
|
|
260
|
+
A pipeline would need a step that passes the user and the workspace on together; see [Composing Larger Flows](#composing-larger-flows). Keep decisions in step functions all the same, as `registerUserFlowGen` does, so each can be tested on its own.
|
|
272
261
|
|
|
273
|
-
The
|
|
262
|
+
The body can run more than once: under a `Retry`, when one flow value is run twice, and when a test walks a second branch. So keep it to its own variables, and get `Date.now()` or a random ID from a Command. [Generator Flows in Depth](#generator-flows-in-depth) covers when it runs again, how a `catch` or `finally` in it behaves when a step stops the flow, and the mistakes `effectGen` catches.
|
|
274
263
|
|
|
275
|
-
|
|
264
|
+
### Testing a generator flow
|
|
276
265
|
|
|
277
|
-
|
|
266
|
+
Test each step function by handing it an answer, as [Testing Without Mocks](#testing-without-mocks) does, since the generator only puts the steps in order. Then run the whole flow with each Command answered by name, as for a pipeline:
|
|
278
267
|
|
|
279
268
|
```js
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
const page = await api.listOrders(cursor);
|
|
285
|
-
orders.push(...page.items);
|
|
286
|
-
cursor = page.nextCursor;
|
|
287
|
-
} while (cursor);
|
|
288
|
-
return orders;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
const listAllOrders = () => {
|
|
292
|
-
const cmdListAllOrders = () => fetchAllOrders();
|
|
293
|
-
return Command(cmdListAllOrders);
|
|
294
|
-
};
|
|
269
|
+
const answers = { cmdFindUser: null, cmdSaveUser: { id: 1, ...input } };
|
|
270
|
+
const answerByName = (asked) => (asked.name in answers ? { result: answers[asked.name] } : undefined);
|
|
271
|
+
const { result } = await replayEffect(registerUserFlowGen(input), answerByName);
|
|
272
|
+
assert.deepEqual(result, Success({ id: 1, ...input }));
|
|
295
273
|
```
|
|
296
274
|
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
The loop belongs in the flow only when the flow has to decide something on each pass, such as stopping at the first order that matches, or saving each page as it arrives. Then the Command's `next` returns the Command for the next page instead of a `Success`, until there are no more pages.
|
|
275
|
+
Walking the flow step by step works as it does for a pipeline: a walk straight through runs the body once, and walking a second branch runs it again.
|
|
300
276
|
|
|
301
277
|
## Time-Travel Debugging
|
|
302
278
|
|
|
@@ -351,7 +327,7 @@ it('prod incident 8f3a: a 100% promo produces a $0 charge', async () => {
|
|
|
351
327
|
});
|
|
352
328
|
```
|
|
353
329
|
|
|
354
|
-
The test checks that the flow still takes the recorded path and handles the recorded outcomes the same way. If a refactor reorders or replaces a step, the replay ends in a `Failure` whose error is a `TimeParadox` naming where it diverged. It is not thrown, so a test that expects a `Failure` should check the error too, as this one checks its `code`.
|
|
330
|
+
The test checks that the flow still takes the recorded path and handles the recorded outcomes the same way. It does not check the values the flow computes, since every result comes from the recording; see [What a replay cannot check](#what-a-replay-cannot-check). If a refactor reorders or replaces a step, the replay ends in a `Failure` whose error is a `TimeParadox` naming where it diverged. It is not thrown, so a test that expects a `Failure` should check the error too, as this one checks its `code`. A step the trace lacks ends the replay in a `Failure` holding a `ReplayError`. A trace lacks a step that comes after the end of the recording, one a hook vetoed in production, and one the recorder dropped under `maxEntries`.
|
|
355
331
|
|
|
356
332
|
A flow that stops issuing Commands before the recording ends (for example, a fix that skips the charge) produces no `TimeParadox`, and the replay can end in `Success` with recorded steps left over. `replayEffect` returns those steps as `unreached`, so a test can assert which ones it expects to skip:
|
|
357
333
|
|
|
@@ -366,19 +342,48 @@ it('incident 8f3a fixed: a 100% promo checks out without a charge', async () =>
|
|
|
366
342
|
});
|
|
367
343
|
```
|
|
368
344
|
|
|
369
|
-
For every other recording, `unreached` should be empty, so a fix that skips a step by accident fails the test.
|
|
345
|
+
For every other recording, `unreached` should be empty, so a fix that skips a step by accident fails the test. This works when the removed step is the last one the flow reaches. Remove a step from the middle and every later step moves to a different path, so the replay stops at a `TimeParadox`, and `unreached` lists the steps it never got to.
|
|
346
|
+
|
|
347
|
+
### Reading a trace
|
|
348
|
+
|
|
349
|
+
A trace is plain JSON. This one is from a checkout whose card charge timed out once and then went through:
|
|
350
|
+
|
|
351
|
+
```text
|
|
352
|
+
{
|
|
353
|
+
"flowName": "checkout",
|
|
354
|
+
"version": "b42",
|
|
355
|
+
"initialInput": { "cartId": "cart_1" },
|
|
356
|
+
"context": { "flowName": "checkout" },
|
|
357
|
+
"dropped": 0,
|
|
358
|
+
"trace": [
|
|
359
|
+
{ "command": "cmdFetchCart", "path": "0", "result": { "total": 120 }, "durationMs": 41.3 },
|
|
360
|
+
{ "command": "cmdChargeCard", "path": "1r0/0", "threw": true,
|
|
361
|
+
"error": { "__error": true, "name": "Error", "message": "gateway timeout", "code": "ETIMEDOUT" }, "durationMs": 5002.1 },
|
|
362
|
+
{ "command": "cmdChargeCard", "path": "1r1/0", "result": { "chargeId": "ch_1" }, "durationMs": 181.5 }
|
|
363
|
+
]
|
|
364
|
+
}
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
`trace` holds one entry per step, in the order the steps finished; [`recorder`](#recorderoptions) lists each kind of entry. A replay matches each step by its `path`, its position in the flow, and a `TimeParadox` names the path where the flow and the trace part ways:
|
|
370
368
|
|
|
371
|
-
|
|
369
|
+
- A number counts the Commands, `Retry`s and `Parallel`s the flow reached, from `0`. A `Success` or an `Ask` between them adds nothing.
|
|
370
|
+
- `r` and a number is one attempt of the `Retry` at that position, `r0` being the first try, and `rf` is its `onExhausted` fallback.
|
|
371
|
+
- `p` and a number is one branch of the `Parallel` at that position, from `p0`. The `Parallel` has an entry of its own, at a path such as `2p`, which records whether a branch cancelled the others.
|
|
372
|
+
- `/` goes one level in: `1r1/0` is the first step of the second try of the `Retry` at position 1, and `2p1/0` is the first step of the second branch of the `Parallel` at position 2.
|
|
372
373
|
|
|
373
|
-
|
|
374
|
+
### What a replay cannot check
|
|
374
375
|
|
|
375
|
-
|
|
376
|
+
A replay proves that the flow asks for the same Commands in the same order and handles the same answers. Every result comes from the recording, so it cannot check:
|
|
376
377
|
|
|
377
|
-
**
|
|
378
|
+
- **What the flow computes.** Fix how a refund amount is calculated and replay the bad run, and the charge step still gets the old amount from the recording: the replay reports `Success`, returns the value from before the fix, and flags nothing. Test a value change against the pure step that computes it.
|
|
379
|
+
- **A fix inside a Command's function.** The function never runs, so an old trace hands the flow what it returned or threw before the fix: catch a duplicate-key error inside the function and return it as data, and the old trace still replays the throw. Cover such a fix with an integration test.
|
|
380
|
+
- **The arguments a Command was called with.** A trace records results only. Given the recorded input and results, the flow does the same thing again, so replaying up to a step rebuilds its arguments for a debugger, but a test cannot assert on them. Storing them would also double what `redact` has to cover, since arguments are usually the sensitive part of a call.
|
|
378
381
|
|
|
379
|
-
|
|
382
|
+
When a Command's result changes shape, rename the Command. A trace matches it by name, so under the old name an old trace hands the new code a result in the old shape, which it can take for another answer without any `TimeParadox`.
|
|
380
383
|
|
|
381
|
-
|
|
384
|
+
### Keeping a replay faithful
|
|
385
|
+
|
|
386
|
+
Put anything that varies between runs inside a Command. For replay, the current time or a random ID counts as I/O: in a Command it is recorded and replayed like any other result, while a step that calls `Date.now()` directly gets a new value on every replay and drifts from the trace. To check a flow, record it, replay the trace, and compare the outcomes: a step that computes a fresh value shows up as a different final value, or as a `TimeParadox` if it changes which Commands run. A trace holds each result in the form JSON stores it, so this also catches a result your storage cannot keep, such as a `Date` the flow calls a method on:
|
|
382
387
|
|
|
383
388
|
```js
|
|
384
389
|
const { result, trace } = await recordEffect(registerUserFlow, input);
|
|
@@ -386,9 +391,11 @@ const { result: replayed } = await replayEffect(registerUserFlow(input), trace);
|
|
|
386
391
|
assert.deepEqual(replayed, result); // fails if a step computed a fresh value, or a result did not survive storage
|
|
387
392
|
```
|
|
388
393
|
|
|
389
|
-
|
|
394
|
+
A `Failure` compares the same way when the Command threw a plain `Error`, which comes back with its message, name, cause, custom properties and an `AggregateError`'s list of errors, even a `name` or `cause` set after it was created. An error of any other class, built-in ones included, comes back as a plain `Error` carrying that class's name, so `deepEqual` from `node:assert/strict` refuses the replayed `TypeError` that `fetch` rejects with when the network fails. Where a Command can throw one, compare `error.name` and `error.message` instead.
|
|
395
|
+
|
|
396
|
+
### Replaying from your own storage
|
|
390
397
|
|
|
391
|
-
|
|
398
|
+
`replayEffect` also accepts a resolver function instead of a trace, so you can replay from OpenTelemetry spans, a log pipeline, or a database table, not only from the JSON that `recorder` produces. Whatever you store needs each step's `path`, which `onStep` receives, and its result; the telemetry example records neither, since it keeps values off spans.
|
|
392
399
|
|
|
393
400
|
```js
|
|
394
401
|
// A resolver answers one question: what did production get back for this step? Look the step up by its path, its
|
|
@@ -421,14 +428,126 @@ configureEffect(
|
|
|
421
428
|
);
|
|
422
429
|
```
|
|
423
430
|
|
|
424
|
-
|
|
431
|
+
What the example does with each run:
|
|
432
|
+
|
|
433
|
+
- **Which runs it keeps.** `keep` decides, and by default keeps a run that ended in a `Failure`; successful runs are held in memory and then discarded. When your own code throws, such as a `TypeError` after an API changed the shape of its response, the run rejects. `keep` is offered a `Failure` carrying the thrown error, so by default its trace is kept. Replaying that trace reproduces the throw. A step before the flow's first Command runs when the flow is built, outside `runEffect`, so its throw reaches no hook and is not recorded; that run did no I/O, so its input reproduces it.
|
|
434
|
+
- **What a trace holds.** `redact` runs before anything enters the trace, including the stored `initialInput` and `context`. A value it throws on, or one JSON cannot hold, such as a `BigInt`, is left out of the trace, which marks where with `unrecorded`, and a replay stops there. Everything else is already in the form JSON holds, so the sink can write it to S3 or a database column with `JSON.stringify`.
|
|
435
|
+
- **How long a trace gets.** `maxEntries` caps it and reports the overflow as `dropped`, and a capped trace replays only up to the first step it lacks.
|
|
436
|
+
- **When storage fails.** If `keep` or the sink throws, for example because storage is unreachable, the run keeps its own outcome and the error goes to `onSinkError`, which defaults to `console.error`.
|
|
437
|
+
- **What it warns about.** The example warns through `onWarning`, once per flow, when it keeps a trace that was capped, one holding values it could not record, or one whose steps include any named `'anonymous'`.
|
|
425
438
|
|
|
426
|
-
The example takes the input from `onRun`, which is handed it only for a flow `effectPipe` built, so build the outermost flow with `effectPipe`. A flow that starts with a bare `Command`, `Ask`, `Retry`, or `Parallel` records no input, and `timeTravel` would rebuild it from `undefined`. A one-step pipeline is enough, as in `runEffect(effectPipe(loadProfile)(userId))`. The example warns through `onWarning`, which defaults to `console.warn`, the first time it keeps a trace of such a flow, and `timeTravel` warns when it replays one.
|
|
439
|
+
The example takes the input from `onRun`, which is handed it only for a flow `effectPipe` built, so build the outermost flow with `effectPipe`. A flow that starts with a bare `Command`, `Ask`, `Retry`, or `Parallel` records no input, and `timeTravel` would rebuild it from `undefined`. A one-step pipeline is enough, as in `runEffect(effectPipe(loadProfile)(userId))`. The example warns through `onWarning`, which defaults to `console.warn`, the first time it keeps a trace of such a flow, and `timeTravel` warns when it replays one.
|
|
440
|
+
|
|
441
|
+
The example also takes the context from the run's first Command, so a run that stops before any Command, for example at an `Ask` check, records no context. Such a run did no I/O, so running the flow again with its input and the context from your logs reproduces it.
|
|
427
442
|
|
|
428
443
|
**A trace keeps data, not objects.** A value is copied into the form JSON stores when it is recorded, and copied again each time a replay hands it to the flow, so neither a later step nor a replay can change what the trace says, and a replay from memory gets what a replay from storage gets. The copy keeps values but not classes: a money object or a database entity comes back as a plain object without its methods, a `Date` as a string, a `Map` or a `Set` as `{}`, a `Buffer` as `{ type: 'Buffer', data }`, `undefined` in an array as `null`, and an error returned inside a result with its own fields, such as `code`, but without its message. A reference back to an object the value is inside of, as between an HTTP client's request and response, is cut. A value JSON cannot hold at all, such as a `BigInt` or an object whose getter throws, is left out of the trace and marked `unrecorded` before `redact` sees it, so a context holding a lazy client is left out whole.
|
|
429
444
|
|
|
430
445
|
So return plain data from a Command's function. Turn a class instance into a plain object before returning it, with a small named function you can test on its own, as in `() => db.findCart(id).then(cartToData)`, and rebuild the object in `next` if the flow needs its methods. When you catch an error to return it as data, copy the fields the flow branches on, as in `.catch((error) => ({ ok: false, code: error.code }))`, rather than returning the error itself.
|
|
431
446
|
|
|
447
|
+
### Keeping secrets out of a trace
|
|
448
|
+
|
|
449
|
+
`redact` sees everything a trace stores: each result, each thrown error, the flow's input and the context, told apart by `kind`. It gets a copy in the form the trace stores, so changing it in place is safe, and what it returns is stored in that form too. A thrown `Error` arrives as a plain object holding its `name`, `message` and own fields, and any object returned for it replays as an `Error`.
|
|
450
|
+
|
|
451
|
+
Check a value before replacing a field in it, since `{ ...value, email: '[redacted]' }` turns a `null` into an object and the replay takes the other branch:
|
|
452
|
+
|
|
453
|
+
```js
|
|
454
|
+
// Masks a field only where there is one, so a lookup that found nothing still records null.
|
|
455
|
+
const mask = (value, field) =>
|
|
456
|
+
value && typeof value === 'object' && field in value ? { ...value, [field]: '[redacted]' } : value;
|
|
457
|
+
|
|
458
|
+
const redact = (value, name, kind) => {
|
|
459
|
+
if (kind === 'initialInput') return mask(value, 'cardNumber');
|
|
460
|
+
if (kind === 'context') return mask(value, 'authToken');
|
|
461
|
+
if (kind === 'error') return mask(value, 'attempted');
|
|
462
|
+
return name === 'cmdFetchUser' ? mask(value, 'email') : value;
|
|
463
|
+
};
|
|
464
|
+
recorder({ redact });
|
|
465
|
+
|
|
466
|
+
assert.equal(redact(null, 'cmdFetchUser', 'result'), null); // still nothing found
|
|
467
|
+
assert.equal(redact('card_declined', 'cmdCharge', 'error'), 'card_declined'); // still a string
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
A replay rebuilds the flow from the redacted input and context, so a field a step checks, such as a password, needs a stand-in the check treats the same way, as the example at the top of this section does, and a context field an `Ask` reads should stay.
|
|
471
|
+
|
|
472
|
+
## Hooks
|
|
473
|
+
|
|
474
|
+
Hooks see every run, and recording, replay and the telemetry example are built on them. There are three: `onRun` wraps a whole run, `onStep` wraps each Command and each `Parallel`, and `onBeforeCommand` runs before each Command and can veto it by throwing. A hook that only watches must `await` what it wraps and return its result; [`configureEffect`](#configureeffectconfigs) lists each hook's arguments.
|
|
475
|
+
|
|
476
|
+
`configureEffect` adds a layer of hooks for the whole process and returns a function that removes it. Removing a layer removes only that layer, even when others were installed after it, so a library can add and remove its own hooks without touching the application's:
|
|
477
|
+
|
|
478
|
+
```js
|
|
479
|
+
const remove = configureEffect(telemetryHooks(), recordingHooks({ sink }));
|
|
480
|
+
// the same as configureEffect(telemetryHooks()) followed by configureEffect(recordingHooks({ sink }))
|
|
481
|
+
remove();
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
Layers run in the order they were installed, the first outermost, so a result or a thrown error unwinds from the innermost hook out:
|
|
485
|
+
|
|
486
|
+
```
|
|
487
|
+
runEffect(flow(input))
|
|
488
|
+
│
|
|
489
|
+
├─ telemetry.onRun first configuration: outermost
|
|
490
|
+
│ └─ recording.onRun last configuration: innermost
|
|
491
|
+
│ │
|
|
492
|
+
│ │ for each Command:
|
|
493
|
+
│ ├─ telemetry.onBeforeCommand interceptors all run, in the order given
|
|
494
|
+
│ ├─ recording.onBeforeCommand
|
|
495
|
+
│ ├─ telemetry.onStep
|
|
496
|
+
│ │ └─ recording.onStep closest to the Command
|
|
497
|
+
│ │ └─ cmd()
|
|
498
|
+
│ │ ┌─ recording.onStep returns a result, or a thrown error, unwinds
|
|
499
|
+
│ ├─ telemetry.onStep returns from the inside out
|
|
500
|
+
│ │
|
|
501
|
+
│ ┌─ recording.onRun returns
|
|
502
|
+
├─ telemetry.onRun returns
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
**Knowing which request a step belongs to.** `onStep` and `onRun` get no context, so a hook that logs per request finds the request the way the rest of your logging does. An `AsyncLocalStorage` scope entered around `runEffect` reaches every hook the run calls, and the recording example uses one to give each run its own recorder:
|
|
506
|
+
|
|
507
|
+
```js
|
|
508
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
509
|
+
|
|
510
|
+
const requestScope = new AsyncLocalStorage();
|
|
511
|
+
const stepLog = [];
|
|
512
|
+
|
|
513
|
+
// Logs each step with its request and duration, and returns what the step returned.
|
|
514
|
+
const removeStepLog = configureEffect({
|
|
515
|
+
onStep: async (name, type, op, path) => {
|
|
516
|
+
const started = performance.now();
|
|
517
|
+
try {
|
|
518
|
+
return await op();
|
|
519
|
+
} finally {
|
|
520
|
+
const { requestId } = requestScope.getStore() ?? {};
|
|
521
|
+
stepLog.push({ requestId, name, path, ms: performance.now() - started });
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
await requestScope.run({ requestId: 'req_1' }, () => runEffect(registerUserFlow(input)));
|
|
527
|
+
assert.deepEqual(
|
|
528
|
+
stepLog.map((line) => [line.requestId, line.name]),
|
|
529
|
+
[
|
|
530
|
+
['req_1', 'cmdFindUser'],
|
|
531
|
+
['req_1', 'cmdSaveUser']
|
|
532
|
+
]
|
|
533
|
+
);
|
|
534
|
+
removeStepLog();
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
A Command that `onBeforeCommand` vetoes never reaches `onStep`, so log a veto where you make it. In tests, call `configureEffect()` with no arguments in a `beforeEach`, so a test that fails before removing its hooks does not leave them installed for the next.
|
|
538
|
+
|
|
539
|
+
**Per-call hooks.** `runEffect`'s third argument takes hooks for that call only. They are merged with the configured ones by the same rules: the configured wrappers run outside them, and the configured `onBeforeCommand` hooks run first. `inherit: false` leaves the configured hooks out. With configured hooks `C` and a call `K` that supplies only `onStep`:
|
|
540
|
+
|
|
541
|
+
```
|
|
542
|
+
inherit: true (default) inherit: false
|
|
543
|
+
|
|
544
|
+
onRun C.onRun (none)
|
|
545
|
+
onBeforeCommand C.onBeforeCommand (none)
|
|
546
|
+
onStep C.onStep( K.onStep( cmd ) ) K.onStep
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
`recordEffect` inherits, so recording inside an application that already traces still produces spans. `replayEffect` passes `inherit: false` unless `hooks: true`.
|
|
550
|
+
|
|
432
551
|
## Passing Runtime Context
|
|
433
552
|
|
|
434
553
|
Some values come from the framework (an authenticated tenant, a request ID, environment config) rather than from the data being processed. `Ask` lets a step read the `context` object passed to `runEffect` without passing it through every function:
|
|
@@ -454,18 +573,33 @@ app.post('/checkout', async (req, res) => {
|
|
|
454
573
|
|
|
455
574
|
Recording stores the context alongside the trace, so `Ask` replays with the values the original request saw. It is copied once per run, so read a value that can change while a run is under way, such as a switch an operator can flip to stop a batch, in a Command, whose result the trace records each time.
|
|
456
575
|
|
|
457
|
-
Keep the context to plain values such as IDs, flags and settings. Recording copies it into every trace, so a database client or connection pool in it puts its connection string in the trace, and one whose properties throw when read, as a lazy client's can, leaves the whole context out, so a replay needs it passed in. Reach a service from the Command's function, as `findProduct` reaches `db`. To run a flow against fakes, have the function that builds it take the services,
|
|
576
|
+
Keep the context to plain values such as IDs, flags and settings. Recording copies it into every trace, so a database client or connection pool in it puts its connection string in the trace, and one whose properties throw when read, as a lazy client's can, leaves the whole context out, so a replay needs it passed in. Reach a service from the Command's function, as `findProduct` reaches `db`. To run a flow against fakes or a test database, have the function that builds it take the services, and pass them in the test:
|
|
577
|
+
|
|
578
|
+
```js
|
|
579
|
+
// Takes its catalog, so a test can run it against a fake.
|
|
580
|
+
const makeFindProduct = (catalog) => (productId) => {
|
|
581
|
+
const cmdFindProduct = () => catalog.findProduct(productId);
|
|
582
|
+
return Command(cmdFindProduct, (product) => (product ? Success(product) : Failure('Product not found.')));
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
// The fake answers by the ID it receives, so the test also checks what the Command's function sends.
|
|
586
|
+
const findInFakeCatalog = makeFindProduct({ findProduct: async (id) => (id === 'abc' ? { id } : null) });
|
|
587
|
+
assert.deepEqual(await runEffect(findInFakeCatalog('abc')), Success({ id: 'abc' }));
|
|
588
|
+
assert.deepEqual(await runEffect(findInFakeCatalog('xyz')), Failure('Product not found.'));
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
A walk or a replay never runs a Command's function, so this is the test that catches one passing the wrong value.
|
|
458
592
|
|
|
459
593
|
## Retrying Transient Failures
|
|
460
594
|
|
|
461
|
-
`Retry` runs part of a flow again when
|
|
595
|
+
`Retry` runs part of a flow again when a Command's function throws. A `Failure` a step returned is not retried: the flow decided to stop, so the `Failure` passes on at once, unchanged. Options are given where `Retry` is used, since they describe one dependency; to reuse settings, share an object:
|
|
462
596
|
|
|
463
597
|
```js
|
|
464
598
|
const flakyNetwork = { attempts: 3, delay: 200, backoff: 2 };
|
|
465
599
|
Retry(fetchPrice(sku), flakyNetwork);
|
|
466
600
|
```
|
|
467
601
|
|
|
468
|
-
The
|
|
602
|
+
The settings are a plain object, so a test can check them without running anything:
|
|
469
603
|
|
|
470
604
|
```js
|
|
471
605
|
import { Success, Failure, Command, Retry, runEffect } from 'pure-effect';
|
|
@@ -484,7 +618,7 @@ assert.equal(weatherFn.type, 'Retry');
|
|
|
484
618
|
assert.equal(weatherFn.options.attempts, 3);
|
|
485
619
|
```
|
|
486
620
|
|
|
487
|
-
**Wrap the Command that fails, not the pipeline.** Each attempt
|
|
621
|
+
**Wrap the Command that fails, not the pipeline.** Each attempt runs everything inside the `Retry` again, including Commands that already succeeded:
|
|
488
622
|
|
|
489
623
|
```js
|
|
490
624
|
// Dangerous: a flaky receipt step charges the customer again on every attempt.
|
|
@@ -496,7 +630,7 @@ effectPipe(chargeCard, (charge) => Retry(sendReceipt(charge), { attempts: 3 }))(
|
|
|
496
630
|
|
|
497
631
|
Wrapping a pipeline is safe only when every Command in it is idempotent (safe to run more than once).
|
|
498
632
|
|
|
499
|
-
**Wrapping one Command is not always enough.** A Command's `next` is inside the `Retry` too, so
|
|
633
|
+
**Wrapping one Command is not always enough.** A Command's `next` is inside the `Retry` too, so a `next` that continues the flow puts everything after it inside the `Retry` as well:
|
|
500
634
|
|
|
501
635
|
```js
|
|
502
636
|
// Dangerous: `next` continues the booking, so every later step is inside the Retry.
|
|
@@ -506,9 +640,7 @@ Retry(
|
|
|
506
640
|
);
|
|
507
641
|
```
|
|
508
642
|
|
|
509
|
-
If a later Command's function throws, the `Retry`
|
|
510
|
-
|
|
511
|
-
Instead, leave the retried Command with its default `next` and continue in a later pipeline step, outside the `Retry`:
|
|
643
|
+
If a later Command's function throws, the `Retry` holds the seat and charges the card again. With two of these nested, a failure in the last step of a booking charges the card nine times. Instead, give the retried Command its default `next` and continue in a later step, outside the `Retry`:
|
|
512
644
|
|
|
513
645
|
```js
|
|
514
646
|
// Safe: the tree the Retry repeats is that one Command.
|
|
@@ -524,9 +656,9 @@ When every attempt fails, `runEffect` returns a `Failure` with this error:
|
|
|
524
656
|
{ retryExhausted: true, lastError: <the last error>, attempts: 3 }
|
|
525
657
|
```
|
|
526
658
|
|
|
527
|
-
In TypeScript, a `Retry` adds `RetryExhaustedError` to the
|
|
659
|
+
In TypeScript, a `Retry` adds `RetryExhaustedError` to the error union, beside the errors of the steps it wraps. `lastError` is typed `unknown`, since it is whatever the Command's function threw, so check it before using it, for example with `instanceof Error`.
|
|
528
660
|
|
|
529
|
-
**Use `onExhausted` to fall back when every attempt fails.** The fallback runs
|
|
661
|
+
**Use `onExhausted` to fall back when every attempt fails.** The fallback runs in place of the `Failure`. If it succeeds, its value continues down the pipeline; if it fails, its own `Failure` is returned as is. The fallback can be any Effect, such as a Command that reads a cache, or `Success(defaultValue)`:
|
|
530
662
|
|
|
531
663
|
```js
|
|
532
664
|
const fetchPrice = (sku) =>
|
|
@@ -536,9 +668,7 @@ const fetchPrice = (sku) =>
|
|
|
536
668
|
});
|
|
537
669
|
```
|
|
538
670
|
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
Every attempt is recorded, so a replay repeats the same sequence of failures, without the delays.
|
|
671
|
+
Every attempt and the fallback are recorded, so a replay repeats the same failures and the same fallback, without the delays. A fallback never starts in a `Parallel` branch that has already been cancelled. With `onExhausted` set, the fallback's error type takes the place of `RetryExhaustedError` in the TypeScript error union.
|
|
542
672
|
|
|
543
673
|
## Running Effects in Parallel
|
|
544
674
|
|
|
@@ -581,25 +711,27 @@ Parallel(work, (outcomes) => Success(outcomes.map((o) => (o.type === 'Success' ?
|
|
|
581
711
|
|
|
582
712
|
The outcomes are plain `Success` and `Failure` objects. Returning one of them from `next` is the same as returning any other `Failure`: the flow stops, and `Retry` does not run it again.
|
|
583
713
|
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
Fewer such errors reach the outcomes when a branch returns what it can as data. Catch an error the flow can handle inside the Command's function and return it (see [Which Errors Are Data](#which-errors-are-data)), and stop a batch by reading the operator's switch in a Command whose `next` returns a `Failure`, rather than by vetoing in `onBeforeCommand`:
|
|
714
|
+
**Collecting some failures and stopping on others.** `settled` decides for every failure at once. When a batch should note a missing record and go on, but stop everything when its credentials expire, leave `settled` off and decide in each branch: return what should be collected as a value inside a `Success`, and what should stop the batch as a `Failure`, which cancels the other branches:
|
|
587
715
|
|
|
588
716
|
```js
|
|
589
|
-
//
|
|
590
|
-
const
|
|
591
|
-
const
|
|
592
|
-
Command(
|
|
717
|
+
// A missing user is counted; an expired token stops the batch.
|
|
718
|
+
const fetchProfile = (userId) => {
|
|
719
|
+
const cmdFetchProfile = () => api.getProfile(userId); // resolves to { status, body }
|
|
720
|
+
return Command(cmdFetchProfile, (response) => {
|
|
721
|
+
if (response.status === 401) return Failure('auth_expired');
|
|
722
|
+
if (response.status === 404) return Success({ userId, found: false });
|
|
723
|
+
return Success({ userId, found: true, profile: response.body });
|
|
724
|
+
});
|
|
725
|
+
};
|
|
593
726
|
|
|
594
|
-
|
|
595
|
-
limit: 5,
|
|
596
|
-
settled: true
|
|
597
|
-
});
|
|
598
|
-
```
|
|
727
|
+
const fetchProfiles = (userIds) => Parallel(userIds.map(fetchProfile), { limit: 4 });
|
|
599
728
|
|
|
600
|
-
|
|
729
|
+
const profiles = fetchProfiles(['u1', 'u2']);
|
|
730
|
+
assert.deepEqual(profiles.effects[0].next({ status: 404 }), Success({ userId: 'u1', found: false }));
|
|
731
|
+
assert.deepEqual(profiles.effects[1].next({ status: 401 }), Failure('auth_expired'));
|
|
732
|
+
```
|
|
601
733
|
|
|
602
|
-
|
|
734
|
+
A Command whose function throws, such as on a network error, also stops the batch. Wrap it in `Retry` if the error is likely to pass, or catch it in the function and return it as data if it should be counted; see [Which Errors Are Data](#which-errors-are-data).
|
|
603
735
|
|
|
604
736
|
`limit` caps how many branches run at once; the rest start as others finish. Results and recorded paths stay in array order, so a limit changes only the pacing, and a trace recorded with a limit replays the same without one. A `limit` that is not a positive integer throws an `EffectTypeError` where the `Parallel` is built.
|
|
605
737
|
|
|
@@ -615,9 +747,9 @@ const fetchProfileUncancellable = (userId) => Command(() => fetch(`/users/${user
|
|
|
615
747
|
|
|
616
748
|
Outside a `Parallel`, the function is called with no arguments. A `Retry` inside a cancelled branch stops retrying.
|
|
617
749
|
|
|
618
|
-
|
|
750
|
+
### Undoing what succeeded when a branch fails
|
|
619
751
|
|
|
620
|
-
|
|
752
|
+
Without `settled`, the failing branch's `Failure` is the whole result, and the values of the branches that succeeded are dropped. When one of them did something that has to be undone, such as charging a card for an order whose stock then ran out, the code that called `runEffect` no longer has the charge to refund. Use `settled: true`, so `next` sees every outcome, and have it return the steps that undo whatever succeeded, followed by the failure:
|
|
621
753
|
|
|
622
754
|
```js
|
|
623
755
|
const reserveStock = (order) => {
|
|
@@ -677,6 +809,32 @@ assert.deepEqual(
|
|
|
677
809
|
|
|
678
810
|
A settled `Parallel` cancels nothing, so both steps always run to the end, and the undoing starts once both have finished. The undo steps are part of the flow, so a trace records them and a replay repeats them. An undo step that fails ends the flow with its own error rather than the original one; wrap it in `Retry` if it can fail for a moment.
|
|
679
811
|
|
|
812
|
+
### Errors no branch returned
|
|
813
|
+
|
|
814
|
+
A `Failure` among a settled `Parallel`'s outcomes can also hold an error the branch never returned: what one of its Commands threw, or what an `onBeforeCommand` hook vetoed it with. Neither is in the branch's declared error type, so give the code that reads the outcomes a case for an error it does not recognise, as for a run's result (see [TypeScript](#typescript-typed-errors-and-context)), rather than letting it fall into the last error it expects, which would report a vetoed charge as a declined card.
|
|
815
|
+
|
|
816
|
+
Fewer such errors reach the outcomes when a branch returns what it can as data. Catch an error the flow can handle inside the Command's function and return it (see [Which Errors Are Data](#which-errors-are-data)), and stop a batch by reading the operator's switch in a Command whose `next` returns a `Failure`, rather than by vetoing in `onBeforeCommand`:
|
|
817
|
+
|
|
818
|
+
```js
|
|
819
|
+
// Read before each charge, so a switch flipped mid-batch stops the charges that have not started.
|
|
820
|
+
const cmdBillingHalted = () => flags.get('billing.halted');
|
|
821
|
+
const billUnlessHalted = (subscription) =>
|
|
822
|
+
Command(cmdBillingHalted, (halted) => (halted ? Failure('halted') : billOne(subscription)));
|
|
823
|
+
|
|
824
|
+
Parallel(subscriptions.map(billUnlessHalted), (outcomes) => Success(outcomes.map(summarize)), {
|
|
825
|
+
limit: 5,
|
|
826
|
+
settled: true
|
|
827
|
+
});
|
|
828
|
+
```
|
|
829
|
+
|
|
830
|
+
The halt is then one of the branch's declared errors, typed like a declined card, and the trace records each read of the switch, so the batch replays. A vetoed Command leaves no entry in the trace, so a replay of a vetoed batch fails at the first veto.
|
|
831
|
+
|
|
832
|
+
Bugs in the flow are not collected. An `EffectTypeError`, thrown for a malformed flow, and an error thrown by a `next` function or a pure step both still escape a settled `Parallel`, after the other branches are cancelled.
|
|
833
|
+
|
|
834
|
+
### Replaying a cancelled `Parallel`
|
|
835
|
+
|
|
836
|
+
Which branch failed first and cancelled the others depends on timing, so it is recorded with the trace. A replay of a cancelled `Parallel` returns the same failure production did, and stops each other branch where production stopped it, rather than letting whichever branch the replay reaches first decide. The same holds when the branch that cancelled the others was a `next` function or a pure step that threw: the replay throws the same error. If the branch that cancelled the others no longer fails, or the `Parallel` no longer has that branch, the replay ends in a `TimeParadox` naming it. The trace also records how many branches each `Parallel` had, so a replay of one that has gained or lost a branch ends in a `TimeParadox` before any of its branches run.
|
|
837
|
+
|
|
680
838
|
## Composing Larger Flows
|
|
681
839
|
|
|
682
840
|
`effectPipe` runs steps in a straight line. Branching and joining use the same pieces:
|
|
@@ -712,6 +870,111 @@ When the lookup is written in place rather than reused, the Command's own `next`
|
|
|
712
870
|
|
|
713
871
|
**Pass only what the next steps need.** Avoid one object that collects everything computed so far. When a step's input is all it gets, it cannot depend on a value from far upstream without showing it, stale fields do not linger, and two steps cannot clash over the same key. Data also lives only as long as the flow needs it, which matters for credentials and personal data. In TypeScript, it keeps the pipeline type-checked: if an upstream step changes what it returns, the step that reads the value fails to compile instead of getting `undefined` at runtime.
|
|
714
872
|
|
|
873
|
+
In a generator flow, most of this comes for free. A step that branches into another flow is yielded like any other, as in `yield* step(processOrder(order))`. Values that do not depend on each other are joined with `const [cart, user] = yield* step(Parallel([fetchCart(input.cartId), fetchUser(input.userId)]))`. Values that do are variables, with no step to pass them on together; see [Where a generator helps](#where-a-generator-helps). Keep each decision in a step function that takes only what it needs, as the advice above says for a pipeline's steps.
|
|
874
|
+
|
|
875
|
+
## Writing Loops
|
|
876
|
+
|
|
877
|
+
A loop is written in two parts: a step that gets the list, and a `Parallel` over it, with `limit: 1` so the items run one after another, as in a `for` loop. The `async` version is usually split the same way. Paying a customer's unpaid invoices in order, and stopping at the first that fails:
|
|
878
|
+
|
|
879
|
+
```js
|
|
880
|
+
async function payUnpaidAsync(customerId) {
|
|
881
|
+
const invoices = await billing.findUnpaid(customerId);
|
|
882
|
+
for (const invoice of invoices) {
|
|
883
|
+
const receipt = await payments.charge(invoice);
|
|
884
|
+
await mailer.sendReceipt(receipt);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// First part: get the list.
|
|
889
|
+
const findUnpaidInvoices = (customerId) => {
|
|
890
|
+
const cmdFindUnpaid = () => billing.findUnpaid(customerId);
|
|
891
|
+
return Command(cmdFindUnpaid);
|
|
892
|
+
};
|
|
893
|
+
|
|
894
|
+
// Second part: the loop's body, a flow of its own for one invoice.
|
|
895
|
+
const chargeInvoice = (invoice) => {
|
|
896
|
+
const cmdChargeInvoice = () => payments.charge(invoice);
|
|
897
|
+
return Retry(Command(cmdChargeInvoice), { attempts: 3 });
|
|
898
|
+
};
|
|
899
|
+
|
|
900
|
+
const sendReceipt = (receipt) => {
|
|
901
|
+
const cmdSendReceipt = () => mailer.sendReceipt(receipt);
|
|
902
|
+
return Command(cmdSendReceipt);
|
|
903
|
+
};
|
|
904
|
+
|
|
905
|
+
const payInvoice = (invoice) => effectPipe(chargeInvoice, sendReceipt)(invoice);
|
|
906
|
+
|
|
907
|
+
// The loop: one body per invoice, run one at a time.
|
|
908
|
+
const payAll = (invoices) => Parallel(invoices.map(payInvoice), { limit: 1 });
|
|
909
|
+
|
|
910
|
+
const payUnpaid = (customerId) => effectPipe(findUnpaidInvoices, payAll)(customerId);
|
|
911
|
+
|
|
912
|
+
// The flow starts by getting the list, and hands what it gets to the loop.
|
|
913
|
+
const flow = payUnpaid('cus_1');
|
|
914
|
+
assert.equal(commandName(flow), 'cmdFindUnpaid');
|
|
915
|
+
assert.equal(flow.next([{ id: 1 }, { id: 2 }]).effects.length, 2);
|
|
916
|
+
|
|
917
|
+
// The body is tested on its own: the Retry holds only the charge as its effect, and its next leads to the receipt.
|
|
918
|
+
const body = payInvoice({ id: 1 });
|
|
919
|
+
assert.equal(commandName(body.effect), 'cmdChargeInvoice');
|
|
920
|
+
assert.equal(commandName(body.next({ id: 'receipt_1' })), 'cmdSendReceipt');
|
|
921
|
+
|
|
922
|
+
// An empty list runs nothing.
|
|
923
|
+
assert.deepEqual(await runEffect(payAll([])), Success([]));
|
|
924
|
+
```
|
|
925
|
+
|
|
926
|
+
Each invoice is paid after the one before it has finished, and the first that fails stops the rest from starting, as in the `async` version. When the payments can overlap, a higher `limit` runs several at a time.
|
|
927
|
+
|
|
928
|
+
The loop's body is a flow built for one item, so it can hold as many steps as the body of a `for` loop. Put a `Retry` inside it, on the step that needs one, since a `Retry` runs everything it wraps again (see [Retrying Transient Failures](#retrying-transient-failures)): around the whole loop it would charge the invoices already paid, and around the whole body a receipt that failed to send would charge the card again.
|
|
929
|
+
|
|
930
|
+
The `Parallel`'s `next` receives what each body returned, in order, so a total or a summary of the loop goes there: `Parallel(invoices.map(payInvoice), (receipts) => Success(receipts.length), { limit: 1 })`. To keep going past a failure, as a `try`/`catch` inside the loop would, add `settled: true`: every invoice is tried, and `next` receives one `Success` or `Failure` per invoice. See [Running Effects in Parallel](#running-effects-in-parallel).
|
|
931
|
+
|
|
932
|
+
In a generator flow, the same loop can be a `for` loop over the list, with the body's steps inside it:
|
|
933
|
+
|
|
934
|
+
```js
|
|
935
|
+
const payUnpaidGen = effectGen(function* (customerId) {
|
|
936
|
+
const invoices = yield* step(findUnpaidInvoices(customerId));
|
|
937
|
+
for (const invoice of invoices) yield* step(payInvoice(invoice));
|
|
938
|
+
});
|
|
939
|
+
|
|
940
|
+
// Every charge is declined, so both forms give up on the first invoice once its retries run out, with the same Failure.
|
|
941
|
+
const answers = {
|
|
942
|
+
cmdFindUnpaid: { result: [{ id: 1 }, { id: 2 }] },
|
|
943
|
+
cmdChargeInvoice: { error: new Error('declined') }
|
|
944
|
+
};
|
|
945
|
+
const answer = (asked) => answers[asked.name];
|
|
946
|
+
const fromLoop = await replayEffect(payUnpaidGen('cus_1'), answer);
|
|
947
|
+
const fromParallel = await replayEffect(payUnpaid('cus_1'), answer);
|
|
948
|
+
assert.equal(fromLoop.result.error.retryExhausted, true);
|
|
949
|
+
assert.deepEqual(fromLoop.result, fromParallel.result);
|
|
950
|
+
```
|
|
951
|
+
|
|
952
|
+
It stops at the first invoice that fails, as the `Parallel` with `limit: 1` does. Use the `Parallel` instead when the loop is long, since a generator run keeps every step's result until it ends. Use it too when payments can overlap, with a higher `limit`, or when the loop has to keep going past a failure, with `settled: true`, since a `catch` in the body cannot recover. The two forms record differently, so a trace recorded from one replays against the other as a `TimeParadox`.
|
|
953
|
+
|
|
954
|
+
Sometimes getting the list is a loop of its own. Paging through an API with a cursor is one: each request needs the cursor from the page before, so the requests cannot be listed in advance. Write that loop as an ordinary `async` function, call it from one Command, and map over the list it returns, as above:
|
|
955
|
+
|
|
956
|
+
```js
|
|
957
|
+
async function fetchAllOrders() {
|
|
958
|
+
const orders = [];
|
|
959
|
+
let cursor = null;
|
|
960
|
+
do {
|
|
961
|
+
const page = await api.listOrders(cursor);
|
|
962
|
+
orders.push(...page.items);
|
|
963
|
+
cursor = page.nextCursor;
|
|
964
|
+
} while (cursor);
|
|
965
|
+
return orders;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
const listAllOrders = () => {
|
|
969
|
+
const cmdListAllOrders = () => fetchAllOrders();
|
|
970
|
+
return Command(cmdListAllOrders);
|
|
971
|
+
};
|
|
972
|
+
```
|
|
973
|
+
|
|
974
|
+
To the flow, the whole loop is one step. A trace records the finished list as that step's result, and a replay hands the list back without replaying the pages. A `Retry` around the Command starts again from the first page. A flow test cannot see inside it, so, like any Command's function, it is left to an integration test.
|
|
975
|
+
|
|
976
|
+
The loop belongs in the flow only when the flow has to decide something on each pass, such as stopping at the first order that matches, or saving each page as it arrives. Then the Command's `next` returns the Command for the next page instead of a `Success`, until there are no more pages.
|
|
977
|
+
|
|
715
978
|
## Which Errors Are Data
|
|
716
979
|
|
|
717
980
|
Pure Effect has no catch, on purpose. A flow's outcomes are of two kinds, and each is written differently.
|
|
@@ -773,6 +1036,96 @@ Retry(
|
|
|
773
1036
|
|
|
774
1037
|
In short, **you can recover from an error your I/O produced, but you cannot catch a `Failure` a step returned.** Only the code that called `runEffect` acts on it. For the same reason, do not throw business errors from a Command's function: a throw there tells `Retry` that the I/O broke, and `Retry` will try again. A throw anywhere else in the flow is treated as a bug and thrown as it is instead of returned as a `Failure`: `runEffect` rejects with it, or, from a step before the first Command, the call that builds the flow throws it.
|
|
775
1038
|
|
|
1039
|
+
### A malformed flow
|
|
1040
|
+
|
|
1041
|
+
A flow that is not made of Effects is a bug, so it throws an `EffectTypeError` that says where, rather than returning a `Failure`. The steps before a flow's first Command run as it is built, so a mistake in one of them is thrown by the call that builds the flow, as `registerUserFlow(input)` would throw if its first step returned a plain object:
|
|
1042
|
+
|
|
1043
|
+
```
|
|
1044
|
+
Step 'validateRegistration' returned a plain object. Return Success, Failure, Command, Ask,
|
|
1045
|
+
Retry, or Parallel: a plain value has to be wrapped, as in Success(value).
|
|
1046
|
+
```
|
|
1047
|
+
|
|
1048
|
+
A mistake after the first Command makes `runEffect` reject. That covers a missing `return`, a `next` that returns a plain value, a step or `next` written as `async` (do the awaited work in a Command instead), and `runEffect(flow)` where `runEffect(flow(input))` was meant. The building blocks check their arguments where they are built, before their own I/O runs, so `Command(db.findUser(email))`, which makes the call while the flow is built, `Command(fn, { name })`, with the metadata in `next`'s place, and a `Parallel` or `effectPipe` given the wrong thing each throw an `EffectTypeError` there; one built inside a `next` is checked when that `next` runs.
|
|
1049
|
+
|
|
1050
|
+
## Generator Flows in Depth
|
|
1051
|
+
|
|
1052
|
+
What [Writing Flows as Generators](#writing-flows-as-generators) leaves out: when a body runs again, what a `catch` or `finally` in it can do, and the mistakes `effectGen` catches.
|
|
1053
|
+
|
|
1054
|
+
### What runs once, and what runs again
|
|
1055
|
+
|
|
1056
|
+
A run goes through the body once, top to bottom, as `async` code does. Anything that uses the flow a second time runs it again from the top, since a generator cannot be copied: running one flow value again, or putting it in two branches of a `Parallel`, so build the flow from its input for each run; a `Retry` around the flow, which starts the body afresh for each attempt, as a retried `async` function does; and a test that hands an earlier step a second answer, to walk another branch:
|
|
1057
|
+
|
|
1058
|
+
```js
|
|
1059
|
+
const flow = registerUserFlowGen(input);
|
|
1060
|
+
assert.equal(commandName(flow), 'cmdFindUser');
|
|
1061
|
+
|
|
1062
|
+
// The first answer finds a user, so the flow stops there.
|
|
1063
|
+
assert.deepEqual(flow.next({ id: 1 }), Failure('Email already in use.'));
|
|
1064
|
+
|
|
1065
|
+
// A second answer to the same step runs the body again from the top, and this time it goes on to save.
|
|
1066
|
+
assert.equal(commandName(flow.next(null)), 'cmdSaveUser');
|
|
1067
|
+
```
|
|
1068
|
+
|
|
1069
|
+
So keep the body to its own variables. When it runs again, it has to ask for the same steps in the same order, and a body that asks for a different one stops the run with an `EffectTypeError` naming both. `Date.now()`, a random ID, or a variable outside the body can change between runs: get the first two from a Command, as a pipeline does, and pass the third in the flow's input.
|
|
1070
|
+
|
|
1071
|
+
### How a generator flow stops
|
|
1072
|
+
|
|
1073
|
+
`return` ends the flow. A plain value is its `Success`, `return Failure(error)` stops it with that error, and returning a Command or any other Effect runs it, as `return fetch(url)` does in an `async` function. A `throw` in the body is a bug, as one in a pipeline step is, and `runEffect` rejects with it.
|
|
1074
|
+
|
|
1075
|
+
When a step stops the flow, because its Command threw or it returned a `Failure`, the body's `catch` and `finally` blocks run, as they would for an `await` that rejected. The `catch` gets an error saying where the flow stopped, not the original, which is the flow's `Failure`, so it cannot branch on the original's fields: `e.code` and the like are `undefined`, and `e.name` is `FlowStopped`. It can log, but it cannot recover:
|
|
1076
|
+
|
|
1077
|
+
```js
|
|
1078
|
+
const unreliableDb = {
|
|
1079
|
+
saveUser: async () => {
|
|
1080
|
+
throw new Error('connection reset');
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
|
|
1084
|
+
const saveUser = effectGen(function* (user) {
|
|
1085
|
+
try {
|
|
1086
|
+
const cmdSaveUser = () => unreliableDb.saveUser(user);
|
|
1087
|
+
return yield* step(Command(cmdSaveUser));
|
|
1088
|
+
} catch (error) {
|
|
1089
|
+
// Runs when the save throws. It can log, and it has to let the error pass.
|
|
1090
|
+
throw error;
|
|
1091
|
+
}
|
|
1092
|
+
});
|
|
1093
|
+
|
|
1094
|
+
const result = await runEffect(saveUser({ id: 1 }));
|
|
1095
|
+
assert.equal(result.error.message, 'connection reset');
|
|
1096
|
+
```
|
|
1097
|
+
|
|
1098
|
+
A `catch` that returns or carries on, one that throws a different error, and a `finally` that runs another step all stop the run with an `EffectTypeError` that says so:
|
|
1099
|
+
|
|
1100
|
+
```js
|
|
1101
|
+
const saveLater = effectGen(function* (user) {
|
|
1102
|
+
try {
|
|
1103
|
+
const cmdSaveUser = () => unreliableDb.saveUser(user);
|
|
1104
|
+
return yield* step(Command(cmdSaveUser));
|
|
1105
|
+
} catch {
|
|
1106
|
+
return 'saved later';
|
|
1107
|
+
}
|
|
1108
|
+
});
|
|
1109
|
+
|
|
1110
|
+
await assert.rejects(runEffect(saveLater({ id: 1 })), /kept going after Command 'cmdSaveUser' stopped it/);
|
|
1111
|
+
```
|
|
1112
|
+
|
|
1113
|
+
Handle an error the flow expects inside the Command's function, and return it as data for the body to branch on; recover from one that keeps happening with `Retry`'s `onExhausted`. See [Which Errors Are Data](#which-errors-are-data). Cleanup for the whole run goes in a `try`/`finally` around `runEffect`, as it does for a pipeline.
|
|
1114
|
+
|
|
1115
|
+
### Mistakes it catches
|
|
1116
|
+
|
|
1117
|
+
| Written | What happens |
|
|
1118
|
+
| --- | --- |
|
|
1119
|
+
| `yield step(x)`, without the star | an `EffectTypeError`: write `yield*` |
|
|
1120
|
+
| `yield x` | an `EffectTypeError`: write `yield* step(x)` |
|
|
1121
|
+
| `yield* x`, without `step` | the engine's `TypeError`, which on V8 becomes an `EffectTypeError` saying to write `yield* step(x)` |
|
|
1122
|
+
| `const found = step(x)`, then `found.id` | an `EffectTypeError`: `step(...)` was used as a value |
|
|
1123
|
+
| `[...step(x)]` or `for (const v of step(x))` | an `EffectTypeError`: `step(...)` was iterated outside `yield*` |
|
|
1124
|
+
| `step(db.findUser(email))` | an `EffectTypeError`: put the call in a Command |
|
|
1125
|
+
| `effectGen(async function* () {})` | an `EffectTypeError`: write `function*` |
|
|
1126
|
+
|
|
1127
|
+
In TypeScript, most of these do not compile; see [TypeScript](#typescript-typed-errors-and-context).
|
|
1128
|
+
|
|
776
1129
|
## TypeScript: Typed Errors and Context
|
|
777
1130
|
|
|
778
1131
|
The bundled declarations need TypeScript 5.1 or later.
|
|
@@ -794,7 +1147,11 @@ if (result.type === 'Failure') {
|
|
|
794
1147
|
}
|
|
795
1148
|
```
|
|
796
1149
|
|
|
797
|
-
The annotations are optional. Without them, the union holds whatever each step can pass to `Failure`, each error kept exactly as written, whether a string or an object, and a step that cannot fail, such as a Command without a `next`, adds nothing.
|
|
1150
|
+
The annotations are optional. Without them, the union holds whatever each step can pass to `Failure`, each error kept exactly as written, whether a string or an object, and a step that cannot fail, such as a Command without a `next`, adds nothing.
|
|
1151
|
+
|
|
1152
|
+
**The union covers only the `Failure`s your steps return.** A Command whose function throws, or that an `onBeforeCommand` hook vetoes, also ends the run with a `Failure`, and its error is not in the union. So where the result is handled, give it one fallback, such as a `default` in a `switch` over `result.error`, and treat what reaches it as a server error; the same goes for the outcomes a settled `Parallel` hands `next`. One fallback covers the whole flow: catch inside a Command's function only what the flow can handle, and let the rest throw, which is also what lets `Retry` act on it.
|
|
1153
|
+
|
|
1154
|
+
To check for a thrown error, copy it into a variable typed `unknown` first, as in `const error: unknown = result.error`, since TypeScript refuses `instanceof Error` on an error type made only of strings, or on a flow that declares none.
|
|
798
1155
|
|
|
799
1156
|
To type what a Command's function returns, such as a JSON response, write the function's result type, as in `Command((): Promise<User | null> => fetchJson(url), next)`. `Command<User | null>(…)` also compiles, but with some type arguments given TypeScript infers none of the others, so that Command's errors are typed `unknown`, which hides the rest of the union.
|
|
800
1157
|
|
|
@@ -819,6 +1176,43 @@ const result = await runEffect(findProduct('abc'), { tenant: 'acme', requestId:
|
|
|
819
1176
|
|
|
820
1177
|
Every step's context counts, so a pipeline needs all the contexts its steps read, even when the first step reads none, and a `Parallel` needs every context its branches read. `runEffect` requires a context whenever the flow reads one, since the flow would otherwise get an empty object, and checks one passed as a variable against what the flow reads, as it checks one written in place, so a variable whose type lacks a field the flow reads does not compile. `recordEffect`, `replayEffect` and `timeTravel` check a context the same way, and `replayEffect` given a resolver requires one, since a resolver holds none.
|
|
821
1178
|
|
|
1179
|
+
### Generator flows
|
|
1180
|
+
|
|
1181
|
+
`effectGen` infers everything from the body. Each `yield*` is typed by its own step, the error union collects every step's errors and every `Failure` the body returns, and the context collects what every step reads:
|
|
1182
|
+
|
|
1183
|
+
```ts
|
|
1184
|
+
const registerUser = effectGen(function* (input: { email: string }) {
|
|
1185
|
+
const found = yield* step(findUser(input.email)); // User | null
|
|
1186
|
+
if (found) return Failure('EMAIL_TAKEN');
|
|
1187
|
+
return yield* step(saveUser(input));
|
|
1188
|
+
});
|
|
1189
|
+
// (input: { email: string }) => Effect<User, 'EMAIL_TAKEN' | the errors findUser and saveUser declare>
|
|
1190
|
+
```
|
|
1191
|
+
|
|
1192
|
+
`yield* x` without `step`, reading a property of a step, and an `async function*` do not compile, and a body that returns an untyped value keeps its steps' errors. Returning a step or a Promise compiles, so that a generic helper returning a value of its type parameter does too, and fails when it runs. `yield step(x)` without the star does, and fails when it runs. Name the context `Ask()` reads as `Ask<AppContext>()`.
|
|
1193
|
+
|
|
1194
|
+
### Testing a flow in TypeScript
|
|
1195
|
+
|
|
1196
|
+
A flow is typed as any kind of step it could start with, since validation may already have returned a `Success` or a `Failure`, so `.cmd` and `.next` compile only after the test checks that the step is a Command. `node:assert`'s `assert(step.type === 'Command')` is such a check, and TypeScript follows it. Jest's and Vitest's `expect` is not, so a walk needs a check at every step, and a small helper makes that one line per step with any test framework:
|
|
1197
|
+
|
|
1198
|
+
```ts
|
|
1199
|
+
import assert from 'node:assert/strict';
|
|
1200
|
+
import { commandName } from 'pure-effect';
|
|
1201
|
+
import type { Effect } from 'pure-effect';
|
|
1202
|
+
|
|
1203
|
+
// Fails unless the step is the Command named, and returns it typed as one.
|
|
1204
|
+
function assertCommand<T, E, C>(step: Effect<T, E, C>, name: string) {
|
|
1205
|
+
assert(step.type === 'Command', `expected ${name}, got ${step.type}`);
|
|
1206
|
+
assert.equal(commandName(step), name);
|
|
1207
|
+
return step;
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
const step1 = assertCommand(registerUserFlow(input), 'cmdFindUser');
|
|
1211
|
+
assertCommand(step1.next(null), 'cmdSaveUser');
|
|
1212
|
+
```
|
|
1213
|
+
|
|
1214
|
+
For a step that returns its Command directly, as in `ensureEmailAvailable(input).next(found)`, `next` is checked against what the Command's function returns, so where [Testing Without Mocks](#testing-without-mocks) passes `{ id: 1 }` for a user that was found, a TypeScript test passes a whole user, of the type `db.findUser` returns. A Command reached any other way, by walking the whole flow or through an `Ask`'s `next`, accepts any value, since its type does not say which Command it is.
|
|
1215
|
+
|
|
822
1216
|
## Why Pure Effect
|
|
823
1217
|
|
|
824
1218
|
**vs. Temporal and durable execution (Restate, Inngest):** The closest relatives, built on the same idea: record what every step returned and replay it. Those engines store the history on a server and resume workflows automatically after a crash. Pure Effect leaves storage and restarts to your application, and there is no infrastructure to run.
|
|
@@ -886,9 +1280,9 @@ Use `meta.name` in code that gets minified, since a minifier renames functions a
|
|
|
886
1280
|
|
|
887
1281
|
Returns a Command's name, chosen in the order above, so a test checks a step by the name its trace would record: `assert.equal(commandName(step), 'cmdFindUser')`. Anything but a Command throws an `EffectTypeError`.
|
|
888
1282
|
|
|
889
|
-
#### `Ask(nextFn)`
|
|
1283
|
+
#### `Ask(nextFn?)`
|
|
890
1284
|
|
|
891
|
-
Returns `{ type: 'Ask', next }`. Passes the `context` from `runEffect` into `nextFn`.
|
|
1285
|
+
Returns `{ type: 'Ask', next }`. Passes the `context` from `runEffect` into `nextFn`. With no argument, the flow gets the context itself, as `yield* step(Ask())` reads it.
|
|
892
1286
|
|
|
893
1287
|
#### `Retry(effect, options?)`
|
|
894
1288
|
|
|
@@ -935,6 +1329,19 @@ In either language, a Command a step builds and does not return never runs, and
|
|
|
935
1329
|
|
|
936
1330
|
Return the Command, and have its `next` return the value the rest of the pipeline needs.
|
|
937
1331
|
|
|
1332
|
+
#### `effectGen(body)`
|
|
1333
|
+
|
|
1334
|
+
Returns a flow function, `(input) => Effect`, from a generator function, `function* (input) { ... }`. See [Writing Flows as Generators](#writing-flows-as-generators).
|
|
1335
|
+
|
|
1336
|
+
- Calling it runs the body up to its first `yield*`, so a `Failure` before the first step comes back at once, as a pipeline's does.
|
|
1337
|
+
- `return value` is `Success(value)`, `return Failure(error)` stops the flow, and a returned Effect runs.
|
|
1338
|
+
- When a step stops the flow, the body's `catch` and `finally` blocks run; a `catch` that recovers or throws another error, or a `finally` that runs a step, rejects the run.
|
|
1339
|
+
- An `async function*`, and a body that yields anything but `yield* step(effect)`, throws an `EffectTypeError`.
|
|
1340
|
+
|
|
1341
|
+
#### `step(effect)`
|
|
1342
|
+
|
|
1343
|
+
Wraps an Effect for `yield*` inside `effectGen`, which gives back its value: `const user = yield* step(findUser(email))`. Anything but an Effect throws an `EffectTypeError`, and so does using the result any other way than `yield*`.
|
|
1344
|
+
|
|
938
1345
|
### Running a flow
|
|
939
1346
|
|
|
940
1347
|
#### `runEffect(effect, context?, callConfig?)`
|
|
@@ -942,66 +1349,19 @@ Return the Command, and have its `next` return the value the rest of the pipelin
|
|
|
942
1349
|
Runs a flow and resolves with its `Success` or `Failure`.
|
|
943
1350
|
|
|
944
1351
|
- `context`: what `Ask` reads, also passed to `onBeforeCommand`. `context.flowName` names the run in traces and telemetry.
|
|
945
|
-
- `callConfig`: `onStep`, `onRun` and `onBeforeCommand` for this call only, added to the
|
|
946
|
-
|
|
947
|
-
A flow that is not made of Effects is a bug, so it throws an `EffectTypeError` that says where, rather than returning a `Failure`. The steps before a flow's first Command run as it is built, so a mistake in one of them, as in this first step, is thrown by the call that builds the flow, `registerUserFlow(input)`; a mistake after the first Command makes `runEffect` reject:
|
|
948
|
-
|
|
949
|
-
```
|
|
950
|
-
Step 'validateRegistration' returned a plain object. Return Success, Failure, Command, Ask,
|
|
951
|
-
Retry, or Parallel: a plain value has to be wrapped, as in Success(value).
|
|
952
|
-
```
|
|
953
|
-
|
|
954
|
-
That covers a missing `return`, a `next` that returns a plain value, a step or `next` written as `async` (do the awaited work in a Command instead), and `runEffect(flow)` where `runEffect(flow(input))` was meant. The building blocks check their arguments where they are built, before their own I/O runs, so `Command(db.findUser(email))`, which makes the call while the flow is built, `Command(fn, { name })`, with the metadata in `next`'s place, and a `Parallel` or `effectPipe` given the wrong thing each throw an `EffectTypeError` there; one built inside a `next` is checked when that `next` runs. A throw from a Command's function, or from an `onBeforeCommand` veto, is a `Failure`; a throw from a `next` or a pure step is a bug too, and is thrown as it is, in the same two places.
|
|
1352
|
+
- `callConfig`: `onStep`, `onRun` and `onBeforeCommand` for this call only, added to the configured hooks, or used alone with `inherit: false`; see [Hooks](#hooks).
|
|
1353
|
+
- A throw from a Command's function, or an `onBeforeCommand` veto, ends the run with a `Failure`. A malformed flow, or a throw from a `next` or a pure step, is a bug and is thrown: by the call that builds the flow when it comes before the first Command, and otherwise as a rejection of `runEffect`. See [Which Errors Are Data](#which-errors-are-data).
|
|
955
1354
|
|
|
956
1355
|
#### `configureEffect(...configs)`
|
|
957
1356
|
|
|
958
|
-
Adds a layer of hooks for the whole process and returns a function that removes
|
|
1357
|
+
Adds a layer of hooks for the whole process and returns a function that removes that layer only. Several configurations passed to one call form one layer. `configureEffect()` with no arguments removes every layer, and a call whose arguments are all `undefined` changes nothing. A configuration that is not an object, a key other than the three below, a `retry` key, and a hook that is not a function, `null` included, each throw a `TypeError` before anything is installed. See [Hooks](#hooks).
|
|
959
1358
|
|
|
960
|
-
|
|
961
|
-
const remove = configureEffect(telemetryHooks(), recordingHooks({ sink }));
|
|
962
|
-
// the same as configureEffect(telemetryHooks()) followed by configureEffect(recordingHooks({ sink }))
|
|
963
|
-
remove();
|
|
964
|
-
```
|
|
965
|
-
|
|
966
|
-
- `onRun(effect, pipeline, flowName, initialInput)`: wraps the whole run. It must `await pipeline()` and return its result. `initialInput` is what the flow was called with when `effectPipe` built it, and `undefined` otherwise; pass it on to any hook it calls.
|
|
1359
|
+
- `onRun(effect, pipeline, flowName, initialInput)`: wraps the whole run once, retries included. It must `await pipeline()` and return its result. `initialInput` is what the flow was called with when `effectPipe` built it, and `undefined` otherwise; pass it on to any hook it calls.
|
|
967
1360
|
- `onStep(name, type, op, path)`: wraps each Command, and each `Parallel` with `name` and `type` both `'Parallel'`. It must `await op()` and return its result, and pass `path` on to any hook it calls, since a replay matches steps on it.
|
|
968
1361
|
- For a Command, `op()` returns a promise, even for a synchronous function. Returning a value without calling `op()` answers for the Command, which is how replay works, and throwing without calling it counts as the Command failing.
|
|
969
1362
|
- A throw after `op()` succeeded, or `undefined` returned in place of its value, as a hook that forgot its `return` or its `await` does, is a bug in the hook: the run rejects, and `Retry` does not run the Command again.
|
|
970
|
-
- For a `Parallel`, `op()` runs the branches, so a hook must call it or the run rejects with a `TypeError`. It returns which branch, if any, cancelled the others, and how many branches there were, as in `{ cancelled: true, branch: 0, branches: 2 }`, even when a branch threw
|
|
971
|
-
- `onBeforeCommand(command, context)`: runs before each Command. A throw vetoes the Command: the run returns a `Failure` carrying the thrown error, and `Retry` does not retry it. A vetoed Command leaves no entry in a trace, so a replay of that run fails where it was vetoed;
|
|
972
|
-
|
|
973
|
-
Layers run in the order they were installed, the first outermost, so a result or a thrown error unwinds from the innermost hook out:
|
|
974
|
-
|
|
975
|
-
```
|
|
976
|
-
runEffect(flow(input))
|
|
977
|
-
│
|
|
978
|
-
├─ telemetry.onRun first configuration: outermost
|
|
979
|
-
│ └─ recording.onRun last configuration: innermost
|
|
980
|
-
│ │
|
|
981
|
-
│ │ for each Command:
|
|
982
|
-
│ ├─ telemetry.onBeforeCommand interceptors all run, in the order given
|
|
983
|
-
│ ├─ recording.onBeforeCommand
|
|
984
|
-
│ ├─ telemetry.onStep
|
|
985
|
-
│ │ └─ recording.onStep closest to the Command
|
|
986
|
-
│ │ └─ cmd()
|
|
987
|
-
│ │ ┌─ recording.onStep returns a result, or a thrown error, unwinds
|
|
988
|
-
│ ├─ telemetry.onStep returns from the inside out
|
|
989
|
-
│ │
|
|
990
|
-
│ ┌─ recording.onRun returns
|
|
991
|
-
├─ telemetry.onRun returns
|
|
992
|
-
```
|
|
993
|
-
|
|
994
|
-
**Per-call hooks.** The hooks in a `callConfig` are merged over the configured ones by the same rules, the configured wrappers outside and the configured `onBeforeCommand` hooks first. `inherit: false` leaves the configured hooks out. With configured hooks `C` and a call `K` that supplies only `onStep`:
|
|
995
|
-
|
|
996
|
-
```
|
|
997
|
-
inherit: true (default) inherit: false
|
|
998
|
-
|
|
999
|
-
onRun C.onRun (none)
|
|
1000
|
-
onBeforeCommand C.onBeforeCommand (none)
|
|
1001
|
-
onStep C.onStep( K.onStep( cmd ) ) K.onStep
|
|
1002
|
-
```
|
|
1003
|
-
|
|
1004
|
-
`recordEffect` inherits, so recording inside an application that already traces still produces spans. `replayEffect` passes `inherit: false` unless `hooks: true`.
|
|
1363
|
+
- For a `Parallel`, `op()` runs the branches, so a hook must call it or the run rejects with a `TypeError`. It returns which branch, if any, cancelled the others, and how many branches there were, as in `{ cancelled: true, branch: 0, branches: 2 }`, even when a branch threw, which adds `threw: true`.
|
|
1364
|
+
- `onBeforeCommand(command, context)`: runs before each Command. A throw vetoes the Command: the run returns a `Failure` carrying the thrown error, and `Retry` does not retry it. A vetoed Command leaves no entry in a trace, so a replay of that run fails where it was vetoed; see [Errors no branch returned](#errors-no-branch-returned).
|
|
1005
1365
|
|
|
1006
1366
|
### Recording and replay
|
|
1007
1367
|
|
|
@@ -1009,7 +1369,7 @@ onStep C.onStep( K.onStep( cmd ) ) K.onStep
|
|
|
1009
1369
|
|
|
1010
1370
|
Returns `{ onStep, entries, toTrace }`, a hook that records every step of a run, passed as `runEffect(flow, context, { onStep })`. Give each run its own recorder: one shared by a whole application mixes requests into one trace, which a replay refuses. `recordEffect` and the [recording example](https://github.com/aycangulez/pure-effect/blob/main/examples/recording-example.js) both do this for you.
|
|
1011
1371
|
|
|
1012
|
-
- `onStep`: the hook. Recording never changes a run's outcome.
|
|
1372
|
+
- `onStep`: the hook. Recording never changes a run's outcome.
|
|
1013
1373
|
- `entries`: the steps recorded so far, one per Command and one per `Parallel`. `path` is the step's position in the flow, which a replay matches on; an older entry with `error` and no `threw` still counts as a throw.
|
|
1014
1374
|
|
|
1015
1375
|
```text
|
|
@@ -1021,31 +1381,11 @@ Returns `{ onStep, entries, toTrace }`, a hook that records every step of a run,
|
|
|
1021
1381
|
because 'redact' threw on it or the 'copy' failed
|
|
1022
1382
|
```
|
|
1023
1383
|
|
|
1024
|
-
- `toTrace(meta)`: the entries as a trace, with `meta`'s `initialInput`, `context`, `flowName` and `version`, copied into the form JSON stores when it is called.
|
|
1025
|
-
- `options.redact(value, name, kind)`: returns what the trace stores in place of `value`. `kind` is `'result'`, `'error'`, `'initialInput'` or `'context'`, and `name` is the Command's name, or the kind.
|
|
1384
|
+
- `toTrace(meta)`: the entries as a trace, with `meta`'s `initialInput`, `context`, `flowName` and `version`, copied into the form JSON stores when it is called. If a Command can change the input or the context, as an ORM save that adds an id does, call it before the run for those and again afterwards for the entries, as `recordEffect` does.
|
|
1385
|
+
- `options.redact(value, name, kind)`: returns what the trace stores in place of `value`. `kind` is `'result'`, `'error'`, `'initialInput'` or `'context'`, and `name` is the Command's name, or the kind. See [Keeping secrets out of a trace](#keeping-secrets-out-of-a-trace).
|
|
1026
1386
|
- `options.maxEntries`: the most entries a trace keeps; the rest are counted in `dropped`, and a replay stops at the first step the trace lacks.
|
|
1027
1387
|
- `options.stack`: record stack traces for thrown errors (off by default).
|
|
1028
|
-
|
|
1029
|
-
Results are copied as they are recorded, so a later step cannot change them; see [Recording in Production](#recording-in-production) for what a copy keeps. When writing `redact`, check a value before replacing a field in it, since `{ ...value, email: '[redacted]' }` turns a `null` into an object and the replay takes the other branch:
|
|
1030
|
-
|
|
1031
|
-
```js
|
|
1032
|
-
// Masks a field only where there is one, so a lookup that found nothing still records null.
|
|
1033
|
-
const mask = (value, field) =>
|
|
1034
|
-
value && typeof value === 'object' && field in value ? { ...value, [field]: '[redacted]' } : value;
|
|
1035
|
-
|
|
1036
|
-
const redact = (value, name, kind) => {
|
|
1037
|
-
if (kind === 'initialInput') return mask(value, 'cardNumber');
|
|
1038
|
-
if (kind === 'context') return mask(value, 'authToken');
|
|
1039
|
-
if (kind === 'error') return mask(value, 'attempted');
|
|
1040
|
-
return name === 'cmdFetchUser' ? mask(value, 'email') : value;
|
|
1041
|
-
};
|
|
1042
|
-
recorder({ redact });
|
|
1043
|
-
|
|
1044
|
-
assert.equal(redact(null, 'cmdFetchUser', 'result'), null); // still nothing found
|
|
1045
|
-
assert.equal(redact('card_declined', 'cmdCharge', 'error'), 'card_declined'); // still a string
|
|
1046
|
-
```
|
|
1047
|
-
|
|
1048
|
-
A replay rebuilds the flow from the redacted input and context, so a field a step checks, such as a password, needs a stand-in the check treats the same way, as the recording example in [Recording in Production](#recording-in-production) does, and a context field an `Ask` reads should stay.
|
|
1388
|
+
- A value `redact` throws on, or one JSON cannot hold, is left out and marked `unrecorded`, on its entry or, for the input and context, in the trace's `unrecorded`, as in `{ context: 'copy' }`. A replay stops there with a `ReplayError` rather than hand the flow a stand-in. See [Recording in Production](#recording-in-production) for what a copy keeps.
|
|
1049
1389
|
|
|
1050
1390
|
#### `recordEffect(flowFn, initialInput, options?)`
|
|
1051
1391
|
|
|
@@ -1053,16 +1393,16 @@ Runs a flow for real while recording, returning `{ result, trace }`. Accepts `re
|
|
|
1053
1393
|
|
|
1054
1394
|
#### `replayEffect(effect, traceOrResolver, options?)`
|
|
1055
1395
|
|
|
1056
|
-
Runs a flow with each Command answered from a trace instead of run, and returns `{ result, unreached }`: the flow's outcome, and the recorded steps it never asked for
|
|
1396
|
+
Runs a flow with each Command answered from a trace instead of run, and returns `{ result, unreached }`: the flow's outcome, and the recorded steps it never asked for. A flow that no longer matches the trace ends in a `Failure` whose `error` is a `TimeParadox`, or a `ReplayError` for a step the trace lacks; neither is thrown, so a test checks `error.name`. A malformed trace rejects with a `ReplayError`. See [Time-Travel Debugging](#time-travel-debugging).
|
|
1057
1397
|
|
|
1058
|
-
- `traceOrResolver`: a trace, its bare entries, or a resolver
|
|
1398
|
+
- `traceOrResolver`: a trace, its bare entries, or a resolver: a function that answers each step with `{ result }`, `{ error }`, or `undefined` for a step it has no record of. Any other answer, `null` included, or a throw from the resolver, rejects the replay. With a resolver, `unreached` is absent. See [Replaying from your own storage](#replaying-from-your-own-storage).
|
|
1399
|
+
- A resolver is also asked about each `Parallel`, with `step.type` set to `'Parallel'`: answering with the recorded cancellation as `{ result }` replays it as production decided, and anything else replays it by timing.
|
|
1059
1400
|
- `options.context`: the context for `Ask`, by default the one the trace recorded. A resolver has none, so pass one if the flow reads `Ask`, and a trace whose context could not be recorded refuses to replay without one.
|
|
1060
|
-
- `options.onMissing`: `'throw'` (default) stops at a step the trace lacks
|
|
1401
|
+
- `options.onMissing`: `'throw'` (default) stops at a step the trace lacks; `'execute'` runs its Command for real, so use it only where Commands reach test doubles or only read. A trace that dropped entries refuses `'execute'`, and a flow that changed shape, as when a Command is newly wrapped in `Retry` or moved into a new `Parallel` branch, stops at a `TimeParadox` even under `'execute'`.
|
|
1061
1402
|
- `options.fastRetry` (default `true`): strip `Retry` delays.
|
|
1062
1403
|
- `options.hooks` (default `false`): run the replay inside the configured hooks, a configured recorder included, so they see the replayed steps. Off, a replay cannot reach a telemetry backend or a trace sink.
|
|
1063
1404
|
- `options.onResolved(step, outcome)`: observes each replayed step. A throw stops the replay, and `replayEffect` rejects with it; it never changes an outcome.
|
|
1064
|
-
|
|
1065
|
-
A trace whose entries have no `path`, written by hand or recorded before paths existed, is matched by position. That works for a sequential flow; a Command inside a `Parallel` is refused with a `ReplayError`, since the order branches finish in cannot tell them apart.
|
|
1405
|
+
- A trace whose entries have no `path`, written by hand or recorded before paths existed, is matched in order, and a Command inside a `Parallel` is refused with a `ReplayError`.
|
|
1066
1406
|
|
|
1067
1407
|
#### `timeTravel(flowFn, traceLog, options?)`
|
|
1068
1408
|
|
|
@@ -1070,12 +1410,15 @@ Replays a trace and narrates each step with its recorded duration, naming any re
|
|
|
1070
1410
|
|
|
1071
1411
|
## Limitations
|
|
1072
1412
|
|
|
1073
|
-
- **`Retry` repeats everything it wraps, including a Command's `next`.**
|
|
1413
|
+
- **`Retry` repeats everything it wraps, including a Command's `next`.** Each attempt runs every Command inside the `Retry` again, the ones that already succeeded included, and a retried Command whose `next` continues the flow takes the rest of the flow with it. Wrap only the Command that fails, and continue in a later step, as [Retrying Transient Failures](#retrying-transient-failures) shows. A function that catches its own error is never retried; see [Which Errors Are Data](#which-errors-are-data).
|
|
1074
1414
|
- **Cancelling a `Parallel` branch cannot stop everything.** A cancelled branch starts no new Commands, and a function that uses the `AbortSignal` it is given can be stopped while running. A function that ignores the signal runs to completion, so a branch whose _first_ Command is a write can still write after another branch has failed. So does a function that is never given the signal: one written as `(...args)` or `({ signal } = {})`, or wrapped by a helper that hides its parameters. `Parallel` waits for every branch to finish before returning, so no cancelled work is still running after the `Failure` is returned.
|
|
1075
|
-
- **Inside a `Parallel`, a Command's function that takes a parameter gets the `AbortSignal` in it.**
|
|
1415
|
+
- **Inside a `Parallel`, a Command's function that takes a parameter gets the `AbortSignal` in it.** This catches a function passed by name whose first parameter is optional and has no default value. Inside a `Parallel` that parameter gets the signal, and outside one it gets nothing, so the same Command behaves differently in the two places: `function listUsers(page) { page ??= 1; return db.users(page); }` gets the signal as its page. A parameter with a default value does not count, so `Command(nanoid)`, whose size is written `size = 21`, works everywhere. Wrap such a function, as in `Command(() => listUsers())`. In TypeScript, a function whose first parameter cannot be an `AbortSignal` does not compile as a Command.
|
|
1076
1416
|
- **`redact` covers a trace, not a result.** A `Failure` holds the full error, untrimmed, because tests and debugging need all of it, and an error can quote what a Command sent, as a database's duplicate-key error quotes the key. `redact` keeps sensitive data out of a **trace**. Keeping it out of your **logs** is up to you.
|
|
1077
|
-
- **Replay checks the path, not the values.**
|
|
1078
|
-
- **A trace keeps data, not objects.**
|
|
1079
|
-
- **Replay reproduces what one flow saw, not timing.** A stale read replays exactly. A race between two concurrent requests does not, because a trace records one flow. `Parallel` branches replay with the results each branch saw, and a cancelled `Parallel` with the branch that cancelled it, but not the order they ran in, so replay cannot settle a race between branches that share state.
|
|
1417
|
+
- **Replay checks the path, not the values.** Every Command's result comes from the recording, so replaying an old trace cannot check a fix that changes what a flow computes, and a step removed from the middle of a flow stops the replay at a `TimeParadox` instead of showing in `unreached`; see [Time-Travel Debugging](#time-travel-debugging).
|
|
1418
|
+
- **A trace keeps data, not objects.** A result replays as JSON stores it, so a class instance comes back without its methods and a `Date` as a string, and a thrown error comes back as a plain `Error` with its class's name, so a flow that checks `instanceof TypeError` replays differently; check `error.name` instead. Return plain data from Commands; see [Recording in Production](#recording-in-production).
|
|
1419
|
+
- **Replay reproduces what one flow saw, not timing.** A stale read replays exactly. A race between two concurrent requests does not, because a trace records one flow. `Parallel` branches replay with the results each branch saw, and a cancelled `Parallel` with the branch that cancelled it, but not the order they ran in, so replay cannot settle a race between branches that share state. A generator flow in a branch a recorded cancellation stopped can run its `catch` and `finally` at a different step in a replay, since a trace marks where a branch stopped only by its Commands: one cancelled during a `Retry`'s wait, just before an `Ask`, or at a `Retry` or `Parallel` with no Command in it, replays as though it stopped at its next Command.
|
|
1080
1420
|
- **Configuration belongs to one copy of the library.** `configureEffect` stores hooks in module state, so two copies of the library in one process (from a dual ESM and CJS setup, two versions in the dependency tree, or a worker thread) each have their own. Hooks configured in one do not apply to the other, and nothing warns you.
|
|
1081
1421
|
- **A Command needs a name.** `meta.name` survives minification. `cmd.name` does not, unless the minifier is set to keep function names.
|
|
1422
|
+
- **A generator flow's body can run more than once,** and code in it that changes something outside it, such as a counter or a log line, does so again; see [What runs once, and what runs again](#what-runs-once-and-what-runs-again).
|
|
1423
|
+
- **A generator run keeps every step's result until it ends,** since running the body again needs them. A long loop that fetches large pages holds every page; write it as a pipeline whose `next` asks for the next page.
|
|
1424
|
+
- **A generator body's `finally` does not always run.** It does not run when a bug or a `TimeParadox` rejects the run. In a `Parallel` where one branch threw, another branch that stops for its own reason before the rejection reaches it may still run its `catch` and `finally`, depending on timing. A step in a body's `finally` is not supported: it runs when the body ends normally and is refused when a step stopped the body, but if an error is passing through the body when its `finally` reaches a step, and the flow is cancelled before that step starts, the error is lost. Put cleanup in a `try`/`finally` around `runEffect`.
|