@chainlink/external-adapter-framework 0.0.12 → 0.0.15

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 (220) hide show
  1. package/.eslintignore +1 -0
  2. package/.github/README.MD +35 -10
  3. package/.github/workflows/label.yaml +39 -0
  4. package/.github/workflows/publish.yaml +0 -3
  5. package/dist/examples/coingecko/test/e2e/adapter.test.ts.js +82953 -0
  6. package/dist/examples/coingecko/test/integration/adapter.test.ts.js +91672 -0
  7. package/dist/main.js +72703 -0
  8. package/jest.config.js +5 -0
  9. package/package.json +14 -3
  10. package/src/config/provider-limits.ts +14 -17
  11. package/src/examples/coingecko/src/config/index.ts +12 -0
  12. package/src/examples/coingecko/src/config/overrides.json +10826 -0
  13. package/src/examples/coingecko/src/cryptoUtils.ts +88 -0
  14. package/src/examples/coingecko/src/endpoint/coins.ts +54 -0
  15. package/src/examples/coingecko/src/endpoint/crypto-marketcap.ts +66 -0
  16. package/src/examples/coingecko/src/endpoint/crypto-volume.ts +66 -0
  17. package/src/examples/coingecko/src/endpoint/crypto.ts +63 -0
  18. package/src/examples/coingecko/src/endpoint/dominance.ts +40 -0
  19. package/src/examples/coingecko/src/endpoint/global-marketcap.ts +40 -0
  20. package/src/examples/coingecko/src/endpoint/index.ts +6 -0
  21. package/src/examples/coingecko/src/globalUtils.ts +78 -0
  22. package/src/examples/coingecko/src/index.ts +17 -0
  23. package/src/examples/coingecko/test/e2e/adapter.test.ts +278 -0
  24. package/src/examples/coingecko/test/integration/__snapshots__/adapter.test.ts.snap +15 -0
  25. package/src/examples/coingecko/test/integration/adapter.test.ts +281 -0
  26. package/src/examples/coingecko/test/integration/capturedRequests.json +1 -0
  27. package/src/examples/coingecko/test/integration/fixtures.ts +42 -0
  28. package/src/examples/{coingecko → coingecko-old}/batch-warming.ts +1 -0
  29. package/src/examples/{coingecko → coingecko-old}/index.ts +0 -0
  30. package/src/examples/{coingecko → coingecko-old}/rest.ts +0 -0
  31. package/src/transports/batch-warming.ts +7 -2
  32. package/src/transports/rest.ts +5 -1
  33. package/src/util/index.ts +1 -0
  34. package/src/util/recordRequests.ts +47 -0
  35. package/src/validation/overrideFunctions.ts +44 -0
  36. package/test/metrics/warmer-metrics.test.ts +1 -0
  37. package/test/{smoke.test.ts → smoke/smoke.test.ts} +13 -13
  38. package/{test-payload-fail.json → test/smoke/test-payload-fail.json} +0 -0
  39. package/{test-payload.js → test/smoke/test-payload.js} +0 -0
  40. package/{test-payload.json → test/smoke/test-payload.json} +0 -0
  41. package/test/transports/batch.test.ts +1 -0
  42. package/tsconfig.json +4 -1
  43. package/webpack.config.js +39 -5
  44. package/yarn-error.log +3778 -0
  45. package/dist/src/adapter.d.ts +0 -135
  46. package/dist/src/adapter.js +0 -145
  47. package/dist/src/background-executor.d.ts +0 -11
  48. package/dist/src/background-executor.js +0 -45
  49. package/dist/src/cache/factory.d.ts +0 -6
  50. package/dist/src/cache/factory.js +0 -55
  51. package/dist/src/cache/index.d.ts +0 -94
  52. package/dist/src/cache/index.js +0 -173
  53. package/dist/src/cache/local.d.ts +0 -23
  54. package/dist/src/cache/local.js +0 -83
  55. package/dist/src/cache/metrics.d.ts +0 -27
  56. package/dist/src/cache/metrics.js +0 -120
  57. package/dist/src/cache/redis.d.ts +0 -16
  58. package/dist/src/cache/redis.js +0 -100
  59. package/dist/src/chainlink-external-adapter-framework-0.0.6.tgz +0 -0
  60. package/dist/src/config/index.d.ts +0 -214
  61. package/dist/src/config/index.js +0 -380
  62. package/dist/src/config/provider-limits.d.ts +0 -31
  63. package/dist/src/config/provider-limits.js +0 -75
  64. package/dist/src/examples/bank-frick/accounts.d.ts +0 -39
  65. package/dist/src/examples/bank-frick/accounts.js +0 -192
  66. package/dist/src/examples/bank-frick/config/index.d.ts +0 -4
  67. package/dist/src/examples/bank-frick/config/index.js +0 -54
  68. package/dist/src/examples/bank-frick/index.d.ts +0 -2
  69. package/dist/src/examples/bank-frick/index.js +0 -15
  70. package/dist/src/examples/bank-frick/util.d.ts +0 -4
  71. package/dist/src/examples/bank-frick/util.js +0 -39
  72. package/dist/src/examples/coingecko/batch-warming.d.ts +0 -7
  73. package/dist/src/examples/coingecko/batch-warming.js +0 -53
  74. package/dist/src/examples/coingecko/index.d.ts +0 -2
  75. package/dist/src/examples/coingecko/index.js +0 -11
  76. package/dist/src/examples/coingecko/rest.d.ts +0 -12
  77. package/dist/src/examples/coingecko/rest.js +0 -51
  78. package/dist/src/examples/ncfx/config/index.d.ts +0 -12
  79. package/dist/src/examples/ncfx/config/index.js +0 -15
  80. package/dist/src/examples/ncfx/index.d.ts +0 -13
  81. package/dist/src/examples/ncfx/index.js +0 -11
  82. package/dist/src/examples/ncfx/websocket.d.ts +0 -47
  83. package/dist/src/examples/ncfx/websocket.js +0 -73
  84. package/dist/src/index.d.ts +0 -11
  85. package/dist/src/index.js +0 -128
  86. package/dist/src/metrics/constants.d.ts +0 -16
  87. package/dist/src/metrics/constants.js +0 -25
  88. package/dist/src/metrics/index.d.ts +0 -15
  89. package/dist/src/metrics/index.js +0 -122
  90. package/dist/src/metrics/util.d.ts +0 -7
  91. package/dist/src/metrics/util.js +0 -9
  92. package/dist/src/package/adapter.d.ts +0 -88
  93. package/dist/src/package/adapter.js +0 -112
  94. package/dist/src/package/background-executor.d.ts +0 -11
  95. package/dist/src/package/background-executor.js +0 -45
  96. package/dist/src/package/cache/factory.d.ts +0 -6
  97. package/dist/src/package/cache/factory.js +0 -57
  98. package/dist/src/package/cache/index.d.ts +0 -90
  99. package/dist/src/package/cache/index.js +0 -169
  100. package/dist/src/package/cache/local.d.ts +0 -23
  101. package/dist/src/package/cache/local.js +0 -83
  102. package/dist/src/package/cache/metrics.d.ts +0 -27
  103. package/dist/src/package/cache/metrics.js +0 -120
  104. package/dist/src/package/cache/redis.d.ts +0 -16
  105. package/dist/src/package/cache/redis.js +0 -100
  106. package/dist/src/package/config/index.d.ts +0 -195
  107. package/dist/src/package/config/index.js +0 -365
  108. package/dist/src/package/config/provider-limits.d.ts +0 -31
  109. package/dist/src/package/config/provider-limits.js +0 -76
  110. package/dist/src/package/examples/coingecko/batch-warming.d.ts +0 -2
  111. package/dist/src/package/examples/coingecko/batch-warming.js +0 -52
  112. package/dist/src/package/examples/coingecko/index.d.ts +0 -2
  113. package/dist/src/package/examples/coingecko/index.js +0 -10
  114. package/dist/src/package/examples/coingecko/rest.d.ts +0 -2
  115. package/dist/src/package/examples/coingecko/rest.js +0 -50
  116. package/dist/src/package/examples/ncfx/config/index.d.ts +0 -12
  117. package/dist/src/package/examples/ncfx/config/index.js +0 -15
  118. package/dist/src/package/examples/ncfx/index.d.ts +0 -2
  119. package/dist/src/package/examples/ncfx/index.js +0 -10
  120. package/dist/src/package/examples/ncfx/websocket.d.ts +0 -36
  121. package/dist/src/package/examples/ncfx/websocket.js +0 -72
  122. package/dist/src/package/index.d.ts +0 -12
  123. package/dist/src/package/index.js +0 -92
  124. package/dist/src/package/metrics/constants.d.ts +0 -16
  125. package/dist/src/package/metrics/constants.js +0 -25
  126. package/dist/src/package/metrics/index.d.ts +0 -15
  127. package/dist/src/package/metrics/index.js +0 -123
  128. package/dist/src/package/metrics/util.d.ts +0 -3
  129. package/dist/src/package/metrics/util.js +0 -9
  130. package/dist/src/package/package.json +0 -72
  131. package/dist/src/package/rate-limiting/background/fixed-frequency.d.ts +0 -10
  132. package/dist/src/package/rate-limiting/background/fixed-frequency.js +0 -37
  133. package/dist/src/package/rate-limiting/index.d.ts +0 -54
  134. package/dist/src/package/rate-limiting/index.js +0 -63
  135. package/dist/src/package/rate-limiting/metrics.d.ts +0 -3
  136. package/dist/src/package/rate-limiting/metrics.js +0 -44
  137. package/dist/src/package/rate-limiting/request/simple-counting.d.ts +0 -20
  138. package/dist/src/package/rate-limiting/request/simple-counting.js +0 -62
  139. package/dist/src/package/test.d.ts +0 -1
  140. package/dist/src/package/test.js +0 -6
  141. package/dist/src/package/transports/batch-warming.d.ts +0 -34
  142. package/dist/src/package/transports/batch-warming.js +0 -101
  143. package/dist/src/package/transports/index.d.ts +0 -87
  144. package/dist/src/package/transports/index.js +0 -87
  145. package/dist/src/package/transports/metrics.d.ts +0 -21
  146. package/dist/src/package/transports/metrics.js +0 -105
  147. package/dist/src/package/transports/rest.d.ts +0 -43
  148. package/dist/src/package/transports/rest.js +0 -129
  149. package/dist/src/package/transports/util.d.ts +0 -8
  150. package/dist/src/package/transports/util.js +0 -85
  151. package/dist/src/package/transports/websocket.d.ts +0 -80
  152. package/dist/src/package/transports/websocket.js +0 -169
  153. package/dist/src/package/util/expiring-sorted-set.d.ts +0 -21
  154. package/dist/src/package/util/expiring-sorted-set.js +0 -47
  155. package/dist/src/package/util/index.d.ts +0 -11
  156. package/dist/src/package/util/index.js +0 -35
  157. package/dist/src/package/util/logger.d.ts +0 -42
  158. package/dist/src/package/util/logger.js +0 -62
  159. package/dist/src/package/util/request.d.ts +0 -55
  160. package/dist/src/package/util/request.js +0 -2
  161. package/dist/src/package/validation/error.d.ts +0 -50
  162. package/dist/src/package/validation/error.js +0 -79
  163. package/dist/src/package/validation/index.d.ts +0 -5
  164. package/dist/src/package/validation/index.js +0 -86
  165. package/dist/src/package/validation/input-params.d.ts +0 -15
  166. package/dist/src/package/validation/input-params.js +0 -30
  167. package/dist/src/package/validation/override-functions.d.ts +0 -3
  168. package/dist/src/package/validation/override-functions.js +0 -40
  169. package/dist/src/package/validation/preset-tokens.json +0 -23
  170. package/dist/src/package/validation/validator.d.ts +0 -47
  171. package/dist/src/package/validation/validator.js +0 -303
  172. package/dist/src/package.json +0 -72
  173. package/dist/src/rate-limiting/background/fixed-frequency.d.ts +0 -11
  174. package/dist/src/rate-limiting/background/fixed-frequency.js +0 -35
  175. package/dist/src/rate-limiting/index.d.ts +0 -55
  176. package/dist/src/rate-limiting/index.js +0 -63
  177. package/dist/src/rate-limiting/metrics.d.ts +0 -3
  178. package/dist/src/rate-limiting/metrics.js +0 -44
  179. package/dist/src/rate-limiting/request/simple-counting.d.ts +0 -21
  180. package/dist/src/rate-limiting/request/simple-counting.js +0 -62
  181. package/dist/src/test.d.ts +0 -1
  182. package/dist/src/test.js +0 -6
  183. package/dist/src/transports/batch-warming.d.ts +0 -35
  184. package/dist/src/transports/batch-warming.js +0 -101
  185. package/dist/src/transports/index.d.ts +0 -70
  186. package/dist/src/transports/index.js +0 -87
  187. package/dist/src/transports/metrics.d.ts +0 -22
  188. package/dist/src/transports/metrics.js +0 -105
  189. package/dist/src/transports/rest.d.ts +0 -44
  190. package/dist/src/transports/rest.js +0 -131
  191. package/dist/src/transports/util.d.ts +0 -8
  192. package/dist/src/transports/util.js +0 -85
  193. package/dist/src/transports/websocket.d.ts +0 -80
  194. package/dist/src/transports/websocket.js +0 -166
  195. package/dist/src/util/expiring-sorted-set.d.ts +0 -21
  196. package/dist/src/util/expiring-sorted-set.js +0 -47
  197. package/dist/src/util/index.d.ts +0 -12
  198. package/dist/src/util/index.js +0 -35
  199. package/dist/src/util/logger.d.ts +0 -42
  200. package/dist/src/util/logger.js +0 -62
  201. package/dist/src/util/request.d.ts +0 -57
  202. package/dist/src/util/request.js +0 -2
  203. package/dist/src/util/subscription-set/expiring-sorted-set.d.ts +0 -22
  204. package/dist/src/util/subscription-set/expiring-sorted-set.js +0 -47
  205. package/dist/src/util/subscription-set/subscription-set.d.ts +0 -18
  206. package/dist/src/util/subscription-set/subscription-set.js +0 -19
  207. package/dist/src/util/test-payload-loader.d.ts +0 -25
  208. package/dist/src/util/test-payload-loader.js +0 -83
  209. package/dist/src/validation/error.d.ts +0 -50
  210. package/dist/src/validation/error.js +0 -79
  211. package/dist/src/validation/index.d.ts +0 -5
  212. package/dist/src/validation/index.js +0 -91
  213. package/dist/src/validation/input-params.d.ts +0 -15
  214. package/dist/src/validation/input-params.js +0 -30
  215. package/dist/src/validation/override-functions.d.ts +0 -3
  216. package/dist/src/validation/override-functions.js +0 -40
  217. package/dist/src/validation/preset-tokens.json +0 -23
  218. package/dist/src/validation/validator.d.ts +0 -47
  219. package/dist/src/validation/validator.js +0 -303
  220. package/src/test.ts +0 -5
@@ -1,131 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.RestTransport = void 0;
27
- const util_1 = require("../util");
28
- const error_1 = require("../validation/error");
29
- const util_2 = require("./util");
30
- const rateLimitMetrics = __importStar(require("../rate-limiting/metrics"));
31
- const IN_FLIGHT_PREFIX = 'InFlight';
32
- const logger = (0, util_1.makeLogger)('RestTransport');
33
- /**
34
- * Transport implementation that takes incoming requests, transforms them into a DataProvider request,
35
- * and executes that request returning the response immediately from the `setup` function.
36
- * Optionally, setting the `coalescing` option to `true` will make it so once a request is in flight,
37
- * new adapter requests for the same feed will not trigger a new one, but return an empty promise from
38
- * the setup instead so the normal cache polling mechanism is used.
39
- *
40
- * @typeParam AdapterParams - interface for the adapter request body
41
- * @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
42
- * @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
43
- */
44
- class RestTransport {
45
- constructor(config) {
46
- this.config = config;
47
- }
48
- async initialize(dependencies) {
49
- this.inFlightPrefix = `${IN_FLIGHT_PREFIX}-`;
50
- this.cache = dependencies.cache;
51
- this.rateLimiter = dependencies.requestRateLimiter;
52
- }
53
- async hasBeenSetUp(req) {
54
- if (!this.config.options.coalescing) {
55
- return false;
56
- }
57
- // Check if request is in flight
58
- const inFlight = await this.cache.get(this.inFlightPrefix + req.requestContext.cacheKey);
59
- if (inFlight) {
60
- logger.debug('Request is in flight, transport has been set up');
61
- return true;
62
- }
63
- else {
64
- logger.debug('Request not in flight, transport not set up');
65
- return false;
66
- }
67
- }
68
- async waitUntilUnderRateLimit(options, retry = 0) {
69
- if (this.rateLimiter.isUnderLimits()) {
70
- logger.trace('Incoming request would not be under limits, moving on');
71
- return;
72
- }
73
- if (retry >= options.maxRetries) {
74
- throw new error_1.AdapterError({
75
- statusCode: 504,
76
- message: `REST Transport timed out while waiting for rate limit availability (max retries: ${options.maxRetries})`,
77
- });
78
- }
79
- logger.debug(`Request would be over rate limits, sleeping for ${options.msBetweenRetries}`);
80
- await (0, util_1.sleep)(options.msBetweenRetries);
81
- await this.waitUntilUnderRateLimit(options, retry + 1);
82
- }
83
- async setup(req, config) {
84
- if (this.config.options.coalescing) {
85
- logger.debug('Setting up rest transport, setting request in flight in cache');
86
- // TODO: Should this use a separate cache?
87
- // TODO: Set viable ttl to approximate timeout from API
88
- // TODO: Make this ttl configurable
89
- await this.cache.set(this.inFlightPrefix + req.requestContext.cacheKey, true, 2000); // Can't use Infinity for things like Redis
90
- }
91
- const request = await this.config.prepareRequest(req, config);
92
- logger.trace('Check if we are under rate limits to perform request');
93
- await this.waitUntilUnderRateLimit({
94
- maxRetries: config.REST_TRANSPORT_MAX_RATE_LIMIT_RETRIES,
95
- msBetweenRetries: config.REST_TRANSPORT_MS_BETWEEN_RATE_LIMIT_RETRIES,
96
- });
97
- logger.trace('Sending request to data provider...');
98
- const providerResponse = await (0, util_2.axiosRequest)(request);
99
- logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`); // TODO: Sensitive data?
100
- const parsedResponse = await this.config.parseResponse(req, providerResponse, config);
101
- if (config.METRICS_ENABLED && config.EXPERIMENTAL_METRICS_ENABLED) {
102
- // TODO: Potentially create function to add all telemetry data
103
- parsedResponse.maxAge = Date.now() + config.CACHE_MAX_AGE;
104
- parsedResponse.meta = {
105
- metrics: { feedId: req.requestContext.meta?.metrics?.feedId || 'N/A' },
106
- };
107
- }
108
- logger.debug('Setting provider response in cache');
109
- await this.cache.set(req.requestContext.cacheKey, parsedResponse, config.CACHE_MAX_AGE);
110
- // Record cost of data provider call
111
- const cost = rateLimitMetrics.retrieveCost(providerResponse.data);
112
- rateLimitMetrics.rateLimitCreditsSpentTotal
113
- .labels({
114
- feed_id: req.requestContext.meta?.metrics?.feedId || 'N/A',
115
- participant_id: req.requestContext.cacheKey,
116
- })
117
- .inc(cost);
118
- // Update cacheHit flag in request meta for metrics use
119
- req.requestContext.meta = {
120
- ...req.requestContext.meta,
121
- metrics: { ...req.requestContext.meta?.metrics, cacheHit: false },
122
- };
123
- // TODO: move this to a try/catch/finally
124
- if (this.config.options.coalescing) {
125
- logger.debug('Set provider response in cache, removing in flight from cache');
126
- await this.cache.delete(this.inFlightPrefix);
127
- }
128
- return parsedResponse;
129
- }
130
- }
131
- exports.RestTransport = RestTransport;
@@ -1,8 +0,0 @@
1
- import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
- /**
3
- * Performs axios request along with metrics recording and error handling
4
- *
5
- * @param request - axios request config
6
- * @returns axios response for the request
7
- */
8
- export declare function axiosRequest<ProviderRequestBody, ProviderResponseBody>(request: AxiosRequestConfig<ProviderRequestBody>): Promise<AxiosResponse<ProviderResponseBody>>;
@@ -1,85 +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.axiosRequest = void 0;
30
- const axios_1 = __importDefault(require("axios"));
31
- const error_1 = require("../validation/error");
32
- const transportMetrics = __importStar(require("./metrics"));
33
- /**
34
- * Performs axios request along with metrics recording and error handling
35
- *
36
- * @param request - axios request config
37
- * @returns axios response for the request
38
- */
39
- async function axiosRequest(request) {
40
- const responseTimer = transportMetrics.dataProviderRequestDurationSeconds.startTimer();
41
- let providerResponse;
42
- try {
43
- providerResponse = await axios_1.default.request(request);
44
- }
45
- catch (e) {
46
- const error = e;
47
- // Request error
48
- let providerStatusCode;
49
- let adapterError;
50
- if (error.code === 'ECONNABORTED') {
51
- adapterError = new error_1.AdapterTimeoutError({});
52
- providerStatusCode = error?.response?.status ?? 504;
53
- adapterError.name = 'Data Provider Request Timeout error';
54
- }
55
- else if (error?.response?.status) {
56
- adapterError = new error_1.AdapterDataProviderError({});
57
- providerStatusCode = error?.response?.status;
58
- }
59
- else {
60
- adapterError = new error_1.AdapterConnectionError({});
61
- providerStatusCode = 0; // 0 -> connection error
62
- }
63
- // Record count of failed data provider request
64
- transportMetrics.dataProviderRequests
65
- .labels(transportMetrics.dataProviderMetricsLabel(providerStatusCode, request.method))
66
- .inc();
67
- adapterError.statusCode = 200;
68
- adapterError.providerStatusCode = providerStatusCode;
69
- adapterError.message = error?.message;
70
- adapterError.cause = error;
71
- adapterError.errorResponse = error?.response?.data;
72
- adapterError.url = request.url;
73
- throw adapterError;
74
- }
75
- finally {
76
- // Record time taken for data provider request for success or failure
77
- responseTimer();
78
- }
79
- // Record count of successful data provider requests
80
- transportMetrics.dataProviderRequests
81
- .labels(transportMetrics.dataProviderMetricsLabel(providerResponse.status, request.method))
82
- .inc();
83
- return providerResponse;
84
- }
85
- exports.axiosRequest = axiosRequest;
@@ -1,80 +0,0 @@
1
- import WebSocket from 'ws';
2
- import { AdapterContext, AdapterDependencies } from '../adapter';
3
- import { Cache } from '../cache';
4
- import { AdapterConfig, SettingsMap } from '../config';
5
- import { BackgroundExecuteRateLimiter } from '../rate-limiting';
6
- import { SubscriptionSet } from '../util';
7
- import { AdapterRequest, ProviderResult } from '../util/request';
8
- import { Transport } from './';
9
- declare type WebSocketClass = new (url: string, protocols?: string | string[] | undefined) => WebSocket;
10
- export declare class WebSocketClassProvider {
11
- static ctor: WebSocketClass;
12
- static set(ctor: WebSocketClass): void;
13
- static get(): WebSocketClass;
14
- }
15
- /**
16
- * Config object that is provided to the WebSocketTransport constructor.
17
- */
18
- export interface WebSocketTransportConfig<AdapterParams, ProviderDataMessage, CustomSettings extends SettingsMap> {
19
- /** Endpoint to which to open the WS connection*/
20
- url: string;
21
- /** Map of handlers for different WS lifecycle events */
22
- handlers: {
23
- /**
24
- * Handles when the WS is successfully opened
25
- *
26
- * @param wsConnection - the WebSocket with an established connection
27
- * @returns an empty Promise, or void
28
- */
29
- open: (wsConnection: WebSocket, context: AdapterContext<CustomSettings>) => Promise<void> | void;
30
- /**
31
- * Handles when the WS receives a message
32
- *
33
- * @param message - the message received by the WS
34
- * @param context - the background context for the Adapter
35
- * @returns a list of cache entries of adapter responses to set in the cache
36
- */
37
- message: (message: ProviderDataMessage, context: AdapterContext<CustomSettings>) => ProviderResult<AdapterParams>[];
38
- };
39
- /** Map of "builders", functions that will be used to prepare specific WS messages */
40
- builders: {
41
- /**
42
- * Builds a WS message that will be sent to subscribe to a specific feed
43
- *
44
- * @param params - the body of the adapter request
45
- * @returns the WS message (can be any type as long as the [[WebSocket]] doesn't complain)
46
- */
47
- subscribeMessage: (params: AdapterParams) => unknown;
48
- /**
49
- * Builds a WS message that will be sent to unsubscribe to a specific feed
50
- *
51
- * @param params - the body of the adapter request
52
- * @returns the WS message (can be any type as long as the [[WebSocket]] doesn't complain)
53
- */
54
- unsubscribeMessage: (params: AdapterParams) => unknown;
55
- };
56
- }
57
- /**
58
- * Transport implementation that takes incoming requests, adds them to an [[subscriptionSet]] and,
59
- * through a WebSocket connection, subscribes to the relevant feeds to populate the cache.
60
- *
61
- * @typeParam AdapterParams - interface for the adapter request body
62
- * @typeParam ProviderDataMessage - interface for a WS message containing processable data (i.e. not part of open/close/login/etc)
63
- */
64
- export declare class WebSocketTransport<AdapterParams, ProviderDataMessage, CustomSettings extends SettingsMap> implements Transport<AdapterParams, null, CustomSettings> {
65
- private config;
66
- cache: Cache;
67
- rateLimiter: BackgroundExecuteRateLimiter;
68
- subscriptionSet: SubscriptionSet<AdapterParams>;
69
- localSubscriptions: AdapterParams[];
70
- wsConnection: WebSocket;
71
- constructor(config: WebSocketTransportConfig<AdapterParams, ProviderDataMessage, CustomSettings>);
72
- initialize(dependencies: AdapterDependencies): Promise<void>;
73
- hasBeenSetUp(req: AdapterRequest<AdapterParams>): Promise<boolean>;
74
- setup(req: AdapterRequest<AdapterParams>, config: AdapterConfig<CustomSettings>): Promise<void>;
75
- serializeMessage(payload: unknown): string;
76
- deserializeMessage(data: WebSocket.Data): ProviderDataMessage;
77
- establishWsConnection(context: AdapterContext<CustomSettings>): Promise<unknown>;
78
- backgroundExecute(context: AdapterContext<CustomSettings>): Promise<number>;
79
- }
80
- export {};
@@ -1,166 +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.WebSocketTransport = exports.WebSocketClassProvider = void 0;
30
- const ws_1 = __importDefault(require("ws"));
31
- const util_1 = require("../util");
32
- const _1 = require("./");
33
- const transportMetrics = __importStar(require("./metrics"));
34
- const logger = (0, util_1.makeLogger)('WebSocketTransport');
35
- class WebSocketClassProvider {
36
- static set(ctor) {
37
- this.ctor = ctor;
38
- }
39
- static get() {
40
- return this.ctor;
41
- }
42
- }
43
- exports.WebSocketClassProvider = WebSocketClassProvider;
44
- WebSocketClassProvider.ctor = ws_1.default;
45
- /**
46
- * Transport implementation that takes incoming requests, adds them to an [[subscriptionSet]] and,
47
- * through a WebSocket connection, subscribes to the relevant feeds to populate the cache.
48
- *
49
- * @typeParam AdapterParams - interface for the adapter request body
50
- * @typeParam ProviderDataMessage - interface for a WS message containing processable data (i.e. not part of open/close/login/etc)
51
- */
52
- class WebSocketTransport {
53
- constructor(config) {
54
- this.config = config;
55
- // The double sets serve to create a simple polling mechanism instead of needing a subscription
56
- // This one would not; this is always local state
57
- this.localSubscriptions = [];
58
- }
59
- async initialize(dependencies) {
60
- this.cache = dependencies.cache;
61
- this.rateLimiter = dependencies.backgroundExecuteRateLimiter;
62
- this.subscriptionSet = dependencies.subscriptionSetFactory.buildSet();
63
- }
64
- async hasBeenSetUp(req) {
65
- return !!(await this.subscriptionSet.get(req.requestContext.cacheKey));
66
- }
67
- async setup(req, config) {
68
- logger.debug(`Adding entry to subscription set: [${req.requestContext.cacheKey}] = ${req.requestContext.data}`);
69
- await this.subscriptionSet.add(req.requestContext.cacheKey, req.requestContext.data, config.WS_SUBSCRIPTION_TTL);
70
- }
71
- // TODO: Maybe we don't do this, and leave the preparation on the adapter's side?
72
- // TODO: Maybe we store adapter params pre-prepared? That would be more efficient
73
- // Assuming always JSON payloads for now, makes it all cleaner
74
- serializeMessage(payload) {
75
- return typeof payload === 'string' ? payload : JSON.stringify(payload);
76
- }
77
- deserializeMessage(data) {
78
- return JSON.parse(data.toString());
79
- }
80
- establishWsConnection(context) {
81
- return new Promise((resolve) => {
82
- const ctor = WebSocketClassProvider.get();
83
- this.wsConnection = new ctor(this.config.url);
84
- this.wsConnection.addEventListener('open', async (event) => {
85
- logger.debug(`Opened websocket connection. (event type ${event.type})`);
86
- await this.config.handlers.open(this.wsConnection, context);
87
- logger.debug('Successfully executed connection opened handler');
88
- // Record active ws connections by incrementing count on open
89
- // Using URL in label since connection_key is removed from v3
90
- transportMetrics.wsConnectionActive.inc();
91
- resolve(true);
92
- });
93
- this.wsConnection.addEventListener('message', async (event) => {
94
- // TODO: Assuming JSON always, maybe use BSON also?
95
- const parsed = this.deserializeMessage(event.data);
96
- logger.trace(`Got ws message: ${parsed}`);
97
- const results = this.config.handlers.message(parsed, context);
98
- if (Array.isArray(results)) {
99
- const responses = (0, _1.buildCacheEntriesFromResults)(results, context);
100
- logger.trace(`Writing ${responses.length} responses to cache`);
101
- await this.cache.setMany(responses, context.adapterConfig.CACHE_MAX_AGE);
102
- }
103
- });
104
- this.wsConnection.addEventListener('error', async (event) => {
105
- // Record connection error count
106
- transportMetrics.wsConnectionErrors
107
- .labels(transportMetrics.connectionErrorLabels(event.message))
108
- .inc();
109
- });
110
- this.wsConnection.addEventListener('close', (event) => {
111
- logger.debug(`Closed websocket connection. Code: ${event.code} ; reason: ${event.reason?.toString()}`);
112
- // Record active ws connections by decrementing count on close
113
- // Using URL in label since connection_key is removed from v3
114
- transportMetrics.wsConnectionActive.dec();
115
- });
116
- });
117
- }
118
- // Unlike cache warming, this execute will manage subscriptions
119
- async backgroundExecute(context) {
120
- logger.debug('Starting background execute, getting subscriptions from sorted set');
121
- const desiredSubs = await this.subscriptionSet.getAll();
122
- logger.debug('Generating delta (subscribes & unsubscribes)');
123
- // TODO: More efficient algorithm, this is really easy to read, but high(er) time complexity
124
- const subscribeParams = desiredSubs.filter((s) => !this.localSubscriptions.includes(s));
125
- const subscribes = subscribeParams
126
- .map(this.config.builders.subscribeMessage)
127
- .map(this.serializeMessage);
128
- const unsubscribeParams = this.localSubscriptions.filter((s) => !desiredSubs.includes(s));
129
- const unsubscribes = unsubscribeParams
130
- .map(this.config.builders.unsubscribeMessage)
131
- .map(this.serializeMessage);
132
- logger.debug(`${subscribes.length} new subscriptions; ${unsubscribes.length} to unsubscribe`);
133
- if (subscribes.length) {
134
- logger.trace(`Will subscribe to: ${subscribes}`);
135
- }
136
- if (unsubscribes.length) {
137
- logger.trace(`Will unsubscribe to: ${unsubscribes}`);
138
- }
139
- // New subs && no connection -> connect -> add subs
140
- // No new subs && no connection -> skip
141
- // New subs && connection -> add subs
142
- // No new subs && connection -> unsubs only
143
- if (!subscribes.length && !this.wsConnection) {
144
- logger.debug('No entries in subscription set and no established connection, skipping');
145
- return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name);
146
- }
147
- if (!this.wsConnection && subscribes.length) {
148
- logger.debug('No established connection and new subscriptions available, connecting to WS');
149
- await this.establishWsConnection(context);
150
- }
151
- // TODO: Close connection at some point?
152
- logger.debug('Sending subs/unsubs if there are any');
153
- const messages = unsubscribes.concat(subscribes);
154
- for (const message of messages) {
155
- logger.trace(`Sending message: ${JSON.stringify(message)}`);
156
- this.wsConnection.send(message);
157
- }
158
- // Record WS message and subscription metrics
159
- transportMetrics.recordWsMessageMetrics(context, subscribeParams, unsubscribeParams);
160
- logger.debug('Setting local state to cache value');
161
- this.localSubscriptions = desiredSubs;
162
- logger.debug('Background execute complete');
163
- return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name);
164
- }
165
- }
166
- exports.WebSocketTransport = WebSocketTransport;
@@ -1,21 +0,0 @@
1
- /**
2
- * An object describing an entry in the expiring sorted set.
3
- * @typeParam T - the type of the entry's value
4
- */
5
- interface ExpiringSortedSetEntry<T> {
6
- value: T;
7
- expirationTimestamp: number;
8
- }
9
- /**
10
- * This class implements a set of unique items, each of which has an expiration timestamp.
11
- * On reads, items that have expired will be deleted from the set and not returned.
12
- *
13
- * @typeParam T - the type of the set entries' values
14
- */
15
- export declare class ExpiringSortedSet<T> {
16
- map: Map<string, ExpiringSortedSetEntry<T>>;
17
- add(key: string, value: T, ttl: number): void;
18
- get(key: string): T | undefined;
19
- getAll(): T[];
20
- }
21
- export {};
@@ -1,47 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ExpiringSortedSet = void 0;
4
- /**
5
- * This class implements a set of unique items, each of which has an expiration timestamp.
6
- * On reads, items that have expired will be deleted from the set and not returned.
7
- *
8
- * @typeParam T - the type of the set entries' values
9
- */
10
- class ExpiringSortedSet {
11
- constructor() {
12
- this.map = new Map();
13
- }
14
- add(key, value, ttl) {
15
- this.map.set(key, {
16
- value,
17
- expirationTimestamp: Date.now() + ttl,
18
- });
19
- }
20
- get(key) {
21
- const entry = this.map.get(key);
22
- if (!entry) {
23
- return;
24
- }
25
- else if (entry.expirationTimestamp < Date.now()) {
26
- return entry.value;
27
- }
28
- else {
29
- this.map.delete(key);
30
- }
31
- }
32
- getAll() {
33
- const results = [];
34
- const now = Date.now();
35
- // Since we're iterating, might as well prune here
36
- for (const [key, entry] of this.map.entries()) {
37
- if (entry.expirationTimestamp < now) {
38
- this.map.delete(key); // In theory, this shouldn't happen frequently for feeds
39
- }
40
- else {
41
- results.push(entry.value);
42
- }
43
- }
44
- return results;
45
- }
46
- }
47
- exports.ExpiringSortedSet = ExpiringSortedSet;
@@ -1,12 +0,0 @@
1
- export * from './request';
2
- export * from './logger';
3
- export * from './subscription-set/subscription-set';
4
- /**
5
- * Sleeps for the provided number of milliseconds
6
- * @param ms - The number of milliseconds to sleep for
7
- * @returns a Promise that resolves once the specified time passes
8
- */
9
- export declare const sleep: (ms: number) => Promise<void>;
10
- export declare const isObject: (o: unknown) => boolean;
11
- export declare const isArray: (o: unknown) => boolean;
12
- export declare type PromiseOrValue<T> = Promise<T> | T;
@@ -1,35 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.isArray = exports.isObject = exports.sleep = void 0;
18
- __exportStar(require("./request"), exports);
19
- __exportStar(require("./logger"), exports);
20
- __exportStar(require("./subscription-set/subscription-set"), exports);
21
- /**
22
- * Sleeps for the provided number of milliseconds
23
- * @param ms - The number of milliseconds to sleep for
24
- * @returns a Promise that resolves once the specified time passes
25
- */
26
- const sleep = (ms) => {
27
- return new Promise((resolve) => {
28
- setTimeout(resolve, ms);
29
- });
30
- };
31
- exports.sleep = sleep;
32
- const isObject = (o) => o !== null && typeof o === 'object' && Array.isArray(o) === false;
33
- exports.isObject = isObject;
34
- const isArray = (o) => o !== null && typeof o === 'object' && Array.isArray(o);
35
- exports.isArray = isArray;
@@ -1,42 +0,0 @@
1
- /// <reference types="node" />
2
- import pino from 'pino';
3
- import { AdapterRequest } from './request';
4
- import { FastifyReply, HookHandlerDoneFunction } from 'fastify';
5
- import { AsyncLocalStorage } from 'node:async_hooks';
6
- export declare const asyncLocalStorage: AsyncLocalStorage<unknown>;
7
- export declare type Store = {
8
- correlationId: string;
9
- };
10
- /**
11
- * Instead of using a global logger instance, we want to force using a child logger
12
- * with a specific layer set in it, so that we can filter logs by where they're output from.
13
- *
14
- * Details on what each log level represents:
15
- * "trace": Forensic debugging of issues on a local machine.
16
- * "debug": Detailed logging level to get more context from users on their environments.
17
- * "info": High-level informational messages, to describe at a glance the high level state of the system.
18
- * "warn": A mild error occurred that might require non-urgent action.
19
- * "error": An unexpected error occurred during the regular operation of a well-maintained EA.
20
- * "fatal": The EA encountered an unrecoverable problem and had to exit.
21
- *
22
- * Full reference this is based on can be found at
23
- * https://github.com/smartcontractkit/documentation/blob/main/docs/Node%20Operators/configuration-variables.md#log_level
24
- *
25
- * @param layer - the layer name to include in the logs (e.g. "SomeMiddleware", "RedisCache", etc.)
26
- * @returns a layer specific logger
27
- */
28
- export declare const makeLogger: (layer: string) => pino.Logger<{
29
- level: string;
30
- mixin(): {};
31
- transport: {
32
- target: string;
33
- options: {
34
- levelFirst: boolean;
35
- levelLabel: string;
36
- ignore: string;
37
- messageFormat: string;
38
- translateTime: string;
39
- };
40
- } | undefined;
41
- } & pino.ChildLoggerOptions>;
42
- export declare const loggingContextMiddleware: (req: AdapterRequest, res: FastifyReply, done: HookHandlerDoneFunction) => void;