@aws-amplify/core 4.7.7-unstable.7 → 4.7.7

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.
@@ -187,7 +187,7 @@ export class CredentialsClass {
187
187
  const MAX_DELAY_MS = 10 * 1000;
188
188
  // refreshHandler will retry network errors, otherwise it will
189
189
  // return NonRetryableError to break out of jitteredExponentialRetry
190
- return jitteredExponentialRetry<any>(refreshHandler, [], MAX_DELAY_MS)
190
+ return jitteredExponentialRetry(refreshHandler, [], MAX_DELAY_MS)
191
191
  .then(data => {
192
192
  logger.debug('refresh federated token sucessfully', data);
193
193
  return this._setCredentialsFromFederation({
@@ -256,7 +256,7 @@ export class CredentialsClass {
256
256
  );
257
257
  }
258
258
 
259
- const identityId = (this._identityId = await this._getGuestIdentityId());
259
+ const identityId = this._identityId = await this._getGuestIdentityId();
260
260
 
261
261
  const cognitoClient = new CognitoIdentityClient({
262
262
  region,
@@ -446,14 +446,19 @@ export class CredentialsClass {
446
446
  }
447
447
 
448
448
  const {
449
- Credentials: { AccessKeyId, Expiration, SecretKey, SessionToken },
449
+ Credentials: {
450
+ AccessKeyId,
451
+ Expiration,
452
+ SecretKey,
453
+ SessionToken,
454
+ },
450
455
  // single source of truth for the primary identity associated with the logins
451
456
  // only if a guest identity is used for a first-time user, that guest identity will become its primary identity
452
457
  IdentityId: primaryIdentityId,
453
458
  } = await cognitoClient.send(
454
459
  new GetCredentialsForIdentityCommand({
455
- IdentityId: guestIdentityId || generatedOrRetrievedIdentityId,
456
- Logins: logins,
460
+ IdentityId: guestIdentityId || generatedOrRetrievedIdentityId,
461
+ Logins: logins,
457
462
  })
458
463
  );
459
464
 
@@ -461,13 +466,9 @@ export class CredentialsClass {
461
466
  if (guestIdentityId) {
462
467
  // if guestIdentity is found and used by GetCredentialsForIdentity
463
468
  // it will be linked to the logins provided, and disqualified as an unauth identity
464
- logger.debug(
465
- `The guest identity ${guestIdentityId} has been successfully linked to the logins`
466
- );
469
+ logger.debug(`The guest identity ${guestIdentityId} has been successfully linked to the logins`);
467
470
  if (guestIdentityId === primaryIdentityId) {
468
- logger.debug(
469
- `The guest identity ${guestIdentityId} has become the primary identity`
470
- );
471
+ logger.debug(`The guest identity ${guestIdentityId} has become the primary identity`);
471
472
  }
472
473
  // remove it from local storage to avoid being used as a guest Identity by _setCredentialsForGuest
473
474
  await this._removeGuestIdentityId();
@@ -480,7 +481,7 @@ export class CredentialsClass {
480
481
  sessionToken: SessionToken,
481
482
  expiration: Expiration,
482
483
  identityId: primaryIdentityId,
483
- };
484
+ };
484
485
  };
485
486
 
486
487
  const credentials = credentialsProvider().catch(async err => {
@@ -586,7 +587,7 @@ export class CredentialsClass {
586
587
  await this._storageSync;
587
588
  this._storage.setItem(
588
589
  this._getCognitoIdentityIdStorageKey(identityPoolId),
589
- identityId
590
+ identityId,
590
591
  );
591
592
  } catch (e) {
592
593
  logger.debug('Failed to cache guest identityId', e);
package/src/Util/Retry.ts CHANGED
@@ -18,74 +18,41 @@ const isNonRetryableError = (obj: any): obj is NonRetryableError => {
18
18
  * @private
19
19
  * Internal use of Amplify only
20
20
  */
21
- export async function retry<T>(
22
- functionToRetry: (...args: any[]) => T,
21
+ export async function retry(
22
+ functionToRetry: Function,
23
23
  args: any[],
24
24
  delayFn: DelayFunction,
25
- onTerminate?: Promise<void>
26
- ): Promise<T> {
25
+ attempt: number = 1
26
+ ) {
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
+ }
30
45
 
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
- );
58
-
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`);
46
+ const retryIn = delayFn(attempt, args, err);
47
+ logger.debug(`${functionToRetry.name} retrying in ${retryIn} ms`);
72
48
 
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
- }
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;
84
54
  }
85
-
86
- // reached if terminated while waiting for a timer.
87
- reject(lastError);
88
- });
55
+ }
89
56
  }
90
57
 
91
58
  const MAX_DELAY_MS = 5 * 60 * 1000;
@@ -110,10 +77,8 @@ export function jitteredBackoff(
110
77
  * @private
111
78
  * Internal use of Amplify only
112
79
  */
113
- export const jitteredExponentialRetry = <T>(
114
- functionToRetry: (...args: any[]) => T,
80
+ export const jitteredExponentialRetry = (
81
+ functionToRetry: Function,
115
82
  args: any[],
116
- maxDelayMs: number = MAX_DELAY_MS,
117
- onTerminate?: Promise<void>
118
- ): Promise<T> =>
119
- retry(functionToRetry, args, jitteredBackoff(maxDelayMs), onTerminate);
83
+ maxDelayMs: number = MAX_DELAY_MS
84
+ ) => retry(functionToRetry, args, jitteredBackoff(maxDelayMs));
package/src/Util/index.ts CHANGED
@@ -4,4 +4,3 @@ 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';
@@ -1,178 +0,0 @@
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 declare 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;
18
- /**
19
- * The list of outstanding jobs we'll need to wait for upon `close()`
20
- */
21
- private jobs;
22
- /**
23
- * Creates a new manager for promises, observables, and other types
24
- * of work that may be running in the background. This manager provides
25
- * a centralized mechanism to request termination and await completion.
26
- */
27
- constructor();
28
- /**
29
- * Executes an async `job` function, passing the return value through to
30
- * the caller, registering it as a running job in the manager. When the
31
- * manager *closes*, it will `await` the job.
32
- *
33
- * @param job The function to execute.
34
- * @param description Optional description to help identify pending jobs.
35
- * @returns The return value from the given function.
36
- */
37
- add<T>(job: () => Promise<T>, description?: string): Promise<T>;
38
- /**
39
- * Executes an async `job` function, passing the return value through to
40
- * the caller, registering it as a running job in the manager. When the
41
- * manager *closes*, it will request termination by resolving the
42
- * provided `onTerminate` promise. It will then `await` the job, so it is
43
- * important that the job still `resolve()` or `reject()` when responding
44
- * to a termination request.
45
- *
46
- * @param job The function to execute.
47
- * @param description Optional description to help identify pending jobs.
48
- * @returns The return value from the given function.
49
- */
50
- add<T>(job: (onTerminate: Promise<void>) => Promise<T>, description?: string): Promise<T>;
51
- /**
52
- * Create a no-op job, registers it with the manager, and returns hooks
53
- * to the caller to signal the job's completion and respond to termination
54
- * requests.
55
- *
56
- * When the manager closes, the no-op job will be `await`-ed, so its
57
- * important to always `resolve()` or `reject()` when done responding to an
58
- * `onTerminate` signal.
59
- * @param description Optional description to help identify pending jobs.
60
- * @returns Job promise hooks + onTerminate signaling promise
61
- */
62
- add(description?: string): {
63
- resolve: (value?: unknown) => void;
64
- reject: (reason?: any) => void;
65
- onTerminate: Promise<void>;
66
- };
67
- /**
68
- * Adds another job manager to await on at the time of closing. the inner
69
- * manager's termination is signaled when this manager's `close()` is
70
- * called for.
71
- *
72
- * @param job The inner job manager to await.
73
- * @param description Optional description to help identify pending jobs.
74
- */
75
- add(job: BackgroundProcessManager, description?: string): any;
76
- /**
77
- * Adds a **cleaner** function that doesn't immediately get executed.
78
- * Instead, the caller gets a **terminate** function back. The *cleaner* is
79
- * invoked only once the mananger *closes* or the returned **terminate**
80
- * function is called.
81
- *
82
- * @param clean The cleanup function.
83
- * @param description Optional description to help identify pending jobs.
84
- * @returns A terminate function.
85
- */
86
- addCleaner<T>(clean: () => Promise<T>, description?: string): () => Promise<void>;
87
- private addFunction;
88
- private addManager;
89
- /**
90
- * Creates and registers a fabricated job for processes that need to operate
91
- * with callbacks/hooks. The returned `resolve` and `reject`
92
- * functions can be used to signal the job is done successfully or not.
93
- * The returned `onTerminate` is a promise that will resolve when the
94
- * manager is requesting the termination of the job.
95
- *
96
- * @param description Optional description to help identify pending jobs.
97
- * @returns `{ resolve, reject, onTerminate }`
98
- */
99
- private addHook;
100
- /**
101
- * Adds a Promise based job to the list of jobs for monitoring and listens
102
- * for either a success or failure, upon which the job is considered "done"
103
- * and removed from the registry.
104
- *
105
- * @param promise A promise that is on its way to being returned to a
106
- * caller, which needs to be tracked as a background job.
107
- * @param terminate The termination function to register, which can be
108
- * invoked to request the job stop.
109
- * @param description Optional description to help identify pending jobs.
110
- */
111
- private registerPromise;
112
- /**
113
- * The number of jobs being waited on.
114
- *
115
- * We don't use this for anything. It's just informational for the caller,
116
- * and can be used in logging and testing.
117
- *
118
- * @returns the number of jobs.
119
- */
120
- get length(): number;
121
- /**
122
- * The execution state of the manager. One of:
123
- *
124
- * 1. "Open" -> Accepting new jobs
125
- * 1. "Closing" -> Not accepting new work. Waiting for jobs to complete.
126
- * 1. "Closed" -> Not accepting new work. All submitted jobs are complete.
127
- */
128
- get state(): BackgroundProcessManagerState;
129
- /**
130
- * The registered `description` of all still-pending jobs.
131
- *
132
- * @returns descriptions as an array.
133
- */
134
- get pending(): string[];
135
- /**
136
- * Whether the manager is accepting new jobs.
137
- */
138
- get isOpen(): boolean;
139
- /**
140
- * Whether the manager is rejecting new work, but still waiting for
141
- * submitted work to complete.
142
- */
143
- get isClosing(): boolean;
144
- /**
145
- * Whether the manager is rejecting work and done waiting for submitted
146
- * work to complete.
147
- */
148
- get isClosed(): boolean;
149
- private closedFailure;
150
- /**
151
- * Signals jobs to stop (for those that accept interruptions) and waits
152
- * for confirmation that jobs have stopped.
153
- *
154
- * This immediately puts the manager into a closing state and just begins
155
- * to reject new work. After all work in the manager is complete, the
156
- * manager goes into a `Completed` state and `close()` returns.
157
- *
158
- * @returns The settled results of each job's promise.
159
- */
160
- close(): Promise<PromiseSettledResult<any>[]>;
161
- }
162
- /**
163
- * All possible states a `BackgroundProcessManager` instance can be in.
164
- */
165
- export declare enum BackgroundProcessManagerState {
166
- /**
167
- * Accepting new jobs.
168
- */
169
- Open = "Open",
170
- /**
171
- * Not accepting new jobs. Waiting for submitted jobs to complete.
172
- */
173
- Closing = "Closing",
174
- /**
175
- * Not accepting new jobs. All submitted jobs are complete.
176
- */
177
- Closed = "Closed"
178
- }