@chainlink/external-adapter-framework 0.0.6 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter.js +60 -0
- package/dist/background-executor.js +45 -0
- package/dist/cache/factory.js +57 -0
- package/dist/cache/index.js +163 -0
- package/dist/cache/local.js +83 -0
- package/dist/cache/metrics.js +114 -0
- package/dist/cache/redis.js +100 -0
- package/dist/config/index.js +364 -0
- package/dist/config/provider-limits.js +75 -0
- package/dist/examples/coingecko/batch-warming.js +52 -0
- package/dist/examples/coingecko/index.js +10 -0
- package/dist/examples/coingecko/rest.js +50 -0
- package/dist/examples/ncfx/config/index.js +15 -0
- package/dist/examples/ncfx/index.js +10 -0
- package/dist/examples/ncfx/websocket.js +72 -0
- package/dist/index.js +89 -0
- package/dist/metrics/constants.js +25 -0
- package/dist/metrics/index.js +76 -0
- package/dist/metrics/util.js +9 -0
- package/dist/rate-limiting/factory.js +33 -0
- package/dist/rate-limiting/index.js +36 -0
- package/dist/rate-limiting/metrics.js +32 -0
- package/dist/rate-limiting/nop-limiter.js +15 -0
- package/dist/rate-limiting/simple-counting.js +61 -0
- package/dist/src/adapter.js +112 -0
- package/dist/src/background-executor.js +45 -0
- package/dist/src/cache/factory.js +57 -0
- package/dist/src/cache/index.js +165 -0
- package/dist/src/cache/local.js +83 -0
- package/dist/src/cache/metrics.js +114 -0
- package/dist/src/cache/redis.js +100 -0
- package/dist/src/config/index.js +366 -0
- package/dist/src/config/provider-limits.js +75 -0
- package/dist/src/examples/bank-frick/accounts.js +191 -0
- package/dist/src/examples/bank-frick/config/index.js +45 -0
- package/dist/src/examples/bank-frick/index.js +14 -0
- package/dist/src/examples/bank-frick/util.js +39 -0
- package/dist/src/examples/coingecko/batch-warming.js +52 -0
- package/dist/src/examples/coingecko/index.js +10 -0
- package/dist/src/examples/coingecko/rest.js +50 -0
- package/dist/src/examples/ncfx/config/index.js +15 -0
- package/dist/src/examples/ncfx/index.js +10 -0
- package/dist/src/examples/ncfx/websocket.js +72 -0
- package/dist/src/index.js +89 -0
- package/dist/src/metrics/constants.js +25 -0
- package/dist/src/metrics/index.js +76 -0
- package/dist/src/metrics/util.js +9 -0
- package/dist/src/rate-limiting/background/fixed-frequency.js +37 -0
- package/dist/src/rate-limiting/index.js +63 -0
- package/dist/src/rate-limiting/metrics.js +32 -0
- package/dist/src/rate-limiting/request/simple-counting.js +62 -0
- package/dist/src/test.js +6 -0
- package/dist/src/transports/batch-warming.js +55 -0
- package/dist/src/transports/index.js +85 -0
- package/dist/src/transports/metrics.js +119 -0
- package/dist/src/transports/rest.js +93 -0
- package/dist/src/transports/util.js +85 -0
- package/dist/src/transports/websocket.js +175 -0
- package/dist/src/util/expiring-sorted-set.js +47 -0
- package/dist/src/util/index.js +35 -0
- package/dist/src/util/logger.js +62 -0
- package/dist/src/util/request.js +2 -0
- package/dist/src/validation/error.js +41 -0
- package/dist/src/validation/index.js +84 -0
- package/dist/src/validation/input-params.js +30 -0
- package/dist/src/validation/override-functions.js +40 -0
- package/dist/src/validation/preset-tokens.json +23 -0
- package/dist/src/validation/validator.js +303 -0
- package/dist/test.js +6 -0
- package/dist/transports/batch-warming.js +57 -0
- package/dist/transports/index.js +76 -0
- package/dist/transports/metrics.js +133 -0
- package/dist/transports/rest.js +91 -0
- package/dist/transports/util.js +85 -0
- package/dist/transports/websocket.js +171 -0
- package/dist/util/expiring-sorted-set.js +47 -0
- package/dist/util/index.js +35 -0
- package/dist/util/logger.js +62 -0
- package/dist/util/request.js +2 -0
- package/dist/validation/error.js +41 -0
- package/dist/validation/index.js +82 -0
- package/dist/validation/input-params.js +30 -0
- package/dist/validation/overrideFunctions.js +42 -0
- package/dist/validation/presetTokens.json +23 -0
- package/dist/validation/validator.js +303 -0
- package/package.json +6 -2
- package/.c8rc.json +0 -3
- package/.eslintignore +0 -9
- package/.eslintrc.js +0 -96
- package/.github/README.MD +0 -17
- package/.github/actions/setup/action.yaml +0 -13
- package/.github/workflows/main.yaml +0 -39
- package/.github/workflows/publish.yaml +0 -17
- package/.prettierignore +0 -13
- package/.yarnrc +0 -0
- package/docker-compose.yaml +0 -35
- package/src/adapter.ts +0 -236
- package/src/background-executor.ts +0 -53
- package/src/cache/factory.ts +0 -28
- package/src/cache/index.ts +0 -236
- package/src/cache/local.ts +0 -73
- package/src/cache/metrics.ts +0 -112
- package/src/cache/redis.ts +0 -93
- package/src/config/index.ts +0 -501
- package/src/config/provider-limits.ts +0 -130
- package/src/examples/coingecko/batch-warming.ts +0 -79
- package/src/examples/coingecko/index.ts +0 -9
- package/src/examples/coingecko/rest.ts +0 -77
- package/src/examples/ncfx/config/index.ts +0 -12
- package/src/examples/ncfx/index.ts +0 -9
- package/src/examples/ncfx/websocket.ts +0 -100
- package/src/index.ts +0 -106
- package/src/metrics/constants.ts +0 -23
- package/src/metrics/index.ts +0 -116
- package/src/metrics/util.ts +0 -11
- package/src/rate-limiting/background/fixed-frequency.ts +0 -47
- package/src/rate-limiting/index.ts +0 -100
- package/src/rate-limiting/metrics.ts +0 -18
- package/src/rate-limiting/request/simple-counting.ts +0 -76
- package/src/test.ts +0 -5
- package/src/transports/batch-warming.ts +0 -121
- package/src/transports/index.ts +0 -173
- package/src/transports/metrics.ts +0 -95
- package/src/transports/rest.ts +0 -161
- package/src/transports/util.ts +0 -63
- package/src/transports/websocket.ts +0 -238
- package/src/util/expiring-sorted-set.ts +0 -52
- package/src/util/index.ts +0 -20
- package/src/util/logger.ts +0 -69
- package/src/util/request.ts +0 -115
- package/src/validation/error.ts +0 -116
- package/src/validation/index.ts +0 -101
- package/src/validation/input-params.ts +0 -45
- package/src/validation/override-functions.ts +0 -44
- package/src/validation/preset-tokens.json +0 -23
- package/src/validation/validator.ts +0 -384
- package/test/adapter.test.ts +0 -27
- package/test/background-executor.test.ts +0 -109
- package/test/cache/cache-key.test.ts +0 -96
- package/test/cache/helper.ts +0 -101
- package/test/cache/local.test.ts +0 -54
- package/test/cache/redis.test.ts +0 -89
- package/test/correlation.test.ts +0 -114
- package/test/index.test.ts +0 -37
- package/test/metrics/feed-id.test.ts +0 -33
- package/test/metrics/helper.ts +0 -14
- package/test/metrics/labels.test.ts +0 -36
- package/test/metrics/metrics.test.ts +0 -267
- package/test/metrics/redis-metrics.test.ts +0 -113
- package/test/metrics/warmer-metrics.test.ts +0 -192
- package/test/metrics/ws-metrics.test.ts +0 -225
- package/test/rate-limit-config.test.ts +0 -243
- package/test/transports/batch.test.ts +0 -465
- package/test/transports/rest.test.ts +0 -242
- package/test/transports/websocket.test.ts +0 -183
- package/test/tsconfig.json +0 -5
- package/test/util.ts +0 -76
- package/test/validation.test.ts +0 -169
- package/test.sh +0 -20
- package/tsconfig.json +0 -24
- package/typedoc.json +0 -6
package/src/cache/index.ts
DELETED
|
@@ -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
|
-
}
|
package/src/cache/local.ts
DELETED
|
@@ -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
|
-
}
|
package/src/cache/metrics.ts
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
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
|
-
})
|
package/src/cache/redis.ts
DELETED
|
@@ -1,93 +0,0 @@
|
|
|
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
|
-
// TODO: Add error handling for redis command failures
|
|
15
|
-
export class RedisCache<T = unknown> implements Cache<T> {
|
|
16
|
-
constructor(private client: Redis) {}
|
|
17
|
-
|
|
18
|
-
async get(key: string): Promise<T | undefined> {
|
|
19
|
-
logger.trace(`Getting key ${key}`)
|
|
20
|
-
const value = await this.client.get(key)
|
|
21
|
-
|
|
22
|
-
// Record get command sent to Redis
|
|
23
|
-
cacheMetrics.redisCommandsSentCount
|
|
24
|
-
.labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'get' })
|
|
25
|
-
.inc()
|
|
26
|
-
|
|
27
|
-
if (!value) {
|
|
28
|
-
logger.debug(`No entry in redis cache for key "${key}", returning undefined`)
|
|
29
|
-
return undefined
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
return JSON.parse(value) as T // TODO: Check for invalid parsing
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
async delete(key: string): Promise<void> {
|
|
36
|
-
logger.trace(`Deleting key ${key}`)
|
|
37
|
-
await this.client.del(key)
|
|
38
|
-
|
|
39
|
-
// Record delete command sent to Redis
|
|
40
|
-
cacheMetrics.redisCommandsSentCount
|
|
41
|
-
.labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'delete' })
|
|
42
|
-
.inc()
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
async set(key: string, value: T, ttl: number): Promise<void> {
|
|
46
|
-
logger.trace(`Setting key ${key}`)
|
|
47
|
-
// TODO: Check for invalid stringify
|
|
48
|
-
await this.client.set(key, JSON.stringify(value), 'PX', ttl)
|
|
49
|
-
|
|
50
|
-
// Only record metrics if feed Id is present, otherwise assuming value is not adapter response to record
|
|
51
|
-
const feedId = (value as unknown as AdapterResponse).meta?.metrics?.feedId
|
|
52
|
-
if (feedId) {
|
|
53
|
-
// Record cache set count, max age, and staleness (set to 0 for cache set)
|
|
54
|
-
const label = cacheMetrics.cacheMetricsLabel(key, feedId, cacheMetrics.CacheTypes.Redis)
|
|
55
|
-
cacheMetrics.cacheSet(label, ttl)
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Record set command sent to Redis
|
|
59
|
-
cacheMetrics.redisCommandsSentCount
|
|
60
|
-
.labels({ status: cacheMetrics.CMD_SENT_STATUS.SUCCESS, function_name: 'set' })
|
|
61
|
-
.inc()
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
async setMany(entries: CacheEntry<T>[], ttl: number): Promise<void> {
|
|
65
|
-
logger.trace(`Setting a bunch of keys`)
|
|
66
|
-
// Unfortunately, there's no ttl for mset
|
|
67
|
-
let chain = this.client.multi()
|
|
68
|
-
|
|
69
|
-
for (const entry of entries) {
|
|
70
|
-
chain = chain.set(entry.key, JSON.stringify(entry.value), 'PX', ttl)
|
|
71
|
-
|
|
72
|
-
// TODO: Move to after error handling once implemented to avoid recording cache sets that failed
|
|
73
|
-
// Only record metrics if feed Id is present, otherwise assuming value is not adapter response to record
|
|
74
|
-
const feedId = (entry.value as unknown as AdapterResponse).meta?.metrics?.feedId
|
|
75
|
-
if (feedId) {
|
|
76
|
-
// Record cache set count, max age, and staleness (set to 0 for cache set)
|
|
77
|
-
const label = cacheMetrics.cacheMetricsLabel(
|
|
78
|
-
entry.key,
|
|
79
|
-
feedId,
|
|
80
|
-
cacheMetrics.CacheTypes.Redis,
|
|
81
|
-
)
|
|
82
|
-
cacheMetrics.cacheSet(label, ttl)
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
await chain.exec()
|
|
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
|
-
}
|