@codeinkit/flows-hoa 0.1.0-alpha.0 → 0.2.0-alpha.1
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/README.md +232 -5
- package/dist/compensation.d.ts +32 -0
- package/dist/compensation.js +112 -0
- package/dist/hoa.d.ts +12 -2
- package/dist/hoa.js +72 -52
- package/dist/idempotency.d.ts +99 -0
- package/dist/idempotency.js +299 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/internal.d.ts +34 -0
- package/dist/internal.js +109 -0
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
# @codeinkit/flows-hoa
|
|
2
2
|
|
|
3
|
-
Higher-Order Actions (HOAs) for [@codeinkit/flows](https://github.com/CodeInKit/flows) v4. An HOA takes an action and returns a new action with extra behaviour: `withRetry`, `withFallback`, `withTimeout` and `
|
|
3
|
+
Higher-Order Actions (HOAs) for [@codeinkit/flows](https://github.com/CodeInKit/flows) v4. An HOA takes an action and returns a new action with extra behaviour: `withRetry`, `withFallback`, `withTimeout` (with real cancellation), `withGuard`, `withIdempotency` and `withCompensation`. The package has no runtime dependencies. It imports types only from `@codeinkit/flows`.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
|
-
npm i @codeinkit/flows@
|
|
8
|
+
npm i @codeinkit/flows@next @codeinkit/flows-hoa@next
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
Core v4 is still in alpha
|
|
11
|
+
Core v4 is still in alpha and is published under the `next` tag. Since 0.2.0-alpha.0 the peer dependency range is `@codeinkit/flows` `^4.0.0-alpha.1` (the first core version with `ctx.signal` and `ctx.runId`). This package is alpha too.
|
|
12
12
|
|
|
13
13
|
## Usage
|
|
14
14
|
|
|
@@ -47,6 +47,8 @@ Runs `action` again when it throws.
|
|
|
47
47
|
|
|
48
48
|
`backoffDelay(attempt, options, rand)` is exported and computes the delay. The last error is rethrown unchanged. Invalid options throw when the HOA is created.
|
|
49
49
|
|
|
50
|
+
`withRetry` is abort-aware, see [Cancellation](#cancellation).
|
|
51
|
+
|
|
50
52
|
## withFallback(primary, fallback, { fallbackOn? })
|
|
51
53
|
|
|
52
54
|
If `primary` throws (and `fallbackOn(error)` is not `false`), `fallback` runs with the original input plus `fallbackFrom: { action, message, code }`. `code` is `error.code` or `'error'`. Errors from `fallback` propagate.
|
|
@@ -55,17 +57,242 @@ If `primary` throws (and `fallbackOn(error)` is not `false`), `fallback` runs wi
|
|
|
55
57
|
|
|
56
58
|
Throws `ActionTimeoutError` (`code: 'ETIMEOUT'`, `action`, `ms`) when `action` takes longer than `ms`. The timer is cleared when the action settles. `ms` must be greater than 0.
|
|
57
59
|
|
|
60
|
+
On timeout the inner action is cancelled through `ctx.signal`, see [Cancellation](#cancellation).
|
|
61
|
+
|
|
58
62
|
## withGuard(predicate, action, { otherwise? })
|
|
59
63
|
|
|
60
64
|
Runs `action` when `predicate(data)` is true. Otherwise it runs `otherwise`, or returns the input unchanged.
|
|
61
65
|
|
|
66
|
+
## Cancellation
|
|
67
|
+
|
|
68
|
+
Core `4.0.0-alpha.1` accepts a signal in `execute` and gives it to every action as `ctx.signal`. `withTimeout` and `withRetry` build on it.
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
const loadUser = async (data, unsafe, ctx) => {
|
|
72
|
+
const res = await fetch(`/api/users/${data.id}`, { signal: ctx?.signal as AbortSignal });
|
|
73
|
+
return { ...data, user: await res.json() };
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
flows.register('profile', [
|
|
77
|
+
withRetry(withTimeout(loadUser, { ms: 3000 }), { maxAttempts: 3, idempotent: true }),
|
|
78
|
+
]);
|
|
79
|
+
|
|
80
|
+
const controller = new AbortController();
|
|
81
|
+
const run = flows.execute('profile', { id: 7 }, {}, { signal: controller.signal });
|
|
82
|
+
controller.abort(); // e.g. the user left the page: the fetch stops and `run` rejects
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
**withTimeout**
|
|
86
|
+
|
|
87
|
+
- The inner action receives a copy of `ctx` whose `signal` is a **child signal**. Pass it to `fetch` (or anything else that takes a signal).
|
|
88
|
+
- On timeout the child is aborted with the `ActionTimeoutError` as its reason, then `withTimeout` rejects with that same error.
|
|
89
|
+
- When the parent `ctx.signal` aborts while the action runs, the child is aborted with the parent's reason and `withTimeout` rejects with it right away. When the parent is already aborted, the inner action is not called at all.
|
|
90
|
+
- The timer and the listener on the parent signal are always removed.
|
|
91
|
+
- An action that ignores the signal cannot be stopped. It keeps running and its late result or rejection is ignored.
|
|
92
|
+
- The attempt is reported as `timeout` for the wrapper's own timeout and as `error` for an abort.
|
|
93
|
+
|
|
94
|
+
**withRetry**
|
|
95
|
+
|
|
96
|
+
- No attempt is made when `ctx.signal` is already aborted. It throws the signal's reason.
|
|
97
|
+
- After a failed attempt it never retries an aborted run, whatever `retryOn` says. It rethrows the error of that attempt.
|
|
98
|
+
- The backoff sleep ends as soon as the signal aborts and rejects with the signal's reason.
|
|
99
|
+
- A timeout of an inner `withTimeout` only aborts that attempt's child signal, so `withRetry(withTimeout(x))` still retries it. Every attempt gets a fresh child signal.
|
|
100
|
+
|
|
101
|
+
> **Note:** `withRetry` and `withCompensation` only check the signal between attempts / steps (and `withRetry` aborts its backoff sleep). They do not interrupt an attempt or step that ignores the signal. To stop one mid-flight, wrap the step in `withTimeout` (which races the abort) or pass `ctx.signal` to `fetch`.
|
|
102
|
+
|
|
103
|
+
Signals are typed structurally (`{ aborted, reason? }`, exported as `AbortSignalLike` with optional `addEventListener` / `removeEventListener`), the DOM lib is not needed. A signal without `addEventListener` is only polled: before the call in `withTimeout`, before each attempt and after each sleep in `withRetry`. When a signal has no `reason`, an `Error` named `AbortError` is thrown. On a runtime without a global `AbortController` there is no child signal: `withTimeout` passes `ctx` on unchanged and behaves as it did in 0.1.
|
|
104
|
+
|
|
105
|
+
## withIdempotency(action, options?)
|
|
106
|
+
|
|
107
|
+
Dedupes repeat runs that carry the same Idempotency-Key, so a client can safely send a request again.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import { withIdempotency, withRetry, createMemoryIdempotencyStore } from '@codeinkit/flows-hoa';
|
|
111
|
+
|
|
112
|
+
const flows = new Flows({ ports: { payments, idempotency: createMemoryIdempotencyStore() } });
|
|
113
|
+
flows.register('checkout', [
|
|
114
|
+
withIdempotency(chargeCard, { required: true }),
|
|
115
|
+
]);
|
|
116
|
+
|
|
117
|
+
await flows.execute('checkout', { headers: { 'Idempotency-Key': 'req-1' }, body: { amount: 5 } });
|
|
118
|
+
await flows.execute('checkout', { headers: { 'Idempotency-Key': 'req-1' }, body: { amount: 5 } }); // stored result, chargeCard is not called
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
| Option | Default | Meaning |
|
|
122
|
+
| --- | --- | --- |
|
|
123
|
+
| `key(data)` | `data.idempotencyKey`, else the `idempotency-key` header in `data.headers` (any letter case) | Returns the key, or `undefined` when there is none. |
|
|
124
|
+
| `required` | `false` | When `true`, a run without a key throws `IdempotencyKeyRequiredError`. |
|
|
125
|
+
| `scope` | name of the innermost action | Namespace of the keys. The storage key is `` `${scope}:${key}` ``. |
|
|
126
|
+
| `ttlMs` | 24 hours | How long a record is kept. |
|
|
127
|
+
| `port` | `'idempotency'` | Name of the store on `unsafe`. |
|
|
128
|
+
| `fingerprint(data)` | `data.body ?? data.input ?? data.detail ?? null` | The part of the input that identifies the request. |
|
|
129
|
+
|
|
130
|
+
What happens:
|
|
131
|
+
|
|
132
|
+
- **No key**: the action runs normally (or `IdempotencyKeyRequiredError` when `required`).
|
|
133
|
+
- **First run with a key**: the key is claimed, the action runs, its result is stored (as a JSON clone) and returned.
|
|
134
|
+
- **Repeat, same key and same fingerprint**: a clone of the stored result is returned, the action is not called. Reported as `skipped`.
|
|
135
|
+
- **Same key, different fingerprint**: `IdempotencyConflictError`.
|
|
136
|
+
- **Repeat while the first run is still going**: `IdempotencyInProgressError`.
|
|
137
|
+
- **The action throws**: the key is deleted, so a retry runs the action again. The error is rethrown.
|
|
138
|
+
|
|
139
|
+
### Errors
|
|
140
|
+
|
|
141
|
+
All three errors extend `IdempotencyError` (which extends `Error`) and carry plain, readonly fields:
|
|
142
|
+
|
|
143
|
+
| Error | `status` | `code` | `description` |
|
|
144
|
+
| --- | --- | --- | --- |
|
|
145
|
+
| `IdempotencyKeyRequiredError` | 400 | `EIDEMPOTENCY_KEY_REQUIRED` | `An Idempotency-Key is required for this request.` |
|
|
146
|
+
| `IdempotencyConflictError` | 422 | `EIDEMPOTENCY_CONFLICT` | `This Idempotency-Key was already used with a different request.` |
|
|
147
|
+
| `IdempotencyInProgressError` | 409 | `EIDEMPOTENCY_IN_PROGRESS` | `A request with this Idempotency-Key is still in progress. Try again later.` |
|
|
148
|
+
|
|
149
|
+
| Field | |
|
|
150
|
+
| --- | --- |
|
|
151
|
+
| `status` | The HTTP status that fits the error. |
|
|
152
|
+
| `code` | Stable machine-readable code (type `IdempotencyErrorCode`). |
|
|
153
|
+
| `description` | Short text that is safe to send to a client. It never holds the idempotency key, the scope or a stored result. |
|
|
154
|
+
| `message` | For logs. It **does** hold the scope and the key, so do not send it to a client. |
|
|
155
|
+
| `scope` | The scope of the `withIdempotency` that threw. |
|
|
156
|
+
| `key` | The idempotency key (`IdempotencyConflictError` and `IdempotencyInProgressError` only). |
|
|
157
|
+
|
|
158
|
+
**In `@codeinkit/http-trigger`**: a thrown error with a `status` is answered with that status and the body `err.response ?? err.description ?? 'Internal server error'`. So a flow that lets these errors through answers 400 / 422 / 409 with the `description` as the body, with no mapping of your own. This package does not depend on http-trigger, the fields are plain properties any HTTP layer can read.
|
|
159
|
+
|
|
160
|
+
To tell them apart from other errors use `instanceof IdempotencyError` or the `isIdempotencyError(e)` type guard:
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import { isIdempotencyError } from '@codeinkit/flows-hoa';
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
await flows.execute('checkout', input);
|
|
167
|
+
} catch (e) {
|
|
168
|
+
if (isIdempotencyError(e)) return { status: e.status, body: { code: e.code, error: e.description } };
|
|
169
|
+
throw e;
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`isIdempotencyError` also accepts an `Error` that has one of the three codes with its matching `status` and a string `description`. That keeps it working when two copies of this package are installed, where `instanceof` fails.
|
|
174
|
+
|
|
175
|
+
The fingerprint is a JSON text with sorted object keys, hashed with FNV-1a (32 bit, not cryptographic). Key order in the body does not matter, array order does.
|
|
176
|
+
|
|
177
|
+
Notes:
|
|
178
|
+
|
|
179
|
+
- The result must survive a JSON round trip. That is what a repeat gets back.
|
|
180
|
+
- A stored result is replayed as it was returned, including `$$: { jump }` or `$$: { done }`.
|
|
181
|
+
- When the action succeeded but storing the result fails, the store's error is thrown and the key stays claimed until its TTL (repeats get `IdempotencyInProgressError`). Releasing it could run the action twice.
|
|
182
|
+
- The default `scope` is the action's name. Give an explicit `scope` when two different steps wrap the same action, or when the function is anonymous.
|
|
183
|
+
- The default `scope` comes from the function's name, which a minifier can rename or make collide in browser bundles. Pass an explicit `scope` (for example the flow id) in client code and anywhere names may be mangled.
|
|
184
|
+
- `key` and `fingerprint` receive the action's input itself. Do not change it there.
|
|
185
|
+
|
|
186
|
+
### With withRetry
|
|
187
|
+
|
|
188
|
+
Put `withIdempotency` **inside** `withRetry` and state `idempotent: 'via-key'`. A failed attempt releases the key, so the next attempt runs. Once an attempt succeeds, every later run with that key gets the stored result.
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
withRetry(withIdempotency(chargeCard, { required: true }), { maxAttempts: 3, idempotent: 'via-key' });
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Store port
|
|
195
|
+
|
|
196
|
+
The store is read from `unsafe[port]`. Every method may return a value or a Promise.
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
interface IdempotencyStore {
|
|
200
|
+
claim(key: string, record: IdempotencyRecord, ttlMs: number): boolean; // atomic set-if-absent, true when this call created the record
|
|
201
|
+
get(key: string): IdempotencyRecord | undefined;
|
|
202
|
+
set(key: string, record: IdempotencyRecord, ttlMs: number): void;
|
|
203
|
+
delete(key: string): void;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
interface IdempotencyRecord {
|
|
207
|
+
state: 'in_progress' | 'done';
|
|
208
|
+
fingerprint: string;
|
|
209
|
+
result?: unknown; // set when state is 'done'
|
|
210
|
+
createdAt: number;
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
`claim` has to be atomic. Two calls with the same key at the same moment must not both get `true`. When the port is missing, the HOA throws an `Error` that names it (only for runs that have a key).
|
|
215
|
+
|
|
216
|
+
### Memory store
|
|
217
|
+
|
|
218
|
+
`createMemoryIdempotencyStore({ now? })` keeps the records in a `Map` with TTL expiry. Use it in tests, in the browser and on a single-process server. `now` (default `Date.now`) can be injected for tests.
|
|
219
|
+
|
|
220
|
+
It is **not shared between processes**. A server with more than one instance needs a shared store, where the database does the atomic claim. A sketch for MongoDB, with a unique `_id` and a TTL index:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
// once: await col.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });
|
|
224
|
+
const mongoIdempotencyStore = (col: Collection<any>): IdempotencyStore => ({
|
|
225
|
+
async claim(key, record, ttlMs) {
|
|
226
|
+
try {
|
|
227
|
+
await col.insertOne({ _id: key, ...record, expiresAt: new Date(Date.now() + ttlMs) });
|
|
228
|
+
return true;
|
|
229
|
+
} catch (e: any) {
|
|
230
|
+
if (e.code === 11000) return false; // duplicate key: someone else has it
|
|
231
|
+
throw e;
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
async get(key) {
|
|
235
|
+
// the TTL monitor runs about once a minute, so check expiresAt as well
|
|
236
|
+
const doc = await col.findOne({ _id: key, expiresAt: { $gt: new Date() } });
|
|
237
|
+
return doc ? { state: doc.state, fingerprint: doc.fingerprint, result: doc.result, createdAt: doc.createdAt } : undefined;
|
|
238
|
+
},
|
|
239
|
+
async set(key, record, ttlMs) {
|
|
240
|
+
await col.replaceOne({ _id: key }, { ...record, expiresAt: new Date(Date.now() + ttlMs) }, { upsert: true });
|
|
241
|
+
},
|
|
242
|
+
async delete(key) {
|
|
243
|
+
await col.deleteOne({ _id: key });
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
In this sketch a record that passed its `expiresAt` but was not yet removed by the TTL monitor still blocks `claim` for up to a minute, and the caller gets `IdempotencyInProgressError`.
|
|
249
|
+
|
|
250
|
+
## withCompensation(steps)
|
|
251
|
+
|
|
252
|
+
A saga-style sequence. An HOA cannot see the later steps of a flow, so `withCompensation` wraps the steps that belong together and gives each one an optional `undo`.
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
import { withCompensation } from '@codeinkit/flows-hoa';
|
|
256
|
+
|
|
257
|
+
const reserveStock = async (data, unsafe) => ({ ...data, reservationId: await unsafe.stock.reserve(data.items) });
|
|
258
|
+
const releaseStock = async (data, unsafe) => { await unsafe.stock.release(data.reservationId); return {}; };
|
|
259
|
+
const chargeCard = async (data, unsafe) => ({ ...data, chargeId: await unsafe.payments.charge(data.amount) });
|
|
260
|
+
const refundCard = async (data, unsafe) => { await unsafe.payments.refund(data.chargeId); return {}; };
|
|
261
|
+
const confirmOrder = async (data, unsafe) => ({ ...data, confirmed: await unsafe.orders.confirm(data.orderId) });
|
|
262
|
+
|
|
263
|
+
flows.register('placeOrder', [
|
|
264
|
+
withCompensation([
|
|
265
|
+
{ action: reserveStock, undo: releaseStock },
|
|
266
|
+
{ action: chargeCard, undo: refundCard },
|
|
267
|
+
{ action: confirmOrder },
|
|
268
|
+
]),
|
|
269
|
+
]);
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
When `confirmOrder` throws, `refundCard` runs, then `releaseStock`, and the flow rejects with the error of `confirmOrder`.
|
|
273
|
+
|
|
274
|
+
- The steps run in order. The first one gets a clone of the input, each next one gets the previous step's output. `unsafe` and `ctx` are passed through. The last step's output is returned.
|
|
275
|
+
- A step must return an object, like any action in a flow.
|
|
276
|
+
- When step k throws, the `undo` of every **completed** step runs in reverse order (k-1 down to 0). The failed step itself is not undone. Steps without an `undo` are skipped.
|
|
277
|
+
- Each undo receives `{ ...outputOfItsStep, compensation: { failedAction, message, code } }`, the same `unsafe`, and a `ctx` **without a signal**: an undo is never cancelled. Its return value is ignored.
|
|
278
|
+
- An undo that throws does not stop the other undos.
|
|
279
|
+
- The **original error** is rethrown, not wrapped. When it is an object it gets `compensation: { undone: string[], failed: Array<{ action, message }> }` with the names of the undo actions.
|
|
280
|
+
- When `ctx.signal` is aborted before a step, that counts as a failure of that step with the abort error, and the completed steps are undone.
|
|
281
|
+
- `$$.jump` is not supported inside: a step that returns it fails the sequence with a clear error (and the earlier steps are undone). `$$.done` is allowed on the last step only.
|
|
282
|
+
- Every step and every undo is reported through `ctx.reportAttempt` with `wrapper: 'withCompensation'` and outcome `success` or `error`.
|
|
283
|
+
- `steps` needs at least one step. Every `action` and `undo` must be a function, this is checked when the HOA is created.
|
|
284
|
+
- Metadata: `inner` lists each step action followed by its undo, `roles` holds the matching `'step'` / `'undo'` entries.
|
|
285
|
+
|
|
286
|
+
Steps can be HOAs themselves, for example `{ action: withRetry(withIdempotency(chargeCard), { maxAttempts: 3, idempotent: 'via-key' }), undo: refundCard }`.
|
|
287
|
+
|
|
62
288
|
## Invariants
|
|
63
289
|
|
|
64
290
|
- Retry and fallback trigger only on **thrown** errors. A returned result, including `$$: { done }` or `$$: { jump }`, passes through untouched.
|
|
65
291
|
- Each attempt, fallback and predicate call gets a **fresh clone** of the original input, so a failed attempt cannot leak mutations.
|
|
66
292
|
- The `unsafe` argument is passed on as the **same reference**.
|
|
67
293
|
- Do not keep state in factory closures. An HOA instance is shared by every execution of the flow.
|
|
68
|
-
- `withTimeout` does
|
|
294
|
+
- `withTimeout` cancels through the child `ctx.signal`. An inner action that does not use the signal keeps running and its late result or error is ignored.
|
|
295
|
+
- `withIdempotency` passes the input on as it is (no clone). `withCompensation` clones the input once, for the first step.
|
|
69
296
|
- Order matters. `withRetry(withTimeout(x))` is a timeout per attempt. `withTimeout(withRetry(x))` is one timeout for all attempts.
|
|
70
297
|
- If `unsafe.clock.now`, `unsafe.clock.sleep` or `unsafe.random` exist, they are used (handy for tests). Otherwise real timers and `Math.random` are used.
|
|
71
298
|
|
|
@@ -79,7 +306,7 @@ flows.hook(SupportedHooks.ACTION_ATTEMPT, (e) => console.log(e.wrapper, e.attemp
|
|
|
79
306
|
|
|
80
307
|
```ts
|
|
81
308
|
interface AttemptEvent {
|
|
82
|
-
wrapper: string; // 'withRetry' | 'withFallback' | 'withTimeout' | 'withGuard' | your own
|
|
309
|
+
wrapper: string; // 'withRetry' | 'withFallback' | 'withTimeout' | 'withGuard' | 'withIdempotency' | 'withCompensation' | your own
|
|
83
310
|
inner: Action; // the action that was attempted
|
|
84
311
|
attempt: number; // 1-based
|
|
85
312
|
outcome: 'success' | 'error' | 'timeout' | 'fallback' | 'skipped';
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Action } from '@codeinkit/flows';
|
|
2
|
+
export interface CompensationStep {
|
|
3
|
+
action: Action;
|
|
4
|
+
/** reverts `action`. Runs only when a later step fails */
|
|
5
|
+
undo?: Action;
|
|
6
|
+
}
|
|
7
|
+
/** Added as `compensation` to the input of every undo. */
|
|
8
|
+
export interface CompensationInfo {
|
|
9
|
+
failedAction: string;
|
|
10
|
+
message: string;
|
|
11
|
+
code: string;
|
|
12
|
+
}
|
|
13
|
+
/** Attached as `compensation` to the rethrown error (when it is an object). */
|
|
14
|
+
export interface CompensationResult {
|
|
15
|
+
/** names of the undo actions that ran, in the order they ran */
|
|
16
|
+
undone: string[];
|
|
17
|
+
/** undo actions that threw */
|
|
18
|
+
failed: Array<{
|
|
19
|
+
action: string;
|
|
20
|
+
message: string;
|
|
21
|
+
}>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Saga-style sequence. Runs the steps in order, each one gets the previous step's output.
|
|
25
|
+
* When step k throws (or `ctx.signal` is aborted before it), the `undo` of every completed step
|
|
26
|
+
* runs in reverse order with `{ ...outputOfThatStep, compensation: { failedAction, message, code } }`
|
|
27
|
+
* and a `ctx` without a signal (an undo is never cancelled). An undo that throws does not stop
|
|
28
|
+
* the others. Then the original error is rethrown with `compensation: { undone, failed }` attached.
|
|
29
|
+
*
|
|
30
|
+
* A step must return an object and cannot return `$$.jump` (nor `$$.done`, except the last step).
|
|
31
|
+
*/
|
|
32
|
+
export declare function withCompensation<D = any, R = any>(steps: ReadonlyArray<CompensationStep>): Action<D, R>;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.withCompensation = void 0;
|
|
4
|
+
const hoa_1 = require("./hoa");
|
|
5
|
+
const internal_1 = require("./internal");
|
|
6
|
+
/**
|
|
7
|
+
* Saga-style sequence. Runs the steps in order, each one gets the previous step's output.
|
|
8
|
+
* When step k throws (or `ctx.signal` is aborted before it), the `undo` of every completed step
|
|
9
|
+
* runs in reverse order with `{ ...outputOfThatStep, compensation: { failedAction, message, code } }`
|
|
10
|
+
* and a `ctx` without a signal (an undo is never cancelled). An undo that throws does not stop
|
|
11
|
+
* the others. Then the original error is rethrown with `compensation: { undone, failed }` attached.
|
|
12
|
+
*
|
|
13
|
+
* A step must return an object and cannot return `$$.jump` (nor `$$.done`, except the last step).
|
|
14
|
+
*/
|
|
15
|
+
function withCompensation(steps) {
|
|
16
|
+
if (!Array.isArray(steps) || steps.length < 1) {
|
|
17
|
+
throw new Error('withCompensation: steps must be an array with at least one step');
|
|
18
|
+
}
|
|
19
|
+
const list = steps.map((step, k) => {
|
|
20
|
+
if (!step || typeof step.action !== 'function') {
|
|
21
|
+
throw new Error(`withCompensation: step ${k} needs an action function`);
|
|
22
|
+
}
|
|
23
|
+
if (step.undo !== undefined && typeof step.undo !== 'function') {
|
|
24
|
+
throw new Error(`withCompensation: the undo of step ${k} must be a function`);
|
|
25
|
+
}
|
|
26
|
+
return { action: step.action, undo: step.undo };
|
|
27
|
+
});
|
|
28
|
+
const hoa = async (data, unsafe, ctx) => {
|
|
29
|
+
var _a;
|
|
30
|
+
const clone = (0, internal_1.cloner)(ctx);
|
|
31
|
+
const signal = ctx && ctx.signal;
|
|
32
|
+
const completed = [];
|
|
33
|
+
let current = clone(data);
|
|
34
|
+
for (let k = 0; k < list.length; k++) {
|
|
35
|
+
const step = list[k];
|
|
36
|
+
let failure;
|
|
37
|
+
if (signal && signal.aborted) {
|
|
38
|
+
failure = { error: (0, internal_1.abortReason)(signal) };
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
const start = (0, internal_1.now)(unsafe);
|
|
42
|
+
try {
|
|
43
|
+
const output = await step.action(current, unsafe, ctx);
|
|
44
|
+
if (output === null || typeof output !== 'object') {
|
|
45
|
+
throw new Error(`withCompensation: step ${k} (${(0, internal_1.nameOf)(step.action)}) returned "${output}" instead of an object`);
|
|
46
|
+
}
|
|
47
|
+
if (output.$$ && output.$$.jump) {
|
|
48
|
+
throw new Error(`withCompensation: step ${k} (${(0, internal_1.nameOf)(step.action)}) returned $$.jump, which is not supported inside withCompensation`);
|
|
49
|
+
}
|
|
50
|
+
if (output.$$ && output.$$.done && k < list.length - 1) {
|
|
51
|
+
throw new Error(`withCompensation: step ${k} (${(0, internal_1.nameOf)(step.action)}) returned $$.done, only the last step may do that`);
|
|
52
|
+
}
|
|
53
|
+
(0, internal_1.report)(ctx, { wrapper: 'withCompensation', inner: step.action, attempt: 1, outcome: 'success', durationMs: (0, internal_1.now)(unsafe) - start });
|
|
54
|
+
// keep a copy for the undo: later steps receive `output` itself and may change it
|
|
55
|
+
completed.push({ step, output: clone(output) });
|
|
56
|
+
current = output;
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
(0, internal_1.report)(ctx, { wrapper: 'withCompensation', inner: step.action, attempt: 1, outcome: 'error', error, durationMs: (0, internal_1.now)(unsafe) - start });
|
|
60
|
+
failure = { error };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (failure) {
|
|
64
|
+
const error = failure.error;
|
|
65
|
+
const info = {
|
|
66
|
+
failedAction: (0, internal_1.nameOf)(step.action),
|
|
67
|
+
message: (0, internal_1.messageOf)(error),
|
|
68
|
+
code: (_a = (error && error.code)) !== null && _a !== void 0 ? _a : 'error',
|
|
69
|
+
};
|
|
70
|
+
const undoCtx = ctx ? { ...ctx, signal: undefined } : undefined;
|
|
71
|
+
const result = { undone: [], failed: [] };
|
|
72
|
+
for (let j = completed.length - 1; j >= 0; j--) {
|
|
73
|
+
const undo = completed[j].step.undo;
|
|
74
|
+
if (!undo)
|
|
75
|
+
continue;
|
|
76
|
+
const start = (0, internal_1.now)(unsafe);
|
|
77
|
+
try {
|
|
78
|
+
await undo({ ...completed[j].output, compensation: info }, unsafe, undoCtx);
|
|
79
|
+
(0, internal_1.report)(ctx, { wrapper: 'withCompensation', inner: undo, attempt: 1, outcome: 'success', durationMs: (0, internal_1.now)(unsafe) - start });
|
|
80
|
+
result.undone.push((0, internal_1.nameOf)(undo));
|
|
81
|
+
}
|
|
82
|
+
catch (undoError) {
|
|
83
|
+
(0, internal_1.report)(ctx, { wrapper: 'withCompensation', inner: undo, attempt: 1, outcome: 'error', error: undoError, durationMs: (0, internal_1.now)(unsafe) - start });
|
|
84
|
+
result.failed.push({ action: (0, internal_1.nameOf)(undo), message: (0, internal_1.messageOf)(undoError) });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (error !== null && typeof error === 'object') {
|
|
88
|
+
try {
|
|
89
|
+
error.compensation = result;
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
// a frozen error keeps going without the summary
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return current;
|
|
99
|
+
};
|
|
100
|
+
const inner = [];
|
|
101
|
+
const roles = [];
|
|
102
|
+
for (const step of list) {
|
|
103
|
+
inner.push(step.action);
|
|
104
|
+
roles.push('step');
|
|
105
|
+
if (step.undo) {
|
|
106
|
+
inner.push(step.undo);
|
|
107
|
+
roles.push('undo');
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return (0, hoa_1.defineHoa)(hoa, { wrapper: 'withCompensation', inner, roles });
|
|
111
|
+
}
|
|
112
|
+
exports.withCompensation = withCompensation;
|
package/dist/hoa.d.ts
CHANGED
|
@@ -30,6 +30,10 @@ export interface RetryOptions {
|
|
|
30
30
|
* With jitter (default) this is full jitter: rand() * min(maxBackoffMs, backoffMs * factor^(attempt-1)).
|
|
31
31
|
*/
|
|
32
32
|
export declare function backoffDelay(attempt: number, opts: Pick<RetryOptions, 'backoffMs' | 'factor' | 'maxBackoffMs' | 'jitter'>, rand: () => number): number;
|
|
33
|
+
/**
|
|
34
|
+
* Abort-aware: when `ctx.signal` is aborted no (further) attempt is made, and an abort during
|
|
35
|
+
* the backoff sleep ends the sleep and rejects with the abort reason.
|
|
36
|
+
*/
|
|
33
37
|
export declare function withRetry<D = any, R = any>(action: Action<D, R>, opts: RetryOptions): Action<D, R>;
|
|
34
38
|
export declare function withFallback<D = any, R1 = any, R2 = any>(primary: Action<D, R1>, fallback: Action<D & {
|
|
35
39
|
fallbackFrom: FallbackInfo;
|
|
@@ -43,8 +47,14 @@ export declare class ActionTimeoutError extends Error {
|
|
|
43
47
|
constructor(action: string, ms: number);
|
|
44
48
|
}
|
|
45
49
|
/**
|
|
46
|
-
*
|
|
47
|
-
*
|
|
50
|
+
* Rejects with `ActionTimeoutError` when the action takes longer than `ms`.
|
|
51
|
+
*
|
|
52
|
+
* Cancellation: the inner action gets a copy of `ctx` whose `signal` is a child signal. The child
|
|
53
|
+
* is aborted on timeout (reason: the `ActionTimeoutError`) and when the parent `ctx.signal` aborts
|
|
54
|
+
* (reason: the parent's reason), so an action that passes `ctx.signal` to `fetch` really stops.
|
|
55
|
+
* An action that ignores the signal keeps running in the background and its late result or
|
|
56
|
+
* rejection is ignored. Without a `ctx`, or on a runtime without `AbortController`, there is no
|
|
57
|
+
* child signal and `ctx` is passed on unchanged.
|
|
48
58
|
*/
|
|
49
59
|
export declare function withTimeout<D = any, R = any>(action: Action<D, R>, opts: {
|
|
50
60
|
ms: number;
|
package/dist/hoa.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.withGuard = exports.withTimeout = exports.ActionTimeoutError = exports.withFallback = exports.withRetry = exports.backoffDelay = exports.defineHoa = exports.innermostAction = exports.getHoaMeta = exports.HOA = void 0;
|
|
4
|
+
const internal_1 = require("./internal");
|
|
4
5
|
exports.HOA = Symbol.for('codeinkit.flows.hoa');
|
|
5
6
|
function getHoaMeta(fn) {
|
|
6
7
|
if (typeof fn !== 'function')
|
|
@@ -25,25 +26,6 @@ function defineHoa(fn, meta) {
|
|
|
25
26
|
return fn;
|
|
26
27
|
}
|
|
27
28
|
exports.defineHoa = defineHoa;
|
|
28
|
-
/* ---------- helpers (duck-typed clock / random on the unsafe object) ---------- */
|
|
29
|
-
const jsonClone = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v)));
|
|
30
|
-
const cloner = (ctx) => ctx && typeof ctx.clone === 'function' ? ctx.clone : jsonClone;
|
|
31
|
-
function now(unsafe) {
|
|
32
|
-
return unsafe && unsafe.clock && typeof unsafe.clock.now === 'function' ? unsafe.clock.now() : Date.now();
|
|
33
|
-
}
|
|
34
|
-
function random(unsafe) {
|
|
35
|
-
return unsafe && typeof unsafe.random === 'function' ? unsafe.random() : Math.random();
|
|
36
|
-
}
|
|
37
|
-
function sleep(unsafe, ms) {
|
|
38
|
-
if (unsafe && unsafe.clock && typeof unsafe.clock.sleep === 'function') {
|
|
39
|
-
return Promise.resolve(unsafe.clock.sleep(ms));
|
|
40
|
-
}
|
|
41
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
42
|
-
}
|
|
43
|
-
function report(ctx, ev) {
|
|
44
|
-
if (ctx && typeof ctx.reportAttempt === 'function')
|
|
45
|
-
ctx.reportAttempt(ev);
|
|
46
|
-
}
|
|
47
29
|
/**
|
|
48
30
|
* Delay in ms to wait after failed attempt number `attempt` (1-based).
|
|
49
31
|
* With jitter (default) this is full jitter: rand() * min(maxBackoffMs, backoffMs * factor^(attempt-1)).
|
|
@@ -56,6 +38,10 @@ function backoffDelay(attempt, opts, rand) {
|
|
|
56
38
|
return opts.jitter === false ? capped : rand() * capped;
|
|
57
39
|
}
|
|
58
40
|
exports.backoffDelay = backoffDelay;
|
|
41
|
+
/**
|
|
42
|
+
* Abort-aware: when `ctx.signal` is aborted no (further) attempt is made, and an abort during
|
|
43
|
+
* the backoff sleep ends the sleep and rejects with the abort reason.
|
|
44
|
+
*/
|
|
59
45
|
function withRetry(action, opts) {
|
|
60
46
|
if (!opts || typeof opts.maxAttempts !== 'number' || !Number.isInteger(opts.maxAttempts) || opts.maxAttempts < 1 || opts.maxAttempts > 10) {
|
|
61
47
|
throw new Error('withRetry: maxAttempts must be an integer between 1 and 10');
|
|
@@ -64,21 +50,25 @@ function withRetry(action, opts) {
|
|
|
64
50
|
throw new Error("withRetry: `idempotent` is required (true | 'via-key'); retrying a non-idempotent action can repeat side effects");
|
|
65
51
|
}
|
|
66
52
|
const hoa = async (data, unsafe, ctx) => {
|
|
67
|
-
const clone = cloner(ctx);
|
|
53
|
+
const clone = (0, internal_1.cloner)(ctx);
|
|
68
54
|
const snapshot = clone(data);
|
|
55
|
+
const signal = ctx && ctx.signal;
|
|
69
56
|
for (let attempt = 1;; attempt++) {
|
|
70
|
-
|
|
57
|
+
if (signal && signal.aborted)
|
|
58
|
+
throw (0, internal_1.abortReason)(signal);
|
|
59
|
+
const start = (0, internal_1.now)(unsafe);
|
|
71
60
|
try {
|
|
72
61
|
const result = await action(clone(snapshot), unsafe, ctx);
|
|
73
|
-
report(ctx, { wrapper: 'withRetry', inner: action, attempt, outcome: 'success', durationMs: now(unsafe) - start });
|
|
62
|
+
(0, internal_1.report)(ctx, { wrapper: 'withRetry', inner: action, attempt, outcome: 'success', durationMs: (0, internal_1.now)(unsafe) - start });
|
|
74
63
|
return result;
|
|
75
64
|
}
|
|
76
65
|
catch (error) {
|
|
77
|
-
report(ctx, { wrapper: 'withRetry', inner: action, attempt, outcome: 'error', error, durationMs: now(unsafe) - start });
|
|
78
|
-
|
|
66
|
+
(0, internal_1.report)(ctx, { wrapper: 'withRetry', inner: action, attempt, outcome: 'error', error, durationMs: (0, internal_1.now)(unsafe) - start });
|
|
67
|
+
// an aborted run is never retried, whatever retryOn says
|
|
68
|
+
if ((signal && signal.aborted) || attempt >= opts.maxAttempts || (opts.retryOn && !opts.retryOn(error, attempt))) {
|
|
79
69
|
throw error;
|
|
80
70
|
}
|
|
81
|
-
await sleep(unsafe, backoffDelay(attempt, opts, () => random(unsafe)));
|
|
71
|
+
await (0, internal_1.sleep)(unsafe, backoffDelay(attempt, opts, () => (0, internal_1.random)(unsafe)), signal);
|
|
82
72
|
}
|
|
83
73
|
}
|
|
84
74
|
};
|
|
@@ -88,37 +78,37 @@ exports.withRetry = withRetry;
|
|
|
88
78
|
/* ---------- withFallback ---------- */
|
|
89
79
|
function withFallback(primary, fallback, opts = {}) {
|
|
90
80
|
const hoa = async (data, unsafe, ctx) => {
|
|
91
|
-
var _a
|
|
92
|
-
const clone = cloner(ctx);
|
|
81
|
+
var _a;
|
|
82
|
+
const clone = (0, internal_1.cloner)(ctx);
|
|
93
83
|
const snapshot = clone(data);
|
|
94
|
-
const start = now(unsafe);
|
|
84
|
+
const start = (0, internal_1.now)(unsafe);
|
|
95
85
|
try {
|
|
96
86
|
const result = await primary(clone(snapshot), unsafe, ctx);
|
|
97
|
-
report(ctx, { wrapper: 'withFallback', inner: primary, attempt: 1, outcome: 'success', durationMs: now(unsafe) - start });
|
|
87
|
+
(0, internal_1.report)(ctx, { wrapper: 'withFallback', inner: primary, attempt: 1, outcome: 'success', durationMs: (0, internal_1.now)(unsafe) - start });
|
|
98
88
|
return result;
|
|
99
89
|
}
|
|
100
90
|
catch (error) {
|
|
101
91
|
if (opts.fallbackOn && !opts.fallbackOn(error)) {
|
|
102
|
-
report(ctx, { wrapper: 'withFallback', inner: primary, attempt: 1, outcome: 'error', error, durationMs: now(unsafe) - start });
|
|
92
|
+
(0, internal_1.report)(ctx, { wrapper: 'withFallback', inner: primary, attempt: 1, outcome: 'error', error, durationMs: (0, internal_1.now)(unsafe) - start });
|
|
103
93
|
throw error;
|
|
104
94
|
}
|
|
105
|
-
report(ctx, { wrapper: 'withFallback', inner: primary, attempt: 1, outcome: 'fallback', error, durationMs: now(unsafe) - start });
|
|
106
|
-
const fbStart = now(unsafe);
|
|
95
|
+
(0, internal_1.report)(ctx, { wrapper: 'withFallback', inner: primary, attempt: 1, outcome: 'fallback', error, durationMs: (0, internal_1.now)(unsafe) - start });
|
|
96
|
+
const fbStart = (0, internal_1.now)(unsafe);
|
|
107
97
|
const input = {
|
|
108
98
|
...clone(snapshot),
|
|
109
99
|
fallbackFrom: {
|
|
110
100
|
action: primary.name,
|
|
111
|
-
message:
|
|
112
|
-
code: (
|
|
101
|
+
message: (0, internal_1.messageOf)(error),
|
|
102
|
+
code: (_a = (error && error.code)) !== null && _a !== void 0 ? _a : 'error',
|
|
113
103
|
},
|
|
114
104
|
};
|
|
115
105
|
try {
|
|
116
106
|
const result = await fallback(input, unsafe, ctx);
|
|
117
|
-
report(ctx, { wrapper: 'withFallback', inner: fallback, attempt: 1, outcome: 'success', durationMs: now(unsafe) - fbStart });
|
|
107
|
+
(0, internal_1.report)(ctx, { wrapper: 'withFallback', inner: fallback, attempt: 1, outcome: 'success', durationMs: (0, internal_1.now)(unsafe) - fbStart });
|
|
118
108
|
return result;
|
|
119
109
|
}
|
|
120
110
|
catch (fbError) {
|
|
121
|
-
report(ctx, { wrapper: 'withFallback', inner: fallback, attempt: 1, outcome: 'error', error: fbError, durationMs: now(unsafe) - fbStart });
|
|
111
|
+
(0, internal_1.report)(ctx, { wrapper: 'withFallback', inner: fallback, attempt: 1, outcome: 'error', error: fbError, durationMs: (0, internal_1.now)(unsafe) - fbStart });
|
|
122
112
|
throw fbError;
|
|
123
113
|
}
|
|
124
114
|
}
|
|
@@ -139,42 +129,72 @@ class ActionTimeoutError extends Error {
|
|
|
139
129
|
}
|
|
140
130
|
exports.ActionTimeoutError = ActionTimeoutError;
|
|
141
131
|
/**
|
|
142
|
-
*
|
|
143
|
-
*
|
|
132
|
+
* Rejects with `ActionTimeoutError` when the action takes longer than `ms`.
|
|
133
|
+
*
|
|
134
|
+
* Cancellation: the inner action gets a copy of `ctx` whose `signal` is a child signal. The child
|
|
135
|
+
* is aborted on timeout (reason: the `ActionTimeoutError`) and when the parent `ctx.signal` aborts
|
|
136
|
+
* (reason: the parent's reason), so an action that passes `ctx.signal` to `fetch` really stops.
|
|
137
|
+
* An action that ignores the signal keeps running in the background and its late result or
|
|
138
|
+
* rejection is ignored. Without a `ctx`, or on a runtime without `AbortController`, there is no
|
|
139
|
+
* child signal and `ctx` is passed on unchanged.
|
|
144
140
|
*/
|
|
145
141
|
function withTimeout(action, opts) {
|
|
146
142
|
if (!opts || typeof opts.ms !== 'number' || !(opts.ms > 0)) {
|
|
147
143
|
throw new Error('withTimeout: ms must be a number greater than 0');
|
|
148
144
|
}
|
|
149
145
|
const hoa = async (data, unsafe, ctx) => {
|
|
150
|
-
const clone = cloner(ctx);
|
|
146
|
+
const clone = (0, internal_1.cloner)(ctx);
|
|
151
147
|
const snapshot = clone(data);
|
|
152
|
-
const start = now(unsafe);
|
|
148
|
+
const start = (0, internal_1.now)(unsafe);
|
|
149
|
+
const parent = ctx && ctx.signal;
|
|
150
|
+
if (parent && parent.aborted) {
|
|
151
|
+
const error = (0, internal_1.abortReason)(parent);
|
|
152
|
+
(0, internal_1.report)(ctx, { wrapper: 'withTimeout', inner: action, attempt: 1, outcome: 'error', error, durationMs: (0, internal_1.now)(unsafe) - start });
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
const child = ctx ? (0, internal_1.createAbortController)() : undefined;
|
|
156
|
+
const innerCtx = ctx && child ? { ...ctx, signal: child.signal } : ctx;
|
|
153
157
|
let timer;
|
|
154
|
-
|
|
155
|
-
|
|
158
|
+
let unlisten;
|
|
159
|
+
let timeoutError;
|
|
160
|
+
const interrupted = new Promise((_, reject) => {
|
|
161
|
+
timer = setTimeout(() => {
|
|
162
|
+
timeoutError = new ActionTimeoutError(action.name, opts.ms);
|
|
163
|
+
if (child)
|
|
164
|
+
child.abort(timeoutError);
|
|
165
|
+
reject(timeoutError);
|
|
166
|
+
}, opts.ms);
|
|
167
|
+
unlisten = (0, internal_1.onAbort)(parent, () => {
|
|
168
|
+
const reason = (0, internal_1.abortReason)(parent);
|
|
169
|
+
if (child)
|
|
170
|
+
child.abort(reason);
|
|
171
|
+
reject(reason);
|
|
172
|
+
});
|
|
156
173
|
});
|
|
157
174
|
let running;
|
|
158
175
|
try {
|
|
159
|
-
running = Promise.resolve(action(snapshot, unsafe,
|
|
176
|
+
running = Promise.resolve(action(snapshot, unsafe, innerCtx));
|
|
160
177
|
}
|
|
161
178
|
catch (e) {
|
|
162
179
|
running = Promise.reject(e);
|
|
163
180
|
}
|
|
164
|
-
running.catch(() => undefined); // avoid unhandled rejection after a timeout
|
|
181
|
+
running.catch(() => undefined); // avoid unhandled rejection after a timeout or an abort
|
|
165
182
|
try {
|
|
166
|
-
const result = await Promise.race([running,
|
|
167
|
-
report(ctx, { wrapper: 'withTimeout', inner: action, attempt: 1, outcome: 'success', durationMs: now(unsafe) - start });
|
|
183
|
+
const result = await Promise.race([running, interrupted]);
|
|
184
|
+
(0, internal_1.report)(ctx, { wrapper: 'withTimeout', inner: action, attempt: 1, outcome: 'success', durationMs: (0, internal_1.now)(unsafe) - start });
|
|
168
185
|
return result;
|
|
169
186
|
}
|
|
170
187
|
catch (error) {
|
|
171
|
-
|
|
172
|
-
|
|
188
|
+
// only this wrapper's own timeout is a 'timeout'; an outer one arrives here as an abort reason
|
|
189
|
+
const outcome = timeoutError !== undefined && error === timeoutError ? 'timeout' : 'error';
|
|
190
|
+
(0, internal_1.report)(ctx, { wrapper: 'withTimeout', inner: action, attempt: 1, outcome, error, durationMs: (0, internal_1.now)(unsafe) - start });
|
|
173
191
|
throw error;
|
|
174
192
|
}
|
|
175
193
|
finally {
|
|
176
194
|
if (timer !== undefined)
|
|
177
195
|
clearTimeout(timer);
|
|
196
|
+
if (unlisten)
|
|
197
|
+
unlisten();
|
|
178
198
|
}
|
|
179
199
|
};
|
|
180
200
|
return defineHoa(hoa, { wrapper: 'withTimeout', inner: [action], options: opts });
|
|
@@ -184,15 +204,15 @@ exports.withTimeout = withTimeout;
|
|
|
184
204
|
function withGuard(predicate, action, opts = {}) {
|
|
185
205
|
const inner = opts.otherwise ? [action, opts.otherwise] : [action];
|
|
186
206
|
const hoa = async (data, unsafe, ctx) => {
|
|
187
|
-
const clone = cloner(ctx);
|
|
207
|
+
const clone = (0, internal_1.cloner)(ctx);
|
|
188
208
|
const snapshot = clone(data);
|
|
189
|
-
const start = now(unsafe);
|
|
209
|
+
const start = (0, internal_1.now)(unsafe);
|
|
190
210
|
if (predicate(clone(snapshot))) {
|
|
191
211
|
const result = await action(clone(snapshot), unsafe, ctx);
|
|
192
|
-
report(ctx, { wrapper: 'withGuard', inner: action, attempt: 1, outcome: 'success', durationMs: now(unsafe) - start });
|
|
212
|
+
(0, internal_1.report)(ctx, { wrapper: 'withGuard', inner: action, attempt: 1, outcome: 'success', durationMs: (0, internal_1.now)(unsafe) - start });
|
|
193
213
|
return result;
|
|
194
214
|
}
|
|
195
|
-
report(ctx, { wrapper: 'withGuard', inner: action, attempt: 1, outcome: 'skipped', durationMs: now(unsafe) - start });
|
|
215
|
+
(0, internal_1.report)(ctx, { wrapper: 'withGuard', inner: action, attempt: 1, outcome: 'skipped', durationMs: (0, internal_1.now)(unsafe) - start });
|
|
196
216
|
return opts.otherwise ? opts.otherwise(clone(snapshot), unsafe, ctx) : data;
|
|
197
217
|
};
|
|
198
218
|
return defineHoa(hoa, { wrapper: 'withGuard', inner, roles: opts.otherwise ? ['guarded', 'otherwise'] : ['guarded'], options: opts });
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { Action } from '@codeinkit/flows';
|
|
2
|
+
export interface IdempotencyRecord {
|
|
3
|
+
state: 'in_progress' | 'done';
|
|
4
|
+
/** hash of the request fingerprint, to detect a key reused with a different request */
|
|
5
|
+
fingerprint: string;
|
|
6
|
+
/** JSON-cloned result of the action, set when `state` is `'done'` */
|
|
7
|
+
result?: unknown;
|
|
8
|
+
createdAt: number;
|
|
9
|
+
}
|
|
10
|
+
type MaybePromise<T> = T | PromiseLike<T>;
|
|
11
|
+
/**
|
|
12
|
+
* The store port `withIdempotency` reads from `unsafe[port]`. Every method may be sync or async.
|
|
13
|
+
* `claim` must be an atomic set-if-absent: it returns true only for the call that created the record.
|
|
14
|
+
*/
|
|
15
|
+
export interface IdempotencyStore {
|
|
16
|
+
claim(key: string, record: IdempotencyRecord, ttlMs: number): MaybePromise<boolean>;
|
|
17
|
+
get(key: string): MaybePromise<IdempotencyRecord | undefined | null>;
|
|
18
|
+
set(key: string, record: IdempotencyRecord, ttlMs: number): MaybePromise<unknown>;
|
|
19
|
+
delete(key: string): MaybePromise<unknown>;
|
|
20
|
+
}
|
|
21
|
+
export interface IdempotencyOptions<D = any> {
|
|
22
|
+
/** reads the key from the input. Default: `data.idempotencyKey`, else the `idempotency-key` header in `data.headers` */
|
|
23
|
+
key?: (data: Partial<D>) => string | undefined;
|
|
24
|
+
/** when true, a run without a key throws `IdempotencyKeyRequiredError`. Default false */
|
|
25
|
+
required?: boolean;
|
|
26
|
+
/** namespace of the keys. Default: the name of the innermost action */
|
|
27
|
+
scope?: string;
|
|
28
|
+
/** how long a record is kept. Default 24 hours */
|
|
29
|
+
ttlMs?: number;
|
|
30
|
+
/** name of the store on `unsafe`. Default `'idempotency'` */
|
|
31
|
+
port?: string;
|
|
32
|
+
/** the part of the input that identifies the request. Default: `data.body ?? data.input ?? data.detail ?? null` */
|
|
33
|
+
fingerprint?: (data: Partial<D>) => unknown;
|
|
34
|
+
}
|
|
35
|
+
export type IdempotencyErrorCode = 'EIDEMPOTENCY_KEY_REQUIRED' | 'EIDEMPOTENCY_CONFLICT' | 'EIDEMPOTENCY_IN_PROGRESS';
|
|
36
|
+
/**
|
|
37
|
+
* Base class of the errors `withIdempotency` throws. Every one carries plain `status`, `code` and
|
|
38
|
+
* `description` fields, so an HTTP layer can answer from them without knowing this package
|
|
39
|
+
* (`@codeinkit/http-trigger` answers `status` with `description` as the body).
|
|
40
|
+
*
|
|
41
|
+
* `description` is safe to show to a client: it never holds the idempotency key, the scope or a
|
|
42
|
+
* stored result. `message` is for logs and does hold the key and the scope.
|
|
43
|
+
*/
|
|
44
|
+
export declare class IdempotencyError extends Error {
|
|
45
|
+
/** HTTP status that fits the error: 400, 422 or 409 */
|
|
46
|
+
readonly status: number;
|
|
47
|
+
readonly code: IdempotencyErrorCode;
|
|
48
|
+
/** short, client-safe text. No key, no scope, no stored result */
|
|
49
|
+
readonly description: string;
|
|
50
|
+
readonly scope: string;
|
|
51
|
+
constructor(message: string, fields: {
|
|
52
|
+
status: number;
|
|
53
|
+
code: IdempotencyErrorCode;
|
|
54
|
+
description: string;
|
|
55
|
+
scope: string;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
export declare class IdempotencyKeyRequiredError extends IdempotencyError {
|
|
59
|
+
readonly status: 400;
|
|
60
|
+
readonly code: 'EIDEMPOTENCY_KEY_REQUIRED';
|
|
61
|
+
constructor(scope: string);
|
|
62
|
+
}
|
|
63
|
+
export declare class IdempotencyConflictError extends IdempotencyError {
|
|
64
|
+
readonly status: 422;
|
|
65
|
+
readonly code: 'EIDEMPOTENCY_CONFLICT';
|
|
66
|
+
readonly key: string;
|
|
67
|
+
constructor(scope: string, key: string);
|
|
68
|
+
}
|
|
69
|
+
export declare class IdempotencyInProgressError extends IdempotencyError {
|
|
70
|
+
readonly status: 409;
|
|
71
|
+
readonly code: 'EIDEMPOTENCY_IN_PROGRESS';
|
|
72
|
+
readonly key: string;
|
|
73
|
+
constructor(scope: string, key: string);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* True for the errors `withIdempotency` throws. Besides `instanceof IdempotencyError` it accepts
|
|
77
|
+
* an error with the same `code`, `status` and a string `description`, so it also works when two
|
|
78
|
+
* copies of this package are installed (where `instanceof` fails).
|
|
79
|
+
*/
|
|
80
|
+
export declare function isIdempotencyError(e: unknown): e is IdempotencyError;
|
|
81
|
+
/**
|
|
82
|
+
* Dedupes repeat runs that carry the same Idempotency-Key. The first run claims the key in the
|
|
83
|
+
* store, runs the action and stores its (JSON-cloned) result. A repeat with the same key and the
|
|
84
|
+
* same request fingerprint returns the stored result without running the action. The same key
|
|
85
|
+
* with a different fingerprint throws `IdempotencyConflictError` (422), a repeat while the first
|
|
86
|
+
* run is still going throws `IdempotencyInProgressError` (409). When the action throws, the key
|
|
87
|
+
* is released so a retry can run. Runs without a key are not deduped (or rejected with
|
|
88
|
+
* `IdempotencyKeyRequiredError` (400) when `required` is set).
|
|
89
|
+
*/
|
|
90
|
+
export declare function withIdempotency<D = any, R = any>(action: Action<D, R>, opts?: IdempotencyOptions<D>): Action<D, R>;
|
|
91
|
+
/**
|
|
92
|
+
* In-memory `IdempotencyStore` with TTL expiry, for tests, browsers and single-process servers.
|
|
93
|
+
* It is not shared between processes: a server with more than one instance needs a shared store
|
|
94
|
+
* (for example a Mongo collection with a unique key and a TTL index, see the README).
|
|
95
|
+
*/
|
|
96
|
+
export declare function createMemoryIdempotencyStore(opts?: {
|
|
97
|
+
now?: () => number;
|
|
98
|
+
}): IdempotencyStore;
|
|
99
|
+
export {};
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createMemoryIdempotencyStore = exports.withIdempotency = exports.isIdempotencyError = exports.IdempotencyInProgressError = exports.IdempotencyConflictError = exports.IdempotencyKeyRequiredError = exports.IdempotencyError = void 0;
|
|
4
|
+
const hoa_1 = require("./hoa");
|
|
5
|
+
const internal_1 = require("./internal");
|
|
6
|
+
/**
|
|
7
|
+
* Base class of the errors `withIdempotency` throws. Every one carries plain `status`, `code` and
|
|
8
|
+
* `description` fields, so an HTTP layer can answer from them without knowing this package
|
|
9
|
+
* (`@codeinkit/http-trigger` answers `status` with `description` as the body).
|
|
10
|
+
*
|
|
11
|
+
* `description` is safe to show to a client: it never holds the idempotency key, the scope or a
|
|
12
|
+
* stored result. `message` is for logs and does hold the key and the scope.
|
|
13
|
+
*/
|
|
14
|
+
class IdempotencyError extends Error {
|
|
15
|
+
constructor(message, fields) {
|
|
16
|
+
super(message);
|
|
17
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
18
|
+
this.name = 'IdempotencyError';
|
|
19
|
+
this.status = fields.status;
|
|
20
|
+
this.code = fields.code;
|
|
21
|
+
this.description = fields.description;
|
|
22
|
+
this.scope = fields.scope;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
exports.IdempotencyError = IdempotencyError;
|
|
26
|
+
class IdempotencyKeyRequiredError extends IdempotencyError {
|
|
27
|
+
constructor(scope) {
|
|
28
|
+
super(`an idempotency key is required for ${scope}`, {
|
|
29
|
+
status: 400,
|
|
30
|
+
code: 'EIDEMPOTENCY_KEY_REQUIRED',
|
|
31
|
+
description: 'An Idempotency-Key is required for this request.',
|
|
32
|
+
scope,
|
|
33
|
+
});
|
|
34
|
+
this.name = 'IdempotencyKeyRequiredError';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
exports.IdempotencyKeyRequiredError = IdempotencyKeyRequiredError;
|
|
38
|
+
class IdempotencyConflictError extends IdempotencyError {
|
|
39
|
+
constructor(scope, key) {
|
|
40
|
+
super(`idempotency key "${key}" was already used for ${scope} with a different request`, {
|
|
41
|
+
status: 422,
|
|
42
|
+
code: 'EIDEMPOTENCY_CONFLICT',
|
|
43
|
+
description: 'This Idempotency-Key was already used with a different request.',
|
|
44
|
+
scope,
|
|
45
|
+
});
|
|
46
|
+
this.name = 'IdempotencyConflictError';
|
|
47
|
+
this.key = key;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
exports.IdempotencyConflictError = IdempotencyConflictError;
|
|
51
|
+
class IdempotencyInProgressError extends IdempotencyError {
|
|
52
|
+
constructor(scope, key) {
|
|
53
|
+
super(`a request with idempotency key "${key}" is still in progress for ${scope}`, {
|
|
54
|
+
status: 409,
|
|
55
|
+
code: 'EIDEMPOTENCY_IN_PROGRESS',
|
|
56
|
+
description: 'A request with this Idempotency-Key is still in progress. Try again later.',
|
|
57
|
+
scope,
|
|
58
|
+
});
|
|
59
|
+
this.name = 'IdempotencyInProgressError';
|
|
60
|
+
this.key = key;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
exports.IdempotencyInProgressError = IdempotencyInProgressError;
|
|
64
|
+
const STATUS_BY_CODE = {
|
|
65
|
+
EIDEMPOTENCY_KEY_REQUIRED: 400,
|
|
66
|
+
EIDEMPOTENCY_CONFLICT: 422,
|
|
67
|
+
EIDEMPOTENCY_IN_PROGRESS: 409,
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* True for the errors `withIdempotency` throws. Besides `instanceof IdempotencyError` it accepts
|
|
71
|
+
* an error with the same `code`, `status` and a string `description`, so it also works when two
|
|
72
|
+
* copies of this package are installed (where `instanceof` fails).
|
|
73
|
+
*/
|
|
74
|
+
function isIdempotencyError(e) {
|
|
75
|
+
if (e instanceof IdempotencyError)
|
|
76
|
+
return true;
|
|
77
|
+
if (!(e instanceof Error))
|
|
78
|
+
return false;
|
|
79
|
+
const { code, status, description } = e;
|
|
80
|
+
return (typeof code === 'string' &&
|
|
81
|
+
Object.prototype.hasOwnProperty.call(STATUS_BY_CODE, code) &&
|
|
82
|
+
STATUS_BY_CODE[code] === status &&
|
|
83
|
+
typeof description === 'string');
|
|
84
|
+
}
|
|
85
|
+
exports.isIdempotencyError = isIdempotencyError;
|
|
86
|
+
/* ---------- key and fingerprint ---------- */
|
|
87
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
88
|
+
const asKey = (v) => {
|
|
89
|
+
if (Array.isArray(v))
|
|
90
|
+
v = v[0]; // node gives repeated headers as an array
|
|
91
|
+
if (typeof v === 'number')
|
|
92
|
+
v = String(v);
|
|
93
|
+
return typeof v === 'string' && v !== '' ? v : undefined;
|
|
94
|
+
};
|
|
95
|
+
function defaultKey(data) {
|
|
96
|
+
if (!data || typeof data !== 'object')
|
|
97
|
+
return undefined;
|
|
98
|
+
const direct = asKey(data.idempotencyKey);
|
|
99
|
+
if (direct !== undefined)
|
|
100
|
+
return direct;
|
|
101
|
+
const headers = data.headers;
|
|
102
|
+
if (!headers || typeof headers !== 'object')
|
|
103
|
+
return undefined;
|
|
104
|
+
if (typeof headers.get === 'function')
|
|
105
|
+
return asKey(headers.get('idempotency-key')); // fetch Headers
|
|
106
|
+
for (const name of Object.keys(headers)) {
|
|
107
|
+
if (name.toLowerCase() === 'idempotency-key')
|
|
108
|
+
return asKey(headers[name]);
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
const defaultFingerprint = (data) => { var _a, _b, _c; return (data ? (_c = (_b = (_a = data.body) !== null && _a !== void 0 ? _a : data.input) !== null && _b !== void 0 ? _b : data.detail) !== null && _c !== void 0 ? _c : null : null); };
|
|
113
|
+
/** JSON with sorted object keys, so equal values give equal text whatever the key order. */
|
|
114
|
+
function stableStringify(value, ancestors = []) {
|
|
115
|
+
if (value !== null && typeof value === 'object' && typeof value.toJSON === 'function')
|
|
116
|
+
value = value.toJSON();
|
|
117
|
+
if (value === null || typeof value !== 'object') {
|
|
118
|
+
const text = JSON.stringify(value);
|
|
119
|
+
return text === undefined ? 'null' : text;
|
|
120
|
+
}
|
|
121
|
+
if (ancestors.indexOf(value) !== -1)
|
|
122
|
+
throw new TypeError('withIdempotency: the fingerprint value is circular');
|
|
123
|
+
const path = ancestors.concat([value]);
|
|
124
|
+
if (Array.isArray(value))
|
|
125
|
+
return `[${value.map((v) => stableStringify(v, path)).join(',')}]`;
|
|
126
|
+
const parts = [];
|
|
127
|
+
for (const k of Object.keys(value).sort()) {
|
|
128
|
+
const v = value[k];
|
|
129
|
+
if (v === undefined || typeof v === 'function' || typeof v === 'symbol')
|
|
130
|
+
continue; // same as JSON.stringify
|
|
131
|
+
parts.push(`${JSON.stringify(k)}:${stableStringify(v, path)}`);
|
|
132
|
+
}
|
|
133
|
+
return `{${parts.join(',')}}`;
|
|
134
|
+
}
|
|
135
|
+
/** FNV-1a (32 bit) over the UTF-16 code units, as 8 hex chars. Not cryptographic. */
|
|
136
|
+
function fnv1a(text) {
|
|
137
|
+
let hash = 0x811c9dc5;
|
|
138
|
+
for (let i = 0; i < text.length; i++) {
|
|
139
|
+
const c = text.charCodeAt(i);
|
|
140
|
+
hash = Math.imul(hash ^ (c & 0xff), 0x01000193);
|
|
141
|
+
hash = Math.imul(hash ^ (c >>> 8), 0x01000193);
|
|
142
|
+
}
|
|
143
|
+
return (hash >>> 0).toString(16).padStart(8, '0');
|
|
144
|
+
}
|
|
145
|
+
/* ---------- withIdempotency ---------- */
|
|
146
|
+
/**
|
|
147
|
+
* Dedupes repeat runs that carry the same Idempotency-Key. The first run claims the key in the
|
|
148
|
+
* store, runs the action and stores its (JSON-cloned) result. A repeat with the same key and the
|
|
149
|
+
* same request fingerprint returns the stored result without running the action. The same key
|
|
150
|
+
* with a different fingerprint throws `IdempotencyConflictError` (422), a repeat while the first
|
|
151
|
+
* run is still going throws `IdempotencyInProgressError` (409). When the action throws, the key
|
|
152
|
+
* is released so a retry can run. Runs without a key are not deduped (or rejected with
|
|
153
|
+
* `IdempotencyKeyRequiredError` (400) when `required` is set).
|
|
154
|
+
*/
|
|
155
|
+
function withIdempotency(action, opts = {}) {
|
|
156
|
+
if (typeof action !== 'function') {
|
|
157
|
+
throw new Error('withIdempotency: action must be a function');
|
|
158
|
+
}
|
|
159
|
+
if (opts.ttlMs !== undefined && (typeof opts.ttlMs !== 'number' || !(opts.ttlMs > 0))) {
|
|
160
|
+
throw new Error('withIdempotency: ttlMs must be a number greater than 0');
|
|
161
|
+
}
|
|
162
|
+
if (opts.port !== undefined && (typeof opts.port !== 'string' || opts.port === '')) {
|
|
163
|
+
throw new Error('withIdempotency: port must be a non-empty string');
|
|
164
|
+
}
|
|
165
|
+
const readKey = opts.key || defaultKey;
|
|
166
|
+
const readFingerprint = opts.fingerprint || defaultFingerprint;
|
|
167
|
+
const scope = opts.scope !== undefined ? opts.scope : (0, internal_1.nameOf)((0, hoa_1.innermostAction)(action));
|
|
168
|
+
const ttlMs = opts.ttlMs === undefined ? DAY_MS : opts.ttlMs;
|
|
169
|
+
const port = opts.port === undefined ? 'idempotency' : opts.port;
|
|
170
|
+
const hoa = async (data, unsafe, ctx) => {
|
|
171
|
+
const start = (0, internal_1.now)(unsafe);
|
|
172
|
+
const fail = (error) => {
|
|
173
|
+
(0, internal_1.report)(ctx, { wrapper: 'withIdempotency', inner: action, attempt: 1, outcome: 'error', error, durationMs: (0, internal_1.now)(unsafe) - start });
|
|
174
|
+
throw error;
|
|
175
|
+
};
|
|
176
|
+
const succeed = (result) => {
|
|
177
|
+
(0, internal_1.report)(ctx, { wrapper: 'withIdempotency', inner: action, attempt: 1, outcome: 'success', durationMs: (0, internal_1.now)(unsafe) - start });
|
|
178
|
+
return result;
|
|
179
|
+
};
|
|
180
|
+
const key = asKey(readKey(data));
|
|
181
|
+
if (key === undefined) {
|
|
182
|
+
if (opts.required)
|
|
183
|
+
return fail(new IdempotencyKeyRequiredError(scope));
|
|
184
|
+
let result;
|
|
185
|
+
try {
|
|
186
|
+
result = await action(data, unsafe, ctx);
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
return fail(error);
|
|
190
|
+
}
|
|
191
|
+
return succeed(result);
|
|
192
|
+
}
|
|
193
|
+
const store = unsafe ? unsafe[port] : undefined;
|
|
194
|
+
if (!store || typeof store.claim !== 'function' || typeof store.get !== 'function' || typeof store.set !== 'function' || typeof store.delete !== 'function') {
|
|
195
|
+
return fail(new Error(`withIdempotency: no idempotency store on unsafe.${port} (it needs claim, get, set and delete)`));
|
|
196
|
+
}
|
|
197
|
+
const storageKey = `${scope}:${key}`;
|
|
198
|
+
const fingerprint = fnv1a(stableStringify(readFingerprint(data)));
|
|
199
|
+
const pending = { state: 'in_progress', fingerprint, createdAt: (0, internal_1.now)(unsafe) };
|
|
200
|
+
let existing;
|
|
201
|
+
try {
|
|
202
|
+
let claimed = await store.claim(storageKey, pending, ttlMs);
|
|
203
|
+
if (!claimed) {
|
|
204
|
+
existing = await store.get(storageKey);
|
|
205
|
+
// the record expired or was released between claim and get: one more try
|
|
206
|
+
if (!existing)
|
|
207
|
+
claimed = await store.claim(storageKey, pending, ttlMs);
|
|
208
|
+
if (!existing && !claimed)
|
|
209
|
+
throw new IdempotencyInProgressError(scope, key);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
return fail(error);
|
|
214
|
+
}
|
|
215
|
+
if (existing) {
|
|
216
|
+
if (existing.fingerprint !== fingerprint)
|
|
217
|
+
return fail(new IdempotencyConflictError(scope, key));
|
|
218
|
+
if (existing.state !== 'done')
|
|
219
|
+
return fail(new IdempotencyInProgressError(scope, key));
|
|
220
|
+
(0, internal_1.report)(ctx, { wrapper: 'withIdempotency', inner: action, attempt: 1, outcome: 'skipped', durationMs: (0, internal_1.now)(unsafe) - start });
|
|
221
|
+
return (0, internal_1.jsonClone)(existing.result);
|
|
222
|
+
}
|
|
223
|
+
let result;
|
|
224
|
+
try {
|
|
225
|
+
result = await action(data, unsafe, ctx);
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
try {
|
|
229
|
+
await store.delete(storageKey); // release the key so a retry can run
|
|
230
|
+
}
|
|
231
|
+
catch (e) {
|
|
232
|
+
// the record then stays in progress until its ttl. The action's error matters more
|
|
233
|
+
}
|
|
234
|
+
return fail(error);
|
|
235
|
+
}
|
|
236
|
+
try {
|
|
237
|
+
// The action has run. When storing fails the key is NOT released (that could run it twice):
|
|
238
|
+
// the error is thrown and repeats get "in progress" until the ttl.
|
|
239
|
+
await store.set(storageKey, { state: 'done', fingerprint, result: (0, internal_1.jsonClone)(result), createdAt: (0, internal_1.now)(unsafe) }, ttlMs);
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
return fail(error);
|
|
243
|
+
}
|
|
244
|
+
return succeed(result);
|
|
245
|
+
};
|
|
246
|
+
return (0, hoa_1.defineHoa)(hoa, { wrapper: 'withIdempotency', inner: [action], options: opts });
|
|
247
|
+
}
|
|
248
|
+
exports.withIdempotency = withIdempotency;
|
|
249
|
+
/* ---------- in-memory store ---------- */
|
|
250
|
+
/**
|
|
251
|
+
* In-memory `IdempotencyStore` with TTL expiry, for tests, browsers and single-process servers.
|
|
252
|
+
* It is not shared between processes: a server with more than one instance needs a shared store
|
|
253
|
+
* (for example a Mongo collection with a unique key and a TTL index, see the README).
|
|
254
|
+
*/
|
|
255
|
+
function createMemoryIdempotencyStore(opts = {}) {
|
|
256
|
+
const clock = typeof opts.now === 'function' ? opts.now : Date.now;
|
|
257
|
+
const records = new Map();
|
|
258
|
+
let writes = 0;
|
|
259
|
+
const live = (key) => {
|
|
260
|
+
const entry = records.get(key);
|
|
261
|
+
if (!entry)
|
|
262
|
+
return undefined;
|
|
263
|
+
if (entry.expiresAt <= clock()) {
|
|
264
|
+
records.delete(key);
|
|
265
|
+
return undefined;
|
|
266
|
+
}
|
|
267
|
+
return entry.record;
|
|
268
|
+
};
|
|
269
|
+
const write = (key, record, ttlMs) => {
|
|
270
|
+
// every now and then drop the expired records, so keys that are never read again do not pile up
|
|
271
|
+
if (++writes % 256 === 0) {
|
|
272
|
+
const t = clock();
|
|
273
|
+
records.forEach((entry, k) => {
|
|
274
|
+
if (entry.expiresAt <= t)
|
|
275
|
+
records.delete(k);
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
records.set(key, { record: (0, internal_1.jsonClone)(record), expiresAt: clock() + ttlMs });
|
|
279
|
+
};
|
|
280
|
+
return {
|
|
281
|
+
claim(key, record, ttlMs) {
|
|
282
|
+
if (live(key))
|
|
283
|
+
return false;
|
|
284
|
+
write(key, record, ttlMs);
|
|
285
|
+
return true;
|
|
286
|
+
},
|
|
287
|
+
get(key) {
|
|
288
|
+
const record = live(key);
|
|
289
|
+
return record ? (0, internal_1.jsonClone)(record) : undefined;
|
|
290
|
+
},
|
|
291
|
+
set(key, record, ttlMs) {
|
|
292
|
+
write(key, record, ttlMs);
|
|
293
|
+
},
|
|
294
|
+
delete(key) {
|
|
295
|
+
records.delete(key);
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
exports.createMemoryIdempotencyStore = createMemoryIdempotencyStore;
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -15,3 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
__exportStar(require("./hoa"), exports);
|
|
18
|
+
__exportStar(require("./idempotency"), exports);
|
|
19
|
+
__exportStar(require("./compensation"), exports);
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ActionContext, AttemptEvent, FlowsAbortSignal } from '@codeinkit/flows';
|
|
2
|
+
export declare const jsonClone: <T>(v: T) => T;
|
|
3
|
+
export declare const cloner: (ctx: ActionContext | undefined) => <T>(v: T) => T;
|
|
4
|
+
export declare function now(unsafe: any): number;
|
|
5
|
+
export declare function random(unsafe: any): number;
|
|
6
|
+
export declare function report(ctx: ActionContext | undefined, ev: AttemptEvent): void;
|
|
7
|
+
export declare const nameOf: (fn: unknown) => string;
|
|
8
|
+
export declare const messageOf: (error: any) => string;
|
|
9
|
+
/** A `FlowsAbortSignal` that may also have the listener methods of a real `AbortSignal`. */
|
|
10
|
+
export interface AbortSignalLike extends FlowsAbortSignal {
|
|
11
|
+
addEventListener?: (type: 'abort', listener: () => void, options?: {
|
|
12
|
+
once?: boolean;
|
|
13
|
+
}) => void;
|
|
14
|
+
removeEventListener?: (type: 'abort', listener: () => void) => void;
|
|
15
|
+
}
|
|
16
|
+
export interface AbortControllerLike {
|
|
17
|
+
readonly signal: AbortSignalLike;
|
|
18
|
+
abort(reason?: unknown): void;
|
|
19
|
+
}
|
|
20
|
+
/** The signal's abort reason, or an `AbortError` when it has none. */
|
|
21
|
+
export declare function abortReason(signal: FlowsAbortSignal): unknown;
|
|
22
|
+
/** A new AbortController, or undefined on runtimes that do not have one. */
|
|
23
|
+
export declare function createAbortController(): AbortControllerLike | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* Calls `listener` once when `signal` aborts. Returns a function that removes the listener.
|
|
26
|
+
* A structural signal without `addEventListener` cannot be listened to, then nothing happens.
|
|
27
|
+
*/
|
|
28
|
+
export declare function onAbort(signal: AbortSignalLike | undefined, listener: () => void): () => void;
|
|
29
|
+
/**
|
|
30
|
+
* Sleeps `ms` (with `unsafe.clock.sleep` when present, else a timer). When `signal` aborts
|
|
31
|
+
* during the sleep it rejects with the abort reason right away and clears its own timer.
|
|
32
|
+
* A signal without `addEventListener` is checked once, after the sleep.
|
|
33
|
+
*/
|
|
34
|
+
export declare function sleep(unsafe: any, ms: number, signal?: AbortSignalLike): Promise<void>;
|
package/dist/internal.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sleep = exports.onAbort = exports.createAbortController = exports.abortReason = exports.messageOf = exports.nameOf = exports.report = exports.random = exports.now = exports.cloner = exports.jsonClone = void 0;
|
|
4
|
+
/* ---------- helpers shared by the HOAs (not exported from the package) ---------- */
|
|
5
|
+
const jsonClone = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v)));
|
|
6
|
+
exports.jsonClone = jsonClone;
|
|
7
|
+
const cloner = (ctx) => ctx && typeof ctx.clone === 'function' ? ctx.clone : exports.jsonClone;
|
|
8
|
+
exports.cloner = cloner;
|
|
9
|
+
/* duck-typed clock / random on the unsafe object */
|
|
10
|
+
function now(unsafe) {
|
|
11
|
+
return unsafe && unsafe.clock && typeof unsafe.clock.now === 'function' ? unsafe.clock.now() : Date.now();
|
|
12
|
+
}
|
|
13
|
+
exports.now = now;
|
|
14
|
+
function random(unsafe) {
|
|
15
|
+
return unsafe && typeof unsafe.random === 'function' ? unsafe.random() : Math.random();
|
|
16
|
+
}
|
|
17
|
+
exports.random = random;
|
|
18
|
+
function report(ctx, ev) {
|
|
19
|
+
if (ctx && typeof ctx.reportAttempt === 'function')
|
|
20
|
+
ctx.reportAttempt(ev);
|
|
21
|
+
}
|
|
22
|
+
exports.report = report;
|
|
23
|
+
const nameOf = (fn) => (typeof fn === 'function' && fn.name) || 'anonymous';
|
|
24
|
+
exports.nameOf = nameOf;
|
|
25
|
+
const messageOf = (error) => { var _a; return String((_a = (error && error.message)) !== null && _a !== void 0 ? _a : error); };
|
|
26
|
+
exports.messageOf = messageOf;
|
|
27
|
+
/** The signal's abort reason, or an `AbortError` when it has none. */
|
|
28
|
+
function abortReason(signal) {
|
|
29
|
+
if (signal.reason !== undefined)
|
|
30
|
+
return signal.reason;
|
|
31
|
+
const error = new Error('aborted');
|
|
32
|
+
error.name = 'AbortError';
|
|
33
|
+
error.code = 'ABORT_ERR';
|
|
34
|
+
return error;
|
|
35
|
+
}
|
|
36
|
+
exports.abortReason = abortReason;
|
|
37
|
+
/** A new AbortController, or undefined on runtimes that do not have one. */
|
|
38
|
+
function createAbortController() {
|
|
39
|
+
const Ctor = globalThis.AbortController;
|
|
40
|
+
if (typeof Ctor !== 'function')
|
|
41
|
+
return undefined;
|
|
42
|
+
try {
|
|
43
|
+
return new Ctor();
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
exports.createAbortController = createAbortController;
|
|
50
|
+
const noop = () => undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Calls `listener` once when `signal` aborts. Returns a function that removes the listener.
|
|
53
|
+
* A structural signal without `addEventListener` cannot be listened to, then nothing happens.
|
|
54
|
+
*/
|
|
55
|
+
function onAbort(signal, listener) {
|
|
56
|
+
if (!signal || typeof signal.addEventListener !== 'function')
|
|
57
|
+
return noop;
|
|
58
|
+
signal.addEventListener('abort', listener, { once: true });
|
|
59
|
+
return () => {
|
|
60
|
+
if (typeof signal.removeEventListener === 'function')
|
|
61
|
+
signal.removeEventListener('abort', listener);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
exports.onAbort = onAbort;
|
|
65
|
+
/**
|
|
66
|
+
* Sleeps `ms` (with `unsafe.clock.sleep` when present, else a timer). When `signal` aborts
|
|
67
|
+
* during the sleep it rejects with the abort reason right away and clears its own timer.
|
|
68
|
+
* A signal without `addEventListener` is checked once, after the sleep.
|
|
69
|
+
*/
|
|
70
|
+
function sleep(unsafe, ms, signal) {
|
|
71
|
+
const custom = unsafe && unsafe.clock && typeof unsafe.clock.sleep === 'function';
|
|
72
|
+
if (!signal) {
|
|
73
|
+
if (custom)
|
|
74
|
+
return Promise.resolve(unsafe.clock.sleep(ms));
|
|
75
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
76
|
+
}
|
|
77
|
+
return new Promise((resolve, reject) => {
|
|
78
|
+
let timer;
|
|
79
|
+
const unlisten = onAbort(signal, () => {
|
|
80
|
+
unlisten(); // for signals that do not honour `once`
|
|
81
|
+
if (timer !== undefined)
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
reject(abortReason(signal));
|
|
84
|
+
});
|
|
85
|
+
const done = () => {
|
|
86
|
+
unlisten();
|
|
87
|
+
if (signal.aborted)
|
|
88
|
+
reject(abortReason(signal));
|
|
89
|
+
else
|
|
90
|
+
resolve();
|
|
91
|
+
};
|
|
92
|
+
const fail = (error) => {
|
|
93
|
+
unlisten();
|
|
94
|
+
reject(error);
|
|
95
|
+
};
|
|
96
|
+
if (custom) {
|
|
97
|
+
try {
|
|
98
|
+
Promise.resolve(unsafe.clock.sleep(ms)).then(done, fail);
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
fail(error);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
timer = setTimeout(done, ms);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
exports.sleep = sleep;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codeinkit/flows-hoa",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Higher-Order Actions (retry, fallback, timeout, guard) for @codeinkit/flows v4",
|
|
3
|
+
"version": "0.2.0-alpha.1",
|
|
4
|
+
"description": "Higher-Order Actions (retry, fallback, timeout with cancellation, guard, idempotency, compensation) for @codeinkit/flows v4",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"files": ["dist", "README.md", "LICENSE"],
|
|
@@ -14,9 +14,9 @@
|
|
|
14
14
|
"homepage": "https://github.com/amitmtrn/flows-hoa",
|
|
15
15
|
"license": "MIT",
|
|
16
16
|
"author": "codinkit dev team <dev@codinkit.com>",
|
|
17
|
-
"peerDependencies": { "@codeinkit/flows": "^4.0.0-alpha.
|
|
17
|
+
"peerDependencies": { "@codeinkit/flows": "^4.0.0-alpha.1" },
|
|
18
18
|
"devDependencies": {
|
|
19
|
-
"@codeinkit/flows": "
|
|
19
|
+
"@codeinkit/flows": "4.0.0-alpha.1",
|
|
20
20
|
"@types/jest": "^30.0.0",
|
|
21
21
|
"@types/node": "^12.19.3",
|
|
22
22
|
"jest": "^30.0.0",
|