@layerzerolabs/common-error-utils 0.2.8 → 0.2.10

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@layerzerolabs/common-error-utils",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -13,11 +13,16 @@
13
13
  "main": "./dist/index.cjs",
14
14
  "module": "./dist/index.js",
15
15
  "types": "./dist/index.d.ts",
16
+ "dependencies": {
17
+ "exponential-backoff": "^3.1.1",
18
+ "ms": "^2.1.3"
19
+ },
16
20
  "devDependencies": {
21
+ "@types/ms": "^2.1.0",
17
22
  "tsup": "^8.4.0",
18
23
  "vitest": "^3.2.3",
19
- "@layerzerolabs/tsup-configuration": "0.2.8",
20
- "@layerzerolabs/typescript-configuration": "0.2.8"
24
+ "@layerzerolabs/tsup-configuration": "0.2.10",
25
+ "@layerzerolabs/typescript-configuration": "0.2.10"
21
26
  },
22
27
  "publishConfig": {
23
28
  "access": "restricted",
package/src/errors.ts ADDED
@@ -0,0 +1,145 @@
1
+ const extractMessageFromJsonRpcError = (err: any): string => {
2
+ try {
3
+ if (typeof err.body === 'object' && err.body.message) {
4
+ return err.body.message;
5
+ }
6
+ const parsedBody = JSON.parse(err.body);
7
+ return parsedBody?.error?.message;
8
+ } catch {
9
+ return 'unknown';
10
+ }
11
+ };
12
+
13
+ export function convertErrorToObject(err: any): any {
14
+ return JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)));
15
+ }
16
+
17
+ export function normalizeError(err: any) {
18
+ const error = convertErrorToObject(err);
19
+ return {
20
+ // Normal Error properties
21
+ ...(error.name ? { name: error.name } : {}),
22
+ ...(error.message ? { message: error.message } : {}),
23
+ ...(error.stack ? { stack: error.stack } : {}),
24
+ // Rpc properties
25
+ ...(error.reason ? { reason: error.reason } : {}),
26
+ ...(error.code ? { code: error.code } : {}),
27
+ ...(error.event ? { event: error.event } : {}),
28
+ ...(error.body ? { body: extractMessageFromJsonRpcError(error) } : {}),
29
+ };
30
+ }
31
+
32
+ // Removes the last argument if it is an ErrorOptions
33
+ type RemoveErrorOptions<T extends any[]> = T extends [...infer U, ErrorOptions?] ? U : never;
34
+
35
+ /**
36
+ * Base class for all serializable errors.
37
+ * This class is designed to be extended by other error classes.
38
+ * It provides a way to wrap errors and a way to check if an error is in the stack of a specific error class.
39
+ * All errors that extend this class *must* have error options as the last argument in their constructor.
40
+ */
41
+ export abstract class SerializableError extends Error {
42
+ details: string[];
43
+ /*
44
+ * The instance of the error that was wrapped, if any.
45
+ * Creates a linked list of error objects.
46
+ * Only exists if the error hasn't been serialized and deserialized.
47
+ */
48
+ cause: unknown;
49
+ constructor(message: string, options?: ErrorOptions) {
50
+ super(message, options);
51
+ // for some reason, we need to set the cause directly on the instance, even after calling super
52
+ this.cause = options?.cause;
53
+ this.name = this.constructor.name;
54
+ this.details = [this.constructor.name, 'SerializableError'];
55
+ }
56
+
57
+ /*
58
+ * Checks if the error is an instance of the current class or a subclass. Returns the error if it is.
59
+ * We can't type the error as more than SerializableError because it could have been serialized and deserialized,
60
+ * which could make it lose extra fields.
61
+ */
62
+ static inStackOf<T extends abstract new (...args: any) => any>(
63
+ this: T,
64
+ error: any,
65
+ ): SerializableError | undefined {
66
+ if (error?.details?.includes(this.name)) {
67
+ return error as SerializableError;
68
+ } else if (error?.cause?.details?.includes(this.name)) {
69
+ return error.cause as SerializableError;
70
+ }
71
+ return undefined;
72
+ }
73
+
74
+ // We could limit this to only wrap serializable errors, but that could limit the flexibility of the error system.
75
+ static wrap<T extends new (...args: any) => SerializableError>(
76
+ this: T,
77
+ error: any,
78
+ // Remove the optional error arguments
79
+ ...args: RemoveErrorOptions<ConstructorParameters<T>>
80
+ ): InstanceType<T> {
81
+ const wrappedError = new this(...args, { cause: error });
82
+
83
+ wrappedError.details = error?.details
84
+ ? [wrappedError.name, ...error.details]
85
+ : [wrappedError.name, 'SerializableError', error?.name ?? 'UnknownError'];
86
+
87
+ wrappedError.message = `${wrappedError.message} > ${error?.message ?? String(error)}`;
88
+
89
+ return wrappedError as InstanceType<T>;
90
+ }
91
+ }
92
+
93
+ export class NonRetryableError extends SerializableError {
94
+ constructor(message: string, options?: ErrorOptions) {
95
+ super(message, options);
96
+ }
97
+ }
98
+
99
+ export class NotFoundError extends SerializableError {
100
+ constructor(message?: string, options?: ErrorOptions) {
101
+ super(message ? `Not found: ${message}` : 'Not found', options);
102
+ }
103
+ }
104
+
105
+ // TODO: extend this for chain specific providers
106
+ export class ProviderError extends SerializableError {
107
+ constructor(providerUri: string, options?: ErrorOptions) {
108
+ super(`Provider error at host '${ProviderError.parseHost(providerUri)}'`, options);
109
+ }
110
+
111
+ private static parseHost(providerUri: string): string {
112
+ try {
113
+ const url = new URL(providerUri);
114
+ return url.host;
115
+ } catch {
116
+ return 'UNKNOWN_HOST';
117
+ }
118
+ }
119
+ }
120
+
121
+ export class NonEmittableError extends SerializableError {
122
+ constructor(message: string, options?: ErrorOptions) {
123
+ super(message, options);
124
+ this.name = 'NonEmittableError';
125
+ }
126
+ }
127
+
128
+ export class QuorumNotAchievedYet extends SerializableError {
129
+ constructor(options?: ErrorOptions) {
130
+ super('The quorum was not achieved yet', options);
131
+ }
132
+ }
133
+
134
+ export class MultiError extends Error {
135
+ constructor(public readonly errs: any[]) {
136
+ super(errs.map((err) => err.message).join(', '));
137
+ }
138
+ }
139
+
140
+ export const throwError = <Err extends Error>(
141
+ message: string,
142
+ error?: (message: string) => Err,
143
+ ): never => {
144
+ throw error?.(message) ?? new Error(message);
145
+ };
package/src/index.ts CHANGED
@@ -1,145 +1,2 @@
1
- const extractMessageFromJsonRpcError = (err: any): string => {
2
- try {
3
- if (typeof err.body === 'object' && err.body.message) {
4
- return err.body.message;
5
- }
6
- const parsedBody = JSON.parse(err.body);
7
- return parsedBody?.error?.message;
8
- } catch {
9
- return 'unknown';
10
- }
11
- };
12
-
13
- export function convertErrorToObject(err: any): any {
14
- return JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)));
15
- }
16
-
17
- export function normalizeError(err: any) {
18
- const error = convertErrorToObject(err);
19
- return {
20
- // Normal Error properties
21
- ...(error.name ? { name: error.name } : {}),
22
- ...(error.message ? { message: error.message } : {}),
23
- ...(error.stack ? { stack: error.stack } : {}),
24
- // Rpc properties
25
- ...(error.reason ? { reason: error.reason } : {}),
26
- ...(error.code ? { code: error.code } : {}),
27
- ...(error.event ? { event: error.event } : {}),
28
- ...(error.body ? { body: extractMessageFromJsonRpcError(error) } : {}),
29
- };
30
- }
31
-
32
- // Removes the last argument if it is an ErrorOptions
33
- type RemoveErrorOptions<T extends any[]> = T extends [...infer U, ErrorOptions?] ? U : never;
34
-
35
- /**
36
- * Base class for all serializable errors.
37
- * This class is designed to be extended by other error classes.
38
- * It provides a way to wrap errors and a way to check if an error is in the stack of a specific error class.
39
- * All errors that extend this class *must* have error options as the last argument in their constructor.
40
- */
41
- export abstract class SerializableError extends Error {
42
- details: string[];
43
- /*
44
- * The instance of the error that was wrapped, if any.
45
- * Creates a linked list of error objects.
46
- * Only exists if the error hasn't been serialized and deserialized.
47
- */
48
- cause: unknown;
49
- constructor(message: string, options?: ErrorOptions) {
50
- super(message, options);
51
- // for some reason, we need to set the cause directly on the instance, even after calling super
52
- this.cause = options?.cause;
53
- this.name = this.constructor.name;
54
- this.details = [this.constructor.name, 'SerializableError'];
55
- }
56
-
57
- /*
58
- * Checks if the error is an instance of the current class or a subclass. Returns the error if it is.
59
- * We can't type the error as more than SerializableError because it could have been serialized and deserialized,
60
- * which could make it lose extra fields.
61
- */
62
- static inStackOf<T extends abstract new (...args: any) => any>(
63
- this: T,
64
- error: any,
65
- ): SerializableError | undefined {
66
- if (error?.details?.includes(this.name)) {
67
- return error as SerializableError;
68
- } else if (error?.cause?.details?.includes(this.name)) {
69
- return error.cause as SerializableError;
70
- }
71
- return undefined;
72
- }
73
-
74
- // We could limit this to only wrap serializable errors, but that could limit the flexibility of the error system.
75
- static wrap<T extends new (...args: any) => SerializableError>(
76
- this: T,
77
- error: any,
78
- // Remove the optional error arguments
79
- ...args: RemoveErrorOptions<ConstructorParameters<T>>
80
- ): InstanceType<T> {
81
- const wrappedError = new this(...args, { cause: error });
82
-
83
- wrappedError.details = error?.details
84
- ? [wrappedError.name, ...error.details]
85
- : [wrappedError.name, 'SerializableError', error?.name ?? 'UnknownError'];
86
-
87
- wrappedError.message = `${wrappedError.message} > ${error?.message ?? String(error)}`;
88
-
89
- return wrappedError as InstanceType<T>;
90
- }
91
- }
92
-
93
- export class NonRetryableError extends SerializableError {
94
- constructor(message: string, options?: ErrorOptions) {
95
- super(message, options);
96
- }
97
- }
98
-
99
- export class NotFoundError extends SerializableError {
100
- constructor(message?: string, options?: ErrorOptions) {
101
- super(message ? `Not found: ${message}` : 'Not found', options);
102
- }
103
- }
104
-
105
- // TODO: extend this for chain specific providers
106
- export class ProviderError extends SerializableError {
107
- constructor(providerUri: string, options?: ErrorOptions) {
108
- super(`Provider error at host '${ProviderError.parseHost(providerUri)}'`, options);
109
- }
110
-
111
- private static parseHost(providerUri: string): string {
112
- try {
113
- const url = new URL(providerUri);
114
- return url.host;
115
- } catch {
116
- return 'UNKNOWN_HOST';
117
- }
118
- }
119
- }
120
-
121
- export class NonEmittableError extends SerializableError {
122
- constructor(message: string, options?: ErrorOptions) {
123
- super(message, options);
124
- this.name = 'NonEmittableError';
125
- }
126
- }
127
-
128
- export class QuorumNotAchievedYet extends SerializableError {
129
- constructor(options?: ErrorOptions) {
130
- super('The quorum was not achieved yet', options);
131
- }
132
- }
133
-
134
- export class MultiError extends Error {
135
- constructor(public readonly errs: any[]) {
136
- super(errs.map((err) => err.message).join(', '));
137
- }
138
- }
139
-
140
- export const throwError = <Err extends Error>(
141
- message: string,
142
- error?: (message: string) => Err,
143
- ): never => {
144
- throw error?.(message) ?? new Error(message);
145
- };
1
+ export * from './errors';
2
+ export * from './retry';
package/src/retry.ts ADDED
@@ -0,0 +1,101 @@
1
+ import { backOff } from 'exponential-backoff';
2
+ import type { StringValue } from 'ms';
3
+ import ms from 'ms';
4
+
5
+ const DEFAULT_NONRETRYABLE_ERRORS = ['NonRetryableError'];
6
+
7
+ export interface RetryPolicy {
8
+ /**
9
+ * Maximum time of a single execution attempt.
10
+ * This timeout should be as short as the longest possible execution of the Activity body.
11
+ *
12
+ * @default 10 minutes
13
+ * @format {@link https://www.npmjs.com/package/ms | ms-formatted string}
14
+ */
15
+ startToCloseTimeout?: StringValue;
16
+
17
+ /**
18
+ * Coefficient used to calculate the next retry interval.
19
+ * The next retry interval is previous interval multiplied by this coefficient.
20
+ * @minimum 1
21
+ * @default 2
22
+ */
23
+ backoffCoefficient?: number;
24
+
25
+ /**
26
+ * Interval of the first retry.
27
+ * If coefficient is 1 then it is used for all retries
28
+ * @format {@link https://www.npmjs.com/package/ms | ms-formatted string}
29
+ * @default 1 second
30
+ */
31
+ initialInterval?: StringValue;
32
+
33
+ /**
34
+ * Maximum number of attempts. When exceeded, retries stop.
35
+ *
36
+ * @default Infinity
37
+ */
38
+ maximumAttempts?: number;
39
+
40
+ /**
41
+ * Maximum interval between retries.
42
+ * Exponential backoff leads to interval increase.
43
+ * This value is the cap of the increase.
44
+ *
45
+ * @default 100x of {@link initialInterval}
46
+ * @format {@link https://www.npmjs.com/package/ms | ms-formatted string}
47
+ */
48
+ maximumInterval?: StringValue;
49
+
50
+ /**
51
+ * List of application failures types to not retry.
52
+ */
53
+ nonRetryableErrorTypes?: string[];
54
+ }
55
+
56
+ /**
57
+ * Executes a function with a retry policy.
58
+ * @param fn - The function to execute.
59
+ * @param policy - The retry policy to apply.
60
+ * @param shouldRetry - A callback that determines if the error is retryable besides the nonRetryableErrorTypes.
61
+ * @return A promise that resolves to the result of the function or rejects with an error.
62
+ * @throws Error if the function fails after all retries.
63
+ */
64
+ export const runWithRetryPolicy = <T = unknown>(
65
+ fn: () => Promise<T>,
66
+ policy?: RetryPolicy,
67
+ shouldRetry?: (err: any) => boolean,
68
+ ): Promise<T> => {
69
+ const perTryTimeout = ms(policy?.startToCloseTimeout ?? '10 minutes');
70
+ const numOfAttempts = policy?.maximumAttempts ?? Infinity;
71
+ const startingDelay = ms(policy?.initialInterval ?? '1s');
72
+ const maxDelay = policy?.maximumInterval ? ms(policy.maximumInterval) : startingDelay * 100;
73
+ const timeMultiple = Math.max(policy?.backoffCoefficient ?? 2, 1);
74
+ const nonRetryableErrorTypes = (policy?.nonRetryableErrorTypes ?? []).concat(
75
+ DEFAULT_NONRETRYABLE_ERRORS,
76
+ );
77
+
78
+ return backOff(
79
+ () =>
80
+ new Promise((resolve, reject) => {
81
+ fn().then(resolve).catch(reject);
82
+ setTimeout(() => {
83
+ reject(new Error(`Execution timed out after ${perTryTimeout}ms`));
84
+ }, perTryTimeout);
85
+ }),
86
+ {
87
+ maxDelay,
88
+ startingDelay,
89
+ jitter: 'full',
90
+ timeMultiple,
91
+ numOfAttempts,
92
+ retry: async (error: any) => {
93
+ const errorType = error?.constructor?.name ?? error?.name;
94
+ return (
95
+ !nonRetryableErrorTypes.includes(errorType) &&
96
+ (shouldRetry ? shouldRetry(error) : true)
97
+ );
98
+ },
99
+ },
100
+ );
101
+ };
@@ -0,0 +1,110 @@
1
+ import { backOff } from 'exponential-backoff';
2
+ import { afterEach, describe, expect, test, vi } from 'vitest';
3
+
4
+ import { runWithRetryPolicy } from '../src/retry';
5
+
6
+ vi.mock('exponential-backoff', async (importOriginal) => {
7
+ const originalModule = await importOriginal<typeof import('exponential-backoff')>();
8
+ return {
9
+ ...originalModule,
10
+ backOff: vi.fn(originalModule.backOff),
11
+ };
12
+ });
13
+
14
+ const mockedBackOff = vi.mocked(backOff);
15
+
16
+ describe('runWithRetryPolicy', () => {
17
+ afterEach(() => {
18
+ vi.clearAllMocks();
19
+ });
20
+
21
+ test('startToCloseTimeout', async () => {
22
+ const longRunningFn = () => new Promise(() => {}); // Never resolves
23
+
24
+ await expect(
25
+ runWithRetryPolicy(longRunningFn, {
26
+ startToCloseTimeout: '50ms',
27
+ maximumAttempts: 1,
28
+ }),
29
+ ).rejects.toThrow('Execution timed out after 50ms');
30
+ });
31
+
32
+ test('maximumAttempts', async () => {
33
+ const failingFn = vi.fn().mockRejectedValue(new Error('simulated failure'));
34
+
35
+ await expect(
36
+ runWithRetryPolicy(failingFn, {
37
+ maximumAttempts: 3,
38
+ initialInterval: '1ms',
39
+ }),
40
+ ).rejects.toThrow('simulated failure');
41
+
42
+ expect(mockedBackOff).toHaveBeenCalledWith(
43
+ expect.any(Function),
44
+ expect.objectContaining({ numOfAttempts: 3 }),
45
+ );
46
+ expect(failingFn).toHaveBeenCalledTimes(3);
47
+ });
48
+
49
+ test('initialInterval', async () => {
50
+ const fn = async () => {};
51
+
52
+ await runWithRetryPolicy(fn, {
53
+ initialInterval: '5s',
54
+ });
55
+
56
+ expect(mockedBackOff).toHaveBeenCalledWith(
57
+ expect.any(Function),
58
+ expect.objectContaining({ startingDelay: 5000 }),
59
+ );
60
+ });
61
+
62
+ test('maximumInterval', async () => {
63
+ const fn = async () => {};
64
+ await runWithRetryPolicy(fn, {
65
+ maximumInterval: '10s',
66
+ });
67
+ expect(mockedBackOff).toHaveBeenCalledWith(
68
+ expect.any(Function),
69
+ expect.objectContaining({ maxDelay: 10000 }),
70
+ );
71
+ });
72
+
73
+ test('backoffCoefficient', async () => {
74
+ const fn = async () => {};
75
+ await runWithRetryPolicy(fn, {
76
+ backoffCoefficient: 3,
77
+ });
78
+ expect(mockedBackOff).toHaveBeenCalledWith(
79
+ expect.any(Function),
80
+ expect.objectContaining({ timeMultiple: 3 }),
81
+ );
82
+ });
83
+
84
+ test('nonRetryableErrorTypes', async () => {
85
+ class CustomError extends Error {
86
+ constructor(message: string) {
87
+ super(message);
88
+ this.name = 'CustomError';
89
+ }
90
+ }
91
+
92
+ const retryableError = new Error('A retryable error');
93
+ const nonRetryableError = new CustomError('A non-retryable error');
94
+
95
+ const failingFn = vi
96
+ .fn()
97
+ .mockRejectedValueOnce(retryableError)
98
+ .mockRejectedValueOnce(nonRetryableError);
99
+
100
+ await expect(
101
+ runWithRetryPolicy(failingFn, {
102
+ maximumAttempts: 5,
103
+ initialInterval: '1ms',
104
+ nonRetryableErrorTypes: ['CustomError'],
105
+ }),
106
+ ).rejects.toThrow(nonRetryableError);
107
+
108
+ expect(failingFn).toHaveBeenCalledTimes(2);
109
+ });
110
+ });