feat(performance): 매출 업데이트 취소 버튼

- 진행 창 [업데이트 취소](시작한 사람·관리자) → POST /api/sync/jobs/{id}/cancel
- 어댑터가 API 호출 직전마다 ctx.progress.check() — 취소면 Cancelled 로 멈추고 저장하지 않음(기존 매출 그대로),
  차례가 안 온 쇼핑몰은 취소됨으로 건너뜀, 이미 끝난 쇼핑몰 결과는 유지
- 취소 실행은 perf_sync_runs failed + 업데이트 취소, 연결 상태는 바꾸지 않음
- 테스트 1개 추가(30개 통과), performance.js/css 캐시 버전, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-30 15:06:25 +09:00
parent 8b3e6dffc5
commit da63b93302
14 changed files with 178 additions and 21 deletions
+35 -8
View File
@@ -6,6 +6,9 @@
네이버 "일", 11번가·카페24 "구간").
- 웹 프로세스 하나(uvicorn 단일 워커) 기준 — 워커를 여러 개로 늘리면 진행 상황을 DB 로 옮겨야 한다.
서버를 다시 켜면 진행 중 작업 정보는 사라진다(수집 결과는 DB 에 이미 저장된 만큼 남음).
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
"""
from __future__ import annotations
@@ -16,7 +19,7 @@ import uuid
from datetime import date
from typing import Any
from .adapters.base import Progress
from .adapters.base import Cancelled, Progress
MAX_JOBS = 20
_LOCK = threading.Lock()
@@ -27,10 +30,10 @@ PASSIVE_STATUS = frozenset({"not_implemented", "not_configured"})
class ShopProgress(Progress):
"""쇼핑몰 하나의 진행 상황. state: waiting → running → saving → done | error | skipped."""
"""쇼핑몰 하나의 진행 상황. state: waiting → running → saving → done | error | skipped | cancelled."""
def __init__(self, code: str, name: str, *, active: bool = True) -> None:
self.code, self.name, self.active = code, name, active
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 = "단계"
@@ -47,7 +50,16 @@ class ShopProgress(Progress):
with self._lock:
self.total += max(0, int(n))
def check(self) -> None:
if self.cancel_requested and self.state == "running":
raise Cancelled("사용자가 업데이트를 취소했습니다.")
@property
def cancel_requested(self) -> bool:
return bool(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))
@@ -77,6 +89,11 @@ class ShopProgress(Progress):
self.active = False
self.finished_at = time.time()
def cancelled(self) -> None:
with self._lock:
self.state, self.status, self.message = "cancelled", "cancelled", "취소됨"
self.finished_at = time.time()
def skip(self, message: str) -> None:
with self._lock:
self.state, self.status, self.message = "skipped", "running", message
@@ -84,7 +101,7 @@ class ShopProgress(Progress):
@property
def finished(self) -> bool:
return self.state in ("done", "error", "skipped")
return self.state in ("done", "error", "skipped", "cancelled")
def fraction(self) -> float:
if self.finished:
@@ -115,14 +132,22 @@ class SyncJob:
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) for code, name, active in targets]
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 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()
@@ -136,12 +161,14 @@ class SyncJob:
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,
"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")),
"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),