@chainlink/external-adapter-framework 0.0.14 → 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 +114 -101
- package/cache/factory.js +3 -0
- package/chainlink-external-adapter-framework-v0.0.6.tgz +0 -0
- package/config/index.js +69 -83
- package/config/provider-limits.js +10 -15
- package/examples/bank-frick/accounts.js +3 -2
- package/examples/bank-frick/index.js +3 -2
- 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/{package/examples/coingecko → examples/coingecko-old}/batch-warming.js +4 -3
- package/examples/{coingecko → coingecko-old}/index.js +3 -2
- package/{package/examples/coingecko → examples/coingecko-old}/rest.js +3 -2
- package/examples/ncfx/index.js +3 -2
- package/examples/ncfx/websocket.js +3 -2
- package/index.js +17 -23
- package/package.json +5 -4
- package/rate-limiting/index.js +23 -2
- package/transports/batch-warming.js +1 -1
- package/transports/rest.js +9 -2
- package/transports/util.js +2 -1
- package/transports/websocket.js +4 -6
- package/util/recordRequests.js +45 -0
- package/{package/validation/override-functions.js → validation/overrideFunctions.js} +0 -0
- package/adapter.d.ts +0 -107
- package/background-executor.d.ts +0 -11
- package/cache/factory.d.ts +0 -6
- package/cache/index.d.ts +0 -94
- package/cache/local.d.ts +0 -23
- package/cache/metrics.d.ts +0 -27
- package/cache/redis.d.ts +0 -16
- package/chainlink-external-adapter-framework-0.0.6.tgz +0 -0
- package/config/index.d.ts +0 -209
- package/config/provider-limits.d.ts +0 -31
- package/examples/bank-frick/accounts.d.ts +0 -39
- package/examples/bank-frick/config/index.d.ts +0 -4
- package/examples/bank-frick/index.d.ts +0 -2
- package/examples/bank-frick/util.d.ts +0 -4
- package/examples/coingecko/batch-warming.d.ts +0 -2
- package/examples/coingecko/batch-warming.js +0 -52
- package/examples/coingecko/index.d.ts +0 -2
- package/examples/coingecko/rest.d.ts +0 -2
- package/examples/coingecko/rest.js +0 -50
- package/examples/ncfx/config/index.d.ts +0 -12
- package/examples/ncfx/index.d.ts +0 -2
- package/examples/ncfx/websocket.d.ts +0 -36
- package/index.d.ts +0 -11
- package/metrics/constants.d.ts +0 -16
- package/metrics/index.d.ts +0 -15
- package/metrics/util.d.ts +0 -7
- package/package/adapter.d.ts +0 -88
- package/package/adapter.js +0 -112
- package/package/background-executor.d.ts +0 -11
- package/package/background-executor.js +0 -45
- package/package/cache/factory.d.ts +0 -6
- package/package/cache/factory.js +0 -57
- package/package/cache/index.d.ts +0 -90
- package/package/cache/index.js +0 -169
- package/package/cache/local.d.ts +0 -23
- package/package/cache/local.js +0 -83
- package/package/cache/metrics.d.ts +0 -27
- package/package/cache/metrics.js +0 -120
- package/package/cache/redis.d.ts +0 -16
- package/package/cache/redis.js +0 -100
- package/package/config/index.d.ts +0 -195
- package/package/config/index.js +0 -365
- package/package/config/provider-limits.d.ts +0 -31
- package/package/config/provider-limits.js +0 -76
- package/package/examples/coingecko/batch-warming.d.ts +0 -2
- package/package/examples/coingecko/index.d.ts +0 -2
- package/package/examples/coingecko/index.js +0 -10
- package/package/examples/coingecko/rest.d.ts +0 -2
- package/package/examples/ncfx/config/index.d.ts +0 -12
- package/package/examples/ncfx/config/index.js +0 -15
- package/package/examples/ncfx/index.d.ts +0 -2
- package/package/examples/ncfx/index.js +0 -10
- package/package/examples/ncfx/websocket.d.ts +0 -36
- package/package/examples/ncfx/websocket.js +0 -72
- package/package/index.d.ts +0 -12
- package/package/index.js +0 -92
- package/package/metrics/constants.d.ts +0 -16
- package/package/metrics/constants.js +0 -25
- package/package/metrics/index.d.ts +0 -15
- package/package/metrics/index.js +0 -123
- package/package/metrics/util.d.ts +0 -3
- package/package/metrics/util.js +0 -9
- package/package/package.json +0 -72
- package/package/rate-limiting/background/fixed-frequency.d.ts +0 -10
- package/package/rate-limiting/background/fixed-frequency.js +0 -37
- package/package/rate-limiting/index.d.ts +0 -54
- package/package/rate-limiting/index.js +0 -63
- package/package/rate-limiting/metrics.d.ts +0 -3
- package/package/rate-limiting/metrics.js +0 -44
- package/package/rate-limiting/request/simple-counting.d.ts +0 -20
- package/package/rate-limiting/request/simple-counting.js +0 -62
- package/package/test.d.ts +0 -1
- package/package/test.js +0 -6
- package/package/transports/batch-warming.d.ts +0 -34
- package/package/transports/batch-warming.js +0 -101
- package/package/transports/index.d.ts +0 -87
- package/package/transports/index.js +0 -87
- package/package/transports/metrics.d.ts +0 -21
- package/package/transports/metrics.js +0 -105
- package/package/transports/rest.d.ts +0 -43
- package/package/transports/rest.js +0 -129
- package/package/transports/util.d.ts +0 -8
- package/package/transports/util.js +0 -85
- package/package/transports/websocket.d.ts +0 -80
- package/package/transports/websocket.js +0 -169
- package/package/util/expiring-sorted-set.d.ts +0 -21
- package/package/util/expiring-sorted-set.js +0 -47
- package/package/util/index.d.ts +0 -11
- package/package/util/index.js +0 -35
- package/package/util/logger.d.ts +0 -42
- package/package/util/logger.js +0 -62
- package/package/util/request.d.ts +0 -55
- package/package/util/request.js +0 -2
- package/package/validation/error.d.ts +0 -50
- package/package/validation/error.js +0 -79
- package/package/validation/index.d.ts +0 -5
- package/package/validation/index.js +0 -86
- package/package/validation/input-params.d.ts +0 -15
- package/package/validation/input-params.js +0 -30
- package/package/validation/override-functions.d.ts +0 -3
- package/package/validation/preset-tokens.json +0 -23
- package/package/validation/validator.d.ts +0 -47
- package/package/validation/validator.js +0 -303
- package/rate-limiting/background/fixed-frequency.d.ts +0 -10
- package/rate-limiting/index.d.ts +0 -54
- package/rate-limiting/metrics.d.ts +0 -3
- package/rate-limiting/request/simple-counting.d.ts +0 -20
- package/test.d.ts +0 -1
- package/transports/batch-warming.d.ts +0 -35
- package/transports/index.d.ts +0 -70
- package/transports/metrics.d.ts +0 -21
- package/transports/rest.d.ts +0 -44
- package/transports/util.d.ts +0 -8
- package/transports/websocket.d.ts +0 -81
- package/util/expiring-sorted-set.d.ts +0 -21
- package/util/expiring-sorted-set.js +0 -47
- package/util/index.d.ts +0 -12
- package/util/logger.d.ts +0 -42
- package/util/request.d.ts +0 -57
- package/util/subscription-set/expiring-sorted-set.d.ts +0 -22
- package/util/subscription-set/subscription-set.d.ts +0 -18
- package/util/test-payload-loader.d.ts +0 -25
- package/validation/error.d.ts +0 -50
- package/validation/index.d.ts +0 -5
- package/validation/input-params.d.ts +0 -15
- package/validation/override-functions.d.ts +0 -3
- package/validation/validator.d.ts +0 -47
package/package/test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/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">;
|
|
@@ -1,105 +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.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.adapterEndpoint, 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.adapterEndpoint, 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
|
-
});
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import { AdapterRequest, AdapterResponse } from '../util/request';
|
|
2
|
-
import { AdapterDependencies, Transport } from './';
|
|
3
|
-
import { Cache } from '../cache';
|
|
4
|
-
import { AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
5
|
-
import { AdapterConfig, SettingsMap } from '../config';
|
|
6
|
-
import { RequestRateLimiter } from '../rate-limiting';
|
|
7
|
-
/**
|
|
8
|
-
* Transport implementation that takes incoming requests, transforms them into a DataProvider request,
|
|
9
|
-
* and executes that request returning the response immediately from the `setup` function.
|
|
10
|
-
* Optionally, setting the `coalescing` option to `true` will make it so once a request is in flight,
|
|
11
|
-
* new adapter requests for the same feed will not trigger a new one, but return an empty promise from
|
|
12
|
-
* the setup instead so the normal cache polling mechanism is used.
|
|
13
|
-
*
|
|
14
|
-
* @typeParam AdapterParams - interface for the adapter request body
|
|
15
|
-
* @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
|
|
16
|
-
* @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
|
|
17
|
-
*/
|
|
18
|
-
export declare class RestTransport<AdapterParams, ProviderRequestBody, ProviderResponseBody, CustomSettings extends SettingsMap> implements Transport<AdapterParams, ProviderResponseBody, CustomSettings> {
|
|
19
|
-
protected config: {
|
|
20
|
-
prepareRequest: (req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>) => AxiosRequestConfig<ProviderRequestBody> | Promise<AxiosRequestConfig<ProviderRequestBody>>;
|
|
21
|
-
parseResponse: (req: AdapterRequest<AdapterParams>, res: AxiosResponse<ProviderResponseBody>, config: AdapterConfig<CustomSettings>) => AdapterResponse<ProviderResponseBody> | Promise<AdapterResponse<ProviderResponseBody>>;
|
|
22
|
-
options: {
|
|
23
|
-
coalescing: boolean;
|
|
24
|
-
};
|
|
25
|
-
};
|
|
26
|
-
inFlightPrefix: string;
|
|
27
|
-
cache: Cache;
|
|
28
|
-
rateLimiter: RequestRateLimiter;
|
|
29
|
-
constructor(config: {
|
|
30
|
-
prepareRequest: (req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>) => AxiosRequestConfig<ProviderRequestBody> | Promise<AxiosRequestConfig<ProviderRequestBody>>;
|
|
31
|
-
parseResponse: (req: AdapterRequest<AdapterParams>, res: AxiosResponse<ProviderResponseBody>, config: AdapterConfig<CustomSettings>) => AdapterResponse<ProviderResponseBody> | Promise<AdapterResponse<ProviderResponseBody>>;
|
|
32
|
-
options: {
|
|
33
|
-
coalescing: boolean;
|
|
34
|
-
};
|
|
35
|
-
});
|
|
36
|
-
initialize(dependencies: AdapterDependencies): Promise<void>;
|
|
37
|
-
hasBeenSetUp(req: AdapterRequest<AdapterParams>): Promise<boolean>;
|
|
38
|
-
protected waitUntilUnderRateLimit(options: {
|
|
39
|
-
maxRetries: number;
|
|
40
|
-
msBetweenRetries: number;
|
|
41
|
-
}, retry?: number): Promise<void>;
|
|
42
|
-
setup(req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>): Promise<AdapterResponse<ProviderResponseBody> | undefined>;
|
|
43
|
-
}
|
|
@@ -1,129 +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.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) {
|
|
49
|
-
this.inFlightPrefix = `${IN_FLIGHT_PREFIX}-`;
|
|
50
|
-
this.cache = dependencies.cache;
|
|
51
|
-
this.rateLimiter = dependencies.requestRateLimiter;
|
|
52
|
-
}
|
|
53
|
-
async hasBeenSetUp(req) {
|
|
54
|
-
if (!this.config.options.coalescing) {
|
|
55
|
-
return false;
|
|
56
|
-
}
|
|
57
|
-
// Check if request is in flight
|
|
58
|
-
const inFlight = await this.cache.get(this.inFlightPrefix + req.requestContext.cacheKey);
|
|
59
|
-
if (inFlight) {
|
|
60
|
-
logger.debug('Request is in flight, transport has been set up');
|
|
61
|
-
return true;
|
|
62
|
-
}
|
|
63
|
-
else {
|
|
64
|
-
logger.debug('Request not in flight, transport not set up');
|
|
65
|
-
return false;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
async waitUntilUnderRateLimit(options, retry = 0) {
|
|
69
|
-
if (this.rateLimiter.isUnderLimits()) {
|
|
70
|
-
logger.trace('Incoming request would not be under limits, moving on');
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
if (retry >= options.maxRetries) {
|
|
74
|
-
throw new error_1.AdapterError({
|
|
75
|
-
statusCode: 504,
|
|
76
|
-
message: `REST Transport timed out while waiting for rate limit availability (max retries: ${options.maxRetries})`,
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
logger.debug(`Request would be over rate limits, sleeping for ${options.msBetweenRetries}`);
|
|
80
|
-
await (0, util_1.sleep)(options.msBetweenRetries);
|
|
81
|
-
await this.waitUntilUnderRateLimit(options, retry + 1);
|
|
82
|
-
}
|
|
83
|
-
async setup(req, config) {
|
|
84
|
-
if (this.config.options.coalescing) {
|
|
85
|
-
logger.debug('Setting up rest transport, setting request in flight in cache');
|
|
86
|
-
// TODO: Should this use a separate cache?
|
|
87
|
-
// TODO: Set viable ttl to approximate timeout from API
|
|
88
|
-
// TODO: Make this ttl configurable
|
|
89
|
-
await this.cache.set(this.inFlightPrefix + req.requestContext.cacheKey, true, 2000); // Can't use Infinity for things like Redis
|
|
90
|
-
}
|
|
91
|
-
const request = await this.config.prepareRequest(req, config);
|
|
92
|
-
logger.trace('Check if we are under rate limits to perform request');
|
|
93
|
-
await this.waitUntilUnderRateLimit({
|
|
94
|
-
maxRetries: config.REST_TRANSPORT_MAX_RATE_LIMIT_RETRIES,
|
|
95
|
-
msBetweenRetries: config.REST_TRANSPORT_MS_BETWEEN_RATE_LIMIT_RETRIES,
|
|
96
|
-
});
|
|
97
|
-
logger.trace('Sending request to data provider...');
|
|
98
|
-
const providerResponse = await (0, util_2.axiosRequest)(request);
|
|
99
|
-
logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`); // TODO: Sensitive data?
|
|
100
|
-
const parsedResponse = await this.config.parseResponse(req, providerResponse, config);
|
|
101
|
-
if (config.METRICS_ENABLED && config.EXPERIMENTAL_METRICS_ENABLED) {
|
|
102
|
-
// TODO: Potentially create function to add all telemetry data
|
|
103
|
-
parsedResponse.maxAge = Date.now() + config.CACHE_MAX_AGE;
|
|
104
|
-
parsedResponse.meta = { metrics: { feedId: req.requestContext.meta?.metrics?.feedId || 'N/A' } };
|
|
105
|
-
}
|
|
106
|
-
logger.debug('Setting provider response in cache');
|
|
107
|
-
await this.cache.set(req.requestContext.cacheKey, parsedResponse, config.CACHE_MAX_AGE);
|
|
108
|
-
// Record cost of data provider call
|
|
109
|
-
const cost = rateLimitMetrics.retrieveCost(providerResponse.data);
|
|
110
|
-
rateLimitMetrics.rateLimitCreditsSpentTotal
|
|
111
|
-
.labels({
|
|
112
|
-
feed_id: req.requestContext.meta?.metrics?.feedId || 'N/A',
|
|
113
|
-
participant_id: req.requestContext.cacheKey,
|
|
114
|
-
})
|
|
115
|
-
.inc(cost);
|
|
116
|
-
// Update cacheHit flag in request meta for metrics use
|
|
117
|
-
req.requestContext.meta = {
|
|
118
|
-
...req.requestContext.meta,
|
|
119
|
-
metrics: { ...req.requestContext.meta?.metrics, cacheHit: false },
|
|
120
|
-
};
|
|
121
|
-
// TODO: move this to a try/catch/finally
|
|
122
|
-
if (this.config.options.coalescing) {
|
|
123
|
-
logger.debug('Set provider response in cache, removing in flight from cache');
|
|
124
|
-
await this.cache.delete(this.inFlightPrefix);
|
|
125
|
-
}
|
|
126
|
-
return parsedResponse;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
exports.RestTransport = RestTransport;
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
2
|
-
/**
|
|
3
|
-
* Performs axios request along with metrics recording and error handling
|
|
4
|
-
*
|
|
5
|
-
* @param request - axios request config
|
|
6
|
-
* @returns axios response for the request
|
|
7
|
-
*/
|
|
8
|
-
export declare function axiosRequest<ProviderRequestBody, ProviderResponseBody>(request: AxiosRequestConfig<ProviderRequestBody>): Promise<AxiosResponse<ProviderResponseBody>>;
|