From 8e6ea7346001385c787ca48410e1b8b739030868 Mon Sep 17 00:00:00 2001 From: ld3zian <42660576+ld3z@users.noreply.github.com> Date: Mon, 3 Mar 2025 16:04:16 -0700 Subject: [PATCH] fix fallback servers --- src/lib/db.ts | 56 ++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 12 deletions(-) diff --git a/src/lib/db.ts b/src/lib/db.ts index bb34a83..c46340d 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -284,19 +284,51 @@ export async function checkCacheStatus(slugs: string[], lang: string): Promise { - const redis = await getRedisClient(); - + // First try primary try { - const mapping = await redis.get(feedId); - if (!mapping) return null; - - await redis.expire(feedId, DEFAULT_CACHE_TTL); - - const data = JSON.parse(mapping); - return { - slugs: data.slugs, - lang: data.lang - }; + if (primaryClient?.status === 'ready') { + try { + await primaryClient.ping(); + const mapping = await primaryClient.get(feedId); + if (mapping) { + await primaryClient.expire(feedId, DEFAULT_CACHE_TTL); + const data = JSON.parse(mapping); + return { + slugs: data.slugs, + lang: data.lang + }; + } + // If key not found in primary, we'll fall through to try replicas + } catch (error) { + console.warn('Primary Redis connection failed while retrieving mapping:', error); + // Fall through to try replicas + } + } + + // Try replicas one by one + for (const [url, client] of replicaClients.entries()) { + if (client.status === 'ready') { + try { + await client.ping(); + console.log(`Trying to get key from ${getRedisName(url)}`); + const mapping = await client.get(feedId); + if (mapping) { + await client.expire(feedId, DEFAULT_CACHE_TTL); + const data = JSON.parse(mapping); + return { + slugs: data.slugs, + lang: data.lang + }; + } + } catch (error) { + console.warn(`${getRedisName(url)} connection failed while retrieving mapping:`, error); + // Continue to next replica + } + } + } + + // If we get here, the key wasn't found in any database + return null; } catch (error) { console.error('Error retrieving feed mapping:', error); throw new Error('Failed to retrieve feed mapping');