Code coverage report for core/src/errors/retry.ts

Statements: 64.38% (47 / 73)      Branches: 45.45% (10 / 22)      Functions: 66.67% (12 / 18)      Lines: 64.38% (47 / 73)      Ignored: none     

All files » core/src/errors/ » retry.ts
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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 2221 1                       1             1 1 1             6       6   6                                                                                                                                                                           1           5 5       5         8 8   8 4 4     4 3 3 3       3   3                   3 3         1 1         1             5       5       1 3         3 3   3 3 3 3 3 3 3 3 5       3 3       3        
import {logger, MSG_FMT} from '../internal/log';
import {joinFqn} from '../util';
 
 
export type RetryOptions = {
  name?: string;
 
  maxAttempts: number;
  interval?: number | number[];
  backoff?: number | number[];
};
 
 
export class RetriesExceeded extends Error {
 
  readonly lastErr: Error;
  readonly retryOptions: RetryOptions;
 
 
  constructor(message: string, lastErr: Error, retryOptions: RetryOptions) {
    super(message);
    this.lastErr = lastErr;
    this.retryOptions = retryOptions;
  }
}
 
 
function shift(val?: number | number[]): number | undefined {
  let result: number | undefined;
  Iif (val instanceof Array) {
    result = val.shift();
  }
  else {
    result = val;
  }
  return result;
}
 
 
// Extending Promise doesn't seem possible, runtime errors...
//
// TypeError: undefined is not a promise
// at Trying.Promise (<anonymous>)
// at new Trying (src/errors/retry.ts:42:5)
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class Trying<T> extends Promise<T> {
 
  constructor(
    fn: (...args: unknown[]) => Promise<T>,
    readonly options: RetryOptions,
    readonly thisArg?: Record<string, any>,
    readonly args?: unknown[],
  ) {
    super((resolve, reject) => {
      const name = options.name || fn.name;
      const log = logger(name);// log;
      let lastInterval: number;
 
 
      let counter = 0;
 
 
      function run(): void {
        ++counter;
        let promise: Promise<T>;
 
        if (args) {
          promise = fn.apply(thisArg, args);
        }
        else {
          promise = fn.apply(thisArg);
        }
 
        promise.then(result => {
          log.debug('Resolved after %d retry attempts.', counter);
          resolve(result);
        }).catch(error => {
          if (counter < options.maxAttempts) {
            const wait = shift(options.interval);
            const backoff = shift(options.backoff) || 0;
            const interval = wait
                             ? wait * backoff + wait
                             : lastInterval;
 
            lastInterval = interval;
 
            log.debug(
              'Error calling %o(). Attempt %d/%d, waiting %dms (interval:%d, backoff:%d)',
              fn,
              counter,
              options.maxAttempts,
              interval,
              wait,
              backoff,
              error,
            );
            setTimeout(() => {
              run()
            }, interval);
 
          }
          else {
            log.warn('Max retry attempts (%d) reached for %o()', options.maxAttempts, fn, error);
            reject(new RetriesExceeded(
              `Retry ${name} attempted ${options.maxAttempts} times without success!`,
              error,
              options,
            ));
          }
        });
 
      }
 
 
      run();
    });
  }
}
 
 
export async function retry(
  fn: () => Promise<unknown>,
  options: RetryOptions,
): Promise<unknown> {
  // eslint-disable-next-line sonarjs/no-identical-functions
  function trying(resolve, reject) {
    const name = options.name || fn.name;
    const log = logger(name);// log;
    let lastInterval: number;
 
 
    let counter = 0;
 
 
    // eslint-disable-next-line sonarjs/no-identical-functions
    function run(): void {
      ++counter;
      const promise: Promise<unknown> = fn();
 
      promise.then(result => {
        log.debug('Resolved after %d retry attempts.', counter);
        resolve(result);
        // eslint-disable-next-line sonarjs/no-identical-functions
      }).catch(error => {
        if (counter < options.maxAttempts) {
          const wait = shift(options.interval);
          const backoff = shift(options.backoff) || 0;
          const interval = wait
                           ? wait * backoff + wait
                           : lastInterval;
 
          lastInterval = interval;
 
          log.debug(
            'Error calling %o(). Attempt %d/%d, waiting %dms (interval:%d, backoff:%d)',
            fn,
            counter,
            options.maxAttempts,
            interval,
            wait,
            backoff,
            error,
          );
          setTimeout(() => {
            run()
          }, interval);
 
        }
        else {
          log.warn('Max retry attempts (%d) reached for %o()', options.maxAttempts, fn, error);
          const err = new RetriesExceeded(
            `Retry [${name}] attempted "${options.maxAttempts}" times without success!`,
            error,
            options,
          );
          reject(err);
        }
      });
 
    }
 
 
    run();
  }
 
 
  return new Promise(trying/*, options, thisArg, args*/);
}
 
 
export function Retry(options: RetryOptions): MethodDecorator {
  return function retryDecorator(
    target: Record<string, any>,
    prop: PropertyKey,
    desc: PropertyDescriptor,
  ): PropertyDescriptor {
    const original = desc.value;
    const name = options.name || joinFqn(prop, target.constructor.name);
 
    const log = logger('@Retry');
    log.debug(MSG_FMT.annotatingMethod, target.constructor.name, prop, 'Retry', options);
    console.dir(desc);
    desc.value = function runWithRetry(...args: unknown[]): Promise<unknown> {
      console.dir(desc);
      console.dir(this, {getters:true, showHidden:true,depth:5,colors:true});
      console.dir(target);
      const promise: Promise<unknown> = retry(
        () => original.apply(this, args),
        { name, ...options },
      );
 
      console.assert(promise instanceof Promise, `Not a Promise! ${promise.constructor.name}`);
      return promise/*.then(val => console.log('SUCCESS: result value %o'))
                    .catch(err => console.error('ERRRRRRR: ', err))*/;
    };
 
    return desc;
 
  }
}