"""광고 API 가져오기 — 인증정보(perf_ad_credentials) → 광고 연동(ad_sources) → perf_ad_spend(source='api'). - 광고비 탭 [광고비 업데이트](보고 있는 기간, 진행 창 — jobs kind="ads", 2026-10-20) · 매출 자동 업데이트와 같은 회차 (최근 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, Cancelled 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) AD_MESSAGE_MAX = 1200 # 광고 연동 오류 문구 길이 한도(비밀값 가린 뒤) _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: [])() # 광고 연동 오류는 고칠 곳 안내·진단이 붙어 길다 — 기본 300자에서 자르면 안내가 잘린다(2026-10-16 메타 #200 진단) return redact_text(str(getattr(exc, "message", "") or exc), known, max_len=AD_MESSAGE_MAX) 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 = "", progress: Any = None) -> dict[str, Any]: """기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy. progress(jobs.ShopProgress) 를 주면 수집(절반) → 저장 → 완료로 알리고, 저장 직전 중지·취소를 받아 Cancelled.""" 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) if progress is not None: progress.plan(2, "단계") days = src.fetch_days(ctx, start, end) if progress is not None: progress.step(1, items=len(days)) progress.begin_saving() # 여기까지 받은 [중지]·[취소]는 저장하지 않고 멈춤 except Cancelled: raise # 오류가 아니다 — 상태 기록 없이 sync_all 이 "중지됨/취소됨" 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 = "", job: Any = None) -> list[dict[str, Any]]: """설정이 끝난 광고 연동 전부([광고비 업데이트]·자동 업데이트 회차). 채널별로 실패를 격리한다. job(jobs.SyncJob kind="ads") 을 주면 채널별 진행 막대로 알린다.""" codes = [c for c, ok in self.configured().items() if ok] shops = job.set_targets([(c, get_source(c).name, True) for c in codes], start, end) if job is not None else {} out = [] for code in codes: prog = shops.get(code) if prog is not None and prog.cancel_requested: # 차례가 오기 전에 중지·취소됨 prog.cancelled() out.append({"ok": False, "code": code, "cancelled": True}) continue if prog is not None: prog.start() try: res = self.sync(code, start, end, user=user, progress=prog) except Cancelled: if prog is not None: prog.cancelled() out.append({"ok": False, "code": code, "cancelled": True}) continue except AdSyncBusy as exc: res = {"ok": False, "code": code, "skipped": True, "message": str(exc)} except Exception as exc: # noqa: BLE001 — 다음 채널은 계속 logger.exception("ad sync failed: %s", code) res = {"ok": False, "code": code, "status": "api_error", "label": STATUS_LABELS["api_error"], "message": f"가져오기 중 오류: {type(exc).__name__}"} if prog is not None: if res.get("ok"): prog.finish(upserted=int(res.get("days") or 0), message=f"광고비 ₩{int(res.get('total') or 0):,}") elif res.get("skipped"): prog.skip(str(res.get("message") or "")) else: prog.fail(status=str(res.get("status") or "api_error"), label=str(res.get("label") or ""), message=str(res.get("message") or "")) out.append(res) return out def run_ad_job(store: Any, ring_loader: Callable[[], Any], job: Any, start: date, end: date, *, user: str = "") -> list[dict[str, Any]]: """광고비 업데이트 작업 하나를 끝까지 돌리고 job.finish — [광고비 업데이트] 스레드·자동 업데이트 회차가 쓴다.""" error, results = "", [] try: results = AdSyncService(store, ad_credentials(store, ring_loader)).sync_all(start, end, user=user, job=job) except Exception as exc: # noqa: BLE001 — 스레드 밖으로 새지 않게, 화면에는 "오류"로 logger.exception("ad sync job failed") error = f"광고비 업데이트 중 오류: {type(exc).__name__}" if job is not None: job.finish(error=error, last_update_at=last_ad_update_at(store)) return results def last_ad_update_at(store: Any) -> str | None: """광고비 마지막 업데이트 — 광고 API 채널의 마지막 성공 가져오기 시각 중 가장 최근(없으면 None).""" try: rows = store.ad_source_statuses() except Exception: # noqa: BLE001 — 007 미적용 등 return None times = [str(r.get("last_success_sync_at")) for r in rows.values() if r.get("last_success_sync_at")] return max(times) if times else None