summaryrefslogtreecommitdiff
path: root/lib/internal/perf/event_loop_delay.js
blob: 1c1d657a9a0e61382cc81aa10b8ed4b1bbac1f6b (plain)
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
'use strict';
const {
  ReflectConstruct,
  SafeMap,
  Symbol,
} = primordials;

const {
  codes: {
    ERR_ILLEGAL_CONSTRUCTOR,
    ERR_INVALID_THIS,
  },
} = require('internal/errors');

const {
  createELDHistogram,
} = internalBinding('performance');

const {
  validateInteger,
  validateObject,
} = require('internal/validators');

const {
  Histogram,
  kHandle,
  kMap,
} = require('internal/histogram');

const {
  kEmptyObject,
} = require('internal/util');

const {
  makeTransferable,
} = require('internal/worker/js_transferable');

const kEnabled = Symbol('kEnabled');

class ELDHistogram extends Histogram {
  constructor(i) {
    throw new ERR_ILLEGAL_CONSTRUCTOR();
  }

  /**
   * @returns {boolean}
   */
  enable() {
    if (this[kEnabled] === undefined)
      throw new ERR_INVALID_THIS('ELDHistogram');
    if (this[kEnabled]) return false;
    this[kEnabled] = true;
    this[kHandle].start();
    return true;
  }

  /**
   * @returns {boolean}
   */
  disable() {
    if (this[kEnabled] === undefined)
      throw new ERR_INVALID_THIS('ELDHistogram');
    if (!this[kEnabled]) return false;
    this[kEnabled] = false;
    this[kHandle].stop();
    return true;
  }
}

/**
 * @param {{
 *   resolution : number
 * }} [options]
 * @returns {ELDHistogram}
 */
function monitorEventLoopDelay(options = kEmptyObject) {
  validateObject(options, 'options');

  const { resolution = 10 } = options;
  validateInteger(resolution, 'options.resolution', 1);

  return makeTransferable(ReflectConstruct(
    function() {
      this[kEnabled] = false;
      this[kHandle] = createELDHistogram(resolution);
      this[kMap] = new SafeMap();
    }, [], ELDHistogram));
}

module.exports = monitorEventLoopDelay;