"""광고 API 가져오기 — 인증정보(perf_ad_credentials) → 광고 연동(ad_sources) → perf_ad_spend(source='api'). - 광고비 탭 [구글 광고 불러오기](보고 있는 기간) · 매출 자동 업데이트 회차(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다. - 같은 광고 채널은 동시에 한 번만(프로세스 안 잠금) — 두 번째 요청은 바로 "진행 중" 오류. - 저장은 기간 단위 한 트랜잭션(db.replace_ad_api_range): API 가 준 날은 덮어쓰고, 안 준 날은 예전 API 값만 지운다. - 오류 문구는 저장된 비밀값을 가린 뒤 기록·반환한다(security.redact). """ from __future__ import annotations import logging import threading from datetime import date from typing import Any, Callable from .ad_sources.registry import all_sources, get_source from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError from .credentials import CredentialService from .db import AdCredentialTable from .security.redact import redact_text logger = logging.getLogger("performance.ad_sync") AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for) _locks: dict[str, threading.Lock] = {} _locks_guard = threading.Lock() def _lock(code: str) -> threading.Lock: with _locks_guard: return _locks.setdefault(code, threading.Lock()) class AdSyncBusy(Exception): """같은 광고 채널 가져오기가 이미 진행 중.""" def ad_credentials(store: Any, ring_loader: Callable[[], Any]) -> CredentialService: """광고 API 인증정보 서비스 — 쇼핑몰과 같은 서비스, 저장소만 광고 표.""" return CredentialService(AdCredentialTable(store), ring_loader, aad_ns=AD_NS) class AdSyncService: def __init__(self, store: Any, creds: CredentialService) -> None: self._store = store self._creds = creds def configured(self) -> dict[str, bool]: return self._creds.configured_codes(list(all_sources())) def _ctx(self, code: str, *, values: dict[str, str] | None = None, user: str = "", cleared: set[str] | None = None) -> AdapterContext: trial = values is not None or bool(cleared) acc = self._creds.accessor(code, overrides=values, persist=not trial, user=user, cleared=cleared) return AdapterContext(code=code, credentials=acc, timeout_sec=30.0) @staticmethod def _message(exc: Exception, ctx: AdapterContext) -> str: known = getattr(ctx.credentials, "known_secrets", lambda: [])() return redact_text(str(getattr(exc, "message", "") or exc), known) def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "", cleared: set[str] | None = None) -> dict[str, Any]: """values 가 있으면 저장하지 않은 새 입력값(빈 칸은 저장값)으로 시험, cleared = 화면에서 비운 항목(빈 값으로) — 그때는 상태를 기록하지 않는다.""" src = get_source(code) if src is None: return {"ok": False, "status": "api_error", "label": STATUS_LABELS["api_error"], "message": "알 수 없는 광고 연동입니다."} ctx = self._ctx(code, values=values, user=user, cleared=cleared) trial = bool(values) or bool(cleared) try: src.require_configured(ctx) msg = src.test_connection(ctx) ok, status = True, "ok" except AdapterError as exc: ok, status, msg = False, exc.status, self._message(exc, ctx) except Exception as exc: # noqa: BLE001 — 예상 못 한 오류도 화면에는 짧게 logger.exception("ad test failed: %s", code) ok, status, msg = False, "api_error", f"연결 테스트 중 오류: {type(exc).__name__}" if not trial: self._store.record_ad_status(code, status=status, ok=ok, error="" if ok else msg, kind="test") return {"ok": ok, "status": status, "label": STATUS_LABELS.get(status, status), "message": msg, "unsaved": trial} def sync(self, code: str, start: date, end: date, *, user: str = "") -> dict[str, Any]: """기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy.""" src = get_source(code) if src is None: raise KeyError(code) lock = _lock(code) if not lock.acquire(blocking=False): raise AdSyncBusy(f"{src.name} 가져오기가 이미 진행 중입니다. 잠시 뒤 다시 누르세요.") try: ctx = self._ctx(code, user=user) try: src.require_configured(ctx) days = src.fetch_days(ctx, start, end) except AdapterError as exc: msg = self._message(exc, ctx) self._store.record_ad_status(code, status=exc.status, ok=False, error=msg, kind="sync") return {"ok": False, "code": code, "name": src.name, "status": exc.status, "label": STATUS_LABELS.get(exc.status, exc.status), "message": msg} saved = self._store.replace_ad_api_range( code, start, end, [(d.day, d.amount, d.roas, d.metrics) for d in days], user=user or "광고 API") self._store.record_ad_status(code, status="ok", ok=True, kind="sync") return {"ok": True, "code": code, "name": src.name, "days": saved, "total": sum(d.amount for d in days), "from": start.isoformat(), "to": end.isoformat()} finally: lock.release() def sync_all(self, start: date, end: date, *, user: str = "") -> list[dict[str, Any]]: """설정이 끝난 광고 연동 전부(자동 업데이트 회차). 채널별로 실패를 격리한다.""" out = [] for code, ok in self.configured().items(): if not ok: continue try: out.append(self.sync(code, start, end, user=user)) except AdSyncBusy as exc: out.append({"ok": False, "code": code, "skipped": True, "message": str(exc)}) except Exception as exc: # noqa: BLE001 — 다음 채널은 계속 logger.exception("ad sync failed: %s", code) out.append({"ok": False, "code": code, "message": f"가져오기 중 오류: {type(exc).__name__}"}) return out