UNPKG

2.01 kBJavaScriptView Raw
1/**
2 * Copyright 2015 Google Inc. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17'use strict';
18
19function RateLimiterPolicy(samplesPerSecond) {
20 if (samplesPerSecond > 1000) {
21 samplesPerSecond = 1000;
22 }
23 this.traceWindow = 1000 / samplesPerSecond;
24 this.nextTraceStart = Date.now();
25}
26
27RateLimiterPolicy.prototype.shouldTrace = function(dateMillis) {
28 if (dateMillis < this.nextTraceStart) {
29 return false;
30 }
31 this.nextTraceStart = dateMillis + this.traceWindow;
32 return true;
33};
34
35function FilterPolicy(basePolicy, filterUrls) {
36 this.basePolicy = basePolicy;
37 this.filterUrls = filterUrls;
38}
39
40FilterPolicy.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
47FilterPolicy.prototype.shouldTrace = function(dataMillis, url) {
48 return !this.matches(url) && this.basePolicy.shouldTrace(dataMillis, url);
49};
50
51function TraceAllPolicy() {}
52
53TraceAllPolicy.prototype.shouldTrace = function() { return true; };
54
55module.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};