@creejs/commons-retrier 1.0.8 → 2.0.2
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/dist/cjs/index-dev.cjs +1151 -0
- package/dist/cjs/index-dev.cjs.map +1 -0
- package/dist/cjs/index-min.cjs +2 -0
- package/dist/cjs/index-min.cjs.map +1 -0
- package/dist/esm/index-dev.js +1129 -0
- package/dist/esm/index-dev.js.map +1 -0
- package/dist/esm/index-min.js +2 -0
- package/dist/esm/index-min.js.map +1 -0
- package/dist/umd/index.dev.js +1157 -0
- package/dist/umd/index.dev.js.map +1 -0
- package/dist/umd/index.min.js +2 -0
- package/dist/umd/index.min.js.map +1 -0
- package/package.json +8 -10
- package/lib/alway-task.js +0 -44
- package/lib/constants.js +0 -9
- package/lib/event.js +0 -21
- package/lib/index.js +0 -44
- package/lib/policy/factor-increase-policy.js +0 -46
- package/lib/policy/fixed-increase-policy.js +0 -39
- package/lib/policy/fixed-interval-policy.js +0 -38
- package/lib/policy/shuttle-policy.js +0 -50
- package/lib/policy.js +0 -130
- package/lib/retrier-factory.js +0 -191
- package/lib/retrier.js +0 -530
- package/lib/task.js +0 -58
|
@@ -0,0 +1,1151 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var t$1={constructorName:function(t){return t?.constructor?.name},defaults:function(t,...e){if(null==t)throw new TypeError('"target" must not be null or undefined');for(const n of e)if(null!=n)for(const e in n) void 0===t[e]&&(t[e]=n[e]);return t},extend:e$1,extends:e$1,equals:function(t,e){if(t===e)return true;if("function"==typeof t?.equals)return t.equals(e);if("function"==typeof e?.equals)return e.equals(t);return false},isBrowser:n$1,isNode:function(){return !n$1()}};function e$1(t,...e){if(null==t)throw new TypeError('"target" must not be null or undefined');for(const n of e)if(null!=n)for(const e in n)t[e]=n[e];return t}function n$1(){return "undefined"!=typeof window&&"undefined"!=typeof document}var r$1={isNumber:y,isNil:l$1};function u$1(t){return "function"==typeof t}function l$1(t){return null==t}function f$1(t){return !!y(t)&&t>0}function y(t){return null!=t&&"number"==typeof t}function w$1(t){return null!=t&&"function"==typeof t.then}function d$1(t){return null!=t&&"string"==typeof t}var N={assertNumber:E,assertPositive:function(t,e){if(!f$1(t))throw new Error(`${e?'"'+e+'" ':" "}Not Positive: ${t}`)},assertFunction:v$1,assertNotNil:function(t,e){if(l$1(t))throw new Error((e?'"'+e+'" ':" ")+"Should Not Nil")},assertString:b$1};function $(t,e){if(!Array.isArray(t))throw new Error(`${e?e+"":" "}Not Array: type=${typeof t} value=${JSON.stringify(t)}`)}function b$1(t,e){if(!d$1(t))throw new Error(`${e?'"'+e+'" ':" "}Not String: type=${typeof t} value=${JSON.stringify(t)}`)}function E(t,e){if(!y(t))throw new Error(`${e?'"'+e+'" ':" "}Not Number: type=${typeof t} value=${JSON.stringify(t)}`)}function v$1(t,e){if(!u$1(t))throw new Error(`${e?'"'+e+'" ':" "}Not Function: type=${typeof t} value=${JSON.stringify(t)}`)}function S(t,e){if(!w$1(t))throw new Error(`${e?'"'+e+'" ':" "}Not Promise: type=${typeof t} value=${JSON.stringify(t)}`)}var J={defer:A,delay:function(t,e){y(t)?(e=t,t=Promise.resolve()):null==t&&null==e&&(e=1,t=Promise.resolve());null!=t&&S(t),E(e=e??1e3);const n=A(),r=Date.now();return t.then((...t)=>{const o=Date.now()-r;o<e?setTimeout(()=>n.resolve(...t),e-o):n.resolve(...t);}).catch(t=>{const o=Date.now()-r;o<e?setTimeout(()=>n.reject(t),e-o):n.reject(t);}),n.promise},timeout:function(t,e,n){S(t),E(e=e??1);const r=A(e,n),o=Date.now();return t.then((...t)=>{Date.now()-o<=e?r.resolve(...t):r.reject(new Error(n??`Promise Timeout: ${e}ms`));}).catch(t=>{!r.resolved&&!r.rejected&&r.reject(t);}),r.promise},allSettled:B,returnValuePromised:U,series:async function(t){$(t);const e=[];for(const n of t)v$1(n),e.push(await n());return e},seriesAllSettled:async function(t){$(t);const e=[];for(const n of t){v$1(n);try{e.push({ok:!0,result:await n()});}catch(t){e.push({ok:false,result:t});}}return e},parallel:async function(t,e=5){if($(t),E(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>v$1(t));const n=[];if(t.length<=e){const e=await Promise.all(t.map(t=>U(t)));return n.push(...e),n}const r=[];for(const o of t)if(v$1(o),r.push(o),r.length>=e){const t=await Promise.all(r.map(t=>U(t)));n.push(...t),r.length=0;}if(r.length>0&&r.length<e){const t=await Promise.all(r.map(t=>U(t)));n.push(...t);}return n},parallelAllSettled:async function(t,e=5){if($(t),E(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>v$1(t));const n=[];if(t.length<=e){const e=await B(t.map(t=>U(t)));return n.push(...e),n}const r=[];for(const o of t)if(v$1(o),r.push(o),r.length>=e){const t=await B(r.map(t=>U(t)));n.push(...t),r.length=0;}if(r.length>0&&r.length<e){const t=await B(r.map(t=>U(t)));n.push(...t);}return n}};function A(t=-1,e){E(t);const n={};let r;return t>=0&&(n.timerHandler=r=setTimeout(()=>{clearTimeout(r),n.timerCleared=true,n.reject(new Error(e??`Promise Timeout: ${t}ms`));},t),n.timerHandler=r),n.promise=new Promise((t,e)=>{n.resolve=(...e)=>{null!=r&&(clearTimeout(r),n.timerCleared=true),n.resolved=true,t(...e);},n.reject=t=>{null!=r&&(clearTimeout(r),n.timerCleared=true),n.rejected=true,e(t);};}),n.promise.cancel=()=>{null!=r&&(clearTimeout(r),n.timerCleared=true),n.rejected=true,n.canceled=n.promise.canceled=true,n.reject(new Error("Cancelled"));},n}async function B(t){$(t);const e=await Promise.allSettled(t),n=[];for(const t of e)"fulfilled"===t.status&&n.push({ok:true,result:t.value}),"rejected"===t.status&&n.push({ok:false,result:t.reason});return n}function U(t){try{const e=t();return w$1(e)?e:Promise.resolve(e)}catch(t){return Promise.reject(t)}}
|
|
6
|
+
|
|
7
|
+
// module vars
|
|
8
|
+
const DefaultMinInterval = 50;
|
|
9
|
+
const DefaultMaxInterval = 30 * 1000; // 30s
|
|
10
|
+
const DefaultMaxRetries = 3;
|
|
11
|
+
|
|
12
|
+
// internal
|
|
13
|
+
|
|
14
|
+
// module vars
|
|
15
|
+
const { assertPositive: assertPositive$5 } = N;
|
|
16
|
+
const { isNumber } = r$1;
|
|
17
|
+
|
|
18
|
+
class Policy {
|
|
19
|
+
/**
|
|
20
|
+
* Creates a new Policy instance with specified retry bounds.
|
|
21
|
+
*/
|
|
22
|
+
constructor () {
|
|
23
|
+
this._min = DefaultMinInterval;
|
|
24
|
+
this._max = DefaultMaxInterval;
|
|
25
|
+
this._nextInterval = this._min;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Copies settings to target policy.
|
|
30
|
+
* @param {Policy} targetPolicy - The policy to modify.
|
|
31
|
+
*/
|
|
32
|
+
copyPolicySetting (targetPolicy) {
|
|
33
|
+
targetPolicy.range(this._min, this._max);
|
|
34
|
+
targetPolicy._nextInterval = this._nextInterval;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Sets a fixed interval retry policy.
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Sets the minimum and maximum intervals for retries.
|
|
43
|
+
* @param {number} min - Minimum delay in milliseconds (must be positive and less than max)
|
|
44
|
+
* @param {number} max - Maximum delay in milliseconds (must be positive and greater than min)
|
|
45
|
+
* @returns {this} Returns the Retrier instance for chaining
|
|
46
|
+
* @throws {Error} If min is not less than max or if values are not positive
|
|
47
|
+
*/
|
|
48
|
+
range (min, max) {
|
|
49
|
+
assertPositive$5(min, 'min');
|
|
50
|
+
assertPositive$5(max, 'max');
|
|
51
|
+
if (min >= max) {
|
|
52
|
+
throw new Error('min must < max')
|
|
53
|
+
}
|
|
54
|
+
this._min = min;
|
|
55
|
+
if (this._nextInterval < this._min) {
|
|
56
|
+
this._nextInterval = this._min;
|
|
57
|
+
}
|
|
58
|
+
this._max = max;
|
|
59
|
+
if (this._nextInterval > this._max) {
|
|
60
|
+
this._nextInterval = this._max;
|
|
61
|
+
}
|
|
62
|
+
return this
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Sets the minimum retry delay in milliseconds.
|
|
67
|
+
* 1. will change currentInterval to min
|
|
68
|
+
* @param {number} min - The minimum delay (must be positive and less than max).
|
|
69
|
+
* @returns {this} The retrier instance for chaining.
|
|
70
|
+
* @throws {Error} If min is not positive or is greater than/equal to max.
|
|
71
|
+
*/
|
|
72
|
+
min (min) {
|
|
73
|
+
assertPositive$5(min, 'min');
|
|
74
|
+
if (min >= this._max) {
|
|
75
|
+
throw new Error('min must < max')
|
|
76
|
+
}
|
|
77
|
+
this._min = min;
|
|
78
|
+
this._nextInterval = this._min;
|
|
79
|
+
return this
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Sets the maximum retry retry delay in milliseconds.
|
|
84
|
+
* @param {number} max - The maximum delay (must be positive and greater than min).
|
|
85
|
+
* @throws {Error} If max is not greater than min.
|
|
86
|
+
* @returns {this} The retrier instance for chaining.
|
|
87
|
+
*/
|
|
88
|
+
max (max) {
|
|
89
|
+
assertPositive$5(max, 'max');
|
|
90
|
+
if (max <= this._min) {
|
|
91
|
+
throw new Error('max must > min')
|
|
92
|
+
}
|
|
93
|
+
this._max = max;
|
|
94
|
+
if (this._nextInterval > this._max) {
|
|
95
|
+
this._nextInterval = this._max;
|
|
96
|
+
}
|
|
97
|
+
return this
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
reset () {
|
|
101
|
+
this._nextInterval = this._min;
|
|
102
|
+
return this
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Interval ms of next execution
|
|
107
|
+
* @returns {number}
|
|
108
|
+
* @throws {Error} Always throws "Not Implemented Yet" error.
|
|
109
|
+
*/
|
|
110
|
+
generate () {
|
|
111
|
+
const rtnVal = this._nextInterval;
|
|
112
|
+
this._increase();
|
|
113
|
+
return rtnVal
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
_increase () {
|
|
117
|
+
const nextInterval = this._next();
|
|
118
|
+
if (!isNumber(nextInterval)) {
|
|
119
|
+
throw new Error('Generated Next Interval Not Number')
|
|
120
|
+
}
|
|
121
|
+
if (nextInterval < this._min) {
|
|
122
|
+
return (this._nextInterval = this._min)
|
|
123
|
+
} else if (nextInterval > this._max) {
|
|
124
|
+
return (this._nextInterval = this._max)
|
|
125
|
+
}
|
|
126
|
+
return (this._nextInterval = nextInterval)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* subclass should implement this method
|
|
131
|
+
* @returns {number} The interval in milliseconds to wait before the next retry attempt.
|
|
132
|
+
* @protected
|
|
133
|
+
*/
|
|
134
|
+
_next () {
|
|
135
|
+
throw new Error('Not Impled Yet')
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
var e={isFunction:t,isNil:s};function t(e){return "function"==typeof e}function s(e){return null==e}function n(e){return null!=e&&"string"==typeof e}var r={assertNumber:function(e,t){if(!function(e){return null!=e&&"number"==typeof e}(e))throw new Error(`${t?'"'+t+'" ':" "}Not Number: type=${typeof e} value=${JSON.stringify(e)}`)},assertFunction:function(e,s){if(!t(e))throw new Error(`${s?'"'+s+'" ':" "}Not Function: type=${typeof e} value=${JSON.stringify(e)}`)},assertNotNil:function(e,t){if(s(e))throw new Error((t?'"'+t+'" ':" ")+"Should Not Nil")},assertString:function(e,t){if(!n(e))throw new Error(`${t?'"'+t+'" ':" "}Not String: type=${typeof e} value=${JSON.stringify(e)}`)},assertStringOrSymbol:function(e,t){if(!n(e)&&!function(e){return null!=e&&"symbol"==typeof e}(e))throw new Error(`${t?'"'+t+'" ':" "}Not String or Symbol: type=${typeof e} value=${JSON.stringify(e)}`)}};const i="DOwner$#$",{assertFunction:l,assertNotNil:a}=r;class o{constructor(e,t,s=false){a(e,"event"),l(t,"callback"),this._event=e,this._callback=t,this._isOnce=!!s,this._owner=void 0;}set owner(e){this._owner=e;}get owner(){return this._owner===i?void 0:this._owner}get event(){return this._event}get isOnce(){return this._isOnce}isSameCallback(e){return this._callback===e}get callback(){return this._callback}invoke(...e){try{return this._callback(...e)}finally{if(this._isOnce)try{this._event._remove(this);}catch(e){console.warn(e);}}}listener(...e){return this.invoke(...e)}}const{isFunction:c,isNil:h}=e,{assertStringOrSymbol:u,assertFunction:_}=r;class f{static get DefaultOwner(){return i}constructor(e){u(e,"eventName"),this._name=e,this._callbacks=new Set,this._listeners=[],this._callback2Listeners=new Map,this._listener2Owner=new Map,this._owner2Listeners=new Map;}get name(){return this._name}isEmpty(){return 0===this._callbacks.size}rawListeners(){return [...this._listeners]}listenerCount(e){return null==e?this._listeners.length:this._callback2Listeners.get(e)?.size??0}callbacks(){return [...this.rawListeners().map(e=>e.callback)]}emit(...e){if(0===this._listeners.length)return false;for(const t of [...this._listeners])t.invoke(...e);return true}hasListener(e){return !!c(e)&&this._callbacks.has(e)}hasOwner(e){return !h(e)&&this._owner2Listeners.has(e)}addListener(e,t){return this._addListener(e,t,false,false)}prependListener(e,t){return this._addListener(e,t,false,true)}addOnceListener(e,t){return this._addListener(e,t,true,false)}prependOnceListener(e,t){return this._addListener(e,t,true,true)}_addListener(e,t,s,n){if(h(e))return false;_(e),this._callbacks.has(e)||this._callbacks.add(e),t=t??i;const r=new o(this,e,s);r.owner=t,n?this._listeners.unshift(r):this._listeners.push(r),this._listener2Owner.set(r,t);let l=this._callback2Listeners.get(e);null==l&&(l=new Set,this._callback2Listeners.set(e,l)),l.add(r);let a=this._owner2Listeners.get(t);return null==a&&(a=new Set,this._owner2Listeners.set(t,a)),a.add(r),true}removeListener(e){if(h(e))return false;if(!this._callbacks.has(e))return false;this._callbacks.delete(e);const t=this._callback2Listeners.get(e);if(null==t)return false;this._callback2Listeners.delete(e);for(const e of t){ -1!==this._listeners.indexOf(e)&&this._listeners.splice(this._listeners.indexOf(e),1);const t=this._listener2Owner.get(e);if(null==t)continue;this._listener2Owner.delete(e);const s=this._owner2Listeners.get(t);null!=s&&(s.delete(e),0===s.size&&this._owner2Listeners.delete(t));}return true}_remove(e){const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1);const{callback:s}=e,n=this._callback2Listeners.get(s);null!=n&&(n.delete(e),0===n.size&&(this._callback2Listeners.delete(s),this._callbacks.delete(s)));const r=this._listener2Owner.get(e);if(null==r)return;this._listener2Owner.delete(e);const i=this._owner2Listeners.get(r);null!=i&&(i.delete(e),0===i.size&&this._owner2Listeners.delete(r));}removeAllListeners(e){if(h(e))return this._callbacks.clear(),this._listeners.length=0,this._callback2Listeners.clear(),this._listener2Owner.clear(),this._owner2Listeners.clear(),this;const t=this._owner2Listeners.get(e);if(null==t)return this;this._owner2Listeners.delete(e);for(const e of t){ -1!==this._listeners.indexOf(e)&&this._listeners.splice(this._listeners.indexOf(e),1),this._listener2Owner.delete(e);const{callback:t}=e,s=this._callback2Listeners.get(t);null!=s&&(s.delete(e),0===s.size&&(this._callback2Listeners.delete(t),this._callbacks.delete(t)));}return this}}const{isNil:m}=e,{assertString:d,assertFunction:L,assertNumber:w,assertStringOrSymbol:v,assertNotNil:g}=r,p=["on","once","addListener","prependListener","prependOnceListener","off","offAll","offOwner","removeAllListeners","removeListener","emit","setMaxListeners","getMaxListeners","hasOwner","listeners","listenerCount","eventNames","rawListeners"];let b=10;class O{static mixin(e){const t=new O;e.__emitter=t;for(const s of p){const n=t[s];e[s]=n.bind(t);}return e}static get defaultMaxListeners(){return b}static set defaultMaxListeners(e){w(e),b=e??10;}constructor(){this._name2Event=new Map,this._maxListeners=b;}addListener(e,t,s){return this.on(e,t,s)}prependListener(e,t,s){d(e),L(t),this._checkMaxListeners(e);return this._getOrCreateEvent(e).prependListener(t,s),this}prependOnceListener(e,t,s){d(e),L(t),this._checkMaxListeners(e);return this._getOrCreateEvent(e).prependOnceListener(t,s),this}emit(e,...t){const s=this._name2Event.get(e);return null!=s&&!s.isEmpty()&&(s.emit(...t),true)}eventNames(){return [...this._name2Event.keys()]}getMaxListeners(){return this._maxListeners}listenerCount(e,t){v(e,"eventName");const s=this._name2Event.get(e);return null==s||s.isEmpty()?0:s.listenerCount(t)}listeners(e){v(e,"eventName");const t=this._name2Event.get(e);return null==t||t.isEmpty()?[]:t.callbacks()}off(e,t){const s=this._name2Event.get(e);return null==s?this:(s.removeListener(t),s.isEmpty()?(this._name2Event.delete(e),this):this)}offAll(e,t){v(e,"eventName");const s=this._name2Event.get(e);return null==s?this:(s.removeAllListeners(t),s.isEmpty()?(this._name2Event.delete(e),this):this)}offOwner(e){g(e,"owner");const t=[...this._name2Event.values()];for(const s of t)s.removeAllListeners(e),s.isEmpty()&&this._name2Event.delete(s.name);return this}on(e,t,s){d(e),L(t),this._checkMaxListeners(e);return this._getOrCreateEvent(e).addListener(t,s),this}_checkMaxListeners(e){let t=0;0!==this._maxListeners&&this._maxListeners!==1/0&&(t=this.listenerCount(e))>=this._maxListeners&&console.warn(`maxlistenersexceededwarning: Possible EventEmitter memory leak detected. ${t} ${e} listeners added to [${this}]. Use emitter.setMaxListeners() to increase limit`);}once(e,t,s){d(e),L(t);return this._getOrCreateEvent(e).addOnceListener(t,s),this}rawListeners(e){return this._name2Event.get(e)?.rawListeners()||[]}removeAllListeners(e,t){return this.offAll(e,t)}removeListener(e,t){return this.off(e,t)}setMaxListeners(e){if(w(e),e<0)throw new RangeError("maxListeners must >=0");return this._maxListeners=e,this}_getOrCreateEvent(e){if(this._name2Event.has(e))return this._name2Event.get(e);const t=new f(e);return this._name2Event.set(e,t),t}hasOwner(e){if(m(e))return false;for(const t of this._name2Event.values())if(t.hasOwner(e))return true;return false}}
|
|
140
|
+
|
|
141
|
+
const Start = 'start'; // retry started
|
|
142
|
+
const Stop = 'stop'; // retry stopped
|
|
143
|
+
const Retry = 'retry'; // one retry began
|
|
144
|
+
const Success = 'success'; // one task running succeeded
|
|
145
|
+
const Failure = 'failure'; // one task ran failed
|
|
146
|
+
const Timeout = 'timeout'; // total timeout
|
|
147
|
+
const TaskTimeout = 'task-timeout'; // one task timed out
|
|
148
|
+
const Completed = 'complete'; // all retries completed
|
|
149
|
+
const MaxRetries = 'max-retries'; // Reach the max retries
|
|
150
|
+
|
|
151
|
+
var Event = {
|
|
152
|
+
Start,
|
|
153
|
+
Retry,
|
|
154
|
+
Success,
|
|
155
|
+
Failure,
|
|
156
|
+
Timeout,
|
|
157
|
+
TaskTimeout,
|
|
158
|
+
Stop,
|
|
159
|
+
Completed,
|
|
160
|
+
MaxRetries
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
// 3rd
|
|
164
|
+
// internal
|
|
165
|
+
// module vars
|
|
166
|
+
const { assertPositive: assertPositive$4 } = N;
|
|
167
|
+
class FixedIntervalPolicy extends Policy {
|
|
168
|
+
/**
|
|
169
|
+
* Creates a fixed interval retry policy with the specified interval.
|
|
170
|
+
* @param {number} interval - The fixed interval (in milliseconds) between retry attempts.
|
|
171
|
+
*/
|
|
172
|
+
constructor (interval) {
|
|
173
|
+
super();
|
|
174
|
+
assertPositive$4(interval, 'interval');
|
|
175
|
+
this._interval = interval;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
set interval (interval) {
|
|
179
|
+
assertPositive$4(interval, 'interval');
|
|
180
|
+
this._interval = interval;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
get interval () {
|
|
184
|
+
return this._interval
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Interval ms of next execution
|
|
189
|
+
* @returns {number}
|
|
190
|
+
* @throws {Error} Always throws "Not Implemented Yet" error.
|
|
191
|
+
*/
|
|
192
|
+
_next () {
|
|
193
|
+
return this.interval
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// 3rd
|
|
198
|
+
// internal
|
|
199
|
+
// module vars
|
|
200
|
+
const { assertPositive: assertPositive$3 } = N;
|
|
201
|
+
class FixedIncreasePolicy extends Policy {
|
|
202
|
+
/**
|
|
203
|
+
* each call to _next() increases the interval by "increasement".
|
|
204
|
+
* @param {number} increasement - The fixed interval (in milliseconds) between retry attempts.
|
|
205
|
+
*/
|
|
206
|
+
constructor (increasement) {
|
|
207
|
+
super();
|
|
208
|
+
assertPositive$3(increasement, 'increasement');
|
|
209
|
+
this._increasement = increasement;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
set increasement (increasement) {
|
|
213
|
+
assertPositive$3(increasement, 'increasement');
|
|
214
|
+
this._increasement = increasement;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
get increasement () {
|
|
218
|
+
return this._increasement
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Interval ms of next execution
|
|
223
|
+
* @returns {number}
|
|
224
|
+
*/
|
|
225
|
+
_next () {
|
|
226
|
+
if (this._nextInterval >= this._max) {
|
|
227
|
+
return this._max
|
|
228
|
+
}
|
|
229
|
+
return this._nextInterval + this.increasement
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 3rd
|
|
234
|
+
// internal
|
|
235
|
+
// module vars
|
|
236
|
+
const { assertPositive: assertPositive$2 } = N;
|
|
237
|
+
|
|
238
|
+
class FactoreIncreasePolicy extends Policy {
|
|
239
|
+
/**
|
|
240
|
+
* each call to _next() increases the interval by lastInterval * factor
|
|
241
|
+
* @param {number} factor - the increasement factor, >= 1
|
|
242
|
+
*/
|
|
243
|
+
constructor (factor) {
|
|
244
|
+
super();
|
|
245
|
+
assertPositive$2(factor, 'factor');
|
|
246
|
+
if (factor < 1) {
|
|
247
|
+
throw new Error('factor must be >= 1')
|
|
248
|
+
}
|
|
249
|
+
this._factor = factor;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
set factor (factor) {
|
|
253
|
+
assertPositive$2(factor, 'factor');
|
|
254
|
+
if (factor < 1) {
|
|
255
|
+
throw new Error('factor must be >= 1')
|
|
256
|
+
}
|
|
257
|
+
this._factor = factor;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
get factor () {
|
|
261
|
+
return this._factor
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Interval ms of next execution
|
|
266
|
+
* @returns {number}
|
|
267
|
+
*/
|
|
268
|
+
_next () {
|
|
269
|
+
if (this._nextInterval >= this._max) {
|
|
270
|
+
return this._max
|
|
271
|
+
}
|
|
272
|
+
return this._nextInterval * this.factor
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// 3rd
|
|
277
|
+
// internal
|
|
278
|
+
// module vars
|
|
279
|
+
const { assertPositive: assertPositive$1 } = N;
|
|
280
|
+
|
|
281
|
+
class ShuttlePolicy extends Policy {
|
|
282
|
+
/**
|
|
283
|
+
* the inteval value shuttles between min and max
|
|
284
|
+
* @param {number} stepLength - the step length to change
|
|
285
|
+
*/
|
|
286
|
+
constructor (stepLength) {
|
|
287
|
+
super();
|
|
288
|
+
assertPositive$1(stepLength, 'stepLength');
|
|
289
|
+
this._stepLength = stepLength;
|
|
290
|
+
this.increasement = stepLength;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
set stepLength (stepLength) {
|
|
294
|
+
assertPositive$1(stepLength, 'stepLength');
|
|
295
|
+
this._stepLength = stepLength;
|
|
296
|
+
this.increasement = stepLength;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
get stepLength () {
|
|
300
|
+
return this._stepLength
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Interval ms of next execution
|
|
305
|
+
* @returns {number}
|
|
306
|
+
* @throws {Error} Always throws "Not Implemented Yet" error.
|
|
307
|
+
*/
|
|
308
|
+
_next () {
|
|
309
|
+
const nextInterval = this._nextInterval + this.increasement;
|
|
310
|
+
if (nextInterval >= this._max) {
|
|
311
|
+
this.increasement = -this.stepLength;
|
|
312
|
+
return this._max
|
|
313
|
+
} else if (nextInterval <= this._min) {
|
|
314
|
+
this.increasement = this.stepLength;
|
|
315
|
+
return this._min
|
|
316
|
+
}
|
|
317
|
+
return nextInterval
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// owned
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* @typedef {import('./retrier.js').default} Retrier
|
|
325
|
+
*/
|
|
326
|
+
|
|
327
|
+
// module vars
|
|
328
|
+
const { assertNotNil, assertFunction: assertFunction$1 } = N;
|
|
329
|
+
class Task {
|
|
330
|
+
/**
|
|
331
|
+
* Creates a new Task instance.
|
|
332
|
+
* @param {Retrier} retrier - The retrier instance.
|
|
333
|
+
* @param {Function} task - The function to be executed as the task.
|
|
334
|
+
*/
|
|
335
|
+
constructor (retrier, task) {
|
|
336
|
+
assertNotNil(retrier, 'retrier');
|
|
337
|
+
assertFunction$1(task, 'task');
|
|
338
|
+
this.retrier = retrier;
|
|
339
|
+
this.task = task;
|
|
340
|
+
this.result = undefined;
|
|
341
|
+
this.error = undefined;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
get failed () {
|
|
345
|
+
return this.error != null
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
get succeeded () {
|
|
349
|
+
return this.error == null
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Executes the task with the given retry parameters.
|
|
354
|
+
* 1. if execution throw error, keep error in this.error
|
|
355
|
+
* 2. if execution return value, keep it in this.result
|
|
356
|
+
* 3. always return Promise<void>
|
|
357
|
+
* @param {number} retries - The number of retries attempted so far.
|
|
358
|
+
* @param {number} latence - The current latency ms.
|
|
359
|
+
* @param {number} nextInterval - The next interval ms.
|
|
360
|
+
* @returns {Promise<void>} The result of the task execution.
|
|
361
|
+
*/
|
|
362
|
+
async execute (retries, latence, nextInterval) {
|
|
363
|
+
try {
|
|
364
|
+
this.result = await this.task(retries, latence, nextInterval);
|
|
365
|
+
this.error = undefined;
|
|
366
|
+
} catch (e) {
|
|
367
|
+
this.error = e;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
dispose () {
|
|
372
|
+
// @ts-ignore
|
|
373
|
+
this.retrier = undefined;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// owned
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* @typedef {import('./retrier.js').default} Retrier
|
|
381
|
+
*/
|
|
382
|
+
|
|
383
|
+
class AlwaysTask extends Task {
|
|
384
|
+
/**
|
|
385
|
+
* Checks if the given task is an instance of AlwaysTask.
|
|
386
|
+
* @param {*} task - The task to check.
|
|
387
|
+
* @returns {boolean} True if the task is an instance of AlwaysTask, false otherwise.
|
|
388
|
+
*/
|
|
389
|
+
static isAlwaysTask (task) {
|
|
390
|
+
return task instanceof AlwaysTask
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Creates an AlwaysTask instance.
|
|
395
|
+
* @param {Retrier} retrier - The retrier instance to use for retry logic
|
|
396
|
+
* @param {Function} task - The task function to execute
|
|
397
|
+
* @param {boolean} resetRetryPolicyAfterSuccess - Whether to reset retry policy after successful execution
|
|
398
|
+
*/
|
|
399
|
+
constructor (retrier, task, resetRetryPolicyAfterSuccess) {
|
|
400
|
+
super(retrier, task);
|
|
401
|
+
this.resetPolicy = resetRetryPolicyAfterSuccess;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Executes the task with the given retry parameters.
|
|
406
|
+
* @param {number} retries - The number of retries attempted so far.
|
|
407
|
+
* @param {number} latence - The current latency ms.
|
|
408
|
+
* @param {number} nextInterval - The next interval ms.
|
|
409
|
+
* @returns {Promise<*>} The result of the task execution.
|
|
410
|
+
*/
|
|
411
|
+
async execute (retries, latence, nextInterval) {
|
|
412
|
+
await super.execute(retries, latence, nextInterval);
|
|
413
|
+
if (this.succeeded && this.resetPolicy) {
|
|
414
|
+
this.retrier.resetRetryPolicy();
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// internal
|
|
420
|
+
|
|
421
|
+
// module vars
|
|
422
|
+
const { assertPositive, assertString, assertFunction, assertNumber } = N;
|
|
423
|
+
const { isNil } = r$1;
|
|
424
|
+
const TaskTimoutFlag = '!#@%$&^*';
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* @extends EventEmitter
|
|
428
|
+
*/
|
|
429
|
+
class Retrier {
|
|
430
|
+
/**
|
|
431
|
+
* Creates a new Retrier instance with a fixed interval policy.
|
|
432
|
+
* @param {number} [fixedInterval=1000] - The fixed interval in milliseconds between retry attempts. Defaults to 1000ms if not provided.
|
|
433
|
+
*/
|
|
434
|
+
constructor (fixedInterval) {
|
|
435
|
+
O.mixin(this);
|
|
436
|
+
/**
|
|
437
|
+
* @type {Policy}
|
|
438
|
+
*/
|
|
439
|
+
this._policy = new FixedIntervalPolicy(fixedInterval ?? 1000);
|
|
440
|
+
this._maxRetries = DefaultMaxRetries;
|
|
441
|
+
this._currentRetries = 1;
|
|
442
|
+
/**
|
|
443
|
+
* Timetou for total operation
|
|
444
|
+
* @type {number}
|
|
445
|
+
*/
|
|
446
|
+
this._timeout = 120000; // 120s
|
|
447
|
+
/**
|
|
448
|
+
* Timetou for single task
|
|
449
|
+
*/
|
|
450
|
+
this._taskTimeout = 2000; // 20s
|
|
451
|
+
this._name = 'unamed'; // Retrier name
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* A Deferred Object as Singal to prevent Task concurrent start
|
|
455
|
+
* @type {{resolve:Function, reject:Function, promise: Promise<*>}|undefined}
|
|
456
|
+
*/
|
|
457
|
+
this._taskingFlag = undefined;
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* A Deferred Object as Singal to prevent Task concurrent stop
|
|
461
|
+
* @type {{resolve:Function, reject:Function, promise: Promise<*>}|undefined}
|
|
462
|
+
*/
|
|
463
|
+
this._breakFlag = undefined;
|
|
464
|
+
/**
|
|
465
|
+
* Reason for break
|
|
466
|
+
* @type {Error|undefined}
|
|
467
|
+
*/
|
|
468
|
+
this._breakReason = undefined;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
get running () {
|
|
472
|
+
return !isNil(this._taskingFlag)
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Sets the name of the retrier.
|
|
477
|
+
* @param {string} retrierName - The name to assign to the retrier.
|
|
478
|
+
* @returns {this} The retrier instance for chaining.
|
|
479
|
+
*/
|
|
480
|
+
name (retrierName) {
|
|
481
|
+
assertString(retrierName, 'retrierName');
|
|
482
|
+
this._name = retrierName;
|
|
483
|
+
return this
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* Sets the retry attempts to be infinite by setting max retries to maximum safe integer.
|
|
488
|
+
* @returns {Object} The retrier instance for chaining.
|
|
489
|
+
*/
|
|
490
|
+
infinite () {
|
|
491
|
+
this._maxRetries = Infinity;
|
|
492
|
+
return this
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* Sets the maximum number of retry attempts.
|
|
497
|
+
* @param {number} times - The maximum number of retries.
|
|
498
|
+
* @returns {this} The Retrier instance for chaining.
|
|
499
|
+
*/
|
|
500
|
+
times (times) {
|
|
501
|
+
return this.maxRetries(times)
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Sets the maximum number of retry attempts.
|
|
506
|
+
* @param {number} maxRetries - The maximum number of retries (must be positive).
|
|
507
|
+
* @returns {this} The retrier instance for chaining.
|
|
508
|
+
*/
|
|
509
|
+
maxRetries (maxRetries) {
|
|
510
|
+
assertPositive(maxRetries, 'maxRetries');
|
|
511
|
+
this._maxRetries = maxRetries;
|
|
512
|
+
return this
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Sets the minimum retry delay in milliseconds.
|
|
517
|
+
* @param {number} min - The minimum delay (must be positive and less than max).
|
|
518
|
+
* @returns {this} The retrier instance for chaining.
|
|
519
|
+
* @throws {Error} If min is not positive or is greater than/equal to max.
|
|
520
|
+
*/
|
|
521
|
+
min (min) {
|
|
522
|
+
this._policy.min(min);
|
|
523
|
+
return this
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Sets the maximum retry retry delay in milliseconds.
|
|
528
|
+
* @param {number} max - The maximum delay (must be positive and greater than min).
|
|
529
|
+
* @throws {Error} If max is not greater than min.
|
|
530
|
+
* @returns {this} The retrier instance for chaining.
|
|
531
|
+
*/
|
|
532
|
+
max (max) {
|
|
533
|
+
this._policy.max(max);
|
|
534
|
+
return this
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Sets the minimum and maximum intervals for retries.
|
|
539
|
+
* @param {number} min - Minimum delay in milliseconds (must be positive and less than max)
|
|
540
|
+
* @param {number} max - Maximum delay in milliseconds (must be positive and greater than min)
|
|
541
|
+
* @returns {Retrier} Returns the Retrier instance for chaining
|
|
542
|
+
* @throws {Error} If min is not less than max or if values are not positive
|
|
543
|
+
*/
|
|
544
|
+
range (min, max) {
|
|
545
|
+
this._policy.range(min, max);
|
|
546
|
+
return this
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Sets a fixed interval retry policy.
|
|
551
|
+
* @param {number} fixedInterval - The fixed interval in milliseconds between retries.
|
|
552
|
+
* @returns {Retrier} The Retrier instance for chaining.
|
|
553
|
+
*/
|
|
554
|
+
fixedInterval (fixedInterval) {
|
|
555
|
+
const oldPolicy = this._policy;
|
|
556
|
+
if (oldPolicy instanceof FixedIntervalPolicy) {
|
|
557
|
+
oldPolicy.interval = fixedInterval;
|
|
558
|
+
return this
|
|
559
|
+
}
|
|
560
|
+
const newPolicy = new FixedIntervalPolicy(fixedInterval);
|
|
561
|
+
oldPolicy?.copyPolicySetting(newPolicy);
|
|
562
|
+
newPolicy.reset();
|
|
563
|
+
this._policy = newPolicy;
|
|
564
|
+
return this
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* Sets a fixed increase policy for retry intervals.
|
|
569
|
+
* @param {number} increasement - The fixed amount to increase the interval by on each retry.
|
|
570
|
+
* @returns {this} The retrier instance for chaining.
|
|
571
|
+
*/
|
|
572
|
+
fixedIncrease (increasement) {
|
|
573
|
+
const oldPolicy = this._policy;
|
|
574
|
+
if (oldPolicy instanceof FixedIncreasePolicy) {
|
|
575
|
+
oldPolicy.increasement = increasement;
|
|
576
|
+
return this
|
|
577
|
+
}
|
|
578
|
+
const newPolicy = new FixedIncreasePolicy(increasement);
|
|
579
|
+
oldPolicy?.copyPolicySetting(newPolicy);
|
|
580
|
+
newPolicy.reset();
|
|
581
|
+
this._policy = newPolicy;
|
|
582
|
+
return this
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Sets a fixed increase factor for retry delays.
|
|
587
|
+
* @param {number} factor - The multiplier for delay increase between retries.
|
|
588
|
+
* @returns {this} The retrier instance for method chaining.
|
|
589
|
+
*/
|
|
590
|
+
factorIncrease (factor) {
|
|
591
|
+
const oldPolicy = this._policy;
|
|
592
|
+
if (oldPolicy instanceof FactoreIncreasePolicy) {
|
|
593
|
+
oldPolicy.factor = factor;
|
|
594
|
+
return this
|
|
595
|
+
}
|
|
596
|
+
const newPolicy = new FactoreIncreasePolicy(factor);
|
|
597
|
+
oldPolicy?.copyPolicySetting(newPolicy);
|
|
598
|
+
newPolicy.reset();
|
|
599
|
+
this._policy = newPolicy;
|
|
600
|
+
return this
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* Sets a shuttle retry policy with the given step length.
|
|
605
|
+
* @param {number} stepLength - The interval between retry attempts.
|
|
606
|
+
* @returns {this} The Retrier instance for chaining.
|
|
607
|
+
*/
|
|
608
|
+
shuttleInterval (stepLength) {
|
|
609
|
+
const oldPolicy = this._policy;
|
|
610
|
+
if (oldPolicy instanceof ShuttlePolicy) {
|
|
611
|
+
oldPolicy.stepLength = stepLength;
|
|
612
|
+
return this
|
|
613
|
+
}
|
|
614
|
+
const newPolicy = new ShuttlePolicy(stepLength);
|
|
615
|
+
oldPolicy?.copyPolicySetting(newPolicy);
|
|
616
|
+
newPolicy.reset();
|
|
617
|
+
this._policy = newPolicy;
|
|
618
|
+
return this
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Sets the timeout duration for each Task execution.
|
|
623
|
+
* 1. must > 0
|
|
624
|
+
* @param {number} timeout - The timeout duration in milliseconds.
|
|
625
|
+
* @returns {Object} The retrier instance for chaining.
|
|
626
|
+
*/
|
|
627
|
+
taskTimeout (timeout) {
|
|
628
|
+
assertPositive(timeout, 'timeout');
|
|
629
|
+
this._taskTimeout = timeout;
|
|
630
|
+
return this
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Sets the timeout duration for all retries.
|
|
635
|
+
* 1. <= 0 - no timeout
|
|
636
|
+
* 2. \> 0 - timeout duration in milliseconds
|
|
637
|
+
* @param {number} timeout - The timeout duration in milliseconds.
|
|
638
|
+
* @returns {Object} The retrier instance for chaining.
|
|
639
|
+
*/
|
|
640
|
+
timeout (timeout) {
|
|
641
|
+
assertNumber(timeout, 'timeout');
|
|
642
|
+
this._timeout = timeout;
|
|
643
|
+
return this
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Sets the task function to be retried.
|
|
648
|
+
* @param {Function} task - The function to be executed and retried on failure.
|
|
649
|
+
* @returns {this} Returns the retrier instance for chaining.
|
|
650
|
+
*/
|
|
651
|
+
task (task) {
|
|
652
|
+
assertFunction(task, 'task');
|
|
653
|
+
this._task = new Task(this, task);
|
|
654
|
+
return this
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* alias of {@linkcode Retrier.task()}
|
|
659
|
+
* @param {Function} task - The function to be executed and retried
|
|
660
|
+
* @return {this}
|
|
661
|
+
*/
|
|
662
|
+
retry (task) {
|
|
663
|
+
this.task(task);
|
|
664
|
+
return this
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* Executes the given task, and never stop
|
|
669
|
+
* 1. if the task fails, will retry it after the interval generated by RetryPolicy
|
|
670
|
+
* 2. if the task succeeds, reset RetryPolicy to Minimum Interval and continue to run the task
|
|
671
|
+
* @param {Function} task - The async function to execute and retry.
|
|
672
|
+
* @param {boolean} [resetAfterSuccess=false] - Whether to reset retry counters after success.
|
|
673
|
+
* @returns {this} The Retrier instance for chaining.
|
|
674
|
+
*/
|
|
675
|
+
always (task, resetAfterSuccess = false) {
|
|
676
|
+
this._task = new AlwaysTask(this, task, resetAfterSuccess);
|
|
677
|
+
return this
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* Starts the retry process.
|
|
682
|
+
* @returns {Promise<*>}
|
|
683
|
+
*/
|
|
684
|
+
async start () {
|
|
685
|
+
if (this._task == null) {
|
|
686
|
+
throw new Error('No Task to Retry')
|
|
687
|
+
}
|
|
688
|
+
if (this._taskingFlag != null) {
|
|
689
|
+
return this._taskingFlag.promise
|
|
690
|
+
}
|
|
691
|
+
const startAt = Date.now();
|
|
692
|
+
let lastError = null;
|
|
693
|
+
// @ts-ignore
|
|
694
|
+
this.emit(Event.Start, startAt);
|
|
695
|
+
this._taskingFlag = J.defer();
|
|
696
|
+
let latency = null;
|
|
697
|
+
while (true) {
|
|
698
|
+
// need to stop?
|
|
699
|
+
if (this._breakFlag != null) {
|
|
700
|
+
this._taskingFlag.reject(this._breakReason);
|
|
701
|
+
break
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
latency = Date.now() - startAt;
|
|
705
|
+
|
|
706
|
+
// total timeout?
|
|
707
|
+
if (!isInfinite(this._timeout) && latency >= this._timeout) { // total timeout
|
|
708
|
+
// @ts-ignore
|
|
709
|
+
this.emit(Event.Timeout, this._currentRetries, latency, this._timeout);
|
|
710
|
+
// always task, treat as success, resolve the whole promise with <void>
|
|
711
|
+
if (AlwaysTask.isAlwaysTask(this._task)) {
|
|
712
|
+
this._taskingFlag.resolve();
|
|
713
|
+
break
|
|
714
|
+
}
|
|
715
|
+
this._taskingFlag.reject(lastError ?? new Error(`Timeout "${this._timeout}" Exceeded`));
|
|
716
|
+
break
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// @ts-ignore
|
|
720
|
+
this.emit(Event.Retry, this._currentRetries, latency);
|
|
721
|
+
const task = this._task; // take task, it may be changed in events' callback functions
|
|
722
|
+
const nextDelay = this._policy.generate();
|
|
723
|
+
try {
|
|
724
|
+
try {
|
|
725
|
+
await J.timeout(task.execute(this._currentRetries, latency, nextDelay), this._taskTimeout, TaskTimoutFlag);
|
|
726
|
+
} catch (err) {
|
|
727
|
+
// @ts-ignore
|
|
728
|
+
if (err.message === TaskTimoutFlag) {
|
|
729
|
+
// @ts-ignore
|
|
730
|
+
this.emit(Event.TaskTimeout, this._currentRetries, latency, this._taskTimeout);
|
|
731
|
+
}
|
|
732
|
+
throw err
|
|
733
|
+
}
|
|
734
|
+
// @ts-ignore
|
|
735
|
+
if (task.failed) {
|
|
736
|
+
lastError = task.error;
|
|
737
|
+
throw task.error
|
|
738
|
+
}
|
|
739
|
+
const rtnVal = task.result;
|
|
740
|
+
// @ts-ignore
|
|
741
|
+
this.emit(Event.Success, rtnVal, this._currentRetries, latency);
|
|
742
|
+
|
|
743
|
+
// Not AwaysTask, we can finish all the retries with success
|
|
744
|
+
if (!AlwaysTask.isAlwaysTask(task)) {
|
|
745
|
+
this._taskingFlag.resolve(rtnVal);
|
|
746
|
+
break
|
|
747
|
+
}
|
|
748
|
+
// AwaysTask, continue to run the task
|
|
749
|
+
} catch (e) {
|
|
750
|
+
// @ts-ignore
|
|
751
|
+
this.emit(Event.Failure, e, this._currentRetries, latency);
|
|
752
|
+
}
|
|
753
|
+
const nextRetries = ++this._currentRetries;
|
|
754
|
+
// next retry, max retries reached?
|
|
755
|
+
if (this._currentRetries > this._maxRetries) {
|
|
756
|
+
// @ts-ignore
|
|
757
|
+
this.emit(Event.MaxRetries, nextRetries, this._maxRetries);
|
|
758
|
+
// always task, treat as success, resolve the whole promise with <void>
|
|
759
|
+
if (AlwaysTask.isAlwaysTask(task)) {
|
|
760
|
+
this._taskingFlag.resolve();
|
|
761
|
+
break
|
|
762
|
+
}
|
|
763
|
+
this._taskingFlag.reject(lastError ?? new Error(`Max Retries Exceeded, Retring ${this._currentRetries} times > max ${this._maxRetries}`));
|
|
764
|
+
break
|
|
765
|
+
}
|
|
766
|
+
await J.delay(nextDelay);
|
|
767
|
+
}
|
|
768
|
+
this._taskingFlag.promise.finally(() => {
|
|
769
|
+
this.resetRetryPolicy();
|
|
770
|
+
this._taskingFlag = undefined;
|
|
771
|
+
const spent = Date.now() - startAt;
|
|
772
|
+
// @ts-ignore
|
|
773
|
+
this.emit(Event.Completed, this._currentRetries, spent);
|
|
774
|
+
});
|
|
775
|
+
return this._taskingFlag.promise
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* Stops the retrier with an optional reason. If already stopping, returns the existing break promise.
|
|
780
|
+
* @param {Error} [reason] - Optional reason for stopping (defaults to 'Manually Stop' error).
|
|
781
|
+
* @returns {Promise<void>} A promise that resolves when the retrier has fully stopped.
|
|
782
|
+
*/
|
|
783
|
+
async stop (reason) {
|
|
784
|
+
// @ts-ignore
|
|
785
|
+
this.emit(Event.Stop, reason);
|
|
786
|
+
if (this._taskingFlag == null) {
|
|
787
|
+
return // no task running
|
|
788
|
+
}
|
|
789
|
+
if (this._breakFlag != null) {
|
|
790
|
+
// @ts-ignore
|
|
791
|
+
return this._breakFlag.promise
|
|
792
|
+
}
|
|
793
|
+
this._breakFlag = J.defer();
|
|
794
|
+
this._breakReason = reason ?? new Error('Manually Stop');
|
|
795
|
+
// @ts-ignore
|
|
796
|
+
this.once(Event.Completed, () => {
|
|
797
|
+
// @ts-ignore
|
|
798
|
+
this._breakFlag.resolve();
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
// @ts-ignore
|
|
802
|
+
this._breakFlag.promise.finally(() => {
|
|
803
|
+
this._breakFlag = undefined;
|
|
804
|
+
this._breakReason = undefined;
|
|
805
|
+
});
|
|
806
|
+
return this._breakFlag.promise
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* Resets the retry policy to its initial state.
|
|
811
|
+
*/
|
|
812
|
+
resetRetryPolicy () {
|
|
813
|
+
this._policy.reset();
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/**
|
|
817
|
+
* Registers a listener function to be called on "retry" events.
|
|
818
|
+
* @param {Function} listener - The callback function
|
|
819
|
+
* @returns {this}
|
|
820
|
+
*/
|
|
821
|
+
onRetry (listener) {
|
|
822
|
+
// @ts-ignore
|
|
823
|
+
this.on(Event.Retry, listener);
|
|
824
|
+
return this
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/**
|
|
828
|
+
* Registers a listener for "error" events.
|
|
829
|
+
* @param {Function} listener - The callback function
|
|
830
|
+
* @returns {this}
|
|
831
|
+
*/
|
|
832
|
+
onError (listener) {
|
|
833
|
+
// @ts-ignore
|
|
834
|
+
this.on(Event.Error, listener);
|
|
835
|
+
return this
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Registers a listener for "failure" events.
|
|
840
|
+
* @param {Function} listener - The callback function
|
|
841
|
+
* @returns {this}
|
|
842
|
+
*/
|
|
843
|
+
onFailure (listener) {
|
|
844
|
+
// @ts-ignore
|
|
845
|
+
this.on(Event.Failure, listener);
|
|
846
|
+
return this
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* Registers a listener for "success" events.
|
|
851
|
+
* @param {Function} listener - The callback function
|
|
852
|
+
* @returns {this}
|
|
853
|
+
*/
|
|
854
|
+
onSuccess (listener) {
|
|
855
|
+
// @ts-ignore
|
|
856
|
+
this.on(Event.Success, listener);
|
|
857
|
+
return this
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* Registers a listener for "start" events.
|
|
862
|
+
* @param {Function} listener - The callback function
|
|
863
|
+
* @returns {this}
|
|
864
|
+
*/
|
|
865
|
+
onStart (listener) {
|
|
866
|
+
// @ts-ignore
|
|
867
|
+
this.on(Event.Start, listener);
|
|
868
|
+
return this
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* Registers a listener for "stop" events.
|
|
873
|
+
* @param {Function} listener - The callback function
|
|
874
|
+
* @returns {this}
|
|
875
|
+
*/
|
|
876
|
+
onStop (listener) {
|
|
877
|
+
// @ts-ignore
|
|
878
|
+
this.on(Event.Stop, listener);
|
|
879
|
+
return this
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/**
|
|
883
|
+
* Registers a listener for "timeout" events.
|
|
884
|
+
* @param {Function} listener - The callback function
|
|
885
|
+
*/
|
|
886
|
+
onTimeout (listener) {
|
|
887
|
+
// @ts-ignore
|
|
888
|
+
this.on(Event.Timeout, listener);
|
|
889
|
+
return this
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/**
|
|
893
|
+
* Registers a listener for "task-timeout" events.
|
|
894
|
+
* @param {Function} listener - The callback function
|
|
895
|
+
* @returns {this}
|
|
896
|
+
*/
|
|
897
|
+
onTaskTimeout (listener) {
|
|
898
|
+
// @ts-ignore
|
|
899
|
+
this.on(Event.TaskTimeout, listener);
|
|
900
|
+
return this
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* Registers a listener for "completed" events.
|
|
905
|
+
* @param {Function} listener - The callback function
|
|
906
|
+
*/
|
|
907
|
+
onCompleted (listener) {
|
|
908
|
+
// @ts-ignore
|
|
909
|
+
this.on(Event.Completed, listener);
|
|
910
|
+
return this
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* Registers a listener for the 'MaxRetries' event.
|
|
915
|
+
* @param {Function} listener - The callback function to be executed when max retries are reached.
|
|
916
|
+
* @returns {this}
|
|
917
|
+
*/
|
|
918
|
+
onMaxRetries (listener) {
|
|
919
|
+
// @ts-ignore
|
|
920
|
+
this.on(Event.MaxRetries, listener);
|
|
921
|
+
return this
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* Checks if a value represents infinity or a non-positive number.
|
|
927
|
+
* @param {number} value - The value to check
|
|
928
|
+
* @returns {boolean} True if the value is <= 0 or Infinity, false otherwise
|
|
929
|
+
*/
|
|
930
|
+
function isInfinite (value) {
|
|
931
|
+
return value <= 0 || value === Infinity
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// owned
|
|
935
|
+
/**
|
|
936
|
+
* Creates a new Retrier instance with the specified name.
|
|
937
|
+
* @param {string} name - The name to assign to the retrier.
|
|
938
|
+
* @returns {Retrier} A new Retrier instance with the given name.
|
|
939
|
+
*/
|
|
940
|
+
function name (name) {
|
|
941
|
+
const retrier = new Retrier();
|
|
942
|
+
retrier.name(name);
|
|
943
|
+
return retrier
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/**
|
|
947
|
+
* Creates and returns a Retrier instance configured for infinite retries.
|
|
948
|
+
* @returns {Retrier} A Retrier instance with infinite retry behavior.
|
|
949
|
+
*/
|
|
950
|
+
function infinite () {
|
|
951
|
+
const retrier = new Retrier();
|
|
952
|
+
retrier.infinite();
|
|
953
|
+
return retrier
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/**
|
|
957
|
+
* Creates a retrier configured to attempt an operation a specified number of times.
|
|
958
|
+
* @param {number} times - The maximum number of retry attempts.
|
|
959
|
+
* @returns {Retrier} A configured Retrier instance with the specified max retries.
|
|
960
|
+
*/
|
|
961
|
+
function times (times) {
|
|
962
|
+
const retrier = new Retrier();
|
|
963
|
+
retrier.times(times);
|
|
964
|
+
return retrier
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
/**
|
|
968
|
+
* Alias for times.
|
|
969
|
+
* @param {number} maxRetries - The maximum number of retry attempts.
|
|
970
|
+
* @returns {Retrier} A configured Retrier instance with the specified max retries.
|
|
971
|
+
*/
|
|
972
|
+
function maxRetries (maxRetries) {
|
|
973
|
+
const retrier = new Retrier();
|
|
974
|
+
retrier.maxRetries(maxRetries);
|
|
975
|
+
return retrier
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/**
|
|
979
|
+
* Sets the minimum Interval for the retrier and returns the instance.
|
|
980
|
+
* @param {number} min - The minimum Interval in milliseconds.
|
|
981
|
+
* @returns {Retrier} The retrier instance with updated minimum Interval.
|
|
982
|
+
*/
|
|
983
|
+
function min (min) {
|
|
984
|
+
const retrier = new Retrier();
|
|
985
|
+
retrier.min(min);
|
|
986
|
+
return retrier
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/**
|
|
990
|
+
* Sets the maximum Interval for the retrier and returns the instance.
|
|
991
|
+
* @param {number} max - The maximum Interval in milliseconds.
|
|
992
|
+
* @returns {Retrier} The retrier instance with updated maximum Interval.
|
|
993
|
+
*/
|
|
994
|
+
function max (max) {
|
|
995
|
+
const retrier = new Retrier();
|
|
996
|
+
retrier.max(max);
|
|
997
|
+
return retrier
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/**
|
|
1001
|
+
* Creates a retrier with the specified Interval range.
|
|
1002
|
+
* @param {number} min - Minimum Interval.
|
|
1003
|
+
* @param {number} max - Maximum Interval.
|
|
1004
|
+
* @returns {Retrier} A new Retrier instance configured with specified Interval range.
|
|
1005
|
+
*/
|
|
1006
|
+
function range (min, max) {
|
|
1007
|
+
const retrier = new Retrier();
|
|
1008
|
+
retrier.range(min, max);
|
|
1009
|
+
return retrier
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/**
|
|
1013
|
+
* Creates a retrier with a fixed interval between attempts.
|
|
1014
|
+
* @param {number} fixedInterval - The fixed interval in milliseconds between retry attempts.
|
|
1015
|
+
* @returns {Retrier} A new Retrier instance configured with the specified fixed interval.
|
|
1016
|
+
*/
|
|
1017
|
+
function fixedInterval (fixedInterval) {
|
|
1018
|
+
const retrier = new Retrier();
|
|
1019
|
+
retrier.fixedInterval(fixedInterval);
|
|
1020
|
+
return retrier
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/**
|
|
1024
|
+
* Creates a retrier with a fixed increase strategy.
|
|
1025
|
+
* @param {number} increasement - The fixed amount to increase on each retry.
|
|
1026
|
+
* @returns {Retrier} A retrier instance configured with fixed increase.
|
|
1027
|
+
*/
|
|
1028
|
+
function fixedIncrease (increasement) {
|
|
1029
|
+
const retrier = new Retrier();
|
|
1030
|
+
retrier.fixedIncrease(increasement);
|
|
1031
|
+
return retrier
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Creates a new Retrier instance with factor-increase strategy.
|
|
1036
|
+
* @param {number} factor - The factor by which to increase the interval on each retry.
|
|
1037
|
+
* @returns {Retrier} A new Retrier instance with factor-increase strategy.
|
|
1038
|
+
*/
|
|
1039
|
+
function factorIncrease (factor) {
|
|
1040
|
+
const retrier = new Retrier();
|
|
1041
|
+
retrier.factorIncrease(factor);
|
|
1042
|
+
return retrier
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
/**
|
|
1046
|
+
* Creates a Retrier instance with a shuttle-interval strategt.
|
|
1047
|
+
* @param {number} stepLength - The interval step length of each change
|
|
1048
|
+
* @returns {Retrier} A configured Retrier instance with shuttle-interval strategt.
|
|
1049
|
+
*/
|
|
1050
|
+
function shuttleInterval (stepLength) {
|
|
1051
|
+
const retrier = new Retrier();
|
|
1052
|
+
retrier.shuttleInterval(stepLength);
|
|
1053
|
+
return retrier
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
/**
|
|
1057
|
+
* Creates a Retrier instance with a total-opertion timeout.
|
|
1058
|
+
* @param {number} timeout - The timeout value in milliseconds.
|
|
1059
|
+
* @returns {Retrier} A Retrier instance configured with the given timeout.
|
|
1060
|
+
*/
|
|
1061
|
+
function timeout (timeout) {
|
|
1062
|
+
const retrier = new Retrier();
|
|
1063
|
+
retrier.timeout(timeout);
|
|
1064
|
+
return retrier
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/**
|
|
1068
|
+
* Creates a retrier instance with a single-task timeout.
|
|
1069
|
+
* @param {number} timeout - The timeout duration in milliseconds for the retrier task.
|
|
1070
|
+
* @returns {Retrier} A Retrier instance configured with the given task timeout.
|
|
1071
|
+
*/
|
|
1072
|
+
function taskTimeout (timeout) {
|
|
1073
|
+
const retrier = new Retrier();
|
|
1074
|
+
retrier.taskTimeout(timeout);
|
|
1075
|
+
return retrier
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
/**
|
|
1079
|
+
* Creates a new Retrier instance, sets the task to be retried, and starts the retry process.
|
|
1080
|
+
* @param {Function} task - The asynchronous task function to be retried.
|
|
1081
|
+
* @returns {Promise<*>} A promise that resolves when the retry process completes.
|
|
1082
|
+
*/
|
|
1083
|
+
function start (task) {
|
|
1084
|
+
const retrier = new Retrier();
|
|
1085
|
+
retrier.task(task);
|
|
1086
|
+
return retrier.start()
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
// default export
|
|
1090
|
+
var RetrierFactory = {
|
|
1091
|
+
name,
|
|
1092
|
+
infinite,
|
|
1093
|
+
times,
|
|
1094
|
+
maxRetries,
|
|
1095
|
+
min,
|
|
1096
|
+
max,
|
|
1097
|
+
range,
|
|
1098
|
+
fixedInterval,
|
|
1099
|
+
fixedIncrease,
|
|
1100
|
+
factorIncrease,
|
|
1101
|
+
shuttleInterval,
|
|
1102
|
+
timeout,
|
|
1103
|
+
taskTimeout,
|
|
1104
|
+
start
|
|
1105
|
+
};
|
|
1106
|
+
|
|
1107
|
+
// 3rd
|
|
1108
|
+
|
|
1109
|
+
/**
|
|
1110
|
+
* Add all factory methods to Retrier as static methods.
|
|
1111
|
+
* Now we can create do something like this:
|
|
1112
|
+
* ```
|
|
1113
|
+
* Retrier.name('myRetrier')
|
|
1114
|
+
* Retrier.infinite()
|
|
1115
|
+
* ...
|
|
1116
|
+
* ```
|
|
1117
|
+
*/
|
|
1118
|
+
t$1.defaults(Retrier, RetrierFactory);
|
|
1119
|
+
|
|
1120
|
+
/**
|
|
1121
|
+
* default export to support
|
|
1122
|
+
* 1. import CommonsRetrier from '@creejs/commons-retrier'
|
|
1123
|
+
*/
|
|
1124
|
+
var index = {
|
|
1125
|
+
Policy,
|
|
1126
|
+
Retrier,
|
|
1127
|
+
Event,
|
|
1128
|
+
RetrierFactory,
|
|
1129
|
+
...RetrierFactory
|
|
1130
|
+
};
|
|
1131
|
+
|
|
1132
|
+
exports.Event = Event;
|
|
1133
|
+
exports.Policy = Policy;
|
|
1134
|
+
exports.Retrier = Retrier;
|
|
1135
|
+
exports.RetrierFactory = RetrierFactory;
|
|
1136
|
+
exports.default = index;
|
|
1137
|
+
exports.factorIncrease = factorIncrease;
|
|
1138
|
+
exports.fixedIncrease = fixedIncrease;
|
|
1139
|
+
exports.fixedInterval = fixedInterval;
|
|
1140
|
+
exports.infinite = infinite;
|
|
1141
|
+
exports.max = max;
|
|
1142
|
+
exports.maxRetries = maxRetries;
|
|
1143
|
+
exports.min = min;
|
|
1144
|
+
exports.name = name;
|
|
1145
|
+
exports.range = range;
|
|
1146
|
+
exports.shuttleInterval = shuttleInterval;
|
|
1147
|
+
exports.start = start;
|
|
1148
|
+
exports.taskTimeout = taskTimeout;
|
|
1149
|
+
exports.timeout = timeout;
|
|
1150
|
+
exports.times = times;
|
|
1151
|
+
//# sourceMappingURL=index-dev.cjs.map
|