@chainlink/external-adapter-framework 0.0.10 → 0.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.c8rc.json +3 -0
- package/.eslintignore +9 -0
- package/.eslintrc.js +96 -0
- package/.github/README.MD +17 -0
- package/.github/actions/setup/action.yaml +13 -0
- package/.github/workflows/main.yaml +39 -0
- package/.github/workflows/publish.yaml +20 -0
- package/.prettierignore +13 -0
- package/.yarnrc +0 -0
- package/README.md +103 -0
- package/dist/src/adapter.d.ts +135 -0
- package/dist/src/adapter.js +145 -0
- package/dist/src/background-executor.d.ts +11 -0
- package/{background-executor.js → dist/src/background-executor.js} +0 -0
- package/{cache → dist/src/cache}/factory.d.ts +0 -0
- package/dist/src/cache/factory.js +55 -0
- package/dist/src/cache/index.d.ts +94 -0
- package/dist/src/cache/index.js +173 -0
- package/{cache → dist/src/cache}/local.d.ts +0 -0
- package/{cache → dist/src/cache}/local.js +0 -0
- package/{cache → dist/src/cache}/metrics.d.ts +0 -0
- package/{cache → dist/src/cache}/metrics.js +0 -0
- package/{cache → dist/src/cache}/redis.d.ts +0 -0
- package/dist/src/cache/redis.js +100 -0
- package/dist/src/chainlink-external-adapter-framework-0.0.6.tgz +0 -0
- package/dist/src/config/index.d.ts +214 -0
- package/dist/src/config/index.js +380 -0
- package/{config → dist/src/config}/provider-limits.d.ts +0 -0
- package/{config → dist/src/config}/provider-limits.js +1 -1
- package/dist/src/examples/bank-frick/accounts.d.ts +39 -0
- package/dist/src/examples/bank-frick/accounts.js +192 -0
- package/dist/src/examples/bank-frick/config/index.d.ts +4 -0
- package/dist/src/examples/bank-frick/config/index.js +54 -0
- package/dist/src/examples/bank-frick/index.d.ts +2 -0
- package/dist/src/examples/bank-frick/index.js +15 -0
- package/dist/src/examples/bank-frick/util.d.ts +4 -0
- package/dist/src/examples/bank-frick/util.js +39 -0
- package/dist/src/examples/coingecko/batch-warming.d.ts +7 -0
- package/dist/src/examples/coingecko/batch-warming.js +53 -0
- package/dist/src/examples/coingecko/index.d.ts +2 -0
- package/dist/src/examples/coingecko/index.js +11 -0
- package/dist/src/examples/coingecko/rest.d.ts +12 -0
- package/dist/src/examples/coingecko/rest.js +51 -0
- package/{examples → dist/src/examples}/ncfx/config/index.d.ts +0 -0
- package/{examples → dist/src/examples}/ncfx/config/index.js +0 -0
- package/dist/src/examples/ncfx/index.d.ts +13 -0
- package/dist/src/examples/ncfx/index.js +11 -0
- package/dist/src/examples/ncfx/websocket.d.ts +47 -0
- package/dist/src/examples/ncfx/websocket.js +73 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +128 -0
- package/{metrics → dist/src/metrics}/constants.d.ts +0 -0
- package/{metrics → dist/src/metrics}/constants.js +0 -0
- package/{metrics → dist/src/metrics}/index.d.ts +0 -0
- package/dist/src/metrics/index.js +122 -0
- package/dist/src/metrics/util.d.ts +7 -0
- package/dist/src/metrics/util.js +9 -0
- package/{adapter.d.ts → dist/src/package/adapter.d.ts} +0 -0
- package/{adapter.js → dist/src/package/adapter.js} +0 -0
- package/{background-executor.d.ts → dist/src/package/background-executor.d.ts} +0 -0
- package/dist/src/package/background-executor.js +45 -0
- package/dist/src/package/cache/factory.d.ts +6 -0
- package/{cache → dist/src/package/cache}/factory.js +0 -0
- package/{cache → dist/src/package/cache}/index.d.ts +0 -0
- package/{cache → dist/src/package/cache}/index.js +0 -0
- package/dist/src/package/cache/local.d.ts +23 -0
- package/dist/src/package/cache/local.js +83 -0
- package/dist/src/package/cache/metrics.d.ts +27 -0
- package/dist/src/package/cache/metrics.js +120 -0
- package/dist/src/package/cache/redis.d.ts +16 -0
- package/{cache → dist/src/package/cache}/redis.js +0 -0
- package/{config → dist/src/package/config}/index.d.ts +0 -0
- package/{config → dist/src/package/config}/index.js +0 -0
- package/dist/src/package/config/provider-limits.d.ts +31 -0
- package/dist/src/package/config/provider-limits.js +76 -0
- package/{examples → dist/src/package/examples}/coingecko/batch-warming.d.ts +0 -0
- package/{examples → dist/src/package/examples}/coingecko/batch-warming.js +0 -0
- package/{examples → dist/src/package/examples}/coingecko/index.d.ts +0 -0
- package/{examples → dist/src/package/examples}/coingecko/index.js +0 -0
- package/{examples → dist/src/package/examples}/coingecko/rest.d.ts +0 -0
- package/{examples → dist/src/package/examples}/coingecko/rest.js +0 -0
- package/dist/src/package/examples/ncfx/config/index.d.ts +12 -0
- package/dist/src/package/examples/ncfx/config/index.js +15 -0
- package/{examples → dist/src/package/examples}/ncfx/index.d.ts +0 -0
- package/{examples → dist/src/package/examples}/ncfx/index.js +0 -0
- package/{examples → dist/src/package/examples}/ncfx/websocket.d.ts +0 -0
- package/{examples → dist/src/package/examples}/ncfx/websocket.js +0 -0
- package/{index.d.ts → dist/src/package/index.d.ts} +0 -0
- package/{index.js → dist/src/package/index.js} +0 -0
- package/dist/src/package/metrics/constants.d.ts +16 -0
- package/dist/src/package/metrics/constants.js +25 -0
- package/dist/src/package/metrics/index.d.ts +15 -0
- package/{metrics → dist/src/package/metrics}/index.js +0 -0
- package/{metrics → dist/src/package/metrics}/util.d.ts +0 -0
- package/{metrics → dist/src/package/metrics}/util.js +0 -0
- package/dist/src/package/package.json +72 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/background/fixed-frequency.d.ts +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/background/fixed-frequency.js +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/index.d.ts +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/index.js +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/metrics.d.ts +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/metrics.js +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/request/simple-counting.d.ts +0 -0
- package/{rate-limiting → dist/src/package/rate-limiting}/request/simple-counting.js +0 -0
- package/{test.d.ts → dist/src/package/test.d.ts} +0 -0
- package/{test.js → dist/src/package/test.js} +0 -0
- package/{transports → dist/src/package/transports}/batch-warming.d.ts +0 -0
- package/{transports → dist/src/package/transports}/batch-warming.js +0 -0
- package/{transports → dist/src/package/transports}/index.d.ts +0 -0
- package/{transports → dist/src/package/transports}/index.js +0 -0
- package/{transports → dist/src/package/transports}/metrics.d.ts +0 -0
- package/{transports → dist/src/package/transports}/metrics.js +0 -0
- package/{transports → dist/src/package/transports}/rest.d.ts +0 -0
- package/{transports → dist/src/package/transports}/rest.js +0 -0
- package/{transports → dist/src/package/transports}/util.d.ts +0 -0
- package/{transports → dist/src/package/transports}/util.js +0 -0
- package/{transports → dist/src/package/transports}/websocket.d.ts +0 -0
- package/{transports → dist/src/package/transports}/websocket.js +0 -0
- package/{util → dist/src/package/util}/expiring-sorted-set.d.ts +0 -0
- package/{util → dist/src/package/util}/expiring-sorted-set.js +0 -0
- package/{util → dist/src/package/util}/index.d.ts +0 -0
- package/{util → dist/src/package/util}/index.js +0 -0
- package/{util → dist/src/package/util}/logger.d.ts +0 -0
- package/{util → dist/src/package/util}/logger.js +0 -0
- package/{util → dist/src/package/util}/request.d.ts +0 -0
- package/{util → dist/src/package/util}/request.js +0 -0
- package/{validation → dist/src/package/validation}/error.d.ts +0 -0
- package/{validation → dist/src/package/validation}/error.js +0 -0
- package/{validation → dist/src/package/validation}/index.d.ts +0 -0
- package/{validation → dist/src/package/validation}/index.js +0 -0
- package/{validation → dist/src/package/validation}/input-params.d.ts +0 -0
- package/{validation → dist/src/package/validation}/input-params.js +0 -0
- package/{validation → dist/src/package/validation}/override-functions.d.ts +0 -0
- package/{validation → dist/src/package/validation}/override-functions.js +0 -0
- package/{validation → dist/src/package/validation}/preset-tokens.json +0 -0
- package/{validation → dist/src/package/validation}/validator.d.ts +0 -0
- package/{validation → dist/src/package/validation}/validator.js +0 -0
- package/dist/src/package.json +72 -0
- package/dist/src/rate-limiting/background/fixed-frequency.d.ts +11 -0
- package/dist/src/rate-limiting/background/fixed-frequency.js +35 -0
- package/dist/src/rate-limiting/index.d.ts +55 -0
- package/dist/src/rate-limiting/index.js +63 -0
- package/dist/src/rate-limiting/metrics.d.ts +3 -0
- package/dist/src/rate-limiting/metrics.js +44 -0
- package/dist/src/rate-limiting/request/simple-counting.d.ts +21 -0
- package/dist/src/rate-limiting/request/simple-counting.js +62 -0
- package/dist/src/test.d.ts +1 -0
- package/dist/src/test.js +6 -0
- package/dist/src/transports/batch-warming.d.ts +35 -0
- package/dist/src/transports/batch-warming.js +101 -0
- package/dist/src/transports/index.d.ts +70 -0
- package/dist/src/transports/index.js +87 -0
- package/dist/src/transports/metrics.d.ts +22 -0
- package/dist/src/transports/metrics.js +105 -0
- package/dist/src/transports/rest.d.ts +44 -0
- package/dist/src/transports/rest.js +131 -0
- package/dist/src/transports/util.d.ts +8 -0
- package/dist/src/transports/util.js +85 -0
- package/dist/src/transports/websocket.d.ts +80 -0
- package/dist/src/transports/websocket.js +166 -0
- package/dist/src/util/expiring-sorted-set.d.ts +21 -0
- package/dist/src/util/expiring-sorted-set.js +47 -0
- package/dist/src/util/index.d.ts +12 -0
- package/dist/src/util/index.js +35 -0
- package/dist/src/util/logger.d.ts +42 -0
- package/dist/src/util/logger.js +62 -0
- package/dist/src/util/request.d.ts +57 -0
- package/dist/src/util/request.js +2 -0
- package/dist/src/util/subscription-set/expiring-sorted-set.d.ts +22 -0
- package/dist/src/util/subscription-set/expiring-sorted-set.js +47 -0
- package/dist/src/util/subscription-set/subscription-set.d.ts +18 -0
- package/dist/src/util/subscription-set/subscription-set.js +19 -0
- package/dist/src/util/test-payload-loader.d.ts +25 -0
- package/dist/src/util/test-payload-loader.js +83 -0
- package/dist/src/validation/error.d.ts +50 -0
- package/dist/src/validation/error.js +79 -0
- package/dist/src/validation/index.d.ts +5 -0
- package/dist/src/validation/index.js +91 -0
- package/dist/src/validation/input-params.d.ts +15 -0
- package/dist/src/validation/input-params.js +30 -0
- package/dist/src/validation/override-functions.d.ts +3 -0
- package/dist/src/validation/override-functions.js +40 -0
- package/dist/src/validation/preset-tokens.json +23 -0
- package/dist/src/validation/validator.d.ts +47 -0
- package/dist/src/validation/validator.js +303 -0
- package/docker-compose.yaml +35 -0
- package/env.sh +54 -0
- package/env2.sh +55 -0
- package/package.json +5 -3
- package/publish.sh +0 -0
- package/src/adapter.ts +263 -0
- package/src/background-executor.ts +52 -0
- package/src/cache/factory.ts +26 -0
- package/src/cache/index.ts +258 -0
- package/src/cache/local.ts +73 -0
- package/src/cache/metrics.ts +112 -0
- package/src/cache/redis.ts +93 -0
- package/src/config/index.ts +517 -0
- package/src/config/provider-limits.ts +130 -0
- package/src/examples/bank-frick/README.MD +10 -0
- package/src/examples/bank-frick/accounts.ts +246 -0
- package/src/examples/bank-frick/config/index.ts +53 -0
- package/src/examples/bank-frick/index.ts +13 -0
- package/src/examples/bank-frick/types.d.ts +38 -0
- package/src/examples/bank-frick/util.ts +55 -0
- package/src/examples/coingecko/batch-warming.ts +78 -0
- package/src/examples/coingecko/index.ts +9 -0
- package/src/examples/coingecko/rest.ts +77 -0
- package/src/examples/ncfx/config/index.ts +12 -0
- package/src/examples/ncfx/index.ts +9 -0
- package/src/examples/ncfx/websocket.ts +99 -0
- package/src/index.ts +149 -0
- package/src/metrics/constants.ts +23 -0
- package/src/metrics/index.ts +115 -0
- package/src/metrics/util.ts +18 -0
- package/src/rate-limiting/background/fixed-frequency.ts +45 -0
- package/src/rate-limiting/index.ts +100 -0
- package/src/rate-limiting/metrics.ts +18 -0
- package/src/rate-limiting/request/simple-counting.ts +76 -0
- package/src/test.ts +5 -0
- package/src/transports/batch-warming.ts +122 -0
- package/src/transports/index.ts +152 -0
- package/src/transports/metrics.ts +95 -0
- package/src/transports/rest.ts +164 -0
- package/src/transports/util.ts +63 -0
- package/src/transports/websocket.ts +245 -0
- package/src/util/index.ts +22 -0
- package/src/util/logger.ts +69 -0
- package/src/util/request.ts +117 -0
- package/src/util/subscription-set/expiring-sorted-set.ts +54 -0
- package/src/util/subscription-set/subscription-set.ts +35 -0
- package/src/util/test-payload-loader.ts +87 -0
- package/src/validation/error.ts +116 -0
- package/src/validation/index.ts +110 -0
- package/src/validation/input-params.ts +45 -0
- package/src/validation/override-functions.ts +44 -0
- package/src/validation/preset-tokens.json +23 -0
- package/src/validation/validator.ts +384 -0
- package/test/adapter.test.ts +27 -0
- package/test/background-executor.test.ts +108 -0
- package/test/cache/cache-key.test.ts +114 -0
- package/test/cache/helper.ts +100 -0
- package/test/cache/local.test.ts +54 -0
- package/test/cache/redis.test.ts +89 -0
- package/test/correlation.test.ts +114 -0
- package/test/index.test.ts +37 -0
- package/test/metrics/feed-id.test.ts +38 -0
- package/test/metrics/helper.ts +14 -0
- package/test/metrics/labels.test.ts +36 -0
- package/test/metrics/metrics.test.ts +267 -0
- package/test/metrics/redis-metrics.test.ts +113 -0
- package/test/metrics/warmer-metrics.test.ts +192 -0
- package/test/metrics/ws-metrics.test.ts +225 -0
- package/test/rate-limit-config.test.ts +242 -0
- package/test/smoke.test.ts +166 -0
- package/test/transports/batch.test.ts +465 -0
- package/test/transports/rest.test.ts +242 -0
- package/test/transports/websocket.test.ts +183 -0
- package/test/tsconfig.json +5 -0
- package/test/util.ts +77 -0
- package/test/validation.test.ts +178 -0
- package/test-payload-fail.json +3 -0
- package/test-payload.js +22 -0
- package/test-payload.json +7 -0
- package/test.sh +20 -0
- package/test2.sh +2 -0
- package/tsconfig.json +25 -0
- package/typedoc.json +6 -0
- package/webpack.config.js +23 -0
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { FastifyReply } from 'fastify'
|
|
2
|
+
import { AdapterContext, AdapterDependencies, InitializedAdapter } from '../adapter'
|
|
3
|
+
import {
|
|
4
|
+
Cache,
|
|
5
|
+
CacheEntry,
|
|
6
|
+
calculateCacheKey,
|
|
7
|
+
calculateFeedId,
|
|
8
|
+
pollResponseFromCache,
|
|
9
|
+
} from '../cache'
|
|
10
|
+
import { AdapterConfig, SettingsMap } from '../config'
|
|
11
|
+
import { makeLogger } from '../util'
|
|
12
|
+
import { AdapterRequest, AdapterResponse, ProviderResult } from '../util/request'
|
|
13
|
+
|
|
14
|
+
export * from './batch-warming'
|
|
15
|
+
export * from './rest'
|
|
16
|
+
export * from './websocket'
|
|
17
|
+
|
|
18
|
+
const logger = makeLogger('Transport')
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Generic interface for a Transport.
|
|
22
|
+
* A Transport defines the way in which an AdapterEndpoint will process incoming requests to
|
|
23
|
+
* fetch data from a Data Provider. The setup phase will take care of the former, while the
|
|
24
|
+
* backgroundExecute will be in charge of the latter.
|
|
25
|
+
* This separation gives us the ability of splitting these concerns, and optionally parallelizing
|
|
26
|
+
* the reading and writing of data to a centralized Cache.
|
|
27
|
+
*
|
|
28
|
+
* @typeParam Params - the structure of the AdapterRequest's body
|
|
29
|
+
* @typeParam Result - the structure of the AdapterResponse's body
|
|
30
|
+
*/
|
|
31
|
+
export interface Transport<Params, Result, CustomSettings extends SettingsMap> {
|
|
32
|
+
// TODO: docs / examples to extend dependencies? e.g. JSON rpc
|
|
33
|
+
/**
|
|
34
|
+
* Initializes the transport in the Adapter context.
|
|
35
|
+
*
|
|
36
|
+
* @param dependencies - Adapter dependencies (e.g. cache instance)
|
|
37
|
+
* @returns an empty Promise
|
|
38
|
+
*/
|
|
39
|
+
initialize: (dependencies: AdapterDependencies) => Promise<void>
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Checks if the Transport has already set up the incoming request.
|
|
43
|
+
* This will likely use the cacheKey generated in the provided request.
|
|
44
|
+
*
|
|
45
|
+
* @param req - the incoming AdapterRequest
|
|
46
|
+
* @returns a Promise that returns true if setup is in place
|
|
47
|
+
*/
|
|
48
|
+
hasBeenSetUp: (req: AdapterRequest<Params>) => Promise<boolean>
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Sets up the incoming request within the Transport.
|
|
52
|
+
* In other words, it means that the Adapter has recognized this request, and will begin
|
|
53
|
+
* fetching the necessary data from a Data Provider.
|
|
54
|
+
*
|
|
55
|
+
* @param req - the incoming AdapterRequest
|
|
56
|
+
* @param config - common configuration for the Adapter as a whole
|
|
57
|
+
* @returns a Promise that _optionally_ returns an AdapterResponse, if the Transport has the capability of
|
|
58
|
+
* immediately fetching data and returning it without the background process.
|
|
59
|
+
*/
|
|
60
|
+
setup: (
|
|
61
|
+
req: AdapterRequest<Params>,
|
|
62
|
+
config: AdapterConfig<CustomSettings>,
|
|
63
|
+
) => Promise<AdapterResponse<Result> | void>
|
|
64
|
+
|
|
65
|
+
// TODO: Might need a mechanism to know if this bg execute is in flight to avoid multitple simultaneous invocations
|
|
66
|
+
/**
|
|
67
|
+
* If the Transport relies on an async mechanism, implementing this function will make it
|
|
68
|
+
* so the background task executor calls it on Adapter startup.
|
|
69
|
+
*
|
|
70
|
+
* @param context - background context for the execution (e.g. endpoint name)
|
|
71
|
+
*/
|
|
72
|
+
backgroundExecute?: (context: AdapterContext<CustomSettings>) => Promise<number>
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Helper method to build cache entries to set after getting a bunch of responses from a DP.
|
|
77
|
+
*
|
|
78
|
+
* @param results - a list of results coming from a DataProvider
|
|
79
|
+
* @param context - context for the Adapter
|
|
80
|
+
* @returns a list of CacheEntries of AdapterResponses
|
|
81
|
+
*/
|
|
82
|
+
export const buildCacheEntriesFromResults = <Params, CustomSettings extends SettingsMap>(
|
|
83
|
+
results: ProviderResult<Params>[],
|
|
84
|
+
context: AdapterContext<CustomSettings>,
|
|
85
|
+
): CacheEntry<AdapterResponse<null>>[] =>
|
|
86
|
+
results.map((r) => {
|
|
87
|
+
const cacheEntry = {
|
|
88
|
+
key: calculateCacheKey(context as AdapterContext, r.params),
|
|
89
|
+
value: {
|
|
90
|
+
result: r.value,
|
|
91
|
+
statusCode: 200,
|
|
92
|
+
data: null, // TODO: Maybe add data as well?
|
|
93
|
+
},
|
|
94
|
+
}
|
|
95
|
+
if (
|
|
96
|
+
context.adapterConfig.METRICS_ENABLED &&
|
|
97
|
+
context.adapterConfig.EXPERIMENTAL_METRICS_ENABLED
|
|
98
|
+
) {
|
|
99
|
+
const metrics = {
|
|
100
|
+
maxAge: Date.now() + context.adapterConfig.CACHE_MAX_AGE, // TODO: Replace with telemetry structure in future
|
|
101
|
+
meta: {
|
|
102
|
+
metrics: {
|
|
103
|
+
feedId: calculateFeedId(context as AdapterContext, r.params),
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
}
|
|
107
|
+
cacheEntry.value = { ...cacheEntry.value, ...metrics }
|
|
108
|
+
}
|
|
109
|
+
return cacheEntry
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Takes an Adapter, its configuration, and its dependencies, and it creates an express middleware
|
|
114
|
+
* that will pass along the AdapterRequest to the appropriate Transport (acc. to the endpoint in the req.)
|
|
115
|
+
*
|
|
116
|
+
* @param adapter - main adapter object, already initialized
|
|
117
|
+
* @returns the transport handler middleware function
|
|
118
|
+
*/
|
|
119
|
+
export const buildTransportHandler =
|
|
120
|
+
(adapter: InitializedAdapter) => async (req: AdapterRequest, reply: FastifyReply) => {
|
|
121
|
+
// Get transport, must be here because it's already checked in the validator
|
|
122
|
+
const transport = adapter.endpointsMap[req.requestContext.endpointName].transport
|
|
123
|
+
|
|
124
|
+
// Set up transport if it hasn't been done already
|
|
125
|
+
if (!(await transport.hasBeenSetUp(req))) {
|
|
126
|
+
logger.debug('Transport not set up yet, doing so...')
|
|
127
|
+
const immediateResponse = await transport.setup(req, adapter.config)
|
|
128
|
+
if (immediateResponse) {
|
|
129
|
+
logger.debug('Got immediate response from transport, sending as response')
|
|
130
|
+
return reply.send(immediateResponse)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
logger.debug('Transport is set up, polling cache for response...')
|
|
134
|
+
const response = await pollResponseFromCache(
|
|
135
|
+
adapter.dependencies.cache as Cache<AdapterResponse>,
|
|
136
|
+
req.requestContext.cacheKey,
|
|
137
|
+
{
|
|
138
|
+
maxRetries: adapter.config.CACHE_POLLING_MAX_RETRIES,
|
|
139
|
+
sleep: adapter.config.CACHE_POLLING_SLEEP_MS,
|
|
140
|
+
},
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
if (response) {
|
|
144
|
+
logger.debug('Got a response from the cache, sending that back')
|
|
145
|
+
return reply.send(response)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
logger.debug('Ran out of polling attempts, returning timeout')
|
|
149
|
+
reply.statusCode = 504
|
|
150
|
+
|
|
151
|
+
return reply.send()
|
|
152
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import * as client from 'prom-client'
|
|
2
|
+
import { AdapterContext } from '../adapter'
|
|
3
|
+
import { calculateCacheKey, calculateFeedId } from '../cache'
|
|
4
|
+
import { requestDurationBuckets } from '../metrics/constants'
|
|
5
|
+
|
|
6
|
+
// Data Provider Metrics
|
|
7
|
+
export const dataProviderMetricsLabel = (providerStatusCode?: number, method = 'get') => ({
|
|
8
|
+
provider_status_code: providerStatusCode,
|
|
9
|
+
method: method.toUpperCase(),
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
export const dataProviderRequests = new client.Counter({
|
|
13
|
+
name: 'data_provider_requests',
|
|
14
|
+
help: 'The number of http requests that are made to a data provider',
|
|
15
|
+
labelNames: ['method', 'provider_status_code'] as const,
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
export const dataProviderRequestDurationSeconds = new client.Histogram({
|
|
19
|
+
name: 'data_provider_request_duration_seconds',
|
|
20
|
+
help: 'A histogram bucket of the distribution of data provider request durations',
|
|
21
|
+
buckets: requestDurationBuckets,
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
// Websocket Metrics
|
|
25
|
+
export const connectionErrorLabels = (message: string) => ({
|
|
26
|
+
// Key,
|
|
27
|
+
message,
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
export const messageSubsLabels = (feed_id: string, cache_key: string) => ({
|
|
31
|
+
feed_id,
|
|
32
|
+
subscription_key: cache_key,
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
// Record WS message and subscription metrics
|
|
36
|
+
// Recalculate cacheKey and feedId for metrics
|
|
37
|
+
// since avoiding storing extra info in expiring sorted set
|
|
38
|
+
export const recordWsMessageMetrics = <AdapterParams>(
|
|
39
|
+
context: AdapterContext,
|
|
40
|
+
subscribes: AdapterParams[],
|
|
41
|
+
unsubscrices: AdapterParams[],
|
|
42
|
+
): void => {
|
|
43
|
+
subscribes.forEach((param) => {
|
|
44
|
+
const feedId = calculateFeedId(context, param)
|
|
45
|
+
const cacheKey = calculateCacheKey(context, param)
|
|
46
|
+
// Record total number of ws messages sent
|
|
47
|
+
wsMessageTotal.labels(messageSubsLabels(feedId, cacheKey)).inc()
|
|
48
|
+
|
|
49
|
+
// Record total number of subscriptions made
|
|
50
|
+
wsSubscriptionTotal.labels(messageSubsLabels(feedId, cacheKey)).inc()
|
|
51
|
+
|
|
52
|
+
// Record number of active ws subscriptions
|
|
53
|
+
wsSubscriptionActive.labels(messageSubsLabels(feedId, cacheKey)).inc()
|
|
54
|
+
})
|
|
55
|
+
unsubscrices.forEach((param) => {
|
|
56
|
+
const feedId = calculateFeedId(context, param)
|
|
57
|
+
const cacheKey = calculateCacheKey(context, param)
|
|
58
|
+
|
|
59
|
+
// Record total number of ws messages sent
|
|
60
|
+
wsMessageTotal.labels(messageSubsLabels(feedId, cacheKey)).inc()
|
|
61
|
+
|
|
62
|
+
// Record number of active ws subscriptions
|
|
63
|
+
wsSubscriptionActive.labels(messageSubsLabels(feedId, cacheKey)).dec()
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const wsConnectionActive = new client.Gauge({
|
|
68
|
+
name: 'ws_connection_active',
|
|
69
|
+
help: 'The number of active connections',
|
|
70
|
+
labelNames: ['url'] as const,
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
export const wsConnectionErrors = new client.Counter({
|
|
74
|
+
name: 'ws_connection_errors',
|
|
75
|
+
help: 'The number of connection errors',
|
|
76
|
+
labelNames: ['url', 'message'] as const,
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
export const wsSubscriptionActive = new client.Gauge({
|
|
80
|
+
name: 'ws_subscription_active',
|
|
81
|
+
help: 'The number of currently active subscriptions',
|
|
82
|
+
labelNames: ['connection_url', 'feed_id', 'subscription_key'] as const,
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
export const wsSubscriptionTotal = new client.Counter({
|
|
86
|
+
name: 'ws_subscription_total',
|
|
87
|
+
help: 'The number of subscriptions opened in total',
|
|
88
|
+
labelNames: ['connection_url', 'feed_id', 'subscription_key'] as const,
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
export const wsMessageTotal = new client.Counter({
|
|
92
|
+
name: 'ws_message_total',
|
|
93
|
+
help: 'The number of messages received in total',
|
|
94
|
+
labelNames: ['feed_id', 'subscription_key'] as const,
|
|
95
|
+
})
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { AdapterRequest, AdapterResponse } from '../util/request'
|
|
2
|
+
import { Transport } from './'
|
|
3
|
+
import { Cache } from '../cache'
|
|
4
|
+
import { AxiosRequestConfig, AxiosResponse } from 'axios'
|
|
5
|
+
import { makeLogger, sleep } from '../util'
|
|
6
|
+
import { AdapterConfig, SettingsMap } from '../config'
|
|
7
|
+
import { RequestRateLimiter } from '../rate-limiting'
|
|
8
|
+
import { AdapterError } from '../validation/error'
|
|
9
|
+
import { axiosRequest } from './util'
|
|
10
|
+
import * as rateLimitMetrics from '../rate-limiting/metrics'
|
|
11
|
+
import { AdapterDependencies } from '../adapter'
|
|
12
|
+
|
|
13
|
+
const IN_FLIGHT_PREFIX = 'InFlight'
|
|
14
|
+
|
|
15
|
+
const logger = makeLogger('RestTransport')
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Transport implementation that takes incoming requests, transforms them into a DataProvider request,
|
|
19
|
+
* and executes that request returning the response immediately from the `setup` function.
|
|
20
|
+
* Optionally, setting the `coalescing` option to `true` will make it so once a request is in flight,
|
|
21
|
+
* new adapter requests for the same feed will not trigger a new one, but return an empty promise from
|
|
22
|
+
* the setup instead so the normal cache polling mechanism is used.
|
|
23
|
+
*
|
|
24
|
+
* @typeParam AdapterParams - interface for the adapter request body
|
|
25
|
+
* @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
|
|
26
|
+
* @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
|
|
27
|
+
*/
|
|
28
|
+
export class RestTransport<
|
|
29
|
+
AdapterParams,
|
|
30
|
+
ProviderRequestBody,
|
|
31
|
+
ProviderResponseBody,
|
|
32
|
+
CustomSettings extends SettingsMap,
|
|
33
|
+
> implements Transport<AdapterParams, ProviderResponseBody, CustomSettings>
|
|
34
|
+
{
|
|
35
|
+
inFlightPrefix!: string
|
|
36
|
+
cache!: Cache
|
|
37
|
+
rateLimiter!: RequestRateLimiter
|
|
38
|
+
|
|
39
|
+
constructor(
|
|
40
|
+
protected config: {
|
|
41
|
+
prepareRequest: (
|
|
42
|
+
req: AdapterRequest<AdapterParams>,
|
|
43
|
+
config: AdapterConfig<CustomSettings>,
|
|
44
|
+
) =>
|
|
45
|
+
| AxiosRequestConfig<ProviderRequestBody>
|
|
46
|
+
| Promise<AxiosRequestConfig<ProviderRequestBody>>
|
|
47
|
+
parseResponse: (
|
|
48
|
+
req: AdapterRequest<AdapterParams>,
|
|
49
|
+
res: AxiosResponse<ProviderResponseBody>,
|
|
50
|
+
config: AdapterConfig<CustomSettings>,
|
|
51
|
+
) => AdapterResponse<ProviderResponseBody> | Promise<AdapterResponse<ProviderResponseBody>>
|
|
52
|
+
options: {
|
|
53
|
+
coalescing: boolean
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
) {}
|
|
57
|
+
|
|
58
|
+
async initialize(dependencies: AdapterDependencies): Promise<void> {
|
|
59
|
+
this.inFlightPrefix = `${IN_FLIGHT_PREFIX}-`
|
|
60
|
+
this.cache = dependencies.cache
|
|
61
|
+
this.rateLimiter = dependencies.requestRateLimiter
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async hasBeenSetUp(req: AdapterRequest<AdapterParams>): Promise<boolean> {
|
|
65
|
+
if (!this.config.options.coalescing) {
|
|
66
|
+
return false
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Check if request is in flight
|
|
70
|
+
const inFlight = await this.cache.get(this.inFlightPrefix + req.requestContext.cacheKey)
|
|
71
|
+
if (inFlight) {
|
|
72
|
+
logger.debug('Request is in flight, transport has been set up')
|
|
73
|
+
return true
|
|
74
|
+
} else {
|
|
75
|
+
logger.debug('Request not in flight, transport not set up')
|
|
76
|
+
return false
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
protected async waitUntilUnderRateLimit(
|
|
81
|
+
options: {
|
|
82
|
+
maxRetries: number
|
|
83
|
+
msBetweenRetries: number
|
|
84
|
+
},
|
|
85
|
+
retry = 0,
|
|
86
|
+
) {
|
|
87
|
+
if (this.rateLimiter.isUnderLimits()) {
|
|
88
|
+
logger.trace('Incoming request would not be under limits, moving on')
|
|
89
|
+
return
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (retry >= options.maxRetries) {
|
|
93
|
+
throw new AdapterError({
|
|
94
|
+
statusCode: 504,
|
|
95
|
+
message: `REST Transport timed out while waiting for rate limit availability (max retries: ${options.maxRetries})`,
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
logger.debug(`Request would be over rate limits, sleeping for ${options.msBetweenRetries}`)
|
|
100
|
+
await sleep(options.msBetweenRetries)
|
|
101
|
+
await this.waitUntilUnderRateLimit(options, retry + 1)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async setup(
|
|
105
|
+
req: AdapterRequest<AdapterParams>,
|
|
106
|
+
config: AdapterConfig<CustomSettings>,
|
|
107
|
+
): Promise<AdapterResponse<ProviderResponseBody> | undefined> {
|
|
108
|
+
if (this.config.options.coalescing) {
|
|
109
|
+
logger.debug('Setting up rest transport, setting request in flight in cache')
|
|
110
|
+
// TODO: Should this use a separate cache?
|
|
111
|
+
// TODO: Set viable ttl to approximate timeout from API
|
|
112
|
+
// TODO: Make this ttl configurable
|
|
113
|
+
await this.cache.set(this.inFlightPrefix + req.requestContext.cacheKey, true, 2000) // Can't use Infinity for things like Redis
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const request = await this.config.prepareRequest(req, config)
|
|
117
|
+
|
|
118
|
+
logger.trace('Check if we are under rate limits to perform request')
|
|
119
|
+
await this.waitUntilUnderRateLimit({
|
|
120
|
+
maxRetries: config.REST_TRANSPORT_MAX_RATE_LIMIT_RETRIES,
|
|
121
|
+
msBetweenRetries: config.REST_TRANSPORT_MS_BETWEEN_RATE_LIMIT_RETRIES,
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
logger.trace('Sending request to data provider...')
|
|
125
|
+
const providerResponse = await axiosRequest<ProviderRequestBody, ProviderResponseBody>(request)
|
|
126
|
+
|
|
127
|
+
logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`) // TODO: Sensitive data?
|
|
128
|
+
const parsedResponse = await this.config.parseResponse(req, providerResponse, config)
|
|
129
|
+
|
|
130
|
+
if (config.METRICS_ENABLED && config.EXPERIMENTAL_METRICS_ENABLED) {
|
|
131
|
+
// TODO: Potentially create function to add all telemetry data
|
|
132
|
+
parsedResponse.maxAge = Date.now() + config.CACHE_MAX_AGE
|
|
133
|
+
parsedResponse.meta = {
|
|
134
|
+
metrics: { feedId: req.requestContext.meta?.metrics?.feedId || 'N/A' },
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
logger.debug('Setting provider response in cache')
|
|
139
|
+
await this.cache.set(req.requestContext.cacheKey, parsedResponse, config.CACHE_MAX_AGE)
|
|
140
|
+
|
|
141
|
+
// Record cost of data provider call
|
|
142
|
+
const cost = rateLimitMetrics.retrieveCost(providerResponse.data)
|
|
143
|
+
rateLimitMetrics.rateLimitCreditsSpentTotal
|
|
144
|
+
.labels({
|
|
145
|
+
feed_id: req.requestContext.meta?.metrics?.feedId || 'N/A',
|
|
146
|
+
participant_id: req.requestContext.cacheKey,
|
|
147
|
+
})
|
|
148
|
+
.inc(cost)
|
|
149
|
+
|
|
150
|
+
// Update cacheHit flag in request meta for metrics use
|
|
151
|
+
req.requestContext.meta = {
|
|
152
|
+
...req.requestContext.meta,
|
|
153
|
+
metrics: { ...req.requestContext.meta?.metrics, cacheHit: false },
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// TODO: move this to a try/catch/finally
|
|
157
|
+
if (this.config.options.coalescing) {
|
|
158
|
+
logger.debug('Set provider response in cache, removing in flight from cache')
|
|
159
|
+
await this.cache.delete(this.inFlightPrefix)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return parsedResponse
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
|
|
2
|
+
import {
|
|
3
|
+
AdapterConnectionError,
|
|
4
|
+
AdapterDataProviderError,
|
|
5
|
+
AdapterError,
|
|
6
|
+
AdapterTimeoutError,
|
|
7
|
+
} from '../validation/error'
|
|
8
|
+
import * as transportMetrics from './metrics'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Performs axios request along with metrics recording and error handling
|
|
12
|
+
*
|
|
13
|
+
* @param request - axios request config
|
|
14
|
+
* @returns axios response for the request
|
|
15
|
+
*/
|
|
16
|
+
export async function axiosRequest<ProviderRequestBody, ProviderResponseBody>(
|
|
17
|
+
request: AxiosRequestConfig<ProviderRequestBody>,
|
|
18
|
+
): Promise<AxiosResponse<ProviderResponseBody>> {
|
|
19
|
+
const responseTimer = transportMetrics.dataProviderRequestDurationSeconds.startTimer()
|
|
20
|
+
let providerResponse: AxiosResponse<ProviderResponseBody>
|
|
21
|
+
try {
|
|
22
|
+
providerResponse = await axios.request<ProviderResponseBody>(request)
|
|
23
|
+
} catch (e: unknown) {
|
|
24
|
+
const error = e as AxiosError
|
|
25
|
+
// Request error
|
|
26
|
+
let providerStatusCode: number | undefined
|
|
27
|
+
let adapterError: AdapterError
|
|
28
|
+
if (error.code === 'ECONNABORTED') {
|
|
29
|
+
adapterError = new AdapterTimeoutError({})
|
|
30
|
+
providerStatusCode = error?.response?.status ?? 504
|
|
31
|
+
adapterError.name = 'Data Provider Request Timeout error'
|
|
32
|
+
} else if (error?.response?.status) {
|
|
33
|
+
adapterError = new AdapterDataProviderError({})
|
|
34
|
+
providerStatusCode = error?.response?.status
|
|
35
|
+
} else {
|
|
36
|
+
adapterError = new AdapterConnectionError({})
|
|
37
|
+
providerStatusCode = 0 // 0 -> connection error
|
|
38
|
+
}
|
|
39
|
+
// Record count of failed data provider request
|
|
40
|
+
transportMetrics.dataProviderRequests
|
|
41
|
+
.labels(transportMetrics.dataProviderMetricsLabel(providerStatusCode, request.method))
|
|
42
|
+
.inc()
|
|
43
|
+
|
|
44
|
+
adapterError.statusCode = 200
|
|
45
|
+
adapterError.providerStatusCode = providerStatusCode
|
|
46
|
+
adapterError.message = error?.message
|
|
47
|
+
adapterError.cause = error
|
|
48
|
+
adapterError.errorResponse = error?.response?.data
|
|
49
|
+
adapterError.url = request.url
|
|
50
|
+
|
|
51
|
+
throw adapterError
|
|
52
|
+
} finally {
|
|
53
|
+
// Record time taken for data provider request for success or failure
|
|
54
|
+
responseTimer()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Record count of successful data provider requests
|
|
58
|
+
transportMetrics.dataProviderRequests
|
|
59
|
+
.labels(transportMetrics.dataProviderMetricsLabel(providerResponse.status, request.method))
|
|
60
|
+
.inc()
|
|
61
|
+
|
|
62
|
+
return providerResponse
|
|
63
|
+
}
|