@chainlink/external-adapter-framework 0.0.15 → 0.0.16

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.
Files changed (183) hide show
  1. package/adapter.js +128 -0
  2. package/background-executor.js +45 -0
  3. package/cache/factory.js +58 -0
  4. package/cache/index.js +173 -0
  5. package/cache/local.js +83 -0
  6. package/cache/metrics.js +120 -0
  7. package/cache/redis.js +100 -0
  8. package/chainlink-external-adapter-framework-v0.0.6.tgz +0 -0
  9. package/config/index.js +366 -0
  10. package/config/provider-limits.js +74 -0
  11. package/examples/bank-frick/accounts.js +192 -0
  12. package/examples/bank-frick/config/index.js +54 -0
  13. package/examples/bank-frick/index.js +15 -0
  14. package/examples/bank-frick/util.js +39 -0
  15. package/examples/coingecko/src/config/index.js +13 -0
  16. package/examples/coingecko/src/config/overrides.json +10826 -0
  17. package/examples/coingecko/src/cryptoUtils.js +41 -0
  18. package/examples/coingecko/src/endpoint/coins.js +33 -0
  19. package/examples/coingecko/src/endpoint/crypto-marketcap.js +46 -0
  20. package/examples/coingecko/src/endpoint/crypto-volume.js +46 -0
  21. package/examples/coingecko/src/endpoint/crypto.js +47 -0
  22. package/examples/coingecko/src/endpoint/dominance.js +26 -0
  23. package/examples/coingecko/src/endpoint/global-marketcap.js +26 -0
  24. package/examples/coingecko/src/endpoint/index.js +15 -0
  25. package/examples/coingecko/src/globalUtils.js +48 -0
  26. package/examples/coingecko/src/index.js +14 -0
  27. package/examples/coingecko/test/e2e/adapter.test.js +262 -0
  28. package/examples/coingecko/test/integration/adapter.test.js +264 -0
  29. package/examples/coingecko/test/integration/capturedRequests.json +1 -0
  30. package/examples/coingecko/test/integration/fixtures.js +41 -0
  31. package/examples/coingecko-old/batch-warming.js +53 -0
  32. package/examples/coingecko-old/index.js +11 -0
  33. package/examples/coingecko-old/rest.js +51 -0
  34. package/examples/ncfx/config/index.js +15 -0
  35. package/examples/ncfx/index.js +11 -0
  36. package/examples/ncfx/websocket.js +73 -0
  37. package/index.js +127 -0
  38. package/metrics/constants.js +25 -0
  39. package/metrics/index.js +122 -0
  40. package/metrics/util.js +9 -0
  41. package/package.json +5 -15
  42. package/rate-limiting/background/fixed-frequency.js +35 -0
  43. package/rate-limiting/index.js +84 -0
  44. package/rate-limiting/metrics.js +44 -0
  45. package/rate-limiting/request/simple-counting.js +62 -0
  46. package/test.js +6 -0
  47. package/transports/batch-warming.js +101 -0
  48. package/transports/index.js +87 -0
  49. package/transports/metrics.js +105 -0
  50. package/transports/rest.js +138 -0
  51. package/transports/util.js +86 -0
  52. package/transports/websocket.js +166 -0
  53. package/util/index.js +35 -0
  54. package/util/logger.js +62 -0
  55. package/util/recordRequests.js +45 -0
  56. package/util/request.js +2 -0
  57. package/util/subscription-set/expiring-sorted-set.js +47 -0
  58. package/util/subscription-set/subscription-set.js +19 -0
  59. package/util/test-payload-loader.js +83 -0
  60. package/validation/error.js +79 -0
  61. package/validation/index.js +91 -0
  62. package/validation/input-params.js +30 -0
  63. package/validation/override-functions.js +40 -0
  64. package/validation/overrideFunctions.js +40 -0
  65. package/validation/preset-tokens.json +23 -0
  66. package/validation/validator.js +303 -0
  67. package/.c8rc.json +0 -3
  68. package/.eslintignore +0 -10
  69. package/.eslintrc.js +0 -96
  70. package/.github/README.MD +0 -42
  71. package/.github/actions/setup/action.yaml +0 -13
  72. package/.github/workflows/label.yaml +0 -39
  73. package/.github/workflows/main.yaml +0 -39
  74. package/.github/workflows/publish.yaml +0 -17
  75. package/.prettierignore +0 -13
  76. package/.yarnrc +0 -0
  77. package/README.md +0 -103
  78. package/dist/examples/coingecko/test/e2e/adapter.test.ts.js +0 -82953
  79. package/dist/examples/coingecko/test/integration/adapter.test.ts.js +0 -91672
  80. package/dist/main.js +0 -72703
  81. package/docker-compose.yaml +0 -35
  82. package/env.sh +0 -54
  83. package/env2.sh +0 -55
  84. package/jest.config.js +0 -5
  85. package/publish.sh +0 -0
  86. package/src/adapter.ts +0 -263
  87. package/src/background-executor.ts +0 -52
  88. package/src/cache/factory.ts +0 -26
  89. package/src/cache/index.ts +0 -258
  90. package/src/cache/local.ts +0 -73
  91. package/src/cache/metrics.ts +0 -112
  92. package/src/cache/redis.ts +0 -93
  93. package/src/config/index.ts +0 -517
  94. package/src/config/provider-limits.ts +0 -127
  95. package/src/examples/bank-frick/README.MD +0 -10
  96. package/src/examples/bank-frick/accounts.ts +0 -246
  97. package/src/examples/bank-frick/config/index.ts +0 -53
  98. package/src/examples/bank-frick/index.ts +0 -13
  99. package/src/examples/bank-frick/types.d.ts +0 -38
  100. package/src/examples/bank-frick/util.ts +0 -55
  101. package/src/examples/coingecko/src/config/index.ts +0 -12
  102. package/src/examples/coingecko/src/config/overrides.json +0 -10826
  103. package/src/examples/coingecko/src/cryptoUtils.ts +0 -88
  104. package/src/examples/coingecko/src/endpoint/coins.ts +0 -54
  105. package/src/examples/coingecko/src/endpoint/crypto-marketcap.ts +0 -66
  106. package/src/examples/coingecko/src/endpoint/crypto-volume.ts +0 -66
  107. package/src/examples/coingecko/src/endpoint/crypto.ts +0 -63
  108. package/src/examples/coingecko/src/endpoint/dominance.ts +0 -40
  109. package/src/examples/coingecko/src/endpoint/global-marketcap.ts +0 -40
  110. package/src/examples/coingecko/src/endpoint/index.ts +0 -6
  111. package/src/examples/coingecko/src/globalUtils.ts +0 -78
  112. package/src/examples/coingecko/src/index.ts +0 -17
  113. package/src/examples/coingecko/test/e2e/adapter.test.ts +0 -278
  114. package/src/examples/coingecko/test/integration/__snapshots__/adapter.test.ts.snap +0 -15
  115. package/src/examples/coingecko/test/integration/adapter.test.ts +0 -281
  116. package/src/examples/coingecko/test/integration/capturedRequests.json +0 -1
  117. package/src/examples/coingecko/test/integration/fixtures.ts +0 -42
  118. package/src/examples/coingecko-old/batch-warming.ts +0 -79
  119. package/src/examples/coingecko-old/index.ts +0 -9
  120. package/src/examples/coingecko-old/rest.ts +0 -77
  121. package/src/examples/ncfx/config/index.ts +0 -12
  122. package/src/examples/ncfx/index.ts +0 -9
  123. package/src/examples/ncfx/websocket.ts +0 -99
  124. package/src/index.ts +0 -149
  125. package/src/metrics/constants.ts +0 -23
  126. package/src/metrics/index.ts +0 -115
  127. package/src/metrics/util.ts +0 -18
  128. package/src/rate-limiting/background/fixed-frequency.ts +0 -45
  129. package/src/rate-limiting/index.ts +0 -100
  130. package/src/rate-limiting/metrics.ts +0 -18
  131. package/src/rate-limiting/request/simple-counting.ts +0 -76
  132. package/src/transports/batch-warming.ts +0 -127
  133. package/src/transports/index.ts +0 -152
  134. package/src/transports/metrics.ts +0 -95
  135. package/src/transports/rest.ts +0 -168
  136. package/src/transports/util.ts +0 -63
  137. package/src/transports/websocket.ts +0 -245
  138. package/src/util/index.ts +0 -23
  139. package/src/util/logger.ts +0 -69
  140. package/src/util/recordRequests.ts +0 -47
  141. package/src/util/request.ts +0 -117
  142. package/src/util/subscription-set/expiring-sorted-set.ts +0 -54
  143. package/src/util/subscription-set/subscription-set.ts +0 -35
  144. package/src/util/test-payload-loader.ts +0 -87
  145. package/src/validation/error.ts +0 -116
  146. package/src/validation/index.ts +0 -110
  147. package/src/validation/input-params.ts +0 -45
  148. package/src/validation/override-functions.ts +0 -44
  149. package/src/validation/overrideFunctions.ts +0 -44
  150. package/src/validation/preset-tokens.json +0 -23
  151. package/src/validation/validator.ts +0 -384
  152. package/test/adapter.test.ts +0 -27
  153. package/test/background-executor.test.ts +0 -108
  154. package/test/cache/cache-key.test.ts +0 -114
  155. package/test/cache/helper.ts +0 -100
  156. package/test/cache/local.test.ts +0 -54
  157. package/test/cache/redis.test.ts +0 -89
  158. package/test/correlation.test.ts +0 -114
  159. package/test/index.test.ts +0 -37
  160. package/test/metrics/feed-id.test.ts +0 -38
  161. package/test/metrics/helper.ts +0 -14
  162. package/test/metrics/labels.test.ts +0 -36
  163. package/test/metrics/metrics.test.ts +0 -267
  164. package/test/metrics/redis-metrics.test.ts +0 -113
  165. package/test/metrics/warmer-metrics.test.ts +0 -193
  166. package/test/metrics/ws-metrics.test.ts +0 -225
  167. package/test/rate-limit-config.test.ts +0 -242
  168. package/test/smoke/smoke.test.ts +0 -166
  169. package/test/smoke/test-payload-fail.json +0 -3
  170. package/test/smoke/test-payload.js +0 -22
  171. package/test/smoke/test-payload.json +0 -7
  172. package/test/transports/batch.test.ts +0 -466
  173. package/test/transports/rest.test.ts +0 -242
  174. package/test/transports/websocket.test.ts +0 -183
  175. package/test/tsconfig.json +0 -5
  176. package/test/util.ts +0 -77
  177. package/test/validation.test.ts +0 -178
  178. package/test.sh +0 -20
  179. package/test2.sh +0 -2
  180. package/tsconfig.json +0 -28
  181. package/typedoc.json +0 -6
  182. package/webpack.config.js +0 -57
  183. package/yarn-error.log +0 -3778
@@ -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
- })
@@ -1,76 +0,0 @@
1
- import { AdapterRateLimitTier, RateLimiter } from '..'
2
- import { AdapterEndpoint } from '../../adapter'
3
- import { makeLogger } from '../../util'
4
-
5
- const logger = makeLogger('SimpleCountingRateLimiter')
6
-
7
- /**
8
- * This rate limiter is the simplest stateful option.
9
- * On startup, it'll compare the different thresholds for each tier, calculate them all
10
- * in the finest window we'll use (seconds), and use the most restrictive one.
11
- * This is so if the EA were to restart, we don't need to worry about persisting state
12
- * for things like daily quotas. The downside is that this does not work well for bursty
13
- * loads or spikes, in cases where e.g. the per second limit is high but daily quotas low.
14
- */
15
- export class SimpleCountingRateLimiter implements RateLimiter {
16
- latestSecondInterval = 0
17
- requestsThisSecond = 0
18
- latestMinuteInterval = 0
19
- requestsThisMinute = 0
20
- perSecondLimit!: number
21
- perMinuteLimit!: number
22
-
23
- initialize(endpoints: AdapterEndpoint[], limits?: AdapterRateLimitTier) {
24
- // Translate the hourly limit into reqs per minute
25
- const perHourLimit = (limits?.rateLimit1h || Infinity) / 60
26
- this.perMinuteLimit = Math.min(limits?.rateLimit1m || Infinity, perHourLimit)
27
- this.perSecondLimit = limits?.rateLimit1s || Infinity
28
- logger.debug(
29
- `Using rate limiting settings: perMinute = ${this.perMinuteLimit} | perSecond: = ${this.perSecondLimit}`,
30
- )
31
-
32
- return this
33
- }
34
-
35
- isUnderLimits() {
36
- // If the limit is set to infinity, there was no tier limit specified
37
- if (this.perSecondLimit === Infinity && this.perMinuteLimit === Infinity) {
38
- return true
39
- }
40
-
41
- const now = Date.now()
42
- const nearestSecondInterval = Math.floor(now / 1000)
43
- const nearestMinuteInterval = Math.floor(now / (1000 * 60))
44
-
45
- // This should always run to completion, even if it doesn't look atomic; therefore the
46
- // Ops should be "thread safe". Thank JS and its infinite single threaded dumbness.
47
- if (nearestSecondInterval !== this.latestSecondInterval) {
48
- logger.trace(
49
- `Clearing latest second interval, # of requests logged was: ${this.requestsThisSecond} `,
50
- )
51
- this.latestSecondInterval = nearestSecondInterval
52
- this.requestsThisSecond = 0
53
- }
54
-
55
- if (nearestMinuteInterval !== this.latestMinuteInterval) {
56
- logger.trace(
57
- `Clearing latest second minute, # of requests logged was: ${this.requestsThisMinute} `,
58
- )
59
- this.latestMinuteInterval = nearestMinuteInterval
60
- this.requestsThisMinute = 0
61
- }
62
-
63
- if (
64
- this.requestsThisSecond < this.perSecondLimit &&
65
- this.requestsThisMinute < this.perMinuteLimit
66
- ) {
67
- logger.trace('Request under limits, counting +1')
68
- this.requestsThisSecond++
69
- this.requestsThisMinute++
70
- return true
71
- } else {
72
- logger.trace('Requests seen this interval are above limits')
73
- return false
74
- }
75
- }
76
- }
@@ -1,127 +0,0 @@
1
- import { AxiosRequestConfig, AxiosResponse } from 'axios'
2
- import { Cache } from '../cache'
3
- import { AdapterConfig, SettingsMap } from '../config'
4
- import { BackgroundExecuteRateLimiter } from '../rate-limiting'
5
- import { makeLogger, recordRequests, SubscriptionSet } from '../util'
6
- import { AdapterRequest, ProviderResult } from '../util/request'
7
- import { Transport, buildCacheEntriesFromResults } from './'
8
- import { axiosRequest } from './util'
9
- import * as rateLimitMetrics from '../rate-limiting/metrics'
10
- import * as cacheMetrics from '../cache/metrics'
11
- import { AdapterContext, AdapterDependencies } from '../adapter'
12
-
13
- const WARMUP_BATCH_REQUEST_ID = '9002'
14
-
15
- const logger = makeLogger('BatchWarmingTransport')
16
-
17
- /**
18
- * Transport implementation that takes incoming batches requests and keeps a warm cache of values.
19
- * Within the setup function, adapter params are added to an set that also keeps track and expires values.
20
- * In the background execute, the list of non-expired items in the set is fetched.
21
- * Then, the list is passed through the `prepareRequest` function, that returns an AxiosRequestConfig.
22
- * The Data Provider response is, they are passed through the `parseResponse` function to create a [[CacheEntry]] list.
23
- * Finally, the items in that [[CacheEntry]] list are set in the Cache so the Adapter can fetch values from there.
24
- *
25
- * @typeParam AdapterParams - interface for the adapter request body
26
- * @typeParam ProviderRequestBody - interface for the body of the request to the Data Provider
27
- * @typeParam ProviderResponseBody - interface for the body of the Data Provider's response
28
- */
29
- export class BatchWarmingTransport<
30
- AdapterParams,
31
- ProviderRequestBody,
32
- ProviderResponseBody,
33
- CustomSettings extends SettingsMap,
34
- > implements Transport<AdapterParams, ProviderResponseBody, CustomSettings>
35
- {
36
- cache!: Cache
37
- rateLimiter!: BackgroundExecuteRateLimiter
38
- subscriptionSet!: SubscriptionSet<AdapterParams>
39
-
40
- // Flag used to track whether the warmer has moved from having no entries to having some and vice versa
41
- // Used for recording the cache warmer active metrics accurately
42
- WARMER_ACTIVE = false
43
-
44
- constructor(
45
- private config: {
46
- prepareRequest: (
47
- params: AdapterParams[],
48
- context: AdapterContext<CustomSettings>,
49
- ) => AxiosRequestConfig<ProviderRequestBody>
50
- parseResponse: (
51
- params: AdapterParams[],
52
- res: AxiosResponse<ProviderResponseBody>,
53
- context: AdapterContext<CustomSettings>,
54
- ) => ProviderResult<AdapterParams>[]
55
- },
56
- ) {}
57
-
58
- async initialize(dependencies: AdapterDependencies): Promise<void> {
59
- this.cache = dependencies.cache
60
- this.rateLimiter = dependencies.backgroundExecuteRateLimiter
61
- this.subscriptionSet = dependencies.subscriptionSetFactory.buildSet()
62
- }
63
-
64
- async hasBeenSetUp(req: AdapterRequest<AdapterParams>): Promise<boolean> {
65
- return !!(await this.subscriptionSet.get(req.requestContext.cacheKey))
66
- }
67
-
68
- async setup(
69
- req: AdapterRequest<AdapterParams>,
70
- config: AdapterConfig<CustomSettings>,
71
- ): Promise<void> {
72
- logger.debug(
73
- `Adding entry to batch warming set: [${req.requestContext.cacheKey}] = ${req.requestContext.data}`,
74
- )
75
- await this.subscriptionSet.add(
76
- req.requestContext.cacheKey,
77
- req.requestContext.data,
78
- config.WARMUP_SUBSCRIPTION_TTL,
79
- )
80
- }
81
-
82
- async backgroundExecute(context: AdapterContext<CustomSettings>): Promise<number> {
83
- logger.debug('Starting background execute')
84
- const entries = await this.subscriptionSet.getAll()
85
-
86
- if (!entries.length) {
87
- logger.debug('No entries in batch warming set, skipping')
88
- if (this.WARMER_ACTIVE) {
89
- // Decrement count when warmer changed from having entries to having none
90
- cacheMetrics.cacheWarmerCount.labels({ isBatched: 'true' }).dec()
91
- this.WARMER_ACTIVE = false
92
- }
93
- return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name)
94
- } else if (this.WARMER_ACTIVE === false) {
95
- // Increment count when warmer changed from having no entries to having some
96
- cacheMetrics.cacheWarmerCount.labels({ isBatched: 'true' }).inc()
97
- this.WARMER_ACTIVE = true
98
- }
99
-
100
- const request = this.config.prepareRequest(entries, context)
101
-
102
- logger.trace('Sending request to data provider...')
103
- const providerResponse = await axiosRequest<ProviderRequestBody, ProviderResponseBody>(request)
104
-
105
- if (process.env['RECORD'] === 'true') {
106
- recordRequests(request, providerResponse)
107
- }
108
-
109
- logger.debug(`Got response from provider, parsing (raw body: ${providerResponse.data})`)
110
- const results = this.config.parseResponse(entries, providerResponse, context)
111
- const adapterResponses = buildCacheEntriesFromResults(results, context)
112
-
113
- logger.debug('Setting adapter responses in cache')
114
- await this.cache.setMany(adapterResponses, context.adapterConfig.CACHE_MAX_AGE)
115
-
116
- // Record cost of data provider call
117
- const cost = rateLimitMetrics.retrieveCost(providerResponse.data)
118
- rateLimitMetrics.rateLimitCreditsSpentTotal
119
- .labels({
120
- feed_id: 'N/A',
121
- participant_id: WARMUP_BATCH_REQUEST_ID,
122
- })
123
- .inc(cost)
124
-
125
- return this.rateLimiter.msUntilNextExecution(context.adapterEndpoint.name)
126
- }
127
- }
@@ -1,152 +0,0 @@
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
- }
@@ -1,95 +0,0 @@
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
- })