@naturalcycles/js-lib 14.68.0 → 14.69.3
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/index.d.ts +3 -2
- package/dist/index.js +3 -1
- package/dist/promise/pQueue.d.ts +62 -0
- package/dist/promise/pQueue.js +105 -0
- package/dist/promise/pTimeout.d.ts +2 -1
- package/dist/promise/pTimeout.js +0 -1
- package/dist-esm/index.js +2 -1
- package/dist-esm/promise/pQueue.js +96 -0
- package/dist-esm/promise/pTimeout.js +0 -1
- package/package.json +1 -1
- package/src/index.ts +3 -0
- package/src/promise/pQueue.ts +160 -0
- package/src/promise/pTimeout.ts +3 -2
package/dist/index.d.ts
CHANGED
|
@@ -56,5 +56,6 @@ import { _gb, _hb, _kb, _mb } from './unit/size.util';
|
|
|
56
56
|
import { is } from './vendor/is';
|
|
57
57
|
import { CommonLogLevel, CommonLogFunction, CommonLogger, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix } from './log/commonLogger';
|
|
58
58
|
import { _safeJsonStringify } from './string/safeJsonStringify';
|
|
59
|
-
|
|
60
|
-
export {
|
|
59
|
+
import { PQueue, PQueueCfg } from './promise/pQueue';
|
|
60
|
+
export type { PQueueCfg, MemoCache, PromiseDecoratorCfg, PromiseDecoratorResp, ErrorData, ErrorObject, HttpErrorData, HttpErrorResponse, Admin401ErrorData, Admin403ErrorData, StringMap, PromiseMap, AnyObject, AnyFunction, ValuesOf, ValueOf, KeyValueTuple, ObjectMapper, ObjectPredicate, InstanceId, IsoDate, IsoDateTime, Reviver, PMapOptions, Mapper, AsyncMapper, Predicate, AsyncPredicate, BatchResult, DeferredPromise, PRetryOptions, PTimeoutOptions, TryCatchOptions, StringifyAnyOptions, JsonStringifyFunction, Merge, ReadonlyDeep, Promisable, PromiseValue, Simplify, ConditionalPick, ConditionalExcept, Class, UnixTimestamp, BaseDBEntity, SavedDBEntity, Saved, Unsaved, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, JsonSchema, JsonSchemaAny, JsonSchemaOneOf, JsonSchemaAllOf, JsonSchemaAnyOf, JsonSchemaNot, JsonSchemaRef, JsonSchemaConst, JsonSchemaEnum, JsonSchemaString, JsonSchemaNumber, JsonSchemaBoolean, JsonSchemaNull, JsonSchemaRootObject, JsonSchemaObject, JsonSchemaArray, JsonSchemaTuple, JsonSchemaBuilder, CommonLogLevel, CommonLogFunction, CommonLogger, };
|
|
61
|
+
export { is, _Memo, _memoFn, _LogMethod, _getArgsSignature, _createPromiseDecorator, AppError, HttpError, AssertionError, _isErrorObject, _isHttpErrorObject, _isHttpErrorResponse, _assert, _assertEquals, _assertDeepEquals, _assertIsError, _assertIsString, _assertIsNumber, _assertTypeOf, _randomInt, _randomArrayItem, _createDeterministicRandom, _inRange, _stringMapValues, _stringMapEntries, _objectKeys, _capitalize, _upperFirst, _lowerFirst, _split, _removeWhitespace, _substringBefore, _substringBeforeLast, _substringAfter, _substringAfterLast, _substringBetweenLast, _replaceAll, _nl2br, _truncate, _truncateMiddle, _pick, _omit, _filterFalsyValues, _filterUndefinedValues, _filterNullishValues, _filterEmptyArrays, _filterEmptyValues, _filterObject, _undefinedIfEmpty, _isObject, _isPrimitive, _mapKeys, _mapValues, _mapObject, _objectNullValuesToUndefined, _deepEquals, _deepCopy, _isEmptyObject, _isEmpty, _merge, _deepTrim, _sortObjectDeep, _sortObject, _get, _set, _has, _unset, _mask, _invert, _invertMap, _by, _groupBy, _sortBy, _sortNumbers, _toFixed, _toPrecision, _round, _findLast, _takeWhile, _takeRightWhile, _dropWhile, _dropRightWhile, _countBy, _intersection, _difference, _shuffle, _mapToObject, _findKeyByValue, _anyToError, _anyToErrorObject, _errorToErrorObject, _errorObjectToAppError, _range, _uniq, _uniqBy, _flatten, _flattenDeep, _chunk, SimpleMovingAverage, _average, _averageWeighted, _percentile, _median, _debounce, _throttle, _Debounce, _Throttle, pMap, _passthroughMapper, _passUndefinedMapper, _passthroughPredicate, _passNothingPredicate, _noop, pBatch, ErrorMode, pFilter, pProps, pDelay, pDefer, pHang, pState, AggregatedError, pRetry, pTimeout, pTuple, _Retry, _Timeout, _tryCatch, _TryCatch, _try, pTry, _jsonParseIfPossible, _stringifyAny, _ms, _since, _hb, _gb, _mb, _kb, _snakeCase, _camelCase, _kebabCase, _sum, _sumBy, _clamp, _last, mergeJsonSchemaObjects, jsonSchema, JsonSchemaAnyBuilder, JSON_SCHEMA_ORDER, generateJsonSchemaFromData, _parseQueryString, _defineLazyProperty, _defineLazyProps, _lazyValue, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, _safeJsonStringify, PQueue, };
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports._isObject = exports._undefinedIfEmpty = exports._filterObject = exports._filterEmptyValues = exports._filterEmptyArrays = exports._filterNullishValues = exports._filterUndefinedValues = exports._filterFalsyValues = exports._omit = exports._pick = exports._truncateMiddle = exports._truncate = exports._nl2br = exports._replaceAll = exports._substringBetweenLast = exports._substringAfterLast = exports._substringAfter = exports._substringBeforeLast = exports._substringBefore = exports._removeWhitespace = exports._split = exports._lowerFirst = exports._upperFirst = exports._capitalize = exports._objectKeys = exports._stringMapEntries = exports._stringMapValues = exports._inRange = exports._createDeterministicRandom = exports._randomArrayItem = exports._randomInt = exports._assertTypeOf = exports._assertIsNumber = exports._assertIsString = exports._assertIsError = exports._assertDeepEquals = exports._assertEquals = exports._assert = exports._isHttpErrorResponse = exports._isHttpErrorObject = exports._isErrorObject = exports.AssertionError = exports.HttpError = exports.AppError = exports._createPromiseDecorator = exports._getArgsSignature = exports._LogMethod = exports._memoFn = exports._Memo = exports.is = void 0;
|
|
4
4
|
exports._average = exports.SimpleMovingAverage = exports._chunk = exports._flattenDeep = exports._flatten = exports._uniqBy = exports._uniq = exports._range = exports._errorObjectToAppError = exports._errorToErrorObject = exports._anyToErrorObject = exports._anyToError = exports._findKeyByValue = exports._mapToObject = exports._shuffle = exports._difference = exports._intersection = exports._countBy = exports._dropRightWhile = exports._dropWhile = exports._takeRightWhile = exports._takeWhile = exports._findLast = exports._round = exports._toPrecision = exports._toFixed = exports._sortNumbers = exports._sortBy = exports._groupBy = exports._by = exports._invertMap = exports._invert = exports._mask = exports._unset = exports._has = exports._set = exports._get = exports._sortObject = exports._sortObjectDeep = exports._deepTrim = exports._merge = exports._isEmpty = exports._isEmptyObject = exports._deepCopy = exports._deepEquals = exports._objectNullValuesToUndefined = exports._mapObject = exports._mapValues = exports._mapKeys = exports._isPrimitive = void 0;
|
|
5
5
|
exports.JSON_SCHEMA_ORDER = exports.JsonSchemaAnyBuilder = exports.jsonSchema = exports.mergeJsonSchemaObjects = exports._last = exports._clamp = exports._sumBy = exports._sum = exports._kebabCase = exports._camelCase = exports._snakeCase = exports._kb = exports._mb = exports._gb = exports._hb = exports._since = exports._ms = exports._stringifyAny = exports._jsonParseIfPossible = exports.pTry = exports._try = exports._TryCatch = exports._tryCatch = exports._Timeout = exports._Retry = exports.pTuple = exports.pTimeout = exports.pRetry = exports.AggregatedError = exports.pState = exports.pHang = exports.pDefer = exports.pDelay = exports.pProps = exports.pFilter = exports.ErrorMode = exports.pBatch = exports._noop = exports._passNothingPredicate = exports._passthroughPredicate = exports._passUndefinedMapper = exports._passthroughMapper = exports.pMap = exports._Throttle = exports._Debounce = exports._throttle = exports._debounce = exports._median = exports._percentile = exports._averageWeighted = void 0;
|
|
6
|
-
exports._safeJsonStringify = exports.commonLoggerPrefix = exports.commonLoggerPipe = exports.commonLogLevelNumber = exports.commonLoggerNoop = exports.commonLoggerMinLevel = exports._lazyValue = exports._defineLazyProps = exports._defineLazyProperty = exports._parseQueryString = exports.generateJsonSchemaFromData = void 0;
|
|
6
|
+
exports.PQueue = exports._safeJsonStringify = exports.commonLoggerPrefix = exports.commonLoggerPipe = exports.commonLogLevelNumber = exports.commonLoggerNoop = exports.commonLoggerMinLevel = exports._lazyValue = exports._defineLazyProps = exports._defineLazyProperty = exports._parseQueryString = exports.generateJsonSchemaFromData = void 0;
|
|
7
7
|
const array_util_1 = require("./array/array.util");
|
|
8
8
|
Object.defineProperty(exports, "_by", { enumerable: true, get: function () { return array_util_1._by; } });
|
|
9
9
|
Object.defineProperty(exports, "_chunk", { enumerable: true, get: function () { return array_util_1._chunk; } });
|
|
@@ -219,3 +219,5 @@ Object.defineProperty(exports, "commonLoggerPipe", { enumerable: true, get: func
|
|
|
219
219
|
Object.defineProperty(exports, "commonLoggerPrefix", { enumerable: true, get: function () { return commonLogger_1.commonLoggerPrefix; } });
|
|
220
220
|
const safeJsonStringify_1 = require("./string/safeJsonStringify");
|
|
221
221
|
Object.defineProperty(exports, "_safeJsonStringify", { enumerable: true, get: function () { return safeJsonStringify_1._safeJsonStringify; } });
|
|
222
|
+
const pQueue_1 = require("./promise/pQueue");
|
|
223
|
+
Object.defineProperty(exports, "PQueue", { enumerable: true, get: function () { return pQueue_1.PQueue; } });
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { ErrorMode } from '../error/errorMode';
|
|
2
|
+
import { CommonLogger } from '../log/commonLogger';
|
|
3
|
+
export interface PQueueCfg {
|
|
4
|
+
concurrency: number;
|
|
5
|
+
/**
|
|
6
|
+
* Default: THROW_IMMEDIATELY
|
|
7
|
+
*
|
|
8
|
+
* THROW_AGGREGATED is not supported.
|
|
9
|
+
*
|
|
10
|
+
* SUPPRESS_ERRORS will still log errors via logger. It will resolve the `.push` promise with void.
|
|
11
|
+
*/
|
|
12
|
+
errorMode?: ErrorMode;
|
|
13
|
+
/**
|
|
14
|
+
* @default true
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Default to `console`
|
|
18
|
+
*/
|
|
19
|
+
logger?: CommonLogger;
|
|
20
|
+
/**
|
|
21
|
+
* If true - will LOG EVERYTHING:)
|
|
22
|
+
*/
|
|
23
|
+
debug?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* By default .push method resolves when the Promise is done (finished).
|
|
26
|
+
*
|
|
27
|
+
* If you set resolveOn = 'start' - .push method will resolve the Promise (with void) upon
|
|
28
|
+
* the START of the processing.
|
|
29
|
+
*
|
|
30
|
+
* @default finish
|
|
31
|
+
*/
|
|
32
|
+
resolveOn?: 'finish' | 'start';
|
|
33
|
+
}
|
|
34
|
+
export declare type PromiseReturningFunction<R> = () => Promise<R>;
|
|
35
|
+
/**
|
|
36
|
+
* Inspired by: https://github.com/sindresorhus/p-queue
|
|
37
|
+
*
|
|
38
|
+
* Allows to push "jobs" to the queue and control its concurrency.
|
|
39
|
+
* Jobs are "promise-returning functions".
|
|
40
|
+
*
|
|
41
|
+
* API is @experimental
|
|
42
|
+
*/
|
|
43
|
+
export declare class PQueue {
|
|
44
|
+
constructor(cfg: PQueueCfg);
|
|
45
|
+
private readonly cfg;
|
|
46
|
+
private debug;
|
|
47
|
+
inFlight: number;
|
|
48
|
+
private queue;
|
|
49
|
+
private onIdleListeners;
|
|
50
|
+
get queueSize(): number;
|
|
51
|
+
/**
|
|
52
|
+
* Returns a Promise that resolves when the queue is Idle (next time, since the call).
|
|
53
|
+
* Resolves immediately in case the queue is Idle.
|
|
54
|
+
* Idle means 0 queue and 0 inFlight.
|
|
55
|
+
*/
|
|
56
|
+
onIdle(): Promise<void>;
|
|
57
|
+
/**
|
|
58
|
+
* Push PromiseReturningFunction to the Queue.
|
|
59
|
+
* Returns a Promise that resolves (or rejects) with the return value from the Promise.
|
|
60
|
+
*/
|
|
61
|
+
push<R>(fn_: PromiseReturningFunction<R>): Promise<R>;
|
|
62
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PQueue = void 0;
|
|
4
|
+
const errorMode_1 = require("../error/errorMode");
|
|
5
|
+
const pDefer_1 = require("./pDefer");
|
|
6
|
+
/**
|
|
7
|
+
* Inspired by: https://github.com/sindresorhus/p-queue
|
|
8
|
+
*
|
|
9
|
+
* Allows to push "jobs" to the queue and control its concurrency.
|
|
10
|
+
* Jobs are "promise-returning functions".
|
|
11
|
+
*
|
|
12
|
+
* API is @experimental
|
|
13
|
+
*/
|
|
14
|
+
class PQueue {
|
|
15
|
+
constructor(cfg) {
|
|
16
|
+
this.inFlight = 0;
|
|
17
|
+
this.queue = [];
|
|
18
|
+
this.onIdleListeners = [];
|
|
19
|
+
this.cfg = {
|
|
20
|
+
// concurrency: Number.MAX_SAFE_INTEGER,
|
|
21
|
+
errorMode: errorMode_1.ErrorMode.THROW_IMMEDIATELY,
|
|
22
|
+
logger: console,
|
|
23
|
+
debug: false,
|
|
24
|
+
resolveOn: 'finish',
|
|
25
|
+
...cfg,
|
|
26
|
+
};
|
|
27
|
+
if (!cfg.debug) {
|
|
28
|
+
this.debug = () => { };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
debug(...args) {
|
|
32
|
+
this.cfg.logger.log(...args);
|
|
33
|
+
}
|
|
34
|
+
get queueSize() {
|
|
35
|
+
return this.queue.length;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Returns a Promise that resolves when the queue is Idle (next time, since the call).
|
|
39
|
+
* Resolves immediately in case the queue is Idle.
|
|
40
|
+
* Idle means 0 queue and 0 inFlight.
|
|
41
|
+
*/
|
|
42
|
+
onIdle() {
|
|
43
|
+
if (this.queue.length === 0 && this.inFlight === 0)
|
|
44
|
+
return Promise.resolve();
|
|
45
|
+
const listener = (0, pDefer_1.pDefer)();
|
|
46
|
+
this.onIdleListeners.push(listener);
|
|
47
|
+
return listener;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Push PromiseReturningFunction to the Queue.
|
|
51
|
+
* Returns a Promise that resolves (or rejects) with the return value from the Promise.
|
|
52
|
+
*/
|
|
53
|
+
push(fn_) {
|
|
54
|
+
const { concurrency } = this.cfg;
|
|
55
|
+
const resolveOnStart = this.cfg.resolveOn === 'start';
|
|
56
|
+
const fn = fn_;
|
|
57
|
+
fn.defer || (fn.defer = (0, pDefer_1.pDefer)());
|
|
58
|
+
if (this.inFlight < concurrency) {
|
|
59
|
+
// There is room for more jobs. Can start immediately
|
|
60
|
+
this.inFlight++;
|
|
61
|
+
this.debug(`inFlight++ ${this.inFlight}/${concurrency}, queue ${this.queue.length}`);
|
|
62
|
+
if (resolveOnStart)
|
|
63
|
+
fn.defer.resolve();
|
|
64
|
+
fn()
|
|
65
|
+
.then(result => {
|
|
66
|
+
if (!resolveOnStart)
|
|
67
|
+
fn.defer.resolve(result);
|
|
68
|
+
})
|
|
69
|
+
.catch(err => {
|
|
70
|
+
this.cfg.logger.error(err);
|
|
71
|
+
if (resolveOnStart)
|
|
72
|
+
return;
|
|
73
|
+
if (this.cfg.errorMode === errorMode_1.ErrorMode.SUPPRESS) {
|
|
74
|
+
fn.defer.resolve(); // resolve with `void`
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
// Should be handled on the outside, otherwise it'll cause UnhandledRejection
|
|
78
|
+
fn.defer.reject(err);
|
|
79
|
+
}
|
|
80
|
+
})
|
|
81
|
+
.finally(() => {
|
|
82
|
+
this.inFlight--;
|
|
83
|
+
this.debug(`inFlight-- ${this.inFlight}/${concurrency}, queue ${this.queue.length}`);
|
|
84
|
+
// check if there's room to start next job
|
|
85
|
+
if (this.queue.length && this.inFlight <= concurrency) {
|
|
86
|
+
const nextFn = this.queue.shift();
|
|
87
|
+
void this.push(nextFn);
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
if (this.inFlight === 0) {
|
|
91
|
+
this.debug('onIdle');
|
|
92
|
+
this.onIdleListeners.forEach(defer => defer.resolve());
|
|
93
|
+
this.onIdleListeners.length = 0; // empty the array
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
this.queue.push(fn);
|
|
100
|
+
this.debug(`inFlight ${this.inFlight}/${concurrency}, queue++ ${this.queue.length}`);
|
|
101
|
+
}
|
|
102
|
+
return fn.defer;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
exports.PQueue = PQueue;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { AnyFunction } from '../types';
|
|
1
2
|
export interface PTimeoutOptions {
|
|
2
3
|
/**
|
|
3
4
|
* Timeout in milliseconds.
|
|
@@ -19,4 +20,4 @@ export interface PTimeoutOptions {
|
|
|
19
20
|
* Throws an Error if the Function is not resolved in a certain time.
|
|
20
21
|
* If the Function rejects - passes this rejection further.
|
|
21
22
|
*/
|
|
22
|
-
export declare function pTimeout<T extends
|
|
23
|
+
export declare function pTimeout<T extends AnyFunction>(fn: T, opt: PTimeoutOptions): T;
|
package/dist/promise/pTimeout.js
CHANGED
|
@@ -6,7 +6,6 @@ exports.pTimeout = void 0;
|
|
|
6
6
|
* Throws an Error if the Function is not resolved in a certain time.
|
|
7
7
|
* If the Function rejects - passes this rejection further.
|
|
8
8
|
*/
|
|
9
|
-
// eslint-disable-next-line @typescript-eslint/ban-types
|
|
10
9
|
function pTimeout(fn, opt) {
|
|
11
10
|
// const fname = fn.name || 'function'
|
|
12
11
|
const { timeout, name, onTimeout } = opt;
|
package/dist-esm/index.js
CHANGED
|
@@ -52,4 +52,5 @@ import { _gb, _hb, _kb, _mb } from './unit/size.util';
|
|
|
52
52
|
import { is } from './vendor/is';
|
|
53
53
|
import { commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, } from './log/commonLogger';
|
|
54
54
|
import { _safeJsonStringify } from './string/safeJsonStringify';
|
|
55
|
-
|
|
55
|
+
import { PQueue } from './promise/pQueue';
|
|
56
|
+
export { is, _Memo, _memoFn, _LogMethod, _getArgsSignature, _createPromiseDecorator, AppError, HttpError, AssertionError, _isErrorObject, _isHttpErrorObject, _isHttpErrorResponse, _assert, _assertEquals, _assertDeepEquals, _assertIsError, _assertIsString, _assertIsNumber, _assertTypeOf, _randomInt, _randomArrayItem, _createDeterministicRandom, _inRange, _stringMapValues, _stringMapEntries, _objectKeys, _capitalize, _upperFirst, _lowerFirst, _split, _removeWhitespace, _substringBefore, _substringBeforeLast, _substringAfter, _substringAfterLast, _substringBetweenLast, _replaceAll, _nl2br, _truncate, _truncateMiddle, _pick, _omit, _filterFalsyValues, _filterUndefinedValues, _filterNullishValues, _filterEmptyArrays, _filterEmptyValues, _filterObject, _undefinedIfEmpty, _isObject, _isPrimitive, _mapKeys, _mapValues, _mapObject, _objectNullValuesToUndefined, _deepEquals, _deepCopy, _isEmptyObject, _isEmpty, _merge, _deepTrim, _sortObjectDeep, _sortObject, _get, _set, _has, _unset, _mask, _invert, _invertMap, _by, _groupBy, _sortBy, _sortNumbers, _toFixed, _toPrecision, _round, _findLast, _takeWhile, _takeRightWhile, _dropWhile, _dropRightWhile, _countBy, _intersection, _difference, _shuffle, _mapToObject, _findKeyByValue, _anyToError, _anyToErrorObject, _errorToErrorObject, _errorObjectToAppError, _range, _uniq, _uniqBy, _flatten, _flattenDeep, _chunk, SimpleMovingAverage, _average, _averageWeighted, _percentile, _median, _debounce, _throttle, _Debounce, _Throttle, pMap, _passthroughMapper, _passUndefinedMapper, _passthroughPredicate, _passNothingPredicate, _noop, pBatch, ErrorMode, pFilter, pProps, pDelay, pDefer, pHang, pState, AggregatedError, pRetry, pTimeout, pTuple, _Retry, _Timeout, _tryCatch, _TryCatch, _try, pTry, _jsonParseIfPossible, _stringifyAny, _ms, _since, _hb, _gb, _mb, _kb, _snakeCase, _camelCase, _kebabCase, _sum, _sumBy, _clamp, _last, mergeJsonSchemaObjects, jsonSchema, JsonSchemaAnyBuilder, JSON_SCHEMA_ORDER, generateJsonSchemaFromData, _parseQueryString, _defineLazyProperty, _defineLazyProps, _lazyValue, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, _safeJsonStringify, PQueue, };
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { ErrorMode } from '../error/errorMode';
|
|
2
|
+
import { pDefer } from './pDefer';
|
|
3
|
+
/**
|
|
4
|
+
* Inspired by: https://github.com/sindresorhus/p-queue
|
|
5
|
+
*
|
|
6
|
+
* Allows to push "jobs" to the queue and control its concurrency.
|
|
7
|
+
* Jobs are "promise-returning functions".
|
|
8
|
+
*
|
|
9
|
+
* API is @experimental
|
|
10
|
+
*/
|
|
11
|
+
export class PQueue {
|
|
12
|
+
constructor(cfg) {
|
|
13
|
+
this.inFlight = 0;
|
|
14
|
+
this.queue = [];
|
|
15
|
+
this.onIdleListeners = [];
|
|
16
|
+
this.cfg = Object.assign({
|
|
17
|
+
// concurrency: Number.MAX_SAFE_INTEGER,
|
|
18
|
+
errorMode: ErrorMode.THROW_IMMEDIATELY, logger: console, debug: false, resolveOn: 'finish' }, cfg);
|
|
19
|
+
if (!cfg.debug) {
|
|
20
|
+
this.debug = () => { };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
debug(...args) {
|
|
24
|
+
this.cfg.logger.log(...args);
|
|
25
|
+
}
|
|
26
|
+
get queueSize() {
|
|
27
|
+
return this.queue.length;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Returns a Promise that resolves when the queue is Idle (next time, since the call).
|
|
31
|
+
* Resolves immediately in case the queue is Idle.
|
|
32
|
+
* Idle means 0 queue and 0 inFlight.
|
|
33
|
+
*/
|
|
34
|
+
onIdle() {
|
|
35
|
+
if (this.queue.length === 0 && this.inFlight === 0)
|
|
36
|
+
return Promise.resolve();
|
|
37
|
+
const listener = pDefer();
|
|
38
|
+
this.onIdleListeners.push(listener);
|
|
39
|
+
return listener;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Push PromiseReturningFunction to the Queue.
|
|
43
|
+
* Returns a Promise that resolves (or rejects) with the return value from the Promise.
|
|
44
|
+
*/
|
|
45
|
+
push(fn_) {
|
|
46
|
+
const { concurrency } = this.cfg;
|
|
47
|
+
const resolveOnStart = this.cfg.resolveOn === 'start';
|
|
48
|
+
const fn = fn_;
|
|
49
|
+
fn.defer || (fn.defer = pDefer());
|
|
50
|
+
if (this.inFlight < concurrency) {
|
|
51
|
+
// There is room for more jobs. Can start immediately
|
|
52
|
+
this.inFlight++;
|
|
53
|
+
this.debug(`inFlight++ ${this.inFlight}/${concurrency}, queue ${this.queue.length}`);
|
|
54
|
+
if (resolveOnStart)
|
|
55
|
+
fn.defer.resolve();
|
|
56
|
+
fn()
|
|
57
|
+
.then(result => {
|
|
58
|
+
if (!resolveOnStart)
|
|
59
|
+
fn.defer.resolve(result);
|
|
60
|
+
})
|
|
61
|
+
.catch(err => {
|
|
62
|
+
this.cfg.logger.error(err);
|
|
63
|
+
if (resolveOnStart)
|
|
64
|
+
return;
|
|
65
|
+
if (this.cfg.errorMode === ErrorMode.SUPPRESS) {
|
|
66
|
+
fn.defer.resolve(); // resolve with `void`
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
// Should be handled on the outside, otherwise it'll cause UnhandledRejection
|
|
70
|
+
fn.defer.reject(err);
|
|
71
|
+
}
|
|
72
|
+
})
|
|
73
|
+
.finally(() => {
|
|
74
|
+
this.inFlight--;
|
|
75
|
+
this.debug(`inFlight-- ${this.inFlight}/${concurrency}, queue ${this.queue.length}`);
|
|
76
|
+
// check if there's room to start next job
|
|
77
|
+
if (this.queue.length && this.inFlight <= concurrency) {
|
|
78
|
+
const nextFn = this.queue.shift();
|
|
79
|
+
void this.push(nextFn);
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
if (this.inFlight === 0) {
|
|
83
|
+
this.debug('onIdle');
|
|
84
|
+
this.onIdleListeners.forEach(defer => defer.resolve());
|
|
85
|
+
this.onIdleListeners.length = 0; // empty the array
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
this.queue.push(fn);
|
|
92
|
+
this.debug(`inFlight ${this.inFlight}/${concurrency}, queue++ ${this.queue.length}`);
|
|
93
|
+
}
|
|
94
|
+
return fn.defer;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
* Throws an Error if the Function is not resolved in a certain time.
|
|
4
4
|
* If the Function rejects - passes this rejection further.
|
|
5
5
|
*/
|
|
6
|
-
// eslint-disable-next-line @typescript-eslint/ban-types
|
|
7
6
|
export function pTimeout(fn, opt) {
|
|
8
7
|
// const fname = fn.name || 'function'
|
|
9
8
|
const { timeout, name, onTimeout } = opt;
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -235,8 +235,10 @@ import {
|
|
|
235
235
|
commonLoggerPrefix,
|
|
236
236
|
} from './log/commonLogger'
|
|
237
237
|
import { _safeJsonStringify } from './string/safeJsonStringify'
|
|
238
|
+
import { PQueue, PQueueCfg } from './promise/pQueue'
|
|
238
239
|
|
|
239
240
|
export type {
|
|
241
|
+
PQueueCfg,
|
|
240
242
|
MemoCache,
|
|
241
243
|
PromiseDecoratorCfg,
|
|
242
244
|
PromiseDecoratorResp,
|
|
@@ -473,4 +475,5 @@ export {
|
|
|
473
475
|
commonLoggerPipe,
|
|
474
476
|
commonLoggerPrefix,
|
|
475
477
|
_safeJsonStringify,
|
|
478
|
+
PQueue,
|
|
476
479
|
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { ErrorMode } from '../error/errorMode'
|
|
2
|
+
import { CommonLogger } from '../log/commonLogger'
|
|
3
|
+
import { DeferredPromise, pDefer } from './pDefer'
|
|
4
|
+
|
|
5
|
+
export interface PQueueCfg {
|
|
6
|
+
concurrency: number
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Default: THROW_IMMEDIATELY
|
|
10
|
+
*
|
|
11
|
+
* THROW_AGGREGATED is not supported.
|
|
12
|
+
*
|
|
13
|
+
* SUPPRESS_ERRORS will still log errors via logger. It will resolve the `.push` promise with void.
|
|
14
|
+
*/
|
|
15
|
+
errorMode?: ErrorMode
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @default true
|
|
19
|
+
*/
|
|
20
|
+
// autoStart?: boolean
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Default to `console`
|
|
24
|
+
*/
|
|
25
|
+
logger?: CommonLogger
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* If true - will LOG EVERYTHING:)
|
|
29
|
+
*/
|
|
30
|
+
debug?: boolean
|
|
31
|
+
|
|
32
|
+
// logStatusChange?: boolean
|
|
33
|
+
// logSizeChange?: boolean
|
|
34
|
+
|
|
35
|
+
// timeout
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* By default .push method resolves when the Promise is done (finished).
|
|
39
|
+
*
|
|
40
|
+
* If you set resolveOn = 'start' - .push method will resolve the Promise (with void) upon
|
|
41
|
+
* the START of the processing.
|
|
42
|
+
*
|
|
43
|
+
* @default finish
|
|
44
|
+
*/
|
|
45
|
+
resolveOn?: 'finish' | 'start'
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type PromiseReturningFunction<R> = () => Promise<R>
|
|
49
|
+
|
|
50
|
+
interface PromiseReturningFunctionWithDefer<R> extends PromiseReturningFunction<R> {
|
|
51
|
+
defer: DeferredPromise<R>
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Inspired by: https://github.com/sindresorhus/p-queue
|
|
56
|
+
*
|
|
57
|
+
* Allows to push "jobs" to the queue and control its concurrency.
|
|
58
|
+
* Jobs are "promise-returning functions".
|
|
59
|
+
*
|
|
60
|
+
* API is @experimental
|
|
61
|
+
*/
|
|
62
|
+
export class PQueue {
|
|
63
|
+
constructor(cfg: PQueueCfg) {
|
|
64
|
+
this.cfg = {
|
|
65
|
+
// concurrency: Number.MAX_SAFE_INTEGER,
|
|
66
|
+
errorMode: ErrorMode.THROW_IMMEDIATELY,
|
|
67
|
+
logger: console,
|
|
68
|
+
debug: false,
|
|
69
|
+
resolveOn: 'finish',
|
|
70
|
+
...cfg,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (!cfg.debug) {
|
|
74
|
+
this.debug = () => {}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private readonly cfg: Required<PQueueCfg>
|
|
79
|
+
|
|
80
|
+
private debug(...args: any[]): void {
|
|
81
|
+
this.cfg.logger.log(...args)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
inFlight = 0
|
|
85
|
+
private queue: PromiseReturningFunction<any>[] = []
|
|
86
|
+
private onIdleListeners: DeferredPromise[] = []
|
|
87
|
+
|
|
88
|
+
get queueSize(): number {
|
|
89
|
+
return this.queue.length
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Returns a Promise that resolves when the queue is Idle (next time, since the call).
|
|
94
|
+
* Resolves immediately in case the queue is Idle.
|
|
95
|
+
* Idle means 0 queue and 0 inFlight.
|
|
96
|
+
*/
|
|
97
|
+
onIdle(): Promise<void> {
|
|
98
|
+
if (this.queue.length === 0 && this.inFlight === 0) return Promise.resolve()
|
|
99
|
+
|
|
100
|
+
const listener = pDefer()
|
|
101
|
+
this.onIdleListeners.push(listener)
|
|
102
|
+
return listener
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Push PromiseReturningFunction to the Queue.
|
|
107
|
+
* Returns a Promise that resolves (or rejects) with the return value from the Promise.
|
|
108
|
+
*/
|
|
109
|
+
push<R>(fn_: PromiseReturningFunction<R>): Promise<R> {
|
|
110
|
+
const { concurrency } = this.cfg
|
|
111
|
+
const resolveOnStart = this.cfg.resolveOn === 'start'
|
|
112
|
+
|
|
113
|
+
const fn = fn_ as PromiseReturningFunctionWithDefer<R>
|
|
114
|
+
fn.defer ||= pDefer<R>()
|
|
115
|
+
|
|
116
|
+
if (this.inFlight < concurrency) {
|
|
117
|
+
// There is room for more jobs. Can start immediately
|
|
118
|
+
this.inFlight++
|
|
119
|
+
this.debug(`inFlight++ ${this.inFlight}/${concurrency}, queue ${this.queue.length}`)
|
|
120
|
+
if (resolveOnStart) fn.defer.resolve()
|
|
121
|
+
|
|
122
|
+
fn()
|
|
123
|
+
.then(result => {
|
|
124
|
+
if (!resolveOnStart) fn.defer.resolve(result)
|
|
125
|
+
})
|
|
126
|
+
.catch(err => {
|
|
127
|
+
this.cfg.logger.error(err)
|
|
128
|
+
if (resolveOnStart) return
|
|
129
|
+
|
|
130
|
+
if (this.cfg.errorMode === ErrorMode.SUPPRESS) {
|
|
131
|
+
fn.defer.resolve() // resolve with `void`
|
|
132
|
+
} else {
|
|
133
|
+
// Should be handled on the outside, otherwise it'll cause UnhandledRejection
|
|
134
|
+
fn.defer.reject(err)
|
|
135
|
+
}
|
|
136
|
+
})
|
|
137
|
+
.finally(() => {
|
|
138
|
+
this.inFlight--
|
|
139
|
+
this.debug(`inFlight-- ${this.inFlight}/${concurrency}, queue ${this.queue.length}`)
|
|
140
|
+
|
|
141
|
+
// check if there's room to start next job
|
|
142
|
+
if (this.queue.length && this.inFlight <= concurrency) {
|
|
143
|
+
const nextFn = this.queue.shift()!
|
|
144
|
+
void this.push(nextFn)
|
|
145
|
+
} else {
|
|
146
|
+
if (this.inFlight === 0) {
|
|
147
|
+
this.debug('onIdle')
|
|
148
|
+
this.onIdleListeners.forEach(defer => defer.resolve())
|
|
149
|
+
this.onIdleListeners.length = 0 // empty the array
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
})
|
|
153
|
+
} else {
|
|
154
|
+
this.queue.push(fn)
|
|
155
|
+
this.debug(`inFlight ${this.inFlight}/${concurrency}, queue++ ${this.queue.length}`)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return fn.defer
|
|
159
|
+
}
|
|
160
|
+
}
|
package/src/promise/pTimeout.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { AnyFunction } from '../types'
|
|
2
|
+
|
|
1
3
|
export interface PTimeoutOptions {
|
|
2
4
|
/**
|
|
3
5
|
* Timeout in milliseconds.
|
|
@@ -22,8 +24,7 @@ export interface PTimeoutOptions {
|
|
|
22
24
|
* Throws an Error if the Function is not resolved in a certain time.
|
|
23
25
|
* If the Function rejects - passes this rejection further.
|
|
24
26
|
*/
|
|
25
|
-
|
|
26
|
-
export function pTimeout<T extends Function>(fn: T, opt: PTimeoutOptions): T {
|
|
27
|
+
export function pTimeout<T extends AnyFunction>(fn: T, opt: PTimeoutOptions): T {
|
|
27
28
|
// const fname = fn.name || 'function'
|
|
28
29
|
const { timeout, name, onTimeout } = opt
|
|
29
30
|
|