@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.
Files changed (237) hide show
  1. package/adapter.d.ts +88 -0
  2. package/adapter.js +112 -0
  3. package/background-executor.d.ts +11 -0
  4. package/background-executor.js +45 -0
  5. package/cache/factory.d.ts +6 -0
  6. package/cache/factory.js +57 -0
  7. package/cache/index.d.ts +90 -0
  8. package/cache/index.js +169 -0
  9. package/cache/local.d.ts +23 -0
  10. package/cache/local.js +83 -0
  11. package/cache/metrics.d.ts +27 -0
  12. package/cache/metrics.js +120 -0
  13. package/cache/redis.d.ts +16 -0
  14. package/cache/redis.js +100 -0
  15. package/chainlink-external-adapter-framework-v0.0.8.tgz +0 -0
  16. package/config/index.d.ts +195 -0
  17. package/config/index.js +365 -0
  18. package/config/provider-limits.d.ts +31 -0
  19. package/config/provider-limits.js +75 -0
  20. package/examples/coingecko/batch-warming.d.ts +2 -0
  21. package/examples/coingecko/batch-warming.js +52 -0
  22. package/examples/coingecko/index.d.ts +2 -0
  23. package/examples/coingecko/index.js +10 -0
  24. package/examples/coingecko/rest.d.ts +2 -0
  25. package/examples/coingecko/rest.js +50 -0
  26. package/examples/ncfx/config/index.d.ts +12 -0
  27. package/examples/ncfx/config/index.js +15 -0
  28. package/examples/ncfx/index.d.ts +2 -0
  29. package/examples/ncfx/index.js +10 -0
  30. package/examples/ncfx/websocket.d.ts +36 -0
  31. package/examples/ncfx/websocket.js +72 -0
  32. package/index.d.ts +12 -0
  33. package/index.js +92 -0
  34. package/metrics/constants.d.ts +16 -0
  35. package/metrics/constants.js +25 -0
  36. package/metrics/index.d.ts +15 -0
  37. package/metrics/index.js +123 -0
  38. package/metrics/util.d.ts +3 -0
  39. package/metrics/util.js +9 -0
  40. package/package/adapter.d.ts +88 -0
  41. package/package/adapter.js +112 -0
  42. package/package/background-executor.d.ts +11 -0
  43. package/package/background-executor.js +45 -0
  44. package/package/cache/factory.d.ts +6 -0
  45. package/package/cache/factory.js +57 -0
  46. package/package/cache/index.d.ts +90 -0
  47. package/package/cache/index.js +169 -0
  48. package/package/cache/local.d.ts +23 -0
  49. package/package/cache/local.js +83 -0
  50. package/package/cache/metrics.d.ts +27 -0
  51. package/package/cache/metrics.js +120 -0
  52. package/package/cache/redis.d.ts +16 -0
  53. package/package/cache/redis.js +100 -0
  54. package/package/config/index.d.ts +195 -0
  55. package/package/config/index.js +365 -0
  56. package/package/config/provider-limits.d.ts +31 -0
  57. package/package/config/provider-limits.js +75 -0
  58. package/package/examples/coingecko/batch-warming.d.ts +2 -0
  59. package/package/examples/coingecko/batch-warming.js +52 -0
  60. package/package/examples/coingecko/index.d.ts +2 -0
  61. package/package/examples/coingecko/index.js +10 -0
  62. package/package/examples/coingecko/rest.d.ts +2 -0
  63. package/package/examples/coingecko/rest.js +50 -0
  64. package/package/examples/ncfx/config/index.d.ts +12 -0
  65. package/package/examples/ncfx/config/index.js +15 -0
  66. package/package/examples/ncfx/index.d.ts +2 -0
  67. package/package/examples/ncfx/index.js +10 -0
  68. package/package/examples/ncfx/websocket.d.ts +36 -0
  69. package/package/examples/ncfx/websocket.js +72 -0
  70. package/package/index.d.ts +12 -0
  71. package/package/index.js +92 -0
  72. package/package/metrics/constants.d.ts +16 -0
  73. package/package/metrics/constants.js +25 -0
  74. package/package/metrics/index.d.ts +15 -0
  75. package/package/metrics/index.js +123 -0
  76. package/package/metrics/util.d.ts +3 -0
  77. package/package/metrics/util.js +9 -0
  78. package/package/package.json +69 -0
  79. package/package/rate-limiting/background/fixed-frequency.d.ts +10 -0
  80. package/package/rate-limiting/background/fixed-frequency.js +37 -0
  81. package/package/rate-limiting/index.d.ts +54 -0
  82. package/package/rate-limiting/index.js +63 -0
  83. package/package/rate-limiting/metrics.d.ts +3 -0
  84. package/package/rate-limiting/metrics.js +44 -0
  85. package/package/rate-limiting/request/simple-counting.d.ts +20 -0
  86. package/package/rate-limiting/request/simple-counting.js +62 -0
  87. package/package/test.d.ts +1 -0
  88. package/package/test.js +6 -0
  89. package/package/transports/batch-warming.d.ts +34 -0
  90. package/package/transports/batch-warming.js +101 -0
  91. package/package/transports/index.d.ts +87 -0
  92. package/package/transports/index.js +87 -0
  93. package/package/transports/metrics.d.ts +21 -0
  94. package/package/transports/metrics.js +105 -0
  95. package/package/transports/rest.d.ts +43 -0
  96. package/package/transports/rest.js +129 -0
  97. package/package/transports/util.d.ts +8 -0
  98. package/package/transports/util.js +85 -0
  99. package/package/transports/websocket.d.ts +80 -0
  100. package/package/transports/websocket.js +169 -0
  101. package/package/util/expiring-sorted-set.d.ts +21 -0
  102. package/package/util/expiring-sorted-set.js +47 -0
  103. package/package/util/index.d.ts +11 -0
  104. package/package/util/index.js +35 -0
  105. package/package/util/logger.d.ts +42 -0
  106. package/package/util/logger.js +62 -0
  107. package/package/util/request.d.ts +55 -0
  108. package/package/util/request.js +2 -0
  109. package/package/validation/error.d.ts +50 -0
  110. package/package/validation/error.js +79 -0
  111. package/package/validation/index.d.ts +5 -0
  112. package/package/validation/index.js +86 -0
  113. package/package/validation/input-params.d.ts +15 -0
  114. package/package/validation/input-params.js +30 -0
  115. package/package/validation/override-functions.d.ts +3 -0
  116. package/package/validation/override-functions.js +40 -0
  117. package/package/validation/preset-tokens.json +23 -0
  118. package/package/validation/validator.d.ts +47 -0
  119. package/package/validation/validator.js +303 -0
  120. package/package.json +1 -1
  121. package/rate-limiting/background/fixed-frequency.d.ts +10 -0
  122. package/rate-limiting/background/fixed-frequency.js +37 -0
  123. package/rate-limiting/index.d.ts +54 -0
  124. package/rate-limiting/index.js +63 -0
  125. package/rate-limiting/metrics.d.ts +3 -0
  126. package/rate-limiting/metrics.js +44 -0
  127. package/rate-limiting/request/simple-counting.d.ts +20 -0
  128. package/rate-limiting/request/simple-counting.js +62 -0
  129. package/test.d.ts +1 -0
  130. package/test.js +6 -0
  131. package/transports/batch-warming.d.ts +34 -0
  132. package/transports/batch-warming.js +101 -0
  133. package/transports/index.d.ts +87 -0
  134. package/transports/index.js +87 -0
  135. package/transports/metrics.d.ts +21 -0
  136. package/transports/metrics.js +105 -0
  137. package/transports/rest.d.ts +43 -0
  138. package/transports/rest.js +129 -0
  139. package/transports/util.d.ts +8 -0
  140. package/transports/util.js +85 -0
  141. package/transports/websocket.d.ts +80 -0
  142. package/transports/websocket.js +169 -0
  143. package/util/expiring-sorted-set.d.ts +21 -0
  144. package/util/expiring-sorted-set.js +47 -0
  145. package/util/index.d.ts +11 -0
  146. package/util/index.js +35 -0
  147. package/util/logger.d.ts +42 -0
  148. package/util/logger.js +62 -0
  149. package/util/request.d.ts +55 -0
  150. package/util/request.js +2 -0
  151. package/validation/error.d.ts +50 -0
  152. package/validation/error.js +79 -0
  153. package/validation/index.d.ts +5 -0
  154. package/validation/index.js +86 -0
  155. package/validation/input-params.d.ts +15 -0
  156. package/validation/input-params.js +30 -0
  157. package/validation/override-functions.d.ts +3 -0
  158. package/validation/override-functions.js +40 -0
  159. package/validation/preset-tokens.json +23 -0
  160. package/validation/validator.d.ts +47 -0
  161. package/validation/validator.js +303 -0
  162. package/.c8rc.json +0 -3
  163. package/.eslintignore +0 -9
  164. package/.eslintrc.js +0 -96
  165. package/.github/README.MD +0 -17
  166. package/.github/actions/setup/action.yaml +0 -13
  167. package/.github/workflows/main.yaml +0 -39
  168. package/.github/workflows/publish.yaml +0 -17
  169. package/.prettierignore +0 -13
  170. package/.yarnrc +0 -0
  171. package/README.md +0 -103
  172. package/docker-compose.yaml +0 -35
  173. package/src/adapter.ts +0 -236
  174. package/src/background-executor.ts +0 -53
  175. package/src/cache/factory.ts +0 -28
  176. package/src/cache/index.ts +0 -236
  177. package/src/cache/local.ts +0 -73
  178. package/src/cache/metrics.ts +0 -112
  179. package/src/cache/redis.ts +0 -93
  180. package/src/config/index.ts +0 -501
  181. package/src/config/provider-limits.ts +0 -130
  182. package/src/examples/coingecko/batch-warming.ts +0 -79
  183. package/src/examples/coingecko/index.ts +0 -9
  184. package/src/examples/coingecko/rest.ts +0 -77
  185. package/src/examples/ncfx/config/index.ts +0 -12
  186. package/src/examples/ncfx/index.ts +0 -9
  187. package/src/examples/ncfx/websocket.ts +0 -100
  188. package/src/index.ts +0 -106
  189. package/src/metrics/constants.ts +0 -23
  190. package/src/metrics/index.ts +0 -116
  191. package/src/metrics/util.ts +0 -11
  192. package/src/rate-limiting/background/fixed-frequency.ts +0 -47
  193. package/src/rate-limiting/index.ts +0 -100
  194. package/src/rate-limiting/metrics.ts +0 -18
  195. package/src/rate-limiting/request/simple-counting.ts +0 -76
  196. package/src/test.ts +0 -5
  197. package/src/transports/batch-warming.ts +0 -121
  198. package/src/transports/index.ts +0 -173
  199. package/src/transports/metrics.ts +0 -95
  200. package/src/transports/rest.ts +0 -161
  201. package/src/transports/util.ts +0 -63
  202. package/src/transports/websocket.ts +0 -238
  203. package/src/util/expiring-sorted-set.ts +0 -52
  204. package/src/util/index.ts +0 -20
  205. package/src/util/logger.ts +0 -69
  206. package/src/util/request.ts +0 -115
  207. package/src/validation/error.ts +0 -116
  208. package/src/validation/index.ts +0 -101
  209. package/src/validation/input-params.ts +0 -45
  210. package/src/validation/override-functions.ts +0 -44
  211. package/src/validation/preset-tokens.json +0 -23
  212. package/src/validation/validator.ts +0 -384
  213. package/test/adapter.test.ts +0 -27
  214. package/test/background-executor.test.ts +0 -109
  215. package/test/cache/cache-key.test.ts +0 -96
  216. package/test/cache/helper.ts +0 -101
  217. package/test/cache/local.test.ts +0 -54
  218. package/test/cache/redis.test.ts +0 -89
  219. package/test/correlation.test.ts +0 -114
  220. package/test/index.test.ts +0 -37
  221. package/test/metrics/feed-id.test.ts +0 -33
  222. package/test/metrics/helper.ts +0 -14
  223. package/test/metrics/labels.test.ts +0 -36
  224. package/test/metrics/metrics.test.ts +0 -267
  225. package/test/metrics/redis-metrics.test.ts +0 -113
  226. package/test/metrics/warmer-metrics.test.ts +0 -192
  227. package/test/metrics/ws-metrics.test.ts +0 -225
  228. package/test/rate-limit-config.test.ts +0 -243
  229. package/test/transports/batch.test.ts +0 -465
  230. package/test/transports/rest.test.ts +0 -242
  231. package/test/transports/websocket.test.ts +0 -183
  232. package/test/tsconfig.json +0 -5
  233. package/test/util.ts +0 -76
  234. package/test/validation.test.ts +0 -169
  235. package/test.sh +0 -20
  236. package/tsconfig.json +0 -24
  237. package/typedoc.json +0 -6
package/src/adapter.ts DELETED
@@ -1,236 +0,0 @@
1
- import { CacheFactory } from './cache/factory'
2
- import { AdapterConfig, BaseAdapterConfig, SettingsMap } from './config'
3
- import {
4
- AdapterRateLimitTier,
5
- FixedFrequencyRateLimiter,
6
- getRateLimitingTier,
7
- SimpleCountingRateLimiter,
8
- } from './rate-limiting'
9
- import { AdapterDependencies, Transport } from './transports'
10
- import { makeLogger } from './util'
11
- import { InputParameters } from './validation/input-params'
12
-
13
- const logger = makeLogger('Adapter')
14
-
15
- /**
16
- * Structure to describe rate limits specs for the Adapter
17
- */
18
- interface AdapterRateLimitingConfig {
19
- /** Adapter rate limits, gotten from the specific tier requested */
20
- tiers: Record<string, AdapterRateLimitTier>
21
- }
22
-
23
- /**
24
- * Main structure of an External Adapter
25
- */
26
- export interface Adapter {
27
- /** Name of the adapter */
28
- name: string
29
-
30
- /** If present, the string that will be used for requests with no specified endpoint */
31
- defaultEndpoint?: string
32
-
33
- /** List of [[AdapterEndpoint]]s in the adapter */
34
- endpoints: AdapterEndpoint[]
35
-
36
- /** Map of overrides to the default config values for an Adapter */
37
- envDefaultOverrides?: Partial<BaseAdapterConfig>
38
-
39
- /** List of custom env vars for this particular adapter (e.g. RPC_URL) */
40
- customSettings?: SettingsMap
41
-
42
- /** Configuration relevant to outbound (EA --\> DP) communication rate limiting */
43
- rateLimiting?: AdapterRateLimitingConfig
44
-
45
- /** Overrides for converting the 'base' parameter that are hardcoded into the adapter. */
46
- // This must be included in the middleware in order to generate deterministing cache keys for hardcoded overrides
47
- overrides?: Record<string, string>
48
- }
49
-
50
- /**
51
- * Structure to describe rate limits specs for a specific adapter endpoint
52
- */
53
- export interface EndpointRateLimitingConfig {
54
- /**
55
- * How much of the total limit for the adapter will be assigned to this specific endpoint.
56
- * Should be a non-zero positive number up to 100.
57
- * Endpoints in the same adapter without a specific allocation will divide the remaining limits equally.
58
- */
59
- allocationPercentage: number
60
- }
61
-
62
- /**
63
- * Structure to describe a specific endpoint in an [[Adapter]]
64
- */
65
- export interface AdapterEndpoint {
66
- /** Name that will be used to match input params to this endpoint (case insensitive) */
67
- name: string
68
-
69
- /** List of alternative endpoint names that will resolve to this same transport (case insensitive) */
70
- aliases?: string[]
71
-
72
- /** Transport that will be used to handle data processing and communication for this endpoint */
73
- transport: Transport<any, any, any>
74
-
75
- /** Specification of what the body of a request hitting this endpoint should look like (used for validation) */
76
- inputParameters: InputParameters
77
-
78
- /** Specific details related to the rate limiting for this endpoint in particular */
79
- rateLimiting?: EndpointRateLimitingConfig
80
- }
81
-
82
- /**
83
- * Structure to describe an adapter that has been initialized
84
- */
85
- export interface InitializedAdapter extends Adapter {
86
- /** Object containing alias translations for all endpoints */
87
- endpointsMap: Record<string, AdapterEndpoint>
88
-
89
- /** Initialized dependencies that the adapter will use */
90
- dependencies: AdapterDependencies
91
-
92
- /** Configuration params for various adapter properties */
93
- config: AdapterConfig
94
- }
95
-
96
- /**
97
- * This function will take an adapter structure and go through each endpoint, calculating
98
- * each one's allocation of the total rate limits that are set for the adapter as a whole.
99
- *
100
- * @param adapter - the adapter to initialize rate limiting for
101
- */
102
- const calculateRateLimitAllocations = (adapter: Adapter) => {
103
- const numberOfEndpoints = adapter.endpoints.length
104
- const endpointsWithExplicitAllocations = adapter.endpoints.filter((e) => e.rateLimiting)
105
-
106
- const totalExplicitAllocation = endpointsWithExplicitAllocations
107
- .map((e) => e.rateLimiting?.allocationPercentage || 0)
108
- .reduce((sum, next) => sum + next, 0)
109
-
110
- if (totalExplicitAllocation > 100) {
111
- throw new Error('The total allocation set for all endpoints summed cannot exceed 100%')
112
- }
113
-
114
- if (
115
- totalExplicitAllocation === 100 &&
116
- numberOfEndpoints - endpointsWithExplicitAllocations.length > 0
117
- ) {
118
- throw new Error(
119
- 'The explicit allocation is at 100% but there are endpoints with implicit allocation',
120
- )
121
- }
122
-
123
- const implicitAllocation = 100 - totalExplicitAllocation
124
-
125
- logger.debug('Adapter rate limit allocations:')
126
- for (const endpoint of adapter.endpoints) {
127
- if (!endpoint.rateLimiting) {
128
- endpoint.rateLimiting = {
129
- allocationPercentage:
130
- implicitAllocation / (numberOfEndpoints - endpointsWithExplicitAllocations.length),
131
- }
132
- }
133
-
134
- logger.debug(`Endpoint [${endpoint.name}] - ${endpoint.rateLimiting?.allocationPercentage}%`)
135
- }
136
- }
137
-
138
- /**
139
- * This function will process dependencies for an adapter, such as caches or rate limiters,
140
- * in order to inject them into transports and other relevant places later in the lifecycle.
141
- *
142
- * @param config - the configuration for this adapter
143
- * @param inputDependencies - a partial obj of initialized dependencies to override the created ones
144
- * @param rateLimitingConfig - details from the adapter regarding rate limiting
145
- * @returns a set of AdapterDependencies all initialized
146
- */
147
- export const initializeDependencies = (
148
- adapter: Adapter,
149
- config: AdapterConfig,
150
- inputDependencies?: Partial<AdapterDependencies>,
151
- ): AdapterDependencies => {
152
- const dependencies = inputDependencies || {}
153
- if (!dependencies.cache) {
154
- dependencies.cache = CacheFactory.buildCache(config)
155
- }
156
-
157
- // In the future we might want something more complex, but for now it's better to simplify
158
- // and just use the same rate limiting for everything. Once we have a more complex use case we
159
- // can think of ways to make this more configurable.
160
- const rateLimitingTier = getRateLimitingTier(
161
- adapter.rateLimiting?.tiers,
162
- config.RATE_LIMIT_API_TIER,
163
- )
164
- if (!dependencies.requestRateLimiter) {
165
- dependencies.requestRateLimiter = new SimpleCountingRateLimiter().initialize(
166
- adapter.endpoints,
167
- rateLimitingTier,
168
- )
169
- }
170
- if (!dependencies.backgroundExecuteRateLimiter) {
171
- dependencies.backgroundExecuteRateLimiter = new FixedFrequencyRateLimiter().initialize(
172
- adapter.endpoints,
173
- rateLimitingTier,
174
- )
175
- }
176
-
177
- return dependencies as AdapterDependencies
178
- }
179
-
180
- /**
181
- * Takes an adapter and normalizes all endpoint names and aliases, as well as the default endpoint.
182
- * i.e. makes them lowercase for now
183
- * @param adapter - an instance of an Adapter
184
- */
185
- const normalizeEndpointNames = (adapter: Adapter) => {
186
- // Make endpoints case insensitive, including default
187
- adapter.defaultEndpoint = adapter.defaultEndpoint?.toLowerCase()
188
-
189
- for (const endpoint of adapter.endpoints) {
190
- endpoint.name = endpoint.name.toLowerCase()
191
- endpoint.aliases = endpoint.aliases?.map((a) => a.toLowerCase())
192
- }
193
- }
194
-
195
- /**
196
- * Initializes all of the [[Transport]]s in the adapter, passing along any [[AdapterDependencies]] and [[AdapterConfig]].
197
- * Additionally, it builds a map out of all the endpoint names and aliases (checking for duplicates).
198
- *
199
- * @param adapter - an instance of an Adapter
200
- * @param dependencies - dependencies that the adapter will need at initialization
201
- * @param config - configuration variables already processed and validated
202
- * @returns - the adapter with all transports initialized and aliases map built
203
- */
204
- export const initializeAdapter = async (
205
- adapter: Adapter,
206
- config: AdapterConfig,
207
- dependencies?: Partial<AdapterDependencies>,
208
- ): Promise<InitializedAdapter> => {
209
- normalizeEndpointNames(adapter)
210
- calculateRateLimitAllocations(adapter)
211
- const initializedDependencies = initializeDependencies(adapter, config, dependencies)
212
-
213
- const endpointsMap: Record<string, AdapterEndpoint> = {}
214
-
215
- for (const endpoint of adapter.endpoints) {
216
- // Add aliases to map to use in validation
217
- const aliases = [endpoint.name, ...(endpoint.aliases || [])]
218
- for (const alias of aliases) {
219
- if (endpointsMap[alias]) {
220
- throw new Error(`Duplicate endpoint / alias: "${alias}"`)
221
- }
222
- endpointsMap[alias] = endpoint
223
- }
224
-
225
- logger.debug(`Initializing transport for endpoint "${endpoint.name}"...`)
226
- await endpoint.transport.initialize(initializedDependencies)
227
- }
228
-
229
- logger.debug('Adapter initialization complete.')
230
- return {
231
- ...adapter,
232
- endpointsMap,
233
- dependencies: initializedDependencies,
234
- config,
235
- }
236
- }
@@ -1,53 +0,0 @@
1
- import { Server } from 'http'
2
- import { InitializedAdapter } from './adapter'
3
- import { AdapterContext } from './transports'
4
- import { makeLogger, sleep } from './util'
5
-
6
- const logger = makeLogger('BackgroundExecutor')
7
-
8
- /**
9
- * Very simple background loop that will call the [[Transport.backgroundExecute]] functions in all Transports.
10
- * It gets the time in ms to wait as the return value from those functions, and sleeps until next execution.
11
- *
12
- * @param adapter - an initialized External Adapter
13
- * @param server - the http server to attach an on close listener to
14
- */
15
- export async function callBackgroundExecutes(adapter: InitializedAdapter, server?: Server) {
16
- // Set up variable to check later on to see if we need to stop this background "thread"
17
- // If no server is provided, the listener won't be set and serverClosed will always be false
18
- let serverClosed = false
19
- server?.on('close', () => {
20
- serverClosed = true
21
- })
22
-
23
- for (const endpoint of adapter.endpoints) {
24
- const backgroundExecute = endpoint.transport.backgroundExecute?.bind(endpoint.transport)
25
- if (!backgroundExecute) {
26
- logger.debug(`Endpoint "${endpoint.name}" has no background execute, skipping...`)
27
- continue
28
- }
29
-
30
- const context: AdapterContext = {
31
- adapterEndpoint: endpoint,
32
- adapterConfig: adapter.config,
33
- }
34
-
35
- const handler = async () => {
36
- if (serverClosed) {
37
- logger.info('Server closed, stopping recursive backgroundExecute handler chain')
38
- return
39
- }
40
-
41
- logger.debug(`Calling background execute for endpoint "${endpoint.name}"`)
42
- const timeToWait = await backgroundExecute(context)
43
- logger.debug(
44
- `Finished background execute for endpoint "${endpoint.name}", sleeping for ${timeToWait}ms`,
45
- )
46
- await sleep(timeToWait)
47
- handler()
48
- }
49
-
50
- // Start recursive async calls
51
- handler()
52
- }
53
- }
@@ -1,28 +0,0 @@
1
- import Redis from 'ioredis'
2
- import { AdapterConfig } from '../config'
3
- import { makeLogger } from '../util'
4
- import { LocalCache } from './local'
5
- import * as cacheMetrics from './metrics'
6
- import { RedisCache } from './redis'
7
-
8
- const logger = makeLogger('CacheFactory')
9
- export class CacheFactory {
10
- static buildCache(config: AdapterConfig) {
11
- logger.info(`Using "${config.CACHE_TYPE}" cache.`)
12
- if (config.CACHE_TYPE === 'local') {
13
- return new LocalCache()
14
- } else if (config.CACHE_TYPE === 'redis') {
15
- const redis = new Redis({
16
- enableAutoPipelining: true, // This will make multiple commands be batch automatically
17
- host: config.CACHE_REDIS_HOST,
18
- port: config.CACHE_REDIS_PORT,
19
- })
20
- redis.on('connect', () => {
21
- cacheMetrics.redisConnectionsOpen.inc()
22
- })
23
- // TODO: Maybe track active redis connections instead of just total count of connections created
24
- // Use a Gauge and track with a combo of connect/end events listeners
25
- return new RedisCache(redis)
26
- }
27
- }
28
- }
@@ -1,236 +0,0 @@
1
- import { FastifyReply } from 'fastify'
2
- import { AdapterEndpoint, InitializedAdapter } from '../adapter'
3
- import { AdapterConfig } from '../config'
4
- import {
5
- AdapterMiddlewareBuilder,
6
- AdapterRequest,
7
- AdapterResponse,
8
- makeLogger,
9
- sleep,
10
- } from '../util'
11
- import * as cacheMetrics from './metrics'
12
-
13
- export * from './local'
14
- export * from './redis'
15
-
16
- const logger = makeLogger('Cache')
17
-
18
- /**
19
- * An object describing an entry in the cache.
20
- * @typeParam T - the type of the entry's value
21
- */
22
- export interface CacheEntry<T> {
23
- key: string
24
- value: T
25
- }
26
-
27
- /**
28
- * Generic interface for a local or remote Cache.
29
- * @typeParam T - the type of the cache entries' values
30
- */
31
- export interface Cache<T = unknown> {
32
- /**
33
- * Gets an item from the Cache.
34
- *
35
- * @param key - the key of the desired entry for which to fetch its value
36
- * @returns a Promise of the entry's value, or undefined if not found / expired.
37
- */
38
- get: (key: string) => Promise<T | undefined>
39
-
40
- /**
41
- * Sets an item in the Cache.
42
- *
43
- * @param key - the key of the new entry
44
- * @param value - the value of the new entry
45
- * @param ttl - the time in milliseconds until the entry expires
46
- * @returns an empty Promise that resolves when the entry has been set
47
- */
48
- set: (key: string, value: T, ttl: number) => Promise<void>
49
-
50
- /**
51
- * Sets a list of items in the Cache.
52
- *
53
- * @param entries - a list of cache entries
54
- * @param ttl - the time in milliseconds until the entries expire
55
- * @returns an empty Promise that resolves when all entries have been set
56
- */
57
- setMany: (entries: CacheEntry<T>[], ttl: number) => Promise<void>
58
-
59
- /**
60
- * Deletes the specified item from the Cache
61
- *
62
- * @param key - the key of the entry to be deleted
63
- * @returns an empty Promise that resolves when the entry has been deleted
64
- */
65
- delete: (key: string) => Promise<void>
66
- }
67
-
68
- // Uses calculateKey to generate a unique key from the endpoint name, data, and input parameters
69
- export const calculateCacheKey = (
70
- {
71
- adapterEndpoint,
72
- adapterConfig,
73
- }: {
74
- adapterEndpoint: AdapterEndpoint
75
- adapterConfig: AdapterConfig
76
- },
77
- data: unknown,
78
- ): string => {
79
- const paramNames = Object.keys(adapterEndpoint.inputParameters)
80
- if (paramNames.length === 0) {
81
- logger.trace(`Using default cache key ${adapterConfig.DEFAULT_CACHE_KEY}`)
82
- return adapterConfig.DEFAULT_CACHE_KEY
83
- }
84
- return `${adapterEndpoint.name}-${calculateKey(data, paramNames)}`
85
- }
86
-
87
- export const calculateFeedId = (adapterEndpoint: AdapterEndpoint, data: unknown): string => {
88
- const paramNames = Object.keys(adapterEndpoint.inputParameters)
89
- if (paramNames.length === 0) {
90
- logger.trace(`Cannot generate Feed ID without input parameters`)
91
- return 'N/A'
92
- }
93
- return calculateKey(data, paramNames)
94
- }
95
-
96
- /**
97
- * Calculates a unique key from the provided data.
98
- *
99
- * @param data - the request data/body, i.e. the adapter input params
100
- * @param paramNames - the keys from adapter endpoint input parameters
101
- * @returns the calculated unique key
102
- *
103
- * @example
104
- * ```
105
- * calculateKey({ base: 'ETH', quote: 'BTC' }, ['base','quote'])
106
- * // equals `|base:eth|quote:btc`
107
- * ```
108
- */
109
- export const calculateKey = (data: unknown, paramNames: string[]): string => {
110
- if (data && typeof data !== 'object') {
111
- throw new Error('Data to calculate cache key should be an object')
112
- }
113
-
114
- const params = data as Record<string, unknown>
115
-
116
- let cacheKey = '' // TODO: Maybe there's a faster String Builder
117
- for (const paramName of paramNames) {
118
- // Ignore overrides param when generating cache keys
119
- // TODO: expand support for ignoring `includes` and `tokenOverrides` params when generating keys
120
- if (paramName === 'overrides') {
121
- continue
122
- }
123
- const param = params[paramName]
124
- if (param === undefined) {
125
- continue
126
- }
127
-
128
- cacheKey += `|${paramName}:`
129
- switch (typeof param) {
130
- case 'string':
131
- cacheKey += param.toLowerCase()
132
- break
133
- case 'number':
134
- case 'boolean':
135
- cacheKey += param.toString()
136
- break
137
- case 'object':
138
- // TODO: Implement object sorting for deterministic cache key generation
139
- cacheKey += JSON.stringify(param)
140
- }
141
- }
142
-
143
- // TODO: Check max size, potential issue
144
- logger.trace(`Generated cache key for request: "${cacheKey}"`)
145
- return cacheKey
146
- }
147
-
148
- // Calculate the amount of time the non-expired entry has been in the cache
149
- const calculateStaleness = (expirationTimestamp: number | undefined, ttl: number): number => {
150
- if (expirationTimestamp) {
151
- const createTimestamp = expirationTimestamp - ttl
152
- return (Date.now() - createTimestamp) / 1000
153
- } else {
154
- // If expirationTimestamp is not available, staleness cannot be calculated
155
- // Defaults to ttl for metrics purposes
156
- return ttl
157
- }
158
- }
159
-
160
- /**
161
- * Polls the provided Cache for an AdapterResponse set in the provided key. If the maximum
162
- * amount of retries is exceeded, it returns undefined instead.
163
- *
164
- * @param cache - a Cache instance
165
- * @param key - the key generated from an AdapterRequest that corresponds to the desired AdapterResponse
166
- * @param retry - current retry, only for internal use
167
- * @returns the AdapterResponse if found, else undefined
168
- */
169
- export const pollResponseFromCache = async (
170
- cache: Cache<AdapterResponse>,
171
- key: string,
172
- options: {
173
- maxRetries: number
174
- sleep: number
175
- },
176
- retry = 0,
177
- ): Promise<AdapterResponse | undefined> => {
178
- if (retry > options.maxRetries) {
179
- // Ideally this shouldn't happen often (p99 of reqs should be found in the cache)
180
- logger.info('Exceeded max cache polling retries')
181
- return undefined
182
- }
183
-
184
- logger.trace('Getting response from cache...')
185
- const response = await cache.get(key)
186
- if (response) {
187
- logger.trace('Got response from cache')
188
- return response
189
- }
190
-
191
- if (options.maxRetries === 0) {
192
- logger.debug(`Response not found, retries disabled`)
193
- return undefined
194
- }
195
-
196
- logger.debug(`Response not found, sleeping ${options.sleep} milliseconds...`)
197
- await sleep(options.sleep)
198
-
199
- return pollResponseFromCache(cache, key, options, retry + 1)
200
- }
201
-
202
- /**
203
- * Given a Cache instance in the adapter dependencies, builds a middleware function that will perform
204
- * a get from said Cache and return that if found; otherwise it'll continue the middleware chain.
205
- *
206
- * @param adapter - an initialized adapter
207
- * @returns the cache middleware function
208
- */
209
- export const buildCacheMiddleware: AdapterMiddlewareBuilder =
210
- (adapter: InitializedAdapter) => async (req: AdapterRequest, res: FastifyReply) => {
211
- const response = await (adapter.dependencies.cache as Cache<AdapterResponse>).get(
212
- req.requestContext.cacheKey,
213
- )
214
-
215
- if (response) {
216
- logger.debug('Found response from cache, sending that')
217
- if (adapter.config.METRICS_ENABLED && adapter.config.EXPERIMENTAL_METRICS_ENABLED) {
218
- const label = cacheMetrics.cacheMetricsLabel(
219
- req.requestContext.cacheKey,
220
- req.requestContext.meta?.metrics?.feedId || 'N/A',
221
- adapter.config.CACHE_TYPE,
222
- )
223
-
224
- // Record cache staleness and cache get count and value
225
- const staleness = calculateStaleness(response.maxAge, adapter.config.CACHE_MAX_AGE)
226
- cacheMetrics.cacheGet(label, response.result, staleness)
227
- req.requestContext.meta = {
228
- ...req.requestContext.meta,
229
- metrics: { ...req.requestContext.meta?.metrics, cacheHit: true },
230
- }
231
- }
232
- return res.send(response)
233
- }
234
-
235
- logger.debug('Did not find response in cache, moving to next middleware')
236
- }
@@ -1,73 +0,0 @@
1
- import { AdapterResponse, makeLogger } from '../util'
2
- import { Cache, CacheEntry } from './index'
3
- import * as cacheMetrics from './metrics'
4
-
5
- const logger = makeLogger('LocalCache')
6
-
7
- /**
8
- * Type for a value stored in a LocalCache entry.
9
- *
10
- * @typeParam T - the type for the entry's value
11
- */
12
- export interface LocalCacheEntry<T> {
13
- expirationTimestamp: number
14
- value: T
15
- }
16
-
17
- /**
18
- * Local implementation of a Cache. It uses a simple js Object, storing entries with both
19
- * a value and an expiration timestamp. Expired entries are deleted on reads (i.e. no background gc/upkeep).
20
- *
21
- * @typeParam T - the type for the entries' values
22
- */
23
- export class LocalCache<T = unknown> implements Cache<T> {
24
- store: Record<string, LocalCacheEntry<T>> = {}
25
-
26
- async get(key: string): Promise<T | undefined> {
27
- logger.trace(`Getting key ${key}`)
28
- const entry = this.store[key]
29
-
30
- if (!entry) {
31
- logger.debug(`No entry in local cache for key "${key}", returning undefined`)
32
- return undefined
33
- }
34
-
35
- const expired = entry.expirationTimestamp <= Date.now()
36
- if (expired) {
37
- logger.debug('Entry in local cache expired, deleting and returning undefined')
38
- this.delete(key)
39
- return undefined
40
- } else {
41
- logger.debug('Found valid entry in local cache, returning value')
42
- return entry.value
43
- }
44
- }
45
-
46
- async delete(key: string): Promise<void> {
47
- logger.trace(`Deleting key ${key}`)
48
- delete this.store[key] // Deletes are slower than ignoring or setting null, fyi
49
- }
50
-
51
- async set(key: string, value: T, ttl: number): Promise<void> {
52
- logger.trace(`Setting key ${key} with ttl ${ttl}`)
53
- this.store[key] = {
54
- value,
55
- expirationTimestamp: Date.now() + ttl,
56
- }
57
-
58
- // Only record metrics if feed Id is present, otherwise assuming value is not adapter response to record
59
- const feedId = (value as unknown as AdapterResponse).meta?.metrics?.feedId
60
- if (feedId){
61
- // Record cache set count, max age, and staleness (set to 0 for cache set)
62
- const label = cacheMetrics.cacheMetricsLabel(key, feedId, cacheMetrics.CacheTypes.Local)
63
- cacheMetrics.cacheSet(label, ttl)
64
- }
65
- }
66
-
67
- async setMany(entries: CacheEntry<T>[], ttl: number): Promise<void> {
68
- logger.trace(`Setting a bunch of keys with ttl ${ttl}`)
69
- for (const { key, value } of entries) {
70
- this.set(key, value, ttl)
71
- }
72
- }
73
- }