perf: add cache-control headers on private files (#29221)

* perf: add cache-control headers on private files

- Client(browser) side cache
- 1 hr expiry
- 1 day revalidation
- etagged by nginx in default config (so no data transfer on expiry still)

In conjunction with https://github.com/frappe/agent/pull/157

* fix: Don't override existing headers
This commit is contained in:
Ankush Menat 2025-01-17 18:51:34 +05:30 committed by GitHub
parent cdffd5d047
commit 320798d390
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 5 additions and 12 deletions

View file

@ -236,25 +236,17 @@ def log_request(request, response):
)
def process_response(response):
def process_response(response: Response):
if not response:
return
# cache control
# read: https://simonhearne.com/2022/caching-header-best-practices/
if frappe.local.response.can_cache:
response.headers.extend(
{
# default: 5m (client), 3h (allow stale resources for this long if upstream is down)
"Cache-Control": "private,max-age=300,stale-while-revalidate=10800",
}
)
# default: 5m (client), 3h (allow stale resources for this long if upstream is down)
response.headers.setdefault("Cache-Control", "private,max-age=300,stale-while-revalidate=10800")
else:
response.headers.extend(
{
"Cache-Control": "no-store,no-cache,must-revalidate,max-age=0",
}
)
response.headers.setdefault("Cache-Control", "no-store,no-cache,must-revalidate,max-age=0")
# Set cookies, only if response is non-cacheable to avoid proxy cache invalidation
if hasattr(frappe.local, "cookie_manager") and not frappe.local.response.can_cache:

View file

@ -293,6 +293,7 @@ def send_private_file(path: str) -> Response:
path = "/protected/" + path
response = Response()
response.headers["X-Accel-Redirect"] = quote(frappe.utils.encode(path))
response.headers["Cache-Control"] = "private,max-age=3600,stale-while-revalidate=86400"
else:
filepath = frappe.utils.get_site_path(path)