@chainlink/external-adapter-framework 0.0.15 → 0.0.16
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.js +128 -0
- package/background-executor.js +45 -0
- package/cache/factory.js +58 -0
- package/cache/index.js +173 -0
- package/cache/local.js +83 -0
- package/cache/metrics.js +120 -0
- package/cache/redis.js +100 -0
- package/chainlink-external-adapter-framework-v0.0.6.tgz +0 -0
- package/config/index.js +366 -0
- package/config/provider-limits.js +74 -0
- package/examples/bank-frick/accounts.js +192 -0
- package/examples/bank-frick/config/index.js +54 -0
- package/examples/bank-frick/index.js +15 -0
- package/examples/bank-frick/util.js +39 -0
- package/examples/coingecko/src/config/index.js +13 -0
- package/examples/coingecko/src/config/overrides.json +10826 -0
- package/examples/coingecko/src/cryptoUtils.js +41 -0
- package/examples/coingecko/src/endpoint/coins.js +33 -0
- package/examples/coingecko/src/endpoint/crypto-marketcap.js +46 -0
- package/examples/coingecko/src/endpoint/crypto-volume.js +46 -0
- package/examples/coingecko/src/endpoint/crypto.js +47 -0
- package/examples/coingecko/src/endpoint/dominance.js +26 -0
- package/examples/coingecko/src/endpoint/global-marketcap.js +26 -0
- package/examples/coingecko/src/endpoint/index.js +15 -0
- package/examples/coingecko/src/globalUtils.js +48 -0
- package/examples/coingecko/src/index.js +14 -0
- package/examples/coingecko/test/e2e/adapter.test.js +262 -0
- package/examples/coingecko/test/integration/adapter.test.js +264 -0
- package/examples/coingecko/test/integration/capturedRequests.json +1 -0
- package/examples/coingecko/test/integration/fixtures.js +41 -0
- package/examples/coingecko-old/batch-warming.js +53 -0
- package/examples/coingecko-old/index.js +11 -0
- package/examples/coingecko-old/rest.js +51 -0
- package/examples/ncfx/config/index.js +15 -0
- package/examples/ncfx/index.js +11 -0
- package/examples/ncfx/websocket.js +73 -0
- package/index.js +127 -0
- package/metrics/constants.js +25 -0
- package/metrics/index.js +122 -0
- package/metrics/util.js +9 -0
- package/package.json +5 -15
- package/rate-limiting/background/fixed-frequency.js +35 -0
- package/rate-limiting/index.js +84 -0
- package/rate-limiting/metrics.js +44 -0
- package/rate-limiting/request/simple-counting.js +62 -0
- package/test.js +6 -0
- package/transports/batch-warming.js +101 -0
- package/transports/index.js +87 -0
- package/transports/metrics.js +105 -0
- package/transports/rest.js +138 -0
- package/transports/util.js +86 -0
- package/transports/websocket.js +166 -0
- package/util/index.js +35 -0
- package/util/logger.js +62 -0
- package/util/recordRequests.js +45 -0
- package/util/request.js +2 -0
- package/util/subscription-set/expiring-sorted-set.js +47 -0
- package/util/subscription-set/subscription-set.js +19 -0
- package/util/test-payload-loader.js +83 -0
- package/validation/error.js +79 -0
- package/validation/index.js +91 -0
- package/validation/input-params.js +30 -0
- package/validation/override-functions.js +40 -0
- package/validation/overrideFunctions.js +40 -0
- package/validation/preset-tokens.json +23 -0
- package/validation/validator.js +303 -0
- package/.c8rc.json +0 -3
- package/.eslintignore +0 -10
- package/.eslintrc.js +0 -96
- package/.github/README.MD +0 -42
- package/.github/actions/setup/action.yaml +0 -13
- package/.github/workflows/label.yaml +0 -39
- package/.github/workflows/main.yaml +0 -39
- package/.github/workflows/publish.yaml +0 -17
- package/.prettierignore +0 -13
- package/.yarnrc +0 -0
- package/README.md +0 -103
- package/dist/examples/coingecko/test/e2e/adapter.test.ts.js +0 -82953
- package/dist/examples/coingecko/test/integration/adapter.test.ts.js +0 -91672
- package/dist/main.js +0 -72703
- package/docker-compose.yaml +0 -35
- package/env.sh +0 -54
- package/env2.sh +0 -55
- package/jest.config.js +0 -5
- package/publish.sh +0 -0
- package/src/adapter.ts +0 -263
- package/src/background-executor.ts +0 -52
- package/src/cache/factory.ts +0 -26
- package/src/cache/index.ts +0 -258
- package/src/cache/local.ts +0 -73
- package/src/cache/metrics.ts +0 -112
- package/src/cache/redis.ts +0 -93
- package/src/config/index.ts +0 -517
- package/src/config/provider-limits.ts +0 -127
- package/src/examples/bank-frick/README.MD +0 -10
- package/src/examples/bank-frick/accounts.ts +0 -246
- package/src/examples/bank-frick/config/index.ts +0 -53
- package/src/examples/bank-frick/index.ts +0 -13
- package/src/examples/bank-frick/types.d.ts +0 -38
- package/src/examples/bank-frick/util.ts +0 -55
- package/src/examples/coingecko/src/config/index.ts +0 -12
- package/src/examples/coingecko/src/config/overrides.json +0 -10826
- package/src/examples/coingecko/src/cryptoUtils.ts +0 -88
- package/src/examples/coingecko/src/endpoint/coins.ts +0 -54
- package/src/examples/coingecko/src/endpoint/crypto-marketcap.ts +0 -66
- package/src/examples/coingecko/src/endpoint/crypto-volume.ts +0 -66
- package/src/examples/coingecko/src/endpoint/crypto.ts +0 -63
- package/src/examples/coingecko/src/endpoint/dominance.ts +0 -40
- package/src/examples/coingecko/src/endpoint/global-marketcap.ts +0 -40
- package/src/examples/coingecko/src/endpoint/index.ts +0 -6
- package/src/examples/coingecko/src/globalUtils.ts +0 -78
- package/src/examples/coingecko/src/index.ts +0 -17
- package/src/examples/coingecko/test/e2e/adapter.test.ts +0 -278
- package/src/examples/coingecko/test/integration/__snapshots__/adapter.test.ts.snap +0 -15
- package/src/examples/coingecko/test/integration/adapter.test.ts +0 -281
- package/src/examples/coingecko/test/integration/capturedRequests.json +0 -1
- package/src/examples/coingecko/test/integration/fixtures.ts +0 -42
- package/src/examples/coingecko-old/batch-warming.ts +0 -79
- package/src/examples/coingecko-old/index.ts +0 -9
- package/src/examples/coingecko-old/rest.ts +0 -77
- package/src/examples/ncfx/config/index.ts +0 -12
- package/src/examples/ncfx/index.ts +0 -9
- package/src/examples/ncfx/websocket.ts +0 -99
- package/src/index.ts +0 -149
- package/src/metrics/constants.ts +0 -23
- package/src/metrics/index.ts +0 -115
- package/src/metrics/util.ts +0 -18
- package/src/rate-limiting/background/fixed-frequency.ts +0 -45
- package/src/rate-limiting/index.ts +0 -100
- package/src/rate-limiting/metrics.ts +0 -18
- package/src/rate-limiting/request/simple-counting.ts +0 -76
- package/src/transports/batch-warming.ts +0 -127
- package/src/transports/index.ts +0 -152
- package/src/transports/metrics.ts +0 -95
- package/src/transports/rest.ts +0 -168
- package/src/transports/util.ts +0 -63
- package/src/transports/websocket.ts +0 -245
- package/src/util/index.ts +0 -23
- package/src/util/logger.ts +0 -69
- package/src/util/recordRequests.ts +0 -47
- package/src/util/request.ts +0 -117
- package/src/util/subscription-set/expiring-sorted-set.ts +0 -54
- package/src/util/subscription-set/subscription-set.ts +0 -35
- package/src/util/test-payload-loader.ts +0 -87
- package/src/validation/error.ts +0 -116
- package/src/validation/index.ts +0 -110
- package/src/validation/input-params.ts +0 -45
- package/src/validation/override-functions.ts +0 -44
- package/src/validation/overrideFunctions.ts +0 -44
- package/src/validation/preset-tokens.json +0 -23
- package/src/validation/validator.ts +0 -384
- package/test/adapter.test.ts +0 -27
- package/test/background-executor.test.ts +0 -108
- package/test/cache/cache-key.test.ts +0 -114
- package/test/cache/helper.ts +0 -100
- package/test/cache/local.test.ts +0 -54
- package/test/cache/redis.test.ts +0 -89
- package/test/correlation.test.ts +0 -114
- package/test/index.test.ts +0 -37
- package/test/metrics/feed-id.test.ts +0 -38
- package/test/metrics/helper.ts +0 -14
- package/test/metrics/labels.test.ts +0 -36
- package/test/metrics/metrics.test.ts +0 -267
- package/test/metrics/redis-metrics.test.ts +0 -113
- package/test/metrics/warmer-metrics.test.ts +0 -193
- package/test/metrics/ws-metrics.test.ts +0 -225
- package/test/rate-limit-config.test.ts +0 -242
- package/test/smoke/smoke.test.ts +0 -166
- package/test/smoke/test-payload-fail.json +0 -3
- package/test/smoke/test-payload.js +0 -22
- package/test/smoke/test-payload.json +0 -7
- package/test/transports/batch.test.ts +0 -466
- package/test/transports/rest.test.ts +0 -242
- package/test/transports/websocket.test.ts +0 -183
- package/test/tsconfig.json +0 -5
- package/test/util.ts +0 -77
- package/test/validation.test.ts +0 -178
- package/test.sh +0 -20
- package/test2.sh +0 -2
- package/tsconfig.json +0 -28
- package/typedoc.json +0 -6
- package/webpack.config.js +0 -57
- package/yarn-error.log +0 -3778
|
@@ -0,0 +1,84 @@
|
|
|
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 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 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
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,62 @@
|
|
|
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;
|
package/test.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
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
|
+
// Flag used to track whether the warmer has moved from having no entries to having some and vice versa
|
|
50
|
+
// Used for recording the cache warmer active metrics accurately
|
|
51
|
+
this.WARMER_ACTIVE = false;
|
|
52
|
+
}
|
|
53
|
+
async initialize(dependencies) {
|
|
54
|
+
this.cache = dependencies.cache;
|
|
55
|
+
this.rateLimiter = dependencies.backgroundExecuteRateLimiter;
|
|
56
|
+
this.subscriptionSet = dependencies.subscriptionSetFactory.buildSet();
|
|
57
|
+
}
|
|
58
|
+
async hasBeenSetUp(req) {
|
|
59
|
+
return !!(await this.subscriptionSet.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
|
+
await this.subscriptionSet.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 = await this.subscriptionSet.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, context.adapterConfig);
|
|
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;
|
|
@@ -0,0 +1,87 @@
|
|
|
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, 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;
|
|
@@ -0,0 +1,105 @@
|
|
|
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.wsMessageTotal = exports.wsSubscriptionTotal = exports.wsSubscriptionActive = exports.wsConnectionErrors = exports.wsConnectionActive = exports.recordWsMessageMetrics = exports.messageSubsLabels = exports.connectionErrorLabels = exports.dataProviderRequestDurationSeconds = exports.dataProviderRequests = exports.dataProviderMetricsLabel = void 0;
|
|
27
|
+
const client = __importStar(require("prom-client"));
|
|
28
|
+
const cache_1 = require("../cache");
|
|
29
|
+
const constants_1 = require("../metrics/constants");
|
|
30
|
+
// Data Provider Metrics
|
|
31
|
+
const dataProviderMetricsLabel = (providerStatusCode, method = 'get') => ({
|
|
32
|
+
provider_status_code: providerStatusCode,
|
|
33
|
+
method: method.toUpperCase(),
|
|
34
|
+
});
|
|
35
|
+
exports.dataProviderMetricsLabel = dataProviderMetricsLabel;
|
|
36
|
+
exports.dataProviderRequests = new client.Counter({
|
|
37
|
+
name: 'data_provider_requests',
|
|
38
|
+
help: 'The number of http requests that are made to a data provider',
|
|
39
|
+
labelNames: ['method', 'provider_status_code'],
|
|
40
|
+
});
|
|
41
|
+
exports.dataProviderRequestDurationSeconds = new client.Histogram({
|
|
42
|
+
name: 'data_provider_request_duration_seconds',
|
|
43
|
+
help: 'A histogram bucket of the distribution of data provider request durations',
|
|
44
|
+
buckets: constants_1.requestDurationBuckets,
|
|
45
|
+
});
|
|
46
|
+
// Websocket Metrics
|
|
47
|
+
const connectionErrorLabels = (message) => ({
|
|
48
|
+
// Key,
|
|
49
|
+
message,
|
|
50
|
+
});
|
|
51
|
+
exports.connectionErrorLabels = connectionErrorLabels;
|
|
52
|
+
const messageSubsLabels = (feed_id, cache_key) => ({
|
|
53
|
+
feed_id,
|
|
54
|
+
subscription_key: cache_key,
|
|
55
|
+
});
|
|
56
|
+
exports.messageSubsLabels = messageSubsLabels;
|
|
57
|
+
// Record WS message and subscription metrics
|
|
58
|
+
// Recalculate cacheKey and feedId for metrics
|
|
59
|
+
// since avoiding storing extra info in expiring sorted set
|
|
60
|
+
const recordWsMessageMetrics = (context, subscribes, unsubscrices) => {
|
|
61
|
+
subscribes.forEach((param) => {
|
|
62
|
+
const feedId = (0, cache_1.calculateFeedId)(context, param);
|
|
63
|
+
const cacheKey = (0, cache_1.calculateCacheKey)(context, param);
|
|
64
|
+
// Record total number of ws messages sent
|
|
65
|
+
exports.wsMessageTotal.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
|
|
66
|
+
// Record total number of subscriptions made
|
|
67
|
+
exports.wsSubscriptionTotal.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
|
|
68
|
+
// Record number of active ws subscriptions
|
|
69
|
+
exports.wsSubscriptionActive.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
|
|
70
|
+
});
|
|
71
|
+
unsubscrices.forEach((param) => {
|
|
72
|
+
const feedId = (0, cache_1.calculateFeedId)(context, param);
|
|
73
|
+
const cacheKey = (0, cache_1.calculateCacheKey)(context, param);
|
|
74
|
+
// Record total number of ws messages sent
|
|
75
|
+
exports.wsMessageTotal.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
|
|
76
|
+
// Record number of active ws subscriptions
|
|
77
|
+
exports.wsSubscriptionActive.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).dec();
|
|
78
|
+
});
|
|
79
|
+
};
|
|
80
|
+
exports.recordWsMessageMetrics = recordWsMessageMetrics;
|
|
81
|
+
exports.wsConnectionActive = new client.Gauge({
|
|
82
|
+
name: 'ws_connection_active',
|
|
83
|
+
help: 'The number of active connections',
|
|
84
|
+
labelNames: ['url'],
|
|
85
|
+
});
|
|
86
|
+
exports.wsConnectionErrors = new client.Counter({
|
|
87
|
+
name: 'ws_connection_errors',
|
|
88
|
+
help: 'The number of connection errors',
|
|
89
|
+
labelNames: ['url', 'message'],
|
|
90
|
+
});
|
|
91
|
+
exports.wsSubscriptionActive = new client.Gauge({
|
|
92
|
+
name: 'ws_subscription_active',
|
|
93
|
+
help: 'The number of currently active subscriptions',
|
|
94
|
+
labelNames: ['connection_url', 'feed_id', 'subscription_key'],
|
|
95
|
+
});
|
|
96
|
+
exports.wsSubscriptionTotal = new client.Counter({
|
|
97
|
+
name: 'ws_subscription_total',
|
|
98
|
+
help: 'The number of subscriptions opened in total',
|
|
99
|
+
labelNames: ['connection_url', 'feed_id', 'subscription_key'],
|
|
100
|
+
});
|
|
101
|
+
exports.wsMessageTotal = new client.Counter({
|
|
102
|
+
name: 'ws_message_total',
|
|
103
|
+
help: 'The number of messages received in total',
|
|
104
|
+
labelNames: ['feed_id', 'subscription_key'],
|
|
105
|
+
});
|
|
@@ -0,0 +1,138 @@
|
|
|
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.RestTransport = void 0;
|
|
27
|
+
const util_1 = require("../util");
|
|
28
|
+
const error_1 = require("../validation/error");
|
|
29
|
+
const util_2 = require("./util");
|
|
30
|
+
const rateLimitMetrics = __importStar(require("../rate-limiting/metrics"));
|
|
31
|
+
const IN_FLIGHT_PREFIX = 'InFlight';
|
|
32
|
+
const logger = (0, util_1.makeLogger)('RestTransport');
|
|
33
|
+
/**
|
|
34
|
+
* Transport implementation that takes incoming requests, transforms them into a DataProvider request,
|
|
35
|
+
* and executes that request returning the response immediately from the `setup` function.
|
|
36
|
+
* Optionally, setting the `coalescing` option to `true` will make it so once a request is in flight,
|
|
37
|
+
* new adapter requests for the same feed will not trigger a new one, but return an empty promise from
|
|
38
|
+
* the setup instead so the normal cache polling mechanism is used.
|
|
39
|
+
*
|
|
40
|
+
* @typeParam AdapterParams - interface for the adapter request body
|
|
41
|
+
* @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
|
|
42
|
+
* @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
|
|
43
|
+
*/
|
|
44
|
+
class RestTransport {
|
|
45
|
+
constructor(config) {
|
|
46
|
+
this.config = config;
|
|
47
|
+
}
|
|
48
|
+
async initialize(dependencies, config) {
|
|
49
|
+
this.inFlightPrefix = `${IN_FLIGHT_PREFIX}-`;
|
|
50
|
+
this.cache = dependencies.cache;
|
|
51
|
+
this.rateLimiter = dependencies.requestRateLimiter;
|
|
52
|
+
// Allow enabling/disabling request coalescing through env var
|
|
53
|
+
if (config.REQUEST_COALESCING_ENABLED !== undefined) {
|
|
54
|
+
this.config.options.coalescing = config.REQUEST_COALESCING_ENABLED;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async hasBeenSetUp(req) {
|
|
58
|
+
if (!this.config.options.coalescing) {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
// Check if request is in flight
|
|
62
|
+
const inFlight = await this.cache.get(this.inFlightPrefix + req.requestContext.cacheKey);
|
|
63
|
+
if (inFlight) {
|
|
64
|
+
logger.debug('Request is in flight, transport has been set up');
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
logger.debug('Request not in flight, transport not set up');
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async waitUntilUnderRateLimit(options, retry = 0) {
|
|
73
|
+
if (this.rateLimiter.isUnderLimits()) {
|
|
74
|
+
logger.trace('Incoming request would not be under limits, moving on');
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (retry >= options.maxRetries) {
|
|
78
|
+
throw new error_1.AdapterError({
|
|
79
|
+
statusCode: 504,
|
|
80
|
+
message: `REST Transport timed out while waiting for rate limit availability (max retries: ${options.maxRetries})`,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
logger.debug(`Request would be over rate limits, sleeping for ${options.msBetweenRetries}`);
|
|
84
|
+
await (0, util_1.sleep)(options.msBetweenRetries);
|
|
85
|
+
await this.waitUntilUnderRateLimit(options, retry + 1);
|
|
86
|
+
}
|
|
87
|
+
async setup(req, config) {
|
|
88
|
+
if (this.config.options.coalescing) {
|
|
89
|
+
logger.debug('Setting up rest transport, setting request in flight in cache');
|
|
90
|
+
// TODO: Should this use a separate cache?
|
|
91
|
+
// TODO: Set viable ttl to approximate timeout from API
|
|
92
|
+
// TODO: Make this ttl configurable
|
|
93
|
+
await this.cache.set(this.inFlightPrefix + req.requestContext.cacheKey, true, 2000); // Can't use Infinity for things like Redis
|
|
94
|
+
}
|
|
95
|
+
const request = await this.config.prepareRequest(req, config);
|
|
96
|
+
logger.trace('Check if we are under rate limits to perform request');
|
|
97
|
+
await this.waitUntilUnderRateLimit({
|
|
98
|
+
maxRetries: config.REST_TRANSPORT_MAX_RATE_LIMIT_RETRIES,
|
|
99
|
+
msBetweenRetries: config.REST_TRANSPORT_MS_BETWEEN_RATE_LIMIT_RETRIES,
|
|
100
|
+
});
|
|
101
|
+
logger.trace('Sending request to data provider...');
|
|
102
|
+
const providerResponse = await (0, util_2.axiosRequest)(request, config);
|
|
103
|
+
logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`); // TODO: Sensitive data?
|
|
104
|
+
const parsedResponse = await this.config.parseResponse(req, providerResponse, config);
|
|
105
|
+
if (config.API_VERBOSE) {
|
|
106
|
+
parsedResponse.data = providerResponse.data;
|
|
107
|
+
}
|
|
108
|
+
if (config.METRICS_ENABLED && config.EXPERIMENTAL_METRICS_ENABLED) {
|
|
109
|
+
// TODO: Potentially create function to add all telemetry data
|
|
110
|
+
parsedResponse.maxAge = Date.now() + config.CACHE_MAX_AGE;
|
|
111
|
+
parsedResponse.meta = {
|
|
112
|
+
metrics: { feedId: req.requestContext.meta?.metrics?.feedId || 'N/A' },
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
logger.debug('Setting provider response in cache');
|
|
116
|
+
await this.cache.set(req.requestContext.cacheKey, parsedResponse, config.CACHE_MAX_AGE);
|
|
117
|
+
// Record cost of data provider call
|
|
118
|
+
const cost = rateLimitMetrics.retrieveCost(providerResponse.data);
|
|
119
|
+
rateLimitMetrics.rateLimitCreditsSpentTotal
|
|
120
|
+
.labels({
|
|
121
|
+
feed_id: req.requestContext.meta?.metrics?.feedId || 'N/A',
|
|
122
|
+
participant_id: req.requestContext.cacheKey,
|
|
123
|
+
})
|
|
124
|
+
.inc(cost);
|
|
125
|
+
// Update cacheHit flag in request meta for metrics use
|
|
126
|
+
req.requestContext.meta = {
|
|
127
|
+
...req.requestContext.meta,
|
|
128
|
+
metrics: { ...req.requestContext.meta?.metrics, cacheHit: false },
|
|
129
|
+
};
|
|
130
|
+
// TODO: move this to a try/catch/finally
|
|
131
|
+
if (this.config.options.coalescing) {
|
|
132
|
+
logger.debug('Set provider response in cache, removing in flight from cache');
|
|
133
|
+
await this.cache.delete(this.inFlightPrefix);
|
|
134
|
+
}
|
|
135
|
+
return parsedResponse;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
exports.RestTransport = RestTransport;
|