|
| 1 | +import { AdapterDependencies } from '../../adapter' |
| 2 | +import { AdapterSettings } from '../../config' |
| 3 | +import { |
| 4 | + AdapterResponse, |
| 5 | + makeLogger, |
| 6 | + ResponseGenerics, |
| 7 | + TimestampedAdapterResponse, |
| 8 | + TimestampedProviderResult, |
| 9 | + censor, |
| 10 | + censorLogs, |
| 11 | + TimestampedProviderErrorResponse, |
| 12 | +} from '../../util' |
| 13 | +import { |
| 14 | + InputParameters, |
| 15 | + InputParametersDefinition, |
| 16 | + TypeFromDefinition, |
| 17 | +} from '../../validation/input-params' |
| 18 | +import { Cache, calculateAdapterName, calculateCacheKey, calculateFeedId } from '../' |
| 19 | +import CensorList from '../../util/censor/censor-list' |
| 20 | +import { validator } from '../../validation/utils' |
| 21 | + |
| 22 | +const logger = makeLogger('ResponseCache') |
| 23 | + |
| 24 | +export abstract class ResponseCache< |
| 25 | + T extends { Parameters: InputParametersDefinition; Response: ResponseGenerics }, |
| 26 | +> { |
| 27 | + cache: Cache<AdapterResponse<T['Response']>> |
| 28 | + inputParameters: InputParameters<T['Parameters']> |
| 29 | + adapterName: string |
| 30 | + endpointName: string |
| 31 | + adapterSettings: AdapterSettings |
| 32 | + dependencies: AdapterDependencies |
| 33 | + |
| 34 | + constructor({ |
| 35 | + inputParameters, |
| 36 | + adapterName, |
| 37 | + endpointName, |
| 38 | + adapterSettings, |
| 39 | + dependencies, |
| 40 | + }: { |
| 41 | + dependencies: AdapterDependencies |
| 42 | + adapterSettings: AdapterSettings |
| 43 | + adapterName: string |
| 44 | + endpointName: string |
| 45 | + inputParameters: InputParameters<T['Parameters']> |
| 46 | + }) { |
| 47 | + this.dependencies = dependencies |
| 48 | + this.cache = dependencies.cache as Cache<AdapterResponse<T['Response']>> |
| 49 | + this.inputParameters = inputParameters |
| 50 | + this.adapterName = adapterName |
| 51 | + this.endpointName = endpointName |
| 52 | + this.adapterSettings = adapterSettings |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Sets responses in the adapter cache (adding necessary metadata and defaults) |
| 57 | + * |
| 58 | + * @param transportName - transport name |
| 59 | + * @param results - the entries to write to the cache |
| 60 | + */ |
| 61 | + abstract write(transportName: string, results: TimestampedProviderResult<T>[]): Promise<void> |
| 62 | + |
| 63 | + /** |
| 64 | + * Sets responses with metadata in the adapter cache |
| 65 | + * |
| 66 | + * @param entries - the entries to write to the cache |
| 67 | + */ |
| 68 | + abstract writeEntries( |
| 69 | + entries: { |
| 70 | + key: string |
| 71 | + value: AdapterResponse<T['Response']> |
| 72 | + }[], |
| 73 | + ): Promise<void> |
| 74 | + |
| 75 | + /** |
| 76 | + * Sets a new TTL value for already cached responses in the adapter cache |
| 77 | + * |
| 78 | + * @param transportName - transport name |
| 79 | + * @param params - set of parameters that uniquely relate to the response |
| 80 | + * @param ttl - a new time in milliseconds until the response expires |
| 81 | + */ |
| 82 | + async writeTTL( |
| 83 | + transportName: string, |
| 84 | + params: TypeFromDefinition<T['Parameters']>[], |
| 85 | + ttl: number, |
| 86 | + ): Promise<void> { |
| 87 | + for (const param of params) { |
| 88 | + const key = this.getCacheKey(transportName, param) |
| 89 | + this.cache.setTTL(key, ttl) |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + async get(key: string) { |
| 94 | + return this.cache.get(key) |
| 95 | + } |
| 96 | + |
| 97 | + protected generateCacheEntry( |
| 98 | + transportNameForMeta: string, |
| 99 | + transportNameForCache: string, |
| 100 | + r: TimestampedProviderResult<T>, |
| 101 | + ) { |
| 102 | + const censorList = CensorList.getAll() |
| 103 | + const { data, result, errorMessage } = r.response |
| 104 | + if (!errorMessage && data === undefined) { |
| 105 | + logger.warn('The "data" property of the response is undefined.') |
| 106 | + } else if (!errorMessage && result === undefined) { |
| 107 | + logger.warn('The "result" property of the response is undefined.') |
| 108 | + } |
| 109 | + let censoredResponse |
| 110 | + if (!censorList.length) { |
| 111 | + censoredResponse = r.response |
| 112 | + } else { |
| 113 | + try { |
| 114 | + censoredResponse = censor(r.response, censorList, true) as TimestampedAdapterResponse< |
| 115 | + T['Response'] |
| 116 | + > |
| 117 | + } catch (error) { |
| 118 | + censorLogs(() => logger.error(`Error censoring response: ${error}`)) |
| 119 | + censoredResponse = { |
| 120 | + statusCode: 502, |
| 121 | + errorMessage: 'Response could not be censored due to an error', |
| 122 | + timestamps: r.response.timestamps, |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + const response: AdapterResponse<T['Response']> = { |
| 128 | + ...censoredResponse, |
| 129 | + statusCode: (censoredResponse as TimestampedProviderErrorResponse).statusCode || 200, |
| 130 | + } |
| 131 | + |
| 132 | + if (this.adapterSettings.METRICS_ENABLED && this.adapterSettings.EXPERIMENTAL_METRICS_ENABLED) { |
| 133 | + response.meta = { |
| 134 | + adapterName: calculateAdapterName(this.adapterName, r.params), |
| 135 | + transportName: transportNameForMeta, |
| 136 | + metrics: { |
| 137 | + feedId: calculateFeedId( |
| 138 | + { |
| 139 | + adapterSettings: this.adapterSettings, |
| 140 | + }, |
| 141 | + r.params, |
| 142 | + ), |
| 143 | + }, |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + if (response.timestamps?.providerIndicatedTimeUnixMs !== undefined) { |
| 148 | + const timestampValidator = validator.responseTimestamp() |
| 149 | + const error = timestampValidator.fn(response.timestamps?.providerIndicatedTimeUnixMs) |
| 150 | + if (error) { |
| 151 | + censorLogs(() => logger.warn(`Provider indicated time is invalid: ${error}`)) |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + return { |
| 156 | + key: this.getCacheKey(transportNameForCache, r.params), |
| 157 | + value: response, |
| 158 | + } as const |
| 159 | + } |
| 160 | + |
| 161 | + getCacheKey(transportName: string, params: TypeFromDefinition<T['Parameters']>) { |
| 162 | + return calculateCacheKey({ |
| 163 | + transportName, |
| 164 | + data: params, |
| 165 | + adapterName: this.adapterName, |
| 166 | + endpointName: this.endpointName, |
| 167 | + adapterSettings: this.adapterSettings, |
| 168 | + }) |
| 169 | + } |
| 170 | +} |
0 commit comments