1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | 'use strict';
|
18 |
|
19 | function RateLimiterPolicy(samplesPerSecond) {
|
20 | if (samplesPerSecond > 1000) {
|
21 | samplesPerSecond = 1000;
|
22 | }
|
23 | this.traceWindow = 1000 / samplesPerSecond;
|
24 | this.nextTraceStart = Date.now();
|
25 | }
|
26 |
|
27 | RateLimiterPolicy.prototype.shouldTrace = function(dateMillis) {
|
28 | if (dateMillis < this.nextTraceStart) {
|
29 | return false;
|
30 | }
|
31 | this.nextTraceStart = dateMillis + this.traceWindow;
|
32 | return true;
|
33 | };
|
34 |
|
35 | function FilterPolicy(basePolicy, filterUrls) {
|
36 | this.basePolicy = basePolicy;
|
37 | this.filterUrls = filterUrls;
|
38 | }
|
39 |
|
40 | FilterPolicy.prototype.matches = function(url) {
|
41 | return this.filterUrls.some(function(candidate) {
|
42 | return (typeof candidate === 'string' && candidate === url) ||
|
43 | url.match(candidate);
|
44 | });
|
45 | };
|
46 |
|
47 | FilterPolicy.prototype.shouldTrace = function(dataMillis, url) {
|
48 | return !this.matches(url) && this.basePolicy.shouldTrace(dataMillis, url);
|
49 | };
|
50 |
|
51 | function TraceAllPolicy() {}
|
52 |
|
53 | TraceAllPolicy.prototype.shouldTrace = function() { return true; };
|
54 |
|
55 | module.exports = {
|
56 | createTracePolicy: function(config) {
|
57 | var basePolicy;
|
58 | if (config.samplingRate < 1) {
|
59 | basePolicy = new TraceAllPolicy();
|
60 | } else {
|
61 | basePolicy = new RateLimiterPolicy(config.samplingRate);
|
62 | }
|
63 | if (config.ignoreUrls && config.ignoreUrls.length > 0) {
|
64 | return new FilterPolicy(basePolicy, config.ignoreUrls);
|
65 | } else {
|
66 | return basePolicy;
|
67 | }
|
68 | }
|
69 | };
|