fix: optimize summary count query and refine row keys for external api logs

This commit is contained in:
SmartUp Developer
2026-07-02 15:07:32 +08:00
parent e2129d3796
commit ea3fd64686
4 changed files with 195 additions and 9 deletions
+40 -2
View File
@@ -85,13 +85,15 @@ def get_external_api_log_summary(
slow_ms: Optional[int] = Query(None),
hours: int = Query(24, ge=1, le=720),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
db: Session = Depends(get_db),
_=Depends(get_current_user),
):
"""Return aggregated summary grouped by direction + target + method + path.
- hours: time window (default 24, max 720). None means no time filter.
- hours: time window (default 24, max 720).
- limit: max rows returned (default 50, max 200).
- offset: pagination offset (default 0).
"""
settings = get_settings()
slow_threshold = slow_ms if slow_ms is not None else settings.external_api_log_slow_ms
@@ -107,7 +109,7 @@ def get_external_api_log_summary(
ExternalApiLog.method,
ExternalApiLog.path,
).order_by(func.sum(ExternalApiLog.duration_ms).desc())
q = q.limit(limit)
q = q.offset(offset).limit(limit)
rows = q.all()
return [
@@ -129,6 +131,42 @@ def get_external_api_log_summary(
]
@router.get("/summary/count")
def count_external_api_log_summary(
slow_ms: Optional[int] = Query(None),
hours: int = Query(24, ge=1, le=720),
db: Session = Depends(get_db),
_=Depends(get_current_user),
):
"""Return the number of distinct aggregated summary groups.
Uses the same grouping as /summary, returns the count of groups
(not the count of raw log rows).
"""
settings = get_settings()
slow_threshold = slow_ms if slow_ms is not None else settings.external_api_log_slow_ms
q = db.query(
ExternalApiLog.direction,
ExternalApiLog.target_type,
ExternalApiLog.target_id,
ExternalApiLog.target_name,
ExternalApiLog.method,
ExternalApiLog.path,
)
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
q = q.filter(ExternalApiLog.created_at >= cutoff)
q = q.group_by(
ExternalApiLog.direction,
ExternalApiLog.target_type,
ExternalApiLog.target_id,
ExternalApiLog.target_name,
ExternalApiLog.method,
ExternalApiLog.path,
)
return {"total": q.count()}
def _summary_cols(slow_threshold: int) -> list:
return [
ExternalApiLog.direction,