@aws-amplify/core 4.7.6 → 4.7.7-ds-allow-applicable-data.6

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.
Files changed (38) hide show
  1. package/dist/aws-amplify-core.js +718 -64
  2. package/dist/aws-amplify-core.js.map +1 -1
  3. package/dist/aws-amplify-core.min.js +4 -4
  4. package/dist/aws-amplify-core.min.js.map +1 -1
  5. package/lib/Credentials.d.ts +1 -1
  6. package/lib/Credentials.js +1 -1
  7. package/lib/Credentials.js.map +1 -1
  8. package/lib/Platform/version.d.ts +1 -1
  9. package/lib/Platform/version.js +1 -1
  10. package/lib/Util/BackgroundProcessManager.d.ts +178 -0
  11. package/lib/Util/BackgroundProcessManager.js +385 -0
  12. package/lib/Util/BackgroundProcessManager.js.map +1 -0
  13. package/lib/Util/Retry.d.ts +2 -2
  14. package/lib/Util/Retry.js +76 -34
  15. package/lib/Util/Retry.js.map +1 -1
  16. package/lib/Util/index.d.ts +1 -0
  17. package/lib/Util/index.js +1 -0
  18. package/lib/Util/index.js.map +1 -1
  19. package/lib-esm/Credentials.d.ts +1 -1
  20. package/lib-esm/Credentials.js +1 -1
  21. package/lib-esm/Credentials.js.map +1 -1
  22. package/lib-esm/Platform/version.d.ts +1 -1
  23. package/lib-esm/Platform/version.js +1 -1
  24. package/lib-esm/Util/BackgroundProcessManager.d.ts +178 -0
  25. package/lib-esm/Util/BackgroundProcessManager.js +383 -0
  26. package/lib-esm/Util/BackgroundProcessManager.js.map +1 -0
  27. package/lib-esm/Util/Retry.d.ts +2 -2
  28. package/lib-esm/Util/Retry.js +76 -34
  29. package/lib-esm/Util/Retry.js.map +1 -1
  30. package/lib-esm/Util/index.d.ts +1 -0
  31. package/lib-esm/Util/index.js +1 -0
  32. package/lib-esm/Util/index.js.map +1 -1
  33. package/package.json +2 -2
  34. package/src/Credentials.ts +13 -14
  35. package/src/Platform/version.ts +1 -1
  36. package/src/Util/BackgroundProcessManager.ts +415 -0
  37. package/src/Util/Retry.ts +66 -31
  38. package/src/Util/index.ts +1 -0
@@ -1,2 +1,2 @@
1
1
  // generated by genversion
2
- export const version = '4.7.5';
2
+ export const version = '4.7.6';
@@ -0,0 +1,415 @@
1
+ /**
2
+ * @private For internal Amplify use.
3
+ *
4
+ * Creates a new scope for promises, observables, and other types of work or
5
+ * processes that may be running in the background. This manager provides
6
+ * an singular entrypoint to request termination and await completion.
7
+ *
8
+ * As work completes on its own prior to close, the manager removes them
9
+ * from the registry to avoid holding references to completed jobs.
10
+ */
11
+ export class BackgroundProcessManager {
12
+ /**
13
+ * A string indicating whether the manager is accepting new work ("Open"),
14
+ * waiting for work to complete ("Closing"), or fully done with all
15
+ * submitted work and *not* accepting new jobs ("Closed").
16
+ */
17
+ private _state = BackgroundProcessManagerState.Open;
18
+
19
+ /**
20
+ * The list of outstanding jobs we'll need to wait for upon `close()`
21
+ */
22
+ private jobs = new Set<JobEntry>();
23
+
24
+ /**
25
+ * Creates a new manager for promises, observables, and other types
26
+ * of work that may be running in the background. This manager provides
27
+ * a centralized mechanism to request termination and await completion.
28
+ */
29
+ constructor() {}
30
+
31
+ /**
32
+ * Executes an async `job` function, passing the return value through to
33
+ * the caller, registering it as a running job in the manager. When the
34
+ * manager *closes*, it will `await` the job.
35
+ *
36
+ * @param job The function to execute.
37
+ * @param description Optional description to help identify pending jobs.
38
+ * @returns The return value from the given function.
39
+ */
40
+ add<T>(job: () => Promise<T>, description?: string): Promise<T>;
41
+
42
+ /**
43
+ * Executes an async `job` function, passing the return value through to
44
+ * the caller, registering it as a running job in the manager. When the
45
+ * manager *closes*, it will request termination by resolving the
46
+ * provided `onTerminate` promise. It will then `await` the job, so it is
47
+ * important that the job still `resolve()` or `reject()` when responding
48
+ * to a termination request.
49
+ *
50
+ * @param job The function to execute.
51
+ * @param description Optional description to help identify pending jobs.
52
+ * @returns The return value from the given function.
53
+ */
54
+ add<T>(
55
+ job: (onTerminate: Promise<void>) => Promise<T>,
56
+ description?: string
57
+ ): Promise<T>;
58
+
59
+ /**
60
+ * Create a no-op job, registers it with the manager, and returns hooks
61
+ * to the caller to signal the job's completion and respond to termination
62
+ * requests.
63
+ *
64
+ * When the manager closes, the no-op job will be `await`-ed, so its
65
+ * important to always `resolve()` or `reject()` when done responding to an
66
+ * `onTerminate` signal.
67
+ * @param description Optional description to help identify pending jobs.
68
+ * @returns Job promise hooks + onTerminate signaling promise
69
+ */
70
+ add(description?: string): {
71
+ resolve: (value?: unknown) => void;
72
+ reject: (reason?: any) => void;
73
+ onTerminate: Promise<void>;
74
+ };
75
+
76
+ /**
77
+ * Adds another job manager to await on at the time of closing. the inner
78
+ * manager's termination is signaled when this manager's `close()` is
79
+ * called for.
80
+ *
81
+ * @param job The inner job manager to await.
82
+ * @param description Optional description to help identify pending jobs.
83
+ */
84
+ add(job: BackgroundProcessManager, description?: string);
85
+
86
+ add(jobOrDescription?, optionalDescription?) {
87
+ let job;
88
+ let description: string;
89
+
90
+ if (typeof jobOrDescription === 'string') {
91
+ job = undefined;
92
+ description = jobOrDescription;
93
+ } else {
94
+ job = jobOrDescription;
95
+ description = optionalDescription;
96
+ }
97
+
98
+ const error = this.closedFailure(description);
99
+ if (error) return error;
100
+
101
+ if (job === undefined) {
102
+ return this.addHook(description);
103
+ } else if (typeof job === 'function') {
104
+ return this.addFunction(job, description);
105
+ } else if (job instanceof BackgroundProcessManager) {
106
+ return this.addManager(job, description);
107
+ } else {
108
+ throw new Error(
109
+ 'If `job` is provided, it must be an Observable, Function, or BackgroundProcessManager.'
110
+ );
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Adds a **cleaner** function that doesn't immediately get executed.
116
+ * Instead, the caller gets a **terminate** function back. The *cleaner* is
117
+ * invoked only once the mananger *closes* or the returned **terminate**
118
+ * function is called.
119
+ *
120
+ * @param clean The cleanup function.
121
+ * @param description Optional description to help identify pending jobs.
122
+ * @returns A terminate function.
123
+ */
124
+ addCleaner<T>(
125
+ clean: () => Promise<T>,
126
+ description?: string
127
+ ): () => Promise<void> {
128
+ const { resolve, onTerminate } = this.addHook(description);
129
+
130
+ const proxy = async () => {
131
+ await clean();
132
+ resolve();
133
+ };
134
+
135
+ onTerminate.then(proxy);
136
+
137
+ return proxy;
138
+ }
139
+
140
+ private addFunction<T>(
141
+ job: () => Promise<T>,
142
+ description?: string
143
+ ): Promise<T>;
144
+ private addFunction<T>(
145
+ job: (onTerminate: Promise<void>) => Promise<T>,
146
+ description?: string
147
+ ): Promise<T>;
148
+ private addFunction(job, description) {
149
+ // the function we call when we want to try to terminate this job.
150
+ let terminate;
151
+
152
+ // the promise the job can opt into listening to for termination.
153
+ const onTerminate = new Promise(resolve => {
154
+ terminate = resolve;
155
+ });
156
+
157
+ // finally! start the job.
158
+ const jobResult = job(onTerminate);
159
+
160
+ // depending on what the job gives back, register the result
161
+ // so we can monitor for completion.
162
+ if (typeof jobResult?.then === 'function') {
163
+ this.registerPromise(jobResult, terminate, description);
164
+ }
165
+
166
+ // At the end of the day, or you know, method call, it doesn't matter
167
+ // what the return value is at all; we just pass it through to the
168
+ // caller.
169
+ return jobResult;
170
+ }
171
+
172
+ private addManager(manager: BackgroundProcessManager, description?: string) {
173
+ this.addCleaner(async () => await manager.close(), description);
174
+ }
175
+
176
+ /**
177
+ * Creates and registers a fabricated job for processes that need to operate
178
+ * with callbacks/hooks. The returned `resolve` and `reject`
179
+ * functions can be used to signal the job is done successfully or not.
180
+ * The returned `onTerminate` is a promise that will resolve when the
181
+ * manager is requesting the termination of the job.
182
+ *
183
+ * @param description Optional description to help identify pending jobs.
184
+ * @returns `{ resolve, reject, onTerminate }`
185
+ */
186
+ private addHook(description?: string) {
187
+ // the resolve/reject functions we'll provide to the caller to signal
188
+ // the state of the job.
189
+ let resolve: (value?: unknown) => void;
190
+ let reject: (reason?: any) => void;
191
+
192
+ // the underlying promise we'll use to manage it, pretty much like
193
+ // any other promise.
194
+ const promise = new Promise((res, rej) => {
195
+ resolve = res;
196
+ reject = rej;
197
+ });
198
+
199
+ // the function we call when we want to try to terminate this job.
200
+ let terminate;
201
+
202
+ // the promise the job can opt into listening to for termination.
203
+ const onTerminate = new Promise(resolveTerminate => {
204
+ terminate = resolveTerminate;
205
+ });
206
+
207
+ this.registerPromise(promise, terminate, description);
208
+
209
+ return {
210
+ resolve,
211
+ reject,
212
+ onTerminate,
213
+ };
214
+ }
215
+
216
+ /**
217
+ * Adds a Promise based job to the list of jobs for monitoring and listens
218
+ * for either a success or failure, upon which the job is considered "done"
219
+ * and removed from the registry.
220
+ *
221
+ * @param promise A promise that is on its way to being returned to a
222
+ * caller, which needs to be tracked as a background job.
223
+ * @param terminate The termination function to register, which can be
224
+ * invoked to request the job stop.
225
+ * @param description Optional description to help identify pending jobs.
226
+ */
227
+ private registerPromise<T extends Promise<any>>(
228
+ promise: T,
229
+ terminate: () => void,
230
+ description?: string
231
+ ) {
232
+ const jobEntry = { promise, terminate, description };
233
+ this.jobs.add(jobEntry);
234
+
235
+ // in all of my testing, it is safe to multi-subscribe to a promise.
236
+ // so, rather than create another layer of promising, we're just going
237
+ // to hook into the promise we already have, and when it's done
238
+ // (successfully or not), we no longer need to wait for it upon close.
239
+
240
+ //
241
+ // sorry this is a bit hand-wavy:
242
+ //
243
+ // i believe we use `.then` and `.catch` instead of `.finally` because
244
+ // `.finally` is invoked in a different order in the sequence, and this
245
+ // breaks assumptions throughout and causes failures.
246
+ promise
247
+ .then(() => {
248
+ this.jobs.delete(jobEntry);
249
+ })
250
+ .catch(() => {
251
+ this.jobs.delete(jobEntry);
252
+ });
253
+ }
254
+
255
+ /**
256
+ * The number of jobs being waited on.
257
+ *
258
+ * We don't use this for anything. It's just informational for the caller,
259
+ * and can be used in logging and testing.
260
+ *
261
+ * @returns the number of jobs.
262
+ */
263
+ get length() {
264
+ return this.jobs.size;
265
+ }
266
+
267
+ /**
268
+ * The execution state of the manager. One of:
269
+ *
270
+ * 1. "Open" -> Accepting new jobs
271
+ * 1. "Closing" -> Not accepting new work. Waiting for jobs to complete.
272
+ * 1. "Closed" -> Not accepting new work. All submitted jobs are complete.
273
+ */
274
+ get state() {
275
+ return this._state;
276
+ }
277
+
278
+ /**
279
+ * The registered `description` of all still-pending jobs.
280
+ *
281
+ * @returns descriptions as an array.
282
+ */
283
+ get pending() {
284
+ return Array.from(this.jobs).map(job => job.description);
285
+ }
286
+
287
+ /**
288
+ * Whether the manager is accepting new jobs.
289
+ */
290
+ get isOpen() {
291
+ return this._state === BackgroundProcessManagerState.Open;
292
+ }
293
+
294
+ /**
295
+ * Whether the manager is rejecting new work, but still waiting for
296
+ * submitted work to complete.
297
+ */
298
+ get isClosing() {
299
+ return this._state === BackgroundProcessManagerState.Closing;
300
+ }
301
+
302
+ /**
303
+ * Whether the manager is rejecting work and done waiting for submitted
304
+ * work to complete.
305
+ */
306
+ get isClosed() {
307
+ return this._state === BackgroundProcessManagerState.Closed;
308
+ }
309
+
310
+ private closedFailure(description: string) {
311
+ if (!this.isOpen) {
312
+ return Promise.reject(
313
+ new Error(
314
+ [
315
+ 'The manager is closing or closed, which occurs after `close()` has been called.',
316
+ `This error occurred trying to add "${description}".`,
317
+ `Pending jobs: [\n${this.pending
318
+ .map(t => ' ' + t)
319
+ .join(',\n')}\n]`,
320
+ ].join('\n')
321
+ )
322
+ );
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Signals jobs to stop (for those that accept interruptions) and waits
328
+ * for confirmation that jobs have stopped.
329
+ *
330
+ * This immediately puts the manager into a closing state and just begins
331
+ * to reject new work. After all work in the manager is complete, the
332
+ * manager goes into a `Completed` state and `close()` returns.
333
+ *
334
+ * @returns The settled results of each job's promise.
335
+ */
336
+ async close() {
337
+ // prevents more jobs from being added
338
+ this._state = BackgroundProcessManagerState.Closing;
339
+
340
+ for (const job of Array.from(this.jobs)) {
341
+ try {
342
+ job.terminate();
343
+ } catch (error) {
344
+ // Due to potential races with a job's natural completion, it's
345
+ // reasonable to expect the termination call to fail. Hence,
346
+ // not logging as an error.
347
+ console.warn(
348
+ `Failed to send termination signal to job. Error: ${error.message}`,
349
+ job
350
+ );
351
+ }
352
+ }
353
+
354
+ // Use `allSettled()` because we want to wait for all to finish. We do
355
+ // not want to stop waiting if there is a failure.
356
+ const results = await Promise.allSettled(
357
+ Array.from(this.jobs).map(j => j.promise)
358
+ );
359
+
360
+ // At this point, we're already *not* accepting new work, and all
361
+ // pending work is done. It's safe to set state to `Closed`. Any
362
+ // process that's checking this property will be able to safely operate
363
+ // on this value at this point.
364
+ this._state = BackgroundProcessManagerState.Closed;
365
+
366
+ return results;
367
+ }
368
+ }
369
+
370
+ /**
371
+ * All possible states a `BackgroundProcessManager` instance can be in.
372
+ */
373
+ export enum BackgroundProcessManagerState {
374
+ /**
375
+ * Accepting new jobs.
376
+ */
377
+ Open = 'Open',
378
+
379
+ /**
380
+ * Not accepting new jobs. Waiting for submitted jobs to complete.
381
+ */
382
+ Closing = 'Closing',
383
+
384
+ /**
385
+ * Not accepting new jobs. All submitted jobs are complete.
386
+ */
387
+ Closed = 'Closed',
388
+ }
389
+
390
+ /**
391
+ * Completely internal to `BackgroundProcessManager`, and describes the structure of
392
+ * an entry in the jobs registry.
393
+ */
394
+ type JobEntry = {
395
+ /**
396
+ * The underlying promise provided by the job function to wait for.
397
+ */
398
+ promise: Promise<any>;
399
+
400
+ /**
401
+ * Request the termination of the job.
402
+ */
403
+ terminate: () => void;
404
+
405
+ /**
406
+ * An object provided by the caller that can be used to identify the description
407
+ * of the job, which can otherwise be unclear from the `promise` and
408
+ * `terminate` function. The `description` can be a string. (May be extended
409
+ * later to also support object refs.)
410
+ *
411
+ * Useful for troubleshooting why a manager is waiting for long periods of time
412
+ * on `close()`.
413
+ */
414
+ description?: string;
415
+ };
package/src/Util/Retry.ts CHANGED
@@ -18,41 +18,74 @@ const isNonRetryableError = (obj: any): obj is NonRetryableError => {
18
18
  * @private
19
19
  * Internal use of Amplify only
20
20
  */
21
- export async function retry(
22
- functionToRetry: Function,
21
+ export async function retry<T>(
22
+ functionToRetry: (...args: any[]) => T,
23
23
  args: any[],
24
24
  delayFn: DelayFunction,
25
- attempt: number = 1
26
- ) {
25
+ onTerminate?: Promise<void>
26
+ ): Promise<T> {
27
27
  if (typeof functionToRetry !== 'function') {
28
28
  throw Error('functionToRetry must be a function');
29
29
  }
30
- logger.debug(
31
- `${
32
- functionToRetry.name
33
- } attempt #${attempt} with this vars: ${JSON.stringify(args)}`
34
- );
35
-
36
- try {
37
- return await functionToRetry(...args);
38
- } catch (err) {
39
- logger.debug(`error on ${functionToRetry.name}`, err);
40
-
41
- if (isNonRetryableError(err)) {
42
- logger.debug(`${functionToRetry.name} non retryable error`, err);
43
- throw err;
44
- }
45
30
 
46
- const retryIn = delayFn(attempt, args, err);
47
- logger.debug(`${functionToRetry.name} retrying in ${retryIn} ms`);
31
+ return new Promise(async (resolve, reject) => {
32
+ let attempt = 0;
33
+ let terminated = false;
34
+ let timeout: any;
35
+ let wakeUp: any = () => {}; // will be replaced with a resolver()
36
+
37
+ // used after the loop if terminated while waiting for a timer.
38
+ let lastError: Error;
39
+
40
+ onTerminate &&
41
+ onTerminate.then(() => {
42
+ // signal not to try anymore.
43
+ terminated = true;
44
+
45
+ // stop sleeping if we're sleeping.
46
+ clearTimeout(timeout);
47
+ wakeUp();
48
+ });
49
+
50
+ while (!terminated) {
51
+ attempt++;
52
+
53
+ logger.debug(
54
+ `${
55
+ functionToRetry.name
56
+ } attempt #${attempt} with this vars: ${JSON.stringify(args)}`
57
+ );
48
58
 
49
- if (retryIn !== false) {
50
- await new Promise(res => setTimeout(res, retryIn));
51
- return await retry(functionToRetry, args, delayFn, attempt + 1);
52
- } else {
53
- throw err;
59
+ try {
60
+ return resolve(await functionToRetry(...args));
61
+ } catch (err) {
62
+ lastError = err;
63
+ logger.debug(`error on ${functionToRetry.name}`, err);
64
+
65
+ if (isNonRetryableError(err)) {
66
+ logger.debug(`${functionToRetry.name} non retryable error`, err);
67
+ return reject(err);
68
+ }
69
+
70
+ const retryIn = delayFn(attempt, args, err);
71
+ logger.debug(`${functionToRetry.name} retrying in ${retryIn} ms`);
72
+
73
+ // we check `terminated` again here because it could have flipped
74
+ // in the time it took `functionToRetry` to return.
75
+ if (retryIn === false || terminated) {
76
+ return reject(err);
77
+ } else {
78
+ await new Promise(r => {
79
+ wakeUp = r; // export wakeUp for onTerminate handling
80
+ timeout = setTimeout(wakeUp, retryIn);
81
+ });
82
+ }
83
+ }
54
84
  }
55
- }
85
+
86
+ // reached if terminated while waiting for a timer.
87
+ reject(lastError);
88
+ });
56
89
  }
57
90
 
58
91
  const MAX_DELAY_MS = 5 * 60 * 1000;
@@ -77,8 +110,10 @@ export function jitteredBackoff(
77
110
  * @private
78
111
  * Internal use of Amplify only
79
112
  */
80
- export const jitteredExponentialRetry = (
81
- functionToRetry: Function,
113
+ export const jitteredExponentialRetry = <T>(
114
+ functionToRetry: (...args: any[]) => T,
82
115
  args: any[],
83
- maxDelayMs: number = MAX_DELAY_MS
84
- ) => retry(functionToRetry, args, jitteredBackoff(maxDelayMs));
116
+ maxDelayMs: number = MAX_DELAY_MS,
117
+ onTerminate?: Promise<void>
118
+ ): Promise<T> =>
119
+ retry(functionToRetry, args, jitteredBackoff(maxDelayMs), onTerminate);
package/src/Util/index.ts CHANGED
@@ -4,3 +4,4 @@ export { default as Reachability } from './Reachability';
4
4
  export * from './DateUtils';
5
5
  export * from './StringUtils';
6
6
  export * from './Constants';
7
+ export * from './BackgroundProcessManager';