@chainlink/external-adapter-framework 0.0.6 → 0.0.8
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/adapter.d.ts +88 -0
- package/adapter.js +112 -0
- package/background-executor.d.ts +11 -0
- package/background-executor.js +45 -0
- package/cache/factory.d.ts +6 -0
- package/cache/factory.js +57 -0
- package/cache/index.d.ts +90 -0
- package/cache/index.js +169 -0
- package/cache/local.d.ts +23 -0
- package/cache/local.js +83 -0
- package/cache/metrics.d.ts +27 -0
- package/cache/metrics.js +120 -0
- package/cache/redis.d.ts +16 -0
- package/cache/redis.js +100 -0
- package/chainlink-external-adapter-framework-v0.0.8.tgz +0 -0
- package/config/index.d.ts +195 -0
- package/config/index.js +365 -0
- package/config/provider-limits.d.ts +31 -0
- package/config/provider-limits.js +75 -0
- package/examples/coingecko/batch-warming.d.ts +2 -0
- package/examples/coingecko/batch-warming.js +52 -0
- package/examples/coingecko/index.d.ts +2 -0
- package/examples/coingecko/index.js +10 -0
- package/examples/coingecko/rest.d.ts +2 -0
- package/examples/coingecko/rest.js +50 -0
- package/examples/ncfx/config/index.d.ts +12 -0
- package/examples/ncfx/config/index.js +15 -0
- package/examples/ncfx/index.d.ts +2 -0
- package/examples/ncfx/index.js +10 -0
- package/examples/ncfx/websocket.d.ts +36 -0
- package/examples/ncfx/websocket.js +72 -0
- package/index.d.ts +12 -0
- package/index.js +92 -0
- package/metrics/constants.d.ts +16 -0
- package/metrics/constants.js +25 -0
- package/metrics/index.d.ts +15 -0
- package/metrics/index.js +123 -0
- package/metrics/util.d.ts +3 -0
- package/metrics/util.js +9 -0
- package/package/adapter.d.ts +88 -0
- package/package/adapter.js +112 -0
- package/package/background-executor.d.ts +11 -0
- package/package/background-executor.js +45 -0
- package/package/cache/factory.d.ts +6 -0
- package/package/cache/factory.js +57 -0
- package/package/cache/index.d.ts +90 -0
- package/package/cache/index.js +169 -0
- package/package/cache/local.d.ts +23 -0
- package/package/cache/local.js +83 -0
- package/package/cache/metrics.d.ts +27 -0
- package/package/cache/metrics.js +120 -0
- package/package/cache/redis.d.ts +16 -0
- package/package/cache/redis.js +100 -0
- package/package/config/index.d.ts +195 -0
- package/package/config/index.js +365 -0
- package/package/config/provider-limits.d.ts +31 -0
- package/package/config/provider-limits.js +75 -0
- package/package/examples/coingecko/batch-warming.d.ts +2 -0
- package/package/examples/coingecko/batch-warming.js +52 -0
- package/package/examples/coingecko/index.d.ts +2 -0
- package/package/examples/coingecko/index.js +10 -0
- package/package/examples/coingecko/rest.d.ts +2 -0
- package/package/examples/coingecko/rest.js +50 -0
- package/package/examples/ncfx/config/index.d.ts +12 -0
- package/package/examples/ncfx/config/index.js +15 -0
- package/package/examples/ncfx/index.d.ts +2 -0
- package/package/examples/ncfx/index.js +10 -0
- package/package/examples/ncfx/websocket.d.ts +36 -0
- package/package/examples/ncfx/websocket.js +72 -0
- package/package/index.d.ts +12 -0
- package/package/index.js +92 -0
- package/package/metrics/constants.d.ts +16 -0
- package/package/metrics/constants.js +25 -0
- package/package/metrics/index.d.ts +15 -0
- package/package/metrics/index.js +123 -0
- package/package/metrics/util.d.ts +3 -0
- package/package/metrics/util.js +9 -0
- package/package/package.json +69 -0
- package/package/rate-limiting/background/fixed-frequency.d.ts +10 -0
- package/package/rate-limiting/background/fixed-frequency.js +37 -0
- package/package/rate-limiting/index.d.ts +54 -0
- package/package/rate-limiting/index.js +63 -0
- package/package/rate-limiting/metrics.d.ts +3 -0
- package/package/rate-limiting/metrics.js +44 -0
- package/package/rate-limiting/request/simple-counting.d.ts +20 -0
- package/package/rate-limiting/request/simple-counting.js +62 -0
- package/package/test.d.ts +1 -0
- package/package/test.js +6 -0
- package/package/transports/batch-warming.d.ts +34 -0
- package/package/transports/batch-warming.js +101 -0
- package/package/transports/index.d.ts +87 -0
- package/package/transports/index.js +87 -0
- package/package/transports/metrics.d.ts +21 -0
- package/package/transports/metrics.js +105 -0
- package/package/transports/rest.d.ts +43 -0
- package/package/transports/rest.js +129 -0
- package/package/transports/util.d.ts +8 -0
- package/package/transports/util.js +85 -0
- package/package/transports/websocket.d.ts +80 -0
- package/package/transports/websocket.js +169 -0
- package/package/util/expiring-sorted-set.d.ts +21 -0
- package/package/util/expiring-sorted-set.js +47 -0
- package/package/util/index.d.ts +11 -0
- package/package/util/index.js +35 -0
- package/package/util/logger.d.ts +42 -0
- package/package/util/logger.js +62 -0
- package/package/util/request.d.ts +55 -0
- package/package/util/request.js +2 -0
- package/package/validation/error.d.ts +50 -0
- package/package/validation/error.js +79 -0
- package/package/validation/index.d.ts +5 -0
- package/package/validation/index.js +86 -0
- package/package/validation/input-params.d.ts +15 -0
- package/package/validation/input-params.js +30 -0
- package/package/validation/override-functions.d.ts +3 -0
- package/package/validation/override-functions.js +40 -0
- package/package/validation/preset-tokens.json +23 -0
- package/package/validation/validator.d.ts +47 -0
- package/package/validation/validator.js +303 -0
- package/package.json +1 -1
- package/rate-limiting/background/fixed-frequency.d.ts +10 -0
- package/rate-limiting/background/fixed-frequency.js +37 -0
- package/rate-limiting/index.d.ts +54 -0
- package/rate-limiting/index.js +63 -0
- package/rate-limiting/metrics.d.ts +3 -0
- package/rate-limiting/metrics.js +44 -0
- package/rate-limiting/request/simple-counting.d.ts +20 -0
- package/rate-limiting/request/simple-counting.js +62 -0
- package/test.d.ts +1 -0
- package/test.js +6 -0
- package/transports/batch-warming.d.ts +34 -0
- package/transports/batch-warming.js +101 -0
- package/transports/index.d.ts +87 -0
- package/transports/index.js +87 -0
- package/transports/metrics.d.ts +21 -0
- package/transports/metrics.js +105 -0
- package/transports/rest.d.ts +43 -0
- package/transports/rest.js +129 -0
- package/transports/util.d.ts +8 -0
- package/transports/util.js +85 -0
- package/transports/websocket.d.ts +80 -0
- package/transports/websocket.js +169 -0
- package/util/expiring-sorted-set.d.ts +21 -0
- package/util/expiring-sorted-set.js +47 -0
- package/util/index.d.ts +11 -0
- package/util/index.js +35 -0
- package/util/logger.d.ts +42 -0
- package/util/logger.js +62 -0
- package/util/request.d.ts +55 -0
- package/util/request.js +2 -0
- package/validation/error.d.ts +50 -0
- package/validation/error.js +79 -0
- package/validation/index.d.ts +5 -0
- package/validation/index.js +86 -0
- package/validation/input-params.d.ts +15 -0
- package/validation/input-params.js +30 -0
- package/validation/override-functions.d.ts +3 -0
- package/validation/override-functions.js +40 -0
- package/validation/preset-tokens.json +23 -0
- package/validation/validator.d.ts +47 -0
- package/validation/validator.js +303 -0
- 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/README.md +0 -103
- 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,130 +0,0 @@
|
|
|
1
|
-
import { makeLogger } from '../util'
|
|
2
|
-
|
|
3
|
-
export const DEFAULT_MINUTE_RATE_LIMIT = 60
|
|
4
|
-
export const BURST_UNDEFINED_QUOTA_MULTIPLE = 2
|
|
5
|
-
|
|
6
|
-
export const DEFAULT_WS_CONNECTIONS = 2
|
|
7
|
-
export const DEFAULT_WS_SUBSCRIPTIONS = 10
|
|
8
|
-
|
|
9
|
-
type RateLimitTimeFrame = 'rateLimit1s' | 'rateLimit1m' | 'rateLimit1h'
|
|
10
|
-
|
|
11
|
-
type HTTPTier = {
|
|
12
|
-
rateLimit1s?: number
|
|
13
|
-
rateLimit1m?: number
|
|
14
|
-
rateLimit1h?: number
|
|
15
|
-
note?: string
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
type WSTier = {
|
|
19
|
-
connections: number
|
|
20
|
-
subscriptions: number
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export interface Limits {
|
|
24
|
-
http: {
|
|
25
|
-
[tierName: string]: HTTPTier
|
|
26
|
-
}
|
|
27
|
-
ws: {
|
|
28
|
-
[tierName: string]: WSTier
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
interface ProviderRateLimit {
|
|
33
|
-
second: number
|
|
34
|
-
minute: number
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const logger = makeLogger('ProviderLimits')
|
|
38
|
-
|
|
39
|
-
export const getHTTPLimit = (
|
|
40
|
-
provider: string,
|
|
41
|
-
limits: Limits,
|
|
42
|
-
tier: string,
|
|
43
|
-
timeframe: RateLimitTimeFrame,
|
|
44
|
-
): number => {
|
|
45
|
-
const providerLimit = getProviderLimits(provider, limits, tier, 'http')
|
|
46
|
-
return (providerLimit as HTTPTier)?.[timeframe] || 0
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export const getRateLimit = (provider: string, limits: Limits, tier: string): ProviderRateLimit => {
|
|
50
|
-
const providerLimit = getProviderLimits(provider, limits, tier, 'http')
|
|
51
|
-
return calculateRateLimit(providerLimit as HTTPTier)
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export const getWSLimits = (provider: string, limits: Limits, tier: string): WSTier => {
|
|
55
|
-
const providerLimit = getProviderLimits(provider, limits, tier, 'ws')
|
|
56
|
-
return calculateWSLimits(providerLimit as WSTier)
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
const getProviderLimits = (
|
|
60
|
-
provider: string,
|
|
61
|
-
limits: Limits,
|
|
62
|
-
tier: string,
|
|
63
|
-
protocol: 'ws' | 'http',
|
|
64
|
-
): HTTPTier | WSTier | undefined => {
|
|
65
|
-
const providerConfig = parseLimits(limits)
|
|
66
|
-
if (!providerConfig) {
|
|
67
|
-
throw new Error(
|
|
68
|
-
`Rate Limit: Provider: "${provider}" doesn't match any provider spec in limits.json`,
|
|
69
|
-
)
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const protocolConfig = providerConfig[protocol]
|
|
73
|
-
if (!protocolConfig) {
|
|
74
|
-
throw new Error(
|
|
75
|
-
`Rate Limit: "${provider}" doesn't have any configuration for ${protocol} in limits.json`,
|
|
76
|
-
)
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
let limitsConfig = protocolConfig[tier.toLowerCase()]
|
|
80
|
-
|
|
81
|
-
if (!limitsConfig) {
|
|
82
|
-
logger.debug(
|
|
83
|
-
`Rate Limit: "${provider} does not have tier ${tier} defined. Falling back to lowest tier"`,
|
|
84
|
-
)
|
|
85
|
-
limitsConfig = Object.values(protocolConfig)?.[0]
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
if (!limitsConfig) {
|
|
89
|
-
throw new Error(
|
|
90
|
-
`Rate Limit: Provider: "${provider}" has no tiers defined for ${protocol} in limits.json`,
|
|
91
|
-
)
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
return limitsConfig
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const parseLimits = (limits: Limits): Limits => {
|
|
98
|
-
const _mapObject = (fn: any) => (o: any) => Object.fromEntries(Object.entries(o).map(fn))
|
|
99
|
-
const _formatProtocol = _mapObject((entry: any[]) => {
|
|
100
|
-
const [tierName, rest] = entry
|
|
101
|
-
return [tierName.toLowerCase(), { ...(rest as any) }]
|
|
102
|
-
})
|
|
103
|
-
const _formatProvider = (ls: Limits) => {
|
|
104
|
-
const http = _formatProtocol(ls.http)
|
|
105
|
-
const ws = _formatProtocol(ls?.ws)
|
|
106
|
-
return { http, ws }
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
return _formatProvider(limits)
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
const calculateWSLimits = (providerLimit: WSTier): WSTier => {
|
|
113
|
-
return {
|
|
114
|
-
connections: providerLimit.connections,
|
|
115
|
-
subscriptions: providerLimit.subscriptions,
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
const calculateRateLimit = (providerLimit: HTTPTier): ProviderRateLimit => {
|
|
120
|
-
let quota = providerLimit.rateLimit1m
|
|
121
|
-
if (!quota && providerLimit?.rateLimit1h) {
|
|
122
|
-
quota = providerLimit?.rateLimit1h / 60
|
|
123
|
-
} else if (!quota && providerLimit?.rateLimit1s) {
|
|
124
|
-
quota = providerLimit?.rateLimit1s * 60
|
|
125
|
-
}
|
|
126
|
-
return {
|
|
127
|
-
second: providerLimit?.rateLimit1s || ((quota as number) / 60) * BURST_UNDEFINED_QUOTA_MULTIPLE,
|
|
128
|
-
minute: quota as number,
|
|
129
|
-
}
|
|
130
|
-
}
|
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import { AxiosRequestConfig, AxiosResponse } from 'axios'
|
|
2
|
-
import { AdapterEndpoint } from '../../adapter'
|
|
3
|
-
import { AdapterContext } from '../../transports'
|
|
4
|
-
import { BatchWarmingTransport } from '../../transports/batch-warming'
|
|
5
|
-
import { ProviderResult } from '../../util'
|
|
6
|
-
import { InputParameters } from '../../validation'
|
|
7
|
-
|
|
8
|
-
const DEFAULT_URL = 'https://pro-api.coingecko.com/api/v3'
|
|
9
|
-
|
|
10
|
-
interface AdapterRequestParams {
|
|
11
|
-
base: string
|
|
12
|
-
quote: string
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
const inputParameters: InputParameters = {
|
|
16
|
-
coinid: {
|
|
17
|
-
description:
|
|
18
|
-
'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)',
|
|
19
|
-
required: false,
|
|
20
|
-
},
|
|
21
|
-
base: {
|
|
22
|
-
aliases: ['from', 'coin'],
|
|
23
|
-
description: 'The symbol or array of symbols of the currency to query',
|
|
24
|
-
required: true,
|
|
25
|
-
},
|
|
26
|
-
quote: {
|
|
27
|
-
aliases: ['to', 'market'],
|
|
28
|
-
description: 'The symbol of the currency to convert to',
|
|
29
|
-
required: true,
|
|
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 batchEndpointTransport = new BatchWarmingTransport({
|
|
44
|
-
prepareRequest: (
|
|
45
|
-
params: AdapterRequestParams[],
|
|
46
|
-
context: AdapterContext,
|
|
47
|
-
): AxiosRequestConfig<ProviderRequestBody> => {
|
|
48
|
-
return {
|
|
49
|
-
baseURL: DEFAULT_URL,
|
|
50
|
-
url: '/simple/price',
|
|
51
|
-
method: 'GET',
|
|
52
|
-
params: {
|
|
53
|
-
ids: [...new Set(params.map((p) => p.base))].join(','),
|
|
54
|
-
vs_currencies: [...new Set(params.map((p) => p.quote))].join(','),
|
|
55
|
-
x_cg_pro_api_key: context.adapterConfig.API_KEY,
|
|
56
|
-
},
|
|
57
|
-
}
|
|
58
|
-
},
|
|
59
|
-
parseResponse: (
|
|
60
|
-
res: AxiosResponse<ProviderResponseBody>,
|
|
61
|
-
): ProviderResult<AdapterRequestParams>[] => {
|
|
62
|
-
const entries = [] as ProviderResult<AdapterRequestParams>[]
|
|
63
|
-
for (const [base, entry] of Object.entries(res.data)) {
|
|
64
|
-
for (const [quote, price] of Object.entries(entry)) {
|
|
65
|
-
entries.push({
|
|
66
|
-
params: { base, quote },
|
|
67
|
-
value: price,
|
|
68
|
-
})
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
return entries
|
|
72
|
-
},
|
|
73
|
-
})
|
|
74
|
-
|
|
75
|
-
export const batchEndpoint: AdapterEndpoint = {
|
|
76
|
-
name: 'batch',
|
|
77
|
-
transport: batchEndpointTransport,
|
|
78
|
-
inputParameters,
|
|
79
|
-
}
|
|
@@ -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
|
-
}
|