@chainlink/external-adapter-framework 0.0.10 → 0.0.12
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/.c8rc.json +3 -0
- package/.eslintignore +9 -0
- package/.eslintrc.js +96 -0
- package/.github/README.MD +17 -0
- package/.github/actions/setup/action.yaml +13 -0
- package/.github/workflows/main.yaml +39 -0
- package/.github/workflows/publish.yaml +20 -0
- package/.prettierignore +13 -0
- package/.yarnrc +0 -0
- package/README.md +103 -0
- package/dist/src/adapter.d.ts +135 -0
- package/dist/src/adapter.js +145 -0
- package/dist/src/background-executor.d.ts +11 -0
- package/{background-executor.js → dist/src/background-executor.js} +0 -0
- package/{cache → dist/src/cache}/factory.d.ts +0 -0
- package/dist/src/cache/factory.js +55 -0
- package/dist/src/cache/index.d.ts +94 -0
- package/dist/src/cache/index.js +173 -0
- package/{cache → dist/src/cache}/local.d.ts +0 -0
- package/{cache → dist/src/cache}/local.js +0 -0
- package/{cache → dist/src/cache}/metrics.d.ts +0 -0
- package/{cache → dist/src/cache}/metrics.js +0 -0
- package/{cache → dist/src/cache}/redis.d.ts +0 -0
- package/dist/src/cache/redis.js +100 -0
- package/dist/src/chainlink-external-adapter-framework-0.0.6.tgz +0 -0
- package/dist/src/config/index.d.ts +214 -0
- package/dist/src/config/index.js +380 -0
- package/{config → dist/src/config}/provider-limits.d.ts +0 -0
- package/{config → dist/src/config}/provider-limits.js +1 -1
- package/dist/src/examples/bank-frick/accounts.d.ts +39 -0
- package/dist/src/examples/bank-frick/accounts.js +192 -0
- package/dist/src/examples/bank-frick/config/index.d.ts +4 -0
- package/dist/src/examples/bank-frick/config/index.js +54 -0
- package/dist/src/examples/bank-frick/index.d.ts +2 -0
- package/dist/src/examples/bank-frick/index.js +15 -0
- package/dist/src/examples/bank-frick/util.d.ts +4 -0
- package/dist/src/examples/bank-frick/util.js +39 -0
- package/dist/src/examples/coingecko/batch-warming.d.ts +7 -0
- package/dist/src/examples/coingecko/batch-warming.js +53 -0
- package/dist/src/examples/coingecko/index.d.ts +2 -0
- package/dist/src/examples/coingecko/index.js +11 -0
- package/dist/src/examples/coingecko/rest.d.ts +12 -0
- package/dist/src/examples/coingecko/rest.js +51 -0
- package/{examples → dist/src/examples}/ncfx/config/index.d.ts +0 -0
- package/{examples → dist/src/examples}/ncfx/config/index.js +0 -0
- package/dist/src/examples/ncfx/index.d.ts +13 -0
- package/dist/src/examples/ncfx/index.js +11 -0
- package/dist/src/examples/ncfx/websocket.d.ts +47 -0
- package/dist/src/examples/ncfx/websocket.js +73 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +128 -0
- package/{metrics → dist/src/metrics}/constants.d.ts +0 -0
- package/{metrics → dist/src/metrics}/constants.js +0 -0
- package/{metrics → dist/src/metrics}/index.d.ts +0 -0
- package/dist/src/metrics/index.js +122 -0
- package/dist/src/metrics/util.d.ts +7 -0
- package/dist/src/metrics/util.js +9 -0
- package/{adapter.d.ts → dist/src/package/adapter.d.ts} +0 -0
- package/{adapter.js → dist/src/package/adapter.js} +0 -0
- package/{background-executor.d.ts → dist/src/package/background-executor.d.ts} +0 -0
- package/dist/src/package/background-executor.js +45 -0
- package/dist/src/package/cache/factory.d.ts +6 -0
- package/{cache → dist/src/package/cache}/factory.js +0 -0
- package/{cache → dist/src/package/cache}/index.d.ts +0 -0
- package/{cache → dist/src/package/cache}/index.js +0 -0
- package/dist/src/package/cache/local.d.ts +23 -0
- package/dist/src/package/cache/local.js +83 -0
- package/dist/src/package/cache/metrics.d.ts +27 -0
- package/dist/src/package/cache/metrics.js +120 -0
- package/dist/src/package/cache/redis.d.ts +16 -0
- package/{cache → dist/src/package/cache}/redis.js +0 -0
- package/{config → dist/src/package/config}/index.d.ts +0 -0
- package/{config → dist/src/package/config}/index.js +0 -0
- package/dist/src/package/config/provider-limits.d.ts +31 -0
- package/dist/src/package/config/provider-limits.js +76 -0
- package/{examples → dist/src/package/examples}/coingecko/batch-warming.d.ts +0 -0
- package/{examples → dist/src/package/examples}/coingecko/batch-warming.js +0 -0
- package/{examples → dist/src/package/examples}/coingecko/index.d.ts +0 -0
- package/{examples → dist/src/package/examples}/coingecko/index.js +0 -0
- package/{examples → dist/src/package/examples}/coingecko/rest.d.ts +0 -0
- package/{examples → dist/src/package/examples}/coingecko/rest.js +0 -0
- package/dist/src/package/examples/ncfx/config/index.d.ts +12 -0
- package/dist/src/package/examples/ncfx/config/index.js +15 -0
- package/{examples → dist/src/package/examples}/ncfx/index.d.ts +0 -0
- package/{examples → dist/src/package/examples}/ncfx/index.js +0 -0
- package/{examples → dist/src/package/examples}/ncfx/websocket.d.ts +0 -0
- package/{examples → dist/src/package/examples}/ncfx/websocket.js +0 -0
- package/{index.d.ts → dist/src/package/index.d.ts} +0 -0
- package/{index.js → dist/src/package/index.js} +0 -0
- package/dist/src/package/metrics/constants.d.ts +16 -0
- package/dist/src/package/metrics/constants.js +25 -0
- package/dist/src/package/metrics/index.d.ts +15 -0
- package/{metrics → dist/src/package/metrics}/index.js +0 -0
- package/{metrics → dist/src/package/metrics}/util.d.ts +0 -0
- package/{metrics → dist/src/package/metrics}/util.js +0 -0
- package/dist/src/package/package.json +72 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/background/fixed-frequency.d.ts +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/background/fixed-frequency.js +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/index.d.ts +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/index.js +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/metrics.d.ts +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/metrics.js +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/request/simple-counting.d.ts +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/request/simple-counting.js +0 -0
- package/{test.d.ts → dist/src/package/test.d.ts} +0 -0
- package/{test.js → dist/src/package/test.js} +0 -0
- package/{transports → dist/src/package/transports}/batch-warming.d.ts +0 -0
- package/{transports → dist/src/package/transports}/batch-warming.js +0 -0
- package/{transports → dist/src/package/transports}/index.d.ts +0 -0
- package/{transports → dist/src/package/transports}/index.js +0 -0
- package/{transports → dist/src/package/transports}/metrics.d.ts +0 -0
- package/{transports → dist/src/package/transports}/metrics.js +0 -0
- package/{transports → dist/src/package/transports}/rest.d.ts +0 -0
- package/{transports → dist/src/package/transports}/rest.js +0 -0
- package/{transports → dist/src/package/transports}/util.d.ts +0 -0
- package/{transports → dist/src/package/transports}/util.js +0 -0
- package/{transports → dist/src/package/transports}/websocket.d.ts +0 -0
- package/{transports → dist/src/package/transports}/websocket.js +0 -0
- package/{util → dist/src/package/util}/expiring-sorted-set.d.ts +0 -0
- package/{util → dist/src/package/util}/expiring-sorted-set.js +0 -0
- package/{util → dist/src/package/util}/index.d.ts +0 -0
- package/{util → dist/src/package/util}/index.js +0 -0
- package/{util → dist/src/package/util}/logger.d.ts +0 -0
- package/{util → dist/src/package/util}/logger.js +0 -0
- package/{util → dist/src/package/util}/request.d.ts +0 -0
- package/{util → dist/src/package/util}/request.js +0 -0
- package/{validation → dist/src/package/validation}/error.d.ts +0 -0
- package/{validation → dist/src/package/validation}/error.js +0 -0
- package/{validation → dist/src/package/validation}/index.d.ts +0 -0
- package/{validation → dist/src/package/validation}/index.js +0 -0
- package/{validation → dist/src/package/validation}/input-params.d.ts +0 -0
- package/{validation → dist/src/package/validation}/input-params.js +0 -0
- package/{validation → dist/src/package/validation}/override-functions.d.ts +0 -0
- package/{validation → dist/src/package/validation}/override-functions.js +0 -0
- package/{validation → dist/src/package/validation}/preset-tokens.json +0 -0
- package/{validation → dist/src/package/validation}/validator.d.ts +0 -0
- package/{validation → dist/src/package/validation}/validator.js +0 -0
- package/dist/src/package.json +72 -0
- package/dist/src/rate-limiting/background/fixed-frequency.d.ts +11 -0
- package/dist/src/rate-limiting/background/fixed-frequency.js +35 -0
- package/dist/src/rate-limiting/index.d.ts +55 -0
- package/dist/src/rate-limiting/index.js +63 -0
- package/dist/src/rate-limiting/metrics.d.ts +3 -0
- package/dist/src/rate-limiting/metrics.js +44 -0
- package/dist/src/rate-limiting/request/simple-counting.d.ts +21 -0
- package/dist/src/rate-limiting/request/simple-counting.js +62 -0
- package/dist/src/test.d.ts +1 -0
- package/dist/src/test.js +6 -0
- package/dist/src/transports/batch-warming.d.ts +35 -0
- package/dist/src/transports/batch-warming.js +101 -0
- package/dist/src/transports/index.d.ts +70 -0
- package/dist/src/transports/index.js +87 -0
- package/dist/src/transports/metrics.d.ts +22 -0
- package/dist/src/transports/metrics.js +105 -0
- package/dist/src/transports/rest.d.ts +44 -0
- package/dist/src/transports/rest.js +131 -0
- package/dist/src/transports/util.d.ts +8 -0
- package/dist/src/transports/util.js +85 -0
- package/dist/src/transports/websocket.d.ts +80 -0
- package/dist/src/transports/websocket.js +166 -0
- package/dist/src/util/expiring-sorted-set.d.ts +21 -0
- package/dist/src/util/expiring-sorted-set.js +47 -0
- package/dist/src/util/index.d.ts +12 -0
- package/dist/src/util/index.js +35 -0
- package/dist/src/util/logger.d.ts +42 -0
- package/dist/src/util/logger.js +62 -0
- package/dist/src/util/request.d.ts +57 -0
- package/dist/src/util/request.js +2 -0
- package/dist/src/util/subscription-set/expiring-sorted-set.d.ts +22 -0
- package/dist/src/util/subscription-set/expiring-sorted-set.js +47 -0
- package/dist/src/util/subscription-set/subscription-set.d.ts +18 -0
- package/dist/src/util/subscription-set/subscription-set.js +19 -0
- package/dist/src/util/test-payload-loader.d.ts +25 -0
- package/dist/src/util/test-payload-loader.js +83 -0
- package/dist/src/validation/error.d.ts +50 -0
- package/dist/src/validation/error.js +79 -0
- package/dist/src/validation/index.d.ts +5 -0
- package/dist/src/validation/index.js +91 -0
- package/dist/src/validation/input-params.d.ts +15 -0
- package/dist/src/validation/input-params.js +30 -0
- package/dist/src/validation/override-functions.d.ts +3 -0
- package/dist/src/validation/override-functions.js +40 -0
- package/dist/src/validation/preset-tokens.json +23 -0
- package/dist/src/validation/validator.d.ts +47 -0
- package/dist/src/validation/validator.js +303 -0
- package/docker-compose.yaml +35 -0
- package/env.sh +54 -0
- package/env2.sh +55 -0
- package/package.json +5 -3
- package/publish.sh +0 -0
- package/src/adapter.ts +263 -0
- package/src/background-executor.ts +52 -0
- package/src/cache/factory.ts +26 -0
- package/src/cache/index.ts +258 -0
- package/src/cache/local.ts +73 -0
- package/src/cache/metrics.ts +112 -0
- package/src/cache/redis.ts +93 -0
- package/src/config/index.ts +517 -0
- package/src/config/provider-limits.ts +130 -0
- package/src/examples/bank-frick/README.MD +10 -0
- package/src/examples/bank-frick/accounts.ts +246 -0
- package/src/examples/bank-frick/config/index.ts +53 -0
- package/src/examples/bank-frick/index.ts +13 -0
- package/src/examples/bank-frick/types.d.ts +38 -0
- package/src/examples/bank-frick/util.ts +55 -0
- package/src/examples/coingecko/batch-warming.ts +78 -0
- package/src/examples/coingecko/index.ts +9 -0
- package/src/examples/coingecko/rest.ts +77 -0
- package/src/examples/ncfx/config/index.ts +12 -0
- package/src/examples/ncfx/index.ts +9 -0
- package/src/examples/ncfx/websocket.ts +99 -0
- package/src/index.ts +149 -0
- package/src/metrics/constants.ts +23 -0
- package/src/metrics/index.ts +115 -0
- package/src/metrics/util.ts +18 -0
- package/src/rate-limiting/background/fixed-frequency.ts +45 -0
- package/src/rate-limiting/index.ts +100 -0
- package/src/rate-limiting/metrics.ts +18 -0
- package/src/rate-limiting/request/simple-counting.ts +76 -0
- package/src/test.ts +5 -0
- package/src/transports/batch-warming.ts +122 -0
- package/src/transports/index.ts +152 -0
- package/src/transports/metrics.ts +95 -0
- package/src/transports/rest.ts +164 -0
- package/src/transports/util.ts +63 -0
- package/src/transports/websocket.ts +245 -0
- package/src/util/index.ts +22 -0
- package/src/util/logger.ts +69 -0
- package/src/util/request.ts +117 -0
- package/src/util/subscription-set/expiring-sorted-set.ts +54 -0
- package/src/util/subscription-set/subscription-set.ts +35 -0
- package/src/util/test-payload-loader.ts +87 -0
- package/src/validation/error.ts +116 -0
- package/src/validation/index.ts +110 -0
- package/src/validation/input-params.ts +45 -0
- package/src/validation/override-functions.ts +44 -0
- package/src/validation/preset-tokens.json +23 -0
- package/src/validation/validator.ts +384 -0
- package/test/adapter.test.ts +27 -0
- package/test/background-executor.test.ts +108 -0
- package/test/cache/cache-key.test.ts +114 -0
- package/test/cache/helper.ts +100 -0
- package/test/cache/local.test.ts +54 -0
- package/test/cache/redis.test.ts +89 -0
- package/test/correlation.test.ts +114 -0
- package/test/index.test.ts +37 -0
- package/test/metrics/feed-id.test.ts +38 -0
- package/test/metrics/helper.ts +14 -0
- package/test/metrics/labels.test.ts +36 -0
- package/test/metrics/metrics.test.ts +267 -0
- package/test/metrics/redis-metrics.test.ts +113 -0
- package/test/metrics/warmer-metrics.test.ts +192 -0
- package/test/metrics/ws-metrics.test.ts +225 -0
- package/test/rate-limit-config.test.ts +242 -0
- package/test/smoke.test.ts +166 -0
- package/test/transports/batch.test.ts +465 -0
- package/test/transports/rest.test.ts +242 -0
- package/test/transports/websocket.test.ts +183 -0
- package/test/tsconfig.json +5 -0
- package/test/util.ts +77 -0
- package/test/validation.test.ts +178 -0
- package/test-payload-fail.json +3 -0
- package/test-payload.js +22 -0
- package/test-payload.json +7 -0
- package/test.sh +20 -0
- package/test2.sh +2 -0
- package/tsconfig.json +25 -0
- package/typedoc.json +6 -0
- package/webpack.config.js +23 -0
|
@@ -0,0 +1,166 @@
|
|
|
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 = 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
|
+
const logger = (0, util_1.makeLogger)('WebSocketTransport');
|
|
35
|
+
class WebSocketClassProvider {
|
|
36
|
+
static set(ctor) {
|
|
37
|
+
this.ctor = ctor;
|
|
38
|
+
}
|
|
39
|
+
static get() {
|
|
40
|
+
return this.ctor;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
exports.WebSocketClassProvider = WebSocketClassProvider;
|
|
44
|
+
WebSocketClassProvider.ctor = ws_1.default;
|
|
45
|
+
/**
|
|
46
|
+
* Transport implementation that takes incoming requests, adds them to an [[subscriptionSet]] and,
|
|
47
|
+
* through a WebSocket connection, subscribes to the relevant feeds to populate the cache.
|
|
48
|
+
*
|
|
49
|
+
* @typeParam AdapterParams - interface for the adapter request body
|
|
50
|
+
* @typeParam ProviderDataMessage - interface for a WS message containing processable data (i.e. not part of open/close/login/etc)
|
|
51
|
+
*/
|
|
52
|
+
class WebSocketTransport {
|
|
53
|
+
constructor(config) {
|
|
54
|
+
this.config = config;
|
|
55
|
+
// The double sets serve to create a simple polling mechanism instead of needing a subscription
|
|
56
|
+
// This one would not; this is always local state
|
|
57
|
+
this.localSubscriptions = [];
|
|
58
|
+
}
|
|
59
|
+
async initialize(dependencies) {
|
|
60
|
+
this.cache = dependencies.cache;
|
|
61
|
+
this.rateLimiter = dependencies.backgroundExecuteRateLimiter;
|
|
62
|
+
this.subscriptionSet = dependencies.subscriptionSetFactory.buildSet();
|
|
63
|
+
}
|
|
64
|
+
async hasBeenSetUp(req) {
|
|
65
|
+
return !!(await this.subscriptionSet.get(req.requestContext.cacheKey));
|
|
66
|
+
}
|
|
67
|
+
async setup(req, config) {
|
|
68
|
+
logger.debug(`Adding entry to subscription set: [${req.requestContext.cacheKey}] = ${req.requestContext.data}`);
|
|
69
|
+
await this.subscriptionSet.add(req.requestContext.cacheKey, req.requestContext.data, config.WS_SUBSCRIPTION_TTL);
|
|
70
|
+
}
|
|
71
|
+
// TODO: Maybe we don't do this, and leave the preparation on the adapter's side?
|
|
72
|
+
// TODO: Maybe we store adapter params pre-prepared? That would be more efficient
|
|
73
|
+
// Assuming always JSON payloads for now, makes it all cleaner
|
|
74
|
+
serializeMessage(payload) {
|
|
75
|
+
return typeof payload === 'string' ? payload : JSON.stringify(payload);
|
|
76
|
+
}
|
|
77
|
+
deserializeMessage(data) {
|
|
78
|
+
return JSON.parse(data.toString());
|
|
79
|
+
}
|
|
80
|
+
establishWsConnection(context) {
|
|
81
|
+
return new Promise((resolve) => {
|
|
82
|
+
const ctor = WebSocketClassProvider.get();
|
|
83
|
+
this.wsConnection = new ctor(this.config.url);
|
|
84
|
+
this.wsConnection.addEventListener('open', async (event) => {
|
|
85
|
+
logger.debug(`Opened websocket connection. (event type ${event.type})`);
|
|
86
|
+
await this.config.handlers.open(this.wsConnection, context);
|
|
87
|
+
logger.debug('Successfully executed connection opened handler');
|
|
88
|
+
// Record active ws connections by incrementing count on open
|
|
89
|
+
// Using URL in label since connection_key is removed from v3
|
|
90
|
+
transportMetrics.wsConnectionActive.inc();
|
|
91
|
+
resolve(true);
|
|
92
|
+
});
|
|
93
|
+
this.wsConnection.addEventListener('message', async (event) => {
|
|
94
|
+
// TODO: Assuming JSON always, maybe use BSON also?
|
|
95
|
+
const parsed = this.deserializeMessage(event.data);
|
|
96
|
+
logger.trace(`Got ws message: ${parsed}`);
|
|
97
|
+
const results = this.config.handlers.message(parsed, context);
|
|
98
|
+
if (Array.isArray(results)) {
|
|
99
|
+
const responses = (0, _1.buildCacheEntriesFromResults)(results, context);
|
|
100
|
+
logger.trace(`Writing ${responses.length} responses to cache`);
|
|
101
|
+
await this.cache.setMany(responses, context.adapterConfig.CACHE_MAX_AGE);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
this.wsConnection.addEventListener('error', async (event) => {
|
|
105
|
+
// Record connection error count
|
|
106
|
+
transportMetrics.wsConnectionErrors
|
|
107
|
+
.labels(transportMetrics.connectionErrorLabels(event.message))
|
|
108
|
+
.inc();
|
|
109
|
+
});
|
|
110
|
+
this.wsConnection.addEventListener('close', (event) => {
|
|
111
|
+
logger.debug(`Closed websocket connection. Code: ${event.code} ; reason: ${event.reason?.toString()}`);
|
|
112
|
+
// Record active ws connections by decrementing count on close
|
|
113
|
+
// Using URL in label since connection_key is removed from v3
|
|
114
|
+
transportMetrics.wsConnectionActive.dec();
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
// Unlike cache warming, this execute will manage subscriptions
|
|
119
|
+
async backgroundExecute(context) {
|
|
120
|
+
logger.debug('Starting background execute, getting subscriptions from sorted set');
|
|
121
|
+
const desiredSubs = await this.subscriptionSet.getAll();
|
|
122
|
+
logger.debug('Generating delta (subscribes & unsubscribes)');
|
|
123
|
+
// TODO: More efficient algorithm, this is really easy to read, but high(er) time complexity
|
|
124
|
+
const subscribeParams = desiredSubs.filter((s) => !this.localSubscriptions.includes(s));
|
|
125
|
+
const subscribes = subscribeParams
|
|
126
|
+
.map(this.config.builders.subscribeMessage)
|
|
127
|
+
.map(this.serializeMessage);
|
|
128
|
+
const unsubscribeParams = this.localSubscriptions.filter((s) => !desiredSubs.includes(s));
|
|
129
|
+
const unsubscribes = unsubscribeParams
|
|
130
|
+
.map(this.config.builders.unsubscribeMessage)
|
|
131
|
+
.map(this.serializeMessage);
|
|
132
|
+
logger.debug(`${subscribes.length} new subscriptions; ${unsubscribes.length} to unsubscribe`);
|
|
133
|
+
if (subscribes.length) {
|
|
134
|
+
logger.trace(`Will subscribe to: ${subscribes}`);
|
|
135
|
+
}
|
|
136
|
+
if (unsubscribes.length) {
|
|
137
|
+
logger.trace(`Will unsubscribe to: ${unsubscribes}`);
|
|
138
|
+
}
|
|
139
|
+
// New subs && no connection -> connect -> add subs
|
|
140
|
+
// No new subs && no connection -> skip
|
|
141
|
+
// New subs && connection -> add subs
|
|
142
|
+
// No new subs && connection -> unsubs only
|
|
143
|
+
if (!subscribes.length && !this.wsConnection) {
|
|
144
|
+
logger.debug('No entries in subscription set and no established connection, skipping');
|
|
145
|
+
return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name);
|
|
146
|
+
}
|
|
147
|
+
if (!this.wsConnection && subscribes.length) {
|
|
148
|
+
logger.debug('No established connection and new subscriptions available, connecting to WS');
|
|
149
|
+
await this.establishWsConnection(context);
|
|
150
|
+
}
|
|
151
|
+
// TODO: Close connection at some point?
|
|
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
|
+
}
|
|
158
|
+
// Record WS message and subscription metrics
|
|
159
|
+
transportMetrics.recordWsMessageMetrics(context, subscribeParams, unsubscribeParams);
|
|
160
|
+
logger.debug('Setting local state to cache value');
|
|
161
|
+
this.localSubscriptions = desiredSubs;
|
|
162
|
+
logger.debug('Background execute complete');
|
|
163
|
+
return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
exports.WebSocketTransport = WebSocketTransport;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An object describing an entry in the expiring sorted set.
|
|
3
|
+
* @typeParam T - the type of the entry's value
|
|
4
|
+
*/
|
|
5
|
+
interface ExpiringSortedSetEntry<T> {
|
|
6
|
+
value: T;
|
|
7
|
+
expirationTimestamp: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* This class implements a set of unique items, each of which has an expiration timestamp.
|
|
11
|
+
* On reads, items that have expired will be deleted from the set and not returned.
|
|
12
|
+
*
|
|
13
|
+
* @typeParam T - the type of the set entries' values
|
|
14
|
+
*/
|
|
15
|
+
export declare class ExpiringSortedSet<T> {
|
|
16
|
+
map: Map<string, ExpiringSortedSetEntry<T>>;
|
|
17
|
+
add(key: string, value: T, ttl: number): void;
|
|
18
|
+
get(key: string): T | undefined;
|
|
19
|
+
getAll(): T[];
|
|
20
|
+
}
|
|
21
|
+
export {};
|
|
@@ -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;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from './request';
|
|
2
|
+
export * from './logger';
|
|
3
|
+
export * from './subscription-set/subscription-set';
|
|
4
|
+
/**
|
|
5
|
+
* Sleeps for the provided number of milliseconds
|
|
6
|
+
* @param ms - The number of milliseconds to sleep for
|
|
7
|
+
* @returns a Promise that resolves once the specified time passes
|
|
8
|
+
*/
|
|
9
|
+
export declare const sleep: (ms: number) => Promise<void>;
|
|
10
|
+
export declare const isObject: (o: unknown) => boolean;
|
|
11
|
+
export declare const isArray: (o: unknown) => boolean;
|
|
12
|
+
export declare type PromiseOrValue<T> = Promise<T> | T;
|
|
@@ -0,0 +1,35 @@
|
|
|
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.isArray = exports.isObject = exports.sleep = void 0;
|
|
18
|
+
__exportStar(require("./request"), exports);
|
|
19
|
+
__exportStar(require("./logger"), exports);
|
|
20
|
+
__exportStar(require("./subscription-set/subscription-set"), exports);
|
|
21
|
+
/**
|
|
22
|
+
* Sleeps for the provided number of milliseconds
|
|
23
|
+
* @param ms - The number of milliseconds to sleep for
|
|
24
|
+
* @returns a Promise that resolves once the specified time passes
|
|
25
|
+
*/
|
|
26
|
+
const sleep = (ms) => {
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
setTimeout(resolve, ms);
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
exports.sleep = sleep;
|
|
32
|
+
const isObject = (o) => o !== null && typeof o === 'object' && Array.isArray(o) === false;
|
|
33
|
+
exports.isObject = isObject;
|
|
34
|
+
const isArray = (o) => o !== null && typeof o === 'object' && Array.isArray(o);
|
|
35
|
+
exports.isArray = isArray;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import pino from 'pino';
|
|
3
|
+
import { AdapterRequest } from './request';
|
|
4
|
+
import { FastifyReply, HookHandlerDoneFunction } from 'fastify';
|
|
5
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
6
|
+
export declare const asyncLocalStorage: AsyncLocalStorage<unknown>;
|
|
7
|
+
export declare type Store = {
|
|
8
|
+
correlationId: string;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Instead of using a global logger instance, we want to force using a child logger
|
|
12
|
+
* with a specific layer set in it, so that we can filter logs by where they're output from.
|
|
13
|
+
*
|
|
14
|
+
* Details on what each log level represents:
|
|
15
|
+
* "trace": Forensic debugging of issues on a local machine.
|
|
16
|
+
* "debug": Detailed logging level to get more context from users on their environments.
|
|
17
|
+
* "info": High-level informational messages, to describe at a glance the high level state of the system.
|
|
18
|
+
* "warn": A mild error occurred that might require non-urgent action.
|
|
19
|
+
* "error": An unexpected error occurred during the regular operation of a well-maintained EA.
|
|
20
|
+
* "fatal": The EA encountered an unrecoverable problem and had to exit.
|
|
21
|
+
*
|
|
22
|
+
* Full reference this is based on can be found at
|
|
23
|
+
* https://github.com/smartcontractkit/documentation/blob/main/docs/Node%20Operators/configuration-variables.md#log_level
|
|
24
|
+
*
|
|
25
|
+
* @param layer - the layer name to include in the logs (e.g. "SomeMiddleware", "RedisCache", etc.)
|
|
26
|
+
* @returns a layer specific logger
|
|
27
|
+
*/
|
|
28
|
+
export declare const makeLogger: (layer: string) => pino.Logger<{
|
|
29
|
+
level: string;
|
|
30
|
+
mixin(): {};
|
|
31
|
+
transport: {
|
|
32
|
+
target: string;
|
|
33
|
+
options: {
|
|
34
|
+
levelFirst: boolean;
|
|
35
|
+
levelLabel: string;
|
|
36
|
+
ignore: string;
|
|
37
|
+
messageFormat: string;
|
|
38
|
+
translateTime: string;
|
|
39
|
+
};
|
|
40
|
+
} | undefined;
|
|
41
|
+
} & pino.ChildLoggerOptions>;
|
|
42
|
+
export declare const loggingContextMiddleware: (req: AdapterRequest, res: FastifyReply, done: HookHandlerDoneFunction) => void;
|
|
@@ -0,0 +1,62 @@
|
|
|
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.loggingContextMiddleware = exports.makeLogger = exports.asyncLocalStorage = void 0;
|
|
7
|
+
const pino_1 = __importDefault(require("pino"));
|
|
8
|
+
const config_1 = require("../config");
|
|
9
|
+
const crypto_1 = require("crypto");
|
|
10
|
+
const node_async_hooks_1 = require("node:async_hooks");
|
|
11
|
+
exports.asyncLocalStorage = new node_async_hooks_1.AsyncLocalStorage();
|
|
12
|
+
const debugTransport = {
|
|
13
|
+
target: 'pino-pretty',
|
|
14
|
+
options: {
|
|
15
|
+
levelFirst: true,
|
|
16
|
+
levelLabel: 'level',
|
|
17
|
+
ignore: 'layer,pid,hostname',
|
|
18
|
+
messageFormat: '[{correlationId}][{layer}] {msg}',
|
|
19
|
+
translateTime: 'yyyy-mm-dd HH:MM:ss.l',
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
// Base logger, shouldn't be used because we want layers to be specified
|
|
23
|
+
const baseLogger = (0, pino_1.default)({
|
|
24
|
+
level: process.env['LOG_LEVEL']?.toLowerCase() || config_1.BaseSettings.LOG_LEVEL.default,
|
|
25
|
+
mixin() {
|
|
26
|
+
if (process.env['CORRELATION_ID_ENABLED'] === 'true') {
|
|
27
|
+
const store = exports.asyncLocalStorage.getStore();
|
|
28
|
+
if (store) {
|
|
29
|
+
return store;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return {};
|
|
33
|
+
},
|
|
34
|
+
transport: process.env['DEBUG'] === 'true' ? debugTransport : undefined,
|
|
35
|
+
});
|
|
36
|
+
/**
|
|
37
|
+
* Instead of using a global logger instance, we want to force using a child logger
|
|
38
|
+
* with a specific layer set in it, so that we can filter logs by where they're output from.
|
|
39
|
+
*
|
|
40
|
+
* Details on what each log level represents:
|
|
41
|
+
* "trace": Forensic debugging of issues on a local machine.
|
|
42
|
+
* "debug": Detailed logging level to get more context from users on their environments.
|
|
43
|
+
* "info": High-level informational messages, to describe at a glance the high level state of the system.
|
|
44
|
+
* "warn": A mild error occurred that might require non-urgent action.
|
|
45
|
+
* "error": An unexpected error occurred during the regular operation of a well-maintained EA.
|
|
46
|
+
* "fatal": The EA encountered an unrecoverable problem and had to exit.
|
|
47
|
+
*
|
|
48
|
+
* Full reference this is based on can be found at
|
|
49
|
+
* https://github.com/smartcontractkit/documentation/blob/main/docs/Node%20Operators/configuration-variables.md#log_level
|
|
50
|
+
*
|
|
51
|
+
* @param layer - the layer name to include in the logs (e.g. "SomeMiddleware", "RedisCache", etc.)
|
|
52
|
+
* @returns a layer specific logger
|
|
53
|
+
*/
|
|
54
|
+
const makeLogger = (layer) => baseLogger.child({ layer });
|
|
55
|
+
exports.makeLogger = makeLogger;
|
|
56
|
+
const loggingContextMiddleware = (req, res, done) => {
|
|
57
|
+
const correlationId = req.headers['x-correlation-id'] || (0, crypto_1.randomUUID)();
|
|
58
|
+
exports.asyncLocalStorage.run({ correlationId: correlationId }, () => {
|
|
59
|
+
done();
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
exports.loggingContextMiddleware = loggingContextMiddleware;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from 'fastify';
|
|
2
|
+
import { Adapter } from '../adapter';
|
|
3
|
+
import { AdapterError } from '../validation/error';
|
|
4
|
+
declare module 'fastify' {
|
|
5
|
+
interface FastifyRequest {
|
|
6
|
+
requestContext: AdapterRequestContext;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export interface AdapterRequestBody<T = AdapterRequestData> {
|
|
10
|
+
endpoint?: string;
|
|
11
|
+
data: T;
|
|
12
|
+
id?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare type AdapterRequestContext<T = AdapterRequestData> = {
|
|
15
|
+
id: string;
|
|
16
|
+
endpointName: string;
|
|
17
|
+
cacheKey: string;
|
|
18
|
+
data: T;
|
|
19
|
+
meta?: AdapterRequestMeta;
|
|
20
|
+
};
|
|
21
|
+
export declare type AdapterRouteGeneric<T = AdapterRequestData> = {
|
|
22
|
+
Body: AdapterRequestBody<T>;
|
|
23
|
+
};
|
|
24
|
+
export declare type AdapterRequest<T = AdapterRequestData> = FastifyRequest<AdapterRouteGeneric<T>> & {
|
|
25
|
+
requestContext: AdapterRequestContext<T>;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Meta info that pertains to exposing metrics
|
|
29
|
+
*/
|
|
30
|
+
export interface AdapterRequestMeta {
|
|
31
|
+
metrics?: AdapterMetricsMeta;
|
|
32
|
+
error?: AdapterError | Error;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Meta info that pertains to exposing metrics
|
|
36
|
+
*/
|
|
37
|
+
export interface AdapterMetricsMeta {
|
|
38
|
+
feedId?: string;
|
|
39
|
+
cacheHit?: boolean;
|
|
40
|
+
}
|
|
41
|
+
export declare type AdapterRequestData = Record<string, unknown> & {
|
|
42
|
+
endpoint?: string;
|
|
43
|
+
};
|
|
44
|
+
export interface ProviderResult<Params> {
|
|
45
|
+
params: Params;
|
|
46
|
+
value: unknown;
|
|
47
|
+
}
|
|
48
|
+
export declare type AdapterResponse<T = unknown> = {
|
|
49
|
+
statusCode: number;
|
|
50
|
+
data: T;
|
|
51
|
+
result: unknown;
|
|
52
|
+
maxAge?: number;
|
|
53
|
+
meta?: AdapterRequestMeta;
|
|
54
|
+
providerStatusCode?: number;
|
|
55
|
+
};
|
|
56
|
+
export declare type Middleware = ((req: AdapterRequest, reply: FastifyReply, done: HookHandlerDoneFunction) => FastifyReply | void) | ((req: AdapterRequest, reply: FastifyReply) => Promise<FastifyReply | void>);
|
|
57
|
+
export declare type AdapterMiddlewareBuilder = (adapter: Adapter) => Middleware;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { SubscriptionSet } from './subscription-set';
|
|
2
|
+
/**
|
|
3
|
+
* An object describing an entry in the expiring sorted set.
|
|
4
|
+
* @typeParam T - the type of the entry's value
|
|
5
|
+
*/
|
|
6
|
+
interface ExpiringSortedSetEntry<T> {
|
|
7
|
+
value: T;
|
|
8
|
+
expirationTimestamp: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* This class implements a set of unique items, each of which has an expiration timestamp.
|
|
12
|
+
* On reads, items that have expired will be deleted from the set and not returned.
|
|
13
|
+
*
|
|
14
|
+
* @typeParam T - the type of the set entries' values
|
|
15
|
+
*/
|
|
16
|
+
export declare class ExpiringSortedSet<T> implements SubscriptionSet<T> {
|
|
17
|
+
map: Map<string, ExpiringSortedSetEntry<T>>;
|
|
18
|
+
add(key: string, value: T, ttl: number): void;
|
|
19
|
+
get(key: string): T | undefined;
|
|
20
|
+
getAll(): T[];
|
|
21
|
+
}
|
|
22
|
+
export {};
|
|
@@ -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;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { PromiseOrValue } from '..';
|
|
2
|
+
import { AdapterConfig } from '../../config';
|
|
3
|
+
/**
|
|
4
|
+
* Set to hold items to subscribe to from a provider (regardless of protocol)
|
|
5
|
+
*/
|
|
6
|
+
export interface SubscriptionSet<T> {
|
|
7
|
+
/** Add a new subscription to the set */
|
|
8
|
+
add(key: string, value: T, ttl: number): PromiseOrValue<void>;
|
|
9
|
+
/** Get a specific subscription from the set */
|
|
10
|
+
get(key: string): PromiseOrValue<T | undefined>;
|
|
11
|
+
/** Get all subscriptions from the set as a list */
|
|
12
|
+
getAll(): PromiseOrValue<T[]>;
|
|
13
|
+
}
|
|
14
|
+
export declare class SubscriptionSetFactory {
|
|
15
|
+
private cacheType;
|
|
16
|
+
constructor(config: AdapterConfig);
|
|
17
|
+
buildSet<T>(): SubscriptionSet<T>;
|
|
18
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SubscriptionSetFactory = void 0;
|
|
4
|
+
const expiring_sorted_set_1 = require("./expiring-sorted-set");
|
|
5
|
+
class SubscriptionSetFactory {
|
|
6
|
+
constructor(config) {
|
|
7
|
+
this.cacheType = config.CACHE_TYPE;
|
|
8
|
+
}
|
|
9
|
+
buildSet() {
|
|
10
|
+
switch (this.cacheType) {
|
|
11
|
+
case 'local':
|
|
12
|
+
return new expiring_sorted_set_1.ExpiringSortedSet();
|
|
13
|
+
case 'redis':
|
|
14
|
+
// TODO: Implement redis set
|
|
15
|
+
return new expiring_sorted_set_1.ExpiringSortedSet();
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
exports.SubscriptionSetFactory = SubscriptionSetFactory;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { AdapterRequestData } from './request';
|
|
2
|
+
/**
|
|
3
|
+
* The test payload read in from filesystem
|
|
4
|
+
*/
|
|
5
|
+
export interface Payload {
|
|
6
|
+
requests: Array<AdapterRequestData>;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Test payload with discriminated union so we can tell when we should just do
|
|
10
|
+
* a simple liveness check rather than a sample request
|
|
11
|
+
*/
|
|
12
|
+
declare type TestPayload = (Payload & {
|
|
13
|
+
isDefault: false;
|
|
14
|
+
}) | {
|
|
15
|
+
isDefault: true;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Load in a JSON file containing a test payload for the current adapter,
|
|
19
|
+
* used in healthchecks to make sample requests
|
|
20
|
+
*
|
|
21
|
+
* @param fileName - name of file that contains the test payload data for the smoke endpoint
|
|
22
|
+
* @returns the parsed payload with individual requests
|
|
23
|
+
*/
|
|
24
|
+
export declare function loadTestPayload(fileName?: string): TestPayload;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,83 @@
|
|
|
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.loadTestPayload = void 0;
|
|
7
|
+
const ajv_1 = __importDefault(require("ajv"));
|
|
8
|
+
const fs_1 = __importDefault(require("fs"));
|
|
9
|
+
const path_1 = __importDefault(require("path"));
|
|
10
|
+
const logger_1 = require("./logger");
|
|
11
|
+
const logger = (0, logger_1.makeLogger)('TestPayloadLoader');
|
|
12
|
+
/**
|
|
13
|
+
* Load in a JSON file containing a test payload for the current adapter,
|
|
14
|
+
* used in healthchecks to make sample requests
|
|
15
|
+
*
|
|
16
|
+
* @param fileName - name of file that contains the test payload data for the smoke endpoint
|
|
17
|
+
* @returns the parsed payload with individual requests
|
|
18
|
+
*/
|
|
19
|
+
function loadTestPayload(fileName) {
|
|
20
|
+
const ajv = new ajv_1.default();
|
|
21
|
+
const schema = {
|
|
22
|
+
type: 'object',
|
|
23
|
+
required: ['requests'],
|
|
24
|
+
properties: {
|
|
25
|
+
requests: {
|
|
26
|
+
type: 'array',
|
|
27
|
+
items: {
|
|
28
|
+
type: 'object',
|
|
29
|
+
required: [],
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
const validate = ajv.compile(schema);
|
|
35
|
+
try {
|
|
36
|
+
const payload = resolvePayload(fileName);
|
|
37
|
+
if (!validate(payload) || !payload?.requests) {
|
|
38
|
+
throw Error(JSON.stringify(validate?.errors || 'Could not validate schema for test payload'));
|
|
39
|
+
}
|
|
40
|
+
return { ...payload, isDefault: false };
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
logger.warn(`Could not load payload: ${e.message}`);
|
|
44
|
+
logger.warn('Falling back to default empty payload');
|
|
45
|
+
return { isDefault: true };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
exports.loadTestPayload = loadTestPayload;
|
|
49
|
+
function resolvePayload(fileName) {
|
|
50
|
+
try {
|
|
51
|
+
let payload = null;
|
|
52
|
+
// Find test payload by specified name, fallback to default names if not found
|
|
53
|
+
if (fileName && fs_1.default.existsSync(path_1.default.join(process.cwd(), fileName))) {
|
|
54
|
+
payload = require(path_1.default.join(process.cwd(), fileName));
|
|
55
|
+
}
|
|
56
|
+
else if (fileName && fs_1.default.existsSync(`./${fileName}`)) {
|
|
57
|
+
payload = require(`./${fileName}`);
|
|
58
|
+
}
|
|
59
|
+
// Search for test payload js first if no filename specified or found
|
|
60
|
+
else if (fs_1.default.existsSync(path_1.default.resolve('.', 'test-payload.js'))) {
|
|
61
|
+
payload = require(path_1.default.join(process.cwd(), 'test-payload.js'));
|
|
62
|
+
}
|
|
63
|
+
else if (fs_1.default.existsSync(`./test-payload.js`)) {
|
|
64
|
+
payload = require(`./test-payload.js`);
|
|
65
|
+
}
|
|
66
|
+
// Search for test payload json second if no filename specified or found
|
|
67
|
+
else if (fs_1.default.existsSync(path_1.default.join(process.cwd(), 'test-payload.json'))) {
|
|
68
|
+
payload = require(path_1.default.join(process.cwd(), 'test-payload.json'));
|
|
69
|
+
}
|
|
70
|
+
else if (fs_1.default.existsSync(`./test-payload.json`)) {
|
|
71
|
+
payload = require(`./test-payload.json`);
|
|
72
|
+
}
|
|
73
|
+
if (typeof payload === 'string') {
|
|
74
|
+
return JSON.parse(payload);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
return payload;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|