@chainlink/external-adapter-framework 0.0.5 → 0.0.7

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 (161) hide show
  1. package/dist/adapter.js +60 -0
  2. package/dist/background-executor.js +45 -0
  3. package/dist/cache/factory.js +57 -0
  4. package/dist/cache/index.js +163 -0
  5. package/dist/cache/local.js +83 -0
  6. package/dist/cache/metrics.js +114 -0
  7. package/dist/cache/redis.js +100 -0
  8. package/dist/config/index.js +364 -0
  9. package/dist/config/provider-limits.js +75 -0
  10. package/dist/examples/coingecko/batch-warming.js +52 -0
  11. package/dist/examples/coingecko/index.js +10 -0
  12. package/dist/examples/coingecko/rest.js +50 -0
  13. package/dist/examples/ncfx/config/index.js +15 -0
  14. package/dist/examples/ncfx/index.js +10 -0
  15. package/dist/examples/ncfx/websocket.js +72 -0
  16. package/dist/index.js +89 -0
  17. package/dist/metrics/constants.js +25 -0
  18. package/dist/metrics/index.js +76 -0
  19. package/dist/metrics/util.js +9 -0
  20. package/dist/rate-limiting/factory.js +33 -0
  21. package/dist/rate-limiting/index.js +36 -0
  22. package/dist/rate-limiting/metrics.js +32 -0
  23. package/dist/rate-limiting/nop-limiter.js +15 -0
  24. package/dist/rate-limiting/simple-counting.js +61 -0
  25. package/dist/src/adapter.js +112 -0
  26. package/dist/src/background-executor.js +45 -0
  27. package/dist/src/cache/factory.js +57 -0
  28. package/dist/src/cache/index.js +165 -0
  29. package/dist/src/cache/local.js +83 -0
  30. package/dist/src/cache/metrics.js +114 -0
  31. package/dist/src/cache/redis.js +100 -0
  32. package/dist/src/config/index.js +366 -0
  33. package/dist/src/config/provider-limits.js +75 -0
  34. package/dist/src/examples/bank-frick/accounts.js +191 -0
  35. package/dist/src/examples/bank-frick/config/index.js +45 -0
  36. package/dist/src/examples/bank-frick/index.js +14 -0
  37. package/dist/src/examples/bank-frick/util.js +39 -0
  38. package/dist/src/examples/coingecko/batch-warming.js +52 -0
  39. package/dist/src/examples/coingecko/index.js +10 -0
  40. package/dist/src/examples/coingecko/rest.js +50 -0
  41. package/dist/src/examples/ncfx/config/index.js +15 -0
  42. package/dist/src/examples/ncfx/index.js +10 -0
  43. package/dist/src/examples/ncfx/websocket.js +72 -0
  44. package/dist/src/index.js +89 -0
  45. package/dist/src/metrics/constants.js +25 -0
  46. package/dist/src/metrics/index.js +76 -0
  47. package/dist/src/metrics/util.js +9 -0
  48. package/dist/src/rate-limiting/background/fixed-frequency.js +37 -0
  49. package/dist/src/rate-limiting/index.js +63 -0
  50. package/dist/src/rate-limiting/metrics.js +32 -0
  51. package/dist/src/rate-limiting/request/simple-counting.js +62 -0
  52. package/dist/src/test.js +6 -0
  53. package/dist/src/transports/batch-warming.js +55 -0
  54. package/dist/src/transports/index.js +85 -0
  55. package/dist/src/transports/metrics.js +119 -0
  56. package/dist/src/transports/rest.js +93 -0
  57. package/dist/src/transports/util.js +85 -0
  58. package/dist/src/transports/websocket.js +175 -0
  59. package/dist/src/util/expiring-sorted-set.js +47 -0
  60. package/dist/src/util/index.js +35 -0
  61. package/dist/src/util/logger.js +62 -0
  62. package/dist/src/util/request.js +2 -0
  63. package/dist/src/validation/error.js +41 -0
  64. package/dist/src/validation/index.js +84 -0
  65. package/dist/src/validation/input-params.js +30 -0
  66. package/dist/src/validation/override-functions.js +40 -0
  67. package/dist/src/validation/preset-tokens.json +23 -0
  68. package/dist/src/validation/validator.js +303 -0
  69. package/dist/test.js +6 -0
  70. package/dist/transports/batch-warming.js +57 -0
  71. package/dist/transports/index.js +76 -0
  72. package/dist/transports/metrics.js +133 -0
  73. package/dist/transports/rest.js +91 -0
  74. package/dist/transports/util.js +85 -0
  75. package/dist/transports/websocket.js +171 -0
  76. package/dist/util/expiring-sorted-set.js +47 -0
  77. package/dist/util/index.js +35 -0
  78. package/dist/util/logger.js +62 -0
  79. package/dist/util/request.js +2 -0
  80. package/dist/validation/error.js +41 -0
  81. package/dist/validation/index.js +82 -0
  82. package/dist/validation/input-params.js +30 -0
  83. package/dist/validation/overrideFunctions.js +42 -0
  84. package/dist/validation/presetTokens.json +23 -0
  85. package/dist/validation/validator.js +303 -0
  86. package/package.json +6 -2
  87. package/.c8rc.json +0 -3
  88. package/.eslintignore +0 -9
  89. package/.eslintrc.js +0 -96
  90. package/.github/README.MD +0 -17
  91. package/.github/actions/setup/action.yaml +0 -13
  92. package/.github/workflows/main.yaml +0 -39
  93. package/.github/workflows/publish.yaml +0 -18
  94. package/.prettierignore +0 -13
  95. package/.yarnrc +0 -0
  96. package/docker-compose.yaml +0 -35
  97. package/src/adapter.ts +0 -236
  98. package/src/background-executor.ts +0 -53
  99. package/src/cache/factory.ts +0 -28
  100. package/src/cache/index.ts +0 -236
  101. package/src/cache/local.ts +0 -73
  102. package/src/cache/metrics.ts +0 -112
  103. package/src/cache/redis.ts +0 -93
  104. package/src/config/index.ts +0 -501
  105. package/src/config/provider-limits.ts +0 -130
  106. package/src/examples/coingecko/batch-warming.ts +0 -79
  107. package/src/examples/coingecko/index.ts +0 -9
  108. package/src/examples/coingecko/rest.ts +0 -77
  109. package/src/examples/ncfx/config/index.ts +0 -12
  110. package/src/examples/ncfx/index.ts +0 -9
  111. package/src/examples/ncfx/websocket.ts +0 -100
  112. package/src/index.ts +0 -106
  113. package/src/metrics/constants.ts +0 -23
  114. package/src/metrics/index.ts +0 -116
  115. package/src/metrics/util.ts +0 -11
  116. package/src/rate-limiting/background/fixed-frequency.ts +0 -47
  117. package/src/rate-limiting/index.ts +0 -100
  118. package/src/rate-limiting/metrics.ts +0 -18
  119. package/src/rate-limiting/request/simple-counting.ts +0 -76
  120. package/src/test.ts +0 -5
  121. package/src/transports/batch-warming.ts +0 -121
  122. package/src/transports/index.ts +0 -173
  123. package/src/transports/metrics.ts +0 -95
  124. package/src/transports/rest.ts +0 -161
  125. package/src/transports/util.ts +0 -63
  126. package/src/transports/websocket.ts +0 -238
  127. package/src/util/expiring-sorted-set.ts +0 -52
  128. package/src/util/index.ts +0 -20
  129. package/src/util/logger.ts +0 -69
  130. package/src/util/request.ts +0 -115
  131. package/src/validation/error.ts +0 -116
  132. package/src/validation/index.ts +0 -101
  133. package/src/validation/input-params.ts +0 -45
  134. package/src/validation/override-functions.ts +0 -44
  135. package/src/validation/preset-tokens.json +0 -23
  136. package/src/validation/validator.ts +0 -384
  137. package/test/adapter.test.ts +0 -27
  138. package/test/background-executor.test.ts +0 -109
  139. package/test/cache/cache-key.test.ts +0 -96
  140. package/test/cache/helper.ts +0 -101
  141. package/test/cache/local.test.ts +0 -54
  142. package/test/cache/redis.test.ts +0 -89
  143. package/test/correlation.test.ts +0 -114
  144. package/test/index.test.ts +0 -37
  145. package/test/metrics/feed-id.test.ts +0 -33
  146. package/test/metrics/helper.ts +0 -14
  147. package/test/metrics/labels.test.ts +0 -36
  148. package/test/metrics/metrics.test.ts +0 -267
  149. package/test/metrics/redis-metrics.test.ts +0 -113
  150. package/test/metrics/warmer-metrics.test.ts +0 -192
  151. package/test/metrics/ws-metrics.test.ts +0 -225
  152. package/test/rate-limit-config.test.ts +0 -243
  153. package/test/transports/batch.test.ts +0 -465
  154. package/test/transports/rest.test.ts +0 -242
  155. package/test/transports/websocket.test.ts +0 -183
  156. package/test/tsconfig.json +0 -5
  157. package/test/util.ts +0 -76
  158. package/test/validation.test.ts +0 -169
  159. package/test.sh +0 -20
  160. package/tsconfig.json +0 -24
  161. package/typedoc.json +0 -6
@@ -0,0 +1,60 @@
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 process dependencies for an adapter, such as caches or rate limiters,
10
+ * in order to inject them into transports and other relevant places later in the lifecycle.
11
+ *
12
+ * @param config - the configuration for this adapter
13
+ * @param inputDependencies - a partial obj of initialized dependencies to override the created ones
14
+ * @param rateLimitingConfig - details from the adapter regarding rate limiting
15
+ * @returns a set of AdapterDependencies all initialized
16
+ */
17
+ const initializeDependencies = (config, inputDependencies, rateLimitingConfig) => {
18
+ const dependencies = inputDependencies || {};
19
+ if (!dependencies.cache) {
20
+ dependencies.cache = factory_1.CacheFactory.buildCache(config);
21
+ }
22
+ if (!dependencies.rateLimiter) {
23
+ const rateLimiter = rate_limiting_1.RateLimiterFactory.buildRateLimiter(rateLimitingConfig?.tiers, config['RATE_LIMIT_API_TIER'], rateLimitingConfig?.strategy);
24
+ dependencies.rateLimiter = rateLimiter;
25
+ }
26
+ return dependencies;
27
+ };
28
+ exports.initializeDependencies = initializeDependencies;
29
+ /**
30
+ * Initializes all of the [[Transport]]s in the adapter, passing along any [[AdapterDependencies]] and [[AdapterConfig]].
31
+ * Additionally, it builds a map out of all the endpoint names and aliases (checking for duplicates).
32
+ *
33
+ * @param adapter - an instance of an Adapter
34
+ * @param dependencies - dependencies that the adapter will need at initialization
35
+ * @param config - configuration variables already processed and validated
36
+ * @returns - the adapter with all transports initialized and aliases map built
37
+ */
38
+ const initializeAdapter = async (adapter, config, dependencies) => {
39
+ const initializedDependencies = (0, exports.initializeDependencies)(config, dependencies, adapter.rateLimiting);
40
+ const endpointsMap = {};
41
+ for (const endpoint of adapter.endpoints) {
42
+ // Add aliases to map to use in validation
43
+ const aliases = [endpoint.name, ...(endpoint.aliases || [])];
44
+ for (const alias of aliases) {
45
+ if (endpointsMap[alias]) {
46
+ throw new Error(`Duplicate endpoint / alias: "${alias}"`);
47
+ }
48
+ endpointsMap[alias] = endpoint;
49
+ }
50
+ logger.debug(`Initializing transport for endpoint "${endpoint.name}"...`);
51
+ await endpoint.transport.initialize(initializedDependencies);
52
+ }
53
+ return {
54
+ ...adapter,
55
+ endpointsMap,
56
+ dependencies: initializedDependencies,
57
+ config,
58
+ };
59
+ };
60
+ exports.initializeAdapter = initializeAdapter;
@@ -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,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,163 @@
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
+ const label = cacheMetrics.cacheMetricsLabel(req.requestContext.cacheKey, req.requestContext.metricsMeta?.feedId || 'N/A', adapter.config.CACHE_TYPE);
156
+ // Record cache staleness and cache get count and value
157
+ const staleness = calculateStaleness(response.maxAge, adapter.config.CACHE_MAX_AGE);
158
+ cacheMetrics.cacheGet(label, response.result, staleness);
159
+ return res.send(response);
160
+ }
161
+ logger.debug('Did not find response in cache, moving to next middleware');
162
+ };
163
+ exports.buildCacheMiddleware = buildCacheMiddleware;
@@ -0,0 +1,83 @@
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.LocalCache = void 0;
27
+ const util_1 = require("../util");
28
+ const cacheMetrics = __importStar(require("./metrics"));
29
+ const logger = (0, util_1.makeLogger)('LocalCache');
30
+ /**
31
+ * Local implementation of a Cache. It uses a simple js Object, storing entries with both
32
+ * a value and an expiration timestamp. Expired entries are deleted on reads (i.e. no background gc/upkeep).
33
+ *
34
+ * @typeParam T - the type for the entries' values
35
+ */
36
+ class LocalCache {
37
+ constructor() {
38
+ this.store = {};
39
+ }
40
+ async get(key) {
41
+ logger.trace(`Getting key ${key}`);
42
+ const entry = this.store[key];
43
+ if (!entry) {
44
+ logger.debug(`No entry in local cache for key "${key}", returning undefined`);
45
+ return undefined;
46
+ }
47
+ const expired = entry.expirationTimestamp <= Date.now();
48
+ if (expired) {
49
+ logger.debug('Entry in local cache expired, deleting and returning undefined');
50
+ this.delete(key);
51
+ return undefined;
52
+ }
53
+ else {
54
+ logger.debug('Found valid entry in local cache, returning value');
55
+ return entry.value;
56
+ }
57
+ }
58
+ async delete(key) {
59
+ logger.trace(`Deleting key ${key}`);
60
+ delete this.store[key]; // Deletes are slower than ignoring or setting null, fyi
61
+ }
62
+ async set(key, value, ttl) {
63
+ logger.trace(`Setting key ${key} with ttl ${ttl}`);
64
+ this.store[key] = {
65
+ value,
66
+ expirationTimestamp: Date.now() + ttl,
67
+ };
68
+ // Only record metrics if feed Id is present, otherwise assuming value is not adapter response to record
69
+ const feedId = value.metricsMeta?.feedId;
70
+ if (feedId) {
71
+ // Record cache set count, max age, and staleness (set to 0 for cache set)
72
+ const label = cacheMetrics.cacheMetricsLabel(key, feedId, cacheMetrics.CacheTypes.Local);
73
+ cacheMetrics.cacheSet(label, ttl);
74
+ }
75
+ }
76
+ async setMany(entries, ttl) {
77
+ logger.trace(`Setting a bunch of keys with ttl ${ttl}`);
78
+ for (const { key, value } of entries) {
79
+ this.set(key, value, ttl);
80
+ }
81
+ }
82
+ }
83
+ exports.LocalCache = LocalCache;
@@ -0,0 +1,114 @@
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.redisCommandsSentCount = exports.redisRetriesCount = exports.redisConnectionsOpen = exports.CMD_SENT_STATUS = exports.CacheTypes = exports.cacheMetricsLabel = exports.cacheSet = exports.cacheGet = void 0;
27
+ const client = __importStar(require("prom-client"));
28
+ const cacheGet = (label, value, staleness) => {
29
+ if (typeof value === 'number' || typeof value === 'string') {
30
+ const parsedValue = Number(value);
31
+ if (!Number.isNaN(parsedValue) && Number.isFinite(parsedValue)) {
32
+ cacheDataGetValues.labels(label).set(parsedValue);
33
+ }
34
+ }
35
+ cacheDataGetCount.labels(label).inc();
36
+ cacheDataStalenessSeconds.labels(label).set(staleness);
37
+ };
38
+ exports.cacheGet = cacheGet;
39
+ const cacheSet = (label, maxAge) => {
40
+ cacheDataSetCount.labels(label).inc();
41
+ cacheDataMaxAge.labels(label).set(maxAge);
42
+ cacheDataStalenessSeconds.labels(label).set(0);
43
+ };
44
+ exports.cacheSet = cacheSet;
45
+ const cacheMetricsLabel = (cacheKey, feedId, cacheType) => ({
46
+ participant_id: cacheKey,
47
+ feed_id: feedId,
48
+ cache_type: cacheType,
49
+ });
50
+ exports.cacheMetricsLabel = cacheMetricsLabel;
51
+ var CacheTypes;
52
+ (function (CacheTypes) {
53
+ CacheTypes["Redis"] = "redis";
54
+ CacheTypes["Local"] = "local";
55
+ })(CacheTypes = exports.CacheTypes || (exports.CacheTypes = {}));
56
+ var CMD_SENT_STATUS;
57
+ (function (CMD_SENT_STATUS) {
58
+ CMD_SENT_STATUS["TIMEOUT"] = "TIMEOUT";
59
+ CMD_SENT_STATUS["FAIL"] = "FAIL";
60
+ CMD_SENT_STATUS["SUCCESS"] = "SUCCESS";
61
+ })(CMD_SENT_STATUS = exports.CMD_SENT_STATUS || (exports.CMD_SENT_STATUS = {}));
62
+ const baseLabels = [
63
+ 'feed_id',
64
+ 'participant_id',
65
+ 'cache_type',
66
+ 'is_from_ws',
67
+ 'experimental',
68
+ ];
69
+ // Skipping this metrics for v3
70
+ // const cache_execution_duration_seconds = new client.Histogram({
71
+ // name: 'cache_execution_duration_seconds',
72
+ // help: 'A histogram bucket of the distribution of cache execution durations',
73
+ // labelNames: [...baseLabels, 'cache_hit'] as const,
74
+ // buckets: [0.01, 0.1, 1, 10],
75
+ // })
76
+ const cacheDataGetCount = new client.Counter({
77
+ name: 'cache_data_get_count',
78
+ help: 'A counter that increments every time a value is fetched from the cache',
79
+ labelNames: baseLabels,
80
+ });
81
+ const cacheDataGetValues = new client.Gauge({
82
+ name: 'cache_data_get_values',
83
+ help: 'A gauge keeping track of values being fetched from cache',
84
+ labelNames: baseLabels,
85
+ });
86
+ const cacheDataMaxAge = new client.Gauge({
87
+ name: 'cache_data_max_age',
88
+ help: 'A gauge tracking the max age of stored values in the cache',
89
+ labelNames: baseLabels,
90
+ });
91
+ const cacheDataSetCount = new client.Counter({
92
+ name: 'cache_data_set_count',
93
+ help: 'A counter that increments every time a value is set to the cache',
94
+ labelNames: [...baseLabels, 'status_code'],
95
+ });
96
+ const cacheDataStalenessSeconds = new client.Gauge({
97
+ name: 'cache_data_staleness_seconds',
98
+ help: 'Observes the staleness of the data returned',
99
+ labelNames: baseLabels,
100
+ });
101
+ // Redis Metrics
102
+ exports.redisConnectionsOpen = new client.Counter({
103
+ name: 'redis_connections_open',
104
+ help: 'The number of redis connections that are open',
105
+ });
106
+ exports.redisRetriesCount = new client.Counter({
107
+ name: 'redis_retries_count',
108
+ help: 'The number of retries that have been made to establish a redis connection',
109
+ });
110
+ exports.redisCommandsSentCount = new client.Counter({
111
+ name: 'redis_commands_sent_count',
112
+ help: 'The number of redis commands sent',
113
+ labelNames: ['status', 'function_name'],
114
+ });
@@ -0,0 +1,100 @@
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.RedisCache = void 0;
27
+ const util_1 = require("../util");
28
+ const cacheMetrics = __importStar(require("./metrics"));
29
+ const logger = (0, util_1.makeLogger)('RedisCache');
30
+ /**
31
+ * Redis implementation of a Cache. It uses a simple js Object, storing entries with both
32
+ * a value and an expiration timestamp. Expired entries are deleted on reads (i.e. no background gc/upkeep).
33
+ *
34
+ * @typeParam T - the type for the entries' values
35
+ */
36
+ // TODO: Add error handling for redis command failures
37
+ class RedisCache {
38
+ constructor(client) {
39
+ this.client = client;
40
+ }
41
+ async get(key) {
42
+ logger.trace(`Getting key ${key}`);
43
+ const value = await this.client.get(key);
44
+ // Record get command sent to Redis
45
+ cacheMetrics.redisCommandsSentCount
46
+ .labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'get' })
47
+ .inc();
48
+ if (!value) {
49
+ logger.debug(`No entry in redis cache for key "${key}", returning undefined`);
50
+ return undefined;
51
+ }
52
+ return JSON.parse(value); // TODO: Check for invalid parsing
53
+ }
54
+ async delete(key) {
55
+ logger.trace(`Deleting key ${key}`);
56
+ await this.client.del(key);
57
+ // Record delete command sent to Redis
58
+ cacheMetrics.redisCommandsSentCount
59
+ .labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'delete' })
60
+ .inc();
61
+ }
62
+ async set(key, value, ttl) {
63
+ logger.trace(`Setting key ${key}`);
64
+ // TODO: Check for invalid stringify
65
+ await this.client.set(key, JSON.stringify(value), 'PX', ttl);
66
+ // Only record metrics if feed Id is present, otherwise assuming value is not adapter response to record
67
+ const feedId = value.metricsMeta?.feedId;
68
+ if (feedId) {
69
+ // Record cache set count, max age, and staleness (set to 0 for cache set)
70
+ const label = cacheMetrics.cacheMetricsLabel(key, feedId, cacheMetrics.CacheTypes.Redis);
71
+ cacheMetrics.cacheSet(label, ttl);
72
+ }
73
+ // Record set command sent to Redis
74
+ cacheMetrics.redisCommandsSentCount
75
+ .labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'set' })
76
+ .inc();
77
+ }
78
+ async setMany(entries, ttl) {
79
+ logger.trace(`Setting a bunch of keys`);
80
+ // Unfortunately, there's no ttl for mset
81
+ let chain = this.client.multi();
82
+ for (const entry of entries) {
83
+ chain = chain.set(entry.key, JSON.stringify(entry.value), 'PX', ttl);
84
+ // TODO: Move to after error handling once implemented to avoid recording cache sets that failed
85
+ // Only record metrics if feed Id is present, otherwise assuming value is not adapter response to record
86
+ const feedId = entry.value.metricsMeta?.feedId;
87
+ if (feedId) {
88
+ // Record cache set count, max age, and staleness (set to 0 for cache set)
89
+ const label = cacheMetrics.cacheMetricsLabel(entry.key, feedId, cacheMetrics.CacheTypes.Redis);
90
+ cacheMetrics.cacheSet(label, ttl);
91
+ }
92
+ }
93
+ await chain.exec();
94
+ // Record setMany command sent to Redis
95
+ cacheMetrics.redisCommandsSentCount
96
+ .labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'exec' })
97
+ .inc();
98
+ }
99
+ }
100
+ exports.RedisCache = RedisCache;