@chainlink/external-adapter-framework 0.0.12 → 0.0.15
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/.eslintignore +1 -0
- package/.github/README.MD +35 -10
- package/.github/workflows/label.yaml +39 -0
- package/.github/workflows/publish.yaml +0 -3
- package/dist/examples/coingecko/test/e2e/adapter.test.ts.js +82953 -0
- package/dist/examples/coingecko/test/integration/adapter.test.ts.js +91672 -0
- package/dist/main.js +72703 -0
- package/jest.config.js +5 -0
- package/package.json +14 -3
- package/src/config/provider-limits.ts +14 -17
- package/src/examples/coingecko/src/config/index.ts +12 -0
- package/src/examples/coingecko/src/config/overrides.json +10826 -0
- package/src/examples/coingecko/src/cryptoUtils.ts +88 -0
- package/src/examples/coingecko/src/endpoint/coins.ts +54 -0
- package/src/examples/coingecko/src/endpoint/crypto-marketcap.ts +66 -0
- package/src/examples/coingecko/src/endpoint/crypto-volume.ts +66 -0
- package/src/examples/coingecko/src/endpoint/crypto.ts +63 -0
- package/src/examples/coingecko/src/endpoint/dominance.ts +40 -0
- package/src/examples/coingecko/src/endpoint/global-marketcap.ts +40 -0
- package/src/examples/coingecko/src/endpoint/index.ts +6 -0
- package/src/examples/coingecko/src/globalUtils.ts +78 -0
- package/src/examples/coingecko/src/index.ts +17 -0
- package/src/examples/coingecko/test/e2e/adapter.test.ts +278 -0
- package/src/examples/coingecko/test/integration/__snapshots__/adapter.test.ts.snap +15 -0
- package/src/examples/coingecko/test/integration/adapter.test.ts +281 -0
- package/src/examples/coingecko/test/integration/capturedRequests.json +1 -0
- package/src/examples/coingecko/test/integration/fixtures.ts +42 -0
- package/src/examples/{coingecko → coingecko-old}/batch-warming.ts +1 -0
- package/src/examples/{coingecko → coingecko-old}/index.ts +0 -0
- package/src/examples/{coingecko → coingecko-old}/rest.ts +0 -0
- package/src/transports/batch-warming.ts +7 -2
- package/src/transports/rest.ts +5 -1
- package/src/util/index.ts +1 -0
- package/src/util/recordRequests.ts +47 -0
- package/src/validation/overrideFunctions.ts +44 -0
- package/test/metrics/warmer-metrics.test.ts +1 -0
- package/test/{smoke.test.ts → smoke/smoke.test.ts} +13 -13
- package/{test-payload-fail.json → test/smoke/test-payload-fail.json} +0 -0
- package/{test-payload.js → test/smoke/test-payload.js} +0 -0
- package/{test-payload.json → test/smoke/test-payload.json} +0 -0
- package/test/transports/batch.test.ts +1 -0
- package/tsconfig.json +4 -1
- package/webpack.config.js +39 -5
- package/yarn-error.log +3778 -0
- package/dist/src/adapter.d.ts +0 -135
- package/dist/src/adapter.js +0 -145
- package/dist/src/background-executor.d.ts +0 -11
- package/dist/src/background-executor.js +0 -45
- package/dist/src/cache/factory.d.ts +0 -6
- package/dist/src/cache/factory.js +0 -55
- package/dist/src/cache/index.d.ts +0 -94
- package/dist/src/cache/index.js +0 -173
- package/dist/src/cache/local.d.ts +0 -23
- package/dist/src/cache/local.js +0 -83
- package/dist/src/cache/metrics.d.ts +0 -27
- package/dist/src/cache/metrics.js +0 -120
- package/dist/src/cache/redis.d.ts +0 -16
- package/dist/src/cache/redis.js +0 -100
- package/dist/src/chainlink-external-adapter-framework-0.0.6.tgz +0 -0
- package/dist/src/config/index.d.ts +0 -214
- package/dist/src/config/index.js +0 -380
- package/dist/src/config/provider-limits.d.ts +0 -31
- package/dist/src/config/provider-limits.js +0 -75
- package/dist/src/examples/bank-frick/accounts.d.ts +0 -39
- package/dist/src/examples/bank-frick/accounts.js +0 -192
- package/dist/src/examples/bank-frick/config/index.d.ts +0 -4
- package/dist/src/examples/bank-frick/config/index.js +0 -54
- package/dist/src/examples/bank-frick/index.d.ts +0 -2
- package/dist/src/examples/bank-frick/index.js +0 -15
- package/dist/src/examples/bank-frick/util.d.ts +0 -4
- package/dist/src/examples/bank-frick/util.js +0 -39
- package/dist/src/examples/coingecko/batch-warming.d.ts +0 -7
- package/dist/src/examples/coingecko/batch-warming.js +0 -53
- package/dist/src/examples/coingecko/index.d.ts +0 -2
- package/dist/src/examples/coingecko/index.js +0 -11
- package/dist/src/examples/coingecko/rest.d.ts +0 -12
- package/dist/src/examples/coingecko/rest.js +0 -51
- package/dist/src/examples/ncfx/config/index.d.ts +0 -12
- package/dist/src/examples/ncfx/config/index.js +0 -15
- package/dist/src/examples/ncfx/index.d.ts +0 -13
- package/dist/src/examples/ncfx/index.js +0 -11
- package/dist/src/examples/ncfx/websocket.d.ts +0 -47
- package/dist/src/examples/ncfx/websocket.js +0 -73
- package/dist/src/index.d.ts +0 -11
- package/dist/src/index.js +0 -128
- package/dist/src/metrics/constants.d.ts +0 -16
- package/dist/src/metrics/constants.js +0 -25
- package/dist/src/metrics/index.d.ts +0 -15
- package/dist/src/metrics/index.js +0 -122
- package/dist/src/metrics/util.d.ts +0 -7
- package/dist/src/metrics/util.js +0 -9
- package/dist/src/package/adapter.d.ts +0 -88
- package/dist/src/package/adapter.js +0 -112
- package/dist/src/package/background-executor.d.ts +0 -11
- package/dist/src/package/background-executor.js +0 -45
- package/dist/src/package/cache/factory.d.ts +0 -6
- package/dist/src/package/cache/factory.js +0 -57
- package/dist/src/package/cache/index.d.ts +0 -90
- package/dist/src/package/cache/index.js +0 -169
- package/dist/src/package/cache/local.d.ts +0 -23
- package/dist/src/package/cache/local.js +0 -83
- package/dist/src/package/cache/metrics.d.ts +0 -27
- package/dist/src/package/cache/metrics.js +0 -120
- package/dist/src/package/cache/redis.d.ts +0 -16
- package/dist/src/package/cache/redis.js +0 -100
- package/dist/src/package/config/index.d.ts +0 -195
- package/dist/src/package/config/index.js +0 -365
- package/dist/src/package/config/provider-limits.d.ts +0 -31
- package/dist/src/package/config/provider-limits.js +0 -76
- package/dist/src/package/examples/coingecko/batch-warming.d.ts +0 -2
- package/dist/src/package/examples/coingecko/batch-warming.js +0 -52
- package/dist/src/package/examples/coingecko/index.d.ts +0 -2
- package/dist/src/package/examples/coingecko/index.js +0 -10
- package/dist/src/package/examples/coingecko/rest.d.ts +0 -2
- package/dist/src/package/examples/coingecko/rest.js +0 -50
- package/dist/src/package/examples/ncfx/config/index.d.ts +0 -12
- package/dist/src/package/examples/ncfx/config/index.js +0 -15
- package/dist/src/package/examples/ncfx/index.d.ts +0 -2
- package/dist/src/package/examples/ncfx/index.js +0 -10
- package/dist/src/package/examples/ncfx/websocket.d.ts +0 -36
- package/dist/src/package/examples/ncfx/websocket.js +0 -72
- package/dist/src/package/index.d.ts +0 -12
- package/dist/src/package/index.js +0 -92
- package/dist/src/package/metrics/constants.d.ts +0 -16
- package/dist/src/package/metrics/constants.js +0 -25
- package/dist/src/package/metrics/index.d.ts +0 -15
- package/dist/src/package/metrics/index.js +0 -123
- package/dist/src/package/metrics/util.d.ts +0 -3
- package/dist/src/package/metrics/util.js +0 -9
- package/dist/src/package/package.json +0 -72
- package/dist/src/package/rate-limiting/background/fixed-frequency.d.ts +0 -10
- package/dist/src/package/rate-limiting/background/fixed-frequency.js +0 -37
- package/dist/src/package/rate-limiting/index.d.ts +0 -54
- package/dist/src/package/rate-limiting/index.js +0 -63
- package/dist/src/package/rate-limiting/metrics.d.ts +0 -3
- package/dist/src/package/rate-limiting/metrics.js +0 -44
- package/dist/src/package/rate-limiting/request/simple-counting.d.ts +0 -20
- package/dist/src/package/rate-limiting/request/simple-counting.js +0 -62
- package/dist/src/package/test.d.ts +0 -1
- package/dist/src/package/test.js +0 -6
- package/dist/src/package/transports/batch-warming.d.ts +0 -34
- package/dist/src/package/transports/batch-warming.js +0 -101
- package/dist/src/package/transports/index.d.ts +0 -87
- package/dist/src/package/transports/index.js +0 -87
- package/dist/src/package/transports/metrics.d.ts +0 -21
- package/dist/src/package/transports/metrics.js +0 -105
- package/dist/src/package/transports/rest.d.ts +0 -43
- package/dist/src/package/transports/rest.js +0 -129
- package/dist/src/package/transports/util.d.ts +0 -8
- package/dist/src/package/transports/util.js +0 -85
- package/dist/src/package/transports/websocket.d.ts +0 -80
- package/dist/src/package/transports/websocket.js +0 -169
- package/dist/src/package/util/expiring-sorted-set.d.ts +0 -21
- package/dist/src/package/util/expiring-sorted-set.js +0 -47
- package/dist/src/package/util/index.d.ts +0 -11
- package/dist/src/package/util/index.js +0 -35
- package/dist/src/package/util/logger.d.ts +0 -42
- package/dist/src/package/util/logger.js +0 -62
- package/dist/src/package/util/request.d.ts +0 -55
- package/dist/src/package/util/request.js +0 -2
- package/dist/src/package/validation/error.d.ts +0 -50
- package/dist/src/package/validation/error.js +0 -79
- package/dist/src/package/validation/index.d.ts +0 -5
- package/dist/src/package/validation/index.js +0 -86
- package/dist/src/package/validation/input-params.d.ts +0 -15
- package/dist/src/package/validation/input-params.js +0 -30
- package/dist/src/package/validation/override-functions.d.ts +0 -3
- package/dist/src/package/validation/override-functions.js +0 -40
- package/dist/src/package/validation/preset-tokens.json +0 -23
- package/dist/src/package/validation/validator.d.ts +0 -47
- package/dist/src/package/validation/validator.js +0 -303
- package/dist/src/package.json +0 -72
- package/dist/src/rate-limiting/background/fixed-frequency.d.ts +0 -11
- package/dist/src/rate-limiting/background/fixed-frequency.js +0 -35
- package/dist/src/rate-limiting/index.d.ts +0 -55
- package/dist/src/rate-limiting/index.js +0 -63
- package/dist/src/rate-limiting/metrics.d.ts +0 -3
- package/dist/src/rate-limiting/metrics.js +0 -44
- package/dist/src/rate-limiting/request/simple-counting.d.ts +0 -21
- package/dist/src/rate-limiting/request/simple-counting.js +0 -62
- package/dist/src/test.d.ts +0 -1
- package/dist/src/test.js +0 -6
- package/dist/src/transports/batch-warming.d.ts +0 -35
- package/dist/src/transports/batch-warming.js +0 -101
- package/dist/src/transports/index.d.ts +0 -70
- package/dist/src/transports/index.js +0 -87
- package/dist/src/transports/metrics.d.ts +0 -22
- package/dist/src/transports/metrics.js +0 -105
- package/dist/src/transports/rest.d.ts +0 -44
- package/dist/src/transports/rest.js +0 -131
- package/dist/src/transports/util.d.ts +0 -8
- package/dist/src/transports/util.js +0 -85
- package/dist/src/transports/websocket.d.ts +0 -80
- package/dist/src/transports/websocket.js +0 -166
- package/dist/src/util/expiring-sorted-set.d.ts +0 -21
- package/dist/src/util/expiring-sorted-set.js +0 -47
- package/dist/src/util/index.d.ts +0 -12
- package/dist/src/util/index.js +0 -35
- package/dist/src/util/logger.d.ts +0 -42
- package/dist/src/util/logger.js +0 -62
- package/dist/src/util/request.d.ts +0 -57
- package/dist/src/util/request.js +0 -2
- package/dist/src/util/subscription-set/expiring-sorted-set.d.ts +0 -22
- package/dist/src/util/subscription-set/expiring-sorted-set.js +0 -47
- package/dist/src/util/subscription-set/subscription-set.d.ts +0 -18
- package/dist/src/util/subscription-set/subscription-set.js +0 -19
- package/dist/src/util/test-payload-loader.d.ts +0 -25
- package/dist/src/util/test-payload-loader.js +0 -83
- package/dist/src/validation/error.d.ts +0 -50
- package/dist/src/validation/error.js +0 -79
- package/dist/src/validation/index.d.ts +0 -5
- package/dist/src/validation/index.js +0 -91
- package/dist/src/validation/input-params.d.ts +0 -15
- package/dist/src/validation/input-params.js +0 -30
- package/dist/src/validation/override-functions.d.ts +0 -3
- package/dist/src/validation/override-functions.js +0 -40
- package/dist/src/validation/preset-tokens.json +0 -23
- package/dist/src/validation/validator.d.ts +0 -47
- package/dist/src/validation/validator.js +0 -303
- package/src/test.ts +0 -5
|
@@ -1,37 +0,0 @@
|
|
|
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
|
-
// TODO: See if we can remove this runtime check
|
|
23
|
-
if (endpoint.rateLimiting?.allocationPercentage == null) {
|
|
24
|
-
throw new Error(`Allocation percentage for endpoint "${endpoint.name}" is null`);
|
|
25
|
-
}
|
|
26
|
-
// TODO: Implement different strategy where this is not fixed, but rather divided based on whether all warmers are active
|
|
27
|
-
this.msBetweenRequestsMap[endpoint.name] =
|
|
28
|
-
(sharedMsBetweenRequests / endpoint.rateLimiting?.allocationPercentage) * 100;
|
|
29
|
-
logger.debug(`Endpoint [${endpoint.name}]: ${this.msBetweenRequestsMap[endpoint.name] / 1000}s between requests`);
|
|
30
|
-
}
|
|
31
|
-
return this;
|
|
32
|
-
}
|
|
33
|
-
msUntilNextExecution(endpointName) {
|
|
34
|
-
return this.msBetweenRequestsMap[endpointName];
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
exports.FixedFrequencyRateLimiter = FixedFrequencyRateLimiter;
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import { AdapterEndpoint } from '../adapter';
|
|
2
|
-
export * from './request/simple-counting';
|
|
3
|
-
export * from './background/fixed-frequency';
|
|
4
|
-
export interface AdapterRateLimitTier {
|
|
5
|
-
rateLimit1s?: number;
|
|
6
|
-
rateLimit1m?: number;
|
|
7
|
-
rateLimit1h?: number;
|
|
8
|
-
note?: string;
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* Common interface for all RateLimiter classes to implement
|
|
12
|
-
*/
|
|
13
|
-
export interface RateLimiter {
|
|
14
|
-
/**
|
|
15
|
-
* Method to ensure all RateLimiters can be initialized in the same manner.
|
|
16
|
-
*
|
|
17
|
-
* @param limits - settings for how much throughput to allow for the Adapter
|
|
18
|
-
* @param endpoints - list of adapter endpoints
|
|
19
|
-
*/
|
|
20
|
-
initialize(endpoints: AdapterEndpoint[], limits: AdapterRateLimitTier): this;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* RequestRateLimiters perform checks agains imminent outbound requests for any transport.
|
|
24
|
-
*/
|
|
25
|
-
export interface RequestRateLimiter extends RateLimiter {
|
|
26
|
-
/**
|
|
27
|
-
* This method will check using whatever strategy is implemented to determine if
|
|
28
|
-
* this request can be processed. If so, it returns true; if not, returns false.
|
|
29
|
-
*/
|
|
30
|
-
isUnderLimits(): boolean;
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* BackgroundExecuteFrequencyRateLimiters will implement custom logic to calculate
|
|
34
|
-
* the period of time to wait between background executions for a transport.
|
|
35
|
-
*/
|
|
36
|
-
export interface BackgroundExecuteRateLimiter extends RateLimiter {
|
|
37
|
-
msUntilNextExecution(endpointName: string): number;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* This method will convert all possible settings for a rate limit tier and
|
|
41
|
-
* convert them all to requests per second, returning the lowest one
|
|
42
|
-
*
|
|
43
|
-
* @param limits - the rate limit tier set for the adapter
|
|
44
|
-
* @returns the most restrictive of the set options, in requests per second
|
|
45
|
-
*/
|
|
46
|
-
export declare const consolidateTierLimits: (limits?: AdapterRateLimitTier) => number;
|
|
47
|
-
/**
|
|
48
|
-
* Validates rate limiting tiers specified for the adapter, and returns the one to use.
|
|
49
|
-
*
|
|
50
|
-
* @param tiers - the adapter config listing the different available API tiers
|
|
51
|
-
* @param selectedTier - chosen API tier from settings, if present
|
|
52
|
-
* @returns the specified API tier, or a default one if none are specified
|
|
53
|
-
*/
|
|
54
|
-
export declare const getRateLimitingTier: (tiers?: Record<string, AdapterRateLimitTier>, selectedTier?: string) => AdapterRateLimitTier | undefined;
|
|
@@ -1,63 +0,0 @@
|
|
|
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.getRateLimitingTier = exports.consolidateTierLimits = void 0;
|
|
18
|
-
__exportStar(require("./request/simple-counting"), exports);
|
|
19
|
-
__exportStar(require("./background/fixed-frequency"), 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 tiers - the adapter config listing the different available API tiers
|
|
38
|
-
* @param selectedTier - chosen API tier from settings, if present
|
|
39
|
-
* @returns the specified API tier, or a default one if none are specified
|
|
40
|
-
*/
|
|
41
|
-
const getRateLimitingTier = (tiers, selectedTier) => {
|
|
42
|
-
if (!tiers) {
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
// Check that if the tiers object is defined, it has values
|
|
46
|
-
if (Object.values(tiers).length === 0) {
|
|
47
|
-
throw new Error(`The tiers object is defined, but has no entries`);
|
|
48
|
-
}
|
|
49
|
-
// Check that the tier set in the AdapterConfig is a valid one
|
|
50
|
-
if (selectedTier && !tiers[selectedTier]) {
|
|
51
|
-
const validTiersString = Object.keys(tiers)
|
|
52
|
-
.map((t) => `"${t}"`)
|
|
53
|
-
.join(', ');
|
|
54
|
-
throw new Error(`The selected rate limit tier "${selectedTier}" is not valid (can be one of ${validTiersString})`);
|
|
55
|
-
}
|
|
56
|
-
if (!selectedTier) {
|
|
57
|
-
// Sort the tiers by most to least restrictive
|
|
58
|
-
const sortedTiers = Object.values(tiers).sort((t1, t2) => (0, exports.consolidateTierLimits)(t1) - (0, exports.consolidateTierLimits)(t2));
|
|
59
|
-
return sortedTiers[0];
|
|
60
|
-
}
|
|
61
|
-
return tiers[selectedTier];
|
|
62
|
-
};
|
|
63
|
-
exports.getRateLimitingTier = getRateLimitingTier;
|
|
@@ -1,44 +0,0 @@
|
|
|
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
|
-
});
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { AdapterRateLimitTier, RateLimiter } from '..';
|
|
2
|
-
import { AdapterEndpoint } 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(endpoints: AdapterEndpoint[], limits?: AdapterRateLimitTier): this;
|
|
19
|
-
isUnderLimits(): boolean;
|
|
20
|
-
}
|
|
@@ -1,62 +0,0 @@
|
|
|
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;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/src/package/test.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
2
|
-
import { Cache } from '../cache';
|
|
3
|
-
import { AdapterConfig, SettingsMap } from '../config';
|
|
4
|
-
import { BackgroundExecuteRateLimiter } from '../rate-limiting';
|
|
5
|
-
import { ExpiringSortedSet } from '../util';
|
|
6
|
-
import { AdapterRequest, ProviderResult } from '../util/request';
|
|
7
|
-
import { AdapterContext, AdapterDependencies, Transport } from './';
|
|
8
|
-
/**
|
|
9
|
-
* Transport implementation that takes incoming batches requests and keeps a warm cache of values.
|
|
10
|
-
* Within the setup function, adapter params are added to an set that also keeps track and expires values.
|
|
11
|
-
* In the background execute, the list of non-expired items in the set is fetched.
|
|
12
|
-
* Then, the list is passed through the `prepareRequest` function, that returns an AxiosRequestConfig.
|
|
13
|
-
* The Data Provider response is, they are passed through the `parseResponse` function to create a [[CacheEntry]] list.
|
|
14
|
-
* Finally, the items in that [[CacheEntry]] list are set in the Cache so the Adapter can fetch values from there.
|
|
15
|
-
*
|
|
16
|
-
* @typeParam AdapterParams - interface for the adapter request body
|
|
17
|
-
* @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
|
|
18
|
-
* @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
|
|
19
|
-
*/
|
|
20
|
-
export declare class BatchWarmingTransport<AdapterParams, ProviderRequestBody, ProviderResponseBody, CustomSettings extends SettingsMap> implements Transport<AdapterParams, ProviderResponseBody, CustomSettings> {
|
|
21
|
-
private config;
|
|
22
|
-
cache: Cache;
|
|
23
|
-
rateLimiter: BackgroundExecuteRateLimiter;
|
|
24
|
-
expiringSortedSet: ExpiringSortedSet<AdapterParams>;
|
|
25
|
-
WARMER_ACTIVE: boolean;
|
|
26
|
-
constructor(config: {
|
|
27
|
-
prepareRequest: (params: AdapterParams[], context: AdapterContext<CustomSettings>) => AxiosRequestConfig<ProviderRequestBody>;
|
|
28
|
-
parseResponse: (res: AxiosResponse<ProviderResponseBody>, context: AdapterContext<CustomSettings>) => ProviderResult<AdapterParams>[];
|
|
29
|
-
});
|
|
30
|
-
initialize(dependencies: AdapterDependencies): Promise<void>;
|
|
31
|
-
hasBeenSetUp(req: AdapterRequest<AdapterParams>): Promise<boolean>;
|
|
32
|
-
setup(req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>): Promise<void>;
|
|
33
|
-
backgroundExecute(context: AdapterContext<CustomSettings>): Promise<number>;
|
|
34
|
-
}
|
|
@@ -1,101 +0,0 @@
|
|
|
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.BatchWarmingTransport = void 0;
|
|
27
|
-
const util_1 = require("../util");
|
|
28
|
-
const _1 = require("./");
|
|
29
|
-
const util_2 = require("./util");
|
|
30
|
-
const rateLimitMetrics = __importStar(require("../rate-limiting/metrics"));
|
|
31
|
-
const cacheMetrics = __importStar(require("../cache/metrics"));
|
|
32
|
-
const WARMUP_BATCH_REQUEST_ID = '9002';
|
|
33
|
-
const logger = (0, util_1.makeLogger)('BatchWarmingTransport');
|
|
34
|
-
/**
|
|
35
|
-
* Transport implementation that takes incoming batches requests and keeps a warm cache of values.
|
|
36
|
-
* Within the setup function, adapter params are added to an set that also keeps track and expires values.
|
|
37
|
-
* In the background execute, the list of non-expired items in the set is fetched.
|
|
38
|
-
* Then, the list is passed through the `prepareRequest` function, that returns an AxiosRequestConfig.
|
|
39
|
-
* The Data Provider response is, they are passed through the `parseResponse` function to create a [[CacheEntry]] list.
|
|
40
|
-
* Finally, the items in that [[CacheEntry]] list are set in the Cache so the Adapter can fetch values from there.
|
|
41
|
-
*
|
|
42
|
-
* @typeParam AdapterParams - interface for the adapter request body
|
|
43
|
-
* @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
|
|
44
|
-
* @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
|
|
45
|
-
*/
|
|
46
|
-
class BatchWarmingTransport {
|
|
47
|
-
constructor(config) {
|
|
48
|
-
this.config = config;
|
|
49
|
-
this.expiringSortedSet = new util_1.ExpiringSortedSet(); // TODO: Move to dependencies, inject
|
|
50
|
-
// Flag used to track whether the warmer has moved from having no entries to having some and vice versa
|
|
51
|
-
// Used for recording the cache warmer active metrics accurately
|
|
52
|
-
this.WARMER_ACTIVE = false;
|
|
53
|
-
}
|
|
54
|
-
async initialize(dependencies) {
|
|
55
|
-
this.cache = dependencies.cache;
|
|
56
|
-
this.rateLimiter = dependencies.backgroundExecuteRateLimiter;
|
|
57
|
-
}
|
|
58
|
-
async hasBeenSetUp(req) {
|
|
59
|
-
return !!this.expiringSortedSet.get(req.requestContext.cacheKey);
|
|
60
|
-
}
|
|
61
|
-
async setup(req, config) {
|
|
62
|
-
logger.debug(`Adding entry to batch warming set: [${req.requestContext.cacheKey}] = ${req.requestContext.data}`);
|
|
63
|
-
this.expiringSortedSet.add(req.requestContext.cacheKey, req.requestContext.data, config.WARMUP_SUBSCRIPTION_TTL);
|
|
64
|
-
}
|
|
65
|
-
async backgroundExecute(context) {
|
|
66
|
-
logger.debug('Starting background execute');
|
|
67
|
-
const entries = this.expiringSortedSet.getAll();
|
|
68
|
-
if (!entries.length) {
|
|
69
|
-
logger.debug('No entries in batch warming set, skipping');
|
|
70
|
-
if (this.WARMER_ACTIVE) {
|
|
71
|
-
// Decrement count when warmer changed from having entries to having none
|
|
72
|
-
cacheMetrics.cacheWarmerCount.labels({ isBatched: 'true' }).dec();
|
|
73
|
-
this.WARMER_ACTIVE = false;
|
|
74
|
-
}
|
|
75
|
-
return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name);
|
|
76
|
-
}
|
|
77
|
-
else if (this.WARMER_ACTIVE === false) {
|
|
78
|
-
// Increment count when warmer changed from having no entries to having some
|
|
79
|
-
cacheMetrics.cacheWarmerCount.labels({ isBatched: 'true' }).inc();
|
|
80
|
-
this.WARMER_ACTIVE = true;
|
|
81
|
-
}
|
|
82
|
-
const request = this.config.prepareRequest(entries, context);
|
|
83
|
-
logger.trace('Sending request to data provider...');
|
|
84
|
-
const providerResponse = await (0, util_2.axiosRequest)(request);
|
|
85
|
-
logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`);
|
|
86
|
-
const results = this.config.parseResponse(providerResponse, context);
|
|
87
|
-
const adapterResponses = (0, _1.buildCacheEntriesFromResults)(results, context);
|
|
88
|
-
logger.debug('Setting adapter responses in cache');
|
|
89
|
-
await this.cache.setMany(adapterResponses, context.adapterConfig.CACHE_MAX_AGE);
|
|
90
|
-
// Record cost of data provider call
|
|
91
|
-
const cost = rateLimitMetrics.retrieveCost(providerResponse.data);
|
|
92
|
-
rateLimitMetrics.rateLimitCreditsSpentTotal
|
|
93
|
-
.labels({
|
|
94
|
-
feed_id: 'N/A',
|
|
95
|
-
participant_id: WARMUP_BATCH_REQUEST_ID,
|
|
96
|
-
})
|
|
97
|
-
.inc(cost);
|
|
98
|
-
return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
exports.BatchWarmingTransport = BatchWarmingTransport;
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import { FastifyReply } from 'fastify';
|
|
2
|
-
import { AdapterEndpoint, InitializedAdapter } from '../adapter';
|
|
3
|
-
import { Cache, CacheEntry } from '../cache';
|
|
4
|
-
import { AdapterConfig, CustomSettingsType, SettingsMap } from '../config';
|
|
5
|
-
import { BackgroundExecuteRateLimiter, RequestRateLimiter } from '../rate-limiting';
|
|
6
|
-
import { AdapterRequest, AdapterResponse, ProviderResult } from '../util/request';
|
|
7
|
-
export * from './batch-warming';
|
|
8
|
-
export * from './rest';
|
|
9
|
-
export * from './websocket';
|
|
10
|
-
/**
|
|
11
|
-
* Dependencies that will be injected into the Adapter on startup
|
|
12
|
-
*/
|
|
13
|
-
export interface AdapterDependencies {
|
|
14
|
-
cache: Cache;
|
|
15
|
-
requestRateLimiter: RequestRateLimiter;
|
|
16
|
-
backgroundExecuteRateLimiter: BackgroundExecuteRateLimiter;
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* Context that will be used on background executions of a Transport.
|
|
20
|
-
* For example, the endpointName used to log statements or generate Cache keys.
|
|
21
|
-
*/
|
|
22
|
-
export interface AdapterContext<CustomSettings extends CustomSettingsType<CustomSettings> = SettingsMap> {
|
|
23
|
-
adapterEndpoint: AdapterEndpoint;
|
|
24
|
-
adapterConfig: AdapterConfig<CustomSettings>;
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Generic interface for a Transport.
|
|
28
|
-
* A Transport defines the way in which an AdapterEndpoint will process incoming requests to
|
|
29
|
-
* fetch data from a Data Provider. The setup phase will take care of the former, while the
|
|
30
|
-
* backgroundExecute will be in charge of the latter.
|
|
31
|
-
* This separation gives us the ability of splitting these concerns, and optionally parallelizing
|
|
32
|
-
* the reading and writing of data to a centralized Cache.
|
|
33
|
-
*
|
|
34
|
-
* @typeParam Params - the structure of the AdapterRequest's body
|
|
35
|
-
* @typeParam Result - the structure of the AdapterResponse's body
|
|
36
|
-
*/
|
|
37
|
-
export interface Transport<Params, Result, CustomSettings extends SettingsMap> {
|
|
38
|
-
/**
|
|
39
|
-
* Initializes the transport in the Adapter context.
|
|
40
|
-
*
|
|
41
|
-
* @param dependencies - Adapter dependencies (e.g. cache instance)
|
|
42
|
-
* @returns an empty Promise
|
|
43
|
-
*/
|
|
44
|
-
initialize: (dependencies: AdapterDependencies) => Promise<void>;
|
|
45
|
-
/**
|
|
46
|
-
* Checks if the Transport has already set up the incoming request.
|
|
47
|
-
* This will likely use the cacheKey generated in the provided request.
|
|
48
|
-
*
|
|
49
|
-
* @param req - the incoming AdapterRequest
|
|
50
|
-
* @returns a Promise that returns true if setup is in place
|
|
51
|
-
*/
|
|
52
|
-
hasBeenSetUp: (req: AdapterRequest<Params>) => Promise<boolean>;
|
|
53
|
-
/**
|
|
54
|
-
* Sets up the incoming request within the Transport.
|
|
55
|
-
* In other words, it means that the Adapter has recognized this request, and will begin
|
|
56
|
-
* fetching the necessary data from a Data Provider.
|
|
57
|
-
*
|
|
58
|
-
* @param req - the incoming AdapterRequest
|
|
59
|
-
* @param config - common configuration for the Adapter as a whole
|
|
60
|
-
* @returns a Promise that _optionally_ returns an AdapterResponse, if the Transport has the capability of
|
|
61
|
-
* immediately fetching data and returning it without the background process.
|
|
62
|
-
*/
|
|
63
|
-
setup: (req: AdapterRequest<Params>, config: AdapterConfig<CustomSettings>) => Promise<AdapterResponse<Result> | void>;
|
|
64
|
-
/**
|
|
65
|
-
* If the Transport relies on an async mechanism, implementing this function will make it
|
|
66
|
-
* so the background task executor calls it on Adapter startup.
|
|
67
|
-
*
|
|
68
|
-
* @param context - background context for the execution (e.g. endpoint name)
|
|
69
|
-
*/
|
|
70
|
-
backgroundExecute?: (context: AdapterContext<CustomSettings>) => Promise<number>;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Helper method to build cache entries to set after getting a bunch of responses from a DP.
|
|
74
|
-
*
|
|
75
|
-
* @param results - a list of results coming from a DataProvider
|
|
76
|
-
* @param context - context for the Adapter
|
|
77
|
-
* @returns a list of CacheEntries of AdapterResponses
|
|
78
|
-
*/
|
|
79
|
-
export declare const buildCacheEntriesFromResults: <Params, Context extends AdapterContext<any>>(results: ProviderResult<Params>[], context: Context) => CacheEntry<AdapterResponse<null>>[];
|
|
80
|
-
/**
|
|
81
|
-
* Takes an Adapter, its configuration, and its dependencies, and it creates an express middleware
|
|
82
|
-
* that will pass along the AdapterRequest to the appropriate Transport (acc. to the endpoint in the req.)
|
|
83
|
-
*
|
|
84
|
-
* @param adapter - main adapter object, already initialized
|
|
85
|
-
* @returns the transport handler middleware function
|
|
86
|
-
*/
|
|
87
|
-
export declare const buildTransportHandler: (adapter: InitializedAdapter) => (req: AdapterRequest, reply: FastifyReply) => Promise<never>;
|
|
@@ -1,87 +0,0 @@
|
|
|
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.buildTransportHandler = exports.buildCacheEntriesFromResults = void 0;
|
|
18
|
-
const cache_1 = require("../cache");
|
|
19
|
-
const util_1 = require("../util");
|
|
20
|
-
__exportStar(require("./batch-warming"), exports);
|
|
21
|
-
__exportStar(require("./rest"), exports);
|
|
22
|
-
__exportStar(require("./websocket"), exports);
|
|
23
|
-
const logger = (0, util_1.makeLogger)('Transport');
|
|
24
|
-
/**
|
|
25
|
-
* Helper method to build cache entries to set after getting a bunch of responses from a DP.
|
|
26
|
-
*
|
|
27
|
-
* @param results - a list of results coming from a DataProvider
|
|
28
|
-
* @param context - context for the Adapter
|
|
29
|
-
* @returns a list of CacheEntries of AdapterResponses
|
|
30
|
-
*/
|
|
31
|
-
const buildCacheEntriesFromResults = (results, context) => results.map((r) => {
|
|
32
|
-
const cacheEntry = {
|
|
33
|
-
key: (0, cache_1.calculateCacheKey)(context, r.params),
|
|
34
|
-
value: {
|
|
35
|
-
result: r.value,
|
|
36
|
-
statusCode: 200,
|
|
37
|
-
data: null, // TODO: Maybe add data as well?
|
|
38
|
-
},
|
|
39
|
-
};
|
|
40
|
-
if (context.adapterConfig.METRICS_ENABLED &&
|
|
41
|
-
context.adapterConfig.EXPERIMENTAL_METRICS_ENABLED) {
|
|
42
|
-
const metrics = {
|
|
43
|
-
maxAge: Date.now() + context.adapterConfig.CACHE_MAX_AGE,
|
|
44
|
-
meta: {
|
|
45
|
-
metrics: {
|
|
46
|
-
feedId: (0, cache_1.calculateFeedId)(context.adapterEndpoint, r.params)
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
cacheEntry.value = { ...cacheEntry.value, ...metrics };
|
|
51
|
-
}
|
|
52
|
-
return cacheEntry;
|
|
53
|
-
});
|
|
54
|
-
exports.buildCacheEntriesFromResults = buildCacheEntriesFromResults;
|
|
55
|
-
/**
|
|
56
|
-
* Takes an Adapter, its configuration, and its dependencies, and it creates an express middleware
|
|
57
|
-
* that will pass along the AdapterRequest to the appropriate Transport (acc. to the endpoint in the req.)
|
|
58
|
-
*
|
|
59
|
-
* @param adapter - main adapter object, already initialized
|
|
60
|
-
* @returns the transport handler middleware function
|
|
61
|
-
*/
|
|
62
|
-
const buildTransportHandler = (adapter) => async (req, reply) => {
|
|
63
|
-
// Get transport, must be here because it's already checked in the validator
|
|
64
|
-
const transport = adapter.endpointsMap[req.requestContext.endpointName].transport;
|
|
65
|
-
// Set up transport if it hasn't been done already
|
|
66
|
-
if (!(await transport.hasBeenSetUp(req))) {
|
|
67
|
-
logger.debug('Transport not set up yet, doing so...');
|
|
68
|
-
const immediateResponse = await transport.setup(req, adapter.config);
|
|
69
|
-
if (immediateResponse) {
|
|
70
|
-
logger.debug('Got immediate response from transport, sending as response');
|
|
71
|
-
return reply.send(immediateResponse);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
logger.debug('Transport is set up, polling cache for response...');
|
|
75
|
-
const response = await (0, cache_1.pollResponseFromCache)(adapter.dependencies.cache, req.requestContext.cacheKey, {
|
|
76
|
-
maxRetries: adapter.config.CACHE_POLLING_MAX_RETRIES,
|
|
77
|
-
sleep: adapter.config.CACHE_POLLING_SLEEP_MS,
|
|
78
|
-
});
|
|
79
|
-
if (response) {
|
|
80
|
-
logger.debug('Got a response from the cache, sending that back');
|
|
81
|
-
return reply.send(response);
|
|
82
|
-
}
|
|
83
|
-
logger.debug('Ran out of polling attempts, returning timeout');
|
|
84
|
-
reply.statusCode = 504;
|
|
85
|
-
return reply.send();
|
|
86
|
-
};
|
|
87
|
-
exports.buildTransportHandler = buildTransportHandler;
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import * as client from 'prom-client';
|
|
2
|
-
import { AdapterContext } from '.';
|
|
3
|
-
export declare const dataProviderMetricsLabel: (providerStatusCode?: number, method?: string) => {
|
|
4
|
-
provider_status_code: number | undefined;
|
|
5
|
-
method: string;
|
|
6
|
-
};
|
|
7
|
-
export declare const dataProviderRequests: client.Counter<"method" | "provider_status_code">;
|
|
8
|
-
export declare const dataProviderRequestDurationSeconds: client.Histogram<string>;
|
|
9
|
-
export declare const connectionErrorLabels: (message: string) => {
|
|
10
|
-
message: string;
|
|
11
|
-
};
|
|
12
|
-
export declare const messageSubsLabels: (feed_id: string, cache_key: string) => {
|
|
13
|
-
feed_id: string;
|
|
14
|
-
subscription_key: string;
|
|
15
|
-
};
|
|
16
|
-
export declare const recordWsMessageMetrics: <AdapterParams>(context: AdapterContext, subscribes: AdapterParams[], unsubscrices: AdapterParams[]) => void;
|
|
17
|
-
export declare const wsConnectionActive: client.Gauge<"url">;
|
|
18
|
-
export declare const wsConnectionErrors: client.Counter<"message" | "url">;
|
|
19
|
-
export declare const wsSubscriptionActive: client.Gauge<"feed_id" | "connection_url" | "subscription_key">;
|
|
20
|
-
export declare const wsSubscriptionTotal: client.Counter<"feed_id" | "connection_url" | "subscription_key">;
|
|
21
|
-
export declare const wsMessageTotal: client.Counter<"feed_id" | "subscription_key">;
|