UNPKG

2.33 kBJavaScriptView Raw
1"use strict";
2/*!
3 * Copyright 2017 Google Inc. All Rights Reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17Object.defineProperty(exports, "__esModule", { value: true });
18exports.Histogram = void 0;
19/*!
20 * The Histogram class is used to capture the lifespan of messages within the
21 * the client. These durations are then used to calculate the 99th percentile
22 * of ack deadlines for future messages.
23 *
24 * @private
25 * @class
26 */
27class Histogram {
28 constructor(options) {
29 this.options = Object.assign({ min: 0, max: Number.MAX_SAFE_INTEGER }, options);
30 this.data = new Map();
31 this.length = 0;
32 }
33 /*!
34 * Adds a value to the histogram.
35 *
36 * @private
37 * @param {numnber} value - The value in milliseconds.
38 */
39 add(value) {
40 value = Math.ceil(value);
41 value = Math.max(value, this.options.min);
42 value = Math.min(value, this.options.max);
43 if (!this.data.has(value)) {
44 this.data.set(value, 0);
45 }
46 const count = this.data.get(value);
47 this.data.set(value, count + 1);
48 this.length += 1;
49 }
50 /*!
51 * Retrieves the nth percentile of recorded values.
52 *
53 * @private
54 * @param {number} percent The requested percentage.
55 * @return {number}
56 */
57 percentile(percent) {
58 percent = Math.min(percent, 100);
59 let target = this.length - this.length * (percent / 100);
60 const keys = Array.from(this.data.keys());
61 let key;
62 for (let i = keys.length - 1; i > -1; i--) {
63 key = keys[i];
64 target -= this.data.get(key);
65 if (target <= 0) {
66 return key;
67 }
68 }
69 return this.options.min;
70 }
71}
72exports.Histogram = Histogram;
73//# sourceMappingURL=histogram.js.map
\No newline at end of file