@chainlink/external-adapter-framework 0.0.14 → 0.0.15

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 (292) hide show
  1. package/.c8rc.json +3 -0
  2. package/.eslintignore +10 -0
  3. package/.eslintrc.js +96 -0
  4. package/.github/README.MD +42 -0
  5. package/.github/actions/setup/action.yaml +13 -0
  6. package/.github/workflows/label.yaml +39 -0
  7. package/.github/workflows/main.yaml +39 -0
  8. package/.github/workflows/publish.yaml +17 -0
  9. package/.prettierignore +13 -0
  10. package/.yarnrc +0 -0
  11. package/README.md +103 -0
  12. package/dist/examples/coingecko/test/e2e/adapter.test.ts.js +82953 -0
  13. package/dist/examples/coingecko/test/integration/adapter.test.ts.js +91672 -0
  14. package/dist/main.js +72703 -0
  15. package/docker-compose.yaml +35 -0
  16. package/env.sh +54 -0
  17. package/env2.sh +55 -0
  18. package/jest.config.js +5 -0
  19. package/package.json +14 -3
  20. package/publish.sh +0 -0
  21. package/src/adapter.ts +263 -0
  22. package/src/background-executor.ts +52 -0
  23. package/src/cache/factory.ts +26 -0
  24. package/src/cache/index.ts +258 -0
  25. package/src/cache/local.ts +73 -0
  26. package/src/cache/metrics.ts +112 -0
  27. package/src/cache/redis.ts +93 -0
  28. package/src/config/index.ts +517 -0
  29. package/src/config/provider-limits.ts +127 -0
  30. package/src/examples/bank-frick/README.MD +10 -0
  31. package/src/examples/bank-frick/accounts.ts +246 -0
  32. package/src/examples/bank-frick/config/index.ts +53 -0
  33. package/src/examples/bank-frick/index.ts +13 -0
  34. package/src/examples/bank-frick/types.d.ts +38 -0
  35. package/src/examples/bank-frick/util.ts +55 -0
  36. package/src/examples/coingecko/src/config/index.ts +12 -0
  37. package/src/examples/coingecko/src/config/overrides.json +10826 -0
  38. package/src/examples/coingecko/src/cryptoUtils.ts +88 -0
  39. package/src/examples/coingecko/src/endpoint/coins.ts +54 -0
  40. package/src/examples/coingecko/src/endpoint/crypto-marketcap.ts +66 -0
  41. package/src/examples/coingecko/src/endpoint/crypto-volume.ts +66 -0
  42. package/src/examples/coingecko/src/endpoint/crypto.ts +63 -0
  43. package/src/examples/coingecko/src/endpoint/dominance.ts +40 -0
  44. package/src/examples/coingecko/src/endpoint/global-marketcap.ts +40 -0
  45. package/src/examples/coingecko/src/endpoint/index.ts +6 -0
  46. package/src/examples/coingecko/src/globalUtils.ts +78 -0
  47. package/src/examples/coingecko/src/index.ts +17 -0
  48. package/src/examples/coingecko/test/e2e/adapter.test.ts +278 -0
  49. package/src/examples/coingecko/test/integration/__snapshots__/adapter.test.ts.snap +15 -0
  50. package/src/examples/coingecko/test/integration/adapter.test.ts +281 -0
  51. package/src/examples/coingecko/test/integration/capturedRequests.json +1 -0
  52. package/src/examples/coingecko/test/integration/fixtures.ts +42 -0
  53. package/src/examples/coingecko-old/batch-warming.ts +79 -0
  54. package/src/examples/coingecko-old/index.ts +9 -0
  55. package/src/examples/coingecko-old/rest.ts +77 -0
  56. package/src/examples/ncfx/config/index.ts +12 -0
  57. package/src/examples/ncfx/index.ts +9 -0
  58. package/src/examples/ncfx/websocket.ts +99 -0
  59. package/src/index.ts +149 -0
  60. package/src/metrics/constants.ts +23 -0
  61. package/src/metrics/index.ts +115 -0
  62. package/src/metrics/util.ts +18 -0
  63. package/src/rate-limiting/background/fixed-frequency.ts +45 -0
  64. package/src/rate-limiting/index.ts +100 -0
  65. package/src/rate-limiting/metrics.ts +18 -0
  66. package/src/rate-limiting/request/simple-counting.ts +76 -0
  67. package/src/transports/batch-warming.ts +127 -0
  68. package/src/transports/index.ts +152 -0
  69. package/src/transports/metrics.ts +95 -0
  70. package/src/transports/rest.ts +168 -0
  71. package/src/transports/util.ts +63 -0
  72. package/src/transports/websocket.ts +245 -0
  73. package/src/util/index.ts +23 -0
  74. package/src/util/logger.ts +69 -0
  75. package/src/util/recordRequests.ts +47 -0
  76. package/src/util/request.ts +117 -0
  77. package/src/util/subscription-set/expiring-sorted-set.ts +54 -0
  78. package/src/util/subscription-set/subscription-set.ts +35 -0
  79. package/src/util/test-payload-loader.ts +87 -0
  80. package/src/validation/error.ts +116 -0
  81. package/src/validation/index.ts +110 -0
  82. package/src/validation/input-params.ts +45 -0
  83. package/src/validation/override-functions.ts +44 -0
  84. package/src/validation/overrideFunctions.ts +44 -0
  85. package/src/validation/preset-tokens.json +23 -0
  86. package/src/validation/validator.ts +384 -0
  87. package/test/adapter.test.ts +27 -0
  88. package/test/background-executor.test.ts +108 -0
  89. package/test/cache/cache-key.test.ts +114 -0
  90. package/test/cache/helper.ts +100 -0
  91. package/test/cache/local.test.ts +54 -0
  92. package/test/cache/redis.test.ts +89 -0
  93. package/test/correlation.test.ts +114 -0
  94. package/test/index.test.ts +37 -0
  95. package/test/metrics/feed-id.test.ts +38 -0
  96. package/test/metrics/helper.ts +14 -0
  97. package/test/metrics/labels.test.ts +36 -0
  98. package/test/metrics/metrics.test.ts +267 -0
  99. package/test/metrics/redis-metrics.test.ts +113 -0
  100. package/test/metrics/warmer-metrics.test.ts +193 -0
  101. package/test/metrics/ws-metrics.test.ts +225 -0
  102. package/test/rate-limit-config.test.ts +242 -0
  103. package/test/smoke/smoke.test.ts +166 -0
  104. package/test/smoke/test-payload-fail.json +3 -0
  105. package/test/smoke/test-payload.js +22 -0
  106. package/test/smoke/test-payload.json +7 -0
  107. package/test/transports/batch.test.ts +466 -0
  108. package/test/transports/rest.test.ts +242 -0
  109. package/test/transports/websocket.test.ts +183 -0
  110. package/test/tsconfig.json +5 -0
  111. package/test/util.ts +77 -0
  112. package/test/validation.test.ts +178 -0
  113. package/test.sh +20 -0
  114. package/test2.sh +2 -0
  115. package/tsconfig.json +28 -0
  116. package/typedoc.json +6 -0
  117. package/webpack.config.js +57 -0
  118. package/yarn-error.log +3778 -0
  119. package/adapter.d.ts +0 -107
  120. package/adapter.js +0 -115
  121. package/background-executor.d.ts +0 -11
  122. package/background-executor.js +0 -45
  123. package/cache/factory.d.ts +0 -6
  124. package/cache/factory.js +0 -55
  125. package/cache/index.d.ts +0 -94
  126. package/cache/index.js +0 -173
  127. package/cache/local.d.ts +0 -23
  128. package/cache/local.js +0 -83
  129. package/cache/metrics.d.ts +0 -27
  130. package/cache/metrics.js +0 -120
  131. package/cache/redis.d.ts +0 -16
  132. package/cache/redis.js +0 -100
  133. package/chainlink-external-adapter-framework-0.0.6.tgz +0 -0
  134. package/config/index.d.ts +0 -209
  135. package/config/index.js +0 -380
  136. package/config/provider-limits.d.ts +0 -31
  137. package/config/provider-limits.js +0 -79
  138. package/examples/bank-frick/accounts.d.ts +0 -39
  139. package/examples/bank-frick/accounts.js +0 -191
  140. package/examples/bank-frick/config/index.d.ts +0 -4
  141. package/examples/bank-frick/config/index.js +0 -54
  142. package/examples/bank-frick/index.d.ts +0 -2
  143. package/examples/bank-frick/index.js +0 -14
  144. package/examples/bank-frick/util.d.ts +0 -4
  145. package/examples/bank-frick/util.js +0 -39
  146. package/examples/coingecko/batch-warming.d.ts +0 -2
  147. package/examples/coingecko/batch-warming.js +0 -52
  148. package/examples/coingecko/index.d.ts +0 -2
  149. package/examples/coingecko/index.js +0 -10
  150. package/examples/coingecko/rest.d.ts +0 -2
  151. package/examples/coingecko/rest.js +0 -50
  152. package/examples/ncfx/config/index.d.ts +0 -12
  153. package/examples/ncfx/config/index.js +0 -15
  154. package/examples/ncfx/index.d.ts +0 -2
  155. package/examples/ncfx/index.js +0 -10
  156. package/examples/ncfx/websocket.d.ts +0 -36
  157. package/examples/ncfx/websocket.js +0 -72
  158. package/index.d.ts +0 -11
  159. package/index.js +0 -133
  160. package/metrics/constants.d.ts +0 -16
  161. package/metrics/constants.js +0 -25
  162. package/metrics/index.d.ts +0 -15
  163. package/metrics/index.js +0 -122
  164. package/metrics/util.d.ts +0 -7
  165. package/metrics/util.js +0 -9
  166. package/package/adapter.d.ts +0 -88
  167. package/package/adapter.js +0 -112
  168. package/package/background-executor.d.ts +0 -11
  169. package/package/background-executor.js +0 -45
  170. package/package/cache/factory.d.ts +0 -6
  171. package/package/cache/factory.js +0 -57
  172. package/package/cache/index.d.ts +0 -90
  173. package/package/cache/index.js +0 -169
  174. package/package/cache/local.d.ts +0 -23
  175. package/package/cache/local.js +0 -83
  176. package/package/cache/metrics.d.ts +0 -27
  177. package/package/cache/metrics.js +0 -120
  178. package/package/cache/redis.d.ts +0 -16
  179. package/package/cache/redis.js +0 -100
  180. package/package/config/index.d.ts +0 -195
  181. package/package/config/index.js +0 -365
  182. package/package/config/provider-limits.d.ts +0 -31
  183. package/package/config/provider-limits.js +0 -76
  184. package/package/examples/coingecko/batch-warming.d.ts +0 -2
  185. package/package/examples/coingecko/batch-warming.js +0 -52
  186. package/package/examples/coingecko/index.d.ts +0 -2
  187. package/package/examples/coingecko/index.js +0 -10
  188. package/package/examples/coingecko/rest.d.ts +0 -2
  189. package/package/examples/coingecko/rest.js +0 -50
  190. package/package/examples/ncfx/config/index.d.ts +0 -12
  191. package/package/examples/ncfx/config/index.js +0 -15
  192. package/package/examples/ncfx/index.d.ts +0 -2
  193. package/package/examples/ncfx/index.js +0 -10
  194. package/package/examples/ncfx/websocket.d.ts +0 -36
  195. package/package/examples/ncfx/websocket.js +0 -72
  196. package/package/index.d.ts +0 -12
  197. package/package/index.js +0 -92
  198. package/package/metrics/constants.d.ts +0 -16
  199. package/package/metrics/constants.js +0 -25
  200. package/package/metrics/index.d.ts +0 -15
  201. package/package/metrics/index.js +0 -123
  202. package/package/metrics/util.d.ts +0 -3
  203. package/package/metrics/util.js +0 -9
  204. package/package/package.json +0 -72
  205. package/package/rate-limiting/background/fixed-frequency.d.ts +0 -10
  206. package/package/rate-limiting/background/fixed-frequency.js +0 -37
  207. package/package/rate-limiting/index.d.ts +0 -54
  208. package/package/rate-limiting/index.js +0 -63
  209. package/package/rate-limiting/metrics.d.ts +0 -3
  210. package/package/rate-limiting/metrics.js +0 -44
  211. package/package/rate-limiting/request/simple-counting.d.ts +0 -20
  212. package/package/rate-limiting/request/simple-counting.js +0 -62
  213. package/package/test.d.ts +0 -1
  214. package/package/test.js +0 -6
  215. package/package/transports/batch-warming.d.ts +0 -34
  216. package/package/transports/batch-warming.js +0 -101
  217. package/package/transports/index.d.ts +0 -87
  218. package/package/transports/index.js +0 -87
  219. package/package/transports/metrics.d.ts +0 -21
  220. package/package/transports/metrics.js +0 -105
  221. package/package/transports/rest.d.ts +0 -43
  222. package/package/transports/rest.js +0 -129
  223. package/package/transports/util.d.ts +0 -8
  224. package/package/transports/util.js +0 -85
  225. package/package/transports/websocket.d.ts +0 -80
  226. package/package/transports/websocket.js +0 -169
  227. package/package/util/expiring-sorted-set.d.ts +0 -21
  228. package/package/util/expiring-sorted-set.js +0 -47
  229. package/package/util/index.d.ts +0 -11
  230. package/package/util/index.js +0 -35
  231. package/package/util/logger.d.ts +0 -42
  232. package/package/util/logger.js +0 -62
  233. package/package/util/request.d.ts +0 -55
  234. package/package/util/request.js +0 -2
  235. package/package/validation/error.d.ts +0 -50
  236. package/package/validation/error.js +0 -79
  237. package/package/validation/index.d.ts +0 -5
  238. package/package/validation/index.js +0 -86
  239. package/package/validation/input-params.d.ts +0 -15
  240. package/package/validation/input-params.js +0 -30
  241. package/package/validation/override-functions.d.ts +0 -3
  242. package/package/validation/override-functions.js +0 -40
  243. package/package/validation/preset-tokens.json +0 -23
  244. package/package/validation/validator.d.ts +0 -47
  245. package/package/validation/validator.js +0 -303
  246. package/rate-limiting/background/fixed-frequency.d.ts +0 -10
  247. package/rate-limiting/background/fixed-frequency.js +0 -35
  248. package/rate-limiting/index.d.ts +0 -54
  249. package/rate-limiting/index.js +0 -63
  250. package/rate-limiting/metrics.d.ts +0 -3
  251. package/rate-limiting/metrics.js +0 -44
  252. package/rate-limiting/request/simple-counting.d.ts +0 -20
  253. package/rate-limiting/request/simple-counting.js +0 -62
  254. package/test.d.ts +0 -1
  255. package/test.js +0 -6
  256. package/transports/batch-warming.d.ts +0 -35
  257. package/transports/batch-warming.js +0 -101
  258. package/transports/index.d.ts +0 -70
  259. package/transports/index.js +0 -87
  260. package/transports/metrics.d.ts +0 -21
  261. package/transports/metrics.js +0 -105
  262. package/transports/rest.d.ts +0 -44
  263. package/transports/rest.js +0 -131
  264. package/transports/util.d.ts +0 -8
  265. package/transports/util.js +0 -85
  266. package/transports/websocket.d.ts +0 -81
  267. package/transports/websocket.js +0 -168
  268. package/util/expiring-sorted-set.d.ts +0 -21
  269. package/util/expiring-sorted-set.js +0 -47
  270. package/util/index.d.ts +0 -12
  271. package/util/index.js +0 -35
  272. package/util/logger.d.ts +0 -42
  273. package/util/logger.js +0 -62
  274. package/util/request.d.ts +0 -57
  275. package/util/request.js +0 -2
  276. package/util/subscription-set/expiring-sorted-set.d.ts +0 -22
  277. package/util/subscription-set/expiring-sorted-set.js +0 -47
  278. package/util/subscription-set/subscription-set.d.ts +0 -18
  279. package/util/subscription-set/subscription-set.js +0 -19
  280. package/util/test-payload-loader.d.ts +0 -25
  281. package/util/test-payload-loader.js +0 -83
  282. package/validation/error.d.ts +0 -50
  283. package/validation/error.js +0 -79
  284. package/validation/index.d.ts +0 -5
  285. package/validation/index.js +0 -91
  286. package/validation/input-params.d.ts +0 -15
  287. package/validation/input-params.js +0 -30
  288. package/validation/override-functions.d.ts +0 -3
  289. package/validation/override-functions.js +0 -40
  290. package/validation/preset-tokens.json +0 -23
  291. package/validation/validator.d.ts +0 -47
  292. package/validation/validator.js +0 -303
@@ -0,0 +1,258 @@
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
+ export * from './factory'
16
+
17
+ const logger = makeLogger('Cache')
18
+
19
+ /**
20
+ * An object describing an entry in the cache.
21
+ * @typeParam T - the type of the entry's value
22
+ */
23
+ export interface CacheEntry<T> {
24
+ key: string
25
+ value: T
26
+ }
27
+
28
+ /**
29
+ * Generic interface for a local or remote Cache.
30
+ * @typeParam T - the type of the cache entries' values
31
+ */
32
+ export interface Cache<T = unknown> {
33
+ /**
34
+ * Gets an item from the Cache.
35
+ *
36
+ * @param key - the key of the desired entry for which to fetch its value
37
+ * @returns a Promise of the entry's value, or undefined if not found / expired.
38
+ */
39
+ get: (key: string) => Promise<T | undefined>
40
+
41
+ /**
42
+ * Sets an item in the Cache.
43
+ *
44
+ * @param key - the key of the new entry
45
+ * @param value - the value of the new entry
46
+ * @param ttl - the time in milliseconds until the entry expires
47
+ * @returns an empty Promise that resolves when the entry has been set
48
+ */
49
+ set: (key: string, value: T, ttl: number) => Promise<void>
50
+
51
+ /**
52
+ * Sets a list of items in the Cache.
53
+ *
54
+ * @param entries - a list of cache entries
55
+ * @param ttl - the time in milliseconds until the entries expire
56
+ * @returns an empty Promise that resolves when all entries have been set
57
+ */
58
+ setMany: (entries: CacheEntry<T>[], ttl: number) => Promise<void>
59
+
60
+ /**
61
+ * Deletes the specified item from the Cache
62
+ *
63
+ * @param key - the key of the entry to be deleted
64
+ * @returns an empty Promise that resolves when the entry has been deleted
65
+ */
66
+ delete: (key: string) => Promise<void>
67
+ }
68
+
69
+ // Uses calculateKey to generate a unique key from the endpoint name, data, and input parameters
70
+ export const calculateCacheKey = (
71
+ {
72
+ adapterEndpoint,
73
+ adapterConfig,
74
+ }: {
75
+ adapterEndpoint: AdapterEndpoint
76
+ adapterConfig: AdapterConfig
77
+ },
78
+ data: unknown,
79
+ ): string => {
80
+ const paramNames = Object.keys(adapterEndpoint.inputParameters)
81
+ if (paramNames.length === 0) {
82
+ logger.trace(`Using default cache key ${adapterConfig.DEFAULT_CACHE_KEY}`)
83
+ return adapterConfig.DEFAULT_CACHE_KEY
84
+ }
85
+ return `${adapterEndpoint.name}-${calculateKey(data, paramNames, adapterConfig)}`
86
+ }
87
+
88
+ export const calculateFeedId = (
89
+ {
90
+ adapterEndpoint,
91
+ adapterConfig,
92
+ }: {
93
+ adapterEndpoint: AdapterEndpoint
94
+ adapterConfig: AdapterConfig
95
+ },
96
+ data: unknown,
97
+ ): string => {
98
+ const paramNames = Object.keys(adapterEndpoint.inputParameters)
99
+ if (paramNames.length === 0) {
100
+ logger.trace(`Cannot generate Feed ID without input parameters`)
101
+ return 'N/A'
102
+ }
103
+ return calculateKey(data, paramNames, adapterConfig)
104
+ }
105
+
106
+ /**
107
+ * Calculates a unique key from the provided data.
108
+ *
109
+ * @param data - the request data/body, i.e. the adapter input params
110
+ * @param paramNames - the keys from adapter endpoint input parameters
111
+ * @returns the calculated unique key
112
+ *
113
+ * @example
114
+ * ```
115
+ * calculateKey({ base: 'ETH', quote: 'BTC' }, ['base','quote'])
116
+ * // equals `|base:eth|quote:btc`
117
+ * ```
118
+ */
119
+ export const calculateKey = (
120
+ data: unknown,
121
+ paramNames: string[],
122
+ adapterConfig: AdapterConfig,
123
+ ): string => {
124
+ if (data && typeof data !== 'object') {
125
+ throw new Error('Data to calculate cache key should be an object')
126
+ }
127
+
128
+ const params = data as Record<string, unknown>
129
+
130
+ let cacheKey = ''
131
+ for (const paramName of paramNames) {
132
+ // Ignore overrides param when generating cache keys
133
+ if (paramName === 'overrides') {
134
+ continue
135
+ }
136
+ const param = params[paramName]
137
+ if (param === undefined) {
138
+ continue
139
+ }
140
+
141
+ cacheKey += `|${paramName}:`
142
+ switch (typeof param) {
143
+ case 'string':
144
+ cacheKey += param.toLowerCase()
145
+ break
146
+ case 'number':
147
+ case 'boolean':
148
+ cacheKey += param.toString()
149
+ break
150
+ case 'object':
151
+ // Force cache keys to only use performant properties of the input params.
152
+ // If the object were to be used, we'd have to sort its properties.
153
+ logger.debug(
154
+ `Property "${paramName}" in request parameters is of type object, and won't be used in the cacheKey`,
155
+ )
156
+ }
157
+ }
158
+
159
+ if (cacheKey.length > adapterConfig.MAX_COMMON_KEY_SIZE) {
160
+ logger.warn(
161
+ `Generated cache key for adapter request is bigger than the MAX_COMMON_KEY_SIZE and will be truncated`,
162
+ )
163
+ cacheKey = cacheKey.slice(0, adapterConfig.MAX_COMMON_KEY_SIZE)
164
+ }
165
+
166
+ logger.trace(`Generated cache key for request: "${cacheKey}"`)
167
+ return cacheKey
168
+ }
169
+
170
+ // Calculate the amount of time the non-expired entry has been in the cache
171
+ const calculateStaleness = (expirationTimestamp: number | undefined, ttl: number): number => {
172
+ if (expirationTimestamp) {
173
+ const createTimestamp = expirationTimestamp - ttl
174
+ return (Date.now() - createTimestamp) / 1000
175
+ } else {
176
+ // If expirationTimestamp is not available, staleness cannot be calculated
177
+ // Defaults to ttl for metrics purposes
178
+ return ttl
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Polls the provided Cache for an AdapterResponse set in the provided key. If the maximum
184
+ * amount of retries is exceeded, it returns undefined instead.
185
+ *
186
+ * @param cache - a Cache instance
187
+ * @param key - the key generated from an AdapterRequest that corresponds to the desired AdapterResponse
188
+ * @param retry - current retry, only for internal use
189
+ * @returns the AdapterResponse if found, else undefined
190
+ */
191
+ export const pollResponseFromCache = async (
192
+ cache: Cache<AdapterResponse>,
193
+ key: string,
194
+ options: {
195
+ maxRetries: number
196
+ sleep: number
197
+ },
198
+ retry = 0,
199
+ ): Promise<AdapterResponse | undefined> => {
200
+ if (retry > options.maxRetries) {
201
+ // Ideally this shouldn't happen often (p99 of reqs should be found in the cache)
202
+ logger.info('Exceeded max cache polling retries')
203
+ return undefined
204
+ }
205
+
206
+ logger.trace('Getting response from cache...')
207
+ const response = await cache.get(key)
208
+ if (response) {
209
+ logger.trace('Got response from cache')
210
+ return response
211
+ }
212
+
213
+ if (options.maxRetries === 0) {
214
+ logger.debug(`Response not found, retries disabled`)
215
+ return undefined
216
+ }
217
+
218
+ logger.debug(`Response not found, sleeping ${options.sleep} milliseconds...`)
219
+ await sleep(options.sleep)
220
+
221
+ return pollResponseFromCache(cache, key, options, retry + 1)
222
+ }
223
+
224
+ /**
225
+ * Given a Cache instance in the adapter dependencies, builds a middleware function that will perform
226
+ * a get from said Cache and return that if found; otherwise it'll continue the middleware chain.
227
+ *
228
+ * @param adapter - an initialized adapter
229
+ * @returns the cache middleware function
230
+ */
231
+ export const buildCacheMiddleware: AdapterMiddlewareBuilder =
232
+ (adapter: InitializedAdapter) => async (req: AdapterRequest, res: FastifyReply) => {
233
+ const response = await (adapter.dependencies.cache as Cache<AdapterResponse>).get(
234
+ req.requestContext.cacheKey,
235
+ )
236
+
237
+ if (response) {
238
+ logger.debug('Found response from cache, sending that')
239
+ if (adapter.config.METRICS_ENABLED && adapter.config.EXPERIMENTAL_METRICS_ENABLED) {
240
+ const label = cacheMetrics.cacheMetricsLabel(
241
+ req.requestContext.cacheKey,
242
+ req.requestContext.meta?.metrics?.feedId || 'N/A',
243
+ adapter.config.CACHE_TYPE,
244
+ )
245
+
246
+ // Record cache staleness and cache get count and value
247
+ const staleness = calculateStaleness(response.maxAge, adapter.config.CACHE_MAX_AGE)
248
+ cacheMetrics.cacheGet(label, response.result, staleness)
249
+ req.requestContext.meta = {
250
+ ...req.requestContext.meta,
251
+ metrics: { ...req.requestContext.meta?.metrics, cacheHit: true },
252
+ }
253
+ }
254
+ return res.send(response)
255
+ }
256
+
257
+ logger.debug('Did not find response in cache, moving to next middleware')
258
+ }
@@ -0,0 +1,73 @@
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
+ }
@@ -0,0 +1,112 @@
1
+ import * as client from 'prom-client'
2
+
3
+ interface CacheMetricsLabels {
4
+ participant_id: string
5
+ feed_id: string
6
+ cache_type: string
7
+ // Is_from_ws?: string
8
+ }
9
+
10
+ export const cacheGet = (label: CacheMetricsLabels, value: unknown, staleness: number) => {
11
+ if (typeof value === 'number' || typeof value === 'string') {
12
+ const parsedValue = Number(value)
13
+ if (!Number.isNaN(parsedValue) && Number.isFinite(parsedValue)) {
14
+ cacheDataGetValues.labels(label).set(parsedValue)
15
+ }
16
+ }
17
+ cacheDataGetCount.labels(label).inc()
18
+ cacheDataStalenessSeconds.labels(label).set(staleness)
19
+ }
20
+
21
+ export const cacheSet = (label: CacheMetricsLabels, maxAge: number) => {
22
+ cacheDataSetCount.labels(label).inc()
23
+ cacheDataMaxAge.labels(label).set(maxAge)
24
+ cacheDataStalenessSeconds.labels(label).set(0)
25
+ }
26
+
27
+ export const cacheMetricsLabel = (cacheKey: string, feedId: string, cacheType: string) => ({
28
+ participant_id: cacheKey,
29
+ feed_id: feedId,
30
+ cache_type: cacheType,
31
+ })
32
+
33
+ export enum CacheTypes {
34
+ Redis = 'redis',
35
+ Local = 'local',
36
+ }
37
+
38
+ export enum CMD_SENT_STATUS {
39
+ TIMEOUT = 'TIMEOUT',
40
+ FAIL = 'FAIL',
41
+ SUCCESS = 'SUCCESS',
42
+ }
43
+
44
+ const baseLabels = [
45
+ 'feed_id',
46
+ 'participant_id',
47
+ 'cache_type',
48
+ 'is_from_ws',
49
+ 'experimental',
50
+ ] as const
51
+
52
+ // Skipping this metrics for v3
53
+ // const cache_execution_duration_seconds = new client.Histogram({
54
+ // name: 'cache_execution_duration_seconds',
55
+ // help: 'A histogram bucket of the distribution of cache execution durations',
56
+ // labelNames: [...baseLabels, 'cache_hit'] as const,
57
+ // buckets: [0.01, 0.1, 1, 10],
58
+ // })
59
+
60
+ const cacheDataGetCount = new client.Counter({
61
+ name: 'cache_data_get_count',
62
+ help: 'A counter that increments every time a value is fetched from the cache',
63
+ labelNames: baseLabels,
64
+ })
65
+
66
+ const cacheDataGetValues = new client.Gauge({
67
+ name: 'cache_data_get_values',
68
+ help: 'A gauge keeping track of values being fetched from cache',
69
+ labelNames: baseLabels,
70
+ })
71
+
72
+ const cacheDataMaxAge = new client.Gauge({
73
+ name: 'cache_data_max_age',
74
+ help: 'A gauge tracking the max age of stored values in the cache',
75
+ labelNames: baseLabels,
76
+ })
77
+
78
+ const cacheDataSetCount = new client.Counter({
79
+ name: 'cache_data_set_count',
80
+ help: 'A counter that increments every time a value is set to the cache',
81
+ labelNames: [...baseLabels, 'status_code'],
82
+ })
83
+
84
+ const cacheDataStalenessSeconds = new client.Gauge({
85
+ name: 'cache_data_staleness_seconds',
86
+ help: 'Observes the staleness of the data returned',
87
+ labelNames: baseLabels,
88
+ })
89
+
90
+ // Redis Metrics
91
+ export const redisConnectionsOpen = new client.Counter({
92
+ name: 'redis_connections_open',
93
+ help: 'The number of redis connections that are open',
94
+ })
95
+
96
+ export const redisRetriesCount = new client.Counter({
97
+ name: 'redis_retries_count',
98
+ help: 'The number of retries that have been made to establish a redis connection',
99
+ })
100
+
101
+ export const redisCommandsSentCount = new client.Counter({
102
+ name: 'redis_commands_sent_count',
103
+ help: 'The number of redis commands sent',
104
+ labelNames: ['status', 'function_name'],
105
+ })
106
+
107
+ // Cache Warmer Metrics
108
+ export const cacheWarmerCount = new client.Gauge({
109
+ name: 'cache_warmer_get_count',
110
+ help: 'The number of cache warmers running',
111
+ labelNames: ['isBatched'] as const,
112
+ })
@@ -0,0 +1,93 @@
1
+ import Redis from 'ioredis'
2
+ import { AdapterResponse, makeLogger } from '../util'
3
+ import { Cache, CacheEntry } from './index'
4
+ import * as cacheMetrics from './metrics'
5
+
6
+ const logger = makeLogger('RedisCache')
7
+
8
+ /**
9
+ * Redis implementation of a Cache. It uses a simple js Object, storing entries with both
10
+ * a value and an expiration timestamp. Expired entries are deleted on reads (i.e. no background gc/upkeep).
11
+ *
12
+ * @typeParam T - the type for the entries' values
13
+ */
14
+ export class RedisCache<T = unknown> implements Cache<T> {
15
+ constructor(private client: Redis) {}
16
+
17
+ async get(key: string): Promise<T | undefined> {
18
+ logger.trace(`Getting key ${key}`)
19
+ const value = await this.client.get(key)
20
+
21
+ // Record get command sent to Redis
22
+ cacheMetrics.redisCommandsSentCount
23
+ .labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'get' })
24
+ .inc()
25
+
26
+ if (!value) {
27
+ logger.debug(`No entry in redis cache for key "${key}", returning undefined`)
28
+ return undefined
29
+ }
30
+
31
+ return JSON.parse(value) as T
32
+ }
33
+
34
+ async delete(key: string): Promise<void> {
35
+ logger.trace(`Deleting key ${key}`)
36
+ await this.client.del(key)
37
+
38
+ // Record delete command sent to Redis
39
+ cacheMetrics.redisCommandsSentCount
40
+ .labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'delete' })
41
+ .inc()
42
+ }
43
+
44
+ async set(key: string, value: T, ttl: number): Promise<void> {
45
+ logger.trace(`Setting key ${key}`)
46
+ await this.client.set(key, JSON.stringify(value), 'PX', ttl)
47
+
48
+ // Only record metrics if feed Id is present, otherwise assuming value is not adapter response to record
49
+ const feedId = (value as unknown as AdapterResponse).meta?.metrics?.feedId
50
+ if (feedId) {
51
+ // Record cache set count, max age, and staleness (set to 0 for cache set)
52
+ const label = cacheMetrics.cacheMetricsLabel(key, feedId, cacheMetrics.CacheTypes.Redis)
53
+ cacheMetrics.cacheSet(label, ttl)
54
+ }
55
+
56
+ // Record set command sent to Redis
57
+ cacheMetrics.redisCommandsSentCount
58
+ .labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'set' })
59
+ .inc()
60
+ }
61
+
62
+ async setMany(entries: CacheEntry<T>[], ttl: number): Promise<void> {
63
+ logger.trace(`Setting a bunch of keys`)
64
+ // Unfortunately, there's no ttl for mset
65
+ let chain = this.client.multi()
66
+
67
+ for (const entry of entries) {
68
+ chain = chain.set(entry.key, JSON.stringify(entry.value), 'PX', ttl)
69
+ }
70
+
71
+ await chain.exec()
72
+
73
+ // Loop again, but this time to record these in metrics
74
+ for (const entry of entries) {
75
+ // Only record metrics if feed Id is present, otherwise assuming value is not adapter response to record
76
+ const feedId = (entry.value as unknown as AdapterResponse).meta?.metrics?.feedId
77
+ if (feedId) {
78
+ // Record cache set count, max age, and staleness (set to 0 for cache set)
79
+ const label = cacheMetrics.cacheMetricsLabel(
80
+ entry.key,
81
+ feedId,
82
+ cacheMetrics.CacheTypes.Redis,
83
+ )
84
+ cacheMetrics.cacheSet(label, ttl)
85
+ }
86
+ }
87
+
88
+ // Record setMany command sent to Redis
89
+ cacheMetrics.redisCommandsSentCount
90
+ .labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'exec' })
91
+ .inc()
92
+ }
93
+ }