@chainlink/external-adapter-framework 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/adapter/basic.d.ts +90 -0
- package/adapter/basic.js +325 -0
- package/adapter/basic.js.map +1 -0
- package/adapter/endpoint.d.ts +17 -0
- package/adapter/endpoint.js +20 -0
- package/adapter/endpoint.js.map +1 -0
- package/adapter/index.d.ts +4 -0
- package/adapter/index.js +21 -0
- package/adapter/index.js.map +1 -0
- package/adapter/price.d.ts +77 -0
- package/adapter/price.js +88 -0
- package/adapter/price.js.map +1 -0
- package/adapter/types.d.ts +124 -0
- package/adapter/types.js +3 -0
- package/adapter/types.js.map +1 -0
- package/background-executor.d.ts +9 -0
- package/background-executor.js +97 -0
- package/background-executor.js.map +1 -0
- package/cache/factory.d.ts +6 -0
- package/cache/factory.js +24 -0
- package/cache/factory.js.map +1 -0
- package/cache/index.d.ts +87 -0
- package/cache/index.js +133 -0
- package/cache/index.js.map +1 -0
- package/cache/local.d.ts +23 -0
- package/cache/local.js +84 -0
- package/cache/local.js.map +1 -0
- package/cache/metrics.d.ts +27 -0
- package/cache/metrics.js +121 -0
- package/cache/metrics.js.map +1 -0
- package/cache/redis.d.ts +16 -0
- package/cache/redis.js +101 -0
- package/cache/redis.js.map +1 -0
- package/config/index.d.ts +298 -0
- package/config/index.js +359 -0
- package/config/index.js.map +1 -0
- package/config/provider-limits.d.ts +27 -0
- package/config/provider-limits.js +75 -0
- package/config/provider-limits.js.map +1 -0
- package/examples/bank-frick/accounts.d.ts +45 -0
- package/examples/bank-frick/accounts.js +203 -0
- package/examples/bank-frick/accounts.js.map +1 -0
- package/examples/bank-frick/config/index.d.ts +17 -0
- package/examples/bank-frick/config/index.js +55 -0
- package/examples/bank-frick/config/index.js.map +1 -0
- package/examples/bank-frick/index.d.ts +2 -0
- package/examples/bank-frick/index.js +16 -0
- package/examples/bank-frick/index.js.map +1 -0
- package/examples/bank-frick/util.d.ts +4 -0
- package/examples/bank-frick/util.js +40 -0
- package/examples/bank-frick/util.js.map +1 -0
- package/examples/coingecko/src/config/index.d.ts +2 -0
- package/examples/coingecko/src/config/index.js +6 -0
- package/examples/coingecko/src/config/index.js.map +1 -0
- package/examples/coingecko/src/config/overrides.json +10825 -0
- package/examples/coingecko/src/crypto-utils.d.ts +62 -0
- package/examples/coingecko/src/crypto-utils.js +60 -0
- package/examples/coingecko/src/crypto-utils.js.map +1 -0
- package/examples/coingecko/src/endpoint/coins.d.ts +26 -0
- package/examples/coingecko/src/endpoint/coins.js +37 -0
- package/examples/coingecko/src/endpoint/coins.js.map +1 -0
- package/examples/coingecko/src/endpoint/crypto-marketcap.d.ts +3 -0
- package/examples/coingecko/src/endpoint/crypto-marketcap.js +30 -0
- package/examples/coingecko/src/endpoint/crypto-marketcap.js.map +1 -0
- package/examples/coingecko/src/endpoint/crypto-volume.d.ts +3 -0
- package/examples/coingecko/src/endpoint/crypto-volume.js +30 -0
- package/examples/coingecko/src/endpoint/crypto-volume.js.map +1 -0
- package/examples/coingecko/src/endpoint/crypto.d.ts +3 -0
- package/examples/coingecko/src/endpoint/crypto.js +28 -0
- package/examples/coingecko/src/endpoint/crypto.js.map +1 -0
- package/examples/coingecko/src/endpoint/dominance.d.ts +3 -0
- package/examples/coingecko/src/endpoint/dominance.js +28 -0
- package/examples/coingecko/src/endpoint/dominance.js.map +1 -0
- package/examples/coingecko/src/endpoint/global-marketcap.d.ts +3 -0
- package/examples/coingecko/src/endpoint/global-marketcap.js +28 -0
- package/examples/coingecko/src/endpoint/global-marketcap.js.map +1 -0
- package/examples/coingecko/src/endpoint/index.d.ts +6 -0
- package/examples/coingecko/src/endpoint/index.js +16 -0
- package/examples/coingecko/src/endpoint/index.js.map +1 -0
- package/examples/coingecko/src/global-utils.d.ts +42 -0
- package/examples/coingecko/src/global-utils.js +47 -0
- package/examples/coingecko/src/global-utils.js.map +1 -0
- package/examples/coingecko/src/index.d.ts +4 -0
- package/examples/coingecko/src/index.js +19 -0
- package/examples/coingecko/src/index.js.map +1 -0
- package/examples/coingecko-old/batch-warming.d.ts +7 -0
- package/examples/coingecko-old/batch-warming.js +54 -0
- package/examples/coingecko-old/batch-warming.js.map +1 -0
- package/examples/coingecko-old/index.d.ts +2 -0
- package/examples/coingecko-old/index.js +12 -0
- package/examples/coingecko-old/index.js.map +1 -0
- package/examples/coingecko-old/rest.d.ts +12 -0
- package/examples/coingecko-old/rest.js +55 -0
- package/examples/coingecko-old/rest.js.map +1 -0
- package/examples/cryptocompare/src/config/index.d.ts +2 -0
- package/examples/cryptocompare/src/config/index.js +6 -0
- package/examples/cryptocompare/src/config/index.js.map +1 -0
- package/examples/cryptocompare/src/endpoints/crypto.d.ts +40 -0
- package/examples/cryptocompare/src/endpoints/crypto.js +54 -0
- package/examples/cryptocompare/src/endpoints/crypto.js.map +1 -0
- package/examples/cryptocompare/src/endpoints/index.d.ts +1 -0
- package/examples/cryptocompare/src/endpoints/index.js +6 -0
- package/examples/cryptocompare/src/endpoints/index.js.map +1 -0
- package/examples/cryptocompare/src/index.d.ts +4 -0
- package/examples/cryptocompare/src/index.js +14 -0
- package/examples/cryptocompare/src/index.js.map +1 -0
- package/examples/genesis/config/index.d.ts +7 -0
- package/examples/genesis/config/index.js +11 -0
- package/examples/genesis/config/index.js.map +1 -0
- package/examples/genesis/index.d.ts +2 -0
- package/examples/genesis/index.js +13 -0
- package/examples/genesis/index.js.map +1 -0
- package/examples/genesis/sseStream.d.ts +27 -0
- package/examples/genesis/sseStream.js +149 -0
- package/examples/genesis/sseStream.js.map +1 -0
- package/examples/ncfx/config/index.d.ts +12 -0
- package/examples/ncfx/config/index.js +16 -0
- package/examples/ncfx/config/index.js.map +1 -0
- package/examples/ncfx/index.d.ts +2 -0
- package/examples/ncfx/index.js +12 -0
- package/examples/ncfx/index.js.map +1 -0
- package/examples/ncfx/websocket.d.ts +37 -0
- package/examples/ncfx/websocket.js +74 -0
- package/examples/ncfx/websocket.js.map +1 -0
- package/index.d.ts +17 -0
- package/index.js +174 -0
- package/index.js.map +1 -0
- package/metrics/constants.d.ts +16 -0
- package/metrics/constants.js +26 -0
- package/metrics/constants.js.map +1 -0
- package/metrics/index.d.ts +19 -0
- package/metrics/index.js +139 -0
- package/metrics/index.js.map +1 -0
- package/metrics/util.d.ts +7 -0
- package/metrics/util.js +10 -0
- package/metrics/util.js.map +1 -0
- package/package.json +50 -42
- package/rate-limiting/background/fixed-frequency.d.ts +10 -0
- package/rate-limiting/background/fixed-frequency.js +36 -0
- package/rate-limiting/background/fixed-frequency.js.map +1 -0
- package/rate-limiting/index.d.ts +56 -0
- package/rate-limiting/index.js +86 -0
- package/rate-limiting/index.js.map +1 -0
- package/rate-limiting/metrics.d.ts +3 -0
- package/rate-limiting/metrics.js +45 -0
- package/rate-limiting/metrics.js.map +1 -0
- package/rate-limiting/request/simple-counting.d.ts +20 -0
- package/rate-limiting/request/simple-counting.js +63 -0
- package/rate-limiting/request/simple-counting.js.map +1 -0
- package/transports/batch-warming.d.ts +53 -0
- package/transports/batch-warming.js +136 -0
- package/transports/batch-warming.js.map +1 -0
- package/transports/index.d.ts +108 -0
- package/transports/index.js +56 -0
- package/transports/index.js.map +1 -0
- package/transports/inference-test.d.ts +0 -0
- package/transports/inference-test.js +202 -0
- package/transports/inference-test.js.map +1 -0
- package/transports/metrics.d.ts +25 -0
- package/transports/metrics.js +122 -0
- package/transports/metrics.js.map +1 -0
- package/transports/rest.d.ts +68 -0
- package/transports/rest.js +131 -0
- package/transports/rest.js.map +1 -0
- package/transports/routing.d.ts +21 -0
- package/transports/routing.js +50 -0
- package/transports/routing.js.map +1 -0
- package/transports/sse.d.ts +61 -0
- package/transports/sse.js +97 -0
- package/transports/sse.js.map +1 -0
- package/transports/util.d.ts +9 -0
- package/transports/util.js +87 -0
- package/transports/util.js.map +1 -0
- package/transports/websocket.d.ts +95 -0
- package/transports/websocket.js +164 -0
- package/transports/websocket.js.map +1 -0
- package/util/censor/censor-list.d.ts +9 -0
- package/util/censor/censor-list.js +13 -0
- package/util/censor/censor-list.js.map +1 -0
- package/util/index.d.ts +13 -0
- package/util/index.js +38 -0
- package/util/index.js.map +1 -0
- package/util/logger.d.ts +49 -0
- package/util/logger.js +123 -0
- package/util/logger.js.map +1 -0
- package/util/request.d.ts +138 -0
- package/util/request.js +3 -0
- package/util/request.js.map +1 -0
- package/util/subscription-set/expiring-sorted-set.d.ts +21 -0
- package/util/subscription-set/expiring-sorted-set.js +36 -0
- package/util/subscription-set/expiring-sorted-set.js.map +1 -0
- package/util/subscription-set/redis-sorted-set.d.ts +9 -0
- package/util/subscription-set/redis-sorted-set.js +29 -0
- package/util/subscription-set/redis-sorted-set.js.map +1 -0
- package/util/subscription-set/subscription-set.d.ts +19 -0
- package/util/subscription-set/subscription-set.js +28 -0
- package/util/subscription-set/subscription-set.js.map +1 -0
- package/util/test-payload-loader.d.ts +26 -0
- package/util/test-payload-loader.js +85 -0
- package/util/test-payload-loader.js.map +1 -0
- package/validation/error.d.ts +48 -0
- package/validation/error.js +78 -0
- package/validation/error.js.map +1 -0
- package/validation/index.d.ts +5 -0
- package/validation/index.js +102 -0
- package/validation/index.js.map +1 -0
- package/validation/input-params.d.ts +14 -0
- package/validation/input-params.js +3 -0
- package/validation/input-params.js.map +1 -0
- package/validation/input-validator.d.ts +16 -0
- package/validation/input-validator.js +123 -0
- package/validation/input-validator.js.map +1 -0
- package/README.md +0 -102
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { AdapterEndpoint, EndpointGenerics } from '../adapter';
|
|
2
|
+
import { AdapterConfig } from '../config';
|
|
3
|
+
export * from './background/fixed-frequency';
|
|
4
|
+
export * from './request/simple-counting';
|
|
5
|
+
export interface AdapterRateLimitTier {
|
|
6
|
+
rateLimit1s?: number;
|
|
7
|
+
rateLimit1m?: number;
|
|
8
|
+
rateLimit1h?: number;
|
|
9
|
+
note?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Common interface for all RateLimiter classes to implement
|
|
13
|
+
*/
|
|
14
|
+
export interface RateLimiter {
|
|
15
|
+
/**
|
|
16
|
+
* Method to ensure all RateLimiters can be initialized in the same manner.
|
|
17
|
+
*
|
|
18
|
+
* @param limits - settings for how much throughput to allow for the Adapter
|
|
19
|
+
* @param endpoints - list of adapter endpoints
|
|
20
|
+
*/
|
|
21
|
+
initialize<T extends EndpointGenerics>(endpoints: AdapterEndpoint<T>[], limits: AdapterRateLimitTier): this;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* RequestRateLimiters perform checks agains imminent outbound requests for any transport.
|
|
25
|
+
*/
|
|
26
|
+
export interface RequestRateLimiter extends RateLimiter {
|
|
27
|
+
/**
|
|
28
|
+
* This method will check using whatever strategy is implemented to determine if
|
|
29
|
+
* this request can be processed. If so, it returns true; if not, returns false.
|
|
30
|
+
*/
|
|
31
|
+
isUnderLimits(): boolean;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* BackgroundExecuteFrequencyRateLimiters will implement custom logic to calculate
|
|
35
|
+
* the period of time to wait between background executions for a transport.
|
|
36
|
+
*/
|
|
37
|
+
export interface BackgroundExecuteRateLimiter extends RateLimiter {
|
|
38
|
+
msUntilNextExecution(endpointName: string): number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* This method will convert all possible settings for a rate limit tier and
|
|
42
|
+
* convert them all to requests per second, returning the lowest one
|
|
43
|
+
*
|
|
44
|
+
* @param limits - the rate limit tier set for the adapter
|
|
45
|
+
* @returns the most restrictive of the set options, in requests per second
|
|
46
|
+
*/
|
|
47
|
+
export declare const consolidateTierLimits: (limits?: AdapterRateLimitTier) => number;
|
|
48
|
+
/**
|
|
49
|
+
* Validates rate limiting tiers specified for the adapter, and returns the one to use.
|
|
50
|
+
*
|
|
51
|
+
* @param config - the adapter config containing the env vars
|
|
52
|
+
* @param tiers - the adapter config listing the different available API tiers
|
|
53
|
+
* @returns the specified API tier, or a default one if none are specified
|
|
54
|
+
*/
|
|
55
|
+
export declare const getRateLimitingTier: (config: AdapterConfig, tiers?: Record<string, AdapterRateLimitTier>) => AdapterRateLimitTier | undefined;
|
|
56
|
+
export declare const buildRateLimitTiersFromConfig: (config: AdapterConfig) => AdapterRateLimitTier | undefined;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.buildRateLimitTiersFromConfig = exports.getRateLimitingTier = exports.consolidateTierLimits = void 0;
|
|
18
|
+
__exportStar(require("./background/fixed-frequency"), exports);
|
|
19
|
+
__exportStar(require("./request/simple-counting"), exports);
|
|
20
|
+
/**
|
|
21
|
+
* This method will convert all possible settings for a rate limit tier and
|
|
22
|
+
* convert them all to requests per second, returning the lowest one
|
|
23
|
+
*
|
|
24
|
+
* @param limits - the rate limit tier set for the adapter
|
|
25
|
+
* @returns the most restrictive of the set options, in requests per second
|
|
26
|
+
*/
|
|
27
|
+
const consolidateTierLimits = (limits) => {
|
|
28
|
+
const perHourLimit = (limits?.rateLimit1h || Infinity) / (60 * 60);
|
|
29
|
+
const perMinuteLimit = (limits?.rateLimit1m || Infinity) / 60;
|
|
30
|
+
const perSecondLimit = limits?.rateLimit1s || Infinity;
|
|
31
|
+
return Math.min(perHourLimit, perMinuteLimit, perSecondLimit);
|
|
32
|
+
};
|
|
33
|
+
exports.consolidateTierLimits = consolidateTierLimits;
|
|
34
|
+
/**
|
|
35
|
+
* Validates rate limiting tiers specified for the adapter, and returns the one to use.
|
|
36
|
+
*
|
|
37
|
+
* @param config - the adapter config containing the env vars
|
|
38
|
+
* @param tiers - the adapter config listing the different available API tiers
|
|
39
|
+
* @returns the specified API tier, or a default one if none are specified
|
|
40
|
+
*/
|
|
41
|
+
const getRateLimitingTier = (config, tiers) => {
|
|
42
|
+
if (config.RATE_LIMIT_CAPACITY ||
|
|
43
|
+
config.RATE_LIMIT_CAPACITY_MINUTE ||
|
|
44
|
+
config.RATE_LIMIT_CAPACITY_SECOND) {
|
|
45
|
+
return (0, exports.buildRateLimitTiersFromConfig)(config);
|
|
46
|
+
}
|
|
47
|
+
if (!tiers) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
// Check that if the tiers object is defined, it has values
|
|
51
|
+
if (Object.values(tiers).length === 0) {
|
|
52
|
+
throw new Error(`The tiers object is defined, but has no entries`);
|
|
53
|
+
}
|
|
54
|
+
// Check that the tier set in the AdapterConfig is a valid one
|
|
55
|
+
const selectedTier = config.RATE_LIMIT_API_TIER;
|
|
56
|
+
if (selectedTier && !tiers[selectedTier]) {
|
|
57
|
+
const validTiersString = Object.keys(tiers)
|
|
58
|
+
.map((t) => `"${t}"`)
|
|
59
|
+
.join(', ');
|
|
60
|
+
throw new Error(`The selected rate limit tier "${selectedTier}" is not valid (can be one of ${validTiersString})`);
|
|
61
|
+
}
|
|
62
|
+
if (!selectedTier) {
|
|
63
|
+
// Sort the tiers by most to least restrictive
|
|
64
|
+
const sortedTiers = Object.values(tiers).sort((t1, t2) => (0, exports.consolidateTierLimits)(t1) - (0, exports.consolidateTierLimits)(t2));
|
|
65
|
+
return sortedTiers[0];
|
|
66
|
+
}
|
|
67
|
+
return tiers[selectedTier];
|
|
68
|
+
};
|
|
69
|
+
exports.getRateLimitingTier = getRateLimitingTier;
|
|
70
|
+
// Creates adapter rate limit tier using the configs specified in env vars
|
|
71
|
+
const buildRateLimitTiersFromConfig = (config) => {
|
|
72
|
+
const rateLimit1s = config.RATE_LIMIT_CAPACITY_SECOND;
|
|
73
|
+
let rateLimit1m;
|
|
74
|
+
if (config.RATE_LIMIT_CAPACITY_MINUTE) {
|
|
75
|
+
rateLimit1m = config.RATE_LIMIT_CAPACITY_MINUTE;
|
|
76
|
+
}
|
|
77
|
+
else if (config.RATE_LIMIT_CAPACITY) {
|
|
78
|
+
rateLimit1m = config.RATE_LIMIT_CAPACITY;
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
rateLimit1s,
|
|
82
|
+
rateLimit1m,
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
exports.buildRateLimitTiersFromConfig = buildRateLimitTiersFromConfig;
|
|
86
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/rate-limiting/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAGA,+DAA4C;AAC5C,4DAAyC;AA4CzC;;;;;;GAMG;AACI,MAAM,qBAAqB,GAAG,CAAC,MAA6B,EAAE,EAAE;IACrE,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,WAAW,IAAI,QAAQ,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,CAAA;IAClE,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,WAAW,IAAI,QAAQ,CAAC,GAAG,EAAE,CAAA;IAC7D,MAAM,cAAc,GAAG,MAAM,EAAE,WAAW,IAAI,QAAQ,CAAA;IACtD,OAAO,IAAI,CAAC,GAAG,CAAC,YAAY,EAAE,cAAc,EAAE,cAAc,CAAC,CAAA;AAC/D,CAAC,CAA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AACnE,MAAM,6BAA6B,GAAG,CAC3C,MAAqB,EACa,EAAE;IACpC,MAAM,WAAW,GAAG,MAAM,CAAC,0BAA0B,CAAA;IACrD,IAAI,WAAW,CAAA;IACf,IAAI,MAAM,CAAC,0BAA0B,EAAE;QACrC,WAAW,GAAG,MAAM,CAAC,0BAA0B,CAAA;KAChD;SAAM,IAAI,MAAM,CAAC,mBAAmB,EAAE;QACrC,WAAW,GAAG,MAAM,CAAC,mBAAmB,CAAA;KACzC;IACD,OAAO;QACL,WAAW;QACX,WAAW;KACZ,CAAA;AACH,CAAC,CAAA;AAdY,QAAA,6BAA6B,iCAczC"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.rateLimitCreditsSpentTotal = exports.retrieveCost = void 0;
|
|
27
|
+
const client = __importStar(require("prom-client"));
|
|
28
|
+
// Retrieve cost field from response if exists
|
|
29
|
+
// If not return default cost of 1
|
|
30
|
+
const retrieveCost = (data) => {
|
|
31
|
+
const cost = data['cost'];
|
|
32
|
+
if (typeof cost === 'number' || typeof cost === 'string') {
|
|
33
|
+
return Number(cost);
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
return 1;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
exports.retrieveCost = retrieveCost;
|
|
40
|
+
exports.rateLimitCreditsSpentTotal = new client.Counter({
|
|
41
|
+
name: 'rate_limit_credits_spent_total',
|
|
42
|
+
help: 'The number of data provider credits the adapter is consuming',
|
|
43
|
+
labelNames: ['participant_id', 'feed_id'],
|
|
44
|
+
});
|
|
45
|
+
//# sourceMappingURL=metrics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../../src/rate-limiting/metrics.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AAErC,8CAA8C;AAC9C,kCAAkC;AAC3B,MAAM,YAAY,GAAG,CAAuB,IAA0B,EAAU,EAAE;IACvF,MAAM,IAAI,GAAI,IAAgC,CAAC,MAAM,CAAC,CAAA;IACtD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACxD,OAAO,MAAM,CAAC,IAAI,CAAC,CAAA;KACpB;SAAM;QACL,OAAO,CAAC,CAAA;KACT;AACH,CAAC,CAAA;AAPY,QAAA,YAAY,gBAOxB;AAEY,QAAA,0BAA0B,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC;IAC3D,IAAI,EAAE,gCAAgC;IACtC,IAAI,EAAE,8DAA8D;IACpE,UAAU,EAAE,CAAC,gBAAgB,EAAE,SAAS,CAAU;CACnD,CAAC,CAAA"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { AdapterRateLimitTier, RateLimiter } from '..';
|
|
2
|
+
import { AdapterEndpoint, EndpointGenerics } from '../../adapter';
|
|
3
|
+
/**
|
|
4
|
+
* This rate limiter is the simplest stateful option.
|
|
5
|
+
* On startup, it'll compare the different thresholds for each tier, calculate them all
|
|
6
|
+
* in the finest window we'll use (seconds), and use the most restrictive one.
|
|
7
|
+
* This is so if the EA were to restart, we don't need to worry about persisting state
|
|
8
|
+
* for things like daily quotas. The downside is that this does not work well for bursty
|
|
9
|
+
* loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
|
|
10
|
+
*/
|
|
11
|
+
export declare class SimpleCountingRateLimiter implements RateLimiter {
|
|
12
|
+
latestSecondInterval: number;
|
|
13
|
+
requestsThisSecond: number;
|
|
14
|
+
latestMinuteInterval: number;
|
|
15
|
+
requestsThisMinute: number;
|
|
16
|
+
perSecondLimit: number;
|
|
17
|
+
perMinuteLimit: number;
|
|
18
|
+
initialize<T extends EndpointGenerics>(endpoints: AdapterEndpoint<T>[], limits?: AdapterRateLimitTier): this;
|
|
19
|
+
isUnderLimits(): boolean;
|
|
20
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SimpleCountingRateLimiter = void 0;
|
|
4
|
+
const util_1 = require("../../util");
|
|
5
|
+
const logger = (0, util_1.makeLogger)('SimpleCountingRateLimiter');
|
|
6
|
+
/**
|
|
7
|
+
* This rate limiter is the simplest stateful option.
|
|
8
|
+
* On startup, it'll compare the different thresholds for each tier, calculate them all
|
|
9
|
+
* in the finest window we'll use (seconds), and use the most restrictive one.
|
|
10
|
+
* This is so if the EA were to restart, we don't need to worry about persisting state
|
|
11
|
+
* for things like daily quotas. The downside is that this does not work well for bursty
|
|
12
|
+
* loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
|
|
13
|
+
*/
|
|
14
|
+
class SimpleCountingRateLimiter {
|
|
15
|
+
constructor() {
|
|
16
|
+
this.latestSecondInterval = 0;
|
|
17
|
+
this.requestsThisSecond = 0;
|
|
18
|
+
this.latestMinuteInterval = 0;
|
|
19
|
+
this.requestsThisMinute = 0;
|
|
20
|
+
}
|
|
21
|
+
initialize(endpoints, limits) {
|
|
22
|
+
// Translate the hourly limit into reqs per minute
|
|
23
|
+
const perHourLimit = (limits?.rateLimit1h || Infinity) / 60;
|
|
24
|
+
this.perMinuteLimit = Math.min(limits?.rateLimit1m || Infinity, perHourLimit);
|
|
25
|
+
this.perSecondLimit = limits?.rateLimit1s || Infinity;
|
|
26
|
+
logger.debug(`Using rate limiting settings: perMinute = ${this.perMinuteLimit} | perSecond: = ${this.perSecondLimit}`);
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
isUnderLimits() {
|
|
30
|
+
// If the limit is set to infinity, there was no tier limit specified
|
|
31
|
+
if (this.perSecondLimit === Infinity && this.perMinuteLimit === Infinity) {
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const nearestSecondInterval = Math.floor(now / 1000);
|
|
36
|
+
const nearestMinuteInterval = Math.floor(now / (1000 * 60));
|
|
37
|
+
// This should always run to completion, even if it doesn't look atomic; therefore the
|
|
38
|
+
// Ops should be "thread safe". Thank JS and its infinite single threaded dumbness.
|
|
39
|
+
if (nearestSecondInterval !== this.latestSecondInterval) {
|
|
40
|
+
logger.trace(`Clearing latest second interval, # of requests logged was: ${this.requestsThisSecond} `);
|
|
41
|
+
this.latestSecondInterval = nearestSecondInterval;
|
|
42
|
+
this.requestsThisSecond = 0;
|
|
43
|
+
}
|
|
44
|
+
if (nearestMinuteInterval !== this.latestMinuteInterval) {
|
|
45
|
+
logger.trace(`Clearing latest second minute, # of requests logged was: ${this.requestsThisMinute} `);
|
|
46
|
+
this.latestMinuteInterval = nearestMinuteInterval;
|
|
47
|
+
this.requestsThisMinute = 0;
|
|
48
|
+
}
|
|
49
|
+
if (this.requestsThisSecond < this.perSecondLimit &&
|
|
50
|
+
this.requestsThisMinute < this.perMinuteLimit) {
|
|
51
|
+
logger.trace('Request under limits, counting +1');
|
|
52
|
+
this.requestsThisSecond++;
|
|
53
|
+
this.requestsThisMinute++;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
logger.trace('Requests seen this interval are above limits');
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
exports.SimpleCountingRateLimiter = SimpleCountingRateLimiter;
|
|
63
|
+
//# sourceMappingURL=simple-counting.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"simple-counting.js","sourceRoot":"","sources":["../../../../src/rate-limiting/request/simple-counting.ts"],"names":[],"mappings":";;;AAEA,qCAAuC;AAEvC,MAAM,MAAM,GAAG,IAAA,iBAAU,EAAC,2BAA2B,CAAC,CAAA;AAEtD;;;;;;;GAOG;AACH,MAAa,yBAAyB;IAAtC;QACE,yBAAoB,GAAG,CAAC,CAAA;QACxB,uBAAkB,GAAG,CAAC,CAAA;QACtB,yBAAoB,GAAG,CAAC,CAAA;QACxB,uBAAkB,GAAG,CAAC,CAAA;IA4DxB,CAAC;IAxDC,UAAU,CACR,SAA+B,EAC/B,MAA6B;QAE7B,kDAAkD;QAClD,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,WAAW,IAAI,QAAQ,CAAC,GAAG,EAAE,CAAA;QAC3D,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,WAAW,IAAI,QAAQ,EAAE,YAAY,CAAC,CAAA;QAC7E,IAAI,CAAC,cAAc,GAAG,MAAM,EAAE,WAAW,IAAI,QAAQ,CAAA;QACrD,MAAM,CAAC,KAAK,CACV,6CAA6C,IAAI,CA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M,CAAC,KAAK,CAAC,8CAA8C,CAAC,CAAA;YAC5D,OAAO,KAAK,CAAA;SACb;IACH,CAAC;CACF;AAhED,8DAgEC"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
2
|
+
import { Cache } from '../cache';
|
|
3
|
+
import { AdapterConfig } from '../config';
|
|
4
|
+
import { BackgroundExecuteRateLimiter } from '../rate-limiting';
|
|
5
|
+
import { SubscriptionSet } from '../util';
|
|
6
|
+
import { AdapterRequest, AdapterResponse, ProviderResult } from '../util/request';
|
|
7
|
+
import { Transport, TransportGenerics } from './';
|
|
8
|
+
import { AdapterContext, AdapterDependencies } from '../adapter';
|
|
9
|
+
/**
|
|
10
|
+
* Helper struct type that will be used to pass types to the generic parameters of a Transport.
|
|
11
|
+
* Extends the common TransportGenerics, adding Provider specific types for this Batch endpoint.
|
|
12
|
+
*/
|
|
13
|
+
declare type BatchWarmingTransportGenerics = TransportGenerics & {
|
|
14
|
+
/**
|
|
15
|
+
* Type details for any provider specific interfaces.
|
|
16
|
+
*/
|
|
17
|
+
Provider: {
|
|
18
|
+
/**
|
|
19
|
+
* Structure of the body of the request that will be sent to the data provider.
|
|
20
|
+
*/
|
|
21
|
+
RequestBody: unknown;
|
|
22
|
+
/**
|
|
23
|
+
* Structure for the body of the response coming from the data provider.
|
|
24
|
+
*/
|
|
25
|
+
ResponseBody: unknown;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Transport implementation that takes incoming batches requests and keeps a warm cache of values.
|
|
30
|
+
* Within the setup function, adapter params are added to an set that also keeps track and expires values.
|
|
31
|
+
* In the background execute, the list of non-expired items in the set is fetched.
|
|
32
|
+
* Then, the list is passed through the `prepareRequest` function, that returns an AxiosRequestConfig.
|
|
33
|
+
* The Data Provider response is, they are passed through the `parseResponse` function to create a [[CacheEntry]] list.
|
|
34
|
+
* Finally, the items in that [[CacheEntry]] list are set in the Cache so the Adapter can fetch values from there.
|
|
35
|
+
*
|
|
36
|
+
* @typeParam T - all types related to the [[Transport]]
|
|
37
|
+
*/
|
|
38
|
+
export declare class BatchWarmingTransport<T extends BatchWarmingTransportGenerics> implements Transport<T> {
|
|
39
|
+
private config;
|
|
40
|
+
cache: Cache<AdapterResponse<T['Response']>>;
|
|
41
|
+
rateLimiter: BackgroundExecuteRateLimiter;
|
|
42
|
+
subscriptionSet: SubscriptionSet<T['Request']['Params']>;
|
|
43
|
+
WARMER_ACTIVE: boolean;
|
|
44
|
+
constructor(config: {
|
|
45
|
+
prepareRequest: (params: T['Request']['Params'][], config: AdapterConfig<T['CustomSettings']>) => AxiosRequestConfig<T['Provider']['RequestBody']>;
|
|
46
|
+
parseResponse: (params: T['Request']['Params'][], res: AxiosResponse<T['Provider']['ResponseBody']>, config: AdapterConfig<T['CustomSettings']>) => ProviderResult<T>[];
|
|
47
|
+
});
|
|
48
|
+
initialize(dependencies: AdapterDependencies, _: AdapterConfig<T['CustomSettings']>, endpointName: string): Promise<void>;
|
|
49
|
+
registerRequest(req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>): Promise<void>;
|
|
50
|
+
backgroundExecute(context: AdapterContext<T>): Promise<number>;
|
|
51
|
+
private makeRequest;
|
|
52
|
+
}
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,136 @@
|
|
|
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 transportMetrics = __importStar(require("./metrics"));
|
|
33
|
+
const error_1 = require("../validation/error");
|
|
34
|
+
const WARMUP_BATCH_REQUEST_ID = '9002';
|
|
35
|
+
const logger = (0, util_1.makeLogger)('BatchWarmingTransport');
|
|
36
|
+
/**
|
|
37
|
+
* Transport implementation that takes incoming batches requests and keeps a warm cache of values.
|
|
38
|
+
* Within the setup function, adapter params are added to an set that also keeps track and expires values.
|
|
39
|
+
* In the background execute, the list of non-expired items in the set is fetched.
|
|
40
|
+
* Then, the list is passed through the `prepareRequest` function, that returns an AxiosRequestConfig.
|
|
41
|
+
* The Data Provider response is, they are passed through the `parseResponse` function to create a [[CacheEntry]] list.
|
|
42
|
+
* Finally, the items in that [[CacheEntry]] list are set in the Cache so the Adapter can fetch values from there.
|
|
43
|
+
*
|
|
44
|
+
* @typeParam T - all types related to the [[Transport]]
|
|
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, _, endpointName) {
|
|
54
|
+
this.cache = dependencies.cache;
|
|
55
|
+
this.rateLimiter = dependencies.backgroundExecuteRateLimiter;
|
|
56
|
+
this.subscriptionSet = dependencies.subscriptionSetFactory.buildSet(endpointName);
|
|
57
|
+
}
|
|
58
|
+
// This might need coalescing to avoid too frequent ttl updates
|
|
59
|
+
async registerRequest(req, config) {
|
|
60
|
+
logger.debug(`Adding entry to subscription set (ttl ${config.WARMUP_SUBSCRIPTION_TTL}): [${req.requestContext.cacheKey}] = ${req.requestContext.data}`);
|
|
61
|
+
if (config.BATCH_TRANSPORT_SETUP_VALIDATION) {
|
|
62
|
+
const response = await this.makeRequest([req.requestContext.data], config);
|
|
63
|
+
if (!response.results.length) {
|
|
64
|
+
throw new error_1.AdapterError({
|
|
65
|
+
statusCode: 200,
|
|
66
|
+
providerStatusCode: response.providerResponse.status,
|
|
67
|
+
message: response.providerResponse.message ||
|
|
68
|
+
'There was an error while validating the incoming request before adding to the batch subscription set',
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
await this.subscriptionSet.add(req.requestContext.cacheKey, req.requestContext.data, config.WARMUP_SUBSCRIPTION_TTL);
|
|
73
|
+
}
|
|
74
|
+
async backgroundExecute(context) {
|
|
75
|
+
logger.debug('Starting background execute');
|
|
76
|
+
const entries = await this.subscriptionSet.getAll();
|
|
77
|
+
// Keep track of active subscriptions for background execute
|
|
78
|
+
transportMetrics.bgExecuteSubscriptionSetCount
|
|
79
|
+
.labels({ endpoint: context.adapterEndpoint.name, transport_type: 'batch' })
|
|
80
|
+
.set(entries.length);
|
|
81
|
+
const interval = this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name);
|
|
82
|
+
if (!entries.length) {
|
|
83
|
+
logger.debug('No entries in batch warming set, skipping');
|
|
84
|
+
if (this.WARMER_ACTIVE) {
|
|
85
|
+
// Decrement count when warmer changed from having entries to having none
|
|
86
|
+
cacheMetrics.cacheWarmerCount.labels({ isBatched: 'true' }).dec();
|
|
87
|
+
this.WARMER_ACTIVE = false;
|
|
88
|
+
}
|
|
89
|
+
return interval;
|
|
90
|
+
}
|
|
91
|
+
else if (this.WARMER_ACTIVE === false) {
|
|
92
|
+
// Increment count when warmer changed from having no entries to having some
|
|
93
|
+
cacheMetrics.cacheWarmerCount.labels({ isBatched: 'true' }).inc();
|
|
94
|
+
this.WARMER_ACTIVE = true;
|
|
95
|
+
}
|
|
96
|
+
const response = await this.makeRequest(entries, context.adapterConfig);
|
|
97
|
+
if (!response.results?.length) {
|
|
98
|
+
return interval;
|
|
99
|
+
}
|
|
100
|
+
const cacheEntries = (0, _1.buildCacheEntriesFromResults)(response.results, context);
|
|
101
|
+
logger.debug('Setting adapter responses in cache');
|
|
102
|
+
await this.cache.setMany(cacheEntries, context.adapterConfig.CACHE_MAX_AGE);
|
|
103
|
+
// Record cost of data provider call
|
|
104
|
+
const cost = rateLimitMetrics.retrieveCost(response.providerResponse.data);
|
|
105
|
+
rateLimitMetrics.rateLimitCreditsSpentTotal
|
|
106
|
+
.labels({
|
|
107
|
+
feed_id: 'N/A',
|
|
108
|
+
participant_id: WARMUP_BATCH_REQUEST_ID,
|
|
109
|
+
})
|
|
110
|
+
.inc(cost);
|
|
111
|
+
return interval;
|
|
112
|
+
}
|
|
113
|
+
async makeRequest(entries, config) {
|
|
114
|
+
logger.trace(`Have ${entries.length} entries in batch, preparing request...`);
|
|
115
|
+
const request = this.config.prepareRequest(entries, config);
|
|
116
|
+
logger.trace(`Sending request to data provider: ${JSON.stringify(request)}`);
|
|
117
|
+
let providerResponse;
|
|
118
|
+
try {
|
|
119
|
+
providerResponse = await (0, util_2.axiosRequest)(request, config);
|
|
120
|
+
}
|
|
121
|
+
catch (e) {
|
|
122
|
+
logger.warn(`There was an error while performing the batch request: ${e}`);
|
|
123
|
+
return {
|
|
124
|
+
results: [],
|
|
125
|
+
providerResponse: e,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`);
|
|
129
|
+
return {
|
|
130
|
+
results: this.config.parseResponse(entries, providerResponse, config),
|
|
131
|
+
providerResponse,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
exports.BatchWarmingTransport = BatchWarmingTransport;
|
|
136
|
+
//# sourceMappingURL=batch-warming.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batch-warming.js","sourceRoot":"","sources":["../../../src/transports/batch-warming.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,kCAAqD;AAErD,yBAA+E;AAC/E,iCAAqC;AACrC,2EAA4D;AAC5D,+DAAgD;AAEhD,4DAA6C;AAC7C,+CAAkD;AAElD,MAAM,uBAAuB,GAAG,MAAM,CAAA;AAEtC,MAAM,MAAM,GAAG,IAAA,iBAAU,EAAC,uBAAuB,CAAC,CAAA;AAuBlD;;;;;;;;;GASG;AACH,MAAa,qBAAqB;IAWhC,YACU,MAUP;QAVO,WAAM,GAAN,MAAM,CAUb;QAfH,uGAAuG;QACvG,gEAAgE;QAChE,kBAAa,GAAG,KAAK,CAAA;IAclB,CAAC;IAEJ,KAAK,CAAC,UAAU,CACd,YAAiC,EACjC,CAAqC,EACrC,YAAoB;QAEpB,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC,KAA8C,CAAA;QACxE,IAAI,CAAC,WAAW,GAAG,YAAY,CAAC,4BAA4B,CAAA;QAC5D,IAAI,CAAC,eAAe,GAAG,YAAY,CAAC,sBAAsB,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAA;IACnF,CAAC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;SACxC,CAAC;aACD,GAAG,CAAC,IAAI,CAAC,CAAA;QAEZ,OAAO,QAAQ,CAAA;IACjB,CAAC;IAEO,KAAK,CAAC,WAAW,CACvB,OAAiC,EACjC,MAA0C;QAK1C,MAAM,CAAC,KAAK,CAAC,QAAQ,OAAO,CAAC,MAAM,yCAAyC,CAAC,CAAA;QAC7E,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAE3D,MAAM,CAAC,KAAK,CAAC,qCAAqC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;QAC5E,IAAI,gBAAgB,CAAA;QACpB,IAAI;YACF,gBAAgB,GAAG,MAAM,IAAA,mBAAY,EAInC,OAAO,EAAE,MAAM,CAAC,CAAA;SACnB;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,CAAC,IAAI,CAAC,0DAA0D,CAAC,EAAE,CAAC,CAAA;YAC1E,OAAO;gBACL,OAAO,EAAE,EAAE;gBACX,gBAAgB,EAAE,CAAkB;aACrC,CAAA;SACF;QAED,MAAM,CAAC,KAAK,CAAC,kDAAkD,gBAAgB,CAAC,IAAI,GAAG,CAAC,CAAA;QACxF,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,CAAC;YACrE,gBAAgB;SACjB,CAAA;IACH,CAAC;CACF;AAjJD,sDAiJC"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { AdapterContext, AdapterDependencies } from '../adapter';
|
|
2
|
+
import { Cache, CacheEntry } from '../cache';
|
|
3
|
+
import { AdapterConfig, SettingsMap } from '../config';
|
|
4
|
+
import { AdapterRequest, AdapterResponse, ProviderResult, RequestGenerics, ResponseGenerics } from '../util/request';
|
|
5
|
+
export * from './batch-warming';
|
|
6
|
+
export * from './rest';
|
|
7
|
+
export * from './sse';
|
|
8
|
+
export * from './websocket';
|
|
9
|
+
/**
|
|
10
|
+
* Helper struct type that will be used to pass types to the generic parameters of a Transport.
|
|
11
|
+
* Within the transport, given a generic param T extends TransportGenerics, these will be used like so:
|
|
12
|
+
*
|
|
13
|
+
* const request: AdapterRequest\<T['Request']\> = ...
|
|
14
|
+
*
|
|
15
|
+
* (ignore the slash characters, they're just for proper doc syntax \<)
|
|
16
|
+
*/
|
|
17
|
+
export declare type TransportGenerics = {
|
|
18
|
+
/**
|
|
19
|
+
* Type details about incoming Adapter requests to this Transport
|
|
20
|
+
*/
|
|
21
|
+
Request: RequestGenerics;
|
|
22
|
+
/**
|
|
23
|
+
* Type details about outbound responses from this Transport
|
|
24
|
+
*/
|
|
25
|
+
Response: ResponseGenerics;
|
|
26
|
+
/**
|
|
27
|
+
* Type for any custom settings used for this Transport
|
|
28
|
+
*/
|
|
29
|
+
CustomSettings: SettingsMap;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Generic interface for a Transport.
|
|
33
|
+
* A Transport defines the way in which an AdapterEndpoint will process incoming requests to
|
|
34
|
+
* fetch data from a Data Provider. The setup phase will take care of the former, while the
|
|
35
|
+
* backgroundExecute will be in charge of the latter.
|
|
36
|
+
* This separation gives us the ability of splitting these concerns, and optionally parallelizing
|
|
37
|
+
* the reading and writing of data to a centralized Cache.
|
|
38
|
+
*
|
|
39
|
+
* @typeParam T - Helper struct type that will be used to pass types to the generic parameters (check [[TransportGenerics]])
|
|
40
|
+
*/
|
|
41
|
+
export interface Transport<T extends TransportGenerics> {
|
|
42
|
+
cache?: Cache<AdapterResponse<T['Response']>>;
|
|
43
|
+
/**
|
|
44
|
+
* Initializes the transport in the Adapter context.
|
|
45
|
+
*
|
|
46
|
+
* @param dependencies - Adapter dependencies (e.g. cache instance)
|
|
47
|
+
* @param config - Adapter config containing env vars
|
|
48
|
+
* @returns an empty Promise
|
|
49
|
+
*/
|
|
50
|
+
initialize: (dependencies: AdapterDependencies, config: AdapterConfig<T['CustomSettings']>, endpointName: string) => Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Registers a request within the context of the transport.
|
|
53
|
+
* This means things like adding the request to a subscription set.
|
|
54
|
+
*
|
|
55
|
+
* @param req - the incoming AdapterRequest
|
|
56
|
+
* @param config - common configuration for the Adapter as a whole
|
|
57
|
+
* @returns an empty Promise
|
|
58
|
+
*/
|
|
59
|
+
registerRequest?: (req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>) => Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* Performs a synchronous fetch/processing of information within the lifecycle of an incoming request.
|
|
62
|
+
* This is mostly intended to be used as a backwards compatibility mechanism, or for very specific cases where
|
|
63
|
+
* processing is expected to be very simple. Things like rate limiting for example won't be able to be applied
|
|
64
|
+
* to this method with more than one EA instance. It's heavily encouraged to instead rework adapter logic
|
|
65
|
+
* to perform as much of the work as possible (or all of it) in the backgroundExecute method.
|
|
66
|
+
*
|
|
67
|
+
* @param req - the incoming AdapterRequest
|
|
68
|
+
* @param config - common configuration for the Adapter as a whole
|
|
69
|
+
* @returns a Promise that _optionally_ returns an AdapterResponse, if the Transport has the capability of
|
|
70
|
+
* immediately fetching data and returning it without the background process.
|
|
71
|
+
*/
|
|
72
|
+
foregroundExecute?: (req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>) => Promise<AdapterResponse<{
|
|
73
|
+
Data: T['Response']['Data'];
|
|
74
|
+
Result: T['Response']['Result'];
|
|
75
|
+
}> | void>;
|
|
76
|
+
/**
|
|
77
|
+
* Main function that will be called by the main background loop of the writer EA.
|
|
78
|
+
* All logic fetching from providers should live here.
|
|
79
|
+
*
|
|
80
|
+
* @param context - background context for the execution (e.g. endpoint name)
|
|
81
|
+
* @returns an empty Promise
|
|
82
|
+
*/
|
|
83
|
+
backgroundExecute?: (context: AdapterContext<T>) => Promise<number>;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Generic interface for a Transport that contains or manages other transports.
|
|
87
|
+
* Some transports, such as the RoutingTransport, do not directly fetch data from a Data Provider, but
|
|
88
|
+
* instead coordinate the execution of other transports for fetching and transforming data.
|
|
89
|
+
* These transports have alternative initialization procedures, which typically involve
|
|
90
|
+
* initializing each downstream transport.
|
|
91
|
+
*
|
|
92
|
+
* @typeParam Params - the structure of the AdapterRequest's body
|
|
93
|
+
* @typeParam Result - the structure of the AdapterResponse's body
|
|
94
|
+
* @typeParam CustomSettings - custom settings for the Adapter, or the default SettingsMap
|
|
95
|
+
*/
|
|
96
|
+
export interface MetaTransport<T extends TransportGenerics> extends Transport<T> {
|
|
97
|
+
transports: {
|
|
98
|
+
[key: string]: Transport<T>;
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Helper method to build cache entries to set after getting a bunch of responses from a DP.
|
|
103
|
+
*
|
|
104
|
+
* @param results - a list of results coming from a DataProvider
|
|
105
|
+
* @param context - context for the Adapter
|
|
106
|
+
* @returns a list of CacheEntries of AdapterResponses
|
|
107
|
+
*/
|
|
108
|
+
export declare const buildCacheEntriesFromResults: <T extends TransportGenerics>(results: ProviderResult<T>[], context: AdapterContext<T>) => CacheEntry<AdapterResponse<T["Response"]>>[];
|
|
@@ -0,0 +1,56 @@
|
|
|
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.buildCacheEntriesFromResults = void 0;
|
|
18
|
+
const cache_1 = require("../cache");
|
|
19
|
+
__exportStar(require("./batch-warming"), exports);
|
|
20
|
+
__exportStar(require("./rest"), exports);
|
|
21
|
+
__exportStar(require("./sse"), exports);
|
|
22
|
+
__exportStar(require("./websocket"), exports);
|
|
23
|
+
/**
|
|
24
|
+
* Helper method to build cache entries to set after getting a bunch of responses from a DP.
|
|
25
|
+
*
|
|
26
|
+
* @param results - a list of results coming from a DataProvider
|
|
27
|
+
* @param context - context for the Adapter
|
|
28
|
+
* @returns a list of CacheEntries of AdapterResponses
|
|
29
|
+
*/
|
|
30
|
+
const buildCacheEntriesFromResults = (results, context) => results.map((r) => {
|
|
31
|
+
const cacheEntry = {
|
|
32
|
+
key: (0, cache_1.calculateCacheKey)(context, r.params),
|
|
33
|
+
value: {
|
|
34
|
+
result: r.value,
|
|
35
|
+
statusCode: 200,
|
|
36
|
+
data: {
|
|
37
|
+
result: r.value,
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
if (context.adapterConfig.METRICS_ENABLED &&
|
|
42
|
+
context.adapterConfig.EXPERIMENTAL_METRICS_ENABLED) {
|
|
43
|
+
const metrics = {
|
|
44
|
+
maxAge: Date.now() + context.adapterConfig.CACHE_MAX_AGE,
|
|
45
|
+
meta: {
|
|
46
|
+
metrics: {
|
|
47
|
+
feedId: (0, cache_1.calculateFeedId)(context, r.params),
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
cacheEntry.value = { ...cacheEntry.value, ...metrics };
|
|
52
|
+
}
|
|
53
|
+
return cacheEntry;
|
|
54
|
+
});
|
|
55
|
+
exports.buildCacheEntriesFromResults = buildCacheEntriesFromResults;
|
|
56
|
+
//# sourceMappingURL=index.js.map
|