|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | +import { RedisCacheError } from '../../../errors/RedisCacheError'; |
| 4 | +import { RedisCache } from './redisCache'; |
| 5 | + |
| 6 | +/** |
| 7 | + * A safer wrapper around {@link RedisCache} which is responsible for: |
| 8 | + * - ignoring all Redis command errors. |
| 9 | + * - logging all errors, |
| 10 | + * - returning default values in cases of failures. |
| 11 | + * |
| 12 | + * Thanks to that our application will be able to continue functioning even with Redis being down... |
| 13 | + */ |
| 14 | +export class SafeRedisCache extends RedisCache { |
| 15 | + /** |
| 16 | + * Retrieves a value from the cache. |
| 17 | + * |
| 18 | + * This method wraps {@link RedisCache.get} and ensures `null` is returned instead of throwing error. |
| 19 | + * |
| 20 | + * @param key - The cache key. |
| 21 | + * @param callingMethod - Name of the method making the request (for logging). |
| 22 | + * @returns The cached value, or `null` if Redis fails or the value does not exist. |
| 23 | + */ |
| 24 | + async get(key: string, callingMethod: string): Promise<any> { |
| 25 | + return await this.safeCall(() => super.get(key, callingMethod), null); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + /** |
| 30 | + * Stores a value in the cache safely. |
| 31 | + * |
| 32 | + * Wraps {@link RedisCache.set} and suppresses Redis errors. |
| 33 | + * On failure, nothing is thrown and the error is logged. |
| 34 | + * |
| 35 | + * @param key - The cache key. |
| 36 | + * @param value - The value to store. |
| 37 | + * @param callingMethod - Name of the calling method. |
| 38 | + * @param ttl - Optional TTL in milliseconds. |
| 39 | + */ |
| 40 | + async set(key: string, value: any, callingMethod: string, ttl?: number): Promise<void> { |
| 41 | + await this.safeCall(() => super.set(key, value, callingMethod, ttl), undefined); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Stores multiple key-value pairs safely. |
| 46 | + * |
| 47 | + * Wraps {@link RedisCache.multiSet} with error suppression. |
| 48 | + * |
| 49 | + * @param keyValuePairs - Object of key-value pairs to set. |
| 50 | + * @param callingMethod - Name of the calling method. |
| 51 | + * @param ttl - Optional TTL used in fallback pipeline mode. |
| 52 | + */ |
| 53 | + async multiSet(keyValuePairs: Record<string, any>, callingMethod: string, ttl?: number): Promise<void> { |
| 54 | + await this.safeCall(() => super.multiSet(keyValuePairs, callingMethod, ttl), undefined); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Performs a pipelined multi-set operation safely. |
| 59 | + * |
| 60 | + * Wraps {@link RedisCache.pipelineSet} with error suppression. |
| 61 | + * |
| 62 | + * @param keyValuePairs - Key-value pairs to write. |
| 63 | + * @param callingMethod - Name of the calling method. |
| 64 | + * @param ttl - Optional TTL. |
| 65 | + */ |
| 66 | + async pipelineSet(keyValuePairs: Record<string, any>, callingMethod: string, ttl?: number): Promise<void> { |
| 67 | + await this.safeCall(() => super.pipelineSet(keyValuePairs, callingMethod, ttl), undefined); |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Deletes a value from the cache safely. |
| 72 | + * |
| 73 | + * Wraps {@link RedisCache.delete} with error suppression. |
| 74 | + * |
| 75 | + * @param key - Key to delete. |
| 76 | + * @param callingMethod - Name of the calling method. |
| 77 | + */ |
| 78 | + async delete(key: string, callingMethod: string): Promise<void> { |
| 79 | + await this.safeCall(() => super.delete(key, callingMethod), undefined); |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Increments a numeric value safely. |
| 84 | + * |
| 85 | + * Wraps {@link RedisCache.incrBy}. |
| 86 | + * On failure, returns the `amount` argument as fallback. |
| 87 | + * |
| 88 | + * @param key - Key to increment. |
| 89 | + * @param amount - Increment amount. |
| 90 | + * @param callingMethod - Name of the calling method. |
| 91 | + * @returns The incremented value or the fallback (amount) if Redis fails. |
| 92 | + */ |
| 93 | + async incrBy(key: string, amount: number, callingMethod: string): Promise<number> { |
| 94 | + return await this.safeCall(() => super.incrBy(key, amount, callingMethod), amount); |
| 95 | + } |
| 96 | + |
| 97 | + /** |
| 98 | + * Retrieves a list slice safely. |
| 99 | + * |
| 100 | + * Wraps {@link RedisCache.lRange}. |
| 101 | + * On error, returns an empty array. |
| 102 | + * |
| 103 | + * @param key - List key. |
| 104 | + * @param start - Start index. |
| 105 | + * @param end - End index. |
| 106 | + * @param callingMethod - Name of the calling method. |
| 107 | + * @returns List of elements, or an empty array on failure. |
| 108 | + */ |
| 109 | + async lRange(key: string, start: number, end: number, callingMethod: string): Promise<any[]> { |
| 110 | + return await this.safeCall(() => super.lRange(key, start, end, callingMethod), []); |
| 111 | + } |
| 112 | + |
| 113 | + /** |
| 114 | + * Pushes a value to a list safely. |
| 115 | + * |
| 116 | + * Wraps {@link RedisCache.rPush}. |
| 117 | + * Returns `0` on failure. |
| 118 | + * |
| 119 | + * @param key - List key. |
| 120 | + * @param value - Value to push. |
| 121 | + * @param callingMethod - Name of the calling method. |
| 122 | + * @returns The new list length, or `0` if Redis fails. |
| 123 | + */ |
| 124 | + async rPush(key: string, value: any, callingMethod: string): Promise<number> { |
| 125 | + return await this.safeCall(() => super.rPush(key, value, callingMethod), 0); |
| 126 | + } |
| 127 | + |
| 128 | + /** |
| 129 | + * Retrieves keys matching a pattern safely. |
| 130 | + * |
| 131 | + * Wraps {@link RedisCache.keys}. |
| 132 | + * Returns an empty array on error. |
| 133 | + * |
| 134 | + * @param pattern - Match pattern. |
| 135 | + * @param callingMethod - Name of the calling method. |
| 136 | + * @returns Array of matched keys (prefix removed), or empty array on error. |
| 137 | + */ |
| 138 | + async keys(pattern: string, callingMethod: string): Promise<string[]> { |
| 139 | + return await this.safeCall(() => super.keys(pattern, callingMethod), []); |
| 140 | + } |
| 141 | + |
| 142 | + /** |
| 143 | + * Clears all cache keys safely. |
| 144 | + * |
| 145 | + * Wraps {@link RedisCache.clear}. |
| 146 | + * Any Redis failure is logged and ignored. |
| 147 | + */ |
| 148 | + |
| 149 | + async clear(): Promise<void> { |
| 150 | + await this.safeCall(() => super.clear(), null); |
| 151 | + } |
| 152 | + |
| 153 | + /** |
| 154 | + * Executes a Redis call safely. |
| 155 | + * |
| 156 | + * This is the core safety mechanism of {@link SafeRedisCache}. |
| 157 | + * |
| 158 | + * @template T The expected return type. |
| 159 | + * @param fn - Function containing the Redis call. |
| 160 | + * @param fallback - Value to return if an error occurs. |
| 161 | + * @returns The result of `fn()` or the fallback. |
| 162 | + */ |
| 163 | + async safeCall<T>(fn: () => Promise<T>, fallback: T): Promise<T> { |
| 164 | + try { |
| 165 | + return await fn(); |
| 166 | + } catch (error) { |
| 167 | + const redisError = new RedisCacheError(error); |
| 168 | + this.logger.error(redisError, 'Error occurred while getting the cache from Redis.'); |
| 169 | + return fallback; |
| 170 | + } |
| 171 | + } |
| 172 | +} |
0 commit comments