"""매출 업데이트 진행 상황 — 백그라운드 수집 작업(쇼핑몰별 진행 막대)을 메모리에 둔다. - [매출 업데이트]·[과거 매출 가져오기]는 수집을 백그라운드 스레드로 돌리고 작업 번호를 바로 돌려준다. 화면은 GET /performance/api/sync/jobs/{id} 를 0.8초마다 불러 쇼핑몰별·전체 진행 막대를 그린다. - 어댑터가 ctx.progress.plan()/step() 으로 알린 단계를 ShopProgress 가 모은다(쇼핑몰마다 단위가 다르다 — 네이버 "일", 11번가·카페24 "구간"). - 웹 프로세스 하나(uvicorn 단일 워커) 기준 — 워커를 여러 개로 늘리면 진행 상황을 DB 로 옮겨야 한다. 서버를 다시 켜면 진행 중 작업 정보는 사라진다(수집 결과는 DB 에 이미 저장된 만큼 남음). - [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다. 수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다. 아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다. - 쇼핑몰별 [중지]: SyncJob.stop_shop(code) → 그 쇼핑몰만 같은 방식(다음 API 호출 직전, 저장 안 함)으로 멈추고 "중지됨", 업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 저장 중이면 못 멈춘다. """ from __future__ import annotations import threading import time import uuid from datetime import date from typing import Any from .adapters.base import Cancelled, Progress MAX_JOBS = 20 _LOCK = threading.Lock() _JOBS: dict[str, "SyncJob"] = {} # 끝났지만 막대에서 빼는 쇼핑몰(수집할 수 없어 바로 끝난 것) — 전체 진행률 계산에서 제외 PASSIVE_STATUS = frozenset({"not_implemented", "not_configured"}) class ShopProgress(Progress): """쇼핑몰 하나의 진행 상황. state: waiting → running → saving → done | error | skipped | cancelled.""" def __init__(self, code: str, name: str, *, active: bool = True, job: "SyncJob | None" = None) -> None: self.code, self.name, self.active, self.job = code, name, active, job self.state = "waiting" self.done = self.total = self.items = self.upserted = 0 self.unit = "단계" self.status = self.label = self.message = "" self.started_at = self.finished_at = 0.0 self.stop_requested = False # 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로 self._lock = threading.Lock() def stop(self) -> bool: """[중지] — 대기·수집 중일 때만(저장 중·끝난 뒤엔 못 멈춤). 받아들였으면 True.""" with self._lock: if self.state not in ("waiting", "running"): return False self.stop_requested = True return True # ── 어댑터가 부르는 쪽(Progress) ── def plan(self, total: int, unit: str = "단계") -> None: with self._lock: self.total, self.unit, self.done = max(0, int(total)), unit or "단계", 0 def add(self, n: int) -> None: with self._lock: self.total += max(0, int(n)) def check(self) -> None: if self.cancel_requested and self.state == "running": raise Cancelled("사용자가 이 쇼핑몰 업데이트를 중지했습니다." if self.stopped_only else "사용자가 업데이트를 취소했습니다.") @property def cancel_requested(self) -> bool: """멈춰야 하나 — 업데이트 전체 취소 또는 이 쇼핑몰만 중지.""" return self.stop_requested or bool(self.job is not None and self.job.cancel_requested) @property def stopped_only(self) -> bool: """이 쇼핑몰만 중지(전체 취소가 아님) — 업데이트는 다음 쇼핑몰로 계속된다.""" return self.stop_requested and not (self.job is not None and self.job.cancel_requested) def step(self, n: int = 1, *, items: int = 0) -> None: self.check() with self._lock: self.done += max(0, int(n)) self.items += max(0, int(items)) if self.total and self.done > self.total: # 계획보다 많이 돌면 전체를 늘려 100% 를 넘지 않게 self.total = self.done # ── sync 가 부르는 쪽 ── def start(self) -> None: with self._lock: self.state, self.started_at = "running", time.time() def saving(self) -> None: with self._lock: self.state = "saving" def finish(self, *, upserted: int, message: str = "") -> None: with self._lock: self.state, self.upserted, self.message, self.status = "done", int(upserted), message, "ok" if self.total: self.done = self.total self.finished_at = time.time() def fail(self, *, status: str, label: str, message: str) -> None: with self._lock: self.state, self.status, self.label, self.message = "error", status, label, message if status in PASSIVE_STATUS: self.active = False self.finished_at = time.time() def cancelled(self) -> None: with self._lock: self.state, self.status = "cancelled", "cancelled" self.message = "중지됨" if self.stopped_only else "취소됨" self.finished_at = time.time() def skip(self, message: str) -> None: with self._lock: self.state, self.status, self.message = "skipped", "running", message self.finished_at = time.time() @property def finished(self) -> bool: return self.state in ("done", "error", "skipped", "cancelled") def fraction(self) -> float: if self.finished: return 1.0 if self.state == "saving": return 0.98 if self.state == "running" and self.total: return min(0.97, self.done / self.total) return 0.0 def snapshot(self) -> dict[str, Any]: with self._lock: return { "code": self.code, "name": self.name, "active": self.active, "state": self.state, "done": self.done, "total": self.total, "unit": self.unit, "items": self.items, "upserted": self.upserted, "status": self.status, "label": self.label, "message": self.message, "stop_requested": self.stop_requested, "fraction": round(self.fraction(), 4), "elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0, } class SyncJob: def __init__(self, *, user: str, start: date | None, end: date | None) -> None: self.id = uuid.uuid4().hex[:12] self.user, self.start, self.end = user, start, end self.created_at = time.time() self.finished_at = 0.0 self.shops: list[ShopProgress] = [] self.error = "" self.last_update_at: str | None = None self.cancel_requested = False self.cancelled_by = "" self._lock = threading.Lock() def set_targets(self, targets: list[tuple[str, str, bool]], start: date, end: date) -> dict[str, ShopProgress]: with self._lock: self.start, self.end = start, end self.shops = [ShopProgress(code, name, active=active, job=self) for code, name, active in targets] return {s.code: s for s in self.shops} def cancel(self, user: str = "") -> None: """[업데이트 취소] — 돌고 있는 쇼핑몰은 다음 API 호출 직전에, 기다리는 쇼핑몰은 차례가 오면 멈춘다.""" with self._lock: if not self.finished_at and not self.cancel_requested: self.cancel_requested, self.cancelled_by = True, user def stop_shop(self, code: str) -> bool: """쇼핑몰별 [중지] — 그 쇼핑몰만 멈추고 다음 쇼핑몰로. 끝난 작업·없는 쇼핑몰·저장 중·끝난 쇼핑몰은 False.""" with self._lock: if self.finished_at: return False shop = next((s for s in self.shops if s.code == code), None) return bool(shop is not None and shop.stop()) def finish(self, *, error: str = "", last_update_at: str | None = None) -> None: with self._lock: self.error, self.last_update_at, self.finished_at = error, last_update_at, time.time() @property def finished(self) -> bool: return bool(self.finished_at) def snapshot(self) -> dict[str, Any]: with self._lock: shops = [s.snapshot() for s in self.shops] active = [s for s in shops if s["active"]] return { "id": self.id, "finished": self.finished, "error": self.error, "user": self.user, "cancel_requested": self.cancel_requested, "from": self.start.isoformat() if self.start else None, "to": self.end.isoformat() if self.end else None, "elapsed": round((self.finished_at or time.time()) - self.created_at, 1), "last_update_at": self.last_update_at, "shops": shops, "overall": { "shops": len(active), "finished": sum(1 for s in active if s["state"] in ("done", "error", "skipped", "cancelled")), "fraction": round(sum(s["fraction"] for s in active) / len(active), 4) if active else (1.0 if self.finished else 0.0), "items": sum(s["items"] for s in shops), "upserted": sum(s["upserted"] for s in shops), }, } def create_job(*, user: str, start: date | None, end: date | None) -> SyncJob: job = SyncJob(user=user, start=start, end=end) with _LOCK: _JOBS[job.id] = job if len(_JOBS) > MAX_JOBS: # 오래된 끝난 작업부터 정리 for jid, j in sorted(_JOBS.items(), key=lambda kv: kv[1].created_at): if len(_JOBS) <= MAX_JOBS: break if j.finished: del _JOBS[jid] return job def get_job(job_id: str) -> SyncJob | None: with _LOCK: return _JOBS.get(job_id) def running_job() -> SyncJob | None: """지금 돌고 있는 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고.""" with _LOCK: live = [j for j in _JOBS.values() if not j.finished] return max(live, key=lambda j: j.created_at) if live else None