"""用量记账落库(ARCH §4.8)。 `LedgerSink` 为接口,便于测试注入内存替身;生产用 SQLAlchemy 实现写 usage_ledger。 """ from __future__ import annotations from typing import Protocol from sqlalchemy.ext.asyncio import AsyncSession from ww_db.models import UsageLedger from .types import Scope, Usage class LedgerSink(Protocol): async def record(self, scope: Scope, usage: Usage) -> None: ... class SqlAlchemyLedgerSink: """把每次调用写入 usage_ledger(owner_id 取 scope.user_id,单用户 stub)。""" def __init__(self, session: AsyncSession) -> None: self._session = session async def record(self, scope: Scope, usage: Usage) -> None: row = UsageLedger( owner_id=scope.user_id, project_id=scope.project_id, provider=usage.provider, model=usage.model, input_tokens=usage.input_tokens, output_tokens=usage.output_tokens, cache_read=usage.cache_read_tokens, cost_minor=usage.cost_minor, currency=usage.currency, ) self._session.add(row) await self._session.flush()