@chainlink/external-adapter-framework 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/adapter/basic.d.ts +90 -0
- package/adapter/basic.js +325 -0
- package/adapter/basic.js.map +1 -0
- package/adapter/endpoint.d.ts +17 -0
- package/adapter/endpoint.js +20 -0
- package/adapter/endpoint.js.map +1 -0
- package/adapter/index.d.ts +4 -0
- package/adapter/index.js +21 -0
- package/adapter/index.js.map +1 -0
- package/adapter/price.d.ts +77 -0
- package/adapter/price.js +88 -0
- package/adapter/price.js.map +1 -0
- package/adapter/types.d.ts +124 -0
- package/adapter/types.js +3 -0
- package/adapter/types.js.map +1 -0
- package/background-executor.d.ts +9 -0
- package/background-executor.js +97 -0
- package/background-executor.js.map +1 -0
- package/cache/factory.d.ts +6 -0
- package/cache/factory.js +24 -0
- package/cache/factory.js.map +1 -0
- package/cache/index.d.ts +87 -0
- package/cache/index.js +133 -0
- package/cache/index.js.map +1 -0
- package/cache/local.d.ts +23 -0
- package/cache/local.js +84 -0
- package/cache/local.js.map +1 -0
- package/cache/metrics.d.ts +27 -0
- package/cache/metrics.js +121 -0
- package/cache/metrics.js.map +1 -0
- package/cache/redis.d.ts +16 -0
- package/cache/redis.js +101 -0
- package/cache/redis.js.map +1 -0
- package/config/index.d.ts +298 -0
- package/config/index.js +359 -0
- package/config/index.js.map +1 -0
- package/config/provider-limits.d.ts +27 -0
- package/config/provider-limits.js +75 -0
- package/config/provider-limits.js.map +1 -0
- package/examples/bank-frick/accounts.d.ts +45 -0
- package/examples/bank-frick/accounts.js +203 -0
- package/examples/bank-frick/accounts.js.map +1 -0
- package/examples/bank-frick/config/index.d.ts +17 -0
- package/examples/bank-frick/config/index.js +55 -0
- package/examples/bank-frick/config/index.js.map +1 -0
- package/examples/bank-frick/index.d.ts +2 -0
- package/examples/bank-frick/index.js +16 -0
- package/examples/bank-frick/index.js.map +1 -0
- package/examples/bank-frick/util.d.ts +4 -0
- package/examples/bank-frick/util.js +40 -0
- package/examples/bank-frick/util.js.map +1 -0
- package/examples/coingecko/src/config/index.d.ts +2 -0
- package/examples/coingecko/src/config/index.js +6 -0
- package/examples/coingecko/src/config/index.js.map +1 -0
- package/examples/coingecko/src/config/overrides.json +10825 -0
- package/examples/coingecko/src/crypto-utils.d.ts +62 -0
- package/examples/coingecko/src/crypto-utils.js +60 -0
- package/examples/coingecko/src/crypto-utils.js.map +1 -0
- package/examples/coingecko/src/endpoint/coins.d.ts +26 -0
- package/examples/coingecko/src/endpoint/coins.js +37 -0
- package/examples/coingecko/src/endpoint/coins.js.map +1 -0
- package/examples/coingecko/src/endpoint/crypto-marketcap.d.ts +3 -0
- package/examples/coingecko/src/endpoint/crypto-marketcap.js +30 -0
- package/examples/coingecko/src/endpoint/crypto-marketcap.js.map +1 -0
- package/examples/coingecko/src/endpoint/crypto-volume.d.ts +3 -0
- package/examples/coingecko/src/endpoint/crypto-volume.js +30 -0
- package/examples/coingecko/src/endpoint/crypto-volume.js.map +1 -0
- package/examples/coingecko/src/endpoint/crypto.d.ts +3 -0
- package/examples/coingecko/src/endpoint/crypto.js +28 -0
- package/examples/coingecko/src/endpoint/crypto.js.map +1 -0
- package/examples/coingecko/src/endpoint/dominance.d.ts +3 -0
- package/examples/coingecko/src/endpoint/dominance.js +28 -0
- package/examples/coingecko/src/endpoint/dominance.js.map +1 -0
- package/examples/coingecko/src/endpoint/global-marketcap.d.ts +3 -0
- package/examples/coingecko/src/endpoint/global-marketcap.js +28 -0
- package/examples/coingecko/src/endpoint/global-marketcap.js.map +1 -0
- package/examples/coingecko/src/endpoint/index.d.ts +6 -0
- package/examples/coingecko/src/endpoint/index.js +16 -0
- package/examples/coingecko/src/endpoint/index.js.map +1 -0
- package/examples/coingecko/src/global-utils.d.ts +42 -0
- package/examples/coingecko/src/global-utils.js +47 -0
- package/examples/coingecko/src/global-utils.js.map +1 -0
- package/examples/coingecko/src/index.d.ts +4 -0
- package/examples/coingecko/src/index.js +19 -0
- package/examples/coingecko/src/index.js.map +1 -0
- package/examples/cryptocompare/src/config/index.d.ts +2 -0
- package/examples/cryptocompare/src/config/index.js +6 -0
- package/examples/cryptocompare/src/config/index.js.map +1 -0
- package/examples/cryptocompare/src/endpoints/crypto.d.ts +40 -0
- package/examples/cryptocompare/src/endpoints/crypto.js +54 -0
- package/examples/cryptocompare/src/endpoints/crypto.js.map +1 -0
- package/examples/cryptocompare/src/endpoints/index.d.ts +1 -0
- package/examples/cryptocompare/src/endpoints/index.js +6 -0
- package/examples/cryptocompare/src/endpoints/index.js.map +1 -0
- package/examples/cryptocompare/src/index.d.ts +4 -0
- package/examples/cryptocompare/src/index.js +14 -0
- package/examples/cryptocompare/src/index.js.map +1 -0
- package/examples/genesis/config/index.d.ts +7 -0
- package/examples/genesis/config/index.js +11 -0
- package/examples/genesis/config/index.js.map +1 -0
- package/examples/genesis/index.d.ts +2 -0
- package/examples/genesis/index.js +13 -0
- package/examples/genesis/index.js.map +1 -0
- package/examples/genesis/sseStream.d.ts +27 -0
- package/examples/genesis/sseStream.js +149 -0
- package/examples/genesis/sseStream.js.map +1 -0
- package/index.d.ts +17 -0
- package/index.js +174 -0
- package/index.js.map +1 -0
- package/metrics/constants.d.ts +16 -0
- package/metrics/constants.js +26 -0
- package/metrics/constants.js.map +1 -0
- package/metrics/index.d.ts +19 -0
- package/metrics/index.js +139 -0
- package/metrics/index.js.map +1 -0
- package/metrics/util.d.ts +7 -0
- package/metrics/util.js +10 -0
- package/metrics/util.js.map +1 -0
- package/package.json +50 -42
- package/rate-limiting/background/fixed-frequency.d.ts +10 -0
- package/rate-limiting/background/fixed-frequency.js +36 -0
- package/rate-limiting/background/fixed-frequency.js.map +1 -0
- package/rate-limiting/index.d.ts +56 -0
- package/rate-limiting/index.js +86 -0
- package/rate-limiting/index.js.map +1 -0
- package/rate-limiting/metrics.d.ts +3 -0
- package/rate-limiting/metrics.js +45 -0
- package/rate-limiting/metrics.js.map +1 -0
- package/rate-limiting/request/simple-counting.d.ts +20 -0
- package/rate-limiting/request/simple-counting.js +63 -0
- package/rate-limiting/request/simple-counting.js.map +1 -0
- package/transports/batch-warming.d.ts +53 -0
- package/transports/batch-warming.js +136 -0
- package/transports/batch-warming.js.map +1 -0
- package/transports/index.d.ts +108 -0
- package/transports/index.js +56 -0
- package/transports/index.js.map +1 -0
- package/transports/metrics.d.ts +25 -0
- package/transports/metrics.js +122 -0
- package/transports/metrics.js.map +1 -0
- package/transports/rest.d.ts +68 -0
- package/transports/rest.js +131 -0
- package/transports/rest.js.map +1 -0
- package/transports/routing.d.ts +21 -0
- package/transports/routing.js +50 -0
- package/transports/routing.js.map +1 -0
- package/transports/sse.d.ts +61 -0
- package/transports/sse.js +97 -0
- package/transports/sse.js.map +1 -0
- package/transports/util.d.ts +9 -0
- package/transports/util.js +87 -0
- package/transports/util.js.map +1 -0
- package/transports/websocket.d.ts +95 -0
- package/transports/websocket.js +164 -0
- package/transports/websocket.js.map +1 -0
- package/util/censor/censor-list.d.ts +9 -0
- package/util/censor/censor-list.js +13 -0
- package/util/censor/censor-list.js.map +1 -0
- package/util/index.d.ts +13 -0
- package/util/index.js +38 -0
- package/util/index.js.map +1 -0
- package/util/logger.d.ts +49 -0
- package/util/logger.js +123 -0
- package/util/logger.js.map +1 -0
- package/util/request.d.ts +138 -0
- package/util/request.js +3 -0
- package/util/request.js.map +1 -0
- package/util/subscription-set/expiring-sorted-set.d.ts +21 -0
- package/util/subscription-set/expiring-sorted-set.js +36 -0
- package/util/subscription-set/expiring-sorted-set.js.map +1 -0
- package/util/subscription-set/redis-sorted-set.d.ts +9 -0
- package/util/subscription-set/redis-sorted-set.js +29 -0
- package/util/subscription-set/redis-sorted-set.js.map +1 -0
- package/util/subscription-set/subscription-set.d.ts +19 -0
- package/util/subscription-set/subscription-set.js +28 -0
- package/util/subscription-set/subscription-set.js.map +1 -0
- package/util/test-payload-loader.d.ts +26 -0
- package/util/test-payload-loader.js +85 -0
- package/util/test-payload-loader.js.map +1 -0
- package/validation/error.d.ts +48 -0
- package/validation/error.js +78 -0
- package/validation/error.js.map +1 -0
- package/validation/index.d.ts +5 -0
- package/validation/index.js +102 -0
- package/validation/index.js.map +1 -0
- package/validation/input-params.d.ts +14 -0
- package/validation/input-params.js +3 -0
- package/validation/input-params.js.map +1 -0
- package/validation/input-validator.d.ts +16 -0
- package/validation/input-validator.js +123 -0
- package/validation/input-validator.js.map +1 -0
- package/README.md +0 -102
package/metrics/index.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
+
};
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.bgExecuteDurationSeconds = exports.bgExecuteTotal = exports.httpRequestDurationSeconds = exports.httpRequestsTotal = exports.buildHttpRequestMetricsLabel = exports.buildMetricsMiddleware = exports.setupMetrics = exports.setupMetricsServer = void 0;
|
|
30
|
+
const client = __importStar(require("prom-client"));
|
|
31
|
+
const constants_1 = require("./constants");
|
|
32
|
+
const util_1 = require("../util");
|
|
33
|
+
const fastify_1 = __importDefault(require("fastify"));
|
|
34
|
+
const path_1 = require("path");
|
|
35
|
+
const error_1 = require("../validation/error");
|
|
36
|
+
const logger = (0, util_1.makeLogger)('Metrics');
|
|
37
|
+
function setupMetricsServer(name, config) {
|
|
38
|
+
const metricsApp = (0, fastify_1.default)({
|
|
39
|
+
logger: false,
|
|
40
|
+
});
|
|
41
|
+
const metricsPort = config.METRICS_PORT;
|
|
42
|
+
const endpoint = config.METRICS_USE_BASE_URL ? (0, path_1.join)(config.BASE_URL, 'metrics') : '/metrics';
|
|
43
|
+
const eaHost = config.EA_HOST;
|
|
44
|
+
(0, exports.setupMetrics)(name, config);
|
|
45
|
+
metricsApp.get(endpoint, async (_, res) => {
|
|
46
|
+
res.type('txt');
|
|
47
|
+
res.send(await client.register.metrics());
|
|
48
|
+
});
|
|
49
|
+
metricsApp.listen({
|
|
50
|
+
port: metricsPort,
|
|
51
|
+
host: eaHost,
|
|
52
|
+
}, () => logger.info(`Monitoring listening on port ${metricsPort}!`));
|
|
53
|
+
}
|
|
54
|
+
exports.setupMetricsServer = setupMetricsServer;
|
|
55
|
+
const setupMetrics = (name, config) => {
|
|
56
|
+
client.collectDefaultMetrics();
|
|
57
|
+
client.register.setDefaultLabels({
|
|
58
|
+
app_name: config.METRICS_NAME || name || 'N/A',
|
|
59
|
+
app_version: process.env['npm_package_version'],
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
exports.setupMetrics = setupMetrics;
|
|
63
|
+
/**
|
|
64
|
+
* Builds metrics middleware that records end to end EA response times
|
|
65
|
+
* and count of requests
|
|
66
|
+
*
|
|
67
|
+
* @returns the cache middleware function
|
|
68
|
+
*/
|
|
69
|
+
const buildMetricsMiddleware = (req, res, done) => {
|
|
70
|
+
// The request context can technically be empty if the input validation failed
|
|
71
|
+
const feedId = req.requestContext?.meta?.metrics?.feedId || 'N/A';
|
|
72
|
+
const labels = (0, exports.buildHttpRequestMetricsLabel)(feedId, req.requestContext?.meta?.error, req.requestContext?.meta?.metrics?.cacheHit);
|
|
73
|
+
// Record number of requests sent to EA
|
|
74
|
+
exports.httpRequestsTotal.labels(labels).inc();
|
|
75
|
+
// Record response time of request through entire EA
|
|
76
|
+
exports.httpRequestDurationSeconds.observe(res.getResponseTime() / 1000);
|
|
77
|
+
logger.debug(`Response time for ${feedId}: ${res.getResponseTime()}ms`);
|
|
78
|
+
done();
|
|
79
|
+
};
|
|
80
|
+
exports.buildMetricsMiddleware = buildMetricsMiddleware;
|
|
81
|
+
const buildHttpRequestMetricsLabel = (feedId, error, cacheHit) => {
|
|
82
|
+
const labels = {};
|
|
83
|
+
labels.method = 'POST';
|
|
84
|
+
labels.feed_id = feedId;
|
|
85
|
+
if (error instanceof error_1.AdapterError) {
|
|
86
|
+
// If error present and an instace of AdapterError, build label from error info
|
|
87
|
+
labels.type = error?.metricsLabel || constants_1.HttpRequestType.ADAPTER_ERROR;
|
|
88
|
+
labels.status_code = error?.statusCode;
|
|
89
|
+
labels.provider_status_code = error?.providerStatusCode;
|
|
90
|
+
}
|
|
91
|
+
else if (error instanceof Error) {
|
|
92
|
+
// If error present and not instance of generic Error, unexpected failure occurred
|
|
93
|
+
labels.type = constants_1.HttpRequestType.ADAPTER_ERROR;
|
|
94
|
+
labels.status_code = 500;
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
// If no error present, request went as expected
|
|
98
|
+
labels.status_code = 200;
|
|
99
|
+
if (cacheHit) {
|
|
100
|
+
labels.type = constants_1.HttpRequestType.CACHE_HIT;
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
labels.type = constants_1.HttpRequestType.DATA_PROVIDER_HIT;
|
|
104
|
+
labels.provider_status_code = 200;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return labels;
|
|
108
|
+
};
|
|
109
|
+
exports.buildHttpRequestMetricsLabel = buildHttpRequestMetricsLabel;
|
|
110
|
+
exports.httpRequestsTotal = new client.Counter({
|
|
111
|
+
name: 'http_requests_total',
|
|
112
|
+
help: 'The number of http requests this external adapter has serviced for its entire uptime',
|
|
113
|
+
labelNames: [
|
|
114
|
+
'method',
|
|
115
|
+
'status_code',
|
|
116
|
+
'retry',
|
|
117
|
+
'type',
|
|
118
|
+
'is_cache_warming',
|
|
119
|
+
'feed_id',
|
|
120
|
+
'provider_status_code',
|
|
121
|
+
],
|
|
122
|
+
});
|
|
123
|
+
exports.httpRequestDurationSeconds = new client.Histogram({
|
|
124
|
+
name: 'http_request_duration_seconds',
|
|
125
|
+
help: 'A histogram bucket of the distribution of http request durations',
|
|
126
|
+
buckets: constants_1.requestDurationBuckets,
|
|
127
|
+
});
|
|
128
|
+
// V3 specific metrics
|
|
129
|
+
exports.bgExecuteTotal = new client.Counter({
|
|
130
|
+
name: 'bg_execute_total',
|
|
131
|
+
help: 'The number of background executes performed per endpoint',
|
|
132
|
+
labelNames: ['endpoint'],
|
|
133
|
+
});
|
|
134
|
+
exports.bgExecuteDurationSeconds = new client.Gauge({
|
|
135
|
+
name: 'bg_execute_duration_seconds',
|
|
136
|
+
help: 'A histogram bucket of the distribution of background execute durations',
|
|
137
|
+
labelNames: ['endpoint'],
|
|
138
|
+
});
|
|
139
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/metrics/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AACrC,2CAAqE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AAU;CAClC,CAAC,CAAA"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { AdapterEndpoint } from '../adapter';
|
|
2
|
+
import { AdapterConfig } from '../config';
|
|
3
|
+
import { AdapterMetricsMeta, AdapterRequestData } from '../util';
|
|
4
|
+
export declare const getMetricsMeta: <T extends import("../transports").TransportGenerics>({ adapterEndpoint, adapterConfig, }: {
|
|
5
|
+
adapterEndpoint: AdapterEndpoint<T>;
|
|
6
|
+
adapterConfig: AdapterConfig<T["CustomSettings"]>;
|
|
7
|
+
}, data: AdapterRequestData) => AdapterMetricsMeta;
|
package/metrics/util.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getMetricsMeta = void 0;
|
|
4
|
+
const cache_1 = require("../cache");
|
|
5
|
+
const getMetricsMeta = ({ adapterEndpoint, adapterConfig, }, data) => {
|
|
6
|
+
const feedId = (0, cache_1.calculateFeedId)({ adapterEndpoint, adapterConfig }, data);
|
|
7
|
+
return { feedId };
|
|
8
|
+
};
|
|
9
|
+
exports.getMetricsMeta = getMetricsMeta;
|
|
10
|
+
//# sourceMappingURL=util.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../../src/metrics/util.ts"],"names":[],"mappings":";;;AACA,oCAA0C;AAInC,MAAM,cAAc,GAAG,CAC5B,EACE,eAAe,EACf,aAAa,GAId,EACD,IAAwB,EACJ,EAAE;IACtB,MAAM,MAAM,GAAG,IAAA,uBAAe,EAAC,EAAE,eAAe,EAAE,aAAa,EAAE,EAAE,IAAI,CAAC,CAAA;IACxE,OAAO,EAAE,MAAM,EAAE,CAAA;AACnB,CAAC,CAAA;AAZY,QAAA,cAAc,kBAY1B"}
|
package/package.json
CHANGED
|
@@ -1,47 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chainlink/external-adapter-framework",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.2",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"dependencies": {
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
"
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"ws": "^8.5.0"
|
|
7
|
+
"ajv": "8.11.0",
|
|
8
|
+
"axios": "0.27.2",
|
|
9
|
+
"eventsource": "2.0.2",
|
|
10
|
+
"fastify": "4.7.0",
|
|
11
|
+
"ioredis": "5.2.3",
|
|
12
|
+
"pino": "8.6.1",
|
|
13
|
+
"prom-client": "13.2.0",
|
|
14
|
+
"ws": "8.9.0"
|
|
16
15
|
},
|
|
17
16
|
"scripts": {
|
|
18
|
-
"start": "ts-node src/test.ts",
|
|
19
|
-
"generate-docs": "typedoc src/**/*.ts",
|
|
20
|
-
"test": "LOG_LEVEL=error EA_PORT=0 c8 ava",
|
|
21
17
|
"build": "tsc",
|
|
22
|
-
"lint": "eslint ./src && prettier --check ./src/**/*.ts",
|
|
23
|
-
"lint-fix": "eslint --fix ./src && prettier --write ./src/**/*.ts",
|
|
24
18
|
"dev": "NODE_ENV=develop tsnd --respawn --transpile-only --project tsconfig.json './src/test.ts'",
|
|
25
|
-
"
|
|
19
|
+
"generate-docs": "typedoc src/**/*.ts",
|
|
20
|
+
"lint-fix": "eslint --max-warnings=0 --fix ./src && prettier --write ./src/**/*.ts ./*.{json,js,yaml}",
|
|
21
|
+
"lint": "eslint --max-warnings=0 ./src && prettier --check ./src/**/*.ts ./*.{json,js,yaml}",
|
|
22
|
+
"release": "./release.sh",
|
|
23
|
+
"start": "ts-node -e 'import(`./src/examples/${process.argv[1]}/src/index`).then(ea => ea.server())'",
|
|
24
|
+
"test-debug": "EA_HOST=localhost SKIP_METRICS_CLEAR=true LOG_LEVEL=trace DEBUG=true EA_PORT=0 c8 ava --verbose",
|
|
25
|
+
"test": "EA_HOST=localhost SKIP_METRICS_CLEAR=true LOG_LEVEL=error EA_PORT=0 c8 ava",
|
|
26
|
+
"verify": "yarn lint && yarn build && yarn build -p ./test/tsconfig.json && yarn test",
|
|
27
|
+
"code-coverage": "c8 check-coverage --statements 95 --lines 95 --functions 95 --branches 90"
|
|
26
28
|
},
|
|
27
29
|
"devDependencies": {
|
|
28
|
-
"@sinonjs/fake-timers": "
|
|
29
|
-
"@types/
|
|
30
|
-
"@types/
|
|
31
|
-
"@types/
|
|
32
|
-
"@types/
|
|
33
|
-
"@
|
|
34
|
-
"@
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"eslint
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
30
|
+
"@sinonjs/fake-timers": "9.1.2",
|
|
31
|
+
"@types/eventsource": "1.1.9",
|
|
32
|
+
"@types/jest": "29.1.1",
|
|
33
|
+
"@types/node": "18.8.2",
|
|
34
|
+
"@types/sinonjs__fake-timers": "8.1.2",
|
|
35
|
+
"@types/supertest": "2.0.12",
|
|
36
|
+
"@types/ws": "8.5.3",
|
|
37
|
+
"@typescript-eslint/eslint-plugin": "5.39.0",
|
|
38
|
+
"@typescript-eslint/parser": "5.39.0",
|
|
39
|
+
"ava": "4.3.3",
|
|
40
|
+
"c8": "7.12.0",
|
|
41
|
+
"eslint": "8.24.0",
|
|
42
|
+
"eslint-config-prettier": "8.5.0",
|
|
43
|
+
"eslint-plugin-tsdoc": "0.2.17",
|
|
44
|
+
"jest": "29.1.2",
|
|
45
|
+
"mock-socket": "9.1.5",
|
|
46
|
+
"mocksse": "1.0.4",
|
|
47
|
+
"nock": "13.2.9",
|
|
48
|
+
"pino-pretty": "9.1.0",
|
|
49
|
+
"prettier": "2.7.1",
|
|
50
|
+
"supertest": "6.3.0",
|
|
51
|
+
"ts-node": "10.9.1",
|
|
52
|
+
"ts-jest": "29.0.3",
|
|
53
|
+
"ts-node-dev": "2.0.0",
|
|
54
|
+
"typedoc": "0.23.15",
|
|
55
|
+
"typescript": "4.8.4"
|
|
45
56
|
},
|
|
46
57
|
"prettier": {
|
|
47
58
|
"semi": false,
|
|
@@ -51,10 +62,6 @@
|
|
|
51
62
|
"trailingComma": "all",
|
|
52
63
|
"arrowParens": "always"
|
|
53
64
|
},
|
|
54
|
-
"optionalDependencies": {
|
|
55
|
-
"bufferutil": "^4.0.6",
|
|
56
|
-
"utf-8-validate": "^5.0.9"
|
|
57
|
-
},
|
|
58
65
|
"ava": {
|
|
59
66
|
"files": [
|
|
60
67
|
"test/**/*.test.ts"
|
|
@@ -65,9 +72,10 @@
|
|
|
65
72
|
"require": [
|
|
66
73
|
"ts-node/register"
|
|
67
74
|
],
|
|
68
|
-
"workerThreads": false
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
75
|
+
"workerThreads": false,
|
|
76
|
+
"environmentVariables": {
|
|
77
|
+
"METRICS_ENABLED": "false"
|
|
78
|
+
},
|
|
79
|
+
"timeout": "20s"
|
|
80
|
+
}
|
|
73
81
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { AdapterRateLimitTier, BackgroundExecuteRateLimiter } from '..';
|
|
2
|
+
import { AdapterEndpoint, EndpointGenerics } from '../../adapter';
|
|
3
|
+
export declare const DEFAULT_SHARED_MS_BETWEEN_REQUESTS = 5000;
|
|
4
|
+
export declare class FixedFrequencyRateLimiter implements BackgroundExecuteRateLimiter {
|
|
5
|
+
msBetweenRequestsMap: {
|
|
6
|
+
[endpointName: string]: number;
|
|
7
|
+
};
|
|
8
|
+
initialize<T extends EndpointGenerics>(endpoints: AdapterEndpoint<T>[], limits?: AdapterRateLimitTier): this;
|
|
9
|
+
msUntilNextExecution(endpointName: string): number;
|
|
10
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FixedFrequencyRateLimiter = exports.DEFAULT_SHARED_MS_BETWEEN_REQUESTS = void 0;
|
|
4
|
+
const __1 = require("..");
|
|
5
|
+
const util_1 = require("../../util");
|
|
6
|
+
const logger = (0, util_1.makeLogger)('FixedFrequencyRateLimiter');
|
|
7
|
+
exports.DEFAULT_SHARED_MS_BETWEEN_REQUESTS = 5000;
|
|
8
|
+
class FixedFrequencyRateLimiter {
|
|
9
|
+
constructor() {
|
|
10
|
+
this.msBetweenRequestsMap = {};
|
|
11
|
+
}
|
|
12
|
+
initialize(endpoints, limits) {
|
|
13
|
+
// Translate the hourly limit into reqs per minute
|
|
14
|
+
let sharedMsBetweenRequests = 1000 / (0, __1.consolidateTierLimits)(limits);
|
|
15
|
+
// If there is no limit set, we use some reasonable number
|
|
16
|
+
if (!limits?.rateLimit1h && !limits?.rateLimit1m && !limits?.rateLimit1s) {
|
|
17
|
+
// 5s period for all seems good
|
|
18
|
+
sharedMsBetweenRequests = exports.DEFAULT_SHARED_MS_BETWEEN_REQUESTS;
|
|
19
|
+
}
|
|
20
|
+
logger.debug('Using fixed frequency batch rate limiting');
|
|
21
|
+
for (const endpoint of endpoints) {
|
|
22
|
+
if (endpoint.rateLimiting?.allocationPercentage == null) {
|
|
23
|
+
throw new Error(`Allocation percentage for endpoint "${endpoint.name}" is null`);
|
|
24
|
+
}
|
|
25
|
+
this.msBetweenRequestsMap[endpoint.name] =
|
|
26
|
+
(sharedMsBetweenRequests / endpoint.rateLimiting?.allocationPercentage) * 100;
|
|
27
|
+
logger.debug(`Endpoint [${endpoint.name}]: ${this.msBetweenRequestsMap[endpoint.name] / 1000}s between requests`);
|
|
28
|
+
}
|
|
29
|
+
return this;
|
|
30
|
+
}
|
|
31
|
+
msUntilNextExecution(endpointName) {
|
|
32
|
+
return this.msBetweenRequestsMap[endpointName];
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
exports.FixedFrequencyRateLimiter = FixedFrequencyRateLimiter;
|
|
36
|
+
//# sourceMappingURL=fixed-frequency.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fixed-frequency.js","sourceRoot":"","sources":["../../../../src/rate-limiting/background/fixed-frequency.ts"],"names":[],"mappings":";;;AAAA,0BAA8F;AAE9F,qCAAuC;AAEvC,MAAM,MAAM,GAAG,IAAA,iBAAU,EAAC,2BAA2B,CAAC,CAAA;AACzC,QAAA,kCAAkC,GAAG,IAAI,CAAA;AAEtD,MAAa,yBAAyB;IAAtC;QACE,yBAAoB,GAEhB,EAAE,CAAA;IAqCR,CAAC;IAnCC,UAAU,CACR,SAA+B,EAC/B,MAA6B;QAE7B,kDAAkD;QAClD,IAAI,uBAAuB,GAAG,IAAI,GAAG,IAAA,yBAAqB,EAAC,MAAM,CAAC,CAAA;QAElE,0DAA0D;QAC1D,IAAI,CAAC,MAAM,EAAE,WAAW,IAAI,CAAC,MAAM,EAAE,WAAW,IAAI,CAAC,MAAM,EAAE,WAAW,EAAE;YACxE,+BAA+B;YAC/B,uBAAuB,GAAG,0CAAkC,CAAA;SAC7D;QAED,MAAM,CAAC,KAAK,CAAC,2CAA2C,CAAC,CAAA;QACzD,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE;YAChC,IAAI,QAAQ,CAAC,YAAY,EAAE,oBAAoB,IAAI,IAAI,EAAE;gBACvD,MAAM,IAAI,KAAK,CAAC,uCAAuC,QAAQ,CAAC,IAAI,WAAW,CAAC,CAAA;aACjF;YAED,IAAI,CAAC,oBAAoB,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACtC,CAAC,uBAAuB,GAAG,QAAQ,CAAC,YAAY,EAAE,oBAAoB,CAAC,GAAG,GAAG,CAAA;YAE/E,MAAM,CAAC,KAAK,CACV,aAAa,QAAQ,CAAC,IAAI,MACxB,IAAI,CAAC,oBAAoB,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,IAC7C,oBAAoB,CACrB,CAAA;SACF;QAED,OAAO,IAAI,CAAA;IACb,CAAC;IAED,oBAAoB,CAAC,YAAoB;QACvC,OAAO,IAAI,CAAC,oBAAoB,CAAC,YAAY,CAAC,CAAA;IAChD,CAAC;CACF;AAxCD,8DAwCC"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { AdapterEndpoint, EndpointGenerics } from '../adapter';
|
|
2
|
+
import { AdapterConfig } from '../config';
|
|
3
|
+
export * from './background/fixed-frequency';
|
|
4
|
+
export * from './request/simple-counting';
|
|
5
|
+
export interface AdapterRateLimitTier {
|
|
6
|
+
rateLimit1s?: number;
|
|
7
|
+
rateLimit1m?: number;
|
|
8
|
+
rateLimit1h?: number;
|
|
9
|
+
note?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Common interface for all RateLimiter classes to implement
|
|
13
|
+
*/
|
|
14
|
+
export interface RateLimiter {
|
|
15
|
+
/**
|
|
16
|
+
* Method to ensure all RateLimiters can be initialized in the same manner.
|
|
17
|
+
*
|
|
18
|
+
* @param limits - settings for how much throughput to allow for the Adapter
|
|
19
|
+
* @param endpoints - list of adapter endpoints
|
|
20
|
+
*/
|
|
21
|
+
initialize<T extends EndpointGenerics>(endpoints: AdapterEndpoint<T>[], limits: AdapterRateLimitTier): this;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* RequestRateLimiters perform checks agains imminent outbound requests for any transport.
|
|
25
|
+
*/
|
|
26
|
+
export interface RequestRateLimiter extends RateLimiter {
|
|
27
|
+
/**
|
|
28
|
+
* This method will check using whatever strategy is implemented to determine if
|
|
29
|
+
* this request can be processed. If so, it returns true; if not, returns false.
|
|
30
|
+
*/
|
|
31
|
+
isUnderLimits(): boolean;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* BackgroundExecuteFrequencyRateLimiters will implement custom logic to calculate
|
|
35
|
+
* the period of time to wait between background executions for a transport.
|
|
36
|
+
*/
|
|
37
|
+
export interface BackgroundExecuteRateLimiter extends RateLimiter {
|
|
38
|
+
msUntilNextExecution(endpointName: string): number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* This method will convert all possible settings for a rate limit tier and
|
|
42
|
+
* convert them all to requests per second, returning the lowest one
|
|
43
|
+
*
|
|
44
|
+
* @param limits - the rate limit tier set for the adapter
|
|
45
|
+
* @returns the most restrictive of the set options, in requests per second
|
|
46
|
+
*/
|
|
47
|
+
export declare const consolidateTierLimits: (limits?: AdapterRateLimitTier) => number;
|
|
48
|
+
/**
|
|
49
|
+
* Validates rate limiting tiers specified for the adapter, and returns the one to use.
|
|
50
|
+
*
|
|
51
|
+
* @param config - the adapter config containing the env vars
|
|
52
|
+
* @param tiers - the adapter config listing the different available API tiers
|
|
53
|
+
* @returns the specified API tier, or a default one if none are specified
|
|
54
|
+
*/
|
|
55
|
+
export declare const getRateLimitingTier: (config: AdapterConfig, tiers?: Record<string, AdapterRateLimitTier>) => AdapterRateLimitTier | undefined;
|
|
56
|
+
export declare const buildRateLimitTiersFromConfig: (config: AdapterConfig) => AdapterRateLimitTier | undefined;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.buildRateLimitTiersFromConfig = exports.getRateLimitingTier = exports.consolidateTierLimits = void 0;
|
|
18
|
+
__exportStar(require("./background/fixed-frequency"), exports);
|
|
19
|
+
__exportStar(require("./request/simple-counting"), exports);
|
|
20
|
+
/**
|
|
21
|
+
* This method will convert all possible settings for a rate limit tier and
|
|
22
|
+
* convert them all to requests per second, returning the lowest one
|
|
23
|
+
*
|
|
24
|
+
* @param limits - the rate limit tier set for the adapter
|
|
25
|
+
* @returns the most restrictive of the set options, in requests per second
|
|
26
|
+
*/
|
|
27
|
+
const consolidateTierLimits = (limits) => {
|
|
28
|
+
const perHourLimit = (limits?.rateLimit1h || Infinity) / (60 * 60);
|
|
29
|
+
const perMinuteLimit = (limits?.rateLimit1m || Infinity) / 60;
|
|
30
|
+
const perSecondLimit = limits?.rateLimit1s || Infinity;
|
|
31
|
+
return Math.min(perHourLimit, perMinuteLimit, perSecondLimit);
|
|
32
|
+
};
|
|
33
|
+
exports.consolidateTierLimits = consolidateTierLimits;
|
|
34
|
+
/**
|
|
35
|
+
* Validates rate limiting tiers specified for the adapter, and returns the one to use.
|
|
36
|
+
*
|
|
37
|
+
* @param config - the adapter config containing the env vars
|
|
38
|
+
* @param tiers - the adapter config listing the different available API tiers
|
|
39
|
+
* @returns the specified API tier, or a default one if none are specified
|
|
40
|
+
*/
|
|
41
|
+
const getRateLimitingTier = (config, tiers) => {
|
|
42
|
+
if (config.RATE_LIMIT_CAPACITY ||
|
|
43
|
+
config.RATE_LIMIT_CAPACITY_MINUTE ||
|
|
44
|
+
config.RATE_LIMIT_CAPACITY_SECOND) {
|
|
45
|
+
return (0, exports.buildRateLimitTiersFromConfig)(config);
|
|
46
|
+
}
|
|
47
|
+
if (!tiers) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
// Check that if the tiers object is defined, it has values
|
|
51
|
+
if (Object.values(tiers).length === 0) {
|
|
52
|
+
throw new Error(`The tiers object is defined, but has no entries`);
|
|
53
|
+
}
|
|
54
|
+
// Check that the tier set in the AdapterConfig is a valid one
|
|
55
|
+
const selectedTier = config.RATE_LIMIT_API_TIER;
|
|
56
|
+
if (selectedTier && !tiers[selectedTier]) {
|
|
57
|
+
const validTiersString = Object.keys(tiers)
|
|
58
|
+
.map((t) => `"${t}"`)
|
|
59
|
+
.join(', ');
|
|
60
|
+
throw new Error(`The selected rate limit tier "${selectedTier}" is not valid (can be one of ${validTiersString})`);
|
|
61
|
+
}
|
|
62
|
+
if (!selectedTier) {
|
|
63
|
+
// Sort the tiers by most to least restrictive
|
|
64
|
+
const sortedTiers = Object.values(tiers).sort((t1, t2) => (0, exports.consolidateTierLimits)(t1) - (0, exports.consolidateTierLimits)(t2));
|
|
65
|
+
return sortedTiers[0];
|
|
66
|
+
}
|
|
67
|
+
return tiers[selectedTier];
|
|
68
|
+
};
|
|
69
|
+
exports.getRateLimitingTier = getRateLimitingTier;
|
|
70
|
+
// Creates adapter rate limit tier using the configs specified in env vars
|
|
71
|
+
const buildRateLimitTiersFromConfig = (config) => {
|
|
72
|
+
const rateLimit1s = config.RATE_LIMIT_CAPACITY_SECOND;
|
|
73
|
+
let rateLimit1m;
|
|
74
|
+
if (config.RATE_LIMIT_CAPACITY_MINUTE) {
|
|
75
|
+
rateLimit1m = config.RATE_LIMIT_CAPACITY_MINUTE;
|
|
76
|
+
}
|
|
77
|
+
else if (config.RATE_LIMIT_CAPACITY) {
|
|
78
|
+
rateLimit1m = config.RATE_LIMIT_CAPACITY;
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
rateLimit1s,
|
|
82
|
+
rateLimit1m,
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
exports.buildRateLimitTiersFromConfig = buildRateLimitTiersFromConfig;
|
|
86
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/r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AAI,CAAC,CAAA;QAEb,MAAM,IAAI,KAAK,CACb,iCAAiC,YAAY,iCAAiC,gBAAgB,GAAG,CAClG,CAAA;KACF;IAED,IAAI,CAAC,YAAY,EAAE;QACjB,8CAA8C;QAC9C,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAC3C,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,IAAA,6BAAqB,EAAC,EAAE,CAAC,GAAG,IAAA,6BAAqB,EAAC,EAAE,CAAC,CAClE,CAAA;QAED,OAAO,WAAW,CAAC,CAAC,CAAC,CAAA;KACtB;IAED,OAAO,KAAK,CAAC,YAAY,CAAC,CAAA;AAC5B,CAAC,CAAA;AA1CY,QAAA,mBAAmB,uBA0C/B;AAED,0EAA0E;AACnE,MAAM,6BAA6B,GAAG,CAC3C,MAAqB,EACa,EAAE;IACpC,MAAM,WAAW,GAAG,MAAM,CAAC,0BAA0B,CAAA;IACrD,IAAI,WAAW,CAAA;IACf,IAAI,MAAM,CAAC,0BAA0B,EAAE;QACrC,WAAW,GAAG,MAAM,CAAC,0BAA0B,CAAA;KAChD;SAAM,IAAI,MAAM,CAAC,mBAAmB,EAAE;QACrC,WAAW,GAAG,MAAM,CAAC,mBAAmB,CAAA;KACzC;IACD,OAAO;QACL,WAAW;QACX,WAAW;KACZ,CAAA;AACH,CAAC,CAAA;AAdY,QAAA,6BAA6B,iCAczC"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.rateLimitCreditsSpentTotal = exports.retrieveCost = void 0;
|
|
27
|
+
const client = __importStar(require("prom-client"));
|
|
28
|
+
// Retrieve cost field from response if exists
|
|
29
|
+
// If not return default cost of 1
|
|
30
|
+
const retrieveCost = (data) => {
|
|
31
|
+
const cost = data['cost'];
|
|
32
|
+
if (typeof cost === 'number' || typeof cost === 'string') {
|
|
33
|
+
return Number(cost);
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
return 1;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
exports.retrieveCost = retrieveCost;
|
|
40
|
+
exports.rateLimitCreditsSpentTotal = new client.Counter({
|
|
41
|
+
name: 'rate_limit_credits_spent_total',
|
|
42
|
+
help: 'The number of data provider credits the adapter is consuming',
|
|
43
|
+
labelNames: ['participant_id', 'feed_id'],
|
|
44
|
+
});
|
|
45
|
+
//# sourceMappingURL=metrics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../../src/rate-limiting/metrics.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AAErC,8CAA8C;AAC9C,kCAAkC;AAC3B,MAAM,YAAY,GAAG,CAAuB,IAA0B,EAAU,EAAE;IACvF,MAAM,IAAI,GAAI,IAAgC,CAAC,MAAM,CAAC,CAAA;IACtD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACxD,OAAO,MAAM,CAAC,IAAI,CAAC,CAAA;KACpB;SAAM;QACL,OAAO,CAAC,CAAA;KACT;AACH,CAAC,CAAA;AAPY,QAAA,YAAY,gBAOxB;AAEY,QAAA,0BAA0B,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC;IAC3D,IAAI,EAAE,gCAAgC;IACtC,IAAI,EAAE,8DAA8D;IACpE,UAAU,EAAE,CAAC,gBAAgB,EAAE,SAAS,CAAU;CACnD,CAAC,CAAA"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { AdapterRateLimitTier, RateLimiter } from '..';
|
|
2
|
+
import { AdapterEndpoint, EndpointGenerics } from '../../adapter';
|
|
3
|
+
/**
|
|
4
|
+
* This rate limiter is the simplest stateful option.
|
|
5
|
+
* On startup, it'll compare the different thresholds for each tier, calculate them all
|
|
6
|
+
* in the finest window we'll use (seconds), and use the most restrictive one.
|
|
7
|
+
* This is so if the EA were to restart, we don't need to worry about persisting state
|
|
8
|
+
* for things like daily quotas. The downside is that this does not work well for bursty
|
|
9
|
+
* loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
|
|
10
|
+
*/
|
|
11
|
+
export declare class SimpleCountingRateLimiter implements RateLimiter {
|
|
12
|
+
latestSecondInterval: number;
|
|
13
|
+
requestsThisSecond: number;
|
|
14
|
+
latestMinuteInterval: number;
|
|
15
|
+
requestsThisMinute: number;
|
|
16
|
+
perSecondLimit: number;
|
|
17
|
+
perMinuteLimit: number;
|
|
18
|
+
initialize<T extends EndpointGenerics>(endpoints: AdapterEndpoint<T>[], limits?: AdapterRateLimitTier): this;
|
|
19
|
+
isUnderLimits(): boolean;
|
|
20
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SimpleCountingRateLimiter = void 0;
|
|
4
|
+
const util_1 = require("../../util");
|
|
5
|
+
const logger = (0, util_1.makeLogger)('SimpleCountingRateLimiter');
|
|
6
|
+
/**
|
|
7
|
+
* This rate limiter is the simplest stateful option.
|
|
8
|
+
* On startup, it'll compare the different thresholds for each tier, calculate them all
|
|
9
|
+
* in the finest window we'll use (seconds), and use the most restrictive one.
|
|
10
|
+
* This is so if the EA were to restart, we don't need to worry about persisting state
|
|
11
|
+
* for things like daily quotas. The downside is that this does not work well for bursty
|
|
12
|
+
* loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
|
|
13
|
+
*/
|
|
14
|
+
class SimpleCountingRateLimiter {
|
|
15
|
+
constructor() {
|
|
16
|
+
this.latestSecondInterval = 0;
|
|
17
|
+
this.requestsThisSecond = 0;
|
|
18
|
+
this.latestMinuteInterval = 0;
|
|
19
|
+
this.requestsThisMinute = 0;
|
|
20
|
+
}
|
|
21
|
+
initialize(endpoints, limits) {
|
|
22
|
+
// Translate the hourly limit into reqs per minute
|
|
23
|
+
const perHourLimit = (limits?.rateLimit1h || Infinity) / 60;
|
|
24
|
+
this.perMinuteLimit = Math.min(limits?.rateLimit1m || Infinity, perHourLimit);
|
|
25
|
+
this.perSecondLimit = limits?.rateLimit1s || Infinity;
|
|
26
|
+
logger.debug(`Using rate limiting settings: perMinute = ${this.perMinuteLimit} | perSecond: = ${this.perSecondLimit}`);
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
isUnderLimits() {
|
|
30
|
+
// If the limit is set to infinity, there was no tier limit specified
|
|
31
|
+
if (this.perSecondLimit === Infinity && this.perMinuteLimit === Infinity) {
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const nearestSecondInterval = Math.floor(now / 1000);
|
|
36
|
+
const nearestMinuteInterval = Math.floor(now / (1000 * 60));
|
|
37
|
+
// This should always run to completion, even if it doesn't look atomic; therefore the
|
|
38
|
+
// Ops should be "thread safe". Thank JS and its infinite single threaded dumbness.
|
|
39
|
+
if (nearestSecondInterval !== this.latestSecondInterval) {
|
|
40
|
+
logger.trace(`Clearing latest second interval, # of requests logged was: ${this.requestsThisSecond} `);
|
|
41
|
+
this.latestSecondInterval = nearestSecondInterval;
|
|
42
|
+
this.requestsThisSecond = 0;
|
|
43
|
+
}
|
|
44
|
+
if (nearestMinuteInterval !== this.latestMinuteInterval) {
|
|
45
|
+
logger.trace(`Clearing latest second minute, # of requests logged was: ${this.requestsThisMinute} `);
|
|
46
|
+
this.latestMinuteInterval = nearestMinuteInterval;
|
|
47
|
+
this.requestsThisMinute = 0;
|
|
48
|
+
}
|
|
49
|
+
if (this.requestsThisSecond < this.perSecondLimit &&
|
|
50
|
+
this.requestsThisMinute < this.perMinuteLimit) {
|
|
51
|
+
logger.trace('Request under limits, counting +1');
|
|
52
|
+
this.requestsThisSecond++;
|
|
53
|
+
this.requestsThisMinute++;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
logger.trace('Requests seen this interval are above limits');
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
exports.SimpleCountingRateLimiter = SimpleCountingRateLimiter;
|
|
63
|
+
//# sourceMappingURL=simple-counting.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"simple-counting.js","sourceRoot":"","sources":["../../../../src/rate-limiting/request/simple-counting.ts"],"names":[],"mappings":";;;AAEA,qCAAuC;AAEvC,MAAM,MAAM,GAAG,IAAA,iBAAU,EAAC,2BAA2B,CAAC,CAAA;AAEtD;;;;;;;GAOG;AACH,MAAa,yBAAyB;IAAtC;QACE,yBA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