@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,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.generateJWT = void 0;
|
|
7
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
8
|
+
const axios_1 = __importDefault(require("axios"));
|
|
9
|
+
const util_1 = require("../../util");
|
|
10
|
+
const logger = (0, util_1.makeLogger)('BankFrickUtil');
|
|
11
|
+
// Used by all endpoints requiring authentication
|
|
12
|
+
const generateJWT = async (config, signingAlgorithm = 'rsa-sha512') => {
|
|
13
|
+
logger.info("Generating a new JWT because we don't have one in config.token");
|
|
14
|
+
const { API_KEY, PRIVATE_KEY, API_ENDPOINT } = config;
|
|
15
|
+
// All of these are required, so validation should have failed prior to this line
|
|
16
|
+
if (!API_KEY || !PRIVATE_KEY) {
|
|
17
|
+
throw new Error('API_KEY, PRIVATE_KEY, and PASSWORD all must be defined to get a new token\n' +
|
|
18
|
+
'Received: \n' +
|
|
19
|
+
`API_KEY: ${API_KEY}\n` +
|
|
20
|
+
`PRIVATE_KEY: ${PRIVATE_KEY}`);
|
|
21
|
+
}
|
|
22
|
+
const data = {
|
|
23
|
+
key: API_KEY,
|
|
24
|
+
};
|
|
25
|
+
const signature = crypto_1.default.sign(signingAlgorithm, Buffer.from(JSON.stringify(data)), PRIVATE_KEY);
|
|
26
|
+
const options = {
|
|
27
|
+
method: 'POST',
|
|
28
|
+
baseURL: API_ENDPOINT,
|
|
29
|
+
url: `authorize`,
|
|
30
|
+
headers: {
|
|
31
|
+
Signature: signature.toString('base64'),
|
|
32
|
+
algorithm: signingAlgorithm,
|
|
33
|
+
},
|
|
34
|
+
data,
|
|
35
|
+
};
|
|
36
|
+
const response = await axios_1.default.request(options);
|
|
37
|
+
return response.data.token;
|
|
38
|
+
};
|
|
39
|
+
exports.generateJWT = generateJWT;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.batchEndpoint = void 0;
|
|
4
|
+
const batch_warming_1 = require("../../transports/batch-warming");
|
|
5
|
+
const DEFAULT_URL = 'https://pro-api.coingecko.com/api/v3';
|
|
6
|
+
const inputParameters = {
|
|
7
|
+
coinid: {
|
|
8
|
+
description: 'The CoinGecko id or array of ids of the coin(s) to query (Note: because of current limitations to use a dummy base will need to be supplied)',
|
|
9
|
+
required: false,
|
|
10
|
+
},
|
|
11
|
+
base: {
|
|
12
|
+
aliases: ['from', 'coin'],
|
|
13
|
+
description: 'The symbol or array of symbols of the currency to query',
|
|
14
|
+
required: true,
|
|
15
|
+
},
|
|
16
|
+
quote: {
|
|
17
|
+
aliases: ['to', 'market'],
|
|
18
|
+
description: 'The symbol of the currency to convert to',
|
|
19
|
+
required: true,
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
const batchEndpointTransport = new batch_warming_1.BatchWarmingTransport({
|
|
23
|
+
prepareRequest: (params, context) => {
|
|
24
|
+
return {
|
|
25
|
+
baseURL: DEFAULT_URL,
|
|
26
|
+
url: '/simple/price',
|
|
27
|
+
method: 'GET',
|
|
28
|
+
params: {
|
|
29
|
+
ids: [...new Set(params.map((p) => p.base))].join(','),
|
|
30
|
+
vs_currencies: [...new Set(params.map((p) => p.quote))].join(','),
|
|
31
|
+
x_cg_pro_api_key: context.adapterConfig.API_KEY,
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
},
|
|
35
|
+
parseResponse: (res) => {
|
|
36
|
+
const entries = [];
|
|
37
|
+
for (const [base, entry] of Object.entries(res.data)) {
|
|
38
|
+
for (const [quote, price] of Object.entries(entry)) {
|
|
39
|
+
entries.push({
|
|
40
|
+
params: { base, quote },
|
|
41
|
+
value: price,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return entries;
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
exports.batchEndpoint = {
|
|
49
|
+
name: 'batch',
|
|
50
|
+
transport: batchEndpointTransport,
|
|
51
|
+
inputParameters,
|
|
52
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.adapter = void 0;
|
|
4
|
+
const batch_warming_1 = require("./batch-warming");
|
|
5
|
+
const rest_1 = require("./rest");
|
|
6
|
+
exports.adapter = {
|
|
7
|
+
name: 'coingecko',
|
|
8
|
+
defaultEndpoint: 'batch',
|
|
9
|
+
endpoints: [rest_1.restEndpoint, batch_warming_1.batchEndpoint],
|
|
10
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.restEndpoint = void 0;
|
|
4
|
+
const transports_1 = require("../../transports");
|
|
5
|
+
const DEFAULT_URL = 'https://api.coingecko.com/api/v3';
|
|
6
|
+
const inputParameters = {
|
|
7
|
+
coinid: {
|
|
8
|
+
description: 'The CoinGecko id or array of ids of the coin(s) to query (Note: because of current limitations to use a dummy base will need to be supplied)',
|
|
9
|
+
required: false,
|
|
10
|
+
},
|
|
11
|
+
base: {
|
|
12
|
+
aliases: ['from', 'coin'],
|
|
13
|
+
description: 'The symbol or array of symbols of the currency to query',
|
|
14
|
+
required: true,
|
|
15
|
+
},
|
|
16
|
+
quote: {
|
|
17
|
+
aliases: ['to', 'market'],
|
|
18
|
+
description: 'The symbol of the currency to convert to',
|
|
19
|
+
required: true,
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
const restEndpointTransport = new transports_1.RestTransport({
|
|
23
|
+
prepareRequest: (req) => {
|
|
24
|
+
return {
|
|
25
|
+
baseURL: DEFAULT_URL,
|
|
26
|
+
url: '/simple/price',
|
|
27
|
+
method: 'GET',
|
|
28
|
+
params: {
|
|
29
|
+
ids: req.requestContext.data.base,
|
|
30
|
+
vs_currencies: req.requestContext.data.quote,
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
},
|
|
34
|
+
parseResponse: (req, res) => {
|
|
35
|
+
return {
|
|
36
|
+
data: res.data,
|
|
37
|
+
statusCode: 200,
|
|
38
|
+
result: res.data[req.requestContext.data.base]?.[req.requestContext.data.quote],
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
options: {
|
|
42
|
+
coalescing: true,
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
exports.restEndpoint = {
|
|
46
|
+
name: 'rest',
|
|
47
|
+
aliases: ['qwe'],
|
|
48
|
+
transport: restEndpointTransport,
|
|
49
|
+
inputParameters,
|
|
50
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.customSettings = void 0;
|
|
4
|
+
exports.customSettings = {
|
|
5
|
+
USERNAME: {
|
|
6
|
+
description: 'Username for the NCFX API',
|
|
7
|
+
type: 'string',
|
|
8
|
+
required: true,
|
|
9
|
+
},
|
|
10
|
+
PASSWORD: {
|
|
11
|
+
description: 'Password for the NCFX API',
|
|
12
|
+
type: 'string',
|
|
13
|
+
required: true,
|
|
14
|
+
},
|
|
15
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.adapter = void 0;
|
|
4
|
+
const config_1 = require("./config");
|
|
5
|
+
const websocket_1 = require("./websocket");
|
|
6
|
+
exports.adapter = {
|
|
7
|
+
name: 'ncfx',
|
|
8
|
+
endpoints: [websocket_1.webSocketEndpoint],
|
|
9
|
+
customSettings: config_1.customSettings,
|
|
10
|
+
};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.webSocketEndpoint = exports.websocketTransport = exports.inputParameters = void 0;
|
|
4
|
+
const websocket_1 = require("../../transports/websocket");
|
|
5
|
+
const util_1 = require("../../util");
|
|
6
|
+
exports.inputParameters = {
|
|
7
|
+
base: {
|
|
8
|
+
aliases: ['from', 'coin'],
|
|
9
|
+
description: 'The symbol of the currency to query',
|
|
10
|
+
required: true,
|
|
11
|
+
},
|
|
12
|
+
quote: {
|
|
13
|
+
aliases: ['to', 'market'],
|
|
14
|
+
description: 'The symbol of the currency to convert to',
|
|
15
|
+
required: true,
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
const logger = (0, util_1.makeLogger)('NcfxWebSocketTransport');
|
|
19
|
+
exports.websocketTransport = new websocket_1.WebSocketTransport({
|
|
20
|
+
url: 'wss://feed.newchangefx.com/cryptodata',
|
|
21
|
+
handlers: {
|
|
22
|
+
open(connection, context) {
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
// Set up listener
|
|
25
|
+
connection.on('message', (data) => {
|
|
26
|
+
const parsed = JSON.parse(data.toString());
|
|
27
|
+
if (parsed.Message?.startsWith('Logged in as user')) {
|
|
28
|
+
logger.info('Got logged in response, connection is ready');
|
|
29
|
+
resolve();
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
reject(new Error('Unexpected message after WS connection open'));
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
// Send login payload
|
|
36
|
+
connection.send(JSON.stringify({
|
|
37
|
+
request: 'login',
|
|
38
|
+
username: context.adapterConfig.USERNAME,
|
|
39
|
+
password: context.adapterConfig.PASSWORD,
|
|
40
|
+
}));
|
|
41
|
+
});
|
|
42
|
+
},
|
|
43
|
+
message(message) {
|
|
44
|
+
if (!Array.isArray(message)) {
|
|
45
|
+
logger.debug('WS message is not array, skipping');
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
return message.map((m) => {
|
|
49
|
+
const [base, quote] = m.currencyPair.split('/');
|
|
50
|
+
return {
|
|
51
|
+
params: { base, quote },
|
|
52
|
+
value: m.offer,
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
builders: {
|
|
58
|
+
subscribeMessage: (params) => ({
|
|
59
|
+
request: 'subscribe',
|
|
60
|
+
ccy: `${params.base}/${params.quote}`,
|
|
61
|
+
}),
|
|
62
|
+
unsubscribeMessage: (params) => ({
|
|
63
|
+
request: 'unsubscribe',
|
|
64
|
+
ccy: `${params.base}/${params.quote}`,
|
|
65
|
+
}),
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
exports.webSocketEndpoint = {
|
|
69
|
+
name: 'websocket',
|
|
70
|
+
transport: exports.websocketTransport,
|
|
71
|
+
inputParameters: exports.inputParameters,
|
|
72
|
+
};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.expose = void 0;
|
|
7
|
+
const fastify_1 = __importDefault(require("fastify"));
|
|
8
|
+
const path_1 = require("path");
|
|
9
|
+
const adapter_1 = require("./adapter");
|
|
10
|
+
const background_executor_1 = require("./background-executor");
|
|
11
|
+
const cache_1 = require("./cache");
|
|
12
|
+
const config_1 = require("./config");
|
|
13
|
+
const metrics_1 = require("./metrics");
|
|
14
|
+
const transports_1 = require("./transports");
|
|
15
|
+
const util_1 = require("./util");
|
|
16
|
+
const validation_1 = require("./validation");
|
|
17
|
+
const logger = (0, util_1.makeLogger)('Main');
|
|
18
|
+
const VERSION = process.env['npm_package_version'];
|
|
19
|
+
/**
|
|
20
|
+
* Main function for the framework.
|
|
21
|
+
* Initializes config and dependencies, uses those to initialize Transports, and starts listening for requests.
|
|
22
|
+
*
|
|
23
|
+
* @param adapter - an object describing an External Adapter
|
|
24
|
+
* @param dependencies - an optional object with adapter dependencies to inject
|
|
25
|
+
* @returns a Promise that resolves to the http.Server listening for connections
|
|
26
|
+
*/
|
|
27
|
+
const expose = async (adapter, dependencies) => {
|
|
28
|
+
const config = (0, config_1.buildAdapterConfig)({
|
|
29
|
+
overrides: adapter.envDefaultOverrides,
|
|
30
|
+
customSettings: adapter.customSettings,
|
|
31
|
+
});
|
|
32
|
+
// Initialize adapter (create dependencies, inject them, build endpoint map, etc.)
|
|
33
|
+
const initializedAdapter = await (0, adapter_1.initializeAdapter)(adapter, config, dependencies);
|
|
34
|
+
let server = undefined;
|
|
35
|
+
if (config.METRICS_ENABLED && config.EXPERIMENTAL_METRICS_ENABLED) {
|
|
36
|
+
(0, metrics_1.setupMetricsServer)(adapter.name, config);
|
|
37
|
+
}
|
|
38
|
+
if (config.EA_MODE === 'reader' || config.EA_MODE === 'reader-writer') {
|
|
39
|
+
// Main REST API server to handle incoming requests
|
|
40
|
+
const app = await buildRestApi(config, initializedAdapter);
|
|
41
|
+
// Start listening for incoming requests
|
|
42
|
+
try {
|
|
43
|
+
await app.listen(config.EA_PORT, config.EA_HOST);
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
logger.fatal(`There was an error when starting the EA server: ${err}`);
|
|
47
|
+
process.exit();
|
|
48
|
+
}
|
|
49
|
+
logger.info(`Listening on port ${app.server.address().port}`);
|
|
50
|
+
server = app.server;
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
logger.info('REST API is disabled; this instance will not process incoming requests.');
|
|
54
|
+
}
|
|
55
|
+
if (config.EA_MODE === 'writer' || config.EA_MODE === 'reader-writer') {
|
|
56
|
+
// Start background loop that will take care of calling any async Transports
|
|
57
|
+
logger.info('Starting background execution loop');
|
|
58
|
+
(0, background_executor_1.callBackgroundExecutes)(initializedAdapter, server);
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
logger.info('Background executor is disabled; this instance will not perform async background executes.');
|
|
62
|
+
}
|
|
63
|
+
return server;
|
|
64
|
+
};
|
|
65
|
+
exports.expose = expose;
|
|
66
|
+
async function buildRestApi(config, initializedAdapter) {
|
|
67
|
+
const app = (0, fastify_1.default)();
|
|
68
|
+
// Add healthcheck endpoint before middlewares to bypass them
|
|
69
|
+
app.get((0, path_1.join)(config.BASE_URL, 'health'), (req, res) => {
|
|
70
|
+
res.status(200).send({ message: 'OK', version: VERSION });
|
|
71
|
+
});
|
|
72
|
+
// Use global error handling
|
|
73
|
+
app.setErrorHandler(validation_1.errorCatchingMiddleware);
|
|
74
|
+
const transportHandler = await (0, transports_1.buildTransportHandler)(initializedAdapter);
|
|
75
|
+
app.register(async (router) => {
|
|
76
|
+
// Set up "middlewares" (hooks in fastify)
|
|
77
|
+
router.addHook('preHandler', (0, validation_1.validatorMiddleware)(initializedAdapter));
|
|
78
|
+
router.addHook('preHandler', (0, cache_1.buildCacheMiddleware)(initializedAdapter));
|
|
79
|
+
if (config['CORRELATION_ID_ENABLED']) {
|
|
80
|
+
router.addHook('onRequest', util_1.loggingContextMiddleware);
|
|
81
|
+
}
|
|
82
|
+
router.route({
|
|
83
|
+
url: config.BASE_URL,
|
|
84
|
+
method: 'POST',
|
|
85
|
+
handler: transportHandler,
|
|
86
|
+
}); // Pass config maybe? cleaner that multiple instances / dependencies
|
|
87
|
+
});
|
|
88
|
+
return app;
|
|
89
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.requestDurationBuckets = exports.MAX_FEED_ID_LENGTH = exports.HttpRequestType = void 0;
|
|
4
|
+
var HttpRequestType;
|
|
5
|
+
(function (HttpRequestType) {
|
|
6
|
+
HttpRequestType["CACHE_HIT"] = "cacheHit";
|
|
7
|
+
HttpRequestType["DATA_PROVIDER_HIT"] = "dataProviderHit";
|
|
8
|
+
HttpRequestType["ADAPTER_ERROR"] = "adapterError";
|
|
9
|
+
HttpRequestType["INPUT_ERROR"] = "inputError";
|
|
10
|
+
HttpRequestType["RATE_LIMIT_ERROR"] = "rateLimitError";
|
|
11
|
+
// BURST_LIMIT_ERROR = 'burstLimitError',
|
|
12
|
+
// BACKOFF_ERROR = 'backoffError',
|
|
13
|
+
HttpRequestType["DP_ERROR"] = "dataProviderError";
|
|
14
|
+
HttpRequestType["TIMEOUT_ERROR"] = "timeoutError";
|
|
15
|
+
// CONNECTION_ERROR = 'connectionError',
|
|
16
|
+
// RES_EMPTY_ERROR = 'responseEmptyError',
|
|
17
|
+
// RES_INVALID_ERROR = 'responseInvalidError',
|
|
18
|
+
HttpRequestType["CUSTOM_ERROR"] = "customError";
|
|
19
|
+
})(HttpRequestType = exports.HttpRequestType || (exports.HttpRequestType = {}));
|
|
20
|
+
/**
|
|
21
|
+
* Maxiumum number of characters that a feedId can contain.
|
|
22
|
+
*/
|
|
23
|
+
exports.MAX_FEED_ID_LENGTH = 300;
|
|
24
|
+
// We should tune these as we collect data, this is the default bucket distribution that prom comes with
|
|
25
|
+
exports.requestDurationBuckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
+
};
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.httpRequestDurationSeconds = exports.httpRequestsTotal = exports.setupMetrics = exports.setupMetricsServer = void 0;
|
|
30
|
+
const client = __importStar(require("prom-client"));
|
|
31
|
+
const constants_1 = require("./constants");
|
|
32
|
+
const util_1 = require("../util");
|
|
33
|
+
const fastify_1 = __importDefault(require("fastify"));
|
|
34
|
+
const path_1 = require("path");
|
|
35
|
+
const logger = (0, util_1.makeLogger)('Metrics');
|
|
36
|
+
function setupMetricsServer(name, config) {
|
|
37
|
+
const metricsApp = (0, fastify_1.default)({
|
|
38
|
+
logger: false,
|
|
39
|
+
});
|
|
40
|
+
const metricsPort = config.METRICS_PORT;
|
|
41
|
+
const endpoint = config.METRICS_USE_BASE_URL ? (0, path_1.join)(config.BASE_URL, 'metrics') : '/metrics';
|
|
42
|
+
const eaHost = config.EA_HOST;
|
|
43
|
+
(0, exports.setupMetrics)(name, config);
|
|
44
|
+
metricsApp.get(endpoint, async (_, res) => {
|
|
45
|
+
res.type('txt');
|
|
46
|
+
res.send(await client.register.metrics());
|
|
47
|
+
});
|
|
48
|
+
metricsApp.listen(metricsPort, eaHost, () => logger.info(`Monitoring listening on port ${metricsPort}!`));
|
|
49
|
+
}
|
|
50
|
+
exports.setupMetricsServer = setupMetricsServer;
|
|
51
|
+
const setupMetrics = (name, config) => {
|
|
52
|
+
client.collectDefaultMetrics();
|
|
53
|
+
client.register.setDefaultLabels({
|
|
54
|
+
app_name: config.METRICS_NAME || name || 'N/A',
|
|
55
|
+
app_version: config['npm_package_version'],
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
exports.setupMetrics = setupMetrics;
|
|
59
|
+
exports.httpRequestsTotal = new client.Counter({
|
|
60
|
+
name: 'http_requests_total',
|
|
61
|
+
help: 'The number of http requests this external adapter has serviced for its entire uptime',
|
|
62
|
+
labelNames: [
|
|
63
|
+
'method',
|
|
64
|
+
'status_code',
|
|
65
|
+
'retry',
|
|
66
|
+
'type',
|
|
67
|
+
'is_cache_warming',
|
|
68
|
+
'feed_id',
|
|
69
|
+
'provider_status_code',
|
|
70
|
+
],
|
|
71
|
+
});
|
|
72
|
+
exports.httpRequestDurationSeconds = new client.Histogram({
|
|
73
|
+
name: 'http_request_duration_seconds',
|
|
74
|
+
help: 'A histogram bucket of the distribution of http request durations',
|
|
75
|
+
buckets: constants_1.requestDurationBuckets,
|
|
76
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getMetricsMeta = void 0;
|
|
4
|
+
const cache_1 = require("../cache");
|
|
5
|
+
const getMetricsMeta = (endpoint, data) => {
|
|
6
|
+
const feedId = (0, cache_1.calculateFeedId)(endpoint, data);
|
|
7
|
+
return { feedId };
|
|
8
|
+
};
|
|
9
|
+
exports.getMetricsMeta = getMetricsMeta;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FixedFrequencyRateLimiter = exports.DEFAULT_SHARED_MS_BETWEEN_REQUESTS = void 0;
|
|
4
|
+
const __1 = require("..");
|
|
5
|
+
const util_1 = require("../../util");
|
|
6
|
+
const logger = (0, util_1.makeLogger)('FixedFrequencyRateLimiter');
|
|
7
|
+
exports.DEFAULT_SHARED_MS_BETWEEN_REQUESTS = 5000;
|
|
8
|
+
class FixedFrequencyRateLimiter {
|
|
9
|
+
constructor() {
|
|
10
|
+
this.msBetweenRequestsMap = {};
|
|
11
|
+
}
|
|
12
|
+
initialize(endpoints, limits) {
|
|
13
|
+
// Translate the hourly limit into reqs per minute
|
|
14
|
+
let sharedMsBetweenRequests = 1000 / (0, __1.consolidateTierLimits)(limits);
|
|
15
|
+
// If there is no limit set, we use some reasonable number
|
|
16
|
+
if (!limits?.rateLimit1h && !limits?.rateLimit1m && !limits?.rateLimit1s) {
|
|
17
|
+
// 5s period for all seems good
|
|
18
|
+
sharedMsBetweenRequests = exports.DEFAULT_SHARED_MS_BETWEEN_REQUESTS;
|
|
19
|
+
}
|
|
20
|
+
logger.debug('Using fixed frequency batch rate limiting');
|
|
21
|
+
for (const endpoint of endpoints) {
|
|
22
|
+
// TODO: See if we can remove this runtime check
|
|
23
|
+
if (endpoint.rateLimiting?.allocationPercentage == null) {
|
|
24
|
+
throw new Error(`Allocation percentage for endpoint "${endpoint.name}" is null`);
|
|
25
|
+
}
|
|
26
|
+
// TODO: Implement different strategy where this is not fixed, but rather divided based on whether all warmers are active
|
|
27
|
+
this.msBetweenRequestsMap[endpoint.name] =
|
|
28
|
+
(sharedMsBetweenRequests / endpoint.rateLimiting?.allocationPercentage) * 100;
|
|
29
|
+
logger.debug(`Endpoint [${endpoint.name}]: ${this.msBetweenRequestsMap[endpoint.name] / 1000}s between requests`);
|
|
30
|
+
}
|
|
31
|
+
return this;
|
|
32
|
+
}
|
|
33
|
+
msUntilNextExecution(endpointName) {
|
|
34
|
+
return this.msBetweenRequestsMap[endpointName];
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
exports.FixedFrequencyRateLimiter = FixedFrequencyRateLimiter;
|
|
@@ -0,0 +1,63 @@
|
|
|
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.getRateLimitingTier = exports.consolidateTierLimits = void 0;
|
|
18
|
+
__exportStar(require("./request/simple-counting"), exports);
|
|
19
|
+
__exportStar(require("./background/fixed-frequency"), exports);
|
|
20
|
+
/**
|
|
21
|
+
* This method will convert all possible settings for a rate limit tier and
|
|
22
|
+
* convert them all to requests per second, returning the lowest one
|
|
23
|
+
*
|
|
24
|
+
* @param limits - the rate limit tier set for the adapter
|
|
25
|
+
* @returns the most restrictive of the set options, in requests per second
|
|
26
|
+
*/
|
|
27
|
+
const consolidateTierLimits = (limits) => {
|
|
28
|
+
const perHourLimit = (limits?.rateLimit1h || Infinity) / (60 * 60);
|
|
29
|
+
const perMinuteLimit = (limits?.rateLimit1m || Infinity) / 60;
|
|
30
|
+
const perSecondLimit = limits?.rateLimit1s || Infinity;
|
|
31
|
+
return Math.min(perHourLimit, perMinuteLimit, perSecondLimit);
|
|
32
|
+
};
|
|
33
|
+
exports.consolidateTierLimits = consolidateTierLimits;
|
|
34
|
+
/**
|
|
35
|
+
* Validates rate limiting tiers specified for the adapter, and returns the one to use.
|
|
36
|
+
*
|
|
37
|
+
* @param tiers - the adapter config listing the different available API tiers
|
|
38
|
+
* @param selectedTier - chosen API tier from settings, if present
|
|
39
|
+
* @returns the specified API tier, or a default one if none are specified
|
|
40
|
+
*/
|
|
41
|
+
const getRateLimitingTier = (tiers, selectedTier) => {
|
|
42
|
+
if (!tiers) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
// Check that if the tiers object is defined, it has values
|
|
46
|
+
if (Object.values(tiers).length === 0) {
|
|
47
|
+
throw new Error(`The tiers object is defined, but has no entries`);
|
|
48
|
+
}
|
|
49
|
+
// Check that the tier set in the AdapterConfig is a valid one
|
|
50
|
+
if (selectedTier && !tiers[selectedTier]) {
|
|
51
|
+
const validTiersString = Object.keys(tiers)
|
|
52
|
+
.map((t) => `"${t}"`)
|
|
53
|
+
.join(', ');
|
|
54
|
+
throw new Error(`The selected rate limit tier "${selectedTier}" is not valid (can be one of ${validTiersString})`);
|
|
55
|
+
}
|
|
56
|
+
if (!selectedTier) {
|
|
57
|
+
// Sort the tiers by most to least restrictive
|
|
58
|
+
const sortedTiers = Object.values(tiers).sort((t1, t2) => (0, exports.consolidateTierLimits)(t1) - (0, exports.consolidateTierLimits)(t2));
|
|
59
|
+
return sortedTiers[0];
|
|
60
|
+
}
|
|
61
|
+
return tiers[selectedTier];
|
|
62
|
+
};
|
|
63
|
+
exports.getRateLimitingTier = getRateLimitingTier;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.rateLimitCreditsSpentTotal = void 0;
|
|
27
|
+
const client = __importStar(require("prom-client"));
|
|
28
|
+
exports.rateLimitCreditsSpentTotal = new client.Counter({
|
|
29
|
+
name: 'rate_limit_credits_spent_total',
|
|
30
|
+
help: 'The number of data provider credits the adapter is consuming',
|
|
31
|
+
labelNames: ['participant_id', 'feed_id', 'experimental'],
|
|
32
|
+
});
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SimpleCountingRateLimiter = void 0;
|
|
4
|
+
const util_1 = require("../../util");
|
|
5
|
+
const logger = (0, util_1.makeLogger)('SimpleCountingRateLimiter');
|
|
6
|
+
/**
|
|
7
|
+
* This rate limiter is the simplest stateful option.
|
|
8
|
+
* On startup, it'll compare the different thresholds for each tier, calculate them all
|
|
9
|
+
* in the finest window we'll use (seconds), and use the most restrictive one.
|
|
10
|
+
* This is so if the EA were to restart, we don't need to worry about persisting state
|
|
11
|
+
* for things like daily quotas. The downside is that this does not work well for bursty
|
|
12
|
+
* loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
|
|
13
|
+
*/
|
|
14
|
+
class SimpleCountingRateLimiter {
|
|
15
|
+
constructor() {
|
|
16
|
+
this.latestSecondInterval = 0;
|
|
17
|
+
this.requestsThisSecond = 0;
|
|
18
|
+
this.latestMinuteInterval = 0;
|
|
19
|
+
this.requestsThisMinute = 0;
|
|
20
|
+
}
|
|
21
|
+
initialize(endpoints, limits) {
|
|
22
|
+
// Translate the hourly limit into reqs per minute
|
|
23
|
+
const perHourLimit = (limits?.rateLimit1h || Infinity) / 60;
|
|
24
|
+
this.perMinuteLimit = Math.min(limits?.rateLimit1m || Infinity, perHourLimit);
|
|
25
|
+
this.perSecondLimit = limits?.rateLimit1s || Infinity;
|
|
26
|
+
logger.debug(`Using rate limiting settings: perMinute = ${this.perMinuteLimit} | perSecond: = ${this.perSecondLimit}`);
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
isUnderLimits() {
|
|
30
|
+
// If the limit is set to infinity, there was no tier limit specified
|
|
31
|
+
if (this.perSecondLimit === Infinity && this.perMinuteLimit === Infinity) {
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const nearestSecondInterval = Math.floor(now / 1000);
|
|
36
|
+
const nearestMinuteInterval = Math.floor(now / (1000 * 60));
|
|
37
|
+
// This should always run to completion, even if it doesn't look atomic; therefore the
|
|
38
|
+
// Ops should be "thread safe". Thank JS and its infinite single threaded dumbness.
|
|
39
|
+
if (nearestSecondInterval !== this.latestSecondInterval) {
|
|
40
|
+
logger.trace(`Clearing latest second interval, # of requests logged was: ${this.requestsThisSecond} `);
|
|
41
|
+
this.latestSecondInterval = nearestSecondInterval;
|
|
42
|
+
this.requestsThisSecond = 0;
|
|
43
|
+
}
|
|
44
|
+
if (nearestMinuteInterval !== this.latestMinuteInterval) {
|
|
45
|
+
logger.trace(`Clearing latest second minute, # of requests logged was: ${this.requestsThisMinute} `);
|
|
46
|
+
this.latestMinuteInterval = nearestMinuteInterval;
|
|
47
|
+
this.requestsThisMinute = 0;
|
|
48
|
+
}
|
|
49
|
+
if (this.requestsThisSecond < this.perSecondLimit &&
|
|
50
|
+
this.requestsThisMinute < this.perMinuteLimit) {
|
|
51
|
+
logger.trace('Request under limits, counting +1');
|
|
52
|
+
this.requestsThisSecond++;
|
|
53
|
+
this.requestsThisMinute++;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
logger.trace('Requests seen this interval are above limits');
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
exports.SimpleCountingRateLimiter = SimpleCountingRateLimiter;
|