@chainlink/external-adapter-framework 0.0.10 → 0.0.14

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 (128) hide show
  1. package/adapter.d.ts +22 -3
  2. package/adapter.js +5 -2
  3. package/cache/factory.js +0 -2
  4. package/cache/index.d.ts +6 -2
  5. package/cache/index.js +13 -9
  6. package/cache/redis.js +5 -5
  7. package/chainlink-external-adapter-framework-0.0.6.tgz +0 -0
  8. package/config/index.d.ts +15 -1
  9. package/config/index.js +19 -4
  10. package/config/provider-limits.js +5 -1
  11. package/examples/bank-frick/accounts.d.ts +39 -0
  12. package/examples/bank-frick/accounts.js +191 -0
  13. package/examples/bank-frick/config/index.d.ts +4 -0
  14. package/examples/bank-frick/config/index.js +54 -0
  15. package/examples/bank-frick/index.d.ts +2 -0
  16. package/examples/bank-frick/index.js +14 -0
  17. package/examples/bank-frick/util.d.ts +4 -0
  18. package/examples/bank-frick/util.js +39 -0
  19. package/index.d.ts +1 -2
  20. package/index.js +42 -1
  21. package/metrics/index.js +0 -1
  22. package/metrics/util.d.ts +5 -1
  23. package/metrics/util.js +2 -2
  24. package/package/adapter.d.ts +88 -0
  25. package/package/adapter.js +112 -0
  26. package/package/background-executor.d.ts +11 -0
  27. package/package/background-executor.js +45 -0
  28. package/package/cache/factory.d.ts +6 -0
  29. package/package/cache/factory.js +57 -0
  30. package/package/cache/index.d.ts +90 -0
  31. package/package/cache/index.js +169 -0
  32. package/package/cache/local.d.ts +23 -0
  33. package/package/cache/local.js +83 -0
  34. package/package/cache/metrics.d.ts +27 -0
  35. package/package/cache/metrics.js +120 -0
  36. package/package/cache/redis.d.ts +16 -0
  37. package/package/cache/redis.js +100 -0
  38. package/package/config/index.d.ts +195 -0
  39. package/package/config/index.js +365 -0
  40. package/package/config/provider-limits.d.ts +31 -0
  41. package/package/config/provider-limits.js +76 -0
  42. package/package/examples/coingecko/batch-warming.d.ts +2 -0
  43. package/package/examples/coingecko/batch-warming.js +52 -0
  44. package/package/examples/coingecko/index.d.ts +2 -0
  45. package/package/examples/coingecko/index.js +10 -0
  46. package/package/examples/coingecko/rest.d.ts +2 -0
  47. package/package/examples/coingecko/rest.js +50 -0
  48. package/package/examples/ncfx/config/index.d.ts +12 -0
  49. package/package/examples/ncfx/config/index.js +15 -0
  50. package/package/examples/ncfx/index.d.ts +2 -0
  51. package/package/examples/ncfx/index.js +10 -0
  52. package/package/examples/ncfx/websocket.d.ts +36 -0
  53. package/package/examples/ncfx/websocket.js +72 -0
  54. package/package/index.d.ts +12 -0
  55. package/package/index.js +92 -0
  56. package/package/metrics/constants.d.ts +16 -0
  57. package/package/metrics/constants.js +25 -0
  58. package/package/metrics/index.d.ts +15 -0
  59. package/package/metrics/index.js +123 -0
  60. package/package/metrics/util.d.ts +3 -0
  61. package/package/metrics/util.js +9 -0
  62. package/package/package.json +72 -0
  63. package/package/rate-limiting/background/fixed-frequency.d.ts +10 -0
  64. package/package/rate-limiting/background/fixed-frequency.js +37 -0
  65. package/package/rate-limiting/index.d.ts +54 -0
  66. package/package/rate-limiting/index.js +63 -0
  67. package/package/rate-limiting/metrics.d.ts +3 -0
  68. package/package/rate-limiting/metrics.js +44 -0
  69. package/package/rate-limiting/request/simple-counting.d.ts +20 -0
  70. package/package/rate-limiting/request/simple-counting.js +62 -0
  71. package/package/test.d.ts +1 -0
  72. package/package/test.js +6 -0
  73. package/package/transports/batch-warming.d.ts +34 -0
  74. package/package/transports/batch-warming.js +101 -0
  75. package/package/transports/index.d.ts +87 -0
  76. package/package/transports/index.js +87 -0
  77. package/package/transports/metrics.d.ts +21 -0
  78. package/package/transports/metrics.js +105 -0
  79. package/package/transports/rest.d.ts +43 -0
  80. package/package/transports/rest.js +129 -0
  81. package/package/transports/util.d.ts +8 -0
  82. package/package/transports/util.js +85 -0
  83. package/package/transports/websocket.d.ts +80 -0
  84. package/package/transports/websocket.js +169 -0
  85. package/package/util/expiring-sorted-set.d.ts +21 -0
  86. package/package/util/expiring-sorted-set.js +47 -0
  87. package/package/util/index.d.ts +11 -0
  88. package/package/util/index.js +35 -0
  89. package/package/util/logger.d.ts +42 -0
  90. package/package/util/logger.js +62 -0
  91. package/package/util/request.d.ts +55 -0
  92. package/package/util/request.js +2 -0
  93. package/package/validation/error.d.ts +50 -0
  94. package/package/validation/error.js +79 -0
  95. package/package/validation/index.d.ts +5 -0
  96. package/package/validation/index.js +86 -0
  97. package/package/validation/input-params.d.ts +15 -0
  98. package/package/validation/input-params.js +30 -0
  99. package/package/validation/override-functions.d.ts +3 -0
  100. package/package/validation/override-functions.js +40 -0
  101. package/package/validation/preset-tokens.json +23 -0
  102. package/package/validation/validator.d.ts +47 -0
  103. package/package/validation/validator.js +303 -0
  104. package/package.json +5 -3
  105. package/rate-limiting/background/fixed-frequency.js +0 -2
  106. package/test.js +2 -2
  107. package/transports/batch-warming.d.ts +4 -3
  108. package/transports/batch-warming.js +4 -4
  109. package/transports/index.d.ts +4 -21
  110. package/transports/index.js +3 -3
  111. package/transports/metrics.d.ts +1 -1
  112. package/transports/metrics.js +2 -2
  113. package/transports/rest.d.ts +2 -1
  114. package/transports/rest.js +3 -1
  115. package/transports/websocket.d.ts +5 -4
  116. package/transports/websocket.js +5 -6
  117. package/util/index.d.ts +2 -1
  118. package/util/index.js +1 -1
  119. package/util/request.d.ts +3 -1
  120. package/util/subscription-set/expiring-sorted-set.d.ts +22 -0
  121. package/util/subscription-set/expiring-sorted-set.js +47 -0
  122. package/util/subscription-set/subscription-set.d.ts +18 -0
  123. package/util/subscription-set/subscription-set.js +19 -0
  124. package/util/test-payload-loader.d.ts +25 -0
  125. package/util/test-payload-loader.js +83 -0
  126. package/validation/error.d.ts +2 -2
  127. package/validation/error.js +1 -1
  128. package/validation/index.js +8 -3
@@ -0,0 +1,39 @@
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.generateJWT = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const util_1 = require("../../util");
10
+ const logger = (0, util_1.makeLogger)('BankFrickUtil');
11
+ // Used by all endpoints requiring authentication
12
+ const generateJWT = async (config, signingAlgorithm = 'rsa-sha512') => {
13
+ logger.info("Generating a new JWT because we don't have one in config.token");
14
+ const { API_KEY, PRIVATE_KEY, API_ENDPOINT } = config;
15
+ // All of these are required, so validation should have failed prior to this line
16
+ if (!API_KEY || !PRIVATE_KEY) {
17
+ throw new Error('API_KEY, PRIVATE_KEY, and PASSWORD all must be defined to get a new token\n' +
18
+ 'Received: \n' +
19
+ `API_KEY: ${API_KEY}\n` +
20
+ `PRIVATE_KEY: ${PRIVATE_KEY}`);
21
+ }
22
+ const data = {
23
+ key: API_KEY,
24
+ };
25
+ const signature = crypto_1.default.sign(signingAlgorithm, Buffer.from(JSON.stringify(data)), PRIVATE_KEY);
26
+ const options = {
27
+ method: 'POST',
28
+ baseURL: API_ENDPOINT,
29
+ url: `authorize`,
30
+ headers: {
31
+ Signature: signature.toString('base64'),
32
+ algorithm: signingAlgorithm,
33
+ },
34
+ data,
35
+ };
36
+ const response = await axios_1.default.request(options);
37
+ return response.data.token;
38
+ };
39
+ exports.generateJWT = generateJWT;
package/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { Server } from 'http';
2
- import { Adapter } from './adapter';
3
- import { AdapterDependencies } from './transports';
2
+ import { Adapter, AdapterDependencies } from './adapter';
4
3
  /**
5
4
  * Main function for the framework.
6
5
  * Initializes config and dependencies, uses those to initialize Transports, and starts listening for requests.
package/index.js CHANGED
@@ -13,6 +13,7 @@ const config_1 = require("./config");
13
13
  const metrics_1 = require("./metrics");
14
14
  const transports_1 = require("./transports");
15
15
  const util_1 = require("./util");
16
+ const test_payload_loader_1 = require("./util/test-payload-loader");
16
17
  const validation_1 = require("./validation");
17
18
  const logger = (0, util_1.makeLogger)('Main');
18
19
  const VERSION = process.env['npm_package_version'];
@@ -83,10 +84,50 @@ async function buildRestApi(config, initializedAdapter) {
83
84
  url: config.BASE_URL,
84
85
  method: 'POST',
85
86
  handler: transportHandler,
86
- }); // Pass config maybe? cleaner that multiple instances / dependencies
87
+ });
87
88
  if (config.METRICS_ENABLED && config.EXPERIMENTAL_METRICS_ENABLED) {
88
89
  router.addHook('onResponse', metrics_1.buildMetricsMiddleware);
89
90
  }
90
91
  });
92
+ // Add smoke endpoint after middleware which are needed for tests
93
+ buildSmokeEndpoint(app, config);
91
94
  return app;
92
95
  }
96
+ /**
97
+ * Adds the /smoke endpoint to the API for smoke testing the adapter
98
+ *
99
+ * @param app - the Fastify instance
100
+ * @param config - the initialized adapter config
101
+ */
102
+ function buildSmokeEndpoint(app, config) {
103
+ const testPayload = (0, test_payload_loader_1.loadTestPayload)(config.SMOKE_TEST_PAYLOAD_FILE_NAME);
104
+ app.get((0, path_1.join)(config.BASE_URL, 'smoke'), async (_, res) => {
105
+ if (testPayload.isDefault) {
106
+ return res.status(200).send('OK');
107
+ }
108
+ const errors = [];
109
+ for (const index in testPayload.requests) {
110
+ try {
111
+ const request = { id: index, data: testPayload.requests[index] };
112
+ // Use Fastify's app inject to pass smoke requests internally
113
+ const response = await app.inject({
114
+ method: 'POST',
115
+ url: '/',
116
+ payload: request,
117
+ });
118
+ const parsedResponse = JSON.parse(response.body);
119
+ // Throw error if not 2xx status code
120
+ if (parsedResponse.statusCode < 200 || parsedResponse.statusCode > 299) {
121
+ throw Error('Smoke test request failed');
122
+ }
123
+ }
124
+ catch (e) {
125
+ errors.push(e);
126
+ }
127
+ }
128
+ if (errors.length > 0) {
129
+ return res.status(500).send(errors);
130
+ }
131
+ return res.status(200).send('OK');
132
+ });
133
+ }
package/metrics/index.js CHANGED
@@ -86,7 +86,6 @@ const buildHttpRequestMetricsLabel = (feedId, error, cacheHit) => {
86
86
  }
87
87
  else if (error instanceof Error) {
88
88
  // If error present and not instance of generic Error, unexpected failure occurred
89
- // TODO: Build label with 500 error and withold dp status? Status sent as 200 in error handler
90
89
  labels.type = constants_1.HttpRequestType.ADAPTER_ERROR;
91
90
  labels.status_code = 500;
92
91
  }
package/metrics/util.d.ts CHANGED
@@ -1,3 +1,7 @@
1
1
  import { AdapterMetricsMeta, AdapterRequestData } from '../util';
2
2
  import { AdapterEndpoint } from '../adapter';
3
- export declare const getMetricsMeta: (endpoint: AdapterEndpoint, data: AdapterRequestData) => AdapterMetricsMeta;
3
+ import { AdapterConfig } from '../config';
4
+ export declare const getMetricsMeta: ({ adapterEndpoint, adapterConfig, }: {
5
+ adapterEndpoint: AdapterEndpoint;
6
+ adapterConfig: AdapterConfig;
7
+ }, data: AdapterRequestData) => AdapterMetricsMeta;
package/metrics/util.js CHANGED
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getMetricsMeta = void 0;
4
4
  const cache_1 = require("../cache");
5
- const getMetricsMeta = (endpoint, data) => {
6
- const feedId = (0, cache_1.calculateFeedId)(endpoint, data);
5
+ const getMetricsMeta = ({ adapterEndpoint, adapterConfig, }, data) => {
6
+ const feedId = (0, cache_1.calculateFeedId)({ adapterEndpoint, adapterConfig }, data);
7
7
  return { feedId };
8
8
  };
9
9
  exports.getMetricsMeta = getMetricsMeta;
@@ -0,0 +1,88 @@
1
+ import { AdapterConfig, BaseAdapterConfig, SettingsMap } from './config';
2
+ import { AdapterRateLimitTier } from './rate-limiting';
3
+ import { AdapterDependencies, Transport } from './transports';
4
+ import { InputParameters } from './validation/input-params';
5
+ /**
6
+ * Structure to describe rate limits specs for the Adapter
7
+ */
8
+ interface AdapterRateLimitingConfig {
9
+ /** Adapter rate limits, gotten from the specific tier requested */
10
+ tiers: Record<string, AdapterRateLimitTier>;
11
+ }
12
+ /**
13
+ * Main structure of an External Adapter
14
+ */
15
+ export interface Adapter {
16
+ /** Name of the adapter */
17
+ name: string;
18
+ /** If present, the string that will be used for requests with no specified endpoint */
19
+ defaultEndpoint?: string;
20
+ /** List of [[AdapterEndpoint]]s in the adapter */
21
+ endpoints: AdapterEndpoint[];
22
+ /** Map of overrides to the default config values for an Adapter */
23
+ envDefaultOverrides?: Partial<BaseAdapterConfig>;
24
+ /** List of custom env vars for this particular adapter (e.g. RPC_URL) */
25
+ customSettings?: SettingsMap;
26
+ /** Configuration relevant to outbound (EA --\> DP) communication rate limiting */
27
+ rateLimiting?: AdapterRateLimitingConfig;
28
+ /** Overrides for converting the 'base' parameter that are hardcoded into the adapter. */
29
+ overrides?: Record<string, string>;
30
+ }
31
+ /**
32
+ * Structure to describe rate limits specs for a specific adapter endpoint
33
+ */
34
+ export interface EndpointRateLimitingConfig {
35
+ /**
36
+ * How much of the total limit for the adapter will be assigned to this specific endpoint.
37
+ * Should be a non-zero positive number up to 100.
38
+ * Endpoints in the same adapter without a specific allocation will divide the remaining limits equally.
39
+ */
40
+ allocationPercentage: number;
41
+ }
42
+ /**
43
+ * Structure to describe a specific endpoint in an [[Adapter]]
44
+ */
45
+ export interface AdapterEndpoint {
46
+ /** Name that will be used to match input params to this endpoint (case insensitive) */
47
+ name: string;
48
+ /** List of alternative endpoint names that will resolve to this same transport (case insensitive) */
49
+ aliases?: string[];
50
+ /** Transport that will be used to handle data processing and communication for this endpoint */
51
+ transport: Transport<any, any, any>;
52
+ /** Specification of what the body of a request hitting this endpoint should look like (used for validation) */
53
+ inputParameters: InputParameters;
54
+ /** Specific details related to the rate limiting for this endpoint in particular */
55
+ rateLimiting?: EndpointRateLimitingConfig;
56
+ }
57
+ /**
58
+ * Structure to describe an adapter that has been initialized
59
+ */
60
+ export interface InitializedAdapter extends Adapter {
61
+ /** Object containing alias translations for all endpoints */
62
+ endpointsMap: Record<string, AdapterEndpoint>;
63
+ /** Initialized dependencies that the adapter will use */
64
+ dependencies: AdapterDependencies;
65
+ /** Configuration params for various adapter properties */
66
+ config: AdapterConfig;
67
+ }
68
+ /**
69
+ * This function will process dependencies for an adapter, such as caches or rate limiters,
70
+ * in order to inject them into transports and other relevant places later in the lifecycle.
71
+ *
72
+ * @param config - the configuration for this adapter
73
+ * @param inputDependencies - a partial obj of initialized dependencies to override the created ones
74
+ * @param rateLimitingConfig - details from the adapter regarding rate limiting
75
+ * @returns a set of AdapterDependencies all initialized
76
+ */
77
+ export declare const initializeDependencies: (adapter: Adapter, config: AdapterConfig, inputDependencies?: Partial<AdapterDependencies>) => AdapterDependencies;
78
+ /**
79
+ * Initializes all of the [[Transport]]s in the adapter, passing along any [[AdapterDependencies]] and [[AdapterConfig]].
80
+ * Additionally, it builds a map out of all the endpoint names and aliases (checking for duplicates).
81
+ *
82
+ * @param adapter - an instance of an Adapter
83
+ * @param dependencies - dependencies that the adapter will need at initialization
84
+ * @param config - configuration variables already processed and validated
85
+ * @returns - the adapter with all transports initialized and aliases map built
86
+ */
87
+ export declare const initializeAdapter: (adapter: Adapter, config: AdapterConfig, dependencies?: Partial<AdapterDependencies>) => Promise<InitializedAdapter>;
88
+ export {};
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initializeAdapter = exports.initializeDependencies = void 0;
4
+ const factory_1 = require("./cache/factory");
5
+ const rate_limiting_1 = require("./rate-limiting");
6
+ const util_1 = require("./util");
7
+ const logger = (0, util_1.makeLogger)('Adapter');
8
+ /**
9
+ * This function will take an adapter structure and go through each endpoint, calculating
10
+ * each one's allocation of the total rate limits that are set for the adapter as a whole.
11
+ *
12
+ * @param adapter - the adapter to initialize rate limiting for
13
+ */
14
+ const calculateRateLimitAllocations = (adapter) => {
15
+ const numberOfEndpoints = adapter.endpoints.length;
16
+ const endpointsWithExplicitAllocations = adapter.endpoints.filter((e) => e.rateLimiting);
17
+ const totalExplicitAllocation = endpointsWithExplicitAllocations
18
+ .map((e) => e.rateLimiting?.allocationPercentage || 0)
19
+ .reduce((sum, next) => sum + next, 0);
20
+ if (totalExplicitAllocation > 100) {
21
+ throw new Error('The total allocation set for all endpoints summed cannot exceed 100%');
22
+ }
23
+ if (totalExplicitAllocation === 100 &&
24
+ numberOfEndpoints - endpointsWithExplicitAllocations.length > 0) {
25
+ throw new Error('The explicit allocation is at 100% but there are endpoints with implicit allocation');
26
+ }
27
+ const implicitAllocation = 100 - totalExplicitAllocation;
28
+ logger.debug('Adapter rate limit allocations:');
29
+ for (const endpoint of adapter.endpoints) {
30
+ if (!endpoint.rateLimiting) {
31
+ endpoint.rateLimiting = {
32
+ allocationPercentage: implicitAllocation / (numberOfEndpoints - endpointsWithExplicitAllocations.length),
33
+ };
34
+ }
35
+ logger.debug(`Endpoint [${endpoint.name}] - ${endpoint.rateLimiting?.allocationPercentage}%`);
36
+ }
37
+ };
38
+ /**
39
+ * This function will process dependencies for an adapter, such as caches or rate limiters,
40
+ * in order to inject them into transports and other relevant places later in the lifecycle.
41
+ *
42
+ * @param config - the configuration for this adapter
43
+ * @param inputDependencies - a partial obj of initialized dependencies to override the created ones
44
+ * @param rateLimitingConfig - details from the adapter regarding rate limiting
45
+ * @returns a set of AdapterDependencies all initialized
46
+ */
47
+ const initializeDependencies = (adapter, config, inputDependencies) => {
48
+ const dependencies = inputDependencies || {};
49
+ if (!dependencies.cache) {
50
+ dependencies.cache = factory_1.CacheFactory.buildCache(config);
51
+ }
52
+ // In the future we might want something more complex, but for now it's better to simplify
53
+ // and just use the same rate limiting for everything. Once we have a more complex use case we
54
+ // can think of ways to make this more configurable.
55
+ const rateLimitingTier = (0, rate_limiting_1.getRateLimitingTier)(adapter.rateLimiting?.tiers, config.RATE_LIMIT_API_TIER);
56
+ if (!dependencies.requestRateLimiter) {
57
+ dependencies.requestRateLimiter = new rate_limiting_1.SimpleCountingRateLimiter().initialize(adapter.endpoints, rateLimitingTier);
58
+ }
59
+ if (!dependencies.backgroundExecuteRateLimiter) {
60
+ dependencies.backgroundExecuteRateLimiter = new rate_limiting_1.FixedFrequencyRateLimiter().initialize(adapter.endpoints, rateLimitingTier);
61
+ }
62
+ return dependencies;
63
+ };
64
+ exports.initializeDependencies = initializeDependencies;
65
+ /**
66
+ * Takes an adapter and normalizes all endpoint names and aliases, as well as the default endpoint.
67
+ * i.e. makes them lowercase for now
68
+ * @param adapter - an instance of an Adapter
69
+ */
70
+ const normalizeEndpointNames = (adapter) => {
71
+ // Make endpoints case insensitive, including default
72
+ adapter.defaultEndpoint = adapter.defaultEndpoint?.toLowerCase();
73
+ for (const endpoint of adapter.endpoints) {
74
+ endpoint.name = endpoint.name.toLowerCase();
75
+ endpoint.aliases = endpoint.aliases?.map((a) => a.toLowerCase());
76
+ }
77
+ };
78
+ /**
79
+ * Initializes all of the [[Transport]]s in the adapter, passing along any [[AdapterDependencies]] and [[AdapterConfig]].
80
+ * Additionally, it builds a map out of all the endpoint names and aliases (checking for duplicates).
81
+ *
82
+ * @param adapter - an instance of an Adapter
83
+ * @param dependencies - dependencies that the adapter will need at initialization
84
+ * @param config - configuration variables already processed and validated
85
+ * @returns - the adapter with all transports initialized and aliases map built
86
+ */
87
+ const initializeAdapter = async (adapter, config, dependencies) => {
88
+ normalizeEndpointNames(adapter);
89
+ calculateRateLimitAllocations(adapter);
90
+ const initializedDependencies = (0, exports.initializeDependencies)(adapter, config, dependencies);
91
+ const endpointsMap = {};
92
+ for (const endpoint of adapter.endpoints) {
93
+ // Add aliases to map to use in validation
94
+ const aliases = [endpoint.name, ...(endpoint.aliases || [])];
95
+ for (const alias of aliases) {
96
+ if (endpointsMap[alias]) {
97
+ throw new Error(`Duplicate endpoint / alias: "${alias}"`);
98
+ }
99
+ endpointsMap[alias] = endpoint;
100
+ }
101
+ logger.debug(`Initializing transport for endpoint "${endpoint.name}"...`);
102
+ await endpoint.transport.initialize(initializedDependencies);
103
+ }
104
+ logger.debug('Adapter initialization complete.');
105
+ return {
106
+ ...adapter,
107
+ endpointsMap,
108
+ dependencies: initializedDependencies,
109
+ config,
110
+ };
111
+ };
112
+ exports.initializeAdapter = initializeAdapter;
@@ -0,0 +1,11 @@
1
+ /// <reference types="node" />
2
+ import { Server } from 'http';
3
+ import { InitializedAdapter } from './adapter';
4
+ /**
5
+ * Very simple background loop that will call the [[Transport.backgroundExecute]] functions in all Transports.
6
+ * It gets the time in ms to wait as the return value from those functions, and sleeps until next execution.
7
+ *
8
+ * @param adapter - an initialized External Adapter
9
+ * @param server - the http server to attach an on close listener to
10
+ */
11
+ export declare function callBackgroundExecutes(adapter: InitializedAdapter, server?: Server): Promise<void>;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.callBackgroundExecutes = void 0;
4
+ const util_1 = require("./util");
5
+ const logger = (0, util_1.makeLogger)('BackgroundExecutor');
6
+ /**
7
+ * Very simple background loop that will call the [[Transport.backgroundExecute]] functions in all Transports.
8
+ * It gets the time in ms to wait as the return value from those functions, and sleeps until next execution.
9
+ *
10
+ * @param adapter - an initialized External Adapter
11
+ * @param server - the http server to attach an on close listener to
12
+ */
13
+ async function callBackgroundExecutes(adapter, server) {
14
+ // Set up variable to check later on to see if we need to stop this background "thread"
15
+ // If no server is provided, the listener won't be set and serverClosed will always be false
16
+ let serverClosed = false;
17
+ server?.on('close', () => {
18
+ serverClosed = true;
19
+ });
20
+ for (const endpoint of adapter.endpoints) {
21
+ const backgroundExecute = endpoint.transport.backgroundExecute?.bind(endpoint.transport);
22
+ if (!backgroundExecute) {
23
+ logger.debug(`Endpoint "${endpoint.name}" has no background execute, skipping...`);
24
+ continue;
25
+ }
26
+ const context = {
27
+ adapterEndpoint: endpoint,
28
+ adapterConfig: adapter.config,
29
+ };
30
+ const handler = async () => {
31
+ if (serverClosed) {
32
+ logger.info('Server closed, stopping recursive backgroundExecute handler chain');
33
+ return;
34
+ }
35
+ logger.debug(`Calling background execute for endpoint "${endpoint.name}"`);
36
+ const timeToWait = await backgroundExecute(context);
37
+ logger.debug(`Finished background execute for endpoint "${endpoint.name}", sleeping for ${timeToWait}ms`);
38
+ await (0, util_1.sleep)(timeToWait);
39
+ handler();
40
+ };
41
+ // Start recursive async calls
42
+ handler();
43
+ }
44
+ }
45
+ exports.callBackgroundExecutes = callBackgroundExecutes;
@@ -0,0 +1,6 @@
1
+ import { AdapterConfig } from '../config';
2
+ import { LocalCache } from './local';
3
+ import { RedisCache } from './redis';
4
+ export declare class CacheFactory {
5
+ static buildCache(config: AdapterConfig): LocalCache<unknown> | RedisCache<unknown> | undefined;
6
+ }
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.CacheFactory = void 0;
30
+ const ioredis_1 = __importDefault(require("ioredis"));
31
+ const util_1 = require("../util");
32
+ const local_1 = require("./local");
33
+ const cacheMetrics = __importStar(require("./metrics"));
34
+ const redis_1 = require("./redis");
35
+ const logger = (0, util_1.makeLogger)('CacheFactory');
36
+ class CacheFactory {
37
+ static buildCache(config) {
38
+ logger.info(`Using "${config.CACHE_TYPE}" cache.`);
39
+ if (config.CACHE_TYPE === 'local') {
40
+ return new local_1.LocalCache();
41
+ }
42
+ else if (config.CACHE_TYPE === 'redis') {
43
+ const redis = new ioredis_1.default({
44
+ enableAutoPipelining: true,
45
+ host: config.CACHE_REDIS_HOST,
46
+ port: config.CACHE_REDIS_PORT,
47
+ });
48
+ redis.on('connect', () => {
49
+ cacheMetrics.redisConnectionsOpen.inc();
50
+ });
51
+ // TODO: Maybe track active redis connections instead of just total count of connections created
52
+ // Use a Gauge and track with a combo of connect/end events listeners
53
+ return new redis_1.RedisCache(redis);
54
+ }
55
+ }
56
+ }
57
+ exports.CacheFactory = CacheFactory;
@@ -0,0 +1,90 @@
1
+ import { AdapterEndpoint } from '../adapter';
2
+ import { AdapterConfig } from '../config';
3
+ import { AdapterMiddlewareBuilder, AdapterResponse, sleep } from '../util';
4
+ export * from './local';
5
+ export * from './redis';
6
+ /**
7
+ * An object describing an entry in the cache.
8
+ * @typeParam T - the type of the entry's value
9
+ */
10
+ export interface CacheEntry<T> {
11
+ key: string;
12
+ value: T;
13
+ }
14
+ /**
15
+ * Generic interface for a local or remote Cache.
16
+ * @typeParam T - the type of the cache entries' values
17
+ */
18
+ export interface Cache<T = unknown> {
19
+ /**
20
+ * Gets an item from the Cache.
21
+ *
22
+ * @param key - the key of the desired entry for which to fetch its value
23
+ * @returns a Promise of the entry's value, or undefined if not found / expired.
24
+ */
25
+ get: (key: string) => Promise<T | undefined>;
26
+ /**
27
+ * Sets an item in the Cache.
28
+ *
29
+ * @param key - the key of the new entry
30
+ * @param value - the value of the new entry
31
+ * @param ttl - the time in milliseconds until the entry expires
32
+ * @returns an empty Promise that resolves when the entry has been set
33
+ */
34
+ set: (key: string, value: T, ttl: number) => Promise<void>;
35
+ /**
36
+ * Sets a list of items in the Cache.
37
+ *
38
+ * @param entries - a list of cache entries
39
+ * @param ttl - the time in milliseconds until the entries expire
40
+ * @returns an empty Promise that resolves when all entries have been set
41
+ */
42
+ setMany: (entries: CacheEntry<T>[], ttl: number) => Promise<void>;
43
+ /**
44
+ * Deletes the specified item from the Cache
45
+ *
46
+ * @param key - the key of the entry to be deleted
47
+ * @returns an empty Promise that resolves when the entry has been deleted
48
+ */
49
+ delete: (key: string) => Promise<void>;
50
+ }
51
+ export declare const calculateCacheKey: ({ adapterEndpoint, adapterConfig, }: {
52
+ adapterEndpoint: AdapterEndpoint;
53
+ adapterConfig: AdapterConfig;
54
+ }, data: unknown) => string;
55
+ export declare const calculateFeedId: (adapterEndpoint: AdapterEndpoint, data: unknown) => string;
56
+ /**
57
+ * Calculates a unique key from the provided data.
58
+ *
59
+ * @param data - the request data/body, i.e. the adapter input params
60
+ * @param paramNames - the keys from adapter endpoint input parameters
61
+ * @returns the calculated unique key
62
+ *
63
+ * @example
64
+ * ```
65
+ * calculateKey({ base: 'ETH', quote: 'BTC' }, ['base','quote'])
66
+ * // equals `|base:eth|quote:btc`
67
+ * ```
68
+ */
69
+ export declare const calculateKey: (data: unknown, paramNames: string[]) => string;
70
+ /**
71
+ * Polls the provided Cache for an AdapterResponse set in the provided key. If the maximum
72
+ * amount of retries is exceeded, it returns undefined instead.
73
+ *
74
+ * @param cache - a Cache instance
75
+ * @param key - the key generated from an AdapterRequest that corresponds to the desired AdapterResponse
76
+ * @param retry - current retry, only for internal use
77
+ * @returns the AdapterResponse if found, else undefined
78
+ */
79
+ export declare const pollResponseFromCache: (cache: Cache<AdapterResponse>, key: string, options: {
80
+ maxRetries: number;
81
+ sleep: number;
82
+ }, retry?: number) => Promise<AdapterResponse | undefined>;
83
+ /**
84
+ * Given a Cache instance in the adapter dependencies, builds a middleware function that will perform
85
+ * a get from said Cache and return that if found; otherwise it'll continue the middleware chain.
86
+ *
87
+ * @param adapter - an initialized adapter
88
+ * @returns the cache middleware function
89
+ */
90
+ export declare const buildCacheMiddleware: AdapterMiddlewareBuilder;