@naturalcycles/js-lib 14.79.0 → 14.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import { _since, _stringifyAny, AnyFunction, CommonLogger } from '..'
2
+ import { TimeoutError } from './pTimeout'
2
3
 
3
4
  export interface PRetryOptions {
4
5
  /**
@@ -7,6 +8,13 @@ export interface PRetryOptions {
7
8
  */
8
9
  name?: string
9
10
 
11
+ /**
12
+ * Timeout for each Try, in milliseconds.
13
+ *
14
+ * Defaults to no timeout.
15
+ */
16
+ timeout?: number
17
+
10
18
  /**
11
19
  * How many attempts to try.
12
20
  * First attempt is not a retry, but "initial try". It still counts.
@@ -34,7 +42,7 @@ export interface PRetryOptions {
34
42
  *
35
43
  * @default () => true
36
44
  */
37
- predicate?: (err: unknown, attempt: number, maxAttempts: number) => boolean
45
+ predicate?: (err: Error, attempt: number, maxAttempts: number) => boolean
38
46
 
39
47
  /**
40
48
  * Log the first attempt (which is not a "retry" yet).
@@ -74,76 +82,132 @@ export interface PRetryOptions {
74
82
  * Default to `console`
75
83
  */
76
84
  logger?: CommonLogger
85
+
86
+ /**
87
+ * Defaults to true.
88
+ * If true - preserves the stack trace in case of a Timeout (usually - very useful!).
89
+ * It has a certain perf cost.
90
+ *
91
+ * @experimental
92
+ */
93
+ keepStackTrace?: boolean
77
94
  }
78
95
 
79
96
  /**
80
97
  * Returns a Function (!), enhanced with retry capabilities.
81
98
  * Implements "Exponential back-off strategy" by multiplying the delay by `delayMultiplier` with each try.
82
99
  */
83
- // eslint-disable-next-line @typescript-eslint/ban-types
84
- export function pRetry<T extends AnyFunction>(fn: T, opt: PRetryOptions = {}): T {
100
+ export function pRetryFn<T extends AnyFunction>(fn: T, opt: PRetryOptions = {}): T {
101
+ return async function pRetryFunction(this: any, ...args: any[]) {
102
+ return await pRetry(() => fn.call(this, ...args), opt)
103
+ } as any
104
+ }
105
+
106
+ export async function pRetry<T>(
107
+ fn: (attempt: number) => Promise<T>,
108
+ opt: PRetryOptions = {},
109
+ ): Promise<T> {
85
110
  const {
86
111
  maxAttempts = 4,
87
112
  delay: initialDelay = 1000,
88
113
  delayMultiplier = 2,
89
114
  predicate,
90
115
  logger = console,
91
- name = fn.name,
116
+ name,
117
+ keepStackTrace = true,
118
+ timeout,
92
119
  } = opt
93
120
 
121
+ const fakeError = keepStackTrace ? new Error('RetryError') : undefined
122
+
94
123
  let { logFirstAttempt = false, logRetries = true, logFailures = false, logSuccess = false } = opt
95
124
 
96
125
  if (opt.logAll) {
97
- logFirstAttempt = logRetries = logFailures = true
126
+ logSuccess = logFirstAttempt = logRetries = logFailures = true
98
127
  }
99
128
  if (opt.logNone) {
100
129
  logSuccess = logFirstAttempt = logRetries = logFailures = false
101
130
  }
102
131
 
103
- const fname = ['pRetry', name].filter(Boolean).join('.')
132
+ const fname = name || fn.name || 'pRetry function'
104
133
 
105
- return async function (this: any, ...args: any[]) {
106
- let delay = initialDelay
107
- let attempt = 0
134
+ let delay = initialDelay
135
+ let attempt = 0
136
+ let timer: NodeJS.Timeout | undefined
137
+ let timedOut = false
108
138
 
109
- return await new Promise((resolve, reject) => {
110
- const next = async () => {
111
- const started = Date.now()
139
+ return await new Promise((resolve, reject) => {
140
+ const rejectWithTimeout = () => {
141
+ timedOut = true // to prevent more tries
142
+ const err = new TimeoutError(`"${fname}" timed out after ${timeout} ms`)
143
+ if (fakeError) {
144
+ // keep original stack
145
+ err.stack = fakeError.stack!.replace('Error: RetryError', 'TimeoutError')
146
+ }
147
+ reject(err)
148
+ }
112
149
 
113
- try {
114
- attempt++
115
- if ((attempt === 1 && logFirstAttempt) || (attempt > 1 && logRetries)) {
116
- logger.log(`${fname} attempt #${attempt}...`)
117
- }
150
+ const next = async () => {
151
+ if (timedOut) return
118
152
 
119
- const r = await fn.apply(this, args)
153
+ if (timeout) {
154
+ timer = setTimeout(rejectWithTimeout, timeout)
155
+ }
120
156
 
121
- if (logSuccess) {
122
- logger.log(`${fname} attempt #${attempt} succeeded in ${_since(started)}`)
123
- }
124
- resolve(r)
125
- } catch (err) {
126
- if (logFailures) {
127
- logger.warn(
128
- `${fname} attempt #${attempt} error in ${_since(started)}:`,
129
- _stringifyAny(err, {
130
- includeErrorData: true,
131
- }),
132
- )
133
- }
157
+ const started = Date.now()
158
+
159
+ try {
160
+ attempt++
161
+ if ((attempt === 1 && logFirstAttempt) || (attempt > 1 && logRetries)) {
162
+ logger.log(`${fname} attempt #${attempt}...`)
163
+ }
164
+
165
+ const r = await fn(attempt)
166
+
167
+ clearTimeout(timer!)
134
168
 
135
- if (attempt >= maxAttempts || (predicate && !predicate(err, attempt, maxAttempts))) {
136
- // Give up
137
- reject(err)
138
- } else {
139
- // Retry after delay
140
- delay *= delayMultiplier
141
- setTimeout(next, delay)
169
+ if (logSuccess) {
170
+ logger.log(`${fname} attempt #${attempt} succeeded in ${_since(started)}`)
171
+ }
172
+
173
+ resolve(r)
174
+ } catch (err) {
175
+ clearTimeout(timer!)
176
+
177
+ if (logFailures) {
178
+ logger.warn(
179
+ `${fname} attempt #${attempt} error in ${_since(started)}:`,
180
+ _stringifyAny(err, {
181
+ includeErrorData: true,
182
+ }),
183
+ )
184
+ }
185
+
186
+ if (
187
+ attempt >= maxAttempts ||
188
+ (predicate && !predicate(err as Error, attempt, maxAttempts))
189
+ ) {
190
+ // Give up
191
+
192
+ if (fakeError) {
193
+ // Preserve the original call stack
194
+ Object.defineProperty(err, 'stack', {
195
+ value:
196
+ (err as Error).stack +
197
+ '\n --' +
198
+ fakeError.stack!.replace('Error: RetryError', ''),
199
+ })
142
200
  }
201
+
202
+ reject(err)
203
+ } else {
204
+ // Retry after delay
205
+ delay *= delayMultiplier
206
+ setTimeout(next, delay)
143
207
  }
144
208
  }
209
+ }
145
210
 
146
- void next()
147
- })
148
- } as any
211
+ void next()
212
+ })
149
213
  }
package/src/types.ts CHANGED
@@ -29,15 +29,15 @@ export interface CreatedUpdated {
29
29
  updated: number
30
30
  }
31
31
 
32
- export interface CreatedUpdatedId extends CreatedUpdated {
33
- id: string
32
+ export interface CreatedUpdatedId<ID = string> extends CreatedUpdated {
33
+ id: ID
34
34
  }
35
35
 
36
- export interface ObjectWithId {
37
- id: string
36
+ export interface ObjectWithId<ID = string> {
37
+ id: ID
38
38
  }
39
39
 
40
- export interface AnyObjectWithId extends AnyObject, ObjectWithId {}
40
+ export interface AnyObjectWithId<ID = string> extends AnyObject, ObjectWithId<ID> {}
41
41
 
42
42
  /**
43
43
  * Convenience type shorthand.
@@ -169,8 +169,8 @@ export type UnixTimestamp = number
169
169
  /**
170
170
  * Base interface for any Entity that was saved to DB.
171
171
  */
172
- export interface SavedDBEntity {
173
- id: string
172
+ export interface SavedDBEntity<ID = string> {
173
+ id: ID
174
174
 
175
175
  /**
176
176
  * unixTimestamp of when the entity was first created (in the DB).
@@ -189,10 +189,10 @@ export interface SavedDBEntity {
189
189
  * hence `id`, `created` and `updated` fields CAN BE undefined (yet).
190
190
  * When it's known to be saved - `SavedDBEntity` interface can be used instead.
191
191
  */
192
- export type BaseDBEntity = Partial<SavedDBEntity>
192
+ export type BaseDBEntity<ID = string> = Partial<SavedDBEntity<ID>>
193
193
 
194
- export type Saved<E> = Merge<E, SavedDBEntity>
195
- export type Unsaved<E> = Merge<E, BaseDBEntity>
194
+ export type Saved<E, ID = string> = Merge<E, SavedDBEntity<ID>>
195
+ export type Unsaved<E, ID = string> = Merge<E, BaseDBEntity<ID>>
196
196
 
197
197
  /**
198
198
  * Named type for JSON.parse / JSON.stringify second argument
@@ -1,7 +0,0 @@
1
- import { AbortableAsyncMapper, BatchResult } from '..';
2
- /**
3
- * Like pMap, but doesn't fail on errors, instead returns both successful results and errors.
4
- */
5
- export declare function pBatch<IN, OUT>(iterable: Iterable<IN | PromiseLike<IN>>, mapper: AbortableAsyncMapper<IN, OUT>, opt?: {
6
- concurrency?: number;
7
- }): Promise<BatchResult<OUT>>;
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.pBatch = void 0;
4
- const __1 = require("..");
5
- const pMap_1 = require("./pMap");
6
- /**
7
- * Like pMap, but doesn't fail on errors, instead returns both successful results and errors.
8
- */
9
- async function pBatch(iterable, mapper, opt) {
10
- try {
11
- const results = await (0, pMap_1.pMap)(iterable, mapper, {
12
- ...opt,
13
- errorMode: __1.ErrorMode.THROW_AGGREGATED,
14
- });
15
- return {
16
- results,
17
- errors: [],
18
- };
19
- }
20
- catch (err) {
21
- const { errors, results } = err;
22
- if (!errors || !results)
23
- throw err; // not an AggregatedError
24
- return {
25
- results,
26
- errors,
27
- };
28
- }
29
- }
30
- exports.pBatch = pBatch;
@@ -1,23 +0,0 @@
1
- import { ErrorMode } from '..';
2
- import { pMap } from './pMap';
3
- /**
4
- * Like pMap, but doesn't fail on errors, instead returns both successful results and errors.
5
- */
6
- export async function pBatch(iterable, mapper, opt) {
7
- try {
8
- const results = await pMap(iterable, mapper, Object.assign(Object.assign({}, opt), { errorMode: ErrorMode.THROW_AGGREGATED }));
9
- return {
10
- results,
11
- errors: [],
12
- };
13
- }
14
- catch (err) {
15
- const { errors, results } = err;
16
- if (!errors || !results)
17
- throw err; // not an AggregatedError
18
- return {
19
- results,
20
- errors,
21
- };
22
- }
23
- }
@@ -1,31 +0,0 @@
1
- import { AbortableAsyncMapper, BatchResult, ErrorMode } from '..'
2
- import { AggregatedError } from './AggregatedError'
3
- import { pMap } from './pMap'
4
-
5
- /**
6
- * Like pMap, but doesn't fail on errors, instead returns both successful results and errors.
7
- */
8
- export async function pBatch<IN, OUT>(
9
- iterable: Iterable<IN | PromiseLike<IN>>,
10
- mapper: AbortableAsyncMapper<IN, OUT>,
11
- opt?: { concurrency?: number },
12
- ): Promise<BatchResult<OUT>> {
13
- try {
14
- const results = await pMap(iterable, mapper, {
15
- ...opt,
16
- errorMode: ErrorMode.THROW_AGGREGATED,
17
- })
18
- return {
19
- results,
20
- errors: [],
21
- }
22
- } catch (err) {
23
- const { errors, results } = err as AggregatedError<OUT>
24
- if (!errors || !results) throw err // not an AggregatedError
25
-
26
- return {
27
- results,
28
- errors,
29
- }
30
- }
31
- }