All files / fuse-ui-shared/decorators retry.ts

97.06% Statements 66/68
82.35% Branches 14/17
100% Functions 14/14
96.77% Lines 60/62
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160  1x 1x 1x                                       1x 1x   1x 1x   1x 1x 1x   1x   5x 5x                 1x                   1x 8x   8x   2x   2x   6x 6x   6x         2x   11x     1x 1x   1x   5x 5x 5x   5x                 1x             1x 3x 3x 3x 3x   3x 8x 8x 8x 8x 1x   7x 7x 7x   7x 1x   6x                   1x 4x   4x   12x 2x   10x   10x   8x   2x                 4x   4x    
/* tslint:disable:no-use-before-declare */
import * as _ from 'underscore';
import { createDeferred } from '../deferred';
import { sleep } from '../sleep';
/* tslint:enable:no-use-before-declare */
 
export type SequenceType = 'constant' | 'fibonacci' | 'exponential' | 'linear';
 
export type Delayable = {
  // tslint:disable-next-line:no-reserved-keywords
  type: SequenceType;
  beat?: number;
  maxDuration?: number;
  maxInterval?: number;
  maxIteration?: number;
};
 
// tslint:disable
/**
 * retry decorator
 *
 * @retry()
 */
export function retry(config: Delayable, canRetry: (e: any) => Promise<boolean>) {
  return function (target: any, key: string, descriptor: PropertyDescriptor) {
    // tslint:disable-next-line:no-parameter-reassignment
    descriptor = descriptor || Object.getOwnPropertyDescriptor(target, key);
    const action = descriptor.value;
 
    descriptor.value = function () {
      const args = _.map(arguments, x => x);
      const _this = this;
 
      return retryAction(
        function () { // tslint:disable-line
          try {
            return action.apply(_this, args);
          } catch (ex) {
            // ignore error
          }
        },
        canRetry,
        config);
    };
 
    return descriptor;
  };
}
// tslint:enable
 
export interface Sequence<T> {
  next(): T;
}
 
// tslint:disable-next-line:no-reserved-keywords
export function createSequence(type: SequenceType): Sequence<number> {
  switch (type) {
    case 'constant':
      return { next: () => 1 };
    case 'exponential': {
      let prev = 0;
 
      return {
        next: () => {
          const result = Math.pow(2, prev);
          prev++;
 
          return result;
        }
      };
    }
    case 'linear': {
      let prev = 0;
 
      return { next: () => ++prev };
    }
    case 'fibonacci': {
      let prev = 0;
      let cur = 1;
 
      return {
        next: () => {
          const result = prev + cur;
          prev = cur;
          cur = result;
 
          return result;
        }
      };
    }
    default:
      throw new Error(`unknown sequence type ${type}`);
  }
}
 
const _defaultRetryOption: Delayable = {
  type: 'constant',
  beat: 200,
  maxDuration: 120000,
  maxInterval: 30000
};
 
export async function retryAction<T>(action: () => Promise<T>, canRetry: (e: any) => Promise<boolean>, delay: Delayable) {
  const start = new Date().getTime();
  let { type, beat, maxDuration, maxInterval, maxIteration } = _.extend({}, _defaultRetryOption, delay);
  let sequence = createSequence(type);
  let invokeCount = 0;
 
  return repeat(action, canRetry, async () => {
    const now = new Date().getTime();
    invokeCount++;
    const duration = now - start;
    if (maxIteration > 0 && invokeCount >= maxIteration) {
      throw new Error(`exceeded maxIteration ${maxIteration}`);
    }
    let waitDuration = sequence.next() * beat;
    Eif (maxInterval > 0) {
      waitDuration = Math.min(maxInterval, waitDuration);
    }
    if (maxDuration > 0 && duration + waitDuration > maxDuration) {
      throw new Error(`exceeded maxDuration ${maxDuration}`);
    }
    await sleep(waitDuration);
  });
}
 
/**
 * repeat action until it resolves to promise
 * @param action async action that returns a Promise<T>
 * @param canRetry when action rejects with err, check if the error can be retried
 * @param wait wait before issue the next repeat
 */
export async function repeat<T>(action: () => Promise<T>, canRetry: (v: any) => Promise<boolean>, wait: () => Promise<void>): Promise<T> {
  const result = createDeferred<T>();
 
  const inner = async () => {
    try {
      const x = await action();
      result.resolve(x);
    } catch (innerError) {
      if (await canRetry(innerError)) {
        try {
          await wait();
          //tslint:disable-next-line:no-floating-promises
          inner();
        } catch (waitError) {
          result.reject(waitError);
        }
      } else {
        result.reject(innerError);
      }
    }
  };
 
  //tslint:disable-next-line:no-floating-promises
  inner();
 
  return result.promise;
}