Files
hunjing/backend/app/repositories/idempotency.py
T
2026-08-21 16:00:13 +08:00

34 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""幂等键数据访问。"""
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.idempotency import IdempotencyKey
async def get_by_scope_key(session: AsyncSession, *, scope: str, key: str) -> IdempotencyKey | None:
result = await session.execute(
select(IdempotencyKey).where(IdempotencyKey.scope == scope, IdempotencyKey.key == key)
)
return result.scalar_one_or_none()
async def list_by_trace(session: AsyncSession, trace_id: str) -> list[IdempotencyKey]:
"""链路追踪:按 trace_id 查询幂等键(请求级),按 created_at 升序。"""
result = await session.execute(
select(IdempotencyKey)
.where(IdempotencyKey.trace_id == trace_id)
.order_by(IdempotencyKey.created_at.asc())
)
return list(result.scalars().all())
async def summarize_by_trace(session: AsyncSession):
"""GROUP BY trace_id:(trace_id, 计数, 最近时间),仅 trace_id 非空。供链路追踪列表聚合。"""
result = await session.execute(
select(IdempotencyKey.trace_id, func.count(), func.max(IdempotencyKey.created_at))
.where(IdempotencyKey.trace_id.is_not(None))
.group_by(IdempotencyKey.trace_id)
)
return [(row[0], int(row[1]), row[2]) for row in result.all()]