38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
"""Shared FastAPI dependencies and helpers for the v1 API."""
|
|||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from collections.abc import Awaitable, Callable
|
||
|
|
|
||
|
|
from fastapi import HTTPException, status
|
||
|
|
from pydantic import BaseModel
|
||
|
|
from redis.asyncio import Redis
|
||
|
|
|
||
|
|
from app.services.cache import cache_get_json, cache_set_json
|
||
|
|
|
||
|
|
|
||
|
|
def not_found(entity_type: str, aurora_id_str: str) -> HTTPException:
|
||
|
|
return HTTPException(
|
||
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
||
|
|
detail={"code": f"{entity_type}_not_found", "message": f"No such {entity_type}: {aurora_id_str}"},
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
async def cached_response[T: BaseModel](
|
||
|
|
redis: Redis,
|
||
|
|
key: str,
|
||
|
|
model: type[T],
|
||
|
|
loader: Callable[[], Awaitable[T]],
|
||
|
|
ttl: int | None = None,
|
||
|
|
) -> T:
|
||
|
|
"""Serve `model` from Redis if present, otherwise call `loader`, cache
|
||
|
|
the result, and return it. Fails open to `loader` on any cache error."""
|
||
|
|
|
||
|
|
cached = await cache_get_json(redis, key)
|
||
|
|
if cached is not None:
|
||
|
|
return model.model_validate(cached)
|
||
|
|
|
||
|
|
result = await loader()
|
||
|
|
await cache_set_json(redis, key, result.model_dump(mode="json"), ttl=ttl)
|
||
|
|
return result
|