@sha1n/about-time 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +97 -0
- package/dist/index.js +15 -0
- package/dist/lib/retry.js +87 -0
- package/dist/lib/timeunit.js +28 -0
- package/dist/lib/utilities.js +80 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/lib/retry.d.ts +18 -0
- package/dist/types/lib/timeunit.d.ts +21 -0
- package/dist/types/lib/utilities.d.ts +40 -0
- package/index.ts +3 -0
- package/lib/retry.ts +139 -0
- package/lib/timeunit.ts +25 -0
- package/lib/utilities.ts +90 -0
- package/package.json +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Shai Nagar
|
|
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
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
[](https://github.com/sha1n/about-time/actions/workflows/ci.yml)
|
|
2
|
+
[](https://github.com/sha1n/about-time/actions/workflows/coverage.yml)
|
|
3
|
+

|
|
4
|
+

|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# About-Time
|
|
9
|
+
|
|
10
|
+
A set of essential time related utilities.
|
|
11
|
+
|
|
12
|
+
- [About-Time](#about-time)
|
|
13
|
+
- [Install](#install)
|
|
14
|
+
- [Delay](#delay)
|
|
15
|
+
- [Sleep](#sleep)
|
|
16
|
+
- [Stopwatch](#stopwatch)
|
|
17
|
+
- [Until / Eventually](#until--eventually)
|
|
18
|
+
- [Retry](#retry)
|
|
19
|
+
- [RetryPolicy](#retrypolicy)
|
|
20
|
+
- [Simple retry policy](#simple-retry-policy)
|
|
21
|
+
- [Fixed retry policy](#fixed-retry-policy)
|
|
22
|
+
- [Exponential backoff retry policy](#exponential-backoff-retry-policy)
|
|
23
|
+
- [RetryAround](#retryaround)
|
|
24
|
+
- [Retriable](#retriable)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
```bash
|
|
29
|
+
npm i @sha1n/about-time
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Delay
|
|
33
|
+
```ts
|
|
34
|
+
// Execute a function with delay and return it's value
|
|
35
|
+
await delay(action, 10, TimeUnit.Milliseconds);
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Sleep
|
|
39
|
+
```ts
|
|
40
|
+
// Pause execution for a specified amount of time
|
|
41
|
+
await sleep(10, TimeUnit.Seconds);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Stopwatch
|
|
45
|
+
```ts
|
|
46
|
+
// Measure time between actions
|
|
47
|
+
const elapsed = stopwatch();
|
|
48
|
+
|
|
49
|
+
// do stuff here...
|
|
50
|
+
|
|
51
|
+
const elapsed1 = elapsed(TimeUnit.Milliseconds);
|
|
52
|
+
|
|
53
|
+
// do more stuff here...
|
|
54
|
+
|
|
55
|
+
const elapsed2 = elapsed(TimeUnit.Seconds);
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Until / Eventually
|
|
59
|
+
```ts
|
|
60
|
+
// Wait for a condition to become true
|
|
61
|
+
await until(condition, {timeout: 1, units: TimeUnit.Minute});
|
|
62
|
+
await eventually(condition, {timeout: 1, units: TimeUnit.Minute});
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Retry
|
|
66
|
+
|
|
67
|
+
### RetryPolicy
|
|
68
|
+
#### Simple retry policy
|
|
69
|
+
```ts
|
|
70
|
+
// 3 retries with 10 seconds wait between each
|
|
71
|
+
const retryPolicy = simpleRetryPolicy(3, 10, TimeUnit.Seconds);
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
#### Fixed retry policy
|
|
75
|
+
```ts
|
|
76
|
+
// 4 retries after 3, then after 10, 50 and 100 milliseconds
|
|
77
|
+
const retryPolicy = fixedRetryPolicy([3, 10, 50, 100], TimeUnit.Milliseconds);
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
#### Exponential backoff retry policy
|
|
81
|
+
```ts
|
|
82
|
+
// 10 retries, starting with 10 milliseconds and then exponentially increases the delay based on the default power value without a limit.
|
|
83
|
+
const retryPolicy = exponentialBackoffRetryPolicy(/* count = */10, /* opts?: { exponential?: number, limit?: number, units?: TimeUnit }*/);
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### RetryAround
|
|
87
|
+
Executes the given function with the retries based on the specified policy.
|
|
88
|
+
```ts
|
|
89
|
+
const result = await retryAround(action, retryPolicy);
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Retriable
|
|
93
|
+
Wraps a given function with `retryAround` with the specified policy.
|
|
94
|
+
```ts
|
|
95
|
+
const retriableAction = retriable(action, retryPolicy);
|
|
96
|
+
const result = await retriableAction();
|
|
97
|
+
```
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
5
|
+
}) : (function(o, m, k, k2) {
|
|
6
|
+
if (k2 === undefined) k2 = k;
|
|
7
|
+
o[k2] = m[k];
|
|
8
|
+
}));
|
|
9
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
10
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
11
|
+
};
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
__exportStar(require("./lib/timeunit"), exports);
|
|
14
|
+
__exportStar(require("./lib/utilities"), exports);
|
|
15
|
+
__exportStar(require("./lib/retry"), exports);
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.exponentialBackoffRetryPolicy = exports.simpleRetryPolicy = exports.fixedRetryPolicy = exports.retriable = exports.retryAround = void 0;
|
|
4
|
+
const timeunit_1 = require("./timeunit");
|
|
5
|
+
const utilities_1 = require("./utilities");
|
|
6
|
+
class SimpleRetryPolicy {
|
|
7
|
+
constructor(count, interval, units) {
|
|
8
|
+
this.count = count;
|
|
9
|
+
this.interval = (0, timeunit_1.toMilliseconds)(interval, units);
|
|
10
|
+
}
|
|
11
|
+
*intervals() {
|
|
12
|
+
let count = this.count;
|
|
13
|
+
while (count > 0) {
|
|
14
|
+
count -= 1;
|
|
15
|
+
yield this.interval;
|
|
16
|
+
}
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
class ExponentialBackoffRetryPolicy {
|
|
21
|
+
constructor(count, exponential = 2, limit = Infinity, units = timeunit_1.TimeUnit.Milliseconds) {
|
|
22
|
+
this.count = count;
|
|
23
|
+
this.exponential = exponential;
|
|
24
|
+
this.limit = limit;
|
|
25
|
+
this.units = units;
|
|
26
|
+
}
|
|
27
|
+
*intervals() {
|
|
28
|
+
let index = 0;
|
|
29
|
+
while (index < this.count) {
|
|
30
|
+
const interval = Math.round((Math.pow(this.exponential, index) - 1) / 2);
|
|
31
|
+
yield Math.min(this.limit, interval) * this.units;
|
|
32
|
+
index += 1;
|
|
33
|
+
}
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
class FixedRetryPolicy {
|
|
38
|
+
constructor(intervals, units) {
|
|
39
|
+
this._intervals = intervals.reduceRight((result, v) => {
|
|
40
|
+
result.push((0, timeunit_1.toMilliseconds)(v, units));
|
|
41
|
+
return result;
|
|
42
|
+
}, []);
|
|
43
|
+
}
|
|
44
|
+
*intervals() {
|
|
45
|
+
const intervals = [...this._intervals];
|
|
46
|
+
while (intervals.length > 0) {
|
|
47
|
+
yield intervals.pop();
|
|
48
|
+
}
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function simpleRetryPolicy(count, interval, opts) {
|
|
53
|
+
return Object.freeze(new SimpleRetryPolicy(count, interval, opts === null || opts === void 0 ? void 0 : opts.units));
|
|
54
|
+
}
|
|
55
|
+
exports.simpleRetryPolicy = simpleRetryPolicy;
|
|
56
|
+
function fixedRetryPolicy(intervals, opts) {
|
|
57
|
+
return Object.freeze(new FixedRetryPolicy(intervals, opts === null || opts === void 0 ? void 0 : opts.units));
|
|
58
|
+
}
|
|
59
|
+
exports.fixedRetryPolicy = fixedRetryPolicy;
|
|
60
|
+
function exponentialBackoffRetryPolicy(count, opts) {
|
|
61
|
+
return Object.freeze(new ExponentialBackoffRetryPolicy(count, opts === null || opts === void 0 ? void 0 : opts.exponential, opts === null || opts === void 0 ? void 0 : opts.limit, opts === null || opts === void 0 ? void 0 : opts.units));
|
|
62
|
+
}
|
|
63
|
+
exports.exponentialBackoffRetryPolicy = exponentialBackoffRetryPolicy;
|
|
64
|
+
async function retryAround(action, policy) {
|
|
65
|
+
let next;
|
|
66
|
+
const intervals = policy.intervals()[Symbol.iterator]();
|
|
67
|
+
do {
|
|
68
|
+
try {
|
|
69
|
+
return await action();
|
|
70
|
+
}
|
|
71
|
+
catch (e) {
|
|
72
|
+
next = intervals.next();
|
|
73
|
+
if (next.done) {
|
|
74
|
+
throw e;
|
|
75
|
+
}
|
|
76
|
+
await (0, utilities_1.sleep)(next.value);
|
|
77
|
+
}
|
|
78
|
+
} while (!next.done);
|
|
79
|
+
throw new Error('Unexpected error. This is most likely a bug.');
|
|
80
|
+
}
|
|
81
|
+
exports.retryAround = retryAround;
|
|
82
|
+
function retriable(action, policy) {
|
|
83
|
+
return () => {
|
|
84
|
+
return retryAround(action, policy);
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
exports.retriable = retriable;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.toMilliseconds = exports.TimeUnit = void 0;
|
|
4
|
+
var TimeUnit;
|
|
5
|
+
(function (TimeUnit) {
|
|
6
|
+
TimeUnit[TimeUnit["Milliseconds"] = 1] = "Milliseconds";
|
|
7
|
+
TimeUnit[TimeUnit["Millisecond"] = 1] = "Millisecond";
|
|
8
|
+
TimeUnit[TimeUnit["Seconds"] = 1000] = "Seconds";
|
|
9
|
+
TimeUnit[TimeUnit["Second"] = 1000] = "Second";
|
|
10
|
+
TimeUnit[TimeUnit["Minutes"] = 60000] = "Minutes";
|
|
11
|
+
TimeUnit[TimeUnit["Minute"] = 60000] = "Minute";
|
|
12
|
+
TimeUnit[TimeUnit["Hours"] = 3600000] = "Hours";
|
|
13
|
+
TimeUnit[TimeUnit["Hour"] = 3600000] = "Hour";
|
|
14
|
+
TimeUnit[TimeUnit["Days"] = 86400000] = "Days";
|
|
15
|
+
TimeUnit[TimeUnit["Day"] = 86400000] = "Day";
|
|
16
|
+
})(TimeUnit || (TimeUnit = {}));
|
|
17
|
+
exports.TimeUnit = TimeUnit;
|
|
18
|
+
/**
|
|
19
|
+
* Converts time value in other units to milliseconds.
|
|
20
|
+
*
|
|
21
|
+
* @param time a time value to be converted
|
|
22
|
+
* @param units the units of time
|
|
23
|
+
* @returns the time value in milliseconds
|
|
24
|
+
*/
|
|
25
|
+
function toMilliseconds(time, units) {
|
|
26
|
+
return time * (units ? units : 1);
|
|
27
|
+
}
|
|
28
|
+
exports.toMilliseconds = toMilliseconds;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.eventually = exports.until = exports.stopwatch = exports.delay = exports.sleep = void 0;
|
|
4
|
+
const timeunit_1 = require("./timeunit");
|
|
5
|
+
/**
|
|
6
|
+
* Zzzz...
|
|
7
|
+
*
|
|
8
|
+
* @param time time to sleep
|
|
9
|
+
* @param units the units on time
|
|
10
|
+
* @returns a promise that resolves when the specified time has elapsed.
|
|
11
|
+
*/
|
|
12
|
+
function sleep(time, units) {
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
setTimeout(resolve, (0, timeunit_1.toMilliseconds)(time, units));
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
exports.sleep = sleep;
|
|
18
|
+
/**
|
|
19
|
+
* Delays the execution of the specified action and returns its value.
|
|
20
|
+
*
|
|
21
|
+
* @param action a function to execute with delay
|
|
22
|
+
* @param time time to sleep
|
|
23
|
+
* @param units the units on time
|
|
24
|
+
* @returns a promise that resolves when the specified time has elapsed.
|
|
25
|
+
*/
|
|
26
|
+
function delay(action, time, units) {
|
|
27
|
+
const delayMs = (0, timeunit_1.toMilliseconds)(time, units);
|
|
28
|
+
return new Promise((resolve, reject) => {
|
|
29
|
+
setTimeout(() => Promise.resolve(action()).then(resolve, reject), delayMs);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
exports.delay = delay;
|
|
33
|
+
/**
|
|
34
|
+
* Return a function that returns the elapsed time relative to this call.
|
|
35
|
+
* @returns a function
|
|
36
|
+
*/
|
|
37
|
+
function stopwatch() {
|
|
38
|
+
const startTime = Date.now();
|
|
39
|
+
return (units) => {
|
|
40
|
+
return (Date.now() - startTime) / (units || timeunit_1.TimeUnit.Milliseconds);
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
exports.stopwatch = stopwatch;
|
|
44
|
+
/**
|
|
45
|
+
* Awaits a specified condition to evaluate to true with or without a timeout.
|
|
46
|
+
*
|
|
47
|
+
* @param condition the condition to wait for
|
|
48
|
+
* @param opts options that control evaluation intervals and timeout
|
|
49
|
+
* @returns a promise that resolves when the condition becomes true, or rejects when a set timeout is crossed.
|
|
50
|
+
*/
|
|
51
|
+
async function until(condition, opts) {
|
|
52
|
+
if (condition()) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const defaultInterval = 50;
|
|
56
|
+
const deadline = opts
|
|
57
|
+
? Date.now() + (0, timeunit_1.toMilliseconds)(opts.timeout, opts.units)
|
|
58
|
+
: Number.MAX_VALUE;
|
|
59
|
+
const interval = (opts === null || opts === void 0 ? void 0 : opts.interval)
|
|
60
|
+
? (0, timeunit_1.toMilliseconds)(opts.interval, opts.units)
|
|
61
|
+
: defaultInterval;
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
const handle = setInterval(() => {
|
|
64
|
+
if (Date.now() > deadline) {
|
|
65
|
+
clearInterval(handle);
|
|
66
|
+
reject(new Error('Timeout'));
|
|
67
|
+
}
|
|
68
|
+
if (condition()) {
|
|
69
|
+
clearInterval(handle);
|
|
70
|
+
resolve();
|
|
71
|
+
}
|
|
72
|
+
}, interval);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
exports.until = until;
|
|
76
|
+
/**
|
|
77
|
+
* Alias to `until`
|
|
78
|
+
*/
|
|
79
|
+
const eventually = until;
|
|
80
|
+
exports.eventually = eventually;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { TimeUnit } from './timeunit';
|
|
2
|
+
interface RetryPolicy {
|
|
3
|
+
intervals(): Iterable<number>;
|
|
4
|
+
}
|
|
5
|
+
declare function simpleRetryPolicy(count: number, interval: number, opts?: {
|
|
6
|
+
units?: TimeUnit;
|
|
7
|
+
}): RetryPolicy;
|
|
8
|
+
declare function fixedRetryPolicy(intervals: number[], opts?: {
|
|
9
|
+
units?: TimeUnit;
|
|
10
|
+
}): RetryPolicy;
|
|
11
|
+
declare function exponentialBackoffRetryPolicy(count: number, opts?: {
|
|
12
|
+
exponential?: number;
|
|
13
|
+
limit?: number;
|
|
14
|
+
units?: TimeUnit;
|
|
15
|
+
}): RetryPolicy;
|
|
16
|
+
declare function retryAround<T>(action: () => T | Promise<T>, policy: RetryPolicy): Promise<T>;
|
|
17
|
+
declare function retriable<T>(action: () => T | Promise<T>, policy: RetryPolicy): () => Promise<T>;
|
|
18
|
+
export { RetryPolicy, retryAround, retriable, fixedRetryPolicy, simpleRetryPolicy, exponentialBackoffRetryPolicy };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
declare enum TimeUnit {
|
|
2
|
+
Milliseconds = 1,
|
|
3
|
+
Millisecond = 1,
|
|
4
|
+
Seconds = 1000,
|
|
5
|
+
Second = 1000,
|
|
6
|
+
Minutes = 60000,
|
|
7
|
+
Minute = 60000,
|
|
8
|
+
Hours = 3600000,
|
|
9
|
+
Hour = 3600000,
|
|
10
|
+
Days = 86400000,
|
|
11
|
+
Day = 86400000
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Converts time value in other units to milliseconds.
|
|
15
|
+
*
|
|
16
|
+
* @param time a time value to be converted
|
|
17
|
+
* @param units the units of time
|
|
18
|
+
* @returns the time value in milliseconds
|
|
19
|
+
*/
|
|
20
|
+
declare function toMilliseconds(time: number, units?: TimeUnit): number;
|
|
21
|
+
export { TimeUnit, toMilliseconds };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { TimeUnit } from './timeunit';
|
|
2
|
+
/**
|
|
3
|
+
* Zzzz...
|
|
4
|
+
*
|
|
5
|
+
* @param time time to sleep
|
|
6
|
+
* @param units the units on time
|
|
7
|
+
* @returns a promise that resolves when the specified time has elapsed.
|
|
8
|
+
*/
|
|
9
|
+
declare function sleep(time: number, units?: TimeUnit): Promise<void>;
|
|
10
|
+
/**
|
|
11
|
+
* Delays the execution of the specified action and returns its value.
|
|
12
|
+
*
|
|
13
|
+
* @param action a function to execute with delay
|
|
14
|
+
* @param time time to sleep
|
|
15
|
+
* @param units the units on time
|
|
16
|
+
* @returns a promise that resolves when the specified time has elapsed.
|
|
17
|
+
*/
|
|
18
|
+
declare function delay<T>(action: () => T | Promise<T>, time: number, units?: TimeUnit): Promise<T>;
|
|
19
|
+
/**
|
|
20
|
+
* Return a function that returns the elapsed time relative to this call.
|
|
21
|
+
* @returns a function
|
|
22
|
+
*/
|
|
23
|
+
declare function stopwatch(): (units?: TimeUnit) => number;
|
|
24
|
+
/**
|
|
25
|
+
* Awaits a specified condition to evaluate to true with or without a timeout.
|
|
26
|
+
*
|
|
27
|
+
* @param condition the condition to wait for
|
|
28
|
+
* @param opts options that control evaluation intervals and timeout
|
|
29
|
+
* @returns a promise that resolves when the condition becomes true, or rejects when a set timeout is crossed.
|
|
30
|
+
*/
|
|
31
|
+
declare function until(condition: () => boolean, opts?: {
|
|
32
|
+
interval?: number;
|
|
33
|
+
timeout: number;
|
|
34
|
+
units?: TimeUnit;
|
|
35
|
+
}): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* Alias to `until`
|
|
38
|
+
*/
|
|
39
|
+
declare const eventually: typeof until;
|
|
40
|
+
export { sleep, delay, stopwatch, until, eventually };
|
package/index.ts
ADDED
package/lib/retry.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { TimeUnit, toMilliseconds } from './timeunit';
|
|
2
|
+
import { sleep } from './utilities';
|
|
3
|
+
|
|
4
|
+
interface RetryPolicy {
|
|
5
|
+
intervals(): Iterable<number>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
class SimpleRetryPolicy implements RetryPolicy {
|
|
9
|
+
private readonly interval: number;
|
|
10
|
+
|
|
11
|
+
constructor(
|
|
12
|
+
private readonly count: number,
|
|
13
|
+
interval: number,
|
|
14
|
+
units?: TimeUnit
|
|
15
|
+
) {
|
|
16
|
+
this.interval = toMilliseconds(interval, units);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
*intervals(): Iterable<number> {
|
|
20
|
+
let count = this.count;
|
|
21
|
+
while (count > 0) {
|
|
22
|
+
count -= 1;
|
|
23
|
+
yield this.interval;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
class ExponentialBackoffRetryPolicy implements RetryPolicy {
|
|
31
|
+
constructor(
|
|
32
|
+
private readonly count: number,
|
|
33
|
+
private readonly exponential = 2,
|
|
34
|
+
private readonly limit = Infinity,
|
|
35
|
+
private readonly units = TimeUnit.Milliseconds
|
|
36
|
+
) {}
|
|
37
|
+
|
|
38
|
+
*intervals(): Iterable<number> {
|
|
39
|
+
let index = 0;
|
|
40
|
+
|
|
41
|
+
while (index < this.count) {
|
|
42
|
+
const interval = Math.round((Math.pow(this.exponential, index) - 1) / 2);
|
|
43
|
+
yield Math.min(this.limit, interval) * this.units;
|
|
44
|
+
index += 1;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
class FixedRetryPolicy implements RetryPolicy {
|
|
52
|
+
private _intervals: number[];
|
|
53
|
+
|
|
54
|
+
constructor(intervals: number[], units?: TimeUnit) {
|
|
55
|
+
this._intervals = intervals.reduceRight((result, v) => {
|
|
56
|
+
result.push(toMilliseconds(v, units));
|
|
57
|
+
return result;
|
|
58
|
+
}, []);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
*intervals(): Iterable<number> {
|
|
62
|
+
const intervals = [...this._intervals];
|
|
63
|
+
while (intervals.length > 0) {
|
|
64
|
+
yield intervals.pop();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function simpleRetryPolicy(
|
|
72
|
+
count: number,
|
|
73
|
+
interval: number,
|
|
74
|
+
opts?: { units?: TimeUnit }
|
|
75
|
+
): RetryPolicy {
|
|
76
|
+
return Object.freeze(new SimpleRetryPolicy(count, interval, opts?.units));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function fixedRetryPolicy(
|
|
80
|
+
intervals: number[],
|
|
81
|
+
opts?: { units?: TimeUnit }
|
|
82
|
+
): RetryPolicy {
|
|
83
|
+
return Object.freeze(new FixedRetryPolicy(intervals, opts?.units));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function exponentialBackoffRetryPolicy(
|
|
87
|
+
count: number,
|
|
88
|
+
opts?: { exponential?: number; limit?: number; units?: TimeUnit }
|
|
89
|
+
): RetryPolicy {
|
|
90
|
+
return Object.freeze(
|
|
91
|
+
new ExponentialBackoffRetryPolicy(
|
|
92
|
+
count,
|
|
93
|
+
opts?.exponential,
|
|
94
|
+
opts?.limit,
|
|
95
|
+
opts?.units
|
|
96
|
+
)
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function retryAround<T>(
|
|
101
|
+
action: () => T | Promise<T>,
|
|
102
|
+
policy: RetryPolicy
|
|
103
|
+
): Promise<T> {
|
|
104
|
+
let next: IteratorResult<number, undefined>;
|
|
105
|
+
const intervals = policy.intervals()[Symbol.iterator]();
|
|
106
|
+
do {
|
|
107
|
+
try {
|
|
108
|
+
return await action();
|
|
109
|
+
} catch (e) {
|
|
110
|
+
next = intervals.next();
|
|
111
|
+
|
|
112
|
+
if (next.done) {
|
|
113
|
+
throw e;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
await sleep(next.value);
|
|
117
|
+
}
|
|
118
|
+
} while (!next.done);
|
|
119
|
+
|
|
120
|
+
throw new Error('Unexpected error. This is most likely a bug.');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function retriable<T>(
|
|
124
|
+
action: () => T | Promise<T>,
|
|
125
|
+
policy: RetryPolicy
|
|
126
|
+
): () => Promise<T> {
|
|
127
|
+
return () => {
|
|
128
|
+
return retryAround(action, policy);
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export {
|
|
133
|
+
RetryPolicy,
|
|
134
|
+
retryAround,
|
|
135
|
+
retriable,
|
|
136
|
+
fixedRetryPolicy,
|
|
137
|
+
simpleRetryPolicy,
|
|
138
|
+
exponentialBackoffRetryPolicy
|
|
139
|
+
};
|
package/lib/timeunit.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
enum TimeUnit {
|
|
2
|
+
Milliseconds = 1,
|
|
3
|
+
Millisecond = Milliseconds,
|
|
4
|
+
Seconds = 1000,
|
|
5
|
+
Second = Seconds,
|
|
6
|
+
Minutes = 1000 * 60,
|
|
7
|
+
Minute = Minutes,
|
|
8
|
+
Hours = 1000 * 60 * 60,
|
|
9
|
+
Hour = Hours,
|
|
10
|
+
Days = 1000 * 60 * 60 * 24,
|
|
11
|
+
Day = Days
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Converts time value in other units to milliseconds.
|
|
16
|
+
*
|
|
17
|
+
* @param time a time value to be converted
|
|
18
|
+
* @param units the units of time
|
|
19
|
+
* @returns the time value in milliseconds
|
|
20
|
+
*/
|
|
21
|
+
function toMilliseconds(time: number, units?: TimeUnit): number {
|
|
22
|
+
return time * (units ? units : 1);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export { TimeUnit, toMilliseconds };
|
package/lib/utilities.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { TimeUnit, toMilliseconds } from './timeunit';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Zzzz...
|
|
5
|
+
*
|
|
6
|
+
* @param time time to sleep
|
|
7
|
+
* @param units the units on time
|
|
8
|
+
* @returns a promise that resolves when the specified time has elapsed.
|
|
9
|
+
*/
|
|
10
|
+
function sleep(time: number, units?: TimeUnit): Promise<void> {
|
|
11
|
+
return new Promise((resolve) => {
|
|
12
|
+
setTimeout(resolve, toMilliseconds(time, units));
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Delays the execution of the specified action and returns its value.
|
|
18
|
+
*
|
|
19
|
+
* @param action a function to execute with delay
|
|
20
|
+
* @param time time to sleep
|
|
21
|
+
* @param units the units on time
|
|
22
|
+
* @returns a promise that resolves when the specified time has elapsed.
|
|
23
|
+
*/
|
|
24
|
+
function delay<T>(
|
|
25
|
+
action: () => T | Promise<T>,
|
|
26
|
+
time: number,
|
|
27
|
+
units?: TimeUnit
|
|
28
|
+
): Promise<T> {
|
|
29
|
+
const delayMs = toMilliseconds(time, units);
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
setTimeout(() => Promise.resolve(action()).then(resolve, reject), delayMs);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Return a function that returns the elapsed time relative to this call.
|
|
37
|
+
* @returns a function
|
|
38
|
+
*/
|
|
39
|
+
function stopwatch(): (units?: TimeUnit) => number {
|
|
40
|
+
const startTime = Date.now();
|
|
41
|
+
|
|
42
|
+
return (units?: TimeUnit) => {
|
|
43
|
+
return (Date.now() - startTime) / (units || TimeUnit.Milliseconds);
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Awaits a specified condition to evaluate to true with or without a timeout.
|
|
49
|
+
*
|
|
50
|
+
* @param condition the condition to wait for
|
|
51
|
+
* @param opts options that control evaluation intervals and timeout
|
|
52
|
+
* @returns a promise that resolves when the condition becomes true, or rejects when a set timeout is crossed.
|
|
53
|
+
*/
|
|
54
|
+
async function until(
|
|
55
|
+
condition: () => boolean,
|
|
56
|
+
opts?: { interval?: number; timeout: number; units?: TimeUnit }
|
|
57
|
+
): Promise<void> {
|
|
58
|
+
if (condition()) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const defaultInterval = 50;
|
|
63
|
+
const deadline = opts
|
|
64
|
+
? Date.now() + toMilliseconds(opts.timeout, opts.units)
|
|
65
|
+
: Number.MAX_VALUE;
|
|
66
|
+
const interval = opts?.interval
|
|
67
|
+
? toMilliseconds(opts.interval, opts.units)
|
|
68
|
+
: defaultInterval;
|
|
69
|
+
|
|
70
|
+
return new Promise<void>((resolve, reject) => {
|
|
71
|
+
const handle = setInterval(() => {
|
|
72
|
+
if (Date.now() > deadline) {
|
|
73
|
+
clearInterval(handle);
|
|
74
|
+
reject(new Error('Timeout'));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (condition()) {
|
|
78
|
+
clearInterval(handle);
|
|
79
|
+
resolve();
|
|
80
|
+
}
|
|
81
|
+
}, interval);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Alias to `until`
|
|
87
|
+
*/
|
|
88
|
+
const eventually = until;
|
|
89
|
+
|
|
90
|
+
export { sleep, delay, stopwatch, until, eventually };
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sha1n/about-time",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "A set of essential time related utilities",
|
|
5
|
+
"repository": "https://github.com/sha1n/about-time",
|
|
6
|
+
"author": "Shai Nagar",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"types": "./dist/types",
|
|
9
|
+
"main": "./dist",
|
|
10
|
+
"exports": "./dist/index.js",
|
|
11
|
+
"scripts": {
|
|
12
|
+
"clean": "rm -rf ./dist",
|
|
13
|
+
"prebuild": "yarn run clean",
|
|
14
|
+
"build": "tsc",
|
|
15
|
+
"test": "DEBUG=error:* jest --coverage",
|
|
16
|
+
"lint": "eslint --fix --ext .js,.ts .",
|
|
17
|
+
"posttest": "npm run lint -s",
|
|
18
|
+
"prepublish": "yarn run build"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@types/chance": "^1.1.3",
|
|
23
|
+
"@types/jest": "^27.4.0",
|
|
24
|
+
"@types/node": "^17.0.8",
|
|
25
|
+
"@typescript-eslint/eslint-plugin": "^5.1.0",
|
|
26
|
+
"@typescript-eslint/parser": "^5.1.0",
|
|
27
|
+
"chance": "^1.1.8",
|
|
28
|
+
"eslint": "^7.32.0",
|
|
29
|
+
"eslint-config-prettier": "^8.3.0",
|
|
30
|
+
"eslint-plugin-import": "^2.25.2",
|
|
31
|
+
"eslint-plugin-jest": "^25.7.0",
|
|
32
|
+
"eslint-plugin-no-floating-promise": "^1.0.2",
|
|
33
|
+
"eslint-plugin-node": "^11.1.0",
|
|
34
|
+
"eslint-plugin-prettier": "^4.0.0",
|
|
35
|
+
"eslint-plugin-unused-imports": "^1.1.5",
|
|
36
|
+
"jest": "~27.4.7",
|
|
37
|
+
"jest-environment-node": "^27.2.0",
|
|
38
|
+
"jest-extended": "^1.1.0",
|
|
39
|
+
"jest-html-reporters": "^3.0.3",
|
|
40
|
+
"jest-mock-extended": "^2.0.4",
|
|
41
|
+
"jest-summary-reporter": "^0.0.2",
|
|
42
|
+
"prettier": "^2.4.1",
|
|
43
|
+
"ts-jest": "^27.1.3",
|
|
44
|
+
"ts-node": "^10.4.0",
|
|
45
|
+
"typescript": "^4.5.4"
|
|
46
|
+
}
|
|
47
|
+
}
|