Spaces:
Running on T4
Running on T4
Download backend/app/modules/api_audit/service.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 2.24 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/api_audit/service.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/modules/api_audit/service.py
-
curl -L -o service.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/api_audit/service.py
2.24 kB
| """Bounded, independent database writes: audit failures never replace an API result.""" | |
| import asyncio | |
| import logging | |
| from app.common.schemas import Page | |
| from app.core.config import get_settings | |
| from app.core.database import get_autocommit_engine, get_session_factory | |
| from app.core.errors import ValidationFailed | |
| from app.core.pagination import paginate | |
| from app.modules.api_audit.models import ApiRequestLog | |
| from app.modules.api_audit.repository import AuditLogRepository | |
| from app.modules.api_audit.schemas import AuditLogDetail, AuditLogSummary | |
| log = logging.getLogger(__name__) | |
| async def write_record(record: dict) -> None: | |
| try: | |
| async with asyncio.timeout(get_settings().api_audit_write_timeout_s): | |
| # One INSERT is atomic on its own; autocommit saves the BEGIN and COMMIT round trips. | |
| async with get_session_factory()(bind=get_autocommit_engine()) as db: | |
| db.add(ApiRequestLog(**record)) | |
| await db.commit() | |
| except Exception as exc: | |
| # Do not print payloads, connection strings, SQL parameters or exception messages. | |
| log.error("api_audit_write_failed request_id=%s error_type=%s", record["request_id"], type(exc).__name__) | |
| class AuditLogService: | |
| def __init__(self, db): | |
| self.repo = AuditLogRepository(db) | |
| async def list(self, paging, filters, since=None, until=None): | |
| if any(t is not None and t.utcoffset() is None for t in (since, until)): | |
| raise ValidationFailed(fields={"date_range": "Use timestamps with a timezone."}) | |
| if since is not None and until is not None and since >= until: | |
| raise ValidationFailed(fields={"until": "Must be after since."}) | |
| if paging.cursor and paging.cursor.created_at.utcoffset() is None: | |
| raise ValidationFailed(fields={"cursor": "Cursor timestamp needs a timezone."}) | |
| rows = await self.repo.search(paging, filters, since, until) | |
| rows, next_cursor = paginate(rows, paging.limit) | |
| return Page[AuditLogSummary](items=[AuditLogSummary.model_validate(row) for row in rows], | |
| next_cursor=next_cursor) | |
| async def get(self, log_id): | |
| return AuditLogDetail.model_validate(await self.repo.get_or_404(log_id)) | |