@codeinkit/flows-hoa 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +115 -2
- package/dist/hoa.d.ts +54 -0
- package/dist/hoa.js +200 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +17 -0
- package/package.json +24 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) codeinkit dev team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,116 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @codeinkit/flows-hoa
|
|
2
2
|
|
|
3
|
-
|
|
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`.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm i @codeinkit/flows@alpha @codeinkit/flows-hoa@alpha
|
|
9
|
+
```
|
|
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.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Flows } from '@codeinkit/flows';
|
|
17
|
+
import { withRetry, withTimeout, withFallback, withGuard } from '@codeinkit/flows-hoa';
|
|
18
|
+
|
|
19
|
+
const chargeCard = async (data, unsafe) => ({ ...data, charged: await unsafe.payments.charge(data.amount) });
|
|
20
|
+
const queuePayment = (data) => ({ ...data, queued: true });
|
|
21
|
+
|
|
22
|
+
const flows = new Flows({ ports: { payments } });
|
|
23
|
+
flows.register('checkout', [
|
|
24
|
+
withGuard(
|
|
25
|
+
(data) => data.amount > 0,
|
|
26
|
+
withFallback(
|
|
27
|
+
withRetry(withTimeout(chargeCard, { ms: 2000 }), { maxAttempts: 3, idempotent: 'via-key' }),
|
|
28
|
+
queuePayment
|
|
29
|
+
)
|
|
30
|
+
),
|
|
31
|
+
]);
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## withRetry(action, options)
|
|
35
|
+
|
|
36
|
+
Runs `action` again when it throws.
|
|
37
|
+
|
|
38
|
+
| Option | Default | Meaning |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `maxAttempts` | required | Integer from 1 to 10 (total attempts). |
|
|
41
|
+
| `idempotent` | required | `true` or `'via-key'`. You must state that repeating the action is safe. |
|
|
42
|
+
| `backoffMs` | 100 | Base delay after the first failure. |
|
|
43
|
+
| `factor` | 2 | Multiplier per attempt. |
|
|
44
|
+
| `maxBackoffMs` | 5000 | Upper bound of the delay. |
|
|
45
|
+
| `jitter` | true | Full jitter: `random() * delay`. |
|
|
46
|
+
| `retryOn(error, attempt)` | always | Return `false` to stop and rethrow. |
|
|
47
|
+
|
|
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
|
+
|
|
50
|
+
## withFallback(primary, fallback, { fallbackOn? })
|
|
51
|
+
|
|
52
|
+
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.
|
|
53
|
+
|
|
54
|
+
## withTimeout(action, { ms })
|
|
55
|
+
|
|
56
|
+
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
|
+
|
|
58
|
+
## withGuard(predicate, action, { otherwise? })
|
|
59
|
+
|
|
60
|
+
Runs `action` when `predicate(data)` is true. Otherwise it runs `otherwise`, or returns the input unchanged.
|
|
61
|
+
|
|
62
|
+
## Invariants
|
|
63
|
+
|
|
64
|
+
- Retry and fallback trigger only on **thrown** errors. A returned result, including `$$: { done }` or `$$: { jump }`, passes through untouched.
|
|
65
|
+
- Each attempt, fallback and predicate call gets a **fresh clone** of the original input, so a failed attempt cannot leak mutations.
|
|
66
|
+
- The `unsafe` argument is passed on as the **same reference**.
|
|
67
|
+
- 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.
|
|
69
|
+
- Order matters. `withRetry(withTimeout(x))` is a timeout per attempt. `withTimeout(withRetry(x))` is one timeout for all attempts.
|
|
70
|
+
- 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
|
+
|
|
72
|
+
## How it reports attempts
|
|
73
|
+
|
|
74
|
+
Each HOA calls `ctx.reportAttempt(event)` when a `ctx` is given. The core forwards it to the `ACTION_ATTEMPT` hook with `flowName`, `i` and `actionFn` added:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
flows.hook(SupportedHooks.ACTION_ATTEMPT, (e) => console.log(e.wrapper, e.attempt, e.outcome));
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
interface AttemptEvent {
|
|
82
|
+
wrapper: string; // 'withRetry' | 'withFallback' | 'withTimeout' | 'withGuard' | your own
|
|
83
|
+
inner: Action; // the action that was attempted
|
|
84
|
+
attempt: number; // 1-based
|
|
85
|
+
outcome: 'success' | 'error' | 'timeout' | 'fallback' | 'skipped';
|
|
86
|
+
error?: unknown;
|
|
87
|
+
durationMs: number;
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Writing your own HOA with defineHoa
|
|
92
|
+
|
|
93
|
+
`defineHoa(fn, { wrapper, inner, roles?, options? })` names the function (`wrapper(innerName, ...)`) and attaches metadata.
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { defineHoa, type HigherOrderAction } from '@codeinkit/flows-hoa';
|
|
97
|
+
|
|
98
|
+
const withLog: HigherOrderAction<{ label: string }> = (action, opts) =>
|
|
99
|
+
defineHoa(
|
|
100
|
+
async (data, unsafe, ctx) => {
|
|
101
|
+
console.log(opts.label);
|
|
102
|
+
return action(data, unsafe, ctx);
|
|
103
|
+
},
|
|
104
|
+
{ wrapper: 'withLog', inner: [action], options: opts }
|
|
105
|
+
);
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`getHoaMeta(fn)` returns the metadata and `innermostAction(fn)` follows the first inner action down to the plain action.
|
|
109
|
+
|
|
110
|
+
## HOA metadata symbol
|
|
111
|
+
|
|
112
|
+
The metadata is stored under `Symbol.for('codeinkit.flows.hoa')`, exported as `HOA`. This package owns that symbol. Monitors and scanners can read `fn[Symbol.for('codeinkit.flows.hoa')]` without importing this package.
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
MIT
|
package/dist/hoa.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Action } from '@codeinkit/flows';
|
|
2
|
+
export type FallbackInfo = {
|
|
3
|
+
action: string;
|
|
4
|
+
message: string;
|
|
5
|
+
code: string;
|
|
6
|
+
};
|
|
7
|
+
export declare const HOA: unique symbol;
|
|
8
|
+
export interface HoaMeta {
|
|
9
|
+
wrapper: string;
|
|
10
|
+
inner: Action[];
|
|
11
|
+
roles?: string[];
|
|
12
|
+
options?: unknown;
|
|
13
|
+
}
|
|
14
|
+
export declare function getHoaMeta(fn: unknown): HoaMeta | undefined;
|
|
15
|
+
export declare function innermostAction(fn: Action): Action;
|
|
16
|
+
/** A function that wraps an action using options `O`. */
|
|
17
|
+
export type HigherOrderAction<O = unknown> = (action: Action, options: O) => Action;
|
|
18
|
+
export declare function defineHoa<A extends Action>(fn: A, meta: HoaMeta): A;
|
|
19
|
+
export interface RetryOptions {
|
|
20
|
+
maxAttempts: number;
|
|
21
|
+
backoffMs?: number;
|
|
22
|
+
factor?: number;
|
|
23
|
+
maxBackoffMs?: number;
|
|
24
|
+
jitter?: boolean;
|
|
25
|
+
retryOn?: (error: unknown, attempt: number) => boolean;
|
|
26
|
+
idempotent: true | 'via-key';
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Delay in ms to wait after failed attempt number `attempt` (1-based).
|
|
30
|
+
* With jitter (default) this is full jitter: rand() * min(maxBackoffMs, backoffMs * factor^(attempt-1)).
|
|
31
|
+
*/
|
|
32
|
+
export declare function backoffDelay(attempt: number, opts: Pick<RetryOptions, 'backoffMs' | 'factor' | 'maxBackoffMs' | 'jitter'>, rand: () => number): number;
|
|
33
|
+
export declare function withRetry<D = any, R = any>(action: Action<D, R>, opts: RetryOptions): Action<D, R>;
|
|
34
|
+
export declare function withFallback<D = any, R1 = any, R2 = any>(primary: Action<D, R1>, fallback: Action<D & {
|
|
35
|
+
fallbackFrom: FallbackInfo;
|
|
36
|
+
}, R2>, opts?: {
|
|
37
|
+
fallbackOn?: (error: unknown) => boolean;
|
|
38
|
+
}): Action<D, R1 | R2>;
|
|
39
|
+
export declare class ActionTimeoutError extends Error {
|
|
40
|
+
code: string;
|
|
41
|
+
action: string;
|
|
42
|
+
ms: number;
|
|
43
|
+
constructor(action: string, ms: number);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
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.
|
|
48
|
+
*/
|
|
49
|
+
export declare function withTimeout<D = any, R = any>(action: Action<D, R>, opts: {
|
|
50
|
+
ms: number;
|
|
51
|
+
}): Action<D, R>;
|
|
52
|
+
export declare function withGuard<D = any, R = any>(predicate: (data: any) => boolean, action: Action<D, R>, opts?: {
|
|
53
|
+
otherwise?: Action<D, any>;
|
|
54
|
+
}): Action<D, R | D>;
|
package/dist/hoa.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.withGuard = exports.withTimeout = exports.ActionTimeoutError = exports.withFallback = exports.withRetry = exports.backoffDelay = exports.defineHoa = exports.innermostAction = exports.getHoaMeta = exports.HOA = void 0;
|
|
4
|
+
exports.HOA = Symbol.for('codeinkit.flows.hoa');
|
|
5
|
+
function getHoaMeta(fn) {
|
|
6
|
+
if (typeof fn !== 'function')
|
|
7
|
+
return undefined;
|
|
8
|
+
return fn[exports.HOA];
|
|
9
|
+
}
|
|
10
|
+
exports.getHoaMeta = getHoaMeta;
|
|
11
|
+
function innermostAction(fn) {
|
|
12
|
+
let current = fn;
|
|
13
|
+
for (;;) {
|
|
14
|
+
const meta = getHoaMeta(current);
|
|
15
|
+
if (!meta || !meta.inner.length)
|
|
16
|
+
return current;
|
|
17
|
+
current = meta.inner[0];
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
exports.innermostAction = innermostAction;
|
|
21
|
+
function defineHoa(fn, meta) {
|
|
22
|
+
const names = meta.inner.map((a) => (a && a.name) || 'anonymous').join(', ');
|
|
23
|
+
Object.defineProperty(fn, 'name', { value: `${meta.wrapper}(${names})`, configurable: true });
|
|
24
|
+
Object.defineProperty(fn, exports.HOA, { value: meta, enumerable: false, configurable: true, writable: false });
|
|
25
|
+
return fn;
|
|
26
|
+
}
|
|
27
|
+
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
|
+
/**
|
|
48
|
+
* Delay in ms to wait after failed attempt number `attempt` (1-based).
|
|
49
|
+
* With jitter (default) this is full jitter: rand() * min(maxBackoffMs, backoffMs * factor^(attempt-1)).
|
|
50
|
+
*/
|
|
51
|
+
function backoffDelay(attempt, opts, rand) {
|
|
52
|
+
const base = opts.backoffMs === undefined ? 100 : opts.backoffMs;
|
|
53
|
+
const factor = opts.factor === undefined ? 2 : opts.factor;
|
|
54
|
+
const max = opts.maxBackoffMs === undefined ? 5000 : opts.maxBackoffMs;
|
|
55
|
+
const capped = Math.min(max, base * Math.pow(factor, attempt - 1));
|
|
56
|
+
return opts.jitter === false ? capped : rand() * capped;
|
|
57
|
+
}
|
|
58
|
+
exports.backoffDelay = backoffDelay;
|
|
59
|
+
function withRetry(action, opts) {
|
|
60
|
+
if (!opts || typeof opts.maxAttempts !== 'number' || !Number.isInteger(opts.maxAttempts) || opts.maxAttempts < 1 || opts.maxAttempts > 10) {
|
|
61
|
+
throw new Error('withRetry: maxAttempts must be an integer between 1 and 10');
|
|
62
|
+
}
|
|
63
|
+
if (opts.idempotent !== true && opts.idempotent !== 'via-key') {
|
|
64
|
+
throw new Error("withRetry: `idempotent` is required (true | 'via-key'); retrying a non-idempotent action can repeat side effects");
|
|
65
|
+
}
|
|
66
|
+
const hoa = async (data, unsafe, ctx) => {
|
|
67
|
+
const clone = cloner(ctx);
|
|
68
|
+
const snapshot = clone(data);
|
|
69
|
+
for (let attempt = 1;; attempt++) {
|
|
70
|
+
const start = now(unsafe);
|
|
71
|
+
try {
|
|
72
|
+
const result = await action(clone(snapshot), unsafe, ctx);
|
|
73
|
+
report(ctx, { wrapper: 'withRetry', inner: action, attempt, outcome: 'success', durationMs: now(unsafe) - start });
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
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))) {
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
await sleep(unsafe, backoffDelay(attempt, opts, () => random(unsafe)));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
return defineHoa(hoa, { wrapper: 'withRetry', inner: [action], options: opts });
|
|
86
|
+
}
|
|
87
|
+
exports.withRetry = withRetry;
|
|
88
|
+
/* ---------- withFallback ---------- */
|
|
89
|
+
function withFallback(primary, fallback, opts = {}) {
|
|
90
|
+
const hoa = async (data, unsafe, ctx) => {
|
|
91
|
+
var _a, _b;
|
|
92
|
+
const clone = cloner(ctx);
|
|
93
|
+
const snapshot = clone(data);
|
|
94
|
+
const start = now(unsafe);
|
|
95
|
+
try {
|
|
96
|
+
const result = await primary(clone(snapshot), unsafe, ctx);
|
|
97
|
+
report(ctx, { wrapper: 'withFallback', inner: primary, attempt: 1, outcome: 'success', durationMs: now(unsafe) - start });
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (opts.fallbackOn && !opts.fallbackOn(error)) {
|
|
102
|
+
report(ctx, { wrapper: 'withFallback', inner: primary, attempt: 1, outcome: 'error', error, durationMs: now(unsafe) - start });
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
report(ctx, { wrapper: 'withFallback', inner: primary, attempt: 1, outcome: 'fallback', error, durationMs: now(unsafe) - start });
|
|
106
|
+
const fbStart = now(unsafe);
|
|
107
|
+
const input = {
|
|
108
|
+
...clone(snapshot),
|
|
109
|
+
fallbackFrom: {
|
|
110
|
+
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',
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
try {
|
|
116
|
+
const result = await fallback(input, unsafe, ctx);
|
|
117
|
+
report(ctx, { wrapper: 'withFallback', inner: fallback, attempt: 1, outcome: 'success', durationMs: now(unsafe) - fbStart });
|
|
118
|
+
return result;
|
|
119
|
+
}
|
|
120
|
+
catch (fbError) {
|
|
121
|
+
report(ctx, { wrapper: 'withFallback', inner: fallback, attempt: 1, outcome: 'error', error: fbError, durationMs: now(unsafe) - fbStart });
|
|
122
|
+
throw fbError;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
return defineHoa(hoa, { wrapper: 'withFallback', inner: [primary, fallback], roles: ['primary', 'fallback'], options: opts });
|
|
127
|
+
}
|
|
128
|
+
exports.withFallback = withFallback;
|
|
129
|
+
/* ---------- withTimeout ---------- */
|
|
130
|
+
class ActionTimeoutError extends Error {
|
|
131
|
+
constructor(action, ms) {
|
|
132
|
+
super(`action ${action} timed out after ${ms}ms`);
|
|
133
|
+
this.code = 'ETIMEOUT';
|
|
134
|
+
Object.setPrototypeOf(this, ActionTimeoutError.prototype);
|
|
135
|
+
this.name = 'ActionTimeoutError';
|
|
136
|
+
this.action = action;
|
|
137
|
+
this.ms = ms;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
exports.ActionTimeoutError = ActionTimeoutError;
|
|
141
|
+
/**
|
|
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.
|
|
144
|
+
*/
|
|
145
|
+
function withTimeout(action, opts) {
|
|
146
|
+
if (!opts || typeof opts.ms !== 'number' || !(opts.ms > 0)) {
|
|
147
|
+
throw new Error('withTimeout: ms must be a number greater than 0');
|
|
148
|
+
}
|
|
149
|
+
const hoa = async (data, unsafe, ctx) => {
|
|
150
|
+
const clone = cloner(ctx);
|
|
151
|
+
const snapshot = clone(data);
|
|
152
|
+
const start = now(unsafe);
|
|
153
|
+
let timer;
|
|
154
|
+
const timeout = new Promise((_, reject) => {
|
|
155
|
+
timer = setTimeout(() => reject(new ActionTimeoutError(action.name, opts.ms)), opts.ms);
|
|
156
|
+
});
|
|
157
|
+
let running;
|
|
158
|
+
try {
|
|
159
|
+
running = Promise.resolve(action(snapshot, unsafe, ctx));
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
running = Promise.reject(e);
|
|
163
|
+
}
|
|
164
|
+
running.catch(() => undefined); // avoid unhandled rejection after a timeout
|
|
165
|
+
try {
|
|
166
|
+
const result = await Promise.race([running, timeout]);
|
|
167
|
+
report(ctx, { wrapper: 'withTimeout', inner: action, attempt: 1, outcome: 'success', durationMs: now(unsafe) - start });
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
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 });
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
if (timer !== undefined)
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
return defineHoa(hoa, { wrapper: 'withTimeout', inner: [action], options: opts });
|
|
181
|
+
}
|
|
182
|
+
exports.withTimeout = withTimeout;
|
|
183
|
+
/* ---------- withGuard ---------- */
|
|
184
|
+
function withGuard(predicate, action, opts = {}) {
|
|
185
|
+
const inner = opts.otherwise ? [action, opts.otherwise] : [action];
|
|
186
|
+
const hoa = async (data, unsafe, ctx) => {
|
|
187
|
+
const clone = cloner(ctx);
|
|
188
|
+
const snapshot = clone(data);
|
|
189
|
+
const start = now(unsafe);
|
|
190
|
+
if (predicate(clone(snapshot))) {
|
|
191
|
+
const result = await action(clone(snapshot), unsafe, ctx);
|
|
192
|
+
report(ctx, { wrapper: 'withGuard', inner: action, attempt: 1, outcome: 'success', durationMs: now(unsafe) - start });
|
|
193
|
+
return result;
|
|
194
|
+
}
|
|
195
|
+
report(ctx, { wrapper: 'withGuard', inner: action, attempt: 1, outcome: 'skipped', durationMs: now(unsafe) - start });
|
|
196
|
+
return opts.otherwise ? opts.otherwise(clone(snapshot), unsafe, ctx) : data;
|
|
197
|
+
};
|
|
198
|
+
return defineHoa(hoa, { wrapper: 'withGuard', inner, roles: opts.otherwise ? ['guarded', 'otherwise'] : ['guarded'], options: opts });
|
|
199
|
+
}
|
|
200
|
+
exports.withGuard = withGuard;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './hoa';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./hoa"), exports);
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codeinkit/flows-hoa",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "Higher-Order Actions (retry, fallback, timeout, guard) for @codeinkit/flows v4",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
|
+
"files": ["dist", "README.md", "LICENSE"],
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc",
|
|
10
|
+
"test": "jest",
|
|
11
|
+
"prepublishOnly": "npm run build && npm test"
|
|
12
|
+
},
|
|
13
|
+
"repository": { "type": "git", "url": "git+https://github.com/amitmtrn/flows-hoa.git" },
|
|
14
|
+
"homepage": "https://github.com/amitmtrn/flows-hoa",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"author": "codinkit dev team <dev@codinkit.com>",
|
|
17
|
+
"peerDependencies": { "@codeinkit/flows": "^4.0.0-alpha.0" },
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@codeinkit/flows": "file:vendor/codeinkit-flows-4.0.0-alpha.0.tgz",
|
|
20
|
+
"@types/jest": "^30.0.0",
|
|
21
|
+
"@types/node": "^12.19.3",
|
|
22
|
+
"jest": "^30.0.0",
|
|
23
|
+
"ts-jest": "^29.4.0",
|
|
24
|
+
"typescript": "^4.9.5"
|
|
25
|
+
}
|
|
26
|
+
}
|