6822329ff2
- 편집기 아래 「예약 적용」 폼에 대표 이미지 파일 칸 — 고르면 그 시각에 교체
(상세페이지·진열·판매와 한 예약에 같이 걸 수 있음, 이미지만도 가능)
- 마이그레이션 006: 예약 image_type/image_name + cafe24_schedule_images(BYTEA, CASCADE),
"할 일 없는 예약" CHECK 에 이미지 포함
- worker: 이미지 먼저 set_main_image(즉시 교체와 같은 A 타입) → 스냅샷 → 상세페이지·진열/판매
- 예약 목록 「적용 내용」에 대표이미지 표시 + 미리보기 썸네일(GET /cafe24/schedules/{id}/image)
- 이미지 없는 예약 INSERT 는 006 컬럼을 안 써서 마이그레이션 전에도 기존 예약 등록 유지
- 테스트(경로·검증·worker 순서)·문서 갱신, cafe24.css 캐시 버전 올림
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
355 lines
18 KiB
Python
355 lines
18 KiB
Python
"""카페24 예약 실행 worker.
|
|
|
|
python -m app.modules.cafe24.worker --loop 60 # 60초마다 확인 (운영)
|
|
python -m app.modules.cafe24.worker --once # 한 번만 처리하고 종료
|
|
|
|
왜 별도 프로세스인가
|
|
예약은 브라우저를 닫아도, 아무도 화면을 보고 있지 않아도 그 시각에 실행돼야 한다.
|
|
웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 그대로 무너진다.
|
|
compose 서비스 `dbx-cafe24-worker` 가 web 과 같은 이미지로 이 모듈을 돌린다.
|
|
|
|
한 번에 한 건씩, lease 로 잡는다 (마이그레이션 005)
|
|
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잡아 PROCESSING + lease
|
|
(만료 시각·token)로 바꾼다. worker 가 여럿이어도 같은 예약을 두 번 잡지 않는다.
|
|
카페24에 쓰기 직전 lease 를 연장해 "아직 내 것인가"를 확인하고(펜싱), 결과는
|
|
token 이 맞을 때만 남긴다 — 만료 뒤 늦게 끝난 worker 가 남의 결과를 덮지 않는다.
|
|
|
|
적용 순서는 화면 편집과 같다 (writes.write_product 공용)
|
|
상품 잠금 → 카페24 현재값 재조회 → 유효 현재값(읽기 지연 보정) → BACKUP
|
|
→ 시도 기록 → PUT → 버전(SCHEDULED)·스냅샷 기록
|
|
예약 직전 백업도 읽기 지연을 보정한 값이다(카페24가 아직 옛 HTML 을 돌려줘도
|
|
그것을 "직전 내용"으로 남기지 않는다). 백업의 source 로 관측값/확인된 적용값을 구분한다.
|
|
|
|
결과 분류
|
|
카페24가 거절 → 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시, 소진되면 FAILED
|
|
반영 여부 모름 → NEEDS_REVIEW (자동 재적용 금지 — 사람이 쇼핑몰을 보고 확정)
|
|
반영 성공·기록 실패 → SUCCESS + "기록 복구 필요" 메모. 기록은 다음 주기에 채운다(재적용 없음)
|
|
같은 상품을 다른 작업이 쓰는 중 → 재시도 횟수를 쓰지 않고 잠시 뒤 다시
|
|
|
|
중단 복구 (recover)
|
|
lease 가 만료된 PROCESSING 은 그 예약의 마지막 쓰기 시도를 보고 판정한다
|
|
(store.recovery_decision). 무조건 PENDING 으로 돌리지 않는다 — 카페24에 이미 반영됐을
|
|
수 있기 때문이다. 카페24 현재값이 예약 결과와 같으면 반영된 것으로 확정한다.
|
|
|
|
토큰 갱신은 TokenService 가 행 잠금 안에서 하므로 web 과 동시에 떠 있어도 안전하다.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import logging
|
|
import os
|
|
import socket
|
|
import sys
|
|
import time
|
|
from datetime import timedelta
|
|
from typing import Any
|
|
|
|
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
|
from app.timezone import now_kst
|
|
|
|
from . import store, writes
|
|
from .common import read_lag_grace_minutes
|
|
from .routes_products import load_product
|
|
|
|
logger = logging.getLogger("cafe24.worker")
|
|
|
|
ACTOR = "SCHEDULER"
|
|
DEFAULT_LEASE_SEC = 600 # 한 건 처리(현재값 조회 + PUT + 확인)에 넉넉한 시간
|
|
LEGACY_PROCESSING_MIN = 30 # lease 컬럼이 없는 옛 PROCESSING 을 만료로 볼 시간
|
|
BUSY_RETRY_SECONDS = 30 # 같은 상품을 다른 작업이 쓰는 중일 때 다시 볼 간격
|
|
SETUP_RETRY_SECONDS = 300 # 마이그레이션 미적용 등 설정 문제일 때 다시 볼 간격
|
|
|
|
|
|
def lease_seconds() -> int:
|
|
try:
|
|
value = int(str(os.getenv("CAFE24_SCHEDULE_LEASE_SEC") or "").strip())
|
|
except ValueError:
|
|
return DEFAULT_LEASE_SEC
|
|
return max(60, value)
|
|
|
|
|
|
def worker_owner() -> str:
|
|
return f"{ACTOR}|{socket.gethostname()}:{os.getpid()}"
|
|
|
|
|
|
def _summary(row: dict[str, Any]) -> str:
|
|
return store.describe_schedule_action(
|
|
has_html=bool(row.get("revision_id")),
|
|
set_display=row.get("set_display"),
|
|
set_selling=row.get("set_selling"),
|
|
has_image=bool(row.get("image_type")),
|
|
)
|
|
|
|
|
|
def _apply_image(st: Any, api: Any, product_no: int, data: bytes, content_type: str) -> str:
|
|
"""예약 대표 이미지 교체(routes_product_info.product_image 와 같은 순서). 반환: 새 detail_image.
|
|
|
|
상세페이지·진열/판매보다 **먼저** 한다 — 뒤 단계가 실패해 재시도되면 같은 이미지를 한 번 더
|
|
올릴 뿐이라 안전하고, 앞 단계(시도 기록)가 SUCCESS 로 복구된 뒤 이미지가 빠지는 일이 없다.
|
|
"""
|
|
current, _ = load_product(st, api, product_no)
|
|
if not current:
|
|
raise Cafe24Error("카페24에서 상품을 찾지 못했습니다.")
|
|
images = products.set_main_image(api.client, product_no, data, content_type=content_type)
|
|
if not images.get("detail_image"):
|
|
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
|
writes.remember_product_write(
|
|
st, product_no, {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
|
)
|
|
return str(images["detail_image"])
|
|
|
|
|
|
def _retry_or_fail(st: Any, row: dict[str, Any], token: str, error: str) -> str:
|
|
"""재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태."""
|
|
retry_count = int(row.get("retry_count") or 0)
|
|
schedule_id = int(row["id"])
|
|
if store.can_retry(retry_count):
|
|
wait = store.retry_backoff_seconds(retry_count)
|
|
st.finish_schedule(
|
|
schedule_id, token=token, status=store.STATUS_PENDING, error=error,
|
|
next_retry_at=now_kst() + timedelta(seconds=wait), retry_count=retry_count + 1,
|
|
)
|
|
logger.warning("예약 #%s 상품 %s 실패 — %s초 후 재시도 (%s/%s): %s",
|
|
schedule_id, row.get("product_no"), wait, retry_count + 1, store.MAX_RETRY, error)
|
|
return store.STATUS_PENDING
|
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_FAILED, error=error)
|
|
writes.audit_safe(st, actor=ACTOR, action="schedule_apply", product_no=row.get("product_no"),
|
|
schedule_id=schedule_id, result="FAIL", detail=error)
|
|
logger.error("예약 #%s 상품 %s 최종 실패: %s", schedule_id, row.get("product_no"), error)
|
|
return store.STATUS_FAILED
|
|
|
|
|
|
def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
|
"""lease 로 잡은 예약 1건 실행. 반환: 남긴 상태(또는 'LEASE_LOST')."""
|
|
schedule_id = int(row["id"])
|
|
product_no = int(row["product_no"])
|
|
token = str(row.get("lease_token") or "")
|
|
lease = lease_seconds()
|
|
revision_id = row.get("revision_id")
|
|
set_display = row.get("set_display")
|
|
set_selling = row.get("set_selling")
|
|
|
|
def fence() -> bool:
|
|
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
|
|
|
|
image_type = str(row.get("image_type") or "")
|
|
new_image = ""
|
|
try:
|
|
html: str | None = None
|
|
if revision_id:
|
|
revision = st.get_revision(int(revision_id))
|
|
if not revision:
|
|
raise Cafe24Error(f"예약이 가리키는 버전 {revision_id} 을 찾을 수 없습니다.")
|
|
html = str(revision.get("html_content") or "")
|
|
if not html.strip():
|
|
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
|
image = st.get_schedule_image(schedule_id) if image_type else b""
|
|
if image_type and not image:
|
|
raise Cafe24Error("예약해 둔 대표 이미지 파일을 찾을 수 없습니다.")
|
|
with writes.write_lock(
|
|
st, writes.product_lock_key(product_no), actor=ACTOR,
|
|
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
|
|
) as lock:
|
|
if image:
|
|
if not fence():
|
|
raise writes.WriteBusy("예약 lease 를 잃었습니다 — 다른 worker 가 처리합니다.")
|
|
new_image = _apply_image(st, api, product_no, image, image_type)
|
|
outcome = writes.WriteOutcome()
|
|
if html is not None or set_display is not None or set_selling is not None:
|
|
outcome = writes.write_product(
|
|
st, api, product_no,
|
|
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
|
|
set_display=set_display, set_selling=set_selling,
|
|
schedule_id=schedule_id, target_revision_id=int(revision_id) if revision_id else None,
|
|
memo=f"예약 #{schedule_id} 적용", extra_fence=fence,
|
|
)
|
|
except writes.WriteSetupError as exc:
|
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
|
|
next_retry_at=now_kst() + timedelta(seconds=SETUP_RETRY_SECONDS))
|
|
logger.error("예약 #%s 실행 보류 — %s", schedule_id, exc)
|
|
return store.STATUS_PENDING
|
|
except writes.WriteBusy as exc:
|
|
# 다른 작업이 같은 상품을 쓰는 중이거나 lease 를 잃었다. 재시도 횟수를 쓰지 않는다.
|
|
# (lease 를 잃었으면 finish 는 token 이 안 맞아 아무것도 바꾸지 않는다.)
|
|
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
|
|
next_retry_at=now_kst() + timedelta(seconds=BUSY_RETRY_SECONDS))
|
|
logger.info("예약 #%s 상품 %s 보류(%s): %s", schedule_id, product_no, "재대기" if done else "lease 잃음", exc)
|
|
return store.STATUS_PENDING if done else "LEASE_LOST"
|
|
except (writes.WriteBlocked, writes.RemoteWriteUnknown) as exc:
|
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_NEEDS_REVIEW, error=str(exc))
|
|
writes.audit_safe(st, actor=ACTOR, action="schedule_apply", product_no=product_no,
|
|
schedule_id=schedule_id, result="UNKNOWN", detail=str(exc))
|
|
logger.error("예약 #%s 상품 %s 확인 필요: %s", schedule_id, product_no, exc)
|
|
return store.STATUS_NEEDS_REVIEW
|
|
except (writes.RemoteWriteFailed, Cafe24Error) as exc:
|
|
return _retry_or_fail(st, row, token, str(exc))
|
|
except Exception as exc: # noqa: BLE001 — 카페24에 쓰기 전의 사고(원격 이후는 write_product 가 삼킨다)
|
|
logger.exception("예약 #%s 처리 중 예상치 못한 오류(카페24 쓰기 전)", schedule_id)
|
|
return _retry_or_fail(st, row, token, f"{type(exc).__name__}: {exc}")
|
|
|
|
note = ""
|
|
if outcome.record_error:
|
|
note = f"카페24 반영 성공 · 로컬 기록 실패(자동 복구 예정, 재적용 안 함): {outcome.record_error}"
|
|
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
|
if not done:
|
|
# 반영은 됐다. 결과를 못 남겼어도 lease 만료 후 recover 가 시도 기록(REMOTE_OK/RECORDED)을
|
|
# 보고 SUCCESS 로 확정한다 — 다시 적용하지 않는다.
|
|
logger.warning("예약 #%s 적용됨 — 결과 기록 실패(lease 잃음). 복구 단계가 확정합니다.", schedule_id)
|
|
summary = _summary(row)
|
|
writes.audit_safe(
|
|
st, actor=ACTOR, action="schedule_apply", product_no=product_no,
|
|
revision_id=outcome.revision_id or (int(revision_id) if revision_id else None),
|
|
schedule_id=schedule_id, result="SUCCESS",
|
|
detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "")
|
|
+ (f" / 대표이미지 → '{new_image}'" if new_image else "")
|
|
+ (f" / {note}" if note else ""),
|
|
)
|
|
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
|
return store.STATUS_SUCCESS
|
|
|
|
|
|
def _verify_attempt(st: Any, api: Any, attempt: dict[str, Any]) -> bool:
|
|
"""카페24 현재값이 그 시도의 결과와 같은가(같으면 반영된 것으로 확정해도 된다)."""
|
|
try:
|
|
product = products.get_product(api.client, int(attempt["product_no"]))
|
|
except Cafe24Error as exc:
|
|
logger.warning("시도 #%s 확인용 조회 실패: %s", attempt.get("id"), exc)
|
|
return False
|
|
return writes.attempt_matches_remote(attempt, product)
|
|
|
|
|
|
def recover_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
|
"""lease 만료 PROCESSING 1건 복구 판정 — 반환: 남긴 상태."""
|
|
schedule_id = int(row["id"])
|
|
token = str(row.get("lease_token") or "")
|
|
attempt = st.latest_attempt_for_schedule(schedule_id) or None
|
|
decision, note = store.recovery_decision(attempt, row.get("retry_count"))
|
|
note = f"중단 복구: {note}"
|
|
|
|
if decision == store.RECOVER_REVIEW and attempt:
|
|
try:
|
|
with writes.write_lock(st, writes.product_lock_key(int(row["product_no"])), actor=ACTOR,
|
|
purpose=f"예약 #{schedule_id} 복구 확인", wait_seconds=0):
|
|
if _verify_attempt(st, api, attempt):
|
|
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
|
resolved_by="auto:카페24 값이 예약 결과와 같음",
|
|
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN))
|
|
decision, note = store.RECOVER_RECORD, "중단 복구: 카페24 현재값이 예약 결과와 같아 반영됨으로 확정"
|
|
except writes.WriteBusy:
|
|
pass # 다음 주기에 다시 — 판정은 REVIEW 로 남긴다
|
|
if decision == store.RECOVER_RECORD and attempt:
|
|
try:
|
|
writes.record_attempt(st, attempt)
|
|
except Exception as exc: # noqa: BLE001 — 반영은 됐다. 기록은 다음 주기에.
|
|
logger.exception("예약 #%s 복구 중 버전 기록 실패", schedule_id)
|
|
note += f" (버전 기록 실패 — 자동 재시도: {type(exc).__name__})"
|
|
decision = store.RECOVER_SUCCESS
|
|
|
|
if decision == store.RECOVER_SUCCESS:
|
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
|
status = store.STATUS_SUCCESS
|
|
elif decision == store.RECOVER_REVIEW:
|
|
st.finish_schedule(schedule_id, token=token, status=store.STATUS_NEEDS_REVIEW, error=note)
|
|
status = store.STATUS_NEEDS_REVIEW
|
|
else:
|
|
status = _retry_or_fail(st, row, token, note)
|
|
writes.audit_safe(st, actor=ACTOR, action="schedule_recover", product_no=row.get("product_no"),
|
|
schedule_id=schedule_id, result=status, detail=note)
|
|
logger.warning("예약 #%s 중단 복구 → %s (%s)", schedule_id, status, note)
|
|
return status
|
|
|
|
|
|
def record_pending_attempts(st: Any) -> int:
|
|
"""카페24에 반영됐는데 버전 기록이 빠진 시도(REMOTE_OK)의 기록을 채운다."""
|
|
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
|
done = 0
|
|
for attempt in st.attempts_needing_record(since=since):
|
|
try:
|
|
with writes.write_lock(st, writes.product_lock_key(int(attempt["product_no"])), actor=ACTOR,
|
|
purpose="기록 복구", wait_seconds=0):
|
|
writes.record_attempt(st, attempt)
|
|
done += 1
|
|
except writes.WriteBusy:
|
|
continue
|
|
except Exception: # noqa: BLE001
|
|
logger.exception("시도 #%s 기록 복구 실패", attempt.get("id"))
|
|
return done
|
|
|
|
|
|
def recover(st: Any, api: Any) -> int:
|
|
"""중단 복구 — 기록 복구 + lease 만료 PROCESSING 판정. 처리 건수."""
|
|
count = record_pending_attempts(st)
|
|
rows = st.claim_expired_schedules(
|
|
owner=worker_owner(), ttl_seconds=lease_seconds(), legacy_minutes=LEGACY_PROCESSING_MIN
|
|
)
|
|
for row in rows:
|
|
try:
|
|
recover_one(st, api, row)
|
|
except Exception: # noqa: BLE001 — 한 건 때문에 나머지를 멈추지 않는다(lease 만료 후 다시)
|
|
logger.exception("예약 #%s 복구 중 오류", row.get("id"))
|
|
count += 1
|
|
return count
|
|
|
|
|
|
def process_once(st: Any, api: Any) -> int:
|
|
"""중단 복구 후, 실행할 예약을 모두 처리한다. 처리한(잡은) 예약 건수를 돌려준다."""
|
|
try:
|
|
recover(st, api)
|
|
except Exception: # noqa: BLE001 — 복구 실패가 새 예약 실행을 막지 않게
|
|
logger.exception("중단 복구 단계 오류 — 다음 주기에 다시 시도")
|
|
handled = 0
|
|
while True:
|
|
row = st.claim_due_schedule(now=now_kst(), owner=worker_owner(), ttl_seconds=lease_seconds())
|
|
if row is None:
|
|
return handled
|
|
run_one(st, api, row)
|
|
handled += 1
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description="카페24 예약 실행 worker")
|
|
parser.add_argument("--loop", type=int, default=0, help="확인 간격(초). 0 이면 한 번만")
|
|
parser.add_argument("--once", action="store_true", help="한 번만 처리하고 종료")
|
|
args = parser.parse_args(argv)
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
stream=sys.stdout,
|
|
)
|
|
|
|
dsn = (os.getenv("CAFE24_DB_URL") or "").strip()
|
|
if not dsn:
|
|
logger.error("CAFE24_DB_URL 이 설정되지 않았습니다. worker 를 시작할 수 없습니다.")
|
|
return 1
|
|
|
|
# 지연 import — psycopg 가 없는 개발 환경에서도 이 모듈을 열어볼 수 있게.
|
|
from .db import Cafe24Store # noqa: WPS433
|
|
|
|
store_db = Cafe24Store(dsn)
|
|
api = build_cafe24_api(store_db)
|
|
interval = 0 if args.once else max(0, int(args.loop))
|
|
logger.info("카페24 예약 worker 시작 (간격 %s초)", interval or "단발")
|
|
|
|
try:
|
|
while True:
|
|
try:
|
|
count = process_once(store_db, api)
|
|
if count:
|
|
logger.info("예약 %s건 처리", count)
|
|
except Exception: # noqa: BLE001 — DB 순간 장애로 죽지 않게
|
|
logger.exception("예약 처리 루프에서 오류 — 다음 주기에 다시 시도")
|
|
if not interval:
|
|
return 0
|
|
time.sleep(interval)
|
|
except KeyboardInterrupt:
|
|
logger.info("종료 요청 — worker 를 멈춥니다.")
|
|
return 0
|
|
finally:
|
|
store_db.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|