instance.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import { COUNTER_METRIC_TYPE, GAUGE_METRIC_TYPE, DISTRIBUTION_METRIC_TYPE, SET_METRIC_TYPE } from './constants.js';
  2. import { simpleHash } from './utils.js';
  3. /**
  4. * A metric instance representing a counter.
  5. */
  6. class CounterMetric {
  7. constructor( _value) {this._value = _value;}
  8. /** @inheritDoc */
  9. get weight() {
  10. return 1;
  11. }
  12. /** @inheritdoc */
  13. add(value) {
  14. this._value += value;
  15. }
  16. /** @inheritdoc */
  17. toString() {
  18. return `${this._value}`;
  19. }
  20. }
  21. /**
  22. * A metric instance representing a gauge.
  23. */
  24. class GaugeMetric {
  25. constructor(value) {
  26. this._last = value;
  27. this._min = value;
  28. this._max = value;
  29. this._sum = value;
  30. this._count = 1;
  31. }
  32. /** @inheritDoc */
  33. get weight() {
  34. return 5;
  35. }
  36. /** @inheritdoc */
  37. add(value) {
  38. this._last = value;
  39. if (value < this._min) {
  40. this._min = value;
  41. }
  42. if (value > this._max) {
  43. this._max = value;
  44. }
  45. this._sum += value;
  46. this._count++;
  47. }
  48. /** @inheritdoc */
  49. toString() {
  50. return `${this._last}:${this._min}:${this._max}:${this._sum}:${this._count}`;
  51. }
  52. }
  53. /**
  54. * A metric instance representing a distribution.
  55. */
  56. class DistributionMetric {
  57. constructor(first) {
  58. this._value = [first];
  59. }
  60. /** @inheritDoc */
  61. get weight() {
  62. return this._value.length;
  63. }
  64. /** @inheritdoc */
  65. add(value) {
  66. this._value.push(value);
  67. }
  68. /** @inheritdoc */
  69. toString() {
  70. return this._value.join(':');
  71. }
  72. }
  73. /**
  74. * A metric instance representing a set.
  75. */
  76. class SetMetric {
  77. constructor( first) {this.first = first;
  78. this._value = new Set([first]);
  79. }
  80. /** @inheritDoc */
  81. get weight() {
  82. return this._value.size;
  83. }
  84. /** @inheritdoc */
  85. add(value) {
  86. this._value.add(value);
  87. }
  88. /** @inheritdoc */
  89. toString() {
  90. return Array.from(this._value)
  91. .map(val => (typeof val === 'string' ? simpleHash(val) : val))
  92. .join(':');
  93. }
  94. }
  95. const METRIC_MAP = {
  96. [COUNTER_METRIC_TYPE]: CounterMetric,
  97. [GAUGE_METRIC_TYPE]: GaugeMetric,
  98. [DISTRIBUTION_METRIC_TYPE]: DistributionMetric,
  99. [SET_METRIC_TYPE]: SetMetric,
  100. };
  101. export { CounterMetric, DistributionMetric, GaugeMetric, METRIC_MAP, SetMetric };
  102. //# sourceMappingURL=instance.js.map