Files
dbx-main/app/modules/performance/jobs.py
T
king 3203ff87a4 feat(performance): 매출 업데이트 진행 창 — 쇼핑몰별·전체 진행 막대
- POST /api/sync background=true 로 수집을 백그라운드 스레드에서 돌리고 작업 번호를 바로 돌려줌,
  GET /api/sync/jobs/{id}·/api/sync/current 로 진행 상황 조회(jobs.py, 메모리 보관)
- 어댑터 진행 알림(ctx.progress plan/step/add): 네이버 = 일, 11번가·카페24 = 조회 구간, 받은 자료 건수
- 창: 쇼핑몰마다 막대(대기·수집 중 n/전체·저장 중·완료 n건·실패·건너뜀·경과), 전체 막대(평균),
  수집 없는/인증정보 없는 쇼핑몰은 건너뜀 한 줄, 창을 닫아도 서버에서 계속
- [매출 업데이트]·[과거 매출 가져오기] 모두 진행 창 사용, 이미 진행 중이면 그 진행 상황을 보여 줌
- 테스트 1개 추가(27개 통과), performance.js/css 캐시 버전, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:56:57 +09:00

175 lines
7.2 KiB
Python

"""매출 업데이트 진행 상황 — 백그라운드 수집 작업(쇼핑몰별 진행 막대)을 메모리에 둔다.
- [매출 업데이트]·[과거 매출 가져오기]는 수집을 백그라운드 스레드로 돌리고 작업 번호를 바로 돌려준다.
화면은 GET /performance/api/sync/jobs/{id} 를 0.8초마다 불러 쇼핑몰별·전체 진행 막대를 그린다.
- 어댑터가 ctx.progress.plan()/step() 으로 알린 단계를 ShopProgress 가 모은다(쇼핑몰마다 단위가 다르다 —
네이버 "일", 11번가·카페24 "구간").
- 웹 프로세스 하나(uvicorn 단일 워커) 기준 — 워커를 여러 개로 늘리면 진행 상황을 DB 로 옮겨야 한다.
서버를 다시 켜면 진행 중 작업 정보는 사라진다(수집 결과는 DB 에 이미 저장된 만큼 남음).
"""
from __future__ import annotations
import threading
import time
import uuid
from datetime import date
from typing import Any
from .adapters.base import 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."""
def __init__(self, code: str, name: str, *, active: bool = True) -> None:
self.code, self.name, self.active = code, name, active
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._lock = threading.Lock()
# ── 어댑터가 부르는 쪽(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 step(self, n: int = 1, *, items: int = 0) -> None:
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 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")
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,
"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._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) for code, name, active in targets]
return {s.code: s for s in self.shops}
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,
"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")),
"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