from __future__ import annotations from typing import Annotated, Any from fastapi import APIRouter, Header, Request from ebook_svc.core.rate_limit import rate_limit from ebook_svc.schemas.track import TrackBatchBody from ebook_svc.services.store import store from ebook_svc.services.track import ingest_events router = APIRouter(prefix="/track", tags=["track"]) def _client_ip(request: Request) -> str: xf = (request.headers.get("x-forwarded-for") or "").split(",")[0].strip() if xf: return xf[:64] for key in ("x-real-ip", "cf-connecting-ip", "true-client-ip"): val = (request.headers.get(key) or "").strip() if val: return val[:64] if request.client and request.client.host: return str(request.client.host)[:64] return "" def _enrich_events(events: list[dict[str, Any]], request: Request) -> list[dict[str, Any]]: ip = _client_ip(request) ua = (request.headers.get("user-agent") or "")[:240] country = ( request.headers.get("cf-ipcountry") or request.headers.get("x-vercel-ip-country") or "" )[:8] if not ip and not ua and not country: return events out: list[dict[str, Any]] = [] for ev in events: props = dict(ev.get("props") or {}) if isinstance(ev.get("props"), dict) else {} # 经门户转发时 props 已带真实客户端 IP;勿用本机回环覆盖 if ip and not props.get("ip") and ip not in {"127.0.0.1", "::1"}: props["ip"] = ip if ua and not props.get("ua"): props["ua"] = ua if country and not props.get("country"): props["country"] = country out.append({**ev, "props": props}) return out @router.post("") @router.post("/") async def track_batch( body: TrackBatchBody, request: Request, authorization: Annotated[str | None, Header()] = None, ): """小程序埋点上报。可匿名;若带 Bearer 则绑定 openid。""" rate_limit(request, bucket="track", limit=120, window_sec=60.0) openid = (body.openid or "").strip() or None if authorization and authorization.startswith("Bearer "): token = authorization.removeprefix("Bearer ").strip() user = store.get_user_by_token(token) if user: openid = user.get("openid") or openid events = _enrich_events([e.model_dump() for e in body.events], request) return await ingest_events(events, openid=openid, client=body.client or "miniapp")