|
| 1 | +from functools import wraps |
| 2 | +from contextvars import ContextVar |
| 3 | +from typing import Dict, Any, Callable, Awaitable, Union, Never |
| 4 | + |
| 5 | +from starlette.datastructures import MutableHeaders |
| 6 | +from starlette.types import ASGIApp, Scope, Receive, Send, Message |
| 7 | +from primary.config import DEFAULT_CACHE_MAX_AGE, DEFAULT_STALE_WHILE_REVALIDATE |
| 8 | + |
| 9 | +# Initialize with a factory function to ensure a new dict for each context |
| 10 | +def get_default_context() -> Dict[str, Any]: |
| 11 | + return {"max_age": DEFAULT_CACHE_MAX_AGE, "stale_while_revalidate": DEFAULT_STALE_WHILE_REVALIDATE} |
| 12 | + |
| 13 | + |
| 14 | +cache_context: ContextVar[Dict[str, Any]] = ContextVar("cache_context", default=get_default_context()) |
| 15 | + |
| 16 | + |
| 17 | +def add_custom_cache_time(max_age: int, stale_while_revalidate: int = 0) -> Callable: |
| 18 | + """ |
| 19 | + Decorator that sets a custom browser cache time for the endpoint response. |
| 20 | +
|
| 21 | + Args: |
| 22 | + max_age (int): The maximum age in seconds for the cache |
| 23 | + stale_while_revalidate (int): The stale-while-revalidate time in seconds |
| 24 | +
|
| 25 | + Example: |
| 26 | + @add_custom_cache_time(300, 600) # 5 minutes max age, 10 minutes stale-while-revalidate |
| 27 | + async def my_endpoint(): |
| 28 | + return {"data": "some_data"} |
| 29 | + """ |
| 30 | + |
| 31 | + def decorator(func: Callable) -> Callable: |
| 32 | + @wraps(func) |
| 33 | + async def wrapper(*args: Any, **kwargs: Any) -> Callable: |
| 34 | + context = cache_context.get() |
| 35 | + context["max_age"] = max_age |
| 36 | + context["stale_while_revalidate"] = stale_while_revalidate |
| 37 | + |
| 38 | + return await func(*args, **kwargs) |
| 39 | + |
| 40 | + return wrapper |
| 41 | + |
| 42 | + return decorator |
| 43 | + |
| 44 | + |
| 45 | +def no_cache(func: Callable) -> Callable: |
| 46 | + """ |
| 47 | + Decorator that explicitly disables browser caching for the endpoint response. |
| 48 | +
|
| 49 | + Example: |
| 50 | + @no_cache |
| 51 | + async def my_endpoint(): |
| 52 | + return {"data": "some_data"} |
| 53 | + """ |
| 54 | + |
| 55 | + @wraps(func) |
| 56 | + async def wrapper(*args: Any, **kwargs: Any) -> Callable: |
| 57 | + context = cache_context.get() |
| 58 | + context["max_age"] = 0 |
| 59 | + context["stale_while_revalidate"] = 0 |
| 60 | + |
| 61 | + return await func(*args, **kwargs) |
| 62 | + |
| 63 | + return wrapper |
| 64 | + |
| 65 | + |
| 66 | +class AddBrowserCacheMiddleware: |
| 67 | + """ |
| 68 | + Adds cache-control to the response headers |
| 69 | + """ |
| 70 | + |
| 71 | + def __init__(self, app: ASGIApp) -> None: |
| 72 | + self.app = app |
| 73 | + |
| 74 | + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
| 75 | + if scope["type"] != "http": |
| 76 | + return await self.app(scope, receive, send) |
| 77 | + |
| 78 | + # Set initial context and store token |
| 79 | + cache_context.set(get_default_context()) |
| 80 | + |
| 81 | + async def send_with_cache_header(message: Message) -> None: |
| 82 | + if message["type"] == "http.response.start": |
| 83 | + headers = MutableHeaders(scope=message) |
| 84 | + context = cache_context.get() |
| 85 | + cache_control_str = ( |
| 86 | + f"max-age={context['max_age']}, stale-while-revalidate={context['stale_while_revalidate']}, private" |
| 87 | + ) |
| 88 | + headers.append("cache-control", cache_control_str) |
| 89 | + |
| 90 | + await send(message) |
| 91 | + |
| 92 | + await self.app(scope, receive, send_with_cache_header) |
0 commit comments