Code coverage report for node/src/apm/prometheus/timer.ts

Statements: 18.52% (5 / 27)      Branches: 0% (0 / 4)      Functions: 0% (0 / 8)      Lines: 18.52% (5 / 27)      Ignored: none     

All files » node/src/apm/prometheus/ » timer.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 661 1 1   1                                                                                     1                                    
import {PromMetric, PromOptions} from './metric';
import {TimerWrapper, TimerWrapperFactory, Tags, Providers} from '@btilford/ts-base-core';
import {Histogram as Delegate, Registry} from 'prom-client';
 
export class PromTimerWrapper<T> extends PromMetric implements TimerWrapper<T> {
  protected readonly impl: Delegate<any>;
 
  constructor(name: string, tags: Tags, options: PromOptions) {
    super(name, tags, options);
    this.impl = new Delegate({
      name:this.name,
      help: options.help,
      registers: options.registry || [Providers.provide(Registry)],
      aggregator: options.aggregator,
      labelNames: [...this.supportedLabels],
    });
  }
 
  wrap(func: (...args: unknown[]) => T): (...args: unknown[]) => T {
    const timer = this.impl;
    const _tags = this.filterTags(this.tags);
    return function prometheusTimerWrapper(...args: unknown[]): T {
      const end = timer.startTimer(_tags);
      const result: T = func(...args);
      try {
        if (result instanceof Promise) {
          result.then(result => {
            end();
            return result;
          }).catch(err => {
            end();
            return err;
          });
        } else {
          end();
        }
      } catch (error) {
        end();
        throw error;
      }
      return result;
    };
  }
 
 
}
 
export class PromTimerWrapperFactory extends TimerWrapperFactory {
  protected readonly options: PromOptions;
 
  constructor(options: PromOptions) {
    super();
    this.options = { ...options };
  }
 
  timer<T>(name: string, tags): TimerWrapper<T> {
    return new PromTimerWrapper(name, tags, this.options);
  }
 
  asyncTimer<T>(name: string, tags?): TimerWrapper<Promise<T>> {
    return new PromTimerWrapper(name, tags, this.options);
  }
 
 
}