Files
dbx-main/app/modules/performance/auto_sync.py
T
king c710e184e7 feat(performance): 업데이트 중에도 [매출 업데이트]로 진행 창 다시 보기 · 서버 재시작으로 남은 진행 기록 정리
- 버튼은 업데이트 중 '업데이트 중 · 진행 보기', 누르면 진행 중 작업(수동·자동)을 새로 시작하지 않고 진행 창으로
- 서버 시작 때 perf_sync_runs running 행을 '중단됨(서버 재시작)'으로 정리 — 30분 막힘 방지

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:50:16 +09:00

158 lines
7.0 KiB
Python

"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
- 매출이 끝나면 설정된 광고 API(구글 광고)도 같은 기간으로 가져온다(ad_sync, 실패해도 매출과 무관).
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
환경변수(.env)
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
"""
from __future__ import annotations
import logging
import os
import re
import threading
import time
from datetime import datetime, timedelta
from typing import Any
from app.timezone import now_kst
logger = logging.getLogger("performance.auto_sync")
AUTO_USER = "자동 업데이트"
DEFAULT_DAYS = 10
DEFAULT_HOURS = (9, 19)
SLOT_MINUTES = 30
_started = False
_start_lock = threading.Lock()
def _env(name: str) -> str:
return (os.getenv(name, "") or "").strip()
def enabled() -> bool:
return _env("PERFORMANCE_AUTO_SYNC").lower() not in ("0", "false", "no", "off")
def sync_days() -> int:
try:
return max(1, min(90, int(_env("PERFORMANCE_AUTO_SYNC_DAYS") or DEFAULT_DAYS)))
except ValueError:
return DEFAULT_DAYS
def hour_window() -> tuple[int, int]:
m = re.fullmatch(r"(\d{1,2})\s*-\s*(\d{1,2})", _env("PERFORMANCE_AUTO_SYNC_HOURS"))
if not m:
return DEFAULT_HOURS
first, last = int(m.group(1)), int(m.group(2))
if not (0 <= first <= last <= 23):
return DEFAULT_HOURS
return first, last
def is_slot(t: datetime, hours: tuple[int, int]) -> bool:
"""t(분 단위로 자른 시각)가 회차인가 — 정각·30분, first시 정각 ~ last시 정각."""
first, last = hours
if t.minute % SLOT_MINUTES:
return False
return first <= t.hour < last or (t.hour == last and t.minute == 0)
def next_slot(after: datetime, hours: tuple[int, int]) -> datetime:
"""after 보다 뒤의 첫 회차 시각."""
t = after.replace(second=0, microsecond=0)
t += timedelta(minutes=SLOT_MINUTES - t.minute % SLOT_MINUTES)
for _ in range(48 * 2 + 2): # 하루치 회차를 넘기기 전에 반드시 찾는다
if is_slot(t, hours):
return t
t += timedelta(minutes=SLOT_MINUTES)
raise ValueError("회차를 찾을 수 없습니다")
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
"""한 회차 — 진행 창 작업으로 오늘 포함 최근 days 일 업데이트. 이미 돌고 있으면 건너뜀."""
from . import common, jobs # noqa: WPS433
from .credentials import CredentialService # noqa: WPS433
from .sync import SyncService # noqa: WPS433
if jobs.running_job() is not None:
return {"skipped": True, "reason": "다른 업데이트 진행 중"}
start, end = today - timedelta(days=days - 1), today
job = jobs.create_job(user=AUTO_USER, start=start, end=end)
sync = SyncService(store, CredentialService(store, common.key_ring), app_state=app_state)
error = ""
results: list[dict[str, Any]] = []
try:
results = sync.sync_all(start=start, end=end, trigger="schedule", user=AUTO_USER, job=job)
except Exception as exc: # noqa: BLE001 — 스레드가 죽지 않게
logger.exception("auto sync failed")
error = f"업데이트 중 오류: {type(exc).__name__}"
last = None
try:
last = store.last_update_at()
except Exception: # noqa: BLE001
pass
job.finish(error=error, last_update_at=last)
# 광고 API(구글 광고 등)도 같은 회차·같은 기간으로 — 설정된 연동만, 실패해도 매출 업데이트와 무관(2026-10-15)
ads: list[dict[str, Any]] = []
try:
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
ads = AdSyncService(store, ad_credentials(store, common.key_ring)).sync_all(start, end, user=AUTO_USER)
except Exception: # noqa: BLE001 — 스레드가 죽지 않게
logger.exception("auto ad sync failed")
ok = sum(1 for r in results if r.get("ok"))
return {"skipped": False, "from": start.isoformat(), "to": end.isoformat(), "ok": ok,
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error,
"ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]}
def start_auto_sync_thread(app_state: Any) -> bool:
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
global _started # noqa: PLW0603
store = getattr(app_state, "performance_store", None)
if store is not None and not _started:
try: # 지난 프로세스가 업데이트 도중 끝나 남은 '진행 중' 기록 정리(자동 업데이트를 꺼 둬도)
n = store.abandon_running_runs()
if n:
logger.warning("매출 업데이트 '진행 중' 기록 %d건 정리(서버 재시작으로 중단)", n)
except Exception: # noqa: BLE001 — DB 가 아직 안 붙었어도 앱은 뜬다
logger.exception("매출 업데이트 진행 기록 정리 실패")
if store is None or not enabled():
return False
with _start_lock:
if _started:
return False
_started = True
hours, days = hour_window(), sync_days()
def _loop() -> None:
due = next_slot(now_kst(), hours)
logger.info("매출 자동 업데이트 시작 — %02d~%02d시 30분마다, 최근 %d일, 다음 %s", hours[0], hours[1], days,
due.strftime("%m-%d %H:%M"))
while True:
wait = (due - now_kst()).total_seconds()
if wait > 0:
time.sleep(min(wait, 60)) # 시계 변경·절전에도 1분 안에 다시 확인
continue
try:
res = run_once(store, app_state, today=due.date(), days=days)
logger.info("매출 자동 업데이트 %s: %s", due.strftime("%H:%M"), res)
except Exception: # noqa: BLE001
logger.exception("매출 자동 업데이트 실패 — 다음 회차에 다시")
due = next_slot(max(now_kst(), due), hours)
threading.Thread(target=_loop, name="performance-auto-sync", daemon=True).start()
return True