File size: 2,244 Bytes
7a3215f
 
 
 
 
 
 
be69d1e
7a3215f
ae2c68f
7a3215f
 
 
 
 
 
 
 
 
 
be69d1e
 
7a3215f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
7a3215f
ae2c68f
7a3215f
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""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))