@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.
- package/dist/adapter.js +60 -0
- package/dist/background-executor.js +45 -0
- package/dist/cache/factory.js +57 -0
- package/dist/cache/index.js +163 -0
- package/dist/cache/local.js +83 -0
- package/dist/cache/metrics.js +114 -0
- package/dist/cache/redis.js +100 -0
- package/dist/config/index.js +364 -0
- package/dist/config/provider-limits.js +75 -0
- package/dist/examples/coingecko/batch-warming.js +52 -0
- package/dist/examples/coingecko/index.js +10 -0
- package/dist/examples/coingecko/rest.js +50 -0
- package/dist/examples/ncfx/config/index.js +15 -0
- package/dist/examples/ncfx/index.js +10 -0
- package/dist/examples/ncfx/websocket.js +72 -0
- package/dist/index.js +89 -0
- package/dist/metrics/constants.js +25 -0
- package/dist/metrics/index.js +76 -0
- package/dist/metrics/util.js +9 -0
- package/dist/rate-limiting/factory.js +33 -0
- package/dist/rate-limiting/index.js +36 -0
- package/dist/rate-limiting/metrics.js +32 -0
- package/dist/rate-limiting/nop-limiter.js +15 -0
- package/dist/rate-limiting/simple-counting.js +61 -0
- package/dist/src/adapter.js +112 -0
- package/dist/src/background-executor.js +45 -0
- package/dist/src/cache/factory.js +57 -0
- package/dist/src/cache/index.js +165 -0
- package/dist/src/cache/local.js +83 -0
- package/dist/src/cache/metrics.js +114 -0
- package/dist/src/cache/redis.js +100 -0
- package/dist/src/config/index.js +366 -0
- package/dist/src/config/provider-limits.js +75 -0
- package/dist/src/examples/bank-frick/accounts.js +191 -0
- package/dist/src/examples/bank-frick/config/index.js +45 -0
- package/dist/src/examples/bank-frick/index.js +14 -0
- package/dist/src/examples/bank-frick/util.js +39 -0
- package/dist/src/examples/coingecko/batch-warming.js +52 -0
- package/dist/src/examples/coingecko/index.js +10 -0
- package/dist/src/examples/coingecko/rest.js +50 -0
- package/dist/src/examples/ncfx/config/index.js +15 -0
- package/dist/src/examples/ncfx/index.js +10 -0
- package/dist/src/examples/ncfx/websocket.js +72 -0
- package/dist/src/index.js +89 -0
- package/dist/src/metrics/constants.js +25 -0
- package/dist/src/metrics/index.js +76 -0
- package/dist/src/metrics/util.js +9 -0
- package/dist/src/rate-limiting/background/fixed-frequency.js +37 -0
- package/dist/src/rate-limiting/index.js +63 -0
- package/dist/src/rate-limiting/metrics.js +32 -0
- package/dist/src/rate-limiting/request/simple-counting.js +62 -0
- package/dist/src/test.js +6 -0
- package/dist/src/transports/batch-warming.js +55 -0
- package/dist/src/transports/index.js +85 -0
- package/dist/src/transports/metrics.js +119 -0
- package/dist/src/transports/rest.js +93 -0
- package/dist/src/transports/util.js +85 -0
- package/dist/src/transports/websocket.js +175 -0
- package/dist/src/util/expiring-sorted-set.js +47 -0
- package/dist/src/util/index.js +35 -0
- package/dist/src/util/logger.js +62 -0
- package/dist/src/util/request.js +2 -0
- package/dist/src/validation/error.js +41 -0
- package/dist/src/validation/index.js +84 -0
- package/dist/src/validation/input-params.js +30 -0
- package/dist/src/validation/override-functions.js +40 -0
- package/dist/src/validation/preset-tokens.json +23 -0
- package/dist/src/validation/validator.js +303 -0
- package/dist/test.js +6 -0
- package/dist/transports/batch-warming.js +57 -0
- package/dist/transports/index.js +76 -0
- package/dist/transports/metrics.js +133 -0
- package/dist/transports/rest.js +91 -0
- package/dist/transports/util.js +85 -0
- package/dist/transports/websocket.js +171 -0
- package/dist/util/expiring-sorted-set.js +47 -0
- package/dist/util/index.js +35 -0
- package/dist/util/logger.js +62 -0
- package/dist/util/request.js +2 -0
- package/dist/validation/error.js +41 -0
- package/dist/validation/index.js +82 -0
- package/dist/validation/input-params.js +30 -0
- package/dist/validation/overrideFunctions.js +42 -0
- package/dist/validation/presetTokens.json +23 -0
- package/dist/validation/validator.js +303 -0
- package/package.json +6 -2
- package/.c8rc.json +0 -3
- package/.eslintignore +0 -9
- package/.eslintrc.js +0 -96
- package/.github/README.MD +0 -17
- package/.github/actions/setup/action.yaml +0 -13
- package/.github/workflows/main.yaml +0 -39
- package/.github/workflows/publish.yaml +0 -17
- package/.prettierignore +0 -13
- package/.yarnrc +0 -0
- package/docker-compose.yaml +0 -35
- package/src/adapter.ts +0 -236
- package/src/background-executor.ts +0 -53
- package/src/cache/factory.ts +0 -28
- package/src/cache/index.ts +0 -236
- package/src/cache/local.ts +0 -73
- package/src/cache/metrics.ts +0 -112
- package/src/cache/redis.ts +0 -93
- package/src/config/index.ts +0 -501
- package/src/config/provider-limits.ts +0 -130
- package/src/examples/coingecko/batch-warming.ts +0 -79
- package/src/examples/coingecko/index.ts +0 -9
- package/src/examples/coingecko/rest.ts +0 -77
- package/src/examples/ncfx/config/index.ts +0 -12
- package/src/examples/ncfx/index.ts +0 -9
- package/src/examples/ncfx/websocket.ts +0 -100
- package/src/index.ts +0 -106
- package/src/metrics/constants.ts +0 -23
- package/src/metrics/index.ts +0 -116
- package/src/metrics/util.ts +0 -11
- package/src/rate-limiting/background/fixed-frequency.ts +0 -47
- package/src/rate-limiting/index.ts +0 -100
- package/src/rate-limiting/metrics.ts +0 -18
- package/src/rate-limiting/request/simple-counting.ts +0 -76
- package/src/test.ts +0 -5
- package/src/transports/batch-warming.ts +0 -121
- package/src/transports/index.ts +0 -173
- package/src/transports/metrics.ts +0 -95
- package/src/transports/rest.ts +0 -161
- package/src/transports/util.ts +0 -63
- package/src/transports/websocket.ts +0 -238
- package/src/util/expiring-sorted-set.ts +0 -52
- package/src/util/index.ts +0 -20
- package/src/util/logger.ts +0 -69
- package/src/util/request.ts +0 -115
- package/src/validation/error.ts +0 -116
- package/src/validation/index.ts +0 -101
- package/src/validation/input-params.ts +0 -45
- package/src/validation/override-functions.ts +0 -44
- package/src/validation/preset-tokens.json +0 -23
- package/src/validation/validator.ts +0 -384
- package/test/adapter.test.ts +0 -27
- package/test/background-executor.test.ts +0 -109
- package/test/cache/cache-key.test.ts +0 -96
- package/test/cache/helper.ts +0 -101
- package/test/cache/local.test.ts +0 -54
- package/test/cache/redis.test.ts +0 -89
- package/test/correlation.test.ts +0 -114
- package/test/index.test.ts +0 -37
- package/test/metrics/feed-id.test.ts +0 -33
- package/test/metrics/helper.ts +0 -14
- package/test/metrics/labels.test.ts +0 -36
- package/test/metrics/metrics.test.ts +0 -267
- package/test/metrics/redis-metrics.test.ts +0 -113
- package/test/metrics/warmer-metrics.test.ts +0 -192
- package/test/metrics/ws-metrics.test.ts +0 -225
- package/test/rate-limit-config.test.ts +0 -243
- package/test/transports/batch.test.ts +0 -465
- package/test/transports/rest.test.ts +0 -242
- package/test/transports/websocket.test.ts +0 -183
- package/test/tsconfig.json +0 -5
- package/test/util.ts +0 -76
- package/test/validation.test.ts +0 -169
- package/test.sh +0 -20
- package/tsconfig.json +0 -24
- package/typedoc.json +0 -6
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BatchWarmingTransport = exports.DEFAULT_WARMER_PERIOD = void 0;
|
|
4
|
+
const util_1 = require("../util");
|
|
5
|
+
const _1 = require("./");
|
|
6
|
+
const util_2 = require("./util");
|
|
7
|
+
const DEFAULT_WARMER_TTL = 10000;
|
|
8
|
+
exports.DEFAULT_WARMER_PERIOD = 5000; // TODO: rate limit, this will be dynamic
|
|
9
|
+
const logger = (0, util_1.makeLogger)('BatchWarmingTransport');
|
|
10
|
+
/**
|
|
11
|
+
* Transport implementation that takes incoming batches requests and keeps a warm cache of values.
|
|
12
|
+
* Within the setup function, adapter params are added to an set that also keeps track and expires values.
|
|
13
|
+
* In the background execute, the list of non-expired items in the set is fetched.
|
|
14
|
+
* Then, the list is passed through the `prepareRequest` function, that returns an AxiosRequestConfig.
|
|
15
|
+
* The Data Provider response is, they are passed through the `parseResponse` function to create a [[CacheEntry]] list.
|
|
16
|
+
* Finally, the items in that [[CacheEntry]] list are set in the Cache so the Adapter can fetch values from there.
|
|
17
|
+
*
|
|
18
|
+
* @typeParam AdapterParams - interface for the adapter request body
|
|
19
|
+
* @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
|
|
20
|
+
* @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
|
|
21
|
+
*/
|
|
22
|
+
class BatchWarmingTransport {
|
|
23
|
+
constructor(config) {
|
|
24
|
+
this.config = config;
|
|
25
|
+
this.expiringSortedSet = new util_1.ExpiringSortedSet(); // TODO: Move to dependencies, inject
|
|
26
|
+
}
|
|
27
|
+
async initialize(dependencies) {
|
|
28
|
+
this.cache = dependencies.cache;
|
|
29
|
+
}
|
|
30
|
+
async hasBeenSetUp(req) {
|
|
31
|
+
return !!this.expiringSortedSet.get(req.requestContext.cacheKey);
|
|
32
|
+
}
|
|
33
|
+
async setup(req) {
|
|
34
|
+
logger.debug(`Adding entry to batch warming set: [${req.requestContext.cacheKey}] = ${req.requestContext.data}`);
|
|
35
|
+
this.expiringSortedSet.add(req.requestContext.cacheKey, req.requestContext.data, DEFAULT_WARMER_TTL);
|
|
36
|
+
}
|
|
37
|
+
async backgroundExecute(context) {
|
|
38
|
+
logger.debug('Starting background execute');
|
|
39
|
+
const entries = this.expiringSortedSet.getAll();
|
|
40
|
+
if (!entries.length) {
|
|
41
|
+
logger.debug('No entries in batch warming set, skipping');
|
|
42
|
+
return exports.DEFAULT_WARMER_PERIOD; // TODO: configurable, rate limit
|
|
43
|
+
}
|
|
44
|
+
const request = this.config.prepareRequest(entries, context);
|
|
45
|
+
logger.debug('Sending request to data provider...');
|
|
46
|
+
const providerResponse = await (0, util_2.axiosRequest)(request);
|
|
47
|
+
logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`);
|
|
48
|
+
const results = this.config.parseResponse(providerResponse, context);
|
|
49
|
+
const adapterResponses = (0, _1.buildCacheEntriesFromResults)(results, context);
|
|
50
|
+
logger.debug('Setting adapter responses in cache');
|
|
51
|
+
await this.cache.setMany(adapterResponses, context.adapterConfig.CACHE_MAX_AGE);
|
|
52
|
+
// TODO: Record rate limit credit with cost, default 1
|
|
53
|
+
logger.debug('Background execute complete');
|
|
54
|
+
return exports.DEFAULT_WARMER_PERIOD;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
exports.BatchWarmingTransport = BatchWarmingTransport;
|
|
@@ -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 __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.buildTransportHandler = exports.buildCacheEntriesFromResults = void 0;
|
|
18
|
+
const cache_1 = require("../cache");
|
|
19
|
+
const util_1 = require("../util");
|
|
20
|
+
__exportStar(require("./batch-warming"), exports);
|
|
21
|
+
__exportStar(require("./rest"), exports);
|
|
22
|
+
__exportStar(require("./websocket"), exports);
|
|
23
|
+
const logger = (0, util_1.makeLogger)('Transport');
|
|
24
|
+
/**
|
|
25
|
+
* Helper method to build cache entries to set after getting a bunch of responses from a DP.
|
|
26
|
+
*
|
|
27
|
+
* @param results - a list of results coming from a DataProvider
|
|
28
|
+
* @param context - context for the Adapter
|
|
29
|
+
* @returns a list of CacheEntries of AdapterResponses
|
|
30
|
+
*/
|
|
31
|
+
const buildCacheEntriesFromResults = (results, context) => results.map((r) => ({
|
|
32
|
+
key: (0, cache_1.calculateCacheKey)(context, r.params),
|
|
33
|
+
value: {
|
|
34
|
+
result: r.value,
|
|
35
|
+
statusCode: 200,
|
|
36
|
+
data: null,
|
|
37
|
+
maxAge: Date.now() + context.adapterConfig.CACHE_MAX_AGE,
|
|
38
|
+
metricsMeta: {
|
|
39
|
+
feedId: (0, cache_1.calculateFeedId)(context.adapterEndpoint, r.params)
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
}));
|
|
43
|
+
exports.buildCacheEntriesFromResults = buildCacheEntriesFromResults;
|
|
44
|
+
/**
|
|
45
|
+
* Takes an Adapter, its configuration, and its dependencies, and it creates an express middleware
|
|
46
|
+
* that will pass along the AdapterRequest to the appropriate Transport (acc. to the endpoint in the req.)
|
|
47
|
+
*
|
|
48
|
+
* @param adapter - main adapter object, already initialized
|
|
49
|
+
* @returns the transport handler middleware function
|
|
50
|
+
*/
|
|
51
|
+
const buildTransportHandler = (adapter) => async (req, reply) => {
|
|
52
|
+
// Get transport, must be here because it's already checked in the validator
|
|
53
|
+
const transport = adapter.endpointsMap[req.requestContext.endpointName].transport;
|
|
54
|
+
// Set up transport if it hasn't been done already
|
|
55
|
+
if (!(await transport.hasBeenSetUp(req))) {
|
|
56
|
+
logger.debug('Transport not set up yet, doing so...');
|
|
57
|
+
const immediateResponse = await transport.setup(req, adapter.config);
|
|
58
|
+
if (immediateResponse) {
|
|
59
|
+
logger.debug('Got immediate response from transport, sending as response');
|
|
60
|
+
return reply.send(immediateResponse);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
logger.debug('Transport is set up, polling cache for response...');
|
|
64
|
+
const response = await (0, cache_1.pollResponseFromCache)(adapter.dependencies.cache, req.requestContext.cacheKey, {
|
|
65
|
+
maxRetries: adapter.config.CACHE_POLLING_MAX_RETRIES,
|
|
66
|
+
sleep: adapter.config.CACHE_POLLING_SLEEP_MS,
|
|
67
|
+
});
|
|
68
|
+
if (response) {
|
|
69
|
+
logger.debug('Got a response from the cache, sending that back');
|
|
70
|
+
return reply.send(response);
|
|
71
|
+
}
|
|
72
|
+
logger.debug('Ran out of polling attempts, returning timeout');
|
|
73
|
+
reply.statusCode = 504;
|
|
74
|
+
return reply.send();
|
|
75
|
+
};
|
|
76
|
+
exports.buildTransportHandler = buildTransportHandler;
|
|
@@ -0,0 +1,133 @@
|
|
|
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.cacheWarmerCount = exports.wsMessageTotal = exports.wsSubscriptionErrors = exports.wsSubscriptionTotal = exports.wsSubscriptionActive = exports.wsConnectionRetries = exports.wsConnectionErrors = exports.wsConnectionActive = exports.messageLabels = exports.subscriptionErrorLabels = exports.subscriptionLabels = exports.connectionErrorLabels = exports.connectionLabels = exports.dataProviderRequestDurationSeconds = exports.dataProviderRequests = exports.dataProviderMetricsLabel = void 0;
|
|
27
|
+
const client = __importStar(require("prom-client"));
|
|
28
|
+
const constants_1 = require("../metrics/constants");
|
|
29
|
+
// Data Provider Metrics
|
|
30
|
+
const dataProviderMetricsLabel = (providerStatusCode, method = 'get') => ({
|
|
31
|
+
provider_status_code: providerStatusCode,
|
|
32
|
+
method: method.toUpperCase()
|
|
33
|
+
});
|
|
34
|
+
exports.dataProviderMetricsLabel = dataProviderMetricsLabel;
|
|
35
|
+
exports.dataProviderRequests = new client.Counter({
|
|
36
|
+
name: 'data_provider_requests',
|
|
37
|
+
help: 'The number of http requests that are made to a data provider',
|
|
38
|
+
labelNames: ['method', 'provider_status_code'],
|
|
39
|
+
});
|
|
40
|
+
exports.dataProviderRequestDurationSeconds = new client.Histogram({
|
|
41
|
+
name: 'data_provider_request_duration_seconds',
|
|
42
|
+
help: 'A histogram bucket of the distribution of data provider request durations',
|
|
43
|
+
buckets: constants_1.requestDurationBuckets,
|
|
44
|
+
});
|
|
45
|
+
// Websocket Metrics
|
|
46
|
+
const connectionLabels = (key) => ({
|
|
47
|
+
// Key,
|
|
48
|
+
});
|
|
49
|
+
exports.connectionLabels = connectionLabels;
|
|
50
|
+
const connectionErrorLabels = (message) => ({
|
|
51
|
+
// Key,
|
|
52
|
+
message,
|
|
53
|
+
});
|
|
54
|
+
exports.connectionErrorLabels = connectionErrorLabels;
|
|
55
|
+
const subscriptionLabels = (
|
|
56
|
+
// Connection_key: string,
|
|
57
|
+
feed_id, cache_key) => ({
|
|
58
|
+
// Connection_key,
|
|
59
|
+
feed_id,
|
|
60
|
+
subscription_key: cache_key,
|
|
61
|
+
});
|
|
62
|
+
exports.subscriptionLabels = subscriptionLabels;
|
|
63
|
+
const subscriptionErrorLabels = (
|
|
64
|
+
// Connection_key: string,
|
|
65
|
+
input, message, type) => ({
|
|
66
|
+
// Connection_key,
|
|
67
|
+
feed_id: input ? input.metricsMeta?.feedId : 'N/A',
|
|
68
|
+
message,
|
|
69
|
+
subscription_key: input.cacheKey ? input.cacheKey : 'N/A',
|
|
70
|
+
type,
|
|
71
|
+
});
|
|
72
|
+
exports.subscriptionErrorLabels = subscriptionErrorLabels;
|
|
73
|
+
const messageLabels = (feed_id, cache_key) => ({
|
|
74
|
+
feed_id,
|
|
75
|
+
subscription_key: cache_key,
|
|
76
|
+
});
|
|
77
|
+
exports.messageLabels = messageLabels;
|
|
78
|
+
exports.wsConnectionActive = new client.Gauge({
|
|
79
|
+
name: 'ws_connection_active',
|
|
80
|
+
help: 'The number of active connections',
|
|
81
|
+
labelNames: ['url'],
|
|
82
|
+
});
|
|
83
|
+
exports.wsConnectionErrors = new client.Counter({
|
|
84
|
+
name: 'ws_connection_errors',
|
|
85
|
+
help: 'The number of connection errors',
|
|
86
|
+
labelNames: ['url', 'message'],
|
|
87
|
+
});
|
|
88
|
+
// Doesn't seem to be any retry connection functionality yet
|
|
89
|
+
exports.wsConnectionRetries = new client.Counter({
|
|
90
|
+
name: 'ws_connection_retries',
|
|
91
|
+
help: 'The number of connection retries',
|
|
92
|
+
labelNames: ['url'],
|
|
93
|
+
});
|
|
94
|
+
exports.wsSubscriptionActive = new client.Gauge({
|
|
95
|
+
name: 'ws_subscription_active',
|
|
96
|
+
help: 'The number of currently active subscriptions',
|
|
97
|
+
labelNames: [
|
|
98
|
+
'connection_url',
|
|
99
|
+
'feed_id',
|
|
100
|
+
'subscription_key',
|
|
101
|
+
],
|
|
102
|
+
});
|
|
103
|
+
exports.wsSubscriptionTotal = new client.Counter({
|
|
104
|
+
name: 'ws_subscription_total',
|
|
105
|
+
help: 'The number of subscriptions opened in total',
|
|
106
|
+
labelNames: [
|
|
107
|
+
'connection_url',
|
|
108
|
+
'feed_id',
|
|
109
|
+
'subscription_key',
|
|
110
|
+
],
|
|
111
|
+
});
|
|
112
|
+
exports.wsSubscriptionErrors = new client.Counter({
|
|
113
|
+
name: 'ws_subscription_errors',
|
|
114
|
+
help: 'The number of subscriptions errors',
|
|
115
|
+
labelNames: [
|
|
116
|
+
'connection_url',
|
|
117
|
+
'feed_id',
|
|
118
|
+
'subscription_key',
|
|
119
|
+
'message',
|
|
120
|
+
'type',
|
|
121
|
+
],
|
|
122
|
+
});
|
|
123
|
+
exports.wsMessageTotal = new client.Counter({
|
|
124
|
+
name: 'ws_message_total',
|
|
125
|
+
help: 'The number of messages received in total',
|
|
126
|
+
labelNames: ['feed_id', 'subscription_key'],
|
|
127
|
+
});
|
|
128
|
+
// Cache Warmer Metrics
|
|
129
|
+
exports.cacheWarmerCount = new client.Gauge({
|
|
130
|
+
name: 'cache_warmer_get_count',
|
|
131
|
+
help: 'The number of cache warmers running',
|
|
132
|
+
labelNames: ['isBatched'],
|
|
133
|
+
});
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RestTransport = void 0;
|
|
4
|
+
const util_1 = require("../util");
|
|
5
|
+
const error_1 = require("../validation/error");
|
|
6
|
+
const util_2 = require("./util");
|
|
7
|
+
const IN_FLIGHT_PREFIX = 'InFlight';
|
|
8
|
+
const logger = (0, util_1.makeLogger)('RestTransport');
|
|
9
|
+
/**
|
|
10
|
+
* Transport implementation that takes incoming requests, transforms them into a DataProvider request,
|
|
11
|
+
* and executes that request returning the response immediately from the `setup` function.
|
|
12
|
+
* Optionally, setting the `coalescing` option to `true` will make it so once a request is in flight,
|
|
13
|
+
* new adapter requests for the same feed will not trigger a new one, but return an empty promise from
|
|
14
|
+
* the setup instead so the normal cache polling mechanism is used.
|
|
15
|
+
*
|
|
16
|
+
* @typeParam AdapterParams - interface for the adapter request body
|
|
17
|
+
* @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
|
|
18
|
+
* @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
|
|
19
|
+
*/
|
|
20
|
+
class RestTransport {
|
|
21
|
+
constructor(config) {
|
|
22
|
+
this.config = config;
|
|
23
|
+
}
|
|
24
|
+
async initialize(dependencies) {
|
|
25
|
+
this.inFlightPrefix = `${IN_FLIGHT_PREFIX}-`;
|
|
26
|
+
this.cache = dependencies.cache;
|
|
27
|
+
this.rateLimiter = dependencies.rateLimiter;
|
|
28
|
+
}
|
|
29
|
+
async hasBeenSetUp(req) {
|
|
30
|
+
if (!this.config.options.coalescing) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
// Check if request is in flight
|
|
34
|
+
const inFlight = await this.cache.get(this.inFlightPrefix + req.requestContext.cacheKey);
|
|
35
|
+
if (inFlight) {
|
|
36
|
+
logger.debug('Request is in flight, transport has been set up');
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
logger.debug('Request not in flight, transport not set up');
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async waitUntilUnderRateLimit(options, retry = 0) {
|
|
45
|
+
if (this.rateLimiter.isUnderLimits()) {
|
|
46
|
+
logger.trace('Incoming request would not be under limits, moving on');
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (retry >= options.maxRetries) {
|
|
50
|
+
throw new error_1.AdapterError({
|
|
51
|
+
statusCode: 504,
|
|
52
|
+
message: `REST Transport timed out while waiting for rate limit availability (max retries: ${options.maxRetries})`,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
logger.debug(`Request would be over rate limits, sleeping for ${options.msBetweenRetries}`);
|
|
56
|
+
await (0, util_1.sleep)(options.msBetweenRetries);
|
|
57
|
+
await this.waitUntilUnderRateLimit(options, retry + 1);
|
|
58
|
+
}
|
|
59
|
+
async setup(req, config) {
|
|
60
|
+
if (this.config.options.coalescing) {
|
|
61
|
+
logger.debug('Setting up rest transport, setting request in flight in cache');
|
|
62
|
+
// TODO: Should this use a separate cache?
|
|
63
|
+
// TODO: Set viable ttl to approximate timeout from API
|
|
64
|
+
// TODO: Make this ttl configurable
|
|
65
|
+
await this.cache.set(this.inFlightPrefix + req.requestContext.cacheKey, true, 2000); // Can't use Infinity for things like Redis
|
|
66
|
+
}
|
|
67
|
+
const request = await this.config.prepareRequest(req, config);
|
|
68
|
+
logger.trace('Check if we are under rate limits to perform request');
|
|
69
|
+
await this.waitUntilUnderRateLimit({
|
|
70
|
+
maxRetries: config.REST_TRANSPORT_MAX_RATE_LIMIT_RETRIES,
|
|
71
|
+
msBetweenRetries: config.REST_TRANSPORT_MS_BETWEEN_RATE_LIMIT_RETRIES,
|
|
72
|
+
});
|
|
73
|
+
logger.trace('Sending request to data provider...');
|
|
74
|
+
const providerResponse = await (0, util_2.axiosRequest)(request);
|
|
75
|
+
logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`); // TODO: Sensitive data?
|
|
76
|
+
const parsedResponse = await this.config.parseResponse(req, providerResponse, config);
|
|
77
|
+
// TODO: Potentially create function to add all telemetry data
|
|
78
|
+
parsedResponse.maxAge = Date.now() + config.CACHE_MAX_AGE;
|
|
79
|
+
parsedResponse.metricsMeta = { feedId: req.requestContext.metricsMeta?.feedId || 'N/A' };
|
|
80
|
+
logger.debug('Setting provider response in cache');
|
|
81
|
+
await this.cache.set(req.requestContext.cacheKey, parsedResponse, config.CACHE_MAX_AGE);
|
|
82
|
+
// TODO: Record rate limit credit with cost, default 1
|
|
83
|
+
// TODO: move this to a try/catch/finally
|
|
84
|
+
if (this.config.options.coalescing) {
|
|
85
|
+
logger.debug('Set provider response in cache, removing in flight from cache');
|
|
86
|
+
await this.cache.delete(this.inFlightPrefix);
|
|
87
|
+
}
|
|
88
|
+
return parsedResponse;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
exports.RestTransport = RestTransport;
|
|
@@ -0,0 +1,85 @@
|
|
|
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.axiosRequest = void 0;
|
|
30
|
+
const axios_1 = __importDefault(require("axios"));
|
|
31
|
+
const error_1 = require("../validation/error");
|
|
32
|
+
const transportMetrics = __importStar(require("./metrics"));
|
|
33
|
+
/**
|
|
34
|
+
* Performs axios request along with metrics recording and error handling
|
|
35
|
+
*
|
|
36
|
+
* @param request - axios request config
|
|
37
|
+
* @returns axios response for the request
|
|
38
|
+
*/
|
|
39
|
+
async function axiosRequest(request) {
|
|
40
|
+
const responseTimer = transportMetrics.dataProviderRequestDurationSeconds.startTimer();
|
|
41
|
+
let providerResponse;
|
|
42
|
+
try {
|
|
43
|
+
providerResponse = await axios_1.default.request(request);
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
const error = e;
|
|
47
|
+
// Request error
|
|
48
|
+
let providerStatusCode;
|
|
49
|
+
let name;
|
|
50
|
+
let statusCode;
|
|
51
|
+
if (error.code === 'ECONNABORTED') {
|
|
52
|
+
providerStatusCode = error?.response?.status ?? 504;
|
|
53
|
+
name = 'Data Provider Request Timeout error';
|
|
54
|
+
statusCode = 504;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
providerStatusCode = error?.response?.status ?? 0; // 0 -> connection error
|
|
58
|
+
statusCode = 200;
|
|
59
|
+
}
|
|
60
|
+
// Record count of failed data provider request
|
|
61
|
+
transportMetrics.dataProviderRequests
|
|
62
|
+
.labels(transportMetrics.dataProviderMetricsLabel(providerStatusCode, request.method))
|
|
63
|
+
.inc();
|
|
64
|
+
// TODO: Use specific AdapterErrors once ported over (AdapterTimeoutError, AdapterConnectionError, AdapterDataProviderError)
|
|
65
|
+
throw new error_1.AdapterError({
|
|
66
|
+
statusCode,
|
|
67
|
+
name,
|
|
68
|
+
providerStatusCode,
|
|
69
|
+
message: error?.message,
|
|
70
|
+
cause: error,
|
|
71
|
+
errorResponse: error?.response?.data,
|
|
72
|
+
url: request.url,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
// Record time taken for data provider request for success or failure
|
|
77
|
+
responseTimer();
|
|
78
|
+
}
|
|
79
|
+
// Record count of successful data provider requests
|
|
80
|
+
transportMetrics.dataProviderRequests
|
|
81
|
+
.labels(transportMetrics.dataProviderMetricsLabel(providerResponse.status, request.method))
|
|
82
|
+
.inc();
|
|
83
|
+
return providerResponse;
|
|
84
|
+
}
|
|
85
|
+
exports.axiosRequest = axiosRequest;
|
|
@@ -0,0 +1,171 @@
|
|
|
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.WebSocketTransport = exports.WebSocketClassProvider = exports.DEFAULT_WS_PERIOD = exports.DEFAULT_WS_TTL = void 0;
|
|
30
|
+
const ws_1 = __importDefault(require("ws"));
|
|
31
|
+
const util_1 = require("../util");
|
|
32
|
+
const _1 = require("./");
|
|
33
|
+
const transportMetrics = __importStar(require("./metrics"));
|
|
34
|
+
// TODO: Config
|
|
35
|
+
exports.DEFAULT_WS_TTL = 10000;
|
|
36
|
+
exports.DEFAULT_WS_PERIOD = 500;
|
|
37
|
+
const logger = (0, util_1.makeLogger)('WebSocketTransport');
|
|
38
|
+
class WebSocketClassProvider {
|
|
39
|
+
static set(ctor) {
|
|
40
|
+
this.ctor = ctor;
|
|
41
|
+
}
|
|
42
|
+
static get() {
|
|
43
|
+
return this.ctor;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
exports.WebSocketClassProvider = WebSocketClassProvider;
|
|
47
|
+
WebSocketClassProvider.ctor = ws_1.default;
|
|
48
|
+
/**
|
|
49
|
+
* Transport implementation that takes incoming requests, adds them to an [[ExpiringSortedSet]] and,
|
|
50
|
+
* through a WebSocket connection, subscribes to the relevant feeds to populate the cache.
|
|
51
|
+
*
|
|
52
|
+
* @typeParam AdapterParams - interface for the adapter request body
|
|
53
|
+
* @typeParam ProviderDataMessage - interface for a WS message containing processable data (i.e. not part of open/close/login/etc)
|
|
54
|
+
*/
|
|
55
|
+
class WebSocketTransport {
|
|
56
|
+
constructor(config) {
|
|
57
|
+
this.config = config;
|
|
58
|
+
// The double sets serve to create a simple polling mechanism instead of needing a subscription
|
|
59
|
+
// This one would be either local, redis, etc
|
|
60
|
+
this.expiringSortedSet = new util_1.ExpiringSortedSet(); // TODO: Move to dependencies, inject
|
|
61
|
+
// This one would not; this is always local state
|
|
62
|
+
this.localSubscriptions = [];
|
|
63
|
+
}
|
|
64
|
+
async initialize(dependencies) {
|
|
65
|
+
this.cache = dependencies.cache;
|
|
66
|
+
}
|
|
67
|
+
async hasBeenSetUp(req) {
|
|
68
|
+
return !!this.expiringSortedSet.get(req.requestContext.cacheKey);
|
|
69
|
+
}
|
|
70
|
+
async setup(req) {
|
|
71
|
+
logger.debug(`Adding entry to subscription set: [${req.requestContext.cacheKey}] = ${req.requestContext.data}`);
|
|
72
|
+
this.expiringSortedSet.add(req.requestContext.cacheKey, req.requestContext.data, exports.DEFAULT_WS_TTL);
|
|
73
|
+
}
|
|
74
|
+
// TODO: Maybe we don't do this, and leave the preparation on the adapter's side?
|
|
75
|
+
// TODO: Maybe we store adapter params pre-prepared? That would be more efficient
|
|
76
|
+
// Assuming always JSON payloads for now, makes it all cleaner
|
|
77
|
+
serializeMessage(payload) {
|
|
78
|
+
return typeof payload === 'string' ? payload : JSON.stringify(payload);
|
|
79
|
+
}
|
|
80
|
+
deserializeMessage(data) {
|
|
81
|
+
return JSON.parse(data.toString());
|
|
82
|
+
}
|
|
83
|
+
establishWsConnection(context) {
|
|
84
|
+
return new Promise((resolve) => {
|
|
85
|
+
const ctor = WebSocketClassProvider.get();
|
|
86
|
+
this.wsConnection = new ctor(this.config.url);
|
|
87
|
+
this.wsConnection.addEventListener('open', async (event) => {
|
|
88
|
+
logger.debug(`Opened websocket connection.`);
|
|
89
|
+
await this.config.handlers.open(this.wsConnection, context);
|
|
90
|
+
logger.debug('Successfully executed connection opened handler');
|
|
91
|
+
// Record active ws connections by incrementing count on open
|
|
92
|
+
// Using URL in label since connection_key is removed from v3
|
|
93
|
+
transportMetrics.wsConnectionActive.labels({ url: this.config.url }).inc();
|
|
94
|
+
resolve(true);
|
|
95
|
+
});
|
|
96
|
+
this.wsConnection.addEventListener('message', async (event) => {
|
|
97
|
+
// TODO: Assuming JSON always, maybe use BSON also?
|
|
98
|
+
const parsed = this.deserializeMessage(event.data);
|
|
99
|
+
logger.trace(`Got ws message: ${parsed}`);
|
|
100
|
+
const results = this.config.handlers.message(parsed, context);
|
|
101
|
+
if (Array.isArray(results)) {
|
|
102
|
+
const responses = (0, _1.buildCacheEntriesFromResults)(results, context);
|
|
103
|
+
logger.trace(`Writing ${responses.length} responses to cache`);
|
|
104
|
+
await this.cache.setMany(responses, context.adapterConfig.CACHE_MAX_AGE);
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
this.wsConnection.addEventListener('error', async (event) => {
|
|
108
|
+
// Record connection error count
|
|
109
|
+
transportMetrics.wsConnectionErrors.labels(transportMetrics.connectionErrorLabels(event.message)).inc();
|
|
110
|
+
});
|
|
111
|
+
this.wsConnection.addEventListener('close', (event) => {
|
|
112
|
+
logger.debug(`Closed websocket connection. Code: ${event.code} ; reason: ${event.reason?.toString()}`);
|
|
113
|
+
// Record active ws connections by decrementing count on close
|
|
114
|
+
// Using URL in label since connection_key is removed from v3
|
|
115
|
+
transportMetrics.wsConnectionActive.labels({ url: this.config.url }).dec();
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
// Unlike cache warming, this execute will manage subscriptions
|
|
120
|
+
async backgroundExecute(context) {
|
|
121
|
+
logger.debug('Starting background execute, getting subscriptions from sorted set');
|
|
122
|
+
const desiredSubs = this.expiringSortedSet.getAll();
|
|
123
|
+
logger.debug('Generating delta (subscribes & unsubscribes)');
|
|
124
|
+
// TODO: More efficient algorithm, this is really easy to read, but high(er) time complexity
|
|
125
|
+
const subscribes = desiredSubs
|
|
126
|
+
.filter((s) => !this.localSubscriptions.includes(s))
|
|
127
|
+
.map(this.config.builders.subscribeMessage)
|
|
128
|
+
.map(this.serializeMessage);
|
|
129
|
+
const unsubscribes = this.localSubscriptions
|
|
130
|
+
.filter((s) => !desiredSubs.includes(s))
|
|
131
|
+
.map(this.config.builders.unsubscribeMessage)
|
|
132
|
+
.map(this.serializeMessage);
|
|
133
|
+
if (subscribes.length || unsubscribes.length) {
|
|
134
|
+
logger.debug(`${subscribes.length} new subscriptions; ${unsubscribes.length} to unsubscribe`);
|
|
135
|
+
logger.trace('Will subscribe to:', subscribes);
|
|
136
|
+
logger.trace('Will unsubscribe to:', unsubscribes);
|
|
137
|
+
}
|
|
138
|
+
// New subs && no connection -> connect -> add subs
|
|
139
|
+
// No new subs && no connection -> skip
|
|
140
|
+
// New subs && connection -> add subs
|
|
141
|
+
// No new subs && connection -> unsubs only
|
|
142
|
+
if (!subscribes.length && !this.wsConnection) {
|
|
143
|
+
logger.debug('No entries in subscription set and no established connection, skipping');
|
|
144
|
+
return exports.DEFAULT_WS_PERIOD;
|
|
145
|
+
}
|
|
146
|
+
if (!this.wsConnection && subscribes.length) {
|
|
147
|
+
logger.debug('No established connection and new subscriptions available, connecting to WS');
|
|
148
|
+
await this.establishWsConnection(context);
|
|
149
|
+
}
|
|
150
|
+
// TODO: Close connection at some point?
|
|
151
|
+
// TODO: Finish ws metrics
|
|
152
|
+
logger.debug('Sending subs/unsubs if there are any');
|
|
153
|
+
const messages = unsubscribes.concat(subscribes);
|
|
154
|
+
for (const message of messages) {
|
|
155
|
+
logger.trace(`Sending message: ${JSON.stringify(message)}`);
|
|
156
|
+
this.wsConnection.send(message);
|
|
157
|
+
// Record total number of ws messages sent
|
|
158
|
+
// ws_message_total.labels(messageLabels(this.config.key)).inc()
|
|
159
|
+
}
|
|
160
|
+
// Record number of total subscriptions made
|
|
161
|
+
// ws_subscription_total.labels(subscriptionLabels(this.config.key)).inc(subscribes.length())
|
|
162
|
+
// Record number of active ws subscriptions
|
|
163
|
+
// const activeSubCount = desiredSubs ? desiredSubs.length : 0
|
|
164
|
+
// ws_subscription_active.labels(subscriptionLabels(this.config.key)).set(activeSubCount)
|
|
165
|
+
logger.debug('Setting local state to cache value');
|
|
166
|
+
this.localSubscriptions = desiredSubs;
|
|
167
|
+
logger.debug('Background execute complete');
|
|
168
|
+
return exports.DEFAULT_WS_PERIOD;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
exports.WebSocketTransport = WebSocketTransport;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ExpiringSortedSet = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* This class implements a set of unique items, each of which has an expiration timestamp.
|
|
6
|
+
* On reads, items that have expired will be deleted from the set and not returned.
|
|
7
|
+
*
|
|
8
|
+
* @typeParam T - the type of the set entries' values
|
|
9
|
+
*/
|
|
10
|
+
class ExpiringSortedSet {
|
|
11
|
+
constructor() {
|
|
12
|
+
this.map = new Map();
|
|
13
|
+
}
|
|
14
|
+
add(key, value, ttl) {
|
|
15
|
+
this.map.set(key, {
|
|
16
|
+
value,
|
|
17
|
+
expirationTimestamp: Date.now() + ttl,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
get(key) {
|
|
21
|
+
const entry = this.map.get(key);
|
|
22
|
+
if (!entry) {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
else if (entry.expirationTimestamp < Date.now()) {
|
|
26
|
+
return entry.value;
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
this.map.delete(key);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
getAll() {
|
|
33
|
+
const results = [];
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
// Since we're iterating, might as well prune here
|
|
36
|
+
for (const [key, entry] of this.map.entries()) {
|
|
37
|
+
if (entry.expirationTimestamp < now) {
|
|
38
|
+
this.map.delete(key); // In theory, this shouldn't happen frequently for feeds
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
results.push(entry.value);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return results;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
exports.ExpiringSortedSet = ExpiringSortedSet;
|