@chainlink/external-adapter-framework 0.0.3 → 0.0.4
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.
- package/.github/actions/setup/action.yaml +1 -0
- package/.github/workflows/{publish2.yaml → publish.yaml} +8 -7
- package/package.json +1 -1
- package/dist/adapter.js +0 -60
- package/dist/background-executor.js +0 -45
- package/dist/cache/factory.js +0 -57
- package/dist/cache/index.js +0 -163
- package/dist/cache/local.js +0 -83
- package/dist/cache/metrics.js +0 -114
- package/dist/cache/redis.js +0 -100
- package/dist/config/index.js +0 -364
- package/dist/config/provider-limits.js +0 -75
- package/dist/examples/coingecko/batch-warming.js +0 -52
- package/dist/examples/coingecko/index.js +0 -10
- package/dist/examples/coingecko/rest.js +0 -50
- package/dist/examples/ncfx/config/index.js +0 -15
- package/dist/examples/ncfx/index.js +0 -10
- package/dist/examples/ncfx/websocket.js +0 -72
- package/dist/index.js +0 -89
- package/dist/metrics/constants.js +0 -25
- package/dist/metrics/index.js +0 -76
- package/dist/metrics/util.js +0 -9
- package/dist/rate-limiting/factory.js +0 -33
- package/dist/rate-limiting/index.js +0 -36
- package/dist/rate-limiting/metrics.js +0 -32
- package/dist/rate-limiting/nop-limiter.js +0 -15
- package/dist/rate-limiting/simple-counting.js +0 -61
- package/dist/src/adapter.js +0 -112
- package/dist/src/background-executor.js +0 -45
- package/dist/src/cache/factory.js +0 -57
- package/dist/src/cache/index.js +0 -165
- package/dist/src/cache/local.js +0 -83
- package/dist/src/cache/metrics.js +0 -114
- package/dist/src/cache/redis.js +0 -100
- package/dist/src/config/index.js +0 -366
- package/dist/src/config/provider-limits.js +0 -75
- package/dist/src/examples/bank-frick/accounts.js +0 -191
- package/dist/src/examples/bank-frick/config/index.js +0 -45
- package/dist/src/examples/bank-frick/index.js +0 -14
- package/dist/src/examples/bank-frick/util.js +0 -39
- package/dist/src/examples/coingecko/batch-warming.js +0 -52
- package/dist/src/examples/coingecko/index.js +0 -10
- package/dist/src/examples/coingecko/rest.js +0 -50
- package/dist/src/examples/ncfx/config/index.js +0 -15
- package/dist/src/examples/ncfx/index.js +0 -10
- package/dist/src/examples/ncfx/websocket.js +0 -72
- package/dist/src/index.js +0 -89
- package/dist/src/metrics/constants.js +0 -25
- package/dist/src/metrics/index.js +0 -76
- package/dist/src/metrics/util.js +0 -9
- package/dist/src/rate-limiting/background/fixed-frequency.js +0 -37
- package/dist/src/rate-limiting/index.js +0 -63
- package/dist/src/rate-limiting/metrics.js +0 -32
- package/dist/src/rate-limiting/request/simple-counting.js +0 -62
- package/dist/src/test.js +0 -6
- package/dist/src/transports/batch-warming.js +0 -55
- package/dist/src/transports/index.js +0 -85
- package/dist/src/transports/metrics.js +0 -119
- package/dist/src/transports/rest.js +0 -93
- package/dist/src/transports/util.js +0 -85
- package/dist/src/transports/websocket.js +0 -175
- package/dist/src/util/expiring-sorted-set.js +0 -47
- package/dist/src/util/index.js +0 -35
- package/dist/src/util/logger.js +0 -62
- package/dist/src/util/request.js +0 -2
- package/dist/src/validation/error.js +0 -41
- package/dist/src/validation/index.js +0 -84
- package/dist/src/validation/input-params.js +0 -30
- package/dist/src/validation/override-functions.js +0 -40
- package/dist/src/validation/preset-tokens.json +0 -23
- package/dist/src/validation/validator.js +0 -303
- package/dist/test.js +0 -6
- package/dist/transports/batch-warming.js +0 -57
- package/dist/transports/index.js +0 -76
- package/dist/transports/metrics.js +0 -133
- package/dist/transports/rest.js +0 -91
- package/dist/transports/util.js +0 -85
- package/dist/transports/websocket.js +0 -171
- package/dist/util/expiring-sorted-set.js +0 -47
- package/dist/util/index.js +0 -35
- package/dist/util/logger.js +0 -62
- package/dist/util/request.js +0 -2
- package/dist/validation/error.js +0 -41
- package/dist/validation/index.js +0 -82
- package/dist/validation/input-params.js +0 -30
- package/dist/validation/overrideFunctions.js +0 -42
- package/dist/validation/presetTokens.json +0 -23
- package/dist/validation/validator.js +0 -303
- package/env.sh +0 -55
- package/env2.sh +0 -55
- package/yarn-error.log +0 -2752
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
# This is the entry point for CI. It will setup the application, then run lint, test, and eventually publish if not the master or main branch
|
|
2
2
|
name: 'Publish'
|
|
3
3
|
on:
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
workflow_dispatch:
|
|
5
|
+
push:
|
|
6
|
+
#branches:
|
|
7
|
+
#- master
|
|
8
|
+
#- main
|
|
6
9
|
jobs:
|
|
7
10
|
publish: # Load the dependencies cache for all jobs
|
|
8
11
|
runs-on: ubuntu-latest
|
|
12
|
+
environment: main
|
|
9
13
|
steps:
|
|
10
14
|
- uses: actions/checkout@v3
|
|
11
15
|
- uses: ./.github/actions/setup
|
|
12
|
-
- run: yarn build
|
|
13
|
-
- run: yarn config get registry
|
|
14
|
-
- run: ls -la
|
|
15
16
|
- run: npm publish --access restricted #scoped packages are restricted by default, but this is set because not all branches currently have a scoped package name
|
|
16
|
-
|
|
17
|
-
|
|
17
|
+
env:
|
|
18
|
+
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
package/package.json
CHANGED
package/dist/adapter.js
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
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;
|
|
@@ -1,45 +0,0 @@
|
|
|
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;
|
package/dist/cache/factory.js
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
-
if (mod && mod.__esModule) return mod;
|
|
20
|
-
var result = {};
|
|
21
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
-
__setModuleDefault(result, mod);
|
|
23
|
-
return result;
|
|
24
|
-
};
|
|
25
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
-
};
|
|
28
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
-
exports.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;
|
package/dist/cache/index.js
DELETED
|
@@ -1,163 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
-
if (mod && mod.__esModule) return mod;
|
|
20
|
-
var result = {};
|
|
21
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
-
__setModuleDefault(result, mod);
|
|
23
|
-
return result;
|
|
24
|
-
};
|
|
25
|
-
var __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;
|
package/dist/cache/local.js
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
-
if (mod && mod.__esModule) return mod;
|
|
20
|
-
var result = {};
|
|
21
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
-
__setModuleDefault(result, mod);
|
|
23
|
-
return result;
|
|
24
|
-
};
|
|
25
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.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;
|
package/dist/cache/metrics.js
DELETED
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
-
if (mod && mod.__esModule) return mod;
|
|
20
|
-
var result = {};
|
|
21
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
-
__setModuleDefault(result, mod);
|
|
23
|
-
return result;
|
|
24
|
-
};
|
|
25
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.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
|
-
});
|
package/dist/cache/redis.js
DELETED
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
-
if (mod && mod.__esModule) return mod;
|
|
20
|
-
var result = {};
|
|
21
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
-
__setModuleDefault(result, mod);
|
|
23
|
-
return result;
|
|
24
|
-
};
|
|
25
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.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;
|