@chainlink/external-adapter-framework 0.0.6 → 0.0.8

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.
Files changed (237) hide show
  1. package/adapter.d.ts +88 -0
  2. package/adapter.js +112 -0
  3. package/background-executor.d.ts +11 -0
  4. package/background-executor.js +45 -0
  5. package/cache/factory.d.ts +6 -0
  6. package/cache/factory.js +57 -0
  7. package/cache/index.d.ts +90 -0
  8. package/cache/index.js +169 -0
  9. package/cache/local.d.ts +23 -0
  10. package/cache/local.js +83 -0
  11. package/cache/metrics.d.ts +27 -0
  12. package/cache/metrics.js +120 -0
  13. package/cache/redis.d.ts +16 -0
  14. package/cache/redis.js +100 -0
  15. package/chainlink-external-adapter-framework-v0.0.8.tgz +0 -0
  16. package/config/index.d.ts +195 -0
  17. package/config/index.js +365 -0
  18. package/config/provider-limits.d.ts +31 -0
  19. package/config/provider-limits.js +75 -0
  20. package/examples/coingecko/batch-warming.d.ts +2 -0
  21. package/examples/coingecko/batch-warming.js +52 -0
  22. package/examples/coingecko/index.d.ts +2 -0
  23. package/examples/coingecko/index.js +10 -0
  24. package/examples/coingecko/rest.d.ts +2 -0
  25. package/examples/coingecko/rest.js +50 -0
  26. package/examples/ncfx/config/index.d.ts +12 -0
  27. package/examples/ncfx/config/index.js +15 -0
  28. package/examples/ncfx/index.d.ts +2 -0
  29. package/examples/ncfx/index.js +10 -0
  30. package/examples/ncfx/websocket.d.ts +36 -0
  31. package/examples/ncfx/websocket.js +72 -0
  32. package/index.d.ts +12 -0
  33. package/index.js +92 -0
  34. package/metrics/constants.d.ts +16 -0
  35. package/metrics/constants.js +25 -0
  36. package/metrics/index.d.ts +15 -0
  37. package/metrics/index.js +123 -0
  38. package/metrics/util.d.ts +3 -0
  39. package/metrics/util.js +9 -0
  40. package/package/adapter.d.ts +88 -0
  41. package/package/adapter.js +112 -0
  42. package/package/background-executor.d.ts +11 -0
  43. package/package/background-executor.js +45 -0
  44. package/package/cache/factory.d.ts +6 -0
  45. package/package/cache/factory.js +57 -0
  46. package/package/cache/index.d.ts +90 -0
  47. package/package/cache/index.js +169 -0
  48. package/package/cache/local.d.ts +23 -0
  49. package/package/cache/local.js +83 -0
  50. package/package/cache/metrics.d.ts +27 -0
  51. package/package/cache/metrics.js +120 -0
  52. package/package/cache/redis.d.ts +16 -0
  53. package/package/cache/redis.js +100 -0
  54. package/package/config/index.d.ts +195 -0
  55. package/package/config/index.js +365 -0
  56. package/package/config/provider-limits.d.ts +31 -0
  57. package/package/config/provider-limits.js +75 -0
  58. package/package/examples/coingecko/batch-warming.d.ts +2 -0
  59. package/package/examples/coingecko/batch-warming.js +52 -0
  60. package/package/examples/coingecko/index.d.ts +2 -0
  61. package/package/examples/coingecko/index.js +10 -0
  62. package/package/examples/coingecko/rest.d.ts +2 -0
  63. package/package/examples/coingecko/rest.js +50 -0
  64. package/package/examples/ncfx/config/index.d.ts +12 -0
  65. package/package/examples/ncfx/config/index.js +15 -0
  66. package/package/examples/ncfx/index.d.ts +2 -0
  67. package/package/examples/ncfx/index.js +10 -0
  68. package/package/examples/ncfx/websocket.d.ts +36 -0
  69. package/package/examples/ncfx/websocket.js +72 -0
  70. package/package/index.d.ts +12 -0
  71. package/package/index.js +92 -0
  72. package/package/metrics/constants.d.ts +16 -0
  73. package/package/metrics/constants.js +25 -0
  74. package/package/metrics/index.d.ts +15 -0
  75. package/package/metrics/index.js +123 -0
  76. package/package/metrics/util.d.ts +3 -0
  77. package/package/metrics/util.js +9 -0
  78. package/package/package.json +69 -0
  79. package/package/rate-limiting/background/fixed-frequency.d.ts +10 -0
  80. package/package/rate-limiting/background/fixed-frequency.js +37 -0
  81. package/package/rate-limiting/index.d.ts +54 -0
  82. package/package/rate-limiting/index.js +63 -0
  83. package/package/rate-limiting/metrics.d.ts +3 -0
  84. package/package/rate-limiting/metrics.js +44 -0
  85. package/package/rate-limiting/request/simple-counting.d.ts +20 -0
  86. package/package/rate-limiting/request/simple-counting.js +62 -0
  87. package/package/test.d.ts +1 -0
  88. package/package/test.js +6 -0
  89. package/package/transports/batch-warming.d.ts +34 -0
  90. package/package/transports/batch-warming.js +101 -0
  91. package/package/transports/index.d.ts +87 -0
  92. package/package/transports/index.js +87 -0
  93. package/package/transports/metrics.d.ts +21 -0
  94. package/package/transports/metrics.js +105 -0
  95. package/package/transports/rest.d.ts +43 -0
  96. package/package/transports/rest.js +129 -0
  97. package/package/transports/util.d.ts +8 -0
  98. package/package/transports/util.js +85 -0
  99. package/package/transports/websocket.d.ts +80 -0
  100. package/package/transports/websocket.js +169 -0
  101. package/package/util/expiring-sorted-set.d.ts +21 -0
  102. package/package/util/expiring-sorted-set.js +47 -0
  103. package/package/util/index.d.ts +11 -0
  104. package/package/util/index.js +35 -0
  105. package/package/util/logger.d.ts +42 -0
  106. package/package/util/logger.js +62 -0
  107. package/package/util/request.d.ts +55 -0
  108. package/package/util/request.js +2 -0
  109. package/package/validation/error.d.ts +50 -0
  110. package/package/validation/error.js +79 -0
  111. package/package/validation/index.d.ts +5 -0
  112. package/package/validation/index.js +86 -0
  113. package/package/validation/input-params.d.ts +15 -0
  114. package/package/validation/input-params.js +30 -0
  115. package/package/validation/override-functions.d.ts +3 -0
  116. package/package/validation/override-functions.js +40 -0
  117. package/package/validation/preset-tokens.json +23 -0
  118. package/package/validation/validator.d.ts +47 -0
  119. package/package/validation/validator.js +303 -0
  120. package/package.json +1 -1
  121. package/rate-limiting/background/fixed-frequency.d.ts +10 -0
  122. package/rate-limiting/background/fixed-frequency.js +37 -0
  123. package/rate-limiting/index.d.ts +54 -0
  124. package/rate-limiting/index.js +63 -0
  125. package/rate-limiting/metrics.d.ts +3 -0
  126. package/rate-limiting/metrics.js +44 -0
  127. package/rate-limiting/request/simple-counting.d.ts +20 -0
  128. package/rate-limiting/request/simple-counting.js +62 -0
  129. package/test.d.ts +1 -0
  130. package/test.js +6 -0
  131. package/transports/batch-warming.d.ts +34 -0
  132. package/transports/batch-warming.js +101 -0
  133. package/transports/index.d.ts +87 -0
  134. package/transports/index.js +87 -0
  135. package/transports/metrics.d.ts +21 -0
  136. package/transports/metrics.js +105 -0
  137. package/transports/rest.d.ts +43 -0
  138. package/transports/rest.js +129 -0
  139. package/transports/util.d.ts +8 -0
  140. package/transports/util.js +85 -0
  141. package/transports/websocket.d.ts +80 -0
  142. package/transports/websocket.js +169 -0
  143. package/util/expiring-sorted-set.d.ts +21 -0
  144. package/util/expiring-sorted-set.js +47 -0
  145. package/util/index.d.ts +11 -0
  146. package/util/index.js +35 -0
  147. package/util/logger.d.ts +42 -0
  148. package/util/logger.js +62 -0
  149. package/util/request.d.ts +55 -0
  150. package/util/request.js +2 -0
  151. package/validation/error.d.ts +50 -0
  152. package/validation/error.js +79 -0
  153. package/validation/index.d.ts +5 -0
  154. package/validation/index.js +86 -0
  155. package/validation/input-params.d.ts +15 -0
  156. package/validation/input-params.js +30 -0
  157. package/validation/override-functions.d.ts +3 -0
  158. package/validation/override-functions.js +40 -0
  159. package/validation/preset-tokens.json +23 -0
  160. package/validation/validator.d.ts +47 -0
  161. package/validation/validator.js +303 -0
  162. package/.c8rc.json +0 -3
  163. package/.eslintignore +0 -9
  164. package/.eslintrc.js +0 -96
  165. package/.github/README.MD +0 -17
  166. package/.github/actions/setup/action.yaml +0 -13
  167. package/.github/workflows/main.yaml +0 -39
  168. package/.github/workflows/publish.yaml +0 -17
  169. package/.prettierignore +0 -13
  170. package/.yarnrc +0 -0
  171. package/README.md +0 -103
  172. package/docker-compose.yaml +0 -35
  173. package/src/adapter.ts +0 -236
  174. package/src/background-executor.ts +0 -53
  175. package/src/cache/factory.ts +0 -28
  176. package/src/cache/index.ts +0 -236
  177. package/src/cache/local.ts +0 -73
  178. package/src/cache/metrics.ts +0 -112
  179. package/src/cache/redis.ts +0 -93
  180. package/src/config/index.ts +0 -501
  181. package/src/config/provider-limits.ts +0 -130
  182. package/src/examples/coingecko/batch-warming.ts +0 -79
  183. package/src/examples/coingecko/index.ts +0 -9
  184. package/src/examples/coingecko/rest.ts +0 -77
  185. package/src/examples/ncfx/config/index.ts +0 -12
  186. package/src/examples/ncfx/index.ts +0 -9
  187. package/src/examples/ncfx/websocket.ts +0 -100
  188. package/src/index.ts +0 -106
  189. package/src/metrics/constants.ts +0 -23
  190. package/src/metrics/index.ts +0 -116
  191. package/src/metrics/util.ts +0 -11
  192. package/src/rate-limiting/background/fixed-frequency.ts +0 -47
  193. package/src/rate-limiting/index.ts +0 -100
  194. package/src/rate-limiting/metrics.ts +0 -18
  195. package/src/rate-limiting/request/simple-counting.ts +0 -76
  196. package/src/test.ts +0 -5
  197. package/src/transports/batch-warming.ts +0 -121
  198. package/src/transports/index.ts +0 -173
  199. package/src/transports/metrics.ts +0 -95
  200. package/src/transports/rest.ts +0 -161
  201. package/src/transports/util.ts +0 -63
  202. package/src/transports/websocket.ts +0 -238
  203. package/src/util/expiring-sorted-set.ts +0 -52
  204. package/src/util/index.ts +0 -20
  205. package/src/util/logger.ts +0 -69
  206. package/src/util/request.ts +0 -115
  207. package/src/validation/error.ts +0 -116
  208. package/src/validation/index.ts +0 -101
  209. package/src/validation/input-params.ts +0 -45
  210. package/src/validation/override-functions.ts +0 -44
  211. package/src/validation/preset-tokens.json +0 -23
  212. package/src/validation/validator.ts +0 -384
  213. package/test/adapter.test.ts +0 -27
  214. package/test/background-executor.test.ts +0 -109
  215. package/test/cache/cache-key.test.ts +0 -96
  216. package/test/cache/helper.ts +0 -101
  217. package/test/cache/local.test.ts +0 -54
  218. package/test/cache/redis.test.ts +0 -89
  219. package/test/correlation.test.ts +0 -114
  220. package/test/index.test.ts +0 -37
  221. package/test/metrics/feed-id.test.ts +0 -33
  222. package/test/metrics/helper.ts +0 -14
  223. package/test/metrics/labels.test.ts +0 -36
  224. package/test/metrics/metrics.test.ts +0 -267
  225. package/test/metrics/redis-metrics.test.ts +0 -113
  226. package/test/metrics/warmer-metrics.test.ts +0 -192
  227. package/test/metrics/ws-metrics.test.ts +0 -225
  228. package/test/rate-limit-config.test.ts +0 -243
  229. package/test/transports/batch.test.ts +0 -465
  230. package/test/transports/rest.test.ts +0 -242
  231. package/test/transports/websocket.test.ts +0 -183
  232. package/test/tsconfig.json +0 -5
  233. package/test/util.ts +0 -76
  234. package/test/validation.test.ts +0 -169
  235. package/test.sh +0 -20
  236. package/tsconfig.json +0 -24
  237. package/typedoc.json +0 -6
package/adapter.d.ts ADDED
@@ -0,0 +1,88 @@
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> | undefined) => 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> | undefined) => Promise<InitializedAdapter>;
88
+ export {};
package/adapter.js ADDED
@@ -0,0 +1,112 @@
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;
@@ -0,0 +1,11 @@
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>;
@@ -0,0 +1,45 @@
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;
@@ -0,0 +1,6 @@
1
+ import { AdapterConfig } from '../config';
2
+ import { LocalCache } from './local';
3
+ import { RedisCache } from './redis';
4
+ export declare class CacheFactory {
5
+ static buildCache(config: AdapterConfig): LocalCache<unknown> | RedisCache<unknown> | undefined;
6
+ }
@@ -0,0 +1,57 @@
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;
@@ -0,0 +1,90 @@
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/cache/index.js ADDED
@@ -0,0 +1,169 @@
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;
@@ -0,0 +1,23 @@
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
+ }