Add in-memory read cache with CUD-based invalidation

This commit is contained in:
Chris
2026-04-03 02:32:38 +08:00
parent fa624127c8
commit ed413ce39d
8 changed files with 196 additions and 20 deletions

View File

@@ -12,6 +12,7 @@ from app.schemas.users import UserUpsertBySubRequest
from app.security.api_client_auth import require_api_client
from app.services.idp_admin_service import ProviderAdminService
from app.services.permission_service import PermissionService
from app.services.runtime_cache import runtime_cache
router = APIRouter(prefix="/internal", tags=["internal"], dependencies=[Depends(require_api_client)])
@@ -68,8 +69,13 @@ def _build_user_role_rows(db: Session, user_sub: str) -> list[tuple[str, str, st
@router.get("/users/{user_sub}/roles", response_model=InternalUserRoleResponse)
def get_user_roles(user_sub: str, db: Session = Depends(get_db)) -> InternalUserRoleResponse:
cache_key = f"internal:user_roles:{user_sub}"
cached = runtime_cache.get(cache_key)
if isinstance(cached, InternalUserRoleResponse):
return cached
rows = _build_user_role_rows(db, user_sub)
return InternalUserRoleResponse(
result = InternalUserRoleResponse(
user_sub=user_sub,
roles=[
InternalUserRoleItem(
@@ -94,6 +100,8 @@ def get_user_roles(user_sub: str, db: Session = Depends(get_db)) -> InternalUser
) in rows
],
)
runtime_cache.set(cache_key, result, ttl_seconds=30)
return result
@router.get("/permissions/{user_sub}/snapshot", response_model=RoleSnapshotResponse)
@@ -101,8 +109,15 @@ def get_permission_snapshot(
user_sub: str,
db: Session = Depends(get_db),
) -> RoleSnapshotResponse:
cache_key = f"internal:permissions_snapshot:{user_sub}"
cached = runtime_cache.get(cache_key)
if isinstance(cached, RoleSnapshotResponse):
return cached
rows = _build_user_role_rows(db, user_sub)
return PermissionService.build_role_snapshot(user_sub=user_sub, rows=rows)
result = PermissionService.build_role_snapshot(user_sub=user_sub, rows=rows)
runtime_cache.set(cache_key, result, ttl_seconds=30)
return result
@router.post("/provider/users/ensure", response_model=ProviderEnsureUserResponse)