@chainlink/external-adapter-framework 0.5.0 → 0.5.2

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 (192) hide show
  1. package/adapter/basic.d.ts +90 -0
  2. package/adapter/basic.js +325 -0
  3. package/adapter/basic.js.map +1 -0
  4. package/adapter/endpoint.d.ts +17 -0
  5. package/adapter/endpoint.js +20 -0
  6. package/adapter/endpoint.js.map +1 -0
  7. package/adapter/index.d.ts +4 -0
  8. package/adapter/index.js +21 -0
  9. package/adapter/index.js.map +1 -0
  10. package/adapter/price.d.ts +77 -0
  11. package/adapter/price.js +88 -0
  12. package/adapter/price.js.map +1 -0
  13. package/adapter/types.d.ts +124 -0
  14. package/adapter/types.js +3 -0
  15. package/adapter/types.js.map +1 -0
  16. package/background-executor.d.ts +9 -0
  17. package/background-executor.js +97 -0
  18. package/background-executor.js.map +1 -0
  19. package/cache/factory.d.ts +6 -0
  20. package/cache/factory.js +24 -0
  21. package/cache/factory.js.map +1 -0
  22. package/cache/index.d.ts +87 -0
  23. package/cache/index.js +133 -0
  24. package/cache/index.js.map +1 -0
  25. package/cache/local.d.ts +23 -0
  26. package/cache/local.js +84 -0
  27. package/cache/local.js.map +1 -0
  28. package/cache/metrics.d.ts +27 -0
  29. package/cache/metrics.js +121 -0
  30. package/cache/metrics.js.map +1 -0
  31. package/cache/redis.d.ts +16 -0
  32. package/cache/redis.js +101 -0
  33. package/cache/redis.js.map +1 -0
  34. package/config/index.d.ts +298 -0
  35. package/config/index.js +359 -0
  36. package/config/index.js.map +1 -0
  37. package/config/provider-limits.d.ts +27 -0
  38. package/config/provider-limits.js +75 -0
  39. package/config/provider-limits.js.map +1 -0
  40. package/examples/bank-frick/accounts.d.ts +45 -0
  41. package/examples/bank-frick/accounts.js +203 -0
  42. package/examples/bank-frick/accounts.js.map +1 -0
  43. package/examples/bank-frick/config/index.d.ts +17 -0
  44. package/examples/bank-frick/config/index.js +55 -0
  45. package/examples/bank-frick/config/index.js.map +1 -0
  46. package/examples/bank-frick/index.d.ts +2 -0
  47. package/examples/bank-frick/index.js +16 -0
  48. package/examples/bank-frick/index.js.map +1 -0
  49. package/examples/bank-frick/util.d.ts +4 -0
  50. package/examples/bank-frick/util.js +40 -0
  51. package/examples/bank-frick/util.js.map +1 -0
  52. package/examples/coingecko/src/config/index.d.ts +2 -0
  53. package/examples/coingecko/src/config/index.js +6 -0
  54. package/examples/coingecko/src/config/index.js.map +1 -0
  55. package/examples/coingecko/src/config/overrides.json +10825 -0
  56. package/examples/coingecko/src/crypto-utils.d.ts +62 -0
  57. package/examples/coingecko/src/crypto-utils.js +60 -0
  58. package/examples/coingecko/src/crypto-utils.js.map +1 -0
  59. package/examples/coingecko/src/endpoint/coins.d.ts +26 -0
  60. package/examples/coingecko/src/endpoint/coins.js +37 -0
  61. package/examples/coingecko/src/endpoint/coins.js.map +1 -0
  62. package/examples/coingecko/src/endpoint/crypto-marketcap.d.ts +3 -0
  63. package/examples/coingecko/src/endpoint/crypto-marketcap.js +30 -0
  64. package/examples/coingecko/src/endpoint/crypto-marketcap.js.map +1 -0
  65. package/examples/coingecko/src/endpoint/crypto-volume.d.ts +3 -0
  66. package/examples/coingecko/src/endpoint/crypto-volume.js +30 -0
  67. package/examples/coingecko/src/endpoint/crypto-volume.js.map +1 -0
  68. package/examples/coingecko/src/endpoint/crypto.d.ts +3 -0
  69. package/examples/coingecko/src/endpoint/crypto.js +28 -0
  70. package/examples/coingecko/src/endpoint/crypto.js.map +1 -0
  71. package/examples/coingecko/src/endpoint/dominance.d.ts +3 -0
  72. package/examples/coingecko/src/endpoint/dominance.js +28 -0
  73. package/examples/coingecko/src/endpoint/dominance.js.map +1 -0
  74. package/examples/coingecko/src/endpoint/global-marketcap.d.ts +3 -0
  75. package/examples/coingecko/src/endpoint/global-marketcap.js +28 -0
  76. package/examples/coingecko/src/endpoint/global-marketcap.js.map +1 -0
  77. package/examples/coingecko/src/endpoint/index.d.ts +6 -0
  78. package/examples/coingecko/src/endpoint/index.js +16 -0
  79. package/examples/coingecko/src/endpoint/index.js.map +1 -0
  80. package/examples/coingecko/src/global-utils.d.ts +42 -0
  81. package/examples/coingecko/src/global-utils.js +47 -0
  82. package/examples/coingecko/src/global-utils.js.map +1 -0
  83. package/examples/coingecko/src/index.d.ts +4 -0
  84. package/examples/coingecko/src/index.js +19 -0
  85. package/examples/coingecko/src/index.js.map +1 -0
  86. package/examples/cryptocompare/src/config/index.d.ts +2 -0
  87. package/examples/cryptocompare/src/config/index.js +6 -0
  88. package/examples/cryptocompare/src/config/index.js.map +1 -0
  89. package/examples/cryptocompare/src/endpoints/crypto.d.ts +40 -0
  90. package/examples/cryptocompare/src/endpoints/crypto.js +54 -0
  91. package/examples/cryptocompare/src/endpoints/crypto.js.map +1 -0
  92. package/examples/cryptocompare/src/endpoints/index.d.ts +1 -0
  93. package/examples/cryptocompare/src/endpoints/index.js +6 -0
  94. package/examples/cryptocompare/src/endpoints/index.js.map +1 -0
  95. package/examples/cryptocompare/src/index.d.ts +4 -0
  96. package/examples/cryptocompare/src/index.js +14 -0
  97. package/examples/cryptocompare/src/index.js.map +1 -0
  98. package/examples/genesis/config/index.d.ts +7 -0
  99. package/examples/genesis/config/index.js +11 -0
  100. package/examples/genesis/config/index.js.map +1 -0
  101. package/examples/genesis/index.d.ts +2 -0
  102. package/examples/genesis/index.js +13 -0
  103. package/examples/genesis/index.js.map +1 -0
  104. package/examples/genesis/sseStream.d.ts +27 -0
  105. package/examples/genesis/sseStream.js +149 -0
  106. package/examples/genesis/sseStream.js.map +1 -0
  107. package/index.d.ts +17 -0
  108. package/index.js +174 -0
  109. package/index.js.map +1 -0
  110. package/metrics/constants.d.ts +16 -0
  111. package/metrics/constants.js +26 -0
  112. package/metrics/constants.js.map +1 -0
  113. package/metrics/index.d.ts +19 -0
  114. package/metrics/index.js +139 -0
  115. package/metrics/index.js.map +1 -0
  116. package/metrics/util.d.ts +7 -0
  117. package/metrics/util.js +10 -0
  118. package/metrics/util.js.map +1 -0
  119. package/package.json +50 -42
  120. package/rate-limiting/background/fixed-frequency.d.ts +10 -0
  121. package/rate-limiting/background/fixed-frequency.js +36 -0
  122. package/rate-limiting/background/fixed-frequency.js.map +1 -0
  123. package/rate-limiting/index.d.ts +56 -0
  124. package/rate-limiting/index.js +86 -0
  125. package/rate-limiting/index.js.map +1 -0
  126. package/rate-limiting/metrics.d.ts +3 -0
  127. package/rate-limiting/metrics.js +45 -0
  128. package/rate-limiting/metrics.js.map +1 -0
  129. package/rate-limiting/request/simple-counting.d.ts +20 -0
  130. package/rate-limiting/request/simple-counting.js +63 -0
  131. package/rate-limiting/request/simple-counting.js.map +1 -0
  132. package/transports/batch-warming.d.ts +53 -0
  133. package/transports/batch-warming.js +136 -0
  134. package/transports/batch-warming.js.map +1 -0
  135. package/transports/index.d.ts +108 -0
  136. package/transports/index.js +56 -0
  137. package/transports/index.js.map +1 -0
  138. package/transports/metrics.d.ts +25 -0
  139. package/transports/metrics.js +122 -0
  140. package/transports/metrics.js.map +1 -0
  141. package/transports/rest.d.ts +68 -0
  142. package/transports/rest.js +131 -0
  143. package/transports/rest.js.map +1 -0
  144. package/transports/routing.d.ts +21 -0
  145. package/transports/routing.js +50 -0
  146. package/transports/routing.js.map +1 -0
  147. package/transports/sse.d.ts +61 -0
  148. package/transports/sse.js +97 -0
  149. package/transports/sse.js.map +1 -0
  150. package/transports/util.d.ts +9 -0
  151. package/transports/util.js +87 -0
  152. package/transports/util.js.map +1 -0
  153. package/transports/websocket.d.ts +95 -0
  154. package/transports/websocket.js +164 -0
  155. package/transports/websocket.js.map +1 -0
  156. package/util/censor/censor-list.d.ts +9 -0
  157. package/util/censor/censor-list.js +13 -0
  158. package/util/censor/censor-list.js.map +1 -0
  159. package/util/index.d.ts +13 -0
  160. package/util/index.js +38 -0
  161. package/util/index.js.map +1 -0
  162. package/util/logger.d.ts +49 -0
  163. package/util/logger.js +123 -0
  164. package/util/logger.js.map +1 -0
  165. package/util/request.d.ts +138 -0
  166. package/util/request.js +3 -0
  167. package/util/request.js.map +1 -0
  168. package/util/subscription-set/expiring-sorted-set.d.ts +21 -0
  169. package/util/subscription-set/expiring-sorted-set.js +36 -0
  170. package/util/subscription-set/expiring-sorted-set.js.map +1 -0
  171. package/util/subscription-set/redis-sorted-set.d.ts +9 -0
  172. package/util/subscription-set/redis-sorted-set.js +29 -0
  173. package/util/subscription-set/redis-sorted-set.js.map +1 -0
  174. package/util/subscription-set/subscription-set.d.ts +19 -0
  175. package/util/subscription-set/subscription-set.js +28 -0
  176. package/util/subscription-set/subscription-set.js.map +1 -0
  177. package/util/test-payload-loader.d.ts +26 -0
  178. package/util/test-payload-loader.js +85 -0
  179. package/util/test-payload-loader.js.map +1 -0
  180. package/validation/error.d.ts +48 -0
  181. package/validation/error.js +78 -0
  182. package/validation/error.js.map +1 -0
  183. package/validation/index.d.ts +5 -0
  184. package/validation/index.js +102 -0
  185. package/validation/index.js.map +1 -0
  186. package/validation/input-params.d.ts +14 -0
  187. package/validation/input-params.js +3 -0
  188. package/validation/input-params.js.map +1 -0
  189. package/validation/input-validator.d.ts +16 -0
  190. package/validation/input-validator.js +123 -0
  191. package/validation/input-validator.js.map +1 -0
  192. package/README.md +0 -102
@@ -0,0 +1,53 @@
1
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
+ import { Cache } from '../cache';
3
+ import { AdapterConfig } from '../config';
4
+ import { BackgroundExecuteRateLimiter } from '../rate-limiting';
5
+ import { SubscriptionSet } from '../util';
6
+ import { AdapterRequest, AdapterResponse, ProviderResult } from '../util/request';
7
+ import { Transport, TransportGenerics } from './';
8
+ import { AdapterContext, AdapterDependencies } from '../adapter';
9
+ /**
10
+ * Helper struct type that will be used to pass types to the generic parameters of a Transport.
11
+ * Extends the common TransportGenerics, adding Provider specific types for this Batch endpoint.
12
+ */
13
+ declare type BatchWarmingTransportGenerics = TransportGenerics & {
14
+ /**
15
+ * Type details for any provider specific interfaces.
16
+ */
17
+ Provider: {
18
+ /**
19
+ * Structure of the body of the request that will be sent to the data provider.
20
+ */
21
+ RequestBody: unknown;
22
+ /**
23
+ * Structure for the body of the response coming from the data provider.
24
+ */
25
+ ResponseBody: unknown;
26
+ };
27
+ };
28
+ /**
29
+ * Transport implementation that takes incoming batches requests and keeps a warm cache of values.
30
+ * Within the setup function, adapter params are added to an set that also keeps track and expires values.
31
+ * In the background execute, the list of non-expired items in the set is fetched.
32
+ * Then, the list is passed through the `prepareRequest` function, that returns an AxiosRequestConfig.
33
+ * The Data Provider response is, they are passed through the `parseResponse` function to create a [[CacheEntry]] list.
34
+ * Finally, the items in that [[CacheEntry]] list are set in the Cache so the Adapter can fetch values from there.
35
+ *
36
+ * @typeParam T - all types related to the [[Transport]]
37
+ */
38
+ export declare class BatchWarmingTransport<T extends BatchWarmingTransportGenerics> implements Transport<T> {
39
+ private config;
40
+ cache: Cache<AdapterResponse<T['Response']>>;
41
+ rateLimiter: BackgroundExecuteRateLimiter;
42
+ subscriptionSet: SubscriptionSet<T['Request']['Params']>;
43
+ WARMER_ACTIVE: boolean;
44
+ constructor(config: {
45
+ prepareRequest: (params: T['Request']['Params'][], config: AdapterConfig<T['CustomSettings']>) => AxiosRequestConfig<T['Provider']['RequestBody']>;
46
+ parseResponse: (params: T['Request']['Params'][], res: AxiosResponse<T['Provider']['ResponseBody']>, config: AdapterConfig<T['CustomSettings']>) => ProviderResult<T>[];
47
+ });
48
+ initialize(dependencies: AdapterDependencies, _: AdapterConfig<T['CustomSettings']>, endpointName: string): Promise<void>;
49
+ registerRequest(req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>): Promise<void>;
50
+ backgroundExecute(context: AdapterContext<T>): Promise<number>;
51
+ private makeRequest;
52
+ }
53
+ export {};
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.BatchWarmingTransport = void 0;
27
+ const util_1 = require("../util");
28
+ const _1 = require("./");
29
+ const util_2 = require("./util");
30
+ const rateLimitMetrics = __importStar(require("../rate-limiting/metrics"));
31
+ const cacheMetrics = __importStar(require("../cache/metrics"));
32
+ const transportMetrics = __importStar(require("./metrics"));
33
+ const error_1 = require("../validation/error");
34
+ const WARMUP_BATCH_REQUEST_ID = '9002';
35
+ const logger = (0, util_1.makeLogger)('BatchWarmingTransport');
36
+ /**
37
+ * Transport implementation that takes incoming batches requests and keeps a warm cache of values.
38
+ * Within the setup function, adapter params are added to an set that also keeps track and expires values.
39
+ * In the background execute, the list of non-expired items in the set is fetched.
40
+ * Then, the list is passed through the `prepareRequest` function, that returns an AxiosRequestConfig.
41
+ * The Data Provider response is, they are passed through the `parseResponse` function to create a [[CacheEntry]] list.
42
+ * Finally, the items in that [[CacheEntry]] list are set in the Cache so the Adapter can fetch values from there.
43
+ *
44
+ * @typeParam T - all types related to the [[Transport]]
45
+ */
46
+ class BatchWarmingTransport {
47
+ constructor(config) {
48
+ this.config = config;
49
+ // Flag used to track whether the warmer has moved from having no entries to having some and vice versa
50
+ // Used for recording the cache warmer active metrics accurately
51
+ this.WARMER_ACTIVE = false;
52
+ }
53
+ async initialize(dependencies, _, endpointName) {
54
+ this.cache = dependencies.cache;
55
+ this.rateLimiter = dependencies.backgroundExecuteRateLimiter;
56
+ this.subscriptionSet = dependencies.subscriptionSetFactory.buildSet(endpointName);
57
+ }
58
+ // This might need coalescing to avoid too frequent ttl updates
59
+ async registerRequest(req, config) {
60
+ logger.debug(`Adding entry to subscription set (ttl ${config.WARMUP_SUBSCRIPTION_TTL}): [${req.requestContext.cacheKey}] = ${req.requestContext.data}`);
61
+ if (config.BATCH_TRANSPORT_SETUP_VALIDATION) {
62
+ const response = await this.makeRequest([req.requestContext.data], config);
63
+ if (!response.results.length) {
64
+ throw new error_1.AdapterError({
65
+ statusCode: 200,
66
+ providerStatusCode: response.providerResponse.status,
67
+ message: response.providerResponse.message ||
68
+ 'There was an error while validating the incoming request before adding to the batch subscription set',
69
+ });
70
+ }
71
+ }
72
+ await this.subscriptionSet.add(req.requestContext.cacheKey, req.requestContext.data, config.WARMUP_SUBSCRIPTION_TTL);
73
+ }
74
+ async backgroundExecute(context) {
75
+ logger.debug('Starting background execute');
76
+ const entries = await this.subscriptionSet.getAll();
77
+ // Keep track of active subscriptions for background execute
78
+ transportMetrics.bgExecuteSubscriptionSetCount
79
+ .labels({ endpoint: context.adapterEndpoint.name, transport_type: 'batch' })
80
+ .set(entries.length);
81
+ const interval = this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name);
82
+ if (!entries.length) {
83
+ logger.debug('No entries in batch warming set, skipping');
84
+ if (this.WARMER_ACTIVE) {
85
+ // Decrement count when warmer changed from having entries to having none
86
+ cacheMetrics.cacheWarmerCount.labels({ isBatched: 'true' }).dec();
87
+ this.WARMER_ACTIVE = false;
88
+ }
89
+ return interval;
90
+ }
91
+ else if (this.WARMER_ACTIVE === false) {
92
+ // Increment count when warmer changed from having no entries to having some
93
+ cacheMetrics.cacheWarmerCount.labels({ isBatched: 'true' }).inc();
94
+ this.WARMER_ACTIVE = true;
95
+ }
96
+ const response = await this.makeRequest(entries, context.adapterConfig);
97
+ if (!response.results?.length) {
98
+ return interval;
99
+ }
100
+ const cacheEntries = (0, _1.buildCacheEntriesFromResults)(response.results, context);
101
+ logger.debug('Setting adapter responses in cache');
102
+ await this.cache.setMany(cacheEntries, context.adapterConfig.CACHE_MAX_AGE);
103
+ // Record cost of data provider call
104
+ const cost = rateLimitMetrics.retrieveCost(response.providerResponse.data);
105
+ rateLimitMetrics.rateLimitCreditsSpentTotal
106
+ .labels({
107
+ feed_id: 'N/A',
108
+ participant_id: WARMUP_BATCH_REQUEST_ID,
109
+ })
110
+ .inc(cost);
111
+ return interval;
112
+ }
113
+ async makeRequest(entries, config) {
114
+ logger.trace(`Have ${entries.length} entries in batch, preparing request...`);
115
+ const request = this.config.prepareRequest(entries, config);
116
+ logger.trace(`Sending request to data provider: ${JSON.stringify(request)}`);
117
+ let providerResponse;
118
+ try {
119
+ providerResponse = await (0, util_2.axiosRequest)(request, config);
120
+ }
121
+ catch (e) {
122
+ logger.warn(`There was an error while performing the batch request: ${e}`);
123
+ return {
124
+ results: [],
125
+ providerResponse: e,
126
+ };
127
+ }
128
+ logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`);
129
+ return {
130
+ results: this.config.parseResponse(entries, providerResponse, config),
131
+ providerResponse,
132
+ };
133
+ }
134
+ }
135
+ exports.BatchWarmingTransport = BatchWarmingTransport;
136
+ //# sourceMappingURL=batch-warming.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch-warming.js","sourceRoot":"","sources":["../../../src/transports/batch-warming.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,kCAAqD;AAErD,yBAA+E;AAC/E,iCAAqC;AACrC,2EAA4D;AAC5D,+DAAgD;AAEhD,4DAA6C;AAC7C,+CAAkD;AAElD,MAAM,uBAAuB,GAAG,MAAM,CAAA;AAEtC,MAAM,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AI,GAAG,CAAC,CAAA;QACxF,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,CAAC;YACrE,gBAAgB;SACjB,CAAA;IACH,CAAC;CACF;AAjJD,sDAiJC"}
@@ -0,0 +1,108 @@
1
+ import { AdapterContext, AdapterDependencies } from '../adapter';
2
+ import { Cache, CacheEntry } from '../cache';
3
+ import { AdapterConfig, SettingsMap } from '../config';
4
+ import { AdapterRequest, AdapterResponse, ProviderResult, RequestGenerics, ResponseGenerics } from '../util/request';
5
+ export * from './batch-warming';
6
+ export * from './rest';
7
+ export * from './sse';
8
+ export * from './websocket';
9
+ /**
10
+ * Helper struct type that will be used to pass types to the generic parameters of a Transport.
11
+ * Within the transport, given a generic param T extends TransportGenerics, these will be used like so:
12
+ *
13
+ * const request: AdapterRequest\<T['Request']\> = ...
14
+ *
15
+ * (ignore the slash characters, they're just for proper doc syntax \<)
16
+ */
17
+ export declare type TransportGenerics = {
18
+ /**
19
+ * Type details about incoming Adapter requests to this Transport
20
+ */
21
+ Request: RequestGenerics;
22
+ /**
23
+ * Type details about outbound responses from this Transport
24
+ */
25
+ Response: ResponseGenerics;
26
+ /**
27
+ * Type for any custom settings used for this Transport
28
+ */
29
+ CustomSettings: SettingsMap;
30
+ };
31
+ /**
32
+ * Generic interface for a Transport.
33
+ * A Transport defines the way in which an AdapterEndpoint will process incoming requests to
34
+ * fetch data from a Data Provider. The setup phase will take care of the former, while the
35
+ * backgroundExecute will be in charge of the latter.
36
+ * This separation gives us the ability of splitting these concerns, and optionally parallelizing
37
+ * the reading and writing of data to a centralized Cache.
38
+ *
39
+ * @typeParam T - Helper struct type that will be used to pass types to the generic parameters (check [[TransportGenerics]])
40
+ */
41
+ export interface Transport<T extends TransportGenerics> {
42
+ cache?: Cache<AdapterResponse<T['Response']>>;
43
+ /**
44
+ * Initializes the transport in the Adapter context.
45
+ *
46
+ * @param dependencies - Adapter dependencies (e.g. cache instance)
47
+ * @param config - Adapter config containing env vars
48
+ * @returns an empty Promise
49
+ */
50
+ initialize: (dependencies: AdapterDependencies, config: AdapterConfig<T['CustomSettings']>, endpointName: string) => Promise<void>;
51
+ /**
52
+ * Registers a request within the context of the transport.
53
+ * This means things like adding the request to a subscription set.
54
+ *
55
+ * @param req - the incoming AdapterRequest
56
+ * @param config - common configuration for the Adapter as a whole
57
+ * @returns an empty Promise
58
+ */
59
+ registerRequest?: (req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>) => Promise<void>;
60
+ /**
61
+ * Performs a synchronous fetch/processing of information within the lifecycle of an incoming request.
62
+ * This is mostly intended to be used as a backwards compatibility mechanism, or for very specific cases where
63
+ * processing is expected to be very simple. Things like rate limiting for example won't be able to be applied
64
+ * to this method with more than one EA instance. It's heavily encouraged to instead rework adapter logic
65
+ * to perform as much of the work as possible (or all of it) in the backgroundExecute method.
66
+ *
67
+ * @param req - the incoming AdapterRequest
68
+ * @param config - common configuration for the Adapter as a whole
69
+ * @returns a Promise that _optionally_ returns an AdapterResponse, if the Transport has the capability of
70
+ * immediately fetching data and returning it without the background process.
71
+ */
72
+ foregroundExecute?: (req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>) => Promise<AdapterResponse<{
73
+ Data: T['Response']['Data'];
74
+ Result: T['Response']['Result'];
75
+ }> | void>;
76
+ /**
77
+ * Main function that will be called by the main background loop of the writer EA.
78
+ * All logic fetching from providers should live here.
79
+ *
80
+ * @param context - background context for the execution (e.g. endpoint name)
81
+ * @returns an empty Promise
82
+ */
83
+ backgroundExecute?: (context: AdapterContext<T>) => Promise<number>;
84
+ }
85
+ /**
86
+ * Generic interface for a Transport that contains or manages other transports.
87
+ * Some transports, such as the RoutingTransport, do not directly fetch data from a Data Provider, but
88
+ * instead coordinate the execution of other transports for fetching and transforming data.
89
+ * These transports have alternative initialization procedures, which typically involve
90
+ * initializing each downstream transport.
91
+ *
92
+ * @typeParam Params - the structure of the AdapterRequest's body
93
+ * @typeParam Result - the structure of the AdapterResponse's body
94
+ * @typeParam CustomSettings - custom settings for the Adapter, or the default SettingsMap
95
+ */
96
+ export interface MetaTransport<T extends TransportGenerics> extends Transport<T> {
97
+ transports: {
98
+ [key: string]: Transport<T>;
99
+ };
100
+ }
101
+ /**
102
+ * Helper method to build cache entries to set after getting a bunch of responses from a DP.
103
+ *
104
+ * @param results - a list of results coming from a DataProvider
105
+ * @param context - context for the Adapter
106
+ * @returns a list of CacheEntries of AdapterResponses
107
+ */
108
+ export declare const buildCacheEntriesFromResults: <T extends TransportGenerics>(results: ProviderResult<T>[], context: AdapterContext<T>) => CacheEntry<AdapterResponse<T["Response"]>>[];
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.buildCacheEntriesFromResults = void 0;
18
+ const cache_1 = require("../cache");
19
+ __exportStar(require("./batch-warming"), exports);
20
+ __exportStar(require("./rest"), exports);
21
+ __exportStar(require("./sse"), exports);
22
+ __exportStar(require("./websocket"), exports);
23
+ /**
24
+ * Helper method to build cache entries to set after getting a bunch of responses from a DP.
25
+ *
26
+ * @param results - a list of results coming from a DataProvider
27
+ * @param context - context for the Adapter
28
+ * @returns a list of CacheEntries of AdapterResponses
29
+ */
30
+ const buildCacheEntriesFromResults = (results, context) => results.map((r) => {
31
+ const cacheEntry = {
32
+ key: (0, cache_1.calculateCacheKey)(context, r.params),
33
+ value: {
34
+ result: r.value,
35
+ statusCode: 200,
36
+ data: {
37
+ result: r.value,
38
+ },
39
+ },
40
+ };
41
+ if (context.adapterConfig.METRICS_ENABLED &&
42
+ context.adapterConfig.EXPERIMENTAL_METRICS_ENABLED) {
43
+ const metrics = {
44
+ maxAge: Date.now() + context.adapterConfig.CACHE_MAX_AGE,
45
+ meta: {
46
+ metrics: {
47
+ feedId: (0, cache_1.calculateFeedId)(context, r.params),
48
+ },
49
+ },
50
+ };
51
+ cacheEntry.value = { ...cacheEntry.value, ...metrics };
52
+ }
53
+ return cacheEntry;
54
+ });
55
+ exports.buildCacheEntriesFromResults = buildCacheEntriesFromResults;
56
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/transports/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AACA,oCAAgF;AAUhF,kDAA+B;AAC/B,yCAAsB;AACtB,wCAAqB;AACrB,8CAA2B;AAgH3B;;;;;;GAMG;AACI,MAAM,4BAA4B,GAAG,CAC1C,OAA4B,EAC5B,OAA0B,EACoB,EAAE,CAChD,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;IAChB,MAAM,UAAU,GAAG;QACjB,GAAG,EAAE,IAAA,yBAAiB,EAAC,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC;QACzC,KAAK,EAAE;YACL,MAAM,EAAE,CAAC,CAAC,KAAK;YACf,UAAU,EAAE,GAAG;YACf,IAAI,EAAE;gBACJ,MAAM,EAAE,CAAC,CAAC,KAAK;aAChB;SACF;KACF,CAAA;IAED,IACE,OAAO,CAAC,aAAa,CAAC,eAAe;QACrC,OAAO,CAAC,aAAa,CAAC,4BAA4B,EAClD;QACA,MAAM,OAAO,GAAG;YACd,MAAM,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC,aAAa,CAAC,aAAa;YACxD,IAAI,EAAE;gBACJ,OAAO,EAAE;oBACP,MAAM,EAAE,IAAA,uBAAe,EAAC,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC;iBAC3C;aACF;SACF,CAAA;QACD,UAAU,CAAC,KAAK,GAAG,EAAE,GAAG,UAAU,CAAC,KAAK,EAAE,GAAG,OAAO,EAAE,CAAA;KACvD;IACD,OAAO,UAAU,CAAA;AACnB,CAAC,CAAC,CAAA;AA/BS,QAAA,4BAA4B,gCA+BrC"}
@@ -0,0 +1,25 @@
1
+ import * as client from 'prom-client';
2
+ import { TransportGenerics } from '.';
3
+ import { AdapterContext } from '../adapter';
4
+ export declare const dataProviderMetricsLabel: (providerStatusCode?: number, method?: string) => {
5
+ provider_status_code: number | undefined;
6
+ method: string;
7
+ };
8
+ export declare const dataProviderRequests: client.Counter<"method" | "provider_status_code">;
9
+ export declare const dataProviderRequestDurationSeconds: client.Histogram<string>;
10
+ export declare const connectionErrorLabels: (message: string) => {
11
+ message: string;
12
+ };
13
+ export declare const messageSubsLabels: (feed_id: string, cache_key: string) => {
14
+ feed_id: string;
15
+ subscription_key: string;
16
+ };
17
+ export declare const recordWsMessageMetrics: <T extends TransportGenerics>(context: AdapterContext<T>, subscribes: T["Request"]["Params"][], unsubscribes: T["Request"]["Params"][]) => void;
18
+ export declare const wsConnectionActive: client.Gauge<"url">;
19
+ export declare const wsConnectionErrors: client.Counter<"message" | "url">;
20
+ export declare const wsSubscriptionActive: client.Gauge<"feed_id" | "connection_url" | "subscription_key">;
21
+ export declare const wsSubscriptionTotal: client.Counter<"feed_id" | "connection_url" | "subscription_key">;
22
+ export declare const wsMessageTotal: client.Counter<"feed_id" | "subscription_key">;
23
+ export declare const bgExecuteSubscriptionSetCount: client.Gauge<"endpoint" | "transport_type">;
24
+ export declare const transportPollingFailureCount: client.Counter<"endpoint">;
25
+ export declare const transportPollingDurationSeconds: client.Gauge<"succeeded" | "endpoint">;
@@ -0,0 +1,122 @@
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.transportPollingDurationSeconds = exports.transportPollingFailureCount = exports.bgExecuteSubscriptionSetCount = exports.wsMessageTotal = exports.wsSubscriptionTotal = exports.wsSubscriptionActive = exports.wsConnectionErrors = exports.wsConnectionActive = exports.recordWsMessageMetrics = exports.messageSubsLabels = exports.connectionErrorLabels = exports.dataProviderRequestDurationSeconds = exports.dataProviderRequests = exports.dataProviderMetricsLabel = void 0;
27
+ const client = __importStar(require("prom-client"));
28
+ const cache_1 = require("../cache");
29
+ const constants_1 = require("../metrics/constants");
30
+ // Data Provider Metrics
31
+ const dataProviderMetricsLabel = (providerStatusCode, method = 'get') => ({
32
+ provider_status_code: providerStatusCode,
33
+ method: method.toUpperCase(),
34
+ });
35
+ exports.dataProviderMetricsLabel = dataProviderMetricsLabel;
36
+ exports.dataProviderRequests = new client.Counter({
37
+ name: 'data_provider_requests',
38
+ help: 'The number of http requests that are made to a data provider',
39
+ labelNames: ['method', 'provider_status_code'],
40
+ });
41
+ exports.dataProviderRequestDurationSeconds = new client.Histogram({
42
+ name: 'data_provider_request_duration_seconds',
43
+ help: 'A histogram bucket of the distribution of data provider request durations',
44
+ buckets: constants_1.requestDurationBuckets,
45
+ });
46
+ // Websocket Metrics
47
+ const connectionErrorLabels = (message) => ({
48
+ // Key,
49
+ message,
50
+ });
51
+ exports.connectionErrorLabels = connectionErrorLabels;
52
+ const messageSubsLabels = (feed_id, cache_key) => ({
53
+ feed_id,
54
+ subscription_key: cache_key,
55
+ });
56
+ exports.messageSubsLabels = messageSubsLabels;
57
+ // Record WS message and subscription metrics
58
+ // Recalculate cacheKey and feedId for metrics
59
+ // since avoiding storing extra info in expiring sorted set
60
+ const recordWsMessageMetrics = (context, subscribes, unsubscribes) => {
61
+ subscribes.forEach((param) => {
62
+ const feedId = (0, cache_1.calculateFeedId)(context, param);
63
+ const cacheKey = (0, cache_1.calculateCacheKey)(context, param);
64
+ // Record total number of ws messages sent
65
+ exports.wsMessageTotal.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
66
+ // Record total number of subscriptions made
67
+ exports.wsSubscriptionTotal.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
68
+ // Record number of active ws subscriptions
69
+ exports.wsSubscriptionActive.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
70
+ });
71
+ unsubscribes.forEach((param) => {
72
+ const feedId = (0, cache_1.calculateFeedId)(context, param);
73
+ const cacheKey = (0, cache_1.calculateCacheKey)(context, param);
74
+ // Record total number of ws messages sent
75
+ exports.wsMessageTotal.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).inc();
76
+ // Record number of active ws subscriptions
77
+ exports.wsSubscriptionActive.labels((0, exports.messageSubsLabels)(feedId, cacheKey)).dec();
78
+ });
79
+ };
80
+ exports.recordWsMessageMetrics = recordWsMessageMetrics;
81
+ exports.wsConnectionActive = new client.Gauge({
82
+ name: 'ws_connection_active',
83
+ help: 'The number of active connections',
84
+ labelNames: ['url'],
85
+ });
86
+ exports.wsConnectionErrors = new client.Counter({
87
+ name: 'ws_connection_errors',
88
+ help: 'The number of connection errors',
89
+ labelNames: ['url', 'message'],
90
+ });
91
+ exports.wsSubscriptionActive = new client.Gauge({
92
+ name: 'ws_subscription_active',
93
+ help: 'The number of currently active subscriptions',
94
+ labelNames: ['connection_url', 'feed_id', 'subscription_key'],
95
+ });
96
+ exports.wsSubscriptionTotal = new client.Counter({
97
+ name: 'ws_subscription_total',
98
+ help: 'The number of subscriptions opened in total',
99
+ labelNames: ['connection_url', 'feed_id', 'subscription_key'],
100
+ });
101
+ exports.wsMessageTotal = new client.Counter({
102
+ name: 'ws_message_total',
103
+ help: 'The number of messages received in total',
104
+ labelNames: ['feed_id', 'subscription_key'],
105
+ });
106
+ // V3 specific metrics
107
+ exports.bgExecuteSubscriptionSetCount = new client.Gauge({
108
+ name: 'bg_execute_subscription_set_count',
109
+ help: 'The number of active subscriptions in background execute',
110
+ labelNames: ['endpoint', 'transport_type'],
111
+ });
112
+ exports.transportPollingFailureCount = new client.Counter({
113
+ name: 'transport_polling_failure_count',
114
+ help: 'The number of times the polling mechanism ran out of attempts and failed to return a response',
115
+ labelNames: ['endpoint'],
116
+ });
117
+ exports.transportPollingDurationSeconds = new client.Gauge({
118
+ name: 'transport_polling_duration_seconds',
119
+ help: 'A histogram bucket of the distribution of transport polling idle time durations',
120
+ labelNames: ['endpoint', 'succeeded'],
121
+ });
122
+ //# sourceMappingURL=metrics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics.js","sourceRoot":"","sources":["../../../src/transports/metrics.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AAGrC,oCAA6D;AAC7D,oDAA6D;AAE7D,wBAAwB;AACjB,MAAM,wBAAwB,GAAG,CAAC,kBAA2B,EAAE,MAAM,GAAG,KAAK,EAAE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IAAI,EAAE,8CAA8C;IACpD,UAAU,EAAE,CAAC,gBAAgB,EAAE,SAAS,EAAE,kBAAkB,CAAU;CACvE,CAAC,CAAA;AAEW,QAAA,mBAAmB,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC;IACpD,IAAI,EAAE,uBAAuB;IAC7B,IAAI,EAAE,6CAA6C;IACnD,UAAU,EAAE,CAAC,gBAAgB,EAAE,SAAS,EAAE,kBAAkB,CAAU;CACvE,CAAC,CAAA;AAEW,QAAA,cAAc,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC;IAC/C,IAAI,EAAE,kBAAkB;IACxB,IAAI,EAAE,0CAA0C;IAChD,UAAU,EAAE,CAAC,SAAS,EAAE,kBAAkB,CAAU;CACrD,CAAC,CAAA;AAEF,sBAAsB;AACT,QAAA,6BAA6B,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC;IAC5D,IAAI,EAAE,mCAAmC;IACzC,IAAI,EAAE,0DAA0D;IAChE,UAAU,EAAE,CAAC,UAAU,EAAE,gBAAgB,CAAU;CACpD,CAAC,CAAA;AAEW,QAAA,4BAA4B,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC;IAC7D,IAAI,EAAE,iCAAiC;IACvC,IAAI,EAAE,+FAA+F;IACrG,UAAU,EAAE,CAAC,UAAU,CAAU;CAClC,CAAC,CAAA;AAEW,QAAA,+BAA+B,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC;IAC9D,IAAI,EAAE,oCAAoC;IAC1C,IAAI,EAAE,iFAAiF;IACvF,UAAU,EAAE,CAAC,UAAU,EAAE,WAAW,CAAU;CAC/C,CAAC,CAAA"}
@@ -0,0 +1,68 @@
1
+ import { AdapterRequest, AdapterResponse } from '../util/request';
2
+ import { Transport, TransportGenerics } from './';
3
+ import { Cache } from '../cache';
4
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
5
+ import { AdapterConfig } from '../config';
6
+ import { RequestRateLimiter } from '../rate-limiting';
7
+ import { AdapterDependencies } from '../adapter';
8
+ export { AxiosRequestConfig as HttpRequestConfig, AxiosResponse as HttpResponse };
9
+ /**
10
+ * Helper struct type that will be used to pass types to the generic parameters of a Transport.
11
+ * Extends the common TransportGenerics, adding Provider specific types for this Batch endpoint.
12
+ */
13
+ declare type RestTransportGenerics = TransportGenerics & {
14
+ /**
15
+ * Type details for any provider specific interfaces.
16
+ */
17
+ Provider: {
18
+ /**
19
+ * Structure of the body of the request that will be sent to the data provider.
20
+ */
21
+ RequestBody: unknown;
22
+ /**
23
+ * Structure for the body of the response coming from the data provider.
24
+ */
25
+ ResponseBody: unknown;
26
+ };
27
+ };
28
+ /**
29
+ * Transport implementation that takes incoming requests, transforms them into a DataProvider request,
30
+ * and executes that request returning the response immediately from the `setup` function.
31
+ * Optionally, setting the `coalescing` option to `true` will make it so once a request is in flight,
32
+ * new adapter requests for the same feed will not trigger a new one, but return an empty promise from
33
+ * the setup instead so the normal cache polling mechanism is used.
34
+ *
35
+ * @typeParam T - Helper struct type that will be used to pass types to the generic parameters (check [[RestTransportGenerics]])
36
+ */
37
+ export declare class RestTransport<T extends RestTransportGenerics> implements Transport<T> {
38
+ protected config: {
39
+ prepareRequest: (req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>) => AxiosRequestConfig<T['Provider']['RequestBody']> | Promise<AxiosRequestConfig<T['Provider']['RequestBody']>>;
40
+ parseResponse: (req: AdapterRequest<T['Request']>, res: AxiosResponse<T['Provider']['ResponseBody']>, config: AdapterConfig<T['CustomSettings']>) => AdapterResponse<T['Response']> | Promise<AdapterResponse<T['Response']>>;
41
+ options: {
42
+ requestCoalescing: {
43
+ enabled: boolean;
44
+ entropyMax?: number;
45
+ };
46
+ };
47
+ };
48
+ inFlightPrefix: string;
49
+ cache: Cache<AdapterResponse<T['Response']>>;
50
+ inFlightCache: Cache<boolean>;
51
+ rateLimiter: RequestRateLimiter;
52
+ constructor(config: {
53
+ prepareRequest: (req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>) => AxiosRequestConfig<T['Provider']['RequestBody']> | Promise<AxiosRequestConfig<T['Provider']['RequestBody']>>;
54
+ parseResponse: (req: AdapterRequest<T['Request']>, res: AxiosResponse<T['Provider']['ResponseBody']>, config: AdapterConfig<T['CustomSettings']>) => AdapterResponse<T['Response']> | Promise<AdapterResponse<T['Response']>>;
55
+ options: {
56
+ requestCoalescing: {
57
+ enabled: boolean;
58
+ entropyMax?: number;
59
+ };
60
+ };
61
+ });
62
+ initialize(dependencies: AdapterDependencies, config: AdapterConfig<T['CustomSettings']>): Promise<void>;
63
+ protected waitUntilUnderRateLimit(options: {
64
+ maxRetries: number;
65
+ msBetweenRetries: number;
66
+ }, retry?: number): Promise<void>;
67
+ foregroundExecute(req: AdapterRequest<T['Request']>, config: AdapterConfig<T['CustomSettings']>): Promise<AdapterResponse<T['Response']> | undefined>;
68
+ }