Code coverage report for core/src/profiling/decorators.ts

Statements: 22.22% (8 / 36)      Branches: 0% (0 / 16)      Functions: 0% (0 / 8)      Lines: 23.53% (8 / 34)      Ignored: none     

All files » core/src/profiling/ » decorators.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 671 1 1 1 1     1                 1                                                                   1                                
import {accept, Filter} from '../decorators';
import {internal} from '../internal';
import {Providers} from '../providers';
import {joinFqn, orUseSupplier} from '../util';
import {Profiler} from './profiler';
 
 
const { logger, MSG_FMT } = internal;
 
 
export type ProfileOptions = {
  label?: string;
  filter?: Filter;
  profiler?: Profiler;
}
 
export function Profile(options: ProfileOptions = {}): MethodDecorator {
  return function (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor): PropertyDescriptor {
    const original = descriptor.value;
    const fqn = options?.label || joinFqn(propertyKey, target.constructor.name);
 
    const log = logger('@Profile');
    log.debug(MSG_FMT.annotatingMethod, target.constructor.name, propertyKey, 'Profile', options);
 
 
    descriptor.value = function (...args: unknown[]): unknown {
      let result;
      if (accept(options.filter)) {
        const profiler = Providers.useOrProvide(Profiler, options.profiler);
        profiler.profile(fqn);
        result = original.apply(this, ...args);
        if (result instanceof Promise) {
          result.then(() => profiler.profileEnd(fqn))
        }
        else {
          profiler.profileEnd(fqn);
        }
 
      }
      else {
        result = original.apply(this, ...args);
      }
      return result;
 
    };
    return descriptor;
  }
}
 
 
export function ProfileTimestamp(options: ProfileOptions = {}): MethodDecorator {
  return function (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor): PropertyDescriptor {
    const log = logger('@ProfileTimestamp');
    log.debug(MSG_FMT.annotatingMethod, target.constructor.name, propertyKey, 'ProfileTimestamp', options);
    const original = descriptor.value;
    const _label = options.label || `${target.constructor.name}.${String(propertyKey)}`;
 
    descriptor.value = function (...args: unknown[]): unknown {
      if (accept(options.filter)) {
        orUseSupplier(options.profiler, () => Providers.provide(Profiler)).timeStamp(_label);
      }
      return original.apply(this, ...args);
    };
    return descriptor;
  }
}