@chainlink/external-adapter-framework 0.0.6 → 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 -17
  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
package/dist/index.js ADDED
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.expose = void 0;
7
+ const fastify_1 = __importDefault(require("fastify"));
8
+ const path_1 = require("path");
9
+ const adapter_1 = require("./adapter");
10
+ const background_executor_1 = require("./background-executor");
11
+ const cache_1 = require("./cache");
12
+ const config_1 = require("./config");
13
+ const metrics_1 = require("./metrics");
14
+ const transports_1 = require("./transports");
15
+ const util_1 = require("./util");
16
+ const validation_1 = require("./validation");
17
+ const logger = (0, util_1.makeLogger)('Main');
18
+ const VERSION = process.env['npm_package_version'];
19
+ /**
20
+ * Main function for the framework.
21
+ * Initializes config and dependencies, uses those to initialize Transports, and starts listening for requests.
22
+ *
23
+ * @param adapter - an object describing an External Adapter
24
+ * @param dependencies - an optional object with adapter dependencies to inject
25
+ * @returns a Promise that resolves to the http.Server listening for connections
26
+ */
27
+ const expose = async (adapter, dependencies) => {
28
+ const config = (0, config_1.buildAdapterConfig)({
29
+ overrides: adapter.envDefaultOverrides,
30
+ customSettings: adapter.customSettings,
31
+ });
32
+ // Initialize adapter (create dependencies, inject them, build endpoint map, etc.)
33
+ const initializedAdapter = await (0, adapter_1.initializeAdapter)(adapter, config, dependencies);
34
+ let server = undefined;
35
+ if (config.METRICS_ENABLED && config.EXPERIMENTAL_METRICS_ENABLED) {
36
+ (0, metrics_1.setupMetricsServer)(adapter.name, config);
37
+ }
38
+ if (config.EA_MODE === 'reader' || config.EA_MODE === 'reader-writer') {
39
+ // Main REST API server to handle incoming requests
40
+ const app = await buildRestApi(config, initializedAdapter);
41
+ // Start listening for incoming requests
42
+ try {
43
+ await app.listen(config.EA_PORT, config.EA_HOST);
44
+ }
45
+ catch (err) {
46
+ logger.fatal(`There was an error when starting the EA server: ${err}`);
47
+ process.exit();
48
+ }
49
+ logger.info(`Listening on port ${app.server.address().port}`);
50
+ server = app.server;
51
+ }
52
+ else {
53
+ logger.info('REST API is disabled; this instance will not process incoming requests.');
54
+ }
55
+ if (config.EA_MODE === 'writer' || config.EA_MODE === 'reader-writer') {
56
+ // Start background loop that will take care of calling any async Transports
57
+ logger.info('Starting background execution loop');
58
+ (0, background_executor_1.callBackgroundExecutes)(initializedAdapter, server);
59
+ }
60
+ else {
61
+ logger.info('Background executor is disabled; this instance will not perform async background executes.');
62
+ }
63
+ return server;
64
+ };
65
+ exports.expose = expose;
66
+ async function buildRestApi(config, initializedAdapter) {
67
+ const app = (0, fastify_1.default)();
68
+ // Add healthcheck endpoint before middlewares to bypass them
69
+ app.get((0, path_1.join)(config.BASE_URL, 'health'), (req, res) => {
70
+ res.status(200).send({ message: 'OK', version: VERSION });
71
+ });
72
+ // Use global error handling
73
+ app.setErrorHandler(validation_1.errorCatchingMiddleware);
74
+ const transportHandler = await (0, transports_1.buildTransportHandler)(initializedAdapter);
75
+ app.register(async (router) => {
76
+ // Set up "middlewares" (hooks in fastify)
77
+ router.addHook('preHandler', (0, validation_1.validatorMiddleware)(initializedAdapter));
78
+ router.addHook('preHandler', (0, cache_1.buildCacheMiddleware)(initializedAdapter));
79
+ if (config['CORRELATION_ID_ENABLED']) {
80
+ router.addHook('onRequest', util_1.loggingContextMiddleware);
81
+ }
82
+ router.route({
83
+ url: config.BASE_URL,
84
+ method: 'POST',
85
+ handler: transportHandler,
86
+ }); // Pass config maybe? cleaner that multiple instances / dependencies
87
+ });
88
+ return app;
89
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requestDurationBuckets = exports.MAX_FEED_ID_LENGTH = exports.HttpRequestType = void 0;
4
+ var HttpRequestType;
5
+ (function (HttpRequestType) {
6
+ HttpRequestType["CACHE_HIT"] = "cacheHit";
7
+ HttpRequestType["DATA_PROVIDER_HIT"] = "dataProviderHit";
8
+ HttpRequestType["ADAPTER_ERROR"] = "adapterError";
9
+ HttpRequestType["INPUT_ERROR"] = "inputError";
10
+ HttpRequestType["RATE_LIMIT_ERROR"] = "rateLimitError";
11
+ // BURST_LIMIT_ERROR = 'burstLimitError',
12
+ // BACKOFF_ERROR = 'backoffError',
13
+ HttpRequestType["DP_ERROR"] = "dataProviderError";
14
+ HttpRequestType["TIMEOUT_ERROR"] = "timeoutError";
15
+ // CONNECTION_ERROR = 'connectionError',
16
+ // RES_EMPTY_ERROR = 'responseEmptyError',
17
+ // RES_INVALID_ERROR = 'responseInvalidError',
18
+ HttpRequestType["CUSTOM_ERROR"] = "customError";
19
+ })(HttpRequestType = exports.HttpRequestType || (exports.HttpRequestType = {}));
20
+ /**
21
+ * Maxiumum number of characters that a feedId can contain.
22
+ */
23
+ exports.MAX_FEED_ID_LENGTH = 300;
24
+ // We should tune these as we collect data, this is the default bucket distribution that prom comes with
25
+ exports.requestDurationBuckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
@@ -0,0 +1,76 @@
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.httpRequestDurationSeconds = exports.httpRequestsTotal = exports.setupMetrics = exports.setupMetricsServer = void 0;
30
+ const client = __importStar(require("prom-client"));
31
+ const constants_1 = require("./constants");
32
+ const util_1 = require("../util");
33
+ const fastify_1 = __importDefault(require("fastify"));
34
+ const path_1 = require("path");
35
+ const logger = (0, util_1.makeLogger)('Metrics');
36
+ function setupMetricsServer(name, config) {
37
+ const metricsApp = (0, fastify_1.default)({
38
+ logger: false,
39
+ });
40
+ const metricsPort = config.METRICS_PORT;
41
+ const endpoint = config.METRICS_USE_BASE_URL ? (0, path_1.join)(config.BASE_URL, 'metrics') : '/metrics';
42
+ const eaHost = config.EA_HOST;
43
+ (0, exports.setupMetrics)(name, config);
44
+ metricsApp.get(endpoint, async (_, res) => {
45
+ res.type('txt');
46
+ res.send(await client.register.metrics());
47
+ });
48
+ metricsApp.listen(metricsPort, eaHost, () => logger.info(`Monitoring listening on port ${metricsPort}!`));
49
+ }
50
+ exports.setupMetricsServer = setupMetricsServer;
51
+ const setupMetrics = (name, config) => {
52
+ client.collectDefaultMetrics();
53
+ client.register.setDefaultLabels({
54
+ app_name: config.METRICS_NAME || name || 'N/A',
55
+ app_version: config['npm_package_version'],
56
+ });
57
+ };
58
+ exports.setupMetrics = setupMetrics;
59
+ exports.httpRequestsTotal = new client.Counter({
60
+ name: 'http_requests_total',
61
+ help: 'The number of http requests this external adapter has serviced for its entire uptime',
62
+ labelNames: [
63
+ 'method',
64
+ 'status_code',
65
+ 'retry',
66
+ 'type',
67
+ 'is_cache_warming',
68
+ 'feed_id',
69
+ 'provider_status_code',
70
+ ],
71
+ });
72
+ exports.httpRequestDurationSeconds = new client.Histogram({
73
+ name: 'http_request_duration_seconds',
74
+ help: 'A histogram bucket of the distribution of http request durations',
75
+ buckets: constants_1.requestDurationBuckets,
76
+ });
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMetricsMeta = void 0;
4
+ const cache_1 = require("../cache");
5
+ const getMetricsMeta = (endpoint, data) => {
6
+ const feedId = (0, cache_1.calculateFeedId)(endpoint, data);
7
+ return { feedId };
8
+ };
9
+ exports.getMetricsMeta = getMetricsMeta;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RateLimiterFactory = void 0;
4
+ const _1 = require(".");
5
+ const util_1 = require("../util");
6
+ const logger = (0, util_1.makeLogger)('RateLimiterFactory');
7
+ class RateLimiterFactory {
8
+ static buildRateLimiter(tiers, selectedTier, strategy = _1.RateLimitingStrategy.NOP_RATE_LIMITER) {
9
+ const RateLimiterCtor = _1.RateLimiterMap[strategy];
10
+ let tier;
11
+ if (tiers) {
12
+ // Check that if the tiers object is defined, it has values
13
+ if (Object.values(tiers).length === 0) {
14
+ throw new Error(`The tiers object is defined, but has no entries`);
15
+ }
16
+ // Check that the tier set in the AdapterConfig is a valid one
17
+ if (selectedTier && !tiers[selectedTier]) {
18
+ const validTiersString = Object.keys(tiers)
19
+ .map((t) => `"${t}"`)
20
+ .join(', ');
21
+ throw new Error(`The selected rate limit tier "${selectedTier}" is not valid (can be one of ${validTiersString})`);
22
+ }
23
+ // If no selected tier is present, use the first one
24
+ // TODO: Add logic to select lowest throughput one?
25
+ tier = selectedTier ? tiers[selectedTier] : Object.values(tiers)[0];
26
+ }
27
+ const rateLimiter = new RateLimiterCtor();
28
+ rateLimiter.initialize(tier);
29
+ logger.info(`Initialized rate limiter using "${strategy}" strategy.`);
30
+ return rateLimiter;
31
+ }
32
+ }
33
+ exports.RateLimiterFactory = RateLimiterFactory;
@@ -0,0 +1,36 @@
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.RateLimiterMap = exports.RateLimitingStrategy = void 0;
18
+ const nop_limiter_1 = require("./nop-limiter");
19
+ const simple_counting_1 = require("./simple-counting");
20
+ __exportStar(require("./simple-counting"), exports);
21
+ __exportStar(require("./factory"), exports);
22
+ /**
23
+ * Enum to easily specify rate limiting strategy in the Adapter config
24
+ */
25
+ var RateLimitingStrategy;
26
+ (function (RateLimitingStrategy) {
27
+ RateLimitingStrategy["SIMPLE_COUNTING_LIMITER"] = "SIMPLE_COUNTING_LIMITER";
28
+ RateLimitingStrategy["NOP_RATE_LIMITER"] = "NOP_RATE_LIMITER";
29
+ })(RateLimitingStrategy = exports.RateLimitingStrategy || (exports.RateLimitingStrategy = {}));
30
+ /**
31
+ * Record to map a limiting strategy to the implementing class
32
+ */
33
+ exports.RateLimiterMap = {
34
+ [RateLimitingStrategy.SIMPLE_COUNTING_LIMITER]: simple_counting_1.SimpleCountingRateLimiter,
35
+ [RateLimitingStrategy.NOP_RATE_LIMITER]: nop_limiter_1.NopRateLimiter,
36
+ };
@@ -0,0 +1,32 @@
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.rateLimitCreditsSpentTotal = void 0;
27
+ const client = __importStar(require("prom-client"));
28
+ exports.rateLimitCreditsSpentTotal = new client.Counter({
29
+ name: 'rate_limit_credits_spent_total',
30
+ help: 'The number of data provider credits the adapter is consuming',
31
+ labelNames: ['participant_id', 'feed_id', 'experimental'],
32
+ });
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NopRateLimiter = void 0;
4
+ /**
5
+ * Default rate limiter that will basically do nothing, always allow requests through
6
+ */
7
+ class NopRateLimiter {
8
+ initialize() {
9
+ return;
10
+ }
11
+ isUnderLimits() {
12
+ return true;
13
+ }
14
+ }
15
+ exports.NopRateLimiter = NopRateLimiter;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SimpleCountingRateLimiter = void 0;
4
+ const util_1 = require("../util");
5
+ const logger = (0, util_1.makeLogger)('SimpleCountingRateLimiter');
6
+ /**
7
+ * This rate limiter is the simplest stateful option.
8
+ * On startup, it'll compare the different thresholds for each tier, calculate them all
9
+ * in the finest window we'll use (seconds), and use the most restrictive one.
10
+ * This is so if the EA were to restart, we don't need to worry about persisting state
11
+ * for things like daily quotas. The downside is that this does not work well for bursty
12
+ * loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
13
+ */
14
+ class SimpleCountingRateLimiter {
15
+ constructor() {
16
+ this.latestSecondInterval = 0;
17
+ this.requestsThisSecond = 0;
18
+ this.latestMinuteInterval = 0;
19
+ this.requestsThisMinute = 0;
20
+ }
21
+ initialize(limits) {
22
+ // Translate the hourly limit into reqs per minute
23
+ const perHourLimit = (limits?.rateLimit1h || Infinity) / 60;
24
+ this.perMinuteLimit = Math.min(limits?.rateLimit1m || Infinity, perHourLimit);
25
+ this.perSecondLimit = limits?.rateLimit1s || Infinity;
26
+ logger.debug(`Using rate limiting settings: perMinute = ${this.perMinuteLimit} | perSecond: = ${this.perSecondLimit}`);
27
+ }
28
+ isUnderLimits() {
29
+ // If the limit is set to infinity, there was no tier limit specified
30
+ if (this.perSecondLimit === Infinity && this.perMinuteLimit === Infinity) {
31
+ return true;
32
+ }
33
+ const now = Date.now();
34
+ const nearestSecondInterval = Math.floor(now / 1000);
35
+ const nearestMinuteInterval = Math.floor(now / (1000 * 60));
36
+ // This should always run to completion, even if it doesn't look atomic; therefore the
37
+ // Ops should be "thread safe". Thank JS and its infinite single threaded dumbness.
38
+ if (nearestSecondInterval !== this.latestSecondInterval) {
39
+ logger.trace(`Clearing latest second interval, # of requests logged was: ${this.requestsThisSecond} `);
40
+ this.latestSecondInterval = nearestSecondInterval;
41
+ this.requestsThisSecond = 0;
42
+ }
43
+ if (nearestMinuteInterval !== this.latestMinuteInterval) {
44
+ logger.trace(`Clearing latest second minute, # of requests logged was: ${this.requestsThisMinute} `);
45
+ this.latestMinuteInterval = nearestMinuteInterval;
46
+ this.requestsThisMinute = 0;
47
+ }
48
+ if (this.requestsThisSecond < this.perSecondLimit &&
49
+ this.requestsThisMinute < this.perMinuteLimit) {
50
+ logger.trace('Request under limits, counting +1');
51
+ this.requestsThisSecond++;
52
+ this.requestsThisMinute++;
53
+ return true;
54
+ }
55
+ else {
56
+ logger.trace('Requests seen this interval are above limits');
57
+ return false;
58
+ }
59
+ }
60
+ }
61
+ exports.SimpleCountingRateLimiter = SimpleCountingRateLimiter;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initializeAdapter = exports.initializeDependencies = void 0;
4
+ const factory_1 = require("./cache/factory");
5
+ const rate_limiting_1 = require("./rate-limiting");
6
+ const util_1 = require("./util");
7
+ const logger = (0, util_1.makeLogger)('Adapter');
8
+ /**
9
+ * This function will take an adapter structure and go through each endpoint, calculating
10
+ * each one's allocation of the total rate limits that are set for the adapter as a whole.
11
+ *
12
+ * @param adapter - the adapter to initialize rate limiting for
13
+ */
14
+ const calculateRateLimitAllocations = (adapter) => {
15
+ const numberOfEndpoints = adapter.endpoints.length;
16
+ const endpointsWithExplicitAllocations = adapter.endpoints.filter((e) => e.rateLimiting);
17
+ const totalExplicitAllocation = endpointsWithExplicitAllocations
18
+ .map((e) => e.rateLimiting?.allocationPercentage || 0)
19
+ .reduce((sum, next) => sum + next, 0);
20
+ if (totalExplicitAllocation > 100) {
21
+ throw new Error('The total allocation set for all endpoints summed cannot exceed 100%');
22
+ }
23
+ if (totalExplicitAllocation === 100 &&
24
+ numberOfEndpoints - endpointsWithExplicitAllocations.length > 0) {
25
+ throw new Error('The explicit allocation is at 100% but there are endpoints with implicit allocation');
26
+ }
27
+ const implicitAllocation = 100 - totalExplicitAllocation;
28
+ logger.debug('Adapter rate limit allocations:');
29
+ for (const endpoint of adapter.endpoints) {
30
+ if (!endpoint.rateLimiting) {
31
+ endpoint.rateLimiting = {
32
+ allocationPercentage: implicitAllocation / (numberOfEndpoints - endpointsWithExplicitAllocations.length),
33
+ };
34
+ }
35
+ logger.debug(`Endpoint [${endpoint.name}] - ${endpoint.rateLimiting?.allocationPercentage}%`);
36
+ }
37
+ };
38
+ /**
39
+ * This function will process dependencies for an adapter, such as caches or rate limiters,
40
+ * in order to inject them into transports and other relevant places later in the lifecycle.
41
+ *
42
+ * @param config - the configuration for this adapter
43
+ * @param inputDependencies - a partial obj of initialized dependencies to override the created ones
44
+ * @param rateLimitingConfig - details from the adapter regarding rate limiting
45
+ * @returns a set of AdapterDependencies all initialized
46
+ */
47
+ const initializeDependencies = (adapter, config, inputDependencies) => {
48
+ const dependencies = inputDependencies || {};
49
+ if (!dependencies.cache) {
50
+ dependencies.cache = factory_1.CacheFactory.buildCache(config);
51
+ }
52
+ // In the future we might want something more complex, but for now it's better to simplify
53
+ // and just use the same rate limiting for everything. Once we have a more complex use case we
54
+ // can think of ways to make this more configurable.
55
+ const rateLimitingTier = (0, rate_limiting_1.getRateLimitingTier)(adapter.rateLimiting?.tiers, config.RATE_LIMIT_API_TIER);
56
+ if (!dependencies.requestRateLimiter) {
57
+ dependencies.requestRateLimiter = new rate_limiting_1.SimpleCountingRateLimiter().initialize(adapter.endpoints, rateLimitingTier);
58
+ }
59
+ if (!dependencies.backgroundExecuteRateLimiter) {
60
+ dependencies.backgroundExecuteRateLimiter = new rate_limiting_1.FixedFrequencyRateLimiter().initialize(adapter.endpoints, rateLimitingTier);
61
+ }
62
+ return dependencies;
63
+ };
64
+ exports.initializeDependencies = initializeDependencies;
65
+ /**
66
+ * Takes an adapter and normalizes all endpoint names and aliases, as well as the default endpoint.
67
+ * i.e. makes them lowercase for now
68
+ * @param adapter - an instance of an Adapter
69
+ */
70
+ const normalizeEndpointNames = (adapter) => {
71
+ // Make endpoints case insensitive, including default
72
+ adapter.defaultEndpoint = adapter.defaultEndpoint?.toLowerCase();
73
+ for (const endpoint of adapter.endpoints) {
74
+ endpoint.name = endpoint.name.toLowerCase();
75
+ endpoint.aliases = endpoint.aliases?.map((a) => a.toLowerCase());
76
+ }
77
+ };
78
+ /**
79
+ * Initializes all of the [[Transport]]s in the adapter, passing along any [[AdapterDependencies]] and [[AdapterConfig]].
80
+ * Additionally, it builds a map out of all the endpoint names and aliases (checking for duplicates).
81
+ *
82
+ * @param adapter - an instance of an Adapter
83
+ * @param dependencies - dependencies that the adapter will need at initialization
84
+ * @param config - configuration variables already processed and validated
85
+ * @returns - the adapter with all transports initialized and aliases map built
86
+ */
87
+ const initializeAdapter = async (adapter, config, dependencies) => {
88
+ normalizeEndpointNames(adapter);
89
+ calculateRateLimitAllocations(adapter);
90
+ const initializedDependencies = (0, exports.initializeDependencies)(adapter, config, dependencies);
91
+ const endpointsMap = {};
92
+ for (const endpoint of adapter.endpoints) {
93
+ // Add aliases to map to use in validation
94
+ const aliases = [endpoint.name, ...(endpoint.aliases || [])];
95
+ for (const alias of aliases) {
96
+ if (endpointsMap[alias]) {
97
+ throw new Error(`Duplicate endpoint / alias: "${alias}"`);
98
+ }
99
+ endpointsMap[alias] = endpoint;
100
+ }
101
+ logger.debug(`Initializing transport for endpoint "${endpoint.name}"...`);
102
+ await endpoint.transport.initialize(initializedDependencies);
103
+ }
104
+ logger.debug('Adapter initialization complete.');
105
+ return {
106
+ ...adapter,
107
+ endpointsMap,
108
+ dependencies: initializedDependencies,
109
+ config,
110
+ };
111
+ };
112
+ exports.initializeAdapter = initializeAdapter;
@@ -0,0 +1,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;