🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: implement Redis caching for presigned URLs in file proxy service
YuTengjing15722f1e2749
diff --git a/src/app/(backend)/f/[id]/route.ts b/src/app/(backend)/f/[id]/route.tsindex 6b5df954190..d317a316ee3 100644--- a/src/app/(backend)/f/[id]/route.ts+++ b/src/app/(backend)/f/[id]/route.ts@@ -2,12 +2,24 @@ import debug from 'debug';import { FileModel } from '@/database/models/file';import { getServerDB } from '@/database/server';+import { getRedisConfig } from '@/envs/redis';+import { initializeRedis, isRedisEnabled } from '@/libs/redis';import { FileService } from '@/server/services/file';const log = debug('lobe-file:proxy');type Params = Promise<{ id: string }>;+const FILE_PROXY_KEY_PREFIX = 'file-proxy:';+// Cache presigned URL for 4 minutes (URL expires in 5 minutes)+const PRESIGNED_URL_CACHE_TTL = 240;++const buildCacheKey = (id: string) => `${FILE_PROXY_KEY_PREFIX}${id}`;++interface CachedFileData {+ redirectUrl: string;+}+/*** File proxy service* GET /f/:id@@ -15,6 +27,7 @@ type Params = Promise<{ id: string }>;* Features:* - Query database to get file record (without userId filter for public access)* - Generate access URL based on platform (desktop → local file, web → S3 presigned URL)+ * - Cache presigned URL in Redis to reduce S3 API calls* - Return 302 redirect*/export const GET = async (_req: Request, segmentData: { params: Params }) => {@@ -24,6 +37,20 @@ export const GET = async (_req: Request, segmentData: { params: Params }) => {log('File proxy request: %s', id);+ // Try to get cached presigned URL from Redis+ const redisConfig = getRedisConfig();+ const redisClient = isRedisEnabled(redisConfig) ? await initializeRedis(redisConfig) : null;++ if (redisClient) {+ const cached = await redisClient.get(buildCacheKey(id));+ if (cached) {+ const { redirectUrl } = JSON.parse(cached) as CachedFileData;+ log('Cache hit for file: %s', id);+ return Response.redirect(redirectUrl, 302);+ }+ log('Cache miss for file: %s', id);+ }+// Get database connectionconst db = await getServerDB();@@ -44,6 +71,15 @@ export const GET = async (_req: Request, segmentData: { params: Params }) => {const redirectUrl = await fileService.createPreSignedUrlForPreview(file.url, 300);log('Web S3 presigned URL generated (expires in 5 min)');+ // Cache the presigned URL in Redis+ if (redisClient) {+ const cacheData: CachedFileData = { redirectUrl };+ await redisClient.set(buildCacheKey(id), JSON.stringify(cacheData), {+ ex: PRESIGNED_URL_CACHE_TTL,+ });+ log('Cached presigned URL for file: %s (TTL: %ds)', id, PRESIGNED_URL_CACHE_TTL);+ }+// Return 302 redirectreturn Response.redirect(redirectUrl, 302);} catch (error) {