All files / types/metrics Timer.ts

11.11% Statements 3/27
0% Branches 0/9
0% Functions 0/6
11.11% Lines 3/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 661x   1x   1x                                                                                                                          
import { Constants } from '../Constants';
import { Namespace } from '../Namespace';
import { Histogram } from './Histogram';
 
export class Timer extends Histogram {
  protected defaultBuckets: number[] = Constants.DefaultTimerBuckets;
 
  constructor(
    namespace: Namespace,
    name: string,
    description?: string,
    unit?: string,
    buckets: number[] = [],
    attributes: Record<string, string> = {},
  ) {
    super(namespace, name, description, unit, buckets, attributes);
  }
 
  time<A extends any[], R>(
    buckets: number[] = Constants.DefaultTimerBuckets,
    attributes: Record<string, string> = {},
    fn: (...args: A) => R | Promise<R>,
    ...args1: A
  ): R | Promise<R> {
    const startTime = new Date();
    let result: R | Promise<R>;
 
    const logTimeSpent = () => {
      const combinedAttributes = { ...attributes };
      combinedAttributes.success = success;
 
      const endTime = new Date();
      const duration = endTime.getTime() - startTime.getTime();
 
      this.record(duration, buckets, combinedAttributes);
    };
 
    let success = 'true';
    let synchronous = true;
    try {
      result = fn(...args1);
      Iif (this.isThenable(result)) {
        synchronous = false;
        void result
          .catch(() => {
            success = 'false';
          })
          .then(() => logTimeSpent());
      }
    } catch (error) {
      success = 'false';
      throw error;
    } finally {
      Iif (synchronous) {
        logTimeSpent();
      }
    }
    return result;
  }
 
  private isThenable<T>(value: any): value is Promise<T> {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
    return typeof value === 'object' && value !== null && typeof value.then === 'function';
  }
}