-
Notifications
You must be signed in to change notification settings - Fork 4
Retry decorator #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nicolaecaliman
wants to merge
13
commits into
labs42io:develop
Choose a base branch
from
nicolaecaliman:retry-decorator
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
b36183c
Retry decorator
Caliman-Nicolae 50a3187
Retry decorator tests
Caliman-Nicolae 6afefaf
Retry decorator split code into files
Caliman-Nicolae 1d0e59c
Retry decorator
Caliman-Nicolae 5c1088e
Retry decorator fix test
Caliman-Nicolae b3a4ab5
add new test, remove unused code, simplifying function
Caliman-Nicolae fdfc768
Retry decorator, fix count scope
Caliman-Nicolae 8385a84
remove switch case statement
Caliman-Nicolae 66fc5e8
remove unused code
Caliman-Nicolae 7f832a1
Retry decorator tests
Caliman-Nicolae 6db7068
ReMove .only
Caliman-Nicolae bc449ff
Retry decorator, fixes
Caliman-Nicolae 6e50717
Fix intendations
Caliman-Nicolae File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { retry } from '../lib'; | ||
|
|
||
| class Service { | ||
| @retry(3) | ||
| do(): Promise<number> { | ||
| return new Promise((res, rej) => { | ||
| setTimeout(res, 1000); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| const t = new Service().do().catch(err => console.log(err.message)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import { raiseStrategy } from '../utils'; | ||
| import { DEFAULT_ERROR, DEFAULT_OPTIONS, RetryOptions } from './RetryOptions'; | ||
| import { WaitStrategy } from './WaitStrategy'; | ||
|
|
||
| export class Retryer { | ||
| private attempts: number = 0; | ||
| private readonly retryOptions: RetryOptions = { ...DEFAULT_OPTIONS, ...this.options }; | ||
|
|
||
| constructor( | ||
| private readonly options: RetryOptions, | ||
| private readonly method: any, | ||
| private readonly instance: any, | ||
| private readonly retryCount: number, | ||
| ) { | ||
| this.attempts = (!this.retryCount || this.retryCount < 0) ? 0 : this.retryCount; | ||
| } | ||
|
|
||
| public getResponse(): any | Promise<any> { | ||
| try { | ||
| const response = this.method(); | ||
| const isPromiseLike = response && typeof response.then === 'function'; | ||
|
|
||
| return isPromiseLike ? this.getAsyncResponse(response) : response; | ||
| } catch (err) { | ||
| const isFiltered = this.retryOptions.errorFilter.bind(this.instance)(err); | ||
|
|
||
| return isFiltered ? this.retryGetSyncResponse() : this.error(); | ||
| } | ||
| } | ||
|
|
||
| private retryGetSyncResponse(): any { | ||
| for (let index = 0; index < this.attempts; index += 1) { | ||
| try { | ||
| return this.method(); | ||
| } catch (err) { | ||
| const filteredError = this.retryOptions.errorFilter.bind(this.instance)(err); | ||
|
|
||
| if (!filteredError) { | ||
| return this.error(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return this.error(); | ||
| } | ||
|
|
||
| private async getAsyncResponse(asyncResponse: any): Promise<any> { | ||
| for (let index = 0; index <= this.attempts; index += 1) { | ||
| await this.waitBeforeResponse(index); | ||
|
|
||
| try { | ||
| return index === 0 ? await asyncResponse : await this.method(); | ||
| } catch (err) { | ||
| const filteredError = this.retryOptions.errorFilter.bind(this.instance)(err); | ||
|
|
||
| if (!filteredError) { | ||
| return this.error(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return this.error(); | ||
| } | ||
|
|
||
| private async waitBeforeResponse(attemptIndex: number): Promise<void> { | ||
| if (attemptIndex > 0) { | ||
| const waitStrategy = new WaitStrategy(this.retryOptions.waitPattern); | ||
| await waitStrategy.wait(attemptIndex - 1); | ||
| } | ||
| } | ||
|
|
||
| private error() { | ||
| const raise = raiseStrategy(this.retryOptions); | ||
|
|
||
| return raise(new Error(DEFAULT_ERROR)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import { WaitPattern } from './RetryOptions'; | ||
|
|
||
| export class WaitStrategy { | ||
|
|
||
| constructor( | ||
| private readonly waitPattern: WaitPattern, | ||
| ) { } | ||
|
|
||
| public wait(index: number): Promise<void> { | ||
| if (!this.waitPattern) { | ||
| return Promise.resolve(); | ||
| } | ||
|
|
||
| const timeout = this.getTimeout(index) || 0; | ||
| return new Promise(resolve => setTimeout(resolve, timeout)); | ||
| } | ||
|
|
||
| private getTimeout(index: number): number { | ||
| if (Array.isArray(this.waitPattern)) { | ||
| const values = this.waitPattern as number[]; | ||
| const count = values.length; | ||
|
|
||
| return index > count ? values[count - 1] : values[index]; | ||
| } | ||
|
|
||
| if (typeof this.waitPattern === 'number') { | ||
| return this.waitPattern as number; | ||
| } | ||
|
|
||
| if (typeof this.waitPattern === 'function') { | ||
| return (this.waitPattern as Function)(index); | ||
| } | ||
|
|
||
| throw new Error(`Option ${typeof this.waitPattern} is not supported for 'waitPattern'.`); | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import { Retryer } from './Retryer'; | ||
| import { RetryOptions } from './RetryOptions'; | ||
|
|
||
| export { RetryOptions }; | ||
|
|
||
| /** | ||
| * Retries the execution of a method for a given number of attempts. | ||
| * If the method fails to succeed after `attempts` retries, it fails | ||
| * with error `Retry failed.` | ||
| * @param attempts max number of attempts to retry execution | ||
| * @param options (optional) retry options | ||
| */ | ||
| export function retry(attempts: number, options?: RetryOptions): any { | ||
| return function (target: any, propertyKey: any, descriptor: PropertyDescriptor) { | ||
|
|
||
| const method: Function = descriptor.value; | ||
|
|
||
| descriptor.value = function () { | ||
| const args = arguments; | ||
| const retryer = new Retryer(options, () => method.apply(this, args), this, attempts); | ||
|
|
||
| return retryer.getResponse(); | ||
| }; | ||
|
|
||
| return descriptor; | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { RetryOptions } from '../retry'; | ||
|
|
||
| const DEFAULT_ON_ERROR = 'throw'; | ||
|
|
||
| export function raiseStrategy(options: RetryOptions) { | ||
| const value = options && options.onError || DEFAULT_ON_ERROR; | ||
|
|
||
| switch (value) { | ||
| case 'reject': | ||
| return err => Promise.reject(err); | ||
| case 'throw': | ||
| return (err) => { throw err; }; | ||
| case 'ignore': | ||
| return () => { }; | ||
| case 'ignoreAsync': | ||
| return () => Promise.resolve(); | ||
| default: | ||
| throw new Error(`Option ${value} is not supported for 'behavior'.`); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import { expect } from 'chai'; | ||
| import { RetryOptions } from '../../lib'; | ||
| import { Retryer } from '../../lib/retry/Retryer'; | ||
|
|
||
| describe('Retryer class', () => { | ||
| let retryer: Retryer; | ||
|
|
||
| describe('when called method is synchrone', () => { | ||
| it('should return result', () => { | ||
| retryer = new Retryer({} as RetryOptions, () => 'Success 42!', {} as any, 3); | ||
|
|
||
| expect(retryer.getResponse()).to.equal('Success 42!'); | ||
| }); | ||
|
|
||
| it('should throw error with message \'Retry failed\'', () => { | ||
| retryer = new Retryer( | ||
| {} as RetryOptions, | ||
| () => { throw new Error('Failed 42'); }, | ||
| {} as any, | ||
| 3, | ||
| ); | ||
|
|
||
| expect(() => retryer.getResponse()).to.throw('Retry failed.'); | ||
| }); | ||
|
|
||
| it('should return result if throw\'n error is not filtered as expected', () => { | ||
| retryer = new Retryer( | ||
| { errorFilter: (err: Error) => err.message === 'Error 42.' } as RetryOptions, | ||
| () => { throw new Error('Error.'); }, | ||
| {} as any, | ||
| 3, | ||
| ); | ||
|
|
||
| expect(() => retryer.getResponse()).to.throw('Retry failed.'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('when called method is asynchrone', () => { | ||
| it('should return result', async () => { | ||
| retryer = new Retryer({} as RetryOptions, () => Promise.resolve('Success 42!'), {} as any, 3); | ||
| const response = await retryer.getResponse(); | ||
|
|
||
| expect(response).to.equal('Success 42!'); | ||
| }); | ||
|
|
||
| it('should throw error with message \'Retry failed\'', async () => { | ||
| retryer = new Retryer( | ||
| {} as RetryOptions, | ||
| () => Promise.reject('Failed 42.'), | ||
| {} as any, | ||
| 3, | ||
| ); | ||
|
|
||
| await expect(retryer.getResponse()).to.eventually.be.rejectedWith('Retry failed.'); | ||
| }); | ||
|
|
||
| it('should return result if throw\'n error is not filtered as expected', async () => { | ||
| retryer = new Retryer( | ||
| { errorFilter: (err: Error) => err.message === 'Error 42.' } as RetryOptions, | ||
| () => Promise.reject('Error 42.'), | ||
| {} as any, | ||
| 3, | ||
| ); | ||
|
|
||
| await expect(retryer.getResponse()).to.eventually.be.rejectedWith('Retry failed.'); | ||
| }); | ||
|
|
||
| describe('when method should wait before retry', () => { | ||
| it('should delay expected time when pattern is of type number', async () => { | ||
| retryer = new Retryer( | ||
| { waitPattern: 400 } as RetryOptions, | ||
| () => Promise.reject('Error 42.'), | ||
| {} as any, | ||
| 3, | ||
| ); | ||
|
|
||
| const delay = await getFunctionDelay(async () => { | ||
| return await expect(retryer.getResponse()).to.eventually.be.rejectedWith('Retry failed.'); | ||
| }); | ||
|
|
||
| expect(delay).to.be.approximately(1200, 15); | ||
| }); | ||
|
|
||
| it('should delay expected time when pattern is of type function', async () => { | ||
| retryer = new Retryer( | ||
| { waitPattern: () => { return 300; } } as RetryOptions, | ||
| () => Promise.reject('Error 42.'), | ||
| {} as any, | ||
| 3, | ||
| ); | ||
|
|
||
| const delay = await getFunctionDelay(async () => { | ||
| return await expect(retryer.getResponse()).to.eventually.be.rejectedWith('Retry failed.'); | ||
| }); | ||
|
|
||
| expect(delay).to.be.approximately(900, 15); | ||
| }); | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| async function getFunctionDelay(method: Function): Promise<number> { | ||
| const time = new Date().getTime(); | ||
|
|
||
| await method(); | ||
|
|
||
| return new Date().getTime() - time; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import { expect } from 'chai'; | ||
| import { WaitStrategy } from '../../lib/retry/WaitStrategy'; | ||
|
|
||
| describe('WaitStrategy class', () => { | ||
| let strategy: WaitStrategy; | ||
|
|
||
| it('should delay expected time when pattern is of type number', async () => { | ||
| strategy = new WaitStrategy(400); | ||
| const delay = await getFunctionDelay(() => strategy.wait(0)); | ||
| expect(delay).to.be.approximately(400, 5); | ||
| }); | ||
|
|
||
| it('should delay expected time when pattern is of type function', async () => { | ||
| strategy = new WaitStrategy(() => { return 300; }); | ||
| const delay = await getFunctionDelay(() => strategy.wait(1)); | ||
| expect(delay).to.be.approximately(300, 5); | ||
| }); | ||
|
|
||
| it('should delay expected time when pattern is of type array', async () => { | ||
| strategy = new WaitStrategy([100, 300, 200]); | ||
|
|
||
| let delay = await getFunctionDelay(() => strategy.wait(0)); | ||
| expect(delay).to.be.approximately(100, 5); | ||
|
|
||
| delay = await getFunctionDelay(() => strategy.wait(1)); | ||
| expect(delay).to.be.approximately(300, 5); | ||
|
|
||
| delay = await getFunctionDelay(() => strategy.wait(2)); | ||
| expect(delay).to.be.approximately(200, 5); | ||
| }); | ||
| }); | ||
|
|
||
| async function getFunctionDelay(method: Function): Promise<number> { | ||
| const time = new Date().getTime(); | ||
|
|
||
| await method(); | ||
|
|
||
| return new Date().getTime() - time; | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.