@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
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { Adapter } from '../../adapter'
|
|
2
|
-
import { batchEndpoint } from './batch-warming'
|
|
3
|
-
import { restEndpoint } from './rest'
|
|
4
|
-
|
|
5
|
-
export const adapter: Adapter = {
|
|
6
|
-
name: 'coingecko',
|
|
7
|
-
defaultEndpoint: 'batch',
|
|
8
|
-
endpoints: [restEndpoint, batchEndpoint],
|
|
9
|
-
}
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import { AxiosRequestConfig, AxiosResponse } from 'axios'
|
|
2
|
-
import { AdapterEndpoint } from '../../adapter'
|
|
3
|
-
import { RestTransport } from '../../transports'
|
|
4
|
-
import { AdapterRequest, AdapterResponse } from '../../util'
|
|
5
|
-
import { InputParameters } from '../../validation'
|
|
6
|
-
|
|
7
|
-
const DEFAULT_URL = 'https://api.coingecko.com/api/v3'
|
|
8
|
-
|
|
9
|
-
interface AdapterRequestParams {
|
|
10
|
-
base: string
|
|
11
|
-
quote: string
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
const inputParameters: InputParameters = {
|
|
15
|
-
coinid: {
|
|
16
|
-
description:
|
|
17
|
-
'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)',
|
|
18
|
-
required: false,
|
|
19
|
-
},
|
|
20
|
-
base: {
|
|
21
|
-
aliases: ['from', 'coin'],
|
|
22
|
-
description: 'The symbol or array of symbols of the currency to query',
|
|
23
|
-
required: true,
|
|
24
|
-
},
|
|
25
|
-
quote: {
|
|
26
|
-
aliases: ['to', 'market'],
|
|
27
|
-
description: 'The symbol of the currency to convert to',
|
|
28
|
-
required: true,
|
|
29
|
-
},
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
interface ProviderRequestBody {
|
|
33
|
-
ids: string
|
|
34
|
-
vs_currencies: string
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
interface ProviderResponseBody {
|
|
38
|
-
[base: string]: {
|
|
39
|
-
[quote: string]: number
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const restEndpointTransport = new RestTransport({
|
|
44
|
-
prepareRequest: (
|
|
45
|
-
req: AdapterRequest<AdapterRequestParams>,
|
|
46
|
-
): AxiosRequestConfig<ProviderRequestBody> => {
|
|
47
|
-
return {
|
|
48
|
-
baseURL: DEFAULT_URL,
|
|
49
|
-
url: '/simple/price',
|
|
50
|
-
method: 'GET',
|
|
51
|
-
params: {
|
|
52
|
-
ids: req.requestContext.data.base,
|
|
53
|
-
vs_currencies: req.requestContext.data.quote,
|
|
54
|
-
},
|
|
55
|
-
}
|
|
56
|
-
},
|
|
57
|
-
parseResponse: (
|
|
58
|
-
req: AdapterRequest<AdapterRequestParams>,
|
|
59
|
-
res: AxiosResponse<ProviderResponseBody>,
|
|
60
|
-
): AdapterResponse<ProviderResponseBody> => {
|
|
61
|
-
return {
|
|
62
|
-
data: res.data,
|
|
63
|
-
statusCode: 200,
|
|
64
|
-
result: res.data[req.requestContext.data.base]?.[req.requestContext.data.quote],
|
|
65
|
-
}
|
|
66
|
-
},
|
|
67
|
-
options: {
|
|
68
|
-
coalescing: true,
|
|
69
|
-
},
|
|
70
|
-
})
|
|
71
|
-
|
|
72
|
-
export const restEndpoint: AdapterEndpoint = {
|
|
73
|
-
name: 'rest',
|
|
74
|
-
aliases: ['qwe'],
|
|
75
|
-
transport: restEndpointTransport,
|
|
76
|
-
inputParameters,
|
|
77
|
-
}
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
import { RawData, WebSocket } from 'ws'
|
|
2
|
-
import { AdapterEndpoint } from '../../adapter'
|
|
3
|
-
import { AdapterContext } from '../../transports'
|
|
4
|
-
import { WebSocketTransport } from '../../transports/websocket'
|
|
5
|
-
import { ProviderResult, makeLogger } from '../../util'
|
|
6
|
-
import { InputParameters } from '../../validation'
|
|
7
|
-
import { customSettings } from './config'
|
|
8
|
-
|
|
9
|
-
interface AdapterRequestParams {
|
|
10
|
-
base: string
|
|
11
|
-
quote: string
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export const inputParameters: InputParameters = {
|
|
15
|
-
base: {
|
|
16
|
-
aliases: ['from', 'coin'],
|
|
17
|
-
description: 'The symbol of the currency to query',
|
|
18
|
-
required: true,
|
|
19
|
-
},
|
|
20
|
-
quote: {
|
|
21
|
-
aliases: ['to', 'market'],
|
|
22
|
-
description: 'The symbol of the currency to convert to',
|
|
23
|
-
required: true,
|
|
24
|
-
},
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
interface ProviderMessage {
|
|
28
|
-
timestamp: string
|
|
29
|
-
currencyPair: string
|
|
30
|
-
bid: number
|
|
31
|
-
offer: number
|
|
32
|
-
mid: number
|
|
33
|
-
changes: [
|
|
34
|
-
{
|
|
35
|
-
period: string
|
|
36
|
-
change: number
|
|
37
|
-
percentage: number
|
|
38
|
-
},
|
|
39
|
-
]
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
const logger = makeLogger('NcfxWebSocketTransport')
|
|
43
|
-
|
|
44
|
-
export const websocketTransport = new WebSocketTransport({
|
|
45
|
-
url: 'wss://feed.newchangefx.com/cryptodata',
|
|
46
|
-
handlers: {
|
|
47
|
-
open(connection: WebSocket, context: AdapterContext<typeof customSettings>) {
|
|
48
|
-
return new Promise((resolve, reject) => {
|
|
49
|
-
// Set up listener
|
|
50
|
-
connection.on('message', (data: RawData) => {
|
|
51
|
-
const parsed = JSON.parse(data.toString())
|
|
52
|
-
if (parsed.Message?.startsWith('Logged in as user')) {
|
|
53
|
-
logger.info('Got logged in response, connection is ready')
|
|
54
|
-
resolve()
|
|
55
|
-
} else {
|
|
56
|
-
reject(new Error('Unexpected message after WS connection open'))
|
|
57
|
-
}
|
|
58
|
-
})
|
|
59
|
-
// Send login payload
|
|
60
|
-
connection.send(
|
|
61
|
-
JSON.stringify({
|
|
62
|
-
request: 'login',
|
|
63
|
-
username: context.adapterConfig.USERNAME,
|
|
64
|
-
password: context.adapterConfig.PASSWORD,
|
|
65
|
-
}),
|
|
66
|
-
)
|
|
67
|
-
})
|
|
68
|
-
},
|
|
69
|
-
|
|
70
|
-
message(message: ProviderMessage[]): ProviderResult<AdapterRequestParams>[] {
|
|
71
|
-
if (!Array.isArray(message)) {
|
|
72
|
-
logger.debug('WS message is not array, skipping')
|
|
73
|
-
return []
|
|
74
|
-
}
|
|
75
|
-
return message.map((m) => {
|
|
76
|
-
const [base, quote] = m.currencyPair.split('/')
|
|
77
|
-
return {
|
|
78
|
-
params: { base, quote },
|
|
79
|
-
value: m.offer,
|
|
80
|
-
}
|
|
81
|
-
})
|
|
82
|
-
},
|
|
83
|
-
},
|
|
84
|
-
builders: {
|
|
85
|
-
subscribeMessage: (params: AdapterRequestParams) => ({
|
|
86
|
-
request: 'subscribe',
|
|
87
|
-
ccy: `${params.base}/${params.quote}`,
|
|
88
|
-
}),
|
|
89
|
-
unsubscribeMessage: (params: AdapterRequestParams) => ({
|
|
90
|
-
request: 'unsubscribe',
|
|
91
|
-
ccy: `${params.base}/${params.quote}`,
|
|
92
|
-
}),
|
|
93
|
-
},
|
|
94
|
-
})
|
|
95
|
-
|
|
96
|
-
export const webSocketEndpoint: AdapterEndpoint = {
|
|
97
|
-
name: 'websocket',
|
|
98
|
-
transport: websocketTransport,
|
|
99
|
-
inputParameters,
|
|
100
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
import fastify from 'fastify'
|
|
2
|
-
import { Server } from 'http'
|
|
3
|
-
import { AddressInfo } from 'net'
|
|
4
|
-
import { join } from 'path'
|
|
5
|
-
import { Adapter, InitializedAdapter, initializeAdapter } from './adapter'
|
|
6
|
-
import { callBackgroundExecutes } from './background-executor'
|
|
7
|
-
import { buildCacheMiddleware } from './cache'
|
|
8
|
-
import { AdapterConfig, buildAdapterConfig } from './config'
|
|
9
|
-
import { buildMetricsMiddleware, setupMetricsServer } from './metrics'
|
|
10
|
-
import { AdapterDependencies, buildTransportHandler } from './transports'
|
|
11
|
-
import { AdapterRouteGeneric, loggingContextMiddleware, makeLogger } from './util'
|
|
12
|
-
import { errorCatchingMiddleware, validatorMiddleware } from './validation'
|
|
13
|
-
|
|
14
|
-
const logger = makeLogger('Main')
|
|
15
|
-
|
|
16
|
-
const VERSION = process.env['npm_package_version']
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Main function for the framework.
|
|
20
|
-
* Initializes config and dependencies, uses those to initialize Transports, and starts listening for requests.
|
|
21
|
-
*
|
|
22
|
-
* @param adapter - an object describing an External Adapter
|
|
23
|
-
* @param dependencies - an optional object with adapter dependencies to inject
|
|
24
|
-
* @returns a Promise that resolves to the http.Server listening for connections
|
|
25
|
-
*/
|
|
26
|
-
export const expose = async (
|
|
27
|
-
adapter: Adapter,
|
|
28
|
-
dependencies?: Partial<AdapterDependencies>,
|
|
29
|
-
): Promise<Server | undefined> => {
|
|
30
|
-
const config = buildAdapterConfig({
|
|
31
|
-
overrides: adapter.envDefaultOverrides,
|
|
32
|
-
customSettings: adapter.customSettings,
|
|
33
|
-
})
|
|
34
|
-
// Initialize adapter (create dependencies, inject them, build endpoint map, etc.)
|
|
35
|
-
const initializedAdapter = await initializeAdapter(adapter, config, dependencies)
|
|
36
|
-
|
|
37
|
-
let server: Server | undefined = undefined
|
|
38
|
-
|
|
39
|
-
if (config.METRICS_ENABLED && config.EXPERIMENTAL_METRICS_ENABLED) {
|
|
40
|
-
setupMetricsServer(adapter.name, config)
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
if (config.EA_MODE === 'reader' || config.EA_MODE === 'reader-writer') {
|
|
44
|
-
// Main REST API server to handle incoming requests
|
|
45
|
-
const app = await buildRestApi(config, initializedAdapter)
|
|
46
|
-
|
|
47
|
-
// Start listening for incoming requests
|
|
48
|
-
try {
|
|
49
|
-
await app.listen(config.EA_PORT, config.EA_HOST)
|
|
50
|
-
} catch (err) {
|
|
51
|
-
logger.fatal(`There was an error when starting the EA server: ${err}`)
|
|
52
|
-
process.exit()
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
logger.info(`Listening on port ${(app.server.address() as AddressInfo).port}`)
|
|
56
|
-
server = app.server
|
|
57
|
-
} else {
|
|
58
|
-
logger.info('REST API is disabled; this instance will not process incoming requests.')
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
if (config.EA_MODE === 'writer' || config.EA_MODE === 'reader-writer') {
|
|
62
|
-
// Start background loop that will take care of calling any async Transports
|
|
63
|
-
logger.info('Starting background execution loop')
|
|
64
|
-
callBackgroundExecutes(initializedAdapter, server)
|
|
65
|
-
} else {
|
|
66
|
-
logger.info(
|
|
67
|
-
'Background executor is disabled; this instance will not perform async background executes.',
|
|
68
|
-
)
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
return server
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
async function buildRestApi(config: AdapterConfig, initializedAdapter: InitializedAdapter) {
|
|
75
|
-
const app = fastify()
|
|
76
|
-
|
|
77
|
-
// Add healthcheck endpoint before middlewares to bypass them
|
|
78
|
-
app.get(join(config.BASE_URL, 'health'), (req, res) => {
|
|
79
|
-
res.status(200).send({ message: 'OK', version: VERSION })
|
|
80
|
-
})
|
|
81
|
-
|
|
82
|
-
// Use global error handling
|
|
83
|
-
app.setErrorHandler(errorCatchingMiddleware)
|
|
84
|
-
|
|
85
|
-
const transportHandler = await buildTransportHandler(initializedAdapter)
|
|
86
|
-
|
|
87
|
-
app.register(async (router) => {
|
|
88
|
-
// Set up "middlewares" (hooks in fastify)
|
|
89
|
-
router.addHook<AdapterRouteGeneric>('preHandler', validatorMiddleware(initializedAdapter))
|
|
90
|
-
router.addHook<AdapterRouteGeneric>('preHandler', buildCacheMiddleware(initializedAdapter))
|
|
91
|
-
if (config['CORRELATION_ID_ENABLED']) {
|
|
92
|
-
router.addHook<AdapterRouteGeneric>('onRequest', loggingContextMiddleware)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
router.route<AdapterRouteGeneric>({
|
|
96
|
-
url: config.BASE_URL,
|
|
97
|
-
method: 'POST',
|
|
98
|
-
handler: transportHandler,
|
|
99
|
-
}) // Pass config maybe? cleaner that multiple instances / dependencies
|
|
100
|
-
|
|
101
|
-
if (config.METRICS_ENABLED && config.EXPERIMENTAL_METRICS_ENABLED) {
|
|
102
|
-
router.addHook<AdapterRouteGeneric>('onResponse', buildMetricsMiddleware)
|
|
103
|
-
}
|
|
104
|
-
})
|
|
105
|
-
return app
|
|
106
|
-
}
|
package/src/metrics/constants.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
export enum HttpRequestType {
|
|
2
|
-
CACHE_HIT = 'cacheHit',
|
|
3
|
-
DATA_PROVIDER_HIT = 'dataProviderHit',
|
|
4
|
-
ADAPTER_ERROR = 'adapterError',
|
|
5
|
-
INPUT_ERROR = 'inputError',
|
|
6
|
-
RATE_LIMIT_ERROR = 'rateLimitError',
|
|
7
|
-
// BURST_LIMIT_ERROR = 'burstLimitError',
|
|
8
|
-
// BACKOFF_ERROR = 'backoffError',
|
|
9
|
-
DP_ERROR = 'dataProviderError',
|
|
10
|
-
TIMEOUT_ERROR = 'timeoutError',
|
|
11
|
-
CONNECTION_ERROR = 'connectionError',
|
|
12
|
-
// RES_EMPTY_ERROR = 'responseEmptyError',
|
|
13
|
-
// RES_INVALID_ERROR = 'responseInvalidError',
|
|
14
|
-
CUSTOM_ERROR = 'customError',
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Maxiumum number of characters that a feedId can contain.
|
|
19
|
-
*/
|
|
20
|
-
export const MAX_FEED_ID_LENGTH = 300
|
|
21
|
-
|
|
22
|
-
// We should tune these as we collect data, this is the default bucket distribution that prom comes with
|
|
23
|
-
export const requestDurationBuckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
|
package/src/metrics/index.ts
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
import * as client from 'prom-client'
|
|
2
|
-
import { HttpRequestType, requestDurationBuckets } from './constants'
|
|
3
|
-
import { AdapterRequest, makeLogger } from '../util'
|
|
4
|
-
import { AdapterConfig } from '../config'
|
|
5
|
-
import fastify, { FastifyReply, HookHandlerDoneFunction } from 'fastify'
|
|
6
|
-
import { join } from 'path'
|
|
7
|
-
import { AdapterError } from '../validation/error'
|
|
8
|
-
|
|
9
|
-
const logger = makeLogger('Metrics')
|
|
10
|
-
|
|
11
|
-
export function setupMetricsServer(name: string, config: AdapterConfig) {
|
|
12
|
-
const metricsApp = fastify({
|
|
13
|
-
logger: false,
|
|
14
|
-
})
|
|
15
|
-
const metricsPort = config.METRICS_PORT
|
|
16
|
-
const endpoint = config.METRICS_USE_BASE_URL ? join(config.BASE_URL, 'metrics') : '/metrics'
|
|
17
|
-
const eaHost = config.EA_HOST
|
|
18
|
-
|
|
19
|
-
setupMetrics(name, config)
|
|
20
|
-
|
|
21
|
-
metricsApp.get(endpoint, async (_, res) => {
|
|
22
|
-
res.type('txt')
|
|
23
|
-
res.send(await client.register.metrics())
|
|
24
|
-
})
|
|
25
|
-
|
|
26
|
-
metricsApp.listen(metricsPort, eaHost, () =>
|
|
27
|
-
logger.info(`Monitoring listening on port ${metricsPort}!`),
|
|
28
|
-
)
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export const setupMetrics = (name: string, config: AdapterConfig): void => {
|
|
32
|
-
client.collectDefaultMetrics()
|
|
33
|
-
client.register.setDefaultLabels({
|
|
34
|
-
app_name: config.METRICS_NAME || name || 'N/A',
|
|
35
|
-
app_version: config['npm_package_version'],
|
|
36
|
-
})
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Builds metrics middleware that records end to end EA response times
|
|
41
|
-
* and count of requests
|
|
42
|
-
*
|
|
43
|
-
* @returns the cache middleware function
|
|
44
|
-
*/
|
|
45
|
-
export const buildMetricsMiddleware = (
|
|
46
|
-
req: AdapterRequest,
|
|
47
|
-
res: FastifyReply,
|
|
48
|
-
done: HookHandlerDoneFunction,
|
|
49
|
-
) => {
|
|
50
|
-
const feedId = req.requestContext.meta?.metrics?.feedId || 'N/A'
|
|
51
|
-
const labels = buildHttpRequestMetricsLabel(
|
|
52
|
-
feedId,
|
|
53
|
-
req.requestContext.meta?.error,
|
|
54
|
-
req.requestContext.meta?.metrics?.cacheHit,
|
|
55
|
-
)
|
|
56
|
-
|
|
57
|
-
// Record number of requests sent to EA
|
|
58
|
-
httpRequestsTotal.labels(labels).inc()
|
|
59
|
-
|
|
60
|
-
// Record response time of request through entire EA
|
|
61
|
-
httpRequestDurationSeconds.observe(res.getResponseTime())
|
|
62
|
-
logger.debug(`Response time for ${feedId}: ${res.getResponseTime()}ms`)
|
|
63
|
-
done()
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const buildHttpRequestMetricsLabel = (
|
|
67
|
-
feedId: string,
|
|
68
|
-
error?: AdapterError | Error,
|
|
69
|
-
cacheHit?: boolean,
|
|
70
|
-
): Parameters<typeof httpRequestsTotal.labels>[0] => {
|
|
71
|
-
const labels: Parameters<typeof httpRequestsTotal.labels>[0] = {}
|
|
72
|
-
labels.method = 'POST'
|
|
73
|
-
labels.feed_id = feedId
|
|
74
|
-
if (error instanceof AdapterError) {
|
|
75
|
-
// If error present and an instace of AdapterError, build label from error info
|
|
76
|
-
labels.type = error?.metricsLabel || HttpRequestType.ADAPTER_ERROR
|
|
77
|
-
labels.status_code = error?.statusCode
|
|
78
|
-
labels.provider_status_code = error?.providerStatusCode
|
|
79
|
-
} else if (error instanceof Error) {
|
|
80
|
-
// If error present and not instance of generic Error, unexpected failure occurred
|
|
81
|
-
// TODO: Build label with 500 error and withold dp status? Status sent as 200 in error handler
|
|
82
|
-
labels.type = HttpRequestType.ADAPTER_ERROR
|
|
83
|
-
labels.status_code = 500
|
|
84
|
-
} else {
|
|
85
|
-
// If no error present, request went as expected
|
|
86
|
-
labels.status_code = 200
|
|
87
|
-
if (cacheHit) {
|
|
88
|
-
labels.type = HttpRequestType.CACHE_HIT
|
|
89
|
-
} else {
|
|
90
|
-
labels.type = HttpRequestType.DATA_PROVIDER_HIT
|
|
91
|
-
labels.provider_status_code = 200
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
return labels
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export const httpRequestsTotal = new client.Counter({
|
|
99
|
-
name: 'http_requests_total',
|
|
100
|
-
help: 'The number of http requests this external adapter has serviced for its entire uptime',
|
|
101
|
-
labelNames: [
|
|
102
|
-
'method',
|
|
103
|
-
'status_code',
|
|
104
|
-
'retry',
|
|
105
|
-
'type',
|
|
106
|
-
'is_cache_warming',
|
|
107
|
-
'feed_id',
|
|
108
|
-
'provider_status_code',
|
|
109
|
-
] as const,
|
|
110
|
-
})
|
|
111
|
-
|
|
112
|
-
export const httpRequestDurationSeconds = new client.Histogram({
|
|
113
|
-
name: 'http_request_duration_seconds',
|
|
114
|
-
help: 'A histogram bucket of the distribution of http request durations',
|
|
115
|
-
buckets: requestDurationBuckets,
|
|
116
|
-
})
|
package/src/metrics/util.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { AdapterMetricsMeta, AdapterRequestData } from '../util'
|
|
2
|
-
import { AdapterEndpoint } from '../adapter'
|
|
3
|
-
import { calculateFeedId } from '../cache'
|
|
4
|
-
|
|
5
|
-
export const getMetricsMeta = (
|
|
6
|
-
endpoint: AdapterEndpoint,
|
|
7
|
-
data: AdapterRequestData,
|
|
8
|
-
): AdapterMetricsMeta => {
|
|
9
|
-
const feedId = calculateFeedId(endpoint, data)
|
|
10
|
-
return { feedId }
|
|
11
|
-
}
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { AdapterRateLimitTier, BackgroundExecuteRateLimiter, consolidateTierLimits } from '..'
|
|
2
|
-
import { AdapterEndpoint } from '../../adapter'
|
|
3
|
-
import { makeLogger } from '../../util'
|
|
4
|
-
|
|
5
|
-
const logger = makeLogger('FixedFrequencyRateLimiter')
|
|
6
|
-
export const DEFAULT_SHARED_MS_BETWEEN_REQUESTS = 5000
|
|
7
|
-
|
|
8
|
-
export class FixedFrequencyRateLimiter implements BackgroundExecuteRateLimiter {
|
|
9
|
-
msBetweenRequestsMap: {
|
|
10
|
-
[endpointName: string]: number // In ms
|
|
11
|
-
} = {}
|
|
12
|
-
|
|
13
|
-
initialize(endpoints: AdapterEndpoint[], limits?: AdapterRateLimitTier) {
|
|
14
|
-
// Translate the hourly limit into reqs per minute
|
|
15
|
-
let sharedMsBetweenRequests = 1000 / consolidateTierLimits(limits)
|
|
16
|
-
|
|
17
|
-
// If there is no limit set, we use some reasonable number
|
|
18
|
-
if (!limits?.rateLimit1h && !limits?.rateLimit1m && !limits?.rateLimit1s) {
|
|
19
|
-
// 5s period for all seems good
|
|
20
|
-
sharedMsBetweenRequests = DEFAULT_SHARED_MS_BETWEEN_REQUESTS
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
logger.debug('Using fixed frequency batch rate limiting')
|
|
24
|
-
for (const endpoint of endpoints) {
|
|
25
|
-
// TODO: See if we can remove this runtime check
|
|
26
|
-
if (endpoint.rateLimiting?.allocationPercentage == null) {
|
|
27
|
-
throw new Error(`Allocation percentage for endpoint "${endpoint.name}" is null`)
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// TODO: Implement different strategy where this is not fixed, but rather divided based on whether all warmers are active
|
|
31
|
-
this.msBetweenRequestsMap[endpoint.name] =
|
|
32
|
-
(sharedMsBetweenRequests / endpoint.rateLimiting?.allocationPercentage) * 100
|
|
33
|
-
|
|
34
|
-
logger.debug(
|
|
35
|
-
`Endpoint [${endpoint.name}]: ${
|
|
36
|
-
this.msBetweenRequestsMap[endpoint.name] / 1000
|
|
37
|
-
}s between requests`,
|
|
38
|
-
)
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
return this
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
msUntilNextExecution(endpointName: string): number {
|
|
45
|
-
return this.msBetweenRequestsMap[endpointName]
|
|
46
|
-
}
|
|
47
|
-
}
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
import { AdapterEndpoint } from '../adapter'
|
|
2
|
-
|
|
3
|
-
export * from './request/simple-counting'
|
|
4
|
-
export * from './background/fixed-frequency'
|
|
5
|
-
|
|
6
|
-
export interface AdapterRateLimitTier {
|
|
7
|
-
rateLimit1s?: number
|
|
8
|
-
rateLimit1m?: number
|
|
9
|
-
rateLimit1h?: number
|
|
10
|
-
note?: string
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Common interface for all RateLimiter classes to implement
|
|
15
|
-
*/
|
|
16
|
-
export interface RateLimiter {
|
|
17
|
-
/**
|
|
18
|
-
* Method to ensure all RateLimiters can be initialized in the same manner.
|
|
19
|
-
*
|
|
20
|
-
* @param limits - settings for how much throughput to allow for the Adapter
|
|
21
|
-
* @param endpoints - list of adapter endpoints
|
|
22
|
-
*/
|
|
23
|
-
initialize(endpoints: AdapterEndpoint[], limits: AdapterRateLimitTier): this
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* RequestRateLimiters perform checks agains imminent outbound requests for any transport.
|
|
28
|
-
*/
|
|
29
|
-
export interface RequestRateLimiter extends RateLimiter {
|
|
30
|
-
/**
|
|
31
|
-
* This method will check using whatever strategy is implemented to determine if
|
|
32
|
-
* this request can be processed. If so, it returns true; if not, returns false.
|
|
33
|
-
*/
|
|
34
|
-
isUnderLimits(): boolean
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* BackgroundExecuteFrequencyRateLimiters will implement custom logic to calculate
|
|
39
|
-
* the period of time to wait between background executions for a transport.
|
|
40
|
-
*/
|
|
41
|
-
export interface BackgroundExecuteRateLimiter extends RateLimiter {
|
|
42
|
-
msUntilNextExecution(endpointName: string): number
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* This method will convert all possible settings for a rate limit tier and
|
|
47
|
-
* convert them all to requests per second, returning the lowest one
|
|
48
|
-
*
|
|
49
|
-
* @param limits - the rate limit tier set for the adapter
|
|
50
|
-
* @returns the most restrictive of the set options, in requests per second
|
|
51
|
-
*/
|
|
52
|
-
export const consolidateTierLimits = (limits?: AdapterRateLimitTier) => {
|
|
53
|
-
const perHourLimit = (limits?.rateLimit1h || Infinity) / (60 * 60)
|
|
54
|
-
const perMinuteLimit = (limits?.rateLimit1m || Infinity) / 60
|
|
55
|
-
const perSecondLimit = limits?.rateLimit1s || Infinity
|
|
56
|
-
return Math.min(perHourLimit, perMinuteLimit, perSecondLimit)
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Validates rate limiting tiers specified for the adapter, and returns the one to use.
|
|
61
|
-
*
|
|
62
|
-
* @param tiers - the adapter config listing the different available API tiers
|
|
63
|
-
* @param selectedTier - chosen API tier from settings, if present
|
|
64
|
-
* @returns the specified API tier, or a default one if none are specified
|
|
65
|
-
*/
|
|
66
|
-
export const getRateLimitingTier = (
|
|
67
|
-
tiers?: Record<string, AdapterRateLimitTier>,
|
|
68
|
-
selectedTier?: string,
|
|
69
|
-
): AdapterRateLimitTier | undefined => {
|
|
70
|
-
if (!tiers) {
|
|
71
|
-
return
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// Check that if the tiers object is defined, it has values
|
|
75
|
-
if (Object.values(tiers).length === 0) {
|
|
76
|
-
throw new Error(`The tiers object is defined, but has no entries`)
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// Check that the tier set in the AdapterConfig is a valid one
|
|
80
|
-
if (selectedTier && !tiers[selectedTier]) {
|
|
81
|
-
const validTiersString = Object.keys(tiers)
|
|
82
|
-
.map((t) => `"${t}"`)
|
|
83
|
-
.join(', ')
|
|
84
|
-
|
|
85
|
-
throw new Error(
|
|
86
|
-
`The selected rate limit tier "${selectedTier}" is not valid (can be one of ${validTiersString})`,
|
|
87
|
-
)
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
if (!selectedTier) {
|
|
91
|
-
// Sort the tiers by most to least restrictive
|
|
92
|
-
const sortedTiers = Object.values(tiers).sort(
|
|
93
|
-
(t1, t2) => consolidateTierLimits(t1) - consolidateTierLimits(t2),
|
|
94
|
-
)
|
|
95
|
-
|
|
96
|
-
return sortedTiers[0]
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
return tiers[selectedTier]
|
|
100
|
-
}
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import * as client from 'prom-client'
|
|
2
|
-
|
|
3
|
-
// Retrieve cost field from response if exists
|
|
4
|
-
// If not return default cost of 1
|
|
5
|
-
export const retrieveCost = <ProviderResponseBody>(data: ProviderResponseBody): number => {
|
|
6
|
-
const cost = (data as Record<string, unknown>)['cost']
|
|
7
|
-
if (typeof cost === 'number' || typeof cost === 'string') {
|
|
8
|
-
return Number(cost)
|
|
9
|
-
} else {
|
|
10
|
-
return 1
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export const rateLimitCreditsSpentTotal = new client.Counter({
|
|
15
|
-
name: 'rate_limit_credits_spent_total',
|
|
16
|
-
help: 'The number of data provider credits the adapter is consuming',
|
|
17
|
-
labelNames: ['participant_id', 'feed_id'] as const,
|
|
18
|
-
})
|