@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/metrics/index.d.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import * as client from 'prom-client';
|
|
2
|
-
import { AdapterRequest } from '../util';
|
|
3
|
-
import { AdapterConfig } from '../config';
|
|
4
|
-
import { FastifyReply, HookHandlerDoneFunction } from 'fastify';
|
|
5
|
-
export declare function setupMetricsServer(name: string, config: AdapterConfig): void;
|
|
6
|
-
export declare const setupMetrics: (name: string, config: AdapterConfig) => void;
|
|
7
|
-
/**
|
|
8
|
-
* Builds metrics middleware that records end to end EA response times
|
|
9
|
-
* and count of requests
|
|
10
|
-
*
|
|
11
|
-
* @returns the cache middleware function
|
|
12
|
-
*/
|
|
13
|
-
export declare const buildMetricsMiddleware: (req: AdapterRequest, res: FastifyReply, done: HookHandlerDoneFunction) => void;
|
|
14
|
-
export declare const httpRequestsTotal: client.Counter<"type" | "method" | "feed_id" | "status_code" | "provider_status_code" | "retry" | "is_cache_warming">;
|
|
15
|
-
export declare const httpRequestDurationSeconds: client.Histogram<string>;
|
package/metrics/util.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { AdapterMetricsMeta, AdapterRequestData } from '../util';
|
|
2
|
-
import { AdapterEndpoint } from '../adapter';
|
|
3
|
-
import { AdapterConfig } from '../config';
|
|
4
|
-
export declare const getMetricsMeta: ({ adapterEndpoint, adapterConfig, }: {
|
|
5
|
-
adapterEndpoint: AdapterEndpoint;
|
|
6
|
-
adapterConfig: AdapterConfig;
|
|
7
|
-
}, data: AdapterRequestData) => AdapterMetricsMeta;
|
package/package/adapter.d.ts
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import { AdapterConfig, BaseAdapterConfig, SettingsMap } from './config';
|
|
2
|
-
import { AdapterRateLimitTier } from './rate-limiting';
|
|
3
|
-
import { AdapterDependencies, Transport } from './transports';
|
|
4
|
-
import { InputParameters } from './validation/input-params';
|
|
5
|
-
/**
|
|
6
|
-
* Structure to describe rate limits specs for the Adapter
|
|
7
|
-
*/
|
|
8
|
-
interface AdapterRateLimitingConfig {
|
|
9
|
-
/** Adapter rate limits, gotten from the specific tier requested */
|
|
10
|
-
tiers: Record<string, AdapterRateLimitTier>;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Main structure of an External Adapter
|
|
14
|
-
*/
|
|
15
|
-
export interface Adapter {
|
|
16
|
-
/** Name of the adapter */
|
|
17
|
-
name: string;
|
|
18
|
-
/** If present, the string that will be used for requests with no specified endpoint */
|
|
19
|
-
defaultEndpoint?: string;
|
|
20
|
-
/** List of [[AdapterEndpoint]]s in the adapter */
|
|
21
|
-
endpoints: AdapterEndpoint[];
|
|
22
|
-
/** Map of overrides to the default config values for an Adapter */
|
|
23
|
-
envDefaultOverrides?: Partial<BaseAdapterConfig>;
|
|
24
|
-
/** List of custom env vars for this particular adapter (e.g. RPC_URL) */
|
|
25
|
-
customSettings?: SettingsMap;
|
|
26
|
-
/** Configuration relevant to outbound (EA --\> DP) communication rate limiting */
|
|
27
|
-
rateLimiting?: AdapterRateLimitingConfig;
|
|
28
|
-
/** Overrides for converting the 'base' parameter that are hardcoded into the adapter. */
|
|
29
|
-
overrides?: Record<string, string>;
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Structure to describe rate limits specs for a specific adapter endpoint
|
|
33
|
-
*/
|
|
34
|
-
export interface EndpointRateLimitingConfig {
|
|
35
|
-
/**
|
|
36
|
-
* How much of the total limit for the adapter will be assigned to this specific endpoint.
|
|
37
|
-
* Should be a non-zero positive number up to 100.
|
|
38
|
-
* Endpoints in the same adapter without a specific allocation will divide the remaining limits equally.
|
|
39
|
-
*/
|
|
40
|
-
allocationPercentage: number;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Structure to describe a specific endpoint in an [[Adapter]]
|
|
44
|
-
*/
|
|
45
|
-
export interface AdapterEndpoint {
|
|
46
|
-
/** Name that will be used to match input params to this endpoint (case insensitive) */
|
|
47
|
-
name: string;
|
|
48
|
-
/** List of alternative endpoint names that will resolve to this same transport (case insensitive) */
|
|
49
|
-
aliases?: string[];
|
|
50
|
-
/** Transport that will be used to handle data processing and communication for this endpoint */
|
|
51
|
-
transport: Transport<any, any, any>;
|
|
52
|
-
/** Specification of what the body of a request hitting this endpoint should look like (used for validation) */
|
|
53
|
-
inputParameters: InputParameters;
|
|
54
|
-
/** Specific details related to the rate limiting for this endpoint in particular */
|
|
55
|
-
rateLimiting?: EndpointRateLimitingConfig;
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Structure to describe an adapter that has been initialized
|
|
59
|
-
*/
|
|
60
|
-
export interface InitializedAdapter extends Adapter {
|
|
61
|
-
/** Object containing alias translations for all endpoints */
|
|
62
|
-
endpointsMap: Record<string, AdapterEndpoint>;
|
|
63
|
-
/** Initialized dependencies that the adapter will use */
|
|
64
|
-
dependencies: AdapterDependencies;
|
|
65
|
-
/** Configuration params for various adapter properties */
|
|
66
|
-
config: AdapterConfig;
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* This function will process dependencies for an adapter, such as caches or rate limiters,
|
|
70
|
-
* in order to inject them into transports and other relevant places later in the lifecycle.
|
|
71
|
-
*
|
|
72
|
-
* @param config - the configuration for this adapter
|
|
73
|
-
* @param inputDependencies - a partial obj of initialized dependencies to override the created ones
|
|
74
|
-
* @param rateLimitingConfig - details from the adapter regarding rate limiting
|
|
75
|
-
* @returns a set of AdapterDependencies all initialized
|
|
76
|
-
*/
|
|
77
|
-
export declare const initializeDependencies: (adapter: Adapter, config: AdapterConfig, inputDependencies?: Partial<AdapterDependencies>) => AdapterDependencies;
|
|
78
|
-
/**
|
|
79
|
-
* Initializes all of the [[Transport]]s in the adapter, passing along any [[AdapterDependencies]] and [[AdapterConfig]].
|
|
80
|
-
* Additionally, it builds a map out of all the endpoint names and aliases (checking for duplicates).
|
|
81
|
-
*
|
|
82
|
-
* @param adapter - an instance of an Adapter
|
|
83
|
-
* @param dependencies - dependencies that the adapter will need at initialization
|
|
84
|
-
* @param config - configuration variables already processed and validated
|
|
85
|
-
* @returns - the adapter with all transports initialized and aliases map built
|
|
86
|
-
*/
|
|
87
|
-
export declare const initializeAdapter: (adapter: Adapter, config: AdapterConfig, dependencies?: Partial<AdapterDependencies>) => Promise<InitializedAdapter>;
|
|
88
|
-
export {};
|
package/package/adapter.js
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.initializeAdapter = exports.initializeDependencies = void 0;
|
|
4
|
-
const factory_1 = require("./cache/factory");
|
|
5
|
-
const rate_limiting_1 = require("./rate-limiting");
|
|
6
|
-
const util_1 = require("./util");
|
|
7
|
-
const logger = (0, util_1.makeLogger)('Adapter');
|
|
8
|
-
/**
|
|
9
|
-
* This function will take an adapter structure and go through each endpoint, calculating
|
|
10
|
-
* each one's allocation of the total rate limits that are set for the adapter as a whole.
|
|
11
|
-
*
|
|
12
|
-
* @param adapter - the adapter to initialize rate limiting for
|
|
13
|
-
*/
|
|
14
|
-
const calculateRateLimitAllocations = (adapter) => {
|
|
15
|
-
const numberOfEndpoints = adapter.endpoints.length;
|
|
16
|
-
const endpointsWithExplicitAllocations = adapter.endpoints.filter((e) => e.rateLimiting);
|
|
17
|
-
const totalExplicitAllocation = endpointsWithExplicitAllocations
|
|
18
|
-
.map((e) => e.rateLimiting?.allocationPercentage || 0)
|
|
19
|
-
.reduce((sum, next) => sum + next, 0);
|
|
20
|
-
if (totalExplicitAllocation > 100) {
|
|
21
|
-
throw new Error('The total allocation set for all endpoints summed cannot exceed 100%');
|
|
22
|
-
}
|
|
23
|
-
if (totalExplicitAllocation === 100 &&
|
|
24
|
-
numberOfEndpoints - endpointsWithExplicitAllocations.length > 0) {
|
|
25
|
-
throw new Error('The explicit allocation is at 100% but there are endpoints with implicit allocation');
|
|
26
|
-
}
|
|
27
|
-
const implicitAllocation = 100 - totalExplicitAllocation;
|
|
28
|
-
logger.debug('Adapter rate limit allocations:');
|
|
29
|
-
for (const endpoint of adapter.endpoints) {
|
|
30
|
-
if (!endpoint.rateLimiting) {
|
|
31
|
-
endpoint.rateLimiting = {
|
|
32
|
-
allocationPercentage: implicitAllocation / (numberOfEndpoints - endpointsWithExplicitAllocations.length),
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
logger.debug(`Endpoint [${endpoint.name}] - ${endpoint.rateLimiting?.allocationPercentage}%`);
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
/**
|
|
39
|
-
* This function will process dependencies for an adapter, such as caches or rate limiters,
|
|
40
|
-
* in order to inject them into transports and other relevant places later in the lifecycle.
|
|
41
|
-
*
|
|
42
|
-
* @param config - the configuration for this adapter
|
|
43
|
-
* @param inputDependencies - a partial obj of initialized dependencies to override the created ones
|
|
44
|
-
* @param rateLimitingConfig - details from the adapter regarding rate limiting
|
|
45
|
-
* @returns a set of AdapterDependencies all initialized
|
|
46
|
-
*/
|
|
47
|
-
const initializeDependencies = (adapter, config, inputDependencies) => {
|
|
48
|
-
const dependencies = inputDependencies || {};
|
|
49
|
-
if (!dependencies.cache) {
|
|
50
|
-
dependencies.cache = factory_1.CacheFactory.buildCache(config);
|
|
51
|
-
}
|
|
52
|
-
// In the future we might want something more complex, but for now it's better to simplify
|
|
53
|
-
// and just use the same rate limiting for everything. Once we have a more complex use case we
|
|
54
|
-
// can think of ways to make this more configurable.
|
|
55
|
-
const rateLimitingTier = (0, rate_limiting_1.getRateLimitingTier)(adapter.rateLimiting?.tiers, config.RATE_LIMIT_API_TIER);
|
|
56
|
-
if (!dependencies.requestRateLimiter) {
|
|
57
|
-
dependencies.requestRateLimiter = new rate_limiting_1.SimpleCountingRateLimiter().initialize(adapter.endpoints, rateLimitingTier);
|
|
58
|
-
}
|
|
59
|
-
if (!dependencies.backgroundExecuteRateLimiter) {
|
|
60
|
-
dependencies.backgroundExecuteRateLimiter = new rate_limiting_1.FixedFrequencyRateLimiter().initialize(adapter.endpoints, rateLimitingTier);
|
|
61
|
-
}
|
|
62
|
-
return dependencies;
|
|
63
|
-
};
|
|
64
|
-
exports.initializeDependencies = initializeDependencies;
|
|
65
|
-
/**
|
|
66
|
-
* Takes an adapter and normalizes all endpoint names and aliases, as well as the default endpoint.
|
|
67
|
-
* i.e. makes them lowercase for now
|
|
68
|
-
* @param adapter - an instance of an Adapter
|
|
69
|
-
*/
|
|
70
|
-
const normalizeEndpointNames = (adapter) => {
|
|
71
|
-
// Make endpoints case insensitive, including default
|
|
72
|
-
adapter.defaultEndpoint = adapter.defaultEndpoint?.toLowerCase();
|
|
73
|
-
for (const endpoint of adapter.endpoints) {
|
|
74
|
-
endpoint.name = endpoint.name.toLowerCase();
|
|
75
|
-
endpoint.aliases = endpoint.aliases?.map((a) => a.toLowerCase());
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
/**
|
|
79
|
-
* Initializes all of the [[Transport]]s in the adapter, passing along any [[AdapterDependencies]] and [[AdapterConfig]].
|
|
80
|
-
* Additionally, it builds a map out of all the endpoint names and aliases (checking for duplicates).
|
|
81
|
-
*
|
|
82
|
-
* @param adapter - an instance of an Adapter
|
|
83
|
-
* @param dependencies - dependencies that the adapter will need at initialization
|
|
84
|
-
* @param config - configuration variables already processed and validated
|
|
85
|
-
* @returns - the adapter with all transports initialized and aliases map built
|
|
86
|
-
*/
|
|
87
|
-
const initializeAdapter = async (adapter, config, dependencies) => {
|
|
88
|
-
normalizeEndpointNames(adapter);
|
|
89
|
-
calculateRateLimitAllocations(adapter);
|
|
90
|
-
const initializedDependencies = (0, exports.initializeDependencies)(adapter, config, dependencies);
|
|
91
|
-
const endpointsMap = {};
|
|
92
|
-
for (const endpoint of adapter.endpoints) {
|
|
93
|
-
// Add aliases to map to use in validation
|
|
94
|
-
const aliases = [endpoint.name, ...(endpoint.aliases || [])];
|
|
95
|
-
for (const alias of aliases) {
|
|
96
|
-
if (endpointsMap[alias]) {
|
|
97
|
-
throw new Error(`Duplicate endpoint / alias: "${alias}"`);
|
|
98
|
-
}
|
|
99
|
-
endpointsMap[alias] = endpoint;
|
|
100
|
-
}
|
|
101
|
-
logger.debug(`Initializing transport for endpoint "${endpoint.name}"...`);
|
|
102
|
-
await endpoint.transport.initialize(initializedDependencies);
|
|
103
|
-
}
|
|
104
|
-
logger.debug('Adapter initialization complete.');
|
|
105
|
-
return {
|
|
106
|
-
...adapter,
|
|
107
|
-
endpointsMap,
|
|
108
|
-
dependencies: initializedDependencies,
|
|
109
|
-
config,
|
|
110
|
-
};
|
|
111
|
-
};
|
|
112
|
-
exports.initializeAdapter = initializeAdapter;
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
|
-
import { Server } from 'http';
|
|
3
|
-
import { InitializedAdapter } from './adapter';
|
|
4
|
-
/**
|
|
5
|
-
* Very simple background loop that will call the [[Transport.backgroundExecute]] functions in all Transports.
|
|
6
|
-
* It gets the time in ms to wait as the return value from those functions, and sleeps until next execution.
|
|
7
|
-
*
|
|
8
|
-
* @param adapter - an initialized External Adapter
|
|
9
|
-
* @param server - the http server to attach an on close listener to
|
|
10
|
-
*/
|
|
11
|
-
export declare function callBackgroundExecutes(adapter: InitializedAdapter, server?: Server): Promise<void>;
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.callBackgroundExecutes = void 0;
|
|
4
|
-
const util_1 = require("./util");
|
|
5
|
-
const logger = (0, util_1.makeLogger)('BackgroundExecutor');
|
|
6
|
-
/**
|
|
7
|
-
* Very simple background loop that will call the [[Transport.backgroundExecute]] functions in all Transports.
|
|
8
|
-
* It gets the time in ms to wait as the return value from those functions, and sleeps until next execution.
|
|
9
|
-
*
|
|
10
|
-
* @param adapter - an initialized External Adapter
|
|
11
|
-
* @param server - the http server to attach an on close listener to
|
|
12
|
-
*/
|
|
13
|
-
async function callBackgroundExecutes(adapter, server) {
|
|
14
|
-
// Set up variable to check later on to see if we need to stop this background "thread"
|
|
15
|
-
// If no server is provided, the listener won't be set and serverClosed will always be false
|
|
16
|
-
let serverClosed = false;
|
|
17
|
-
server?.on('close', () => {
|
|
18
|
-
serverClosed = true;
|
|
19
|
-
});
|
|
20
|
-
for (const endpoint of adapter.endpoints) {
|
|
21
|
-
const backgroundExecute = endpoint.transport.backgroundExecute?.bind(endpoint.transport);
|
|
22
|
-
if (!backgroundExecute) {
|
|
23
|
-
logger.debug(`Endpoint "${endpoint.name}" has no background execute, skipping...`);
|
|
24
|
-
continue;
|
|
25
|
-
}
|
|
26
|
-
const context = {
|
|
27
|
-
adapterEndpoint: endpoint,
|
|
28
|
-
adapterConfig: adapter.config,
|
|
29
|
-
};
|
|
30
|
-
const handler = async () => {
|
|
31
|
-
if (serverClosed) {
|
|
32
|
-
logger.info('Server closed, stopping recursive backgroundExecute handler chain');
|
|
33
|
-
return;
|
|
34
|
-
}
|
|
35
|
-
logger.debug(`Calling background execute for endpoint "${endpoint.name}"`);
|
|
36
|
-
const timeToWait = await backgroundExecute(context);
|
|
37
|
-
logger.debug(`Finished background execute for endpoint "${endpoint.name}", sleeping for ${timeToWait}ms`);
|
|
38
|
-
await (0, util_1.sleep)(timeToWait);
|
|
39
|
-
handler();
|
|
40
|
-
};
|
|
41
|
-
// Start recursive async calls
|
|
42
|
-
handler();
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
exports.callBackgroundExecutes = callBackgroundExecutes;
|
package/package/cache/factory.js
DELETED
|
@@ -1,57 +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
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
-
};
|
|
28
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
-
exports.CacheFactory = void 0;
|
|
30
|
-
const ioredis_1 = __importDefault(require("ioredis"));
|
|
31
|
-
const util_1 = require("../util");
|
|
32
|
-
const local_1 = require("./local");
|
|
33
|
-
const cacheMetrics = __importStar(require("./metrics"));
|
|
34
|
-
const redis_1 = require("./redis");
|
|
35
|
-
const logger = (0, util_1.makeLogger)('CacheFactory');
|
|
36
|
-
class CacheFactory {
|
|
37
|
-
static buildCache(config) {
|
|
38
|
-
logger.info(`Using "${config.CACHE_TYPE}" cache.`);
|
|
39
|
-
if (config.CACHE_TYPE === 'local') {
|
|
40
|
-
return new local_1.LocalCache();
|
|
41
|
-
}
|
|
42
|
-
else if (config.CACHE_TYPE === 'redis') {
|
|
43
|
-
const redis = new ioredis_1.default({
|
|
44
|
-
enableAutoPipelining: true,
|
|
45
|
-
host: config.CACHE_REDIS_HOST,
|
|
46
|
-
port: config.CACHE_REDIS_PORT,
|
|
47
|
-
});
|
|
48
|
-
redis.on('connect', () => {
|
|
49
|
-
cacheMetrics.redisConnectionsOpen.inc();
|
|
50
|
-
});
|
|
51
|
-
// TODO: Maybe track active redis connections instead of just total count of connections created
|
|
52
|
-
// Use a Gauge and track with a combo of connect/end events listeners
|
|
53
|
-
return new redis_1.RedisCache(redis);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
exports.CacheFactory = CacheFactory;
|
package/package/cache/index.d.ts
DELETED
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import { AdapterEndpoint } from '../adapter';
|
|
2
|
-
import { AdapterConfig } from '../config';
|
|
3
|
-
import { AdapterMiddlewareBuilder, AdapterResponse, sleep } from '../util';
|
|
4
|
-
export * from './local';
|
|
5
|
-
export * from './redis';
|
|
6
|
-
/**
|
|
7
|
-
* An object describing an entry in the cache.
|
|
8
|
-
* @typeParam T - the type of the entry's value
|
|
9
|
-
*/
|
|
10
|
-
export interface CacheEntry<T> {
|
|
11
|
-
key: string;
|
|
12
|
-
value: T;
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* Generic interface for a local or remote Cache.
|
|
16
|
-
* @typeParam T - the type of the cache entries' values
|
|
17
|
-
*/
|
|
18
|
-
export interface Cache<T = unknown> {
|
|
19
|
-
/**
|
|
20
|
-
* Gets an item from the Cache.
|
|
21
|
-
*
|
|
22
|
-
* @param key - the key of the desired entry for which to fetch its value
|
|
23
|
-
* @returns a Promise of the entry's value, or undefined if not found / expired.
|
|
24
|
-
*/
|
|
25
|
-
get: (key: string) => Promise<T | undefined>;
|
|
26
|
-
/**
|
|
27
|
-
* Sets an item in the Cache.
|
|
28
|
-
*
|
|
29
|
-
* @param key - the key of the new entry
|
|
30
|
-
* @param value - the value of the new entry
|
|
31
|
-
* @param ttl - the time in milliseconds until the entry expires
|
|
32
|
-
* @returns an empty Promise that resolves when the entry has been set
|
|
33
|
-
*/
|
|
34
|
-
set: (key: string, value: T, ttl: number) => Promise<void>;
|
|
35
|
-
/**
|
|
36
|
-
* Sets a list of items in the Cache.
|
|
37
|
-
*
|
|
38
|
-
* @param entries - a list of cache entries
|
|
39
|
-
* @param ttl - the time in milliseconds until the entries expire
|
|
40
|
-
* @returns an empty Promise that resolves when all entries have been set
|
|
41
|
-
*/
|
|
42
|
-
setMany: (entries: CacheEntry<T>[], ttl: number) => Promise<void>;
|
|
43
|
-
/**
|
|
44
|
-
* Deletes the specified item from the Cache
|
|
45
|
-
*
|
|
46
|
-
* @param key - the key of the entry to be deleted
|
|
47
|
-
* @returns an empty Promise that resolves when the entry has been deleted
|
|
48
|
-
*/
|
|
49
|
-
delete: (key: string) => Promise<void>;
|
|
50
|
-
}
|
|
51
|
-
export declare const calculateCacheKey: ({ adapterEndpoint, adapterConfig, }: {
|
|
52
|
-
adapterEndpoint: AdapterEndpoint;
|
|
53
|
-
adapterConfig: AdapterConfig;
|
|
54
|
-
}, data: unknown) => string;
|
|
55
|
-
export declare const calculateFeedId: (adapterEndpoint: AdapterEndpoint, data: unknown) => string;
|
|
56
|
-
/**
|
|
57
|
-
* Calculates a unique key from the provided data.
|
|
58
|
-
*
|
|
59
|
-
* @param data - the request data/body, i.e. the adapter input params
|
|
60
|
-
* @param paramNames - the keys from adapter endpoint input parameters
|
|
61
|
-
* @returns the calculated unique key
|
|
62
|
-
*
|
|
63
|
-
* @example
|
|
64
|
-
* ```
|
|
65
|
-
* calculateKey({ base: 'ETH', quote: 'BTC' }, ['base','quote'])
|
|
66
|
-
* // equals `|base:eth|quote:btc`
|
|
67
|
-
* ```
|
|
68
|
-
*/
|
|
69
|
-
export declare const calculateKey: (data: unknown, paramNames: string[]) => string;
|
|
70
|
-
/**
|
|
71
|
-
* Polls the provided Cache for an AdapterResponse set in the provided key. If the maximum
|
|
72
|
-
* amount of retries is exceeded, it returns undefined instead.
|
|
73
|
-
*
|
|
74
|
-
* @param cache - a Cache instance
|
|
75
|
-
* @param key - the key generated from an AdapterRequest that corresponds to the desired AdapterResponse
|
|
76
|
-
* @param retry - current retry, only for internal use
|
|
77
|
-
* @returns the AdapterResponse if found, else undefined
|
|
78
|
-
*/
|
|
79
|
-
export declare const pollResponseFromCache: (cache: Cache<AdapterResponse>, key: string, options: {
|
|
80
|
-
maxRetries: number;
|
|
81
|
-
sleep: number;
|
|
82
|
-
}, retry?: number) => Promise<AdapterResponse | undefined>;
|
|
83
|
-
/**
|
|
84
|
-
* Given a Cache instance in the adapter dependencies, builds a middleware function that will perform
|
|
85
|
-
* a get from said Cache and return that if found; otherwise it'll continue the middleware chain.
|
|
86
|
-
*
|
|
87
|
-
* @param adapter - an initialized adapter
|
|
88
|
-
* @returns the cache middleware function
|
|
89
|
-
*/
|
|
90
|
-
export declare const buildCacheMiddleware: AdapterMiddlewareBuilder;
|
package/package/cache/index.js
DELETED
|
@@ -1,169 +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
|
-
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
26
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
27
|
-
};
|
|
28
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
-
exports.buildCacheMiddleware = exports.pollResponseFromCache = exports.calculateKey = exports.calculateFeedId = exports.calculateCacheKey = void 0;
|
|
30
|
-
const util_1 = require("../util");
|
|
31
|
-
const cacheMetrics = __importStar(require("./metrics"));
|
|
32
|
-
__exportStar(require("./local"), exports);
|
|
33
|
-
__exportStar(require("./redis"), exports);
|
|
34
|
-
const logger = (0, util_1.makeLogger)('Cache');
|
|
35
|
-
// Uses calculateKey to generate a unique key from the endpoint name, data, and input parameters
|
|
36
|
-
const calculateCacheKey = ({ adapterEndpoint, adapterConfig, }, data) => {
|
|
37
|
-
const paramNames = Object.keys(adapterEndpoint.inputParameters);
|
|
38
|
-
if (paramNames.length === 0) {
|
|
39
|
-
logger.trace(`Using default cache key ${adapterConfig.DEFAULT_CACHE_KEY}`);
|
|
40
|
-
return adapterConfig.DEFAULT_CACHE_KEY;
|
|
41
|
-
}
|
|
42
|
-
return `${adapterEndpoint.name}-${(0, exports.calculateKey)(data, paramNames)}`;
|
|
43
|
-
};
|
|
44
|
-
exports.calculateCacheKey = calculateCacheKey;
|
|
45
|
-
const calculateFeedId = (adapterEndpoint, data) => {
|
|
46
|
-
const paramNames = Object.keys(adapterEndpoint.inputParameters);
|
|
47
|
-
if (paramNames.length === 0) {
|
|
48
|
-
logger.trace(`Cannot generate Feed ID without input parameters`);
|
|
49
|
-
return 'N/A';
|
|
50
|
-
}
|
|
51
|
-
return (0, exports.calculateKey)(data, paramNames);
|
|
52
|
-
};
|
|
53
|
-
exports.calculateFeedId = calculateFeedId;
|
|
54
|
-
/**
|
|
55
|
-
* Calculates a unique key from the provided data.
|
|
56
|
-
*
|
|
57
|
-
* @param data - the request data/body, i.e. the adapter input params
|
|
58
|
-
* @param paramNames - the keys from adapter endpoint input parameters
|
|
59
|
-
* @returns the calculated unique key
|
|
60
|
-
*
|
|
61
|
-
* @example
|
|
62
|
-
* ```
|
|
63
|
-
* calculateKey({ base: 'ETH', quote: 'BTC' }, ['base','quote'])
|
|
64
|
-
* // equals `|base:eth|quote:btc`
|
|
65
|
-
* ```
|
|
66
|
-
*/
|
|
67
|
-
const calculateKey = (data, paramNames) => {
|
|
68
|
-
if (data && typeof data !== 'object') {
|
|
69
|
-
throw new Error('Data to calculate cache key should be an object');
|
|
70
|
-
}
|
|
71
|
-
const params = data;
|
|
72
|
-
let cacheKey = ''; // TODO: Maybe there's a faster String Builder
|
|
73
|
-
for (const paramName of paramNames) {
|
|
74
|
-
// Ignore overrides param when generating cache keys
|
|
75
|
-
// TODO: expand support for ignoring `includes` and `tokenOverrides` params when generating keys
|
|
76
|
-
if (paramName === 'overrides') {
|
|
77
|
-
continue;
|
|
78
|
-
}
|
|
79
|
-
const param = params[paramName];
|
|
80
|
-
if (param === undefined) {
|
|
81
|
-
continue;
|
|
82
|
-
}
|
|
83
|
-
cacheKey += `|${paramName}:`;
|
|
84
|
-
switch (typeof param) {
|
|
85
|
-
case 'string':
|
|
86
|
-
cacheKey += param.toLowerCase();
|
|
87
|
-
break;
|
|
88
|
-
case 'number':
|
|
89
|
-
case 'boolean':
|
|
90
|
-
cacheKey += param.toString();
|
|
91
|
-
break;
|
|
92
|
-
case 'object':
|
|
93
|
-
// TODO: Implement object sorting for deterministic cache key generation
|
|
94
|
-
cacheKey += JSON.stringify(param);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
// TODO: Check max size, potential issue
|
|
98
|
-
logger.trace(`Generated cache key for request: "${cacheKey}"`);
|
|
99
|
-
return cacheKey;
|
|
100
|
-
};
|
|
101
|
-
exports.calculateKey = calculateKey;
|
|
102
|
-
// Calculate the amount of time the non-expired entry has been in the cache
|
|
103
|
-
const calculateStaleness = (expirationTimestamp, ttl) => {
|
|
104
|
-
if (expirationTimestamp) {
|
|
105
|
-
const createTimestamp = expirationTimestamp - ttl;
|
|
106
|
-
return (Date.now() - createTimestamp) / 1000;
|
|
107
|
-
}
|
|
108
|
-
else {
|
|
109
|
-
// If expirationTimestamp is not available, staleness cannot be calculated
|
|
110
|
-
// Defaults to ttl for metrics purposes
|
|
111
|
-
return ttl;
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
/**
|
|
115
|
-
* Polls the provided Cache for an AdapterResponse set in the provided key. If the maximum
|
|
116
|
-
* amount of retries is exceeded, it returns undefined instead.
|
|
117
|
-
*
|
|
118
|
-
* @param cache - a Cache instance
|
|
119
|
-
* @param key - the key generated from an AdapterRequest that corresponds to the desired AdapterResponse
|
|
120
|
-
* @param retry - current retry, only for internal use
|
|
121
|
-
* @returns the AdapterResponse if found, else undefined
|
|
122
|
-
*/
|
|
123
|
-
const pollResponseFromCache = async (cache, key, options, retry = 0) => {
|
|
124
|
-
if (retry > options.maxRetries) {
|
|
125
|
-
// Ideally this shouldn't happen often (p99 of reqs should be found in the cache)
|
|
126
|
-
logger.info('Exceeded max cache polling retries');
|
|
127
|
-
return undefined;
|
|
128
|
-
}
|
|
129
|
-
logger.trace('Getting response from cache...');
|
|
130
|
-
const response = await cache.get(key);
|
|
131
|
-
if (response) {
|
|
132
|
-
logger.trace('Got response from cache');
|
|
133
|
-
return response;
|
|
134
|
-
}
|
|
135
|
-
if (options.maxRetries === 0) {
|
|
136
|
-
logger.debug(`Response not found, retries disabled`);
|
|
137
|
-
return undefined;
|
|
138
|
-
}
|
|
139
|
-
logger.debug(`Response not found, sleeping ${options.sleep} milliseconds...`);
|
|
140
|
-
await (0, util_1.sleep)(options.sleep);
|
|
141
|
-
return (0, exports.pollResponseFromCache)(cache, key, options, retry + 1);
|
|
142
|
-
};
|
|
143
|
-
exports.pollResponseFromCache = pollResponseFromCache;
|
|
144
|
-
/**
|
|
145
|
-
* Given a Cache instance in the adapter dependencies, builds a middleware function that will perform
|
|
146
|
-
* a get from said Cache and return that if found; otherwise it'll continue the middleware chain.
|
|
147
|
-
*
|
|
148
|
-
* @param adapter - an initialized adapter
|
|
149
|
-
* @returns the cache middleware function
|
|
150
|
-
*/
|
|
151
|
-
const buildCacheMiddleware = (adapter) => async (req, res) => {
|
|
152
|
-
const response = await adapter.dependencies.cache.get(req.requestContext.cacheKey);
|
|
153
|
-
if (response) {
|
|
154
|
-
logger.debug('Found response from cache, sending that');
|
|
155
|
-
if (adapter.config.METRICS_ENABLED && adapter.config.EXPERIMENTAL_METRICS_ENABLED) {
|
|
156
|
-
const label = cacheMetrics.cacheMetricsLabel(req.requestContext.cacheKey, req.requestContext.meta?.metrics?.feedId || 'N/A', adapter.config.CACHE_TYPE);
|
|
157
|
-
// Record cache staleness and cache get count and value
|
|
158
|
-
const staleness = calculateStaleness(response.maxAge, adapter.config.CACHE_MAX_AGE);
|
|
159
|
-
cacheMetrics.cacheGet(label, response.result, staleness);
|
|
160
|
-
req.requestContext.meta = {
|
|
161
|
-
...req.requestContext.meta,
|
|
162
|
-
metrics: { ...req.requestContext.meta?.metrics, cacheHit: true },
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
return res.send(response);
|
|
166
|
-
}
|
|
167
|
-
logger.debug('Did not find response in cache, moving to next middleware');
|
|
168
|
-
};
|
|
169
|
-
exports.buildCacheMiddleware = buildCacheMiddleware;
|
package/package/cache/local.d.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { Cache, CacheEntry } from './index';
|
|
2
|
-
/**
|
|
3
|
-
* Type for a value stored in a LocalCache entry.
|
|
4
|
-
*
|
|
5
|
-
* @typeParam T - the type for the entry's value
|
|
6
|
-
*/
|
|
7
|
-
export interface LocalCacheEntry<T> {
|
|
8
|
-
expirationTimestamp: number;
|
|
9
|
-
value: T;
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Local implementation of a Cache. It uses a simple js Object, storing entries with both
|
|
13
|
-
* a value and an expiration timestamp. Expired entries are deleted on reads (i.e. no background gc/upkeep).
|
|
14
|
-
*
|
|
15
|
-
* @typeParam T - the type for the entries' values
|
|
16
|
-
*/
|
|
17
|
-
export declare class LocalCache<T = unknown> implements Cache<T> {
|
|
18
|
-
store: Record<string, LocalCacheEntry<T>>;
|
|
19
|
-
get(key: string): Promise<T | undefined>;
|
|
20
|
-
delete(key: string): Promise<void>;
|
|
21
|
-
set(key: string, value: T, ttl: number): Promise<void>;
|
|
22
|
-
setMany(entries: CacheEntry<T>[], ttl: number): Promise<void>;
|
|
23
|
-
}
|