@codeinkit/flows-hoa 0.1.0-alpha.0 → 0.2.0-alpha.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/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 `withGuard`. The package has no runtime dependencies. It imports types only from `@codeinkit/flows`.
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@alpha @codeinkit/flows-hoa@alpha
8
+ npm i @codeinkit/flows@next @codeinkit/flows-hoa@next
9
9
  ```
10
10
 
11
- Core v4 is still in alpha, so it needs the `alpha` tag (the peer dependency range is `@codeinkit/flows` `^4.0.0-alpha.0`). This package is alpha too.
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,212 @@ 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
+ | Error | `code` | `status` |
140
+ | --- | --- | --- |
141
+ | `IdempotencyKeyRequiredError` | `EIDEMPOTENCY_KEY_REQUIRED` | 400 |
142
+ | `IdempotencyConflictError` | `EIDEMPOTENCY_CONFLICT` | 422 |
143
+ | `IdempotencyInProgressError` | `EIDEMPOTENCY_IN_PROGRESS` | 409 |
144
+
145
+ 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.
146
+
147
+ Notes:
148
+
149
+ - The result must survive a JSON round trip. That is what a repeat gets back.
150
+ - A stored result is replayed as it was returned, including `$$: { jump }` or `$$: { done }`.
151
+ - 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.
152
+ - 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.
153
+ - 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.
154
+ - `key` and `fingerprint` receive the action's input itself. Do not change it there.
155
+
156
+ ### With withRetry
157
+
158
+ 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.
159
+
160
+ ```ts
161
+ withRetry(withIdempotency(chargeCard, { required: true }), { maxAttempts: 3, idempotent: 'via-key' });
162
+ ```
163
+
164
+ ### Store port
165
+
166
+ The store is read from `unsafe[port]`. Every method may return a value or a Promise.
167
+
168
+ ```ts
169
+ interface IdempotencyStore {
170
+ claim(key: string, record: IdempotencyRecord, ttlMs: number): boolean; // atomic set-if-absent, true when this call created the record
171
+ get(key: string): IdempotencyRecord | undefined;
172
+ set(key: string, record: IdempotencyRecord, ttlMs: number): void;
173
+ delete(key: string): void;
174
+ }
175
+
176
+ interface IdempotencyRecord {
177
+ state: 'in_progress' | 'done';
178
+ fingerprint: string;
179
+ result?: unknown; // set when state is 'done'
180
+ createdAt: number;
181
+ }
182
+ ```
183
+
184
+ `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).
185
+
186
+ ### Memory store
187
+
188
+ `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.
189
+
190
+ 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:
191
+
192
+ ```ts
193
+ // once: await col.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });
194
+ const mongoIdempotencyStore = (col: Collection<any>): IdempotencyStore => ({
195
+ async claim(key, record, ttlMs) {
196
+ try {
197
+ await col.insertOne({ _id: key, ...record, expiresAt: new Date(Date.now() + ttlMs) });
198
+ return true;
199
+ } catch (e: any) {
200
+ if (e.code === 11000) return false; // duplicate key: someone else has it
201
+ throw e;
202
+ }
203
+ },
204
+ async get(key) {
205
+ // the TTL monitor runs about once a minute, so check expiresAt as well
206
+ const doc = await col.findOne({ _id: key, expiresAt: { $gt: new Date() } });
207
+ return doc ? { state: doc.state, fingerprint: doc.fingerprint, result: doc.result, createdAt: doc.createdAt } : undefined;
208
+ },
209
+ async set(key, record, ttlMs) {
210
+ await col.replaceOne({ _id: key }, { ...record, expiresAt: new Date(Date.now() + ttlMs) }, { upsert: true });
211
+ },
212
+ async delete(key) {
213
+ await col.deleteOne({ _id: key });
214
+ },
215
+ });
216
+ ```
217
+
218
+ 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`.
219
+
220
+ ## withCompensation(steps)
221
+
222
+ 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`.
223
+
224
+ ```ts
225
+ import { withCompensation } from '@codeinkit/flows-hoa';
226
+
227
+ const reserveStock = async (data, unsafe) => ({ ...data, reservationId: await unsafe.stock.reserve(data.items) });
228
+ const releaseStock = async (data, unsafe) => { await unsafe.stock.release(data.reservationId); return {}; };
229
+ const chargeCard = async (data, unsafe) => ({ ...data, chargeId: await unsafe.payments.charge(data.amount) });
230
+ const refundCard = async (data, unsafe) => { await unsafe.payments.refund(data.chargeId); return {}; };
231
+ const confirmOrder = async (data, unsafe) => ({ ...data, confirmed: await unsafe.orders.confirm(data.orderId) });
232
+
233
+ flows.register('placeOrder', [
234
+ withCompensation([
235
+ { action: reserveStock, undo: releaseStock },
236
+ { action: chargeCard, undo: refundCard },
237
+ { action: confirmOrder },
238
+ ]),
239
+ ]);
240
+ ```
241
+
242
+ When `confirmOrder` throws, `refundCard` runs, then `releaseStock`, and the flow rejects with the error of `confirmOrder`.
243
+
244
+ - 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.
245
+ - A step must return an object, like any action in a flow.
246
+ - 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.
247
+ - 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.
248
+ - An undo that throws does not stop the other undos.
249
+ - 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.
250
+ - 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.
251
+ - `$$.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.
252
+ - Every step and every undo is reported through `ctx.reportAttempt` with `wrapper: 'withCompensation'` and outcome `success` or `error`.
253
+ - `steps` needs at least one step. Every `action` and `undo` must be a function, this is checked when the HOA is created.
254
+ - Metadata: `inner` lists each step action followed by its undo, `roles` holds the matching `'step'` / `'undo'` entries.
255
+
256
+ Steps can be HOAs themselves, for example `{ action: withRetry(withIdempotency(chargeCard), { maxAttempts: 3, idempotent: 'via-key' }), undo: refundCard }`.
257
+
62
258
  ## Invariants
63
259
 
64
260
  - Retry and fallback trigger only on **thrown** errors. A returned result, including `$$: { done }` or `$$: { jump }`, passes through untouched.
65
261
  - Each attempt, fallback and predicate call gets a **fresh clone** of the original input, so a failed attempt cannot leak mutations.
66
262
  - The `unsafe` argument is passed on as the **same reference**.
67
263
  - Do not keep state in factory closures. An HOA instance is shared by every execution of the flow.
68
- - `withTimeout` does **not cancel** the inner promise. It keeps running and its late result or error is ignored.
264
+ - `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.
265
+ - `withIdempotency` passes the input on as it is (no clone). `withCompensation` clones the input once, for the first step.
69
266
  - Order matters. `withRetry(withTimeout(x))` is a timeout per attempt. `withTimeout(withRetry(x))` is one timeout for all attempts.
70
267
  - 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
268
 
@@ -79,7 +276,7 @@ flows.hook(SupportedHooks.ACTION_ATTEMPT, (e) => console.log(e.wrapper, e.attemp
79
276
 
80
277
  ```ts
81
278
  interface AttemptEvent {
82
- wrapper: string; // 'withRetry' | 'withFallback' | 'withTimeout' | 'withGuard' | your own
279
+ wrapper: string; // 'withRetry' | 'withFallback' | 'withTimeout' | 'withGuard' | 'withIdempotency' | 'withCompensation' | your own
83
280
  inner: Action; // the action that was attempted
84
281
  attempt: number; // 1-based
85
282
  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
- * Note: the inner promise is NOT cancelled on timeout, it keeps running in the background
47
- * (its late result or rejection is ignored). Cancellation (e.g. an abort signal) is out of scope.
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
- const start = now(unsafe);
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
- if (attempt >= opts.maxAttempts || (opts.retryOn && !opts.retryOn(error, attempt))) {
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, _b;
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: String((_a = (error && error.message)) !== null && _a !== void 0 ? _a : error),
112
- code: (_b = (error && error.code)) !== null && _b !== void 0 ? _b : 'error',
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
- * Note: the inner promise is NOT cancelled on timeout, it keeps running in the background
143
- * (its late result or rejection is ignored). Cancellation (e.g. an abort signal) is out of scope.
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
- const timeout = new Promise((_, reject) => {
155
- timer = setTimeout(() => reject(new ActionTimeoutError(action.name, opts.ms)), opts.ms);
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, ctx));
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, timeout]);
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
- const outcome = error instanceof ActionTimeoutError ? 'timeout' : 'error';
172
- report(ctx, { wrapper: 'withTimeout', inner: action, attempt: 1, outcome, error, durationMs: now(unsafe) - start });
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,73 @@
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 declare class IdempotencyKeyRequiredError extends Error {
36
+ code: string;
37
+ status: number;
38
+ scope: string;
39
+ constructor(scope: string);
40
+ }
41
+ export declare class IdempotencyConflictError extends Error {
42
+ code: string;
43
+ status: number;
44
+ scope: string;
45
+ key: string;
46
+ constructor(scope: string, key: string);
47
+ }
48
+ export declare class IdempotencyInProgressError extends Error {
49
+ code: string;
50
+ status: number;
51
+ scope: string;
52
+ key: string;
53
+ constructor(scope: string, key: string);
54
+ }
55
+ /**
56
+ * Dedupes repeat runs that carry the same Idempotency-Key. The first run claims the key in the
57
+ * store, runs the action and stores its (JSON-cloned) result. A repeat with the same key and the
58
+ * same request fingerprint returns the stored result without running the action. The same key
59
+ * with a different fingerprint throws `IdempotencyConflictError` (422), a repeat while the first
60
+ * run is still going throws `IdempotencyInProgressError` (409). When the action throws, the key
61
+ * is released so a retry can run. Runs without a key are not deduped (or rejected with
62
+ * `IdempotencyKeyRequiredError` (400) when `required` is set).
63
+ */
64
+ export declare function withIdempotency<D = any, R = any>(action: Action<D, R>, opts?: IdempotencyOptions<D>): Action<D, R>;
65
+ /**
66
+ * In-memory `IdempotencyStore` with TTL expiry, for tests, browsers and single-process servers.
67
+ * It is not shared between processes: a server with more than one instance needs a shared store
68
+ * (for example a Mongo collection with a unique key and a TTL index, see the README).
69
+ */
70
+ export declare function createMemoryIdempotencyStore(opts?: {
71
+ now?: () => number;
72
+ }): IdempotencyStore;
73
+ export {};
@@ -0,0 +1,255 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createMemoryIdempotencyStore = exports.withIdempotency = exports.IdempotencyInProgressError = exports.IdempotencyConflictError = exports.IdempotencyKeyRequiredError = void 0;
4
+ const hoa_1 = require("./hoa");
5
+ const internal_1 = require("./internal");
6
+ /* ---------- errors ---------- */
7
+ class IdempotencyKeyRequiredError extends Error {
8
+ constructor(scope) {
9
+ super(`an idempotency key is required for ${scope}`);
10
+ this.code = 'EIDEMPOTENCY_KEY_REQUIRED';
11
+ this.status = 400;
12
+ Object.setPrototypeOf(this, IdempotencyKeyRequiredError.prototype);
13
+ this.name = 'IdempotencyKeyRequiredError';
14
+ this.scope = scope;
15
+ }
16
+ }
17
+ exports.IdempotencyKeyRequiredError = IdempotencyKeyRequiredError;
18
+ class IdempotencyConflictError extends Error {
19
+ constructor(scope, key) {
20
+ super(`idempotency key "${key}" was already used for ${scope} with a different request`);
21
+ this.code = 'EIDEMPOTENCY_CONFLICT';
22
+ this.status = 422;
23
+ Object.setPrototypeOf(this, IdempotencyConflictError.prototype);
24
+ this.name = 'IdempotencyConflictError';
25
+ this.scope = scope;
26
+ this.key = key;
27
+ }
28
+ }
29
+ exports.IdempotencyConflictError = IdempotencyConflictError;
30
+ class IdempotencyInProgressError extends Error {
31
+ constructor(scope, key) {
32
+ super(`a request with idempotency key "${key}" is still in progress for ${scope}`);
33
+ this.code = 'EIDEMPOTENCY_IN_PROGRESS';
34
+ this.status = 409;
35
+ Object.setPrototypeOf(this, IdempotencyInProgressError.prototype);
36
+ this.name = 'IdempotencyInProgressError';
37
+ this.scope = scope;
38
+ this.key = key;
39
+ }
40
+ }
41
+ exports.IdempotencyInProgressError = IdempotencyInProgressError;
42
+ /* ---------- key and fingerprint ---------- */
43
+ const DAY_MS = 24 * 60 * 60 * 1000;
44
+ const asKey = (v) => {
45
+ if (Array.isArray(v))
46
+ v = v[0]; // node gives repeated headers as an array
47
+ if (typeof v === 'number')
48
+ v = String(v);
49
+ return typeof v === 'string' && v !== '' ? v : undefined;
50
+ };
51
+ function defaultKey(data) {
52
+ if (!data || typeof data !== 'object')
53
+ return undefined;
54
+ const direct = asKey(data.idempotencyKey);
55
+ if (direct !== undefined)
56
+ return direct;
57
+ const headers = data.headers;
58
+ if (!headers || typeof headers !== 'object')
59
+ return undefined;
60
+ if (typeof headers.get === 'function')
61
+ return asKey(headers.get('idempotency-key')); // fetch Headers
62
+ for (const name of Object.keys(headers)) {
63
+ if (name.toLowerCase() === 'idempotency-key')
64
+ return asKey(headers[name]);
65
+ }
66
+ return undefined;
67
+ }
68
+ 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); };
69
+ /** JSON with sorted object keys, so equal values give equal text whatever the key order. */
70
+ function stableStringify(value, ancestors = []) {
71
+ if (value !== null && typeof value === 'object' && typeof value.toJSON === 'function')
72
+ value = value.toJSON();
73
+ if (value === null || typeof value !== 'object') {
74
+ const text = JSON.stringify(value);
75
+ return text === undefined ? 'null' : text;
76
+ }
77
+ if (ancestors.indexOf(value) !== -1)
78
+ throw new TypeError('withIdempotency: the fingerprint value is circular');
79
+ const path = ancestors.concat([value]);
80
+ if (Array.isArray(value))
81
+ return `[${value.map((v) => stableStringify(v, path)).join(',')}]`;
82
+ const parts = [];
83
+ for (const k of Object.keys(value).sort()) {
84
+ const v = value[k];
85
+ if (v === undefined || typeof v === 'function' || typeof v === 'symbol')
86
+ continue; // same as JSON.stringify
87
+ parts.push(`${JSON.stringify(k)}:${stableStringify(v, path)}`);
88
+ }
89
+ return `{${parts.join(',')}}`;
90
+ }
91
+ /** FNV-1a (32 bit) over the UTF-16 code units, as 8 hex chars. Not cryptographic. */
92
+ function fnv1a(text) {
93
+ let hash = 0x811c9dc5;
94
+ for (let i = 0; i < text.length; i++) {
95
+ const c = text.charCodeAt(i);
96
+ hash = Math.imul(hash ^ (c & 0xff), 0x01000193);
97
+ hash = Math.imul(hash ^ (c >>> 8), 0x01000193);
98
+ }
99
+ return (hash >>> 0).toString(16).padStart(8, '0');
100
+ }
101
+ /* ---------- withIdempotency ---------- */
102
+ /**
103
+ * Dedupes repeat runs that carry the same Idempotency-Key. The first run claims the key in the
104
+ * store, runs the action and stores its (JSON-cloned) result. A repeat with the same key and the
105
+ * same request fingerprint returns the stored result without running the action. The same key
106
+ * with a different fingerprint throws `IdempotencyConflictError` (422), a repeat while the first
107
+ * run is still going throws `IdempotencyInProgressError` (409). When the action throws, the key
108
+ * is released so a retry can run. Runs without a key are not deduped (or rejected with
109
+ * `IdempotencyKeyRequiredError` (400) when `required` is set).
110
+ */
111
+ function withIdempotency(action, opts = {}) {
112
+ if (typeof action !== 'function') {
113
+ throw new Error('withIdempotency: action must be a function');
114
+ }
115
+ if (opts.ttlMs !== undefined && (typeof opts.ttlMs !== 'number' || !(opts.ttlMs > 0))) {
116
+ throw new Error('withIdempotency: ttlMs must be a number greater than 0');
117
+ }
118
+ if (opts.port !== undefined && (typeof opts.port !== 'string' || opts.port === '')) {
119
+ throw new Error('withIdempotency: port must be a non-empty string');
120
+ }
121
+ const readKey = opts.key || defaultKey;
122
+ const readFingerprint = opts.fingerprint || defaultFingerprint;
123
+ const scope = opts.scope !== undefined ? opts.scope : (0, internal_1.nameOf)((0, hoa_1.innermostAction)(action));
124
+ const ttlMs = opts.ttlMs === undefined ? DAY_MS : opts.ttlMs;
125
+ const port = opts.port === undefined ? 'idempotency' : opts.port;
126
+ const hoa = async (data, unsafe, ctx) => {
127
+ const start = (0, internal_1.now)(unsafe);
128
+ const fail = (error) => {
129
+ (0, internal_1.report)(ctx, { wrapper: 'withIdempotency', inner: action, attempt: 1, outcome: 'error', error, durationMs: (0, internal_1.now)(unsafe) - start });
130
+ throw error;
131
+ };
132
+ const succeed = (result) => {
133
+ (0, internal_1.report)(ctx, { wrapper: 'withIdempotency', inner: action, attempt: 1, outcome: 'success', durationMs: (0, internal_1.now)(unsafe) - start });
134
+ return result;
135
+ };
136
+ const key = asKey(readKey(data));
137
+ if (key === undefined) {
138
+ if (opts.required)
139
+ return fail(new IdempotencyKeyRequiredError(scope));
140
+ let result;
141
+ try {
142
+ result = await action(data, unsafe, ctx);
143
+ }
144
+ catch (error) {
145
+ return fail(error);
146
+ }
147
+ return succeed(result);
148
+ }
149
+ const store = unsafe ? unsafe[port] : undefined;
150
+ if (!store || typeof store.claim !== 'function' || typeof store.get !== 'function' || typeof store.set !== 'function' || typeof store.delete !== 'function') {
151
+ return fail(new Error(`withIdempotency: no idempotency store on unsafe.${port} (it needs claim, get, set and delete)`));
152
+ }
153
+ const storageKey = `${scope}:${key}`;
154
+ const fingerprint = fnv1a(stableStringify(readFingerprint(data)));
155
+ const pending = { state: 'in_progress', fingerprint, createdAt: (0, internal_1.now)(unsafe) };
156
+ let existing;
157
+ try {
158
+ let claimed = await store.claim(storageKey, pending, ttlMs);
159
+ if (!claimed) {
160
+ existing = await store.get(storageKey);
161
+ // the record expired or was released between claim and get: one more try
162
+ if (!existing)
163
+ claimed = await store.claim(storageKey, pending, ttlMs);
164
+ if (!existing && !claimed)
165
+ throw new IdempotencyInProgressError(scope, key);
166
+ }
167
+ }
168
+ catch (error) {
169
+ return fail(error);
170
+ }
171
+ if (existing) {
172
+ if (existing.fingerprint !== fingerprint)
173
+ return fail(new IdempotencyConflictError(scope, key));
174
+ if (existing.state !== 'done')
175
+ return fail(new IdempotencyInProgressError(scope, key));
176
+ (0, internal_1.report)(ctx, { wrapper: 'withIdempotency', inner: action, attempt: 1, outcome: 'skipped', durationMs: (0, internal_1.now)(unsafe) - start });
177
+ return (0, internal_1.jsonClone)(existing.result);
178
+ }
179
+ let result;
180
+ try {
181
+ result = await action(data, unsafe, ctx);
182
+ }
183
+ catch (error) {
184
+ try {
185
+ await store.delete(storageKey); // release the key so a retry can run
186
+ }
187
+ catch (e) {
188
+ // the record then stays in progress until its ttl. The action's error matters more
189
+ }
190
+ return fail(error);
191
+ }
192
+ try {
193
+ // The action has run. When storing fails the key is NOT released (that could run it twice):
194
+ // the error is thrown and repeats get "in progress" until the ttl.
195
+ await store.set(storageKey, { state: 'done', fingerprint, result: (0, internal_1.jsonClone)(result), createdAt: (0, internal_1.now)(unsafe) }, ttlMs);
196
+ }
197
+ catch (error) {
198
+ return fail(error);
199
+ }
200
+ return succeed(result);
201
+ };
202
+ return (0, hoa_1.defineHoa)(hoa, { wrapper: 'withIdempotency', inner: [action], options: opts });
203
+ }
204
+ exports.withIdempotency = withIdempotency;
205
+ /* ---------- in-memory store ---------- */
206
+ /**
207
+ * In-memory `IdempotencyStore` with TTL expiry, for tests, browsers and single-process servers.
208
+ * It is not shared between processes: a server with more than one instance needs a shared store
209
+ * (for example a Mongo collection with a unique key and a TTL index, see the README).
210
+ */
211
+ function createMemoryIdempotencyStore(opts = {}) {
212
+ const clock = typeof opts.now === 'function' ? opts.now : Date.now;
213
+ const records = new Map();
214
+ let writes = 0;
215
+ const live = (key) => {
216
+ const entry = records.get(key);
217
+ if (!entry)
218
+ return undefined;
219
+ if (entry.expiresAt <= clock()) {
220
+ records.delete(key);
221
+ return undefined;
222
+ }
223
+ return entry.record;
224
+ };
225
+ const write = (key, record, ttlMs) => {
226
+ // every now and then drop the expired records, so keys that are never read again do not pile up
227
+ if (++writes % 256 === 0) {
228
+ const t = clock();
229
+ records.forEach((entry, k) => {
230
+ if (entry.expiresAt <= t)
231
+ records.delete(k);
232
+ });
233
+ }
234
+ records.set(key, { record: (0, internal_1.jsonClone)(record), expiresAt: clock() + ttlMs });
235
+ };
236
+ return {
237
+ claim(key, record, ttlMs) {
238
+ if (live(key))
239
+ return false;
240
+ write(key, record, ttlMs);
241
+ return true;
242
+ },
243
+ get(key) {
244
+ const record = live(key);
245
+ return record ? (0, internal_1.jsonClone)(record) : undefined;
246
+ },
247
+ set(key, record, ttlMs) {
248
+ write(key, record, ttlMs);
249
+ },
250
+ delete(key) {
251
+ records.delete(key);
252
+ },
253
+ };
254
+ }
255
+ exports.createMemoryIdempotencyStore = createMemoryIdempotencyStore;
package/dist/index.d.ts CHANGED
@@ -1 +1,4 @@
1
1
  export * from './hoa';
2
+ export * from './idempotency';
3
+ export * from './compensation';
4
+ export type { AbortSignalLike } from './internal';
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>;
@@ -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.1.0-alpha.0",
4
- "description": "Higher-Order Actions (retry, fallback, timeout, guard) for @codeinkit/flows v4",
3
+ "version": "0.2.0-alpha.0",
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.0" },
17
+ "peerDependencies": { "@codeinkit/flows": "^4.0.0-alpha.1" },
18
18
  "devDependencies": {
19
- "@codeinkit/flows": "file:vendor/codeinkit-flows-4.0.0-alpha.0.tgz",
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",