From 45cebc71c5957a4419b59ffbeb6185f3675c31c5 Mon Sep 17 00:00:00 2001 From: yangdx Date: Wed, 21 May 2025 16:46:18 +0800 Subject: [PATCH] Refactor: Optimize static file caching for WebUI - Renamed `NoCacheStaticFiles` to `SmartStaticFiles`. - Implemented long-term caching (1 year, immutable) for versioned assets in `/webui/assets/`. - Ensured `index.html` remains un-cached. - Set correct `Content-Type` for JS and CSS files. --- lightrag/api/lightrag_server.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/lightrag/api/lightrag_server.py b/lightrag/api/lightrag_server.py index 51e1b6af..99fb15e5 100644 --- a/lightrag/api/lightrag_server.py +++ b/lightrag/api/lightrag_server.py @@ -478,18 +478,25 @@ def create_app(args): logger.error(f"Error getting health status: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) - # Custom StaticFiles class to prevent caching of HTML files - class NoCacheStaticFiles(StaticFiles): + # Custom StaticFiles class for smart caching + class SmartStaticFiles(StaticFiles): # Renamed from NoCacheStaticFiles async def get_response(self, path: str, scope): response = await super().get_response(path, scope) + if path.endswith(".html"): - response.headers["Cache-Control"] = ( - "no-cache, no-store, must-revalidate" - ) + response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Pragma"] = "no-cache" response.headers["Expires"] = "0" - elif path.endswith(".js"): + elif "/assets/" in path: # Assets (JS, CSS, images, fonts) generated by Vite with hash in filename + response.headers["Cache-Control"] = "public, max-age=31536000, immutable" + # Add other rules here if needed for non-HTML, non-asset files + + # Ensure correct Content-Type + if path.endswith(".js"): response.headers["Content-Type"] = "application/javascript" + elif path.endswith(".css"): + response.headers["Content-Type"] = "text/css" + return response # Webui mount webui/index.html @@ -497,7 +504,7 @@ def create_app(args): static_dir.mkdir(exist_ok=True) app.mount( "/webui", - NoCacheStaticFiles(directory=static_dir, html=True, check_dir=True), + SmartStaticFiles(directory=static_dir, html=True, check_dir=True), # Use SmartStaticFiles name="webui", )