@celljs/retry 3.0.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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +192 -0
  3. package/cell.yml +0 -0
  4. package/lib/common/back-off/back-off-policy.d.ts +7 -0
  5. package/lib/common/back-off/back-off-policy.d.ts.map +1 -0
  6. package/lib/common/back-off/back-off-policy.js +56 -0
  7. package/lib/common/back-off/back-off-policy.js.map +1 -0
  8. package/lib/common/back-off/back-off-policy.spec.d.ts +2 -0
  9. package/lib/common/back-off/back-off-policy.spec.d.ts.map +1 -0
  10. package/lib/common/back-off/back-off-policy.spec.js +209 -0
  11. package/lib/common/back-off/back-off-policy.spec.js.map +1 -0
  12. package/lib/common/back-off/back-off-protocol.d.ts +12 -0
  13. package/lib/common/back-off/back-off-protocol.d.ts.map +1 -0
  14. package/lib/common/back-off/back-off-protocol.js +5 -0
  15. package/lib/common/back-off/back-off-protocol.js.map +1 -0
  16. package/lib/common/back-off/index.d.ts +3 -0
  17. package/lib/common/back-off/index.d.ts.map +1 -0
  18. package/lib/common/back-off/index.js +19 -0
  19. package/lib/common/back-off/index.js.map +1 -0
  20. package/lib/common/error/index.d.ts +2 -0
  21. package/lib/common/error/index.d.ts.map +1 -0
  22. package/lib/common/error/index.js +18 -0
  23. package/lib/common/error/index.js.map +1 -0
  24. package/lib/common/error/retry-error.d.ts +4 -0
  25. package/lib/common/error/retry-error.d.ts.map +1 -0
  26. package/lib/common/error/retry-error.js +8 -0
  27. package/lib/common/error/retry-error.js.map +1 -0
  28. package/lib/common/index.d.ts +5 -0
  29. package/lib/common/index.d.ts.map +1 -0
  30. package/lib/common/index.js +21 -0
  31. package/lib/common/index.js.map +1 -0
  32. package/lib/common/module.d.ts +4 -0
  33. package/lib/common/module.d.ts.map +1 -0
  34. package/lib/common/module.js +6 -0
  35. package/lib/common/module.js.map +1 -0
  36. package/lib/common/policy/index.d.ts +3 -0
  37. package/lib/common/policy/index.d.ts.map +1 -0
  38. package/lib/common/policy/index.js +19 -0
  39. package/lib/common/policy/index.js.map +1 -0
  40. package/lib/common/policy/policy-protocol.d.ts +6 -0
  41. package/lib/common/policy/policy-protocol.d.ts.map +1 -0
  42. package/lib/common/policy/policy-protocol.js +5 -0
  43. package/lib/common/policy/policy-protocol.js.map +1 -0
  44. package/lib/common/policy/retry-policy.d.ts +6 -0
  45. package/lib/common/policy/retry-policy.d.ts.map +1 -0
  46. package/lib/common/policy/retry-policy.js +49 -0
  47. package/lib/common/policy/retry-policy.js.map +1 -0
  48. package/lib/common/policy/retry-policy.spec.d.ts +2 -0
  49. package/lib/common/policy/retry-policy.spec.d.ts.map +1 -0
  50. package/lib/common/policy/retry-policy.spec.js +102 -0
  51. package/lib/common/policy/retry-policy.spec.js.map +1 -0
  52. package/lib/common/retry/index.d.ts +3 -0
  53. package/lib/common/retry/index.d.ts.map +1 -0
  54. package/lib/common/retry/index.js +19 -0
  55. package/lib/common/retry/index.js.map +1 -0
  56. package/lib/common/retry/retry-operations.d.ts +15 -0
  57. package/lib/common/retry/retry-operations.d.ts.map +1 -0
  58. package/lib/common/retry/retry-operations.js +94 -0
  59. package/lib/common/retry/retry-operations.js.map +1 -0
  60. package/lib/common/retry/retry-operations.spec.d.ts +2 -0
  61. package/lib/common/retry/retry-operations.spec.d.ts.map +1 -0
  62. package/lib/common/retry/retry-operations.spec.js +140 -0
  63. package/lib/common/retry/retry-operations.spec.js.map +1 -0
  64. package/lib/common/retry/retry-protocol.d.ts +123 -0
  65. package/lib/common/retry/retry-protocol.d.ts.map +1 -0
  66. package/lib/common/retry/retry-protocol.js +5 -0
  67. package/lib/common/retry/retry-protocol.js.map +1 -0
  68. package/lib/package.spec.d.ts +1 -0
  69. package/lib/package.spec.d.ts.map +1 -0
  70. package/lib/package.spec.js +4 -0
  71. package/lib/package.spec.js.map +1 -0
  72. package/package.json +41 -0
  73. package/src/common/back-off/back-off-policy.spec.ts +246 -0
  74. package/src/common/back-off/back-off-policy.ts +43 -0
  75. package/src/common/back-off/back-off-protocol.ts +14 -0
  76. package/src/common/back-off/index.ts +2 -0
  77. package/src/common/error/index.ts +1 -0
  78. package/src/common/error/retry-error.ts +5 -0
  79. package/src/common/index.ts +4 -0
  80. package/src/common/module.ts +4 -0
  81. package/src/common/policy/index.ts +2 -0
  82. package/src/common/policy/policy-protocol.ts +7 -0
  83. package/src/common/policy/retry-policy.spec.ts +125 -0
  84. package/src/common/policy/retry-policy.ts +39 -0
  85. package/src/common/retry/index.ts +2 -0
  86. package/src/common/retry/retry-operations.spec.ts +154 -0
  87. package/src/common/retry/retry-operations.ts +78 -0
  88. package/src/common/retry/retry-protocol.ts +133 -0
  89. package/src/package.spec.ts +4 -0
@@ -0,0 +1,123 @@
1
+ import { CustomError } from '@celljs/core';
2
+ export declare const RetryOperations: unique symbol;
3
+ /**
4
+ * Represents the context for retrying an operation.
5
+ */
6
+ export interface RetryContext {
7
+ startTime: number;
8
+ maxAttempts?: number;
9
+ timeout?: number;
10
+ backOffOptions?: BackOffOptions;
11
+ rollbackError?: typeof CustomError;
12
+ retryCount: number;
13
+ lastError?: Error;
14
+ exhaustedOnly?: boolean;
15
+ noRecovery?: boolean;
16
+ retryErrors: (typeof CustomError)[];
17
+ notRetryErrors: (typeof CustomError)[];
18
+ }
19
+ export interface RetryCallback<T> {
20
+ (): Promise<T>;
21
+ }
22
+ export interface RetryCallback<T> {
23
+ (ctx: RetryContext): Promise<T>;
24
+ }
25
+ export interface RecoveryCallback<T> {
26
+ (ctx: RetryContext): Promise<T>;
27
+ }
28
+ export interface FixedBackoffOptions {
29
+ /**
30
+ * Set the back off period in milliseconds. Cannot be < 1. Default value is 1000ms.
31
+ */
32
+ period: number;
33
+ }
34
+ export interface BackOffOptions {
35
+ /**
36
+ * A canonical backoff period. Used as an initial value in the exponential case, and
37
+ * as a minimum value in the uniform case.
38
+ * The initial or canonical backoff period in milliseconds.
39
+ */
40
+ delay?: number | (() => Promise<number>);
41
+ /**
42
+ * If positive, then used as a multiplier for generating the next delay for backoff.
43
+ * A multiplier to use to calculate the next backoff delay.
44
+ */
45
+ multiplier?: number;
46
+ /**
47
+ * The maximum wait in milliseconds between retries. If less than {@link delay}
48
+ * then a default value is applied depending on the resulting policy.
49
+ * The maximum wait between retries in milliseconds.
50
+ */
51
+ maxDelay?: number | (() => Promise<number>);
52
+ /**
53
+ * In the exponential case ({@link multiplier} > 0) set this to true to have the
54
+ * backoff delays randomized, so that the maximum delay is multiplier times the
55
+ * previous delay and the distribution is uniform between the two values.
56
+ * The flag to signal randomization is required.
57
+ */
58
+ random?: boolean;
59
+ }
60
+ /**
61
+ * RetryOptions interface represents the options for retrying a task.
62
+ *
63
+ * @template T - The type of the recovery callback parameter.
64
+ * @property {RecoveryCallback<T>} recoveryCallback - The callback function to recover from an error.
65
+ * @property {typeof CustomError} rollbackError - The custom error class to rollback the operation.
66
+ * @property {number} maxAttempts - The maximum number of attempts to retry the task.
67
+ * @property {number} timeout - The timeout duration in milliseconds for each attempt.
68
+ * @property {boolean} exhaustedOnly - Indicates whether to retry only when all attempts are exhausted.
69
+ * @property {BackOffOptions} backOffOptions - The options for exponential backoff strategy.
70
+ * @property {(typeof CustomError)[]} retryErrors - The list of custom error classes to retry on.
71
+ * @property {(typeof CustomError)[]} notRetryErrors - The list of custom error classes to not retry on.
72
+ */
73
+ export interface RetryOptions<T = any> {
74
+ recoveryCallback?: RecoveryCallback<T>;
75
+ rollbackError?: typeof CustomError;
76
+ maxAttempts?: number;
77
+ timeout?: number;
78
+ exhaustedOnly?: boolean;
79
+ backOffOptions?: BackOffOptions;
80
+ retryErrors?: (typeof CustomError)[];
81
+ notRetryErrors?: (typeof CustomError)[];
82
+ }
83
+ /**
84
+ * RetryOperations interface represents the operations for retrying a task with different options.
85
+ */
86
+ export interface RetryOperations {
87
+ /**
88
+ * Execute the callback function with the given options.
89
+ *
90
+ * @template T - The type of the return value of the callback function.
91
+ * @param {RetryCallback<T>} callback - The callback function to execute.
92
+ * @param {RetryOptions<T>} options - The options for retrying the task.
93
+ * @returns {Promise<T>} - The result of the callback function
94
+ * @throws {RetryError} - If an error occurred during retry.
95
+ * @example
96
+ * const result = await retryOperations.execute(async () => {
97
+ * // do something
98
+ * }, { maxAttempts: 3, timeout: 1000 });
99
+ * console.log(result);
100
+ * @example
101
+ * const result = await retryOperations.execute(async () => {
102
+ * // do something
103
+ * }, { maxAttempts: 3, timeout: 1000, backOffOptions: { delay: 1000 } });
104
+ * console.log(result);
105
+ * @example
106
+ * const result = await retryOperations.execute(async () => {
107
+ * // do something
108
+ * }, { maxAttempts: 3, timeout: 1000, backOffOptions: { delay: 1000, multiplier: 2 } });
109
+ * console.log(result);
110
+ * @example
111
+ * const result = await retryOperations.execute(async () => {
112
+ * // do something
113
+ * }, { maxAttempts: 3, timeout: 1000, backOffOptions: { delay: 1000, multiplier: 2, random: true } });
114
+ * console.log(result);
115
+ * @example
116
+ * const result = await retryOperations.execute(async () => {
117
+ * // do something
118
+ * }, { maxAttempts: 3, timeout: 1000, backOffOptions: { delay: 1000, multiplier: 2, random: true, maxDelay: 5000 } });
119
+ * console.log(result);
120
+ */
121
+ execute<T>(callback: RetryCallback<T>, options?: RetryOptions<T>): Promise<T>;
122
+ }
123
+ //# sourceMappingURL=retry-protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry-protocol.d.ts","sourceRoot":"","sources":["../../../src/common/retry/retry-protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,eAAO,MAAM,eAAe,eAA4B,CAAC;AAEzD;;GAEG;AACH,MAAM,WAAW,YAAY;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,aAAa,CAAC,EAAE,OAAO,WAAW,CAAC;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,KAAK,CAAC;IAClB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,WAAW,EAAE,CAAC,OAAO,WAAW,CAAC,EAAE,CAAC;IACpC,cAAc,EAAE,CAAC,OAAO,WAAW,CAAC,EAAE,CAAC;CAC1C;AAED,MAAM,WAAW,aAAa,CAAC,CAAC;IAC5B,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;CAClB;AAED,MAAM,WAAW,aAAa,CAAC,CAAC;IAC5B,CAAC,GAAG,EAAE,YAAY,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACnC;AAED,MAAM,WAAW,gBAAgB,CAAC,CAAC;IAC/B,CAAC,GAAG,EAAE,YAAY,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACnC;AAED,MAAM,WAAW,mBAAmB;IAChC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,cAAc;IAC3B;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IACzC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IAE5C;;;;;OAKG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,YAAY,CAAC,CAAC,GAAG,GAAG;IACjC,gBAAgB,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IACvC,aAAa,CAAC,EAAE,OAAO,WAAW,CAAC;IACnC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,WAAW,CAAC,EAAE,CAAC,OAAO,WAAW,CAAC,EAAE,CAAC;IACrC,cAAc,CAAC,EAAE,CAAC,OAAO,WAAW,CAAC,EAAE,CAAC;CAE3C;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAiCG;IACH,OAAO,CAAC,CAAC,EAAE,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACjF"}
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RetryOperations = void 0;
4
+ exports.RetryOperations = Symbol('RetryOperations');
5
+ //# sourceMappingURL=retry-protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry-protocol.js","sourceRoot":"","sources":["../../../src/common/retry/retry-protocol.ts"],"names":[],"mappings":";;;AAEa,QAAA,eAAe,GAAG,MAAM,CAAC,iBAAiB,CAAC,CAAC"}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=package.spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package.spec.d.ts","sourceRoot":"","sources":["../src/package.spec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,4 @@
1
+ describe('retry package', () => {
2
+ it('support retry coverage statistics', () => { });
3
+ });
4
+ //# sourceMappingURL=package.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package.spec.js","sourceRoot":"","sources":["../src/package.spec.ts"],"names":[],"mappings":"AAAA,QAAQ,CAAC,eAAe,EAAE,GAAG,EAAE;IAE3B,EAAE,CAAC,mCAAmC,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;AACtD,CAAC,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@celljs/retry",
3
+ "version": "3.0.0",
4
+ "description": "",
5
+ "main": "lib/common/index.js",
6
+ "typings": "lib/common/index.d.ts",
7
+ "dependencies": {
8
+ "@celljs/core": "3.0.0"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "keywords": [
14
+ "cell-component"
15
+ ],
16
+ "license": "MIT",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/cellbang/cell.git"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/cellbang/cell/issues"
23
+ },
24
+ "homepage": "https://github.com/cellbang/cell",
25
+ "files": [
26
+ "lib",
27
+ "src",
28
+ "cell.yml"
29
+ ],
30
+ "scripts": {
31
+ "lint": "cell-component lint",
32
+ "build": "cell-component build",
33
+ "watch": "cell-component watch",
34
+ "clean": "cell-component clean",
35
+ "test": "cell-component test:js"
36
+ },
37
+ "devDependencies": {
38
+ "@celljs/component": "3.0.0"
39
+ },
40
+ "gitHead": "c0ef8d269e33a795406bcbb240cac4b845c6c24c"
41
+ }
@@ -0,0 +1,246 @@
1
+ import * as chai from 'chai';
2
+ import * as sinon from 'sinon';
3
+ import { DefaultBackOffPolicyImpl } from './back-off-policy';
4
+ import { RetryContext } from '../retry';
5
+ import { BackOffContext } from './back-off-protocol';
6
+
7
+ const expect = chai.expect;
8
+
9
+ describe('DefaultBackOffPolicyImpl', () => {
10
+ let backOffPolicy: DefaultBackOffPolicyImpl;
11
+
12
+ beforeEach(() => {
13
+ backOffPolicy = new DefaultBackOffPolicyImpl();
14
+ });
15
+
16
+ it('should return a BackOffContext with delay and startTime', async () => {
17
+ const ctx: RetryContext = {
18
+ startTime: Date.now(),
19
+ retryCount: 0,
20
+ retryErrors: [],
21
+ notRetryErrors: [],
22
+ backOffOptions: {
23
+ delay: 100
24
+ }
25
+ };
26
+
27
+ const result = await backOffPolicy.start(ctx);
28
+
29
+ expect(result.delay).equals(100);
30
+ expect(result.startTime).to.be.a('number');
31
+ expect(result.retryContext).equals(ctx);
32
+ });
33
+
34
+ it('should return a BackOffContext with delay from a delay function', async () => {
35
+ const ctx: RetryContext = {
36
+ startTime: Date.now(),
37
+ retryCount: 0,
38
+ retryErrors: [],
39
+ notRetryErrors: [],
40
+ backOffOptions: {
41
+ delay: async () => 200
42
+ }
43
+ };
44
+
45
+ const result = await backOffPolicy.start(ctx);
46
+
47
+ expect(result.delay).equals(200);
48
+ expect(result.startTime).to.be.a('number');
49
+ expect(result.retryContext).equals(ctx);
50
+ });
51
+
52
+ it('should return a BackOffContext with default delay if delay is not provided', async () => {
53
+ const ctx: RetryContext = {
54
+ startTime: Date.now(),
55
+ retryCount: 0,
56
+ retryErrors: [],
57
+ notRetryErrors: [],
58
+ backOffOptions: {}
59
+ };
60
+
61
+ const result = await backOffPolicy.start(ctx);
62
+
63
+ expect(result.delay).equals(100);
64
+ expect(result.startTime).to.be.a('number');
65
+ expect(result.retryContext).equals(ctx);
66
+ });
67
+
68
+ it('should return a BackOffContext with delay and startTime', async () => {
69
+ const ctx: RetryContext = {
70
+ startTime: Date.now(),
71
+ retryCount: 0,
72
+ retryErrors: [],
73
+ notRetryErrors: [],
74
+ backOffOptions: {
75
+ delay: 0
76
+ }
77
+ };
78
+
79
+ const result = await backOffPolicy.start(ctx);
80
+
81
+ expect(result.delay).equals(0);
82
+ expect(result.startTime).to.be.a('number');
83
+ expect(result.retryContext).equals(ctx);
84
+ });
85
+
86
+ describe('backOff', () => {
87
+ it('should update the delay in the BackOffContext', async () => {
88
+ const ctx: BackOffContext = {
89
+ startTime: Date.now(),
90
+ delay: 100,
91
+ retryContext: {
92
+ startTime: Date.now(),
93
+ retryCount: 0,
94
+ retryErrors: [],
95
+ notRetryErrors: [],
96
+ backOffOptions: {
97
+ delay: 100,
98
+ maxDelay: 1000,
99
+ multiplier: 2,
100
+ random: false
101
+ }
102
+ }
103
+ };
104
+
105
+ await backOffPolicy.backOff(ctx);
106
+
107
+ expect(ctx.delay).equals(200);
108
+ });
109
+
110
+ it('should update the delay in the BackOffContext with random delay', async () => {
111
+ const ctx: BackOffContext = {
112
+ startTime: Date.now(),
113
+ delay: 100,
114
+ retryContext: {
115
+ startTime: Date.now(),
116
+ retryCount: 0,
117
+ retryErrors: [],
118
+ notRetryErrors: [],
119
+ backOffOptions: {
120
+ delay: 100,
121
+ maxDelay: 1000,
122
+ multiplier: 2,
123
+ random: true
124
+ }
125
+ }
126
+ };
127
+
128
+ await backOffPolicy.backOff(ctx);
129
+
130
+ expect(ctx.delay).to.be.greaterThan(100);
131
+ expect(ctx.delay).to.be.lessThanOrEqual(200);
132
+ });
133
+
134
+ it('should not update the delay in the BackOffContext if backOffOptions is not provided', async () => {
135
+ const ctx: BackOffContext = {
136
+ startTime: Date.now(),
137
+ delay: 100,
138
+ retryContext: {
139
+ startTime: Date.now(),
140
+ retryCount: 0,
141
+ retryErrors: [],
142
+ notRetryErrors: []
143
+ }
144
+ };
145
+
146
+ await backOffPolicy.backOff(ctx);
147
+
148
+ expect(ctx.delay).equals(100);
149
+ });
150
+
151
+ it('should not update the delay in the BackOffContext if maxDelay is not provided', async () => {
152
+ const ctx: BackOffContext = {
153
+ startTime: Date.now(),
154
+ delay: 100,
155
+ retryContext: {
156
+ startTime: Date.now(),
157
+ retryCount: 0,
158
+ retryErrors: [],
159
+ notRetryErrors: [],
160
+ backOffOptions: {
161
+ delay: 100,
162
+ multiplier: 2,
163
+ random: false
164
+ }
165
+ }
166
+ };
167
+
168
+ await backOffPolicy.backOff(ctx);
169
+
170
+ expect(ctx.delay).equals(100);
171
+ });
172
+
173
+ it('should not update the delay in the BackOffContext if delay is greater than or equal to maxDelay', async () => {
174
+ const ctx: BackOffContext = {
175
+ startTime: Date.now(),
176
+ delay: 1000,
177
+ retryContext: {
178
+ startTime: Date.now(),
179
+ retryCount: 0,
180
+ retryErrors: [],
181
+ notRetryErrors: [],
182
+ backOffOptions: {
183
+ delay: 1000,
184
+ maxDelay: 1000,
185
+ multiplier: 2,
186
+ random: false
187
+ }
188
+ }
189
+ };
190
+
191
+ await backOffPolicy.backOff(ctx);
192
+
193
+ expect(ctx.delay).equals(1000);
194
+ });
195
+
196
+ it('should update the delay in the BackOffContext with random delay if random is true', async () => {
197
+ const ctx: BackOffContext = {
198
+ startTime: Date.now(),
199
+ delay: 100,
200
+ retryContext: {
201
+ startTime: Date.now(),
202
+ retryCount: 0,
203
+ retryErrors: [],
204
+ notRetryErrors: [],
205
+ backOffOptions: {
206
+ delay: 100,
207
+ maxDelay: 1000,
208
+ multiplier: 2,
209
+ random: true
210
+ }
211
+ }
212
+ };
213
+
214
+ const randomStub = sinon.stub(Math, 'random').returns(0.5);
215
+
216
+ await backOffPolicy.backOff(ctx);
217
+
218
+ expect(ctx.delay).to.be.eq(150);
219
+
220
+ randomStub.restore();
221
+ });
222
+
223
+ it('should update the delay in the BackOffContext with random delay if random is true and multiplier is not provided', async () => {
224
+ const ctx: BackOffContext = {
225
+ startTime: Date.now(),
226
+ delay: 100,
227
+ retryContext: {
228
+ startTime: Date.now(),
229
+ retryCount: 0,
230
+ retryErrors: [],
231
+ notRetryErrors: [],
232
+ backOffOptions: {
233
+ delay: 100,
234
+ maxDelay: 1000,
235
+ random: true
236
+ }
237
+ }
238
+ };
239
+
240
+ await backOffPolicy.backOff(ctx);
241
+
242
+ expect(ctx.delay).to.be.greaterThan(100);
243
+ expect(ctx.delay).to.be.lessThanOrEqual(1000);
244
+ });
245
+ });
246
+ });
@@ -0,0 +1,43 @@
1
+ import { Component, timeout } from '@celljs/core';
2
+ import { BackOffContext, BackOffPolicy } from './back-off-protocol';
3
+ import { RetryContext } from '../retry';
4
+
5
+ @Component(BackOffPolicy)
6
+ export class DefaultBackOffPolicyImpl implements BackOffPolicy {
7
+ async start(ctx: RetryContext): Promise<BackOffContext> {
8
+ const { backOffOptions } = ctx;
9
+ const delay = typeof backOffOptions?.delay === 'function' ? await backOffOptions.delay() : backOffOptions?.delay;
10
+ return {
11
+ delay: delay ?? 100,
12
+ startTime: Date.now(),
13
+ retryContext: ctx
14
+ };
15
+ }
16
+ async backOff(ctx: BackOffContext): Promise<void> {
17
+ const { retryContext, delay } = ctx;
18
+ const { backOffOptions } = retryContext;
19
+ if (!backOffOptions) {
20
+ return;
21
+ }
22
+ const minDelay = typeof backOffOptions.delay === 'function' ? await backOffOptions.delay() : (backOffOptions.delay ?? 100);
23
+ const maxDelay = typeof backOffOptions.maxDelay === 'function' ? await backOffOptions.maxDelay() : backOffOptions.maxDelay;
24
+ const multiplier = backOffOptions?.multiplier;
25
+ const random = backOffOptions?.random;
26
+ let nextDelay = delay;
27
+ if (maxDelay) {
28
+ if (multiplier) {
29
+ if (random) {
30
+ nextDelay = Math.floor(nextDelay * (1 + Math.random() * (multiplier - 1)));
31
+ } else {
32
+ nextDelay = nextDelay * multiplier;
33
+ }
34
+ } else {
35
+ nextDelay = minDelay + Math.floor(Math.random() * (maxDelay - minDelay));
36
+ }
37
+ nextDelay = Math.min(maxDelay, nextDelay);
38
+ }
39
+ ctx.delay = nextDelay;
40
+ await timeout(nextDelay);
41
+ }
42
+
43
+ }
@@ -0,0 +1,14 @@
1
+ import { RetryContext } from '../retry/retry-protocol';
2
+
3
+ export const BackOffPolicy = Symbol('BackOffPolicy');
4
+
5
+ export interface BackOffPolicy {
6
+ start(ctx: RetryContext): Promise<BackOffContext>;
7
+ backOff(ctx: BackOffContext): Promise<void>;
8
+ }
9
+
10
+ export interface BackOffContext {
11
+ delay: number;
12
+ startTime: number;
13
+ retryContext: RetryContext;
14
+ }
@@ -0,0 +1,2 @@
1
+ export * from './back-off-protocol';
2
+ export * from './back-off-policy';
@@ -0,0 +1 @@
1
+ export * from './retry-error';
@@ -0,0 +1,5 @@
1
+ import { CustomError } from '@celljs/core';
2
+
3
+ export class RetryError extends CustomError {
4
+
5
+ }
@@ -0,0 +1,4 @@
1
+ export * from './retry';
2
+ export * from './policy';
3
+ export * from './back-off';
4
+ export * from './error';
@@ -0,0 +1,4 @@
1
+ import { autoBind } from '@celljs/core';
2
+ import './index';
3
+
4
+ export default autoBind();
@@ -0,0 +1,2 @@
1
+ export * from './policy-protocol';
2
+ export * from './retry-policy';
@@ -0,0 +1,7 @@
1
+ import { RetryContext } from '../retry/retry-protocol';
2
+
3
+ export const RetryPolicy = Symbol('RetryPolicy');
4
+
5
+ export interface RetryPolicy {
6
+ canRetry(ctx: RetryContext): Promise<boolean>;
7
+ }
@@ -0,0 +1,125 @@
1
+ import { DefaultRetryPolicy } from './retry-policy';
2
+ import { RetryContext } from '../retry/retry-protocol';
3
+ import * as chai from 'chai';
4
+ import { RetryError } from '../error';
5
+ const expect = chai.expect;
6
+
7
+ describe('DefaultRetryPolicy', () => {
8
+ let retryPolicy: DefaultRetryPolicy;
9
+
10
+ beforeEach(() => {
11
+ retryPolicy = new DefaultRetryPolicy();
12
+ });
13
+
14
+ it('should return false if timeout is exceeded', async () => {
15
+ const ctx: RetryContext = {
16
+ startTime: Date.now(),
17
+ timeout: 100, // 100 ms
18
+ maxAttempts: 3,
19
+ retryCount: 0,
20
+ retryErrors: [],
21
+ notRetryErrors: []
22
+ };
23
+
24
+ // Simulate timeout exceeded
25
+ await new Promise(resolve => setTimeout(resolve, 200));
26
+
27
+ const result = await retryPolicy.canRetry(ctx);
28
+
29
+ expect(result).equals(false);
30
+ });
31
+
32
+ it('should return false if maxAttempts is exceeded', async () => {
33
+ const ctx: RetryContext = {
34
+ startTime: Date.now(),
35
+ timeout: undefined,
36
+ maxAttempts: 3,
37
+ retryCount: 4,
38
+ retryErrors: [],
39
+ notRetryErrors: []
40
+ };
41
+
42
+ const result = await retryPolicy.canRetry(ctx);
43
+
44
+ expect(result).equals(false);
45
+ });
46
+
47
+ it('should return false if lastError is in notRetryErrors', async () => {
48
+ const ctx: RetryContext = {
49
+ startTime: Date.now(),
50
+ timeout: undefined,
51
+ maxAttempts: undefined,
52
+ retryCount: 0,
53
+ lastError: new RetryError(),
54
+ retryErrors: [],
55
+ notRetryErrors: [RetryError]
56
+ };
57
+
58
+ const result = await retryPolicy.canRetry(ctx);
59
+
60
+ expect(result).equals(false);
61
+ });
62
+
63
+ it('should return false if lastError is not in retryErrors', async () => {
64
+
65
+ const ctx: RetryContext = {
66
+ startTime: Date.now(),
67
+ timeout: undefined,
68
+ maxAttempts: undefined,
69
+ retryCount: 0,
70
+ lastError: new Error(),
71
+ retryErrors: [RetryError],
72
+ notRetryErrors: []
73
+ };
74
+
75
+ const result = await retryPolicy.canRetry(ctx);
76
+
77
+ expect(result).equals(false);
78
+ });
79
+
80
+ it('should return true if none of the conditions are met', async () => {
81
+ const ctx: RetryContext = {
82
+ startTime: Date.now(),
83
+ timeout: undefined,
84
+ maxAttempts: undefined,
85
+ retryCount: 0,
86
+ retryErrors: [],
87
+ notRetryErrors: []
88
+ };
89
+
90
+ const result = await retryPolicy.canRetry(ctx);
91
+
92
+ expect(result).equals(true);
93
+ });
94
+
95
+ it('should return true if lastError is in retryErrors', async () => {
96
+ const ctx: RetryContext = {
97
+ startTime: Date.now(),
98
+ timeout: undefined,
99
+ maxAttempts: undefined,
100
+ retryCount: 0,
101
+ lastError: new RetryError(),
102
+ retryErrors: [RetryError],
103
+ notRetryErrors: []
104
+ };
105
+
106
+ const result = await retryPolicy.canRetry(ctx);
107
+
108
+ expect(result).equals(true);
109
+ });
110
+
111
+ it('should return true if maxAttempts is not exceeded', async () => {
112
+ const ctx: RetryContext = {
113
+ startTime: Date.now(),
114
+ timeout: undefined,
115
+ maxAttempts: 3,
116
+ retryCount: 2,
117
+ retryErrors: [],
118
+ notRetryErrors: []
119
+ };
120
+
121
+ const result = await retryPolicy.canRetry(ctx);
122
+
123
+ expect(result).equals(true);
124
+ });
125
+ });