Files
king 1efc59ffcf fix(cafe24): 진열/판매 변경 후 예전 상태로 보이는 읽기 지연 보정
- overlay_recent_write: updated_date 가 같아도 값이 다르면 지연으로 판정
  (진열/판매만 바꾼 PUT 은 updated_date 를 올리지 않을 수 있음)
- 상품 목록에도 최근 쓰기 스냅샷 보정 적용(overlay_product_rows) —
  목록·필터가 예전 값으로 보이고 캐시가 예전 값으로 덮이던 문제
- 예약 폼 현재 상태 미리보기도 load_product 로 보정
- PUT 응답에 product_no 가 없어도 스냅샷 저장
- 회귀 테스트 추가

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

535 lines
24 KiB
Python

"""카페24 쓰기 공통 처리 — 잠금 · 유효 현재값 판정 · 백업 · 시도 기록 · 결과 분류.
상세설명(과 예약의 진열/판매)을 카페24에 쓰는 모든 경로 — 즉시 적용, 버전 복원,
예약 worker — 가 `write_product` 한 곳을 지난다. 경로마다 판정이 달라 생기던 문제
(예약 직전 백업이 지연된 옛 HTML 을 담는 등)를 막기 위해서다.
순서 (docs/CAFE24_MODULE.md 3-2, 3-5)
상품 잠금(DB lease) → 카페24 현재값 GET → 결과 모르는 이전 시도 확인
→ 유효 현재값(읽기 지연 보정) → BACKUP → 지문 대조(충돌 거부)
→ 잠금 펜싱 → 시도 기록(STARTED) → PUT
→ 원격 결과 분류(REMOTE_OK / REMOTE_FAILED / UNKNOWN)
→ 스냅샷 · 버전(MANUAL/SCHEDULED/ROLLBACK) 기록(RECORDED)
원칙
- 읽기 지연 판정의 근거는 **원격 반영이 확인된 쓰기**(cafe24_write_attempts 의
REMOTE_OK/RECORDED)뿐이다. 충돌로 거절된 적용의 백업·예약 초안은 넣지 않는다.
- PUT 이 성공한 뒤의 실패(스냅샷·버전 기록)는 "적용 실패"가 아니다. 결과에
record_error 로 알리고, 시도 기록(REMOTE_OK)에 남은 내용으로 나중에 복구한다.
재적용하지 않는다.
- 반영 여부를 모르는 시도(STARTED/UNKNOWN)가 남아 있으면 같은 상품 상세설명을
다시 쓰지 않는다(WriteBlocked). 카페24 값이 그 시도의 내용과 같으면 자동 확정.
- 잠금은 웹 여러 프로세스 + worker 가 공유하는 DB 표(cafe24_write_locks)다.
카페24 관리자 화면에서 사람이 동시에 고치는 것은 막을 수 없다 — 그것은 지문
대조(편집 시작 시점 값과 비교)로만 잡는다.
카페24 호출은 `app.integrations.cafe24` 만 쓴다(httpx 직접 호출 금지).
"""
from __future__ import annotations
import logging
import os
import socket
import time
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import timedelta
from typing import Any, Callable, Iterator
from app.integrations.cafe24 import Cafe24Error, products
from app.timezone import now_kst
from . import store
from .common import read_lag_grace_minutes
logger = logging.getLogger("cafe24.writes")
DEFAULT_LOCK_TTL_SEC = 300 # 이미지 업로드(최대 120초 × 재시도)도 담을 만큼
DEFAULT_LOCK_WAIT_SEC = 3.0 # 웹 요청은 짧게만 기다린다 — 오래 걸리면 "수정 중" 안내
def _env_number(name: str, default: float) -> float:
try:
value = float(str(os.getenv(name) or "").strip())
except ValueError:
return default
return value if value >= 0 else default
def lock_ttl_seconds() -> int:
return max(30, int(_env_number("CAFE24_WRITE_LOCK_TTL_SEC", DEFAULT_LOCK_TTL_SEC)))
def lock_wait_seconds() -> float:
return min(30.0, _env_number("CAFE24_WRITE_LOCK_WAIT_SEC", DEFAULT_LOCK_WAIT_SEC))
# ════════════════════════════════════════════════════════════
# 예외 — http_status 는 JSON API 가 그대로 쓴다
# ════════════════════════════════════════════════════════════
class WriteError(Exception):
http_status = 500
def __init__(self, message: str, *, backup_id: int = 0, attempt_id: int = 0):
super().__init__(message)
self.backup_id = backup_id
self.attempt_id = attempt_id
class WriteSetupError(WriteError):
"""마이그레이션 005 미적용 등 — 안전장치 없이 쓰지 않는다."""
http_status = 503
class WriteBusy(WriteError):
"""다른 요청(또는 예약 실행)이 같은 대상을 쓰는 중이거나, 잠금을 잃었다."""
http_status = 409
class WriteConflict(WriteError):
"""편집 시작 뒤 카페24 값이 바뀌었다(지문 불일치)."""
http_status = 409
class WriteBlocked(WriteError):
"""반영 여부를 모르는 이전 시도가 남아 있다 — 사람이 확정하기 전에는 쓰지 않는다."""
http_status = 409
def __init__(self, message: str, *, attempts: list[dict[str, Any]] | None = None, **kw: Any):
super().__init__(message, **kw)
self.attempts = attempts or []
class RemoteWriteFailed(WriteError):
"""카페24가 거절 — 반영되지 않은 것이 확실하다."""
http_status = 502
class RemoteWriteUnknown(WriteError):
"""요청이 도달했을 수 있으나 응답을 못 받았다 — 반영 여부를 모른다. 재적용 금지."""
http_status = 502
# ════════════════════════════════════════════════════════════
# 잠금
# ════════════════════════════════════════════════════════════
def product_lock_key(product_no: int) -> str:
return f"product:{int(product_no)}"
def design_lock_key(file_key: str) -> str:
return f"design:{file_key}"
def lock_owner(actor: str) -> str:
"""잠금 소유자 표기 — '사람|호스트:pid'. 안내 문구에는 '|' 앞(사람)만 쓴다."""
return f"{actor or '-'}|{socket.gethostname()}:{os.getpid()}"
def require_schema(st: Any) -> None:
try:
ok = st.write_schema_ready()
except Exception as exc: # noqa: BLE001 — DB 접속 실패도 "쓰지 않음"으로
raise WriteSetupError(f"cafe24_db 상태를 확인하지 못해 카페24에 쓰지 않았습니다: {type(exc).__name__}") from exc
if not ok:
raise WriteSetupError(
"cafe24_db 마이그레이션 005(쓰기 안전장치)가 적용되지 않아 카페24에 쓰지 않았습니다. "
"관리자에게 scripts/sql/cafe24_db_005_write_safety.sql 적용을 요청하세요."
)
@dataclass
class WriteLock:
st: Any
key: str
token: str
ttl: int
def still_mine(self) -> bool:
"""아직 내 잠금이면 연장하고 True(펜싱). 만료돼 넘어갔으면 False."""
try:
return bool(self.st.renew_lock(self.key, self.token, ttl_seconds=self.ttl))
except Exception: # noqa: BLE001 — 확인할 수 없으면 쓰지 않는다
logger.exception("잠금 연장 실패 %s", self.key)
return False
@contextmanager
def write_lock(
st: Any,
key: str,
*,
actor: str,
purpose: str,
wait_seconds: float | None = None,
ttl_seconds: int | None = None,
) -> Iterator[WriteLock]:
"""DB 잠금을 잡은 채 작업한다. 못 잡으면 WriteBusy, 스키마가 없으면 WriteSetupError."""
require_schema(st)
ttl = int(ttl_seconds or lock_ttl_seconds())
wait = lock_wait_seconds() if wait_seconds is None else max(0.0, float(wait_seconds))
deadline = time.monotonic() + wait
while True:
token = st.acquire_lock(key, owner=lock_owner(actor), purpose=purpose, ttl_seconds=ttl)
if token:
break
if time.monotonic() >= deadline:
raise WriteBusy(_busy_message(st, key))
time.sleep(0.25)
lock = WriteLock(st=st, key=key, token=token, ttl=ttl)
try:
yield lock
finally:
try:
st.release_lock(key, token)
except Exception: # noqa: BLE001 — 못 풀어도 만료되면 풀린다
logger.exception("잠금 해제 실패 %s (만료 후 자동 해제)", key)
def _busy_message(st: Any, key: str) -> str:
try:
holder = st.lock_holder(key) or {}
except Exception: # noqa: BLE001
holder = {}
who = str(holder.get("owner") or "").split("|", 1)[0]
what = str(holder.get("purpose") or "")
detail = " · ".join(p for p in (what, who) if p and p != "-")
return "다른 작업이 같은 대상을 수정하고 있습니다" + (f"({detail})" if detail else "") + ". 잠시 후 다시 시도하세요."
# ════════════════════════════════════════════════════════════
# 유효 현재값 — 읽기 지연 보정 (확인된 쓰기만 근거)
# ════════════════════════════════════════════════════════════
def resolve_effective(
st: Any, product_no: int, cafe24_html: str, *, fetched_updated: object = None
) -> tuple[str, str, dict[str, Any] | None]:
"""(유효 HTML, 상태 store.SYNC_*, 마지막 확인된 쓰기)."""
grace = read_lag_grace_minutes()
since = now_kst() - timedelta(minutes=grace)
lineage = st.write_lineage(product_no, since=since)
if not lineage:
return cafe24_html, store.SYNC_NONE, None
last = lineage[0]
effective, state = store.resolve_description(
cafe24_html,
last_write=last,
known_digests=store.lineage_digests(lineage),
grace_minutes=grace,
fetched_updated=fetched_updated,
)
return effective, state, last
# ════════════════════════════════════════════════════════════
# 기록 — PUT 성공 뒤의 로컬 저장(실패해도 "적용 실패"가 아니다)
# ════════════════════════════════════════════════════════════
def remember_product_write(st: Any, product_no: int, updated: dict[str, Any]) -> tuple[dict[str, Any], str]:
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. (정규화된 상품 행, 기록 오류 문자열)."""
if updated and not updated.get("product_no"):
# 응답에 상품번호가 빠져도 기록은 남긴다 — 안 남기면 지연 보정이 안 돼 예전 값이 보인다.
updated = {**updated, "product_no": int(product_no)}
info = products.normalize_product(updated) if updated else {}
if not info.get("product_no"):
return info, ""
try:
st.upsert_products([info])
st.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
except Exception as exc: # noqa: BLE001 — 카페24에는 이미 반영됐다
logger.exception("상품 %s 쓰기 스냅샷 저장 실패", product_no)
return info, f"{type(exc).__name__}: {exc}"
return info, ""
def audit_safe(st: Any, **fields: Any) -> None:
"""감사로그 — 실패해도 호출부 결과를 바꾸지 않는다(이미 카페24에 반영된 뒤일 수 있다)."""
try:
st.log_audit(**fields)
except Exception: # noqa: BLE001
logger.exception("감사로그 기록 실패: %s", fields.get("action"))
def record_attempt(st: Any, attempt: dict[str, Any]) -> int:
"""원격 반영된 시도의 버전을 남기고 RECORDED 로 바꾼다(이미 있으면 그 id). 멱등.
진열/판매만 바꾼 시도(상세설명 없음)는 버전을 만들지 않고 상태만 RECORDED 로 둔다.
"""
if not attempt.get("target_digest") and not attempt.get("target_revision_id"):
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_RECORDED, remote_ok=True)
return 0
origin = str(attempt.get("origin") or store.ORIGIN_MANUAL)
revision_type = store.ORIGIN_REVISION_TYPE.get(origin, "MANUAL")
source = store.SOURCE_REVISION if origin == store.ORIGIN_ROLLBACK else ""
source_revision = attempt.get("target_revision_id") if origin != store.ORIGIN_MANUAL else None
return int(st.record_attempt_revision(
int(attempt["id"]),
revision_type=revision_type,
memo=str(attempt.get("memo") or ""),
created_by=str(attempt.get("actor") or ""),
source=source,
source_revision_id=int(source_revision) if source_revision else None,
))
def _flags_match(product: dict[str, Any], attempt: dict[str, Any]) -> bool:
for key in ("set_display", "set_selling"):
want = attempt.get(key)
if want is None:
continue
field_name = key.replace("set_", "")
if products._flag(product.get(field_name)) != bool(want): # noqa: SLF001 — 같은 규칙
return False
return True
def attempt_matches_remote(attempt: dict[str, Any], product: dict[str, Any]) -> bool:
"""카페24 현재값이 그 시도가 쓰려던 결과와 같은가(같으면 결과를 "반영됨"으로 확정해도 된다)."""
if not product:
return False
digest = str(attempt.get("target_digest") or "")
if digest and store.content_digest(str(product.get("description") or "")) != digest:
return False
if not digest and attempt.get("set_display") is None and attempt.get("set_selling") is None:
return False
return _flags_match(product, attempt)
def settle_open_attempts(
st: Any, product_no: int, *, product: dict[str, Any], actor: str = "SYSTEM"
) -> list[dict[str, Any]]:
"""열린 시도를 정리하고 **아직 결과를 모르는 것**만 돌려준다. 잠금 안에서 부른다.
REMOTE_OK → 버전 기록을 채운다(기록 복구)
STARTED / UNKNOWN → 카페24 현재값이 그 시도의 결과와 같으면 반영됨으로 확정
(예약이 "확인 필요"였다면 완료로 바꾼다). 다르면 남긴다.
"""
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
unresolved: list[dict[str, Any]] = []
for attempt in st.open_attempts(product_no, since=since):
status = attempt.get("status")
if status == store.ATTEMPT_REMOTE_OK:
try:
record_attempt(st, attempt)
except Exception: # noqa: BLE001 — 원격은 반영됨. 다음 기회에 다시.
logger.exception("시도 #%s 기록 복구 실패", attempt.get("id"))
continue
if attempt_matches_remote(attempt, product):
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),
)
try:
record_attempt(st, attempt)
except Exception: # noqa: BLE001
logger.exception("시도 #%s 기록 실패(자동 확정 후)", attempt.get("id"))
if attempt.get("schedule_id"):
st.review_schedule(
int(attempt["schedule_id"]), status=store.STATUS_SUCCESS,
note="자동 확인: 카페24 현재값이 예약 내용과 같습니다", actor=actor, action="auto_verify",
)
continue
unresolved.append(attempt)
return unresolved
def describe_attempt(attempt: dict[str, Any]) -> str:
origin = {store.ORIGIN_MANUAL: "즉시 적용", store.ORIGIN_SCHEDULED: "예약", store.ORIGIN_ROLLBACK: "복원"}.get(
str(attempt.get("origin") or ""), "적용")
when = str(attempt.get("created_at") or "").replace("T", " ")[:16]
who = str(attempt.get("actor") or "")
sched = f" · 예약 #{attempt['schedule_id']}" if attempt.get("schedule_id") else ""
return f"시도 #{attempt.get('id')} ({origin}{sched}, {when}{', ' + who if who else ''})"
# ════════════════════════════════════════════════════════════
# 본 처리
# ════════════════════════════════════════════════════════════
@dataclass
class WriteOutcome:
attempt_id: int = 0
backup_id: int = 0
revision_id: int = 0
changed: bool = True # False = 바뀐 것이 없어 PUT 하지 않음
pending: bool = False # 백업이 "마지막 확인된 쓰기" 기준이었나(카페24 읽기 지연)
recorded: bool = False # 버전 기록까지 끝났나
record_error: str = "" # PUT 성공 뒤 로컬 기록 실패 사유(재적용 금지 — 자동 복구)
confirmed: bool = False # PUT 뒤 GET 이 새 값을 돌려줬나
updated: dict[str, Any] = field(default_factory=dict)
def write_product(
st: Any,
api: Any,
product_no: int,
*,
lock: WriteLock,
origin: str,
actor: str,
html: str | None,
base_fingerprint: str | None = None,
set_display: bool | None = None,
set_selling: bool | None = None,
schedule_id: int | None = None,
target_revision_id: int | None = None,
memo: str = "",
skip_if_same: bool = False,
extra_fence: Callable[[], bool] | None = None,
wait_confirm: bool = True,
) -> WriteOutcome:
"""상세설명(html)·진열/판매를 카페24에 쓴다. 잠금(lock)을 잡은 채 부른다.
예외(아무것도 쓰지 않음): Cafe24Error(현재값 조회 실패), WriteBlocked, WriteConflict,
WriteBusy(펜싱 실패) / RemoteWriteFailed(거절) / RemoteWriteUnknown(반영 여부 모름).
PUT 성공 뒤의 로컬 기록 실패는 예외가 아니라 WriteOutcome.record_error 로 알린다.
"""
mall_id = str(getattr(api.config, "mall_id", "") or "")
shop_no = 1
out = WriteOutcome()
current_html: str | None = None
effective: str | None = None
if html is not None:
product = products.get_product(api.client, product_no)
if not product:
raise Cafe24Error("카페24에서 상품을 찾지 못했습니다.")
desc = products.descriptions_from_product(product)
current_html = desc.description
unresolved = [a for a in settle_open_attempts(st, product_no, product=product, actor=actor)
if a.get("target_digest")]
if unresolved:
names = ", ".join(describe_attempt(a) for a in unresolved[:3])
raise WriteBlocked(
f"이전 적용의 반영 여부를 아직 확인하지 못했습니다: {names}. "
"쇼핑몰에서 확인한 뒤 편집기 위 안내에서 결과를 확정하고 다시 시도하세요.",
attempts=unresolved,
)
effective, state, last = resolve_effective(
st, product_no, current_html, fetched_updated=product.get("updated_date")
)
out.pending = state == store.SYNC_PENDING
label = {store.ORIGIN_SCHEDULED: f"예약 #{schedule_id} 적용 직전 자동 백업",
store.ORIGIN_ROLLBACK: "복원 직전 자동 백업"}.get(origin, "적용 직전 자동 백업")
out.backup_id = st.add_revision(
product_no=product_no,
html_content=effective,
revision_type=store.REVISION_BACKUP,
memo=label + (" (카페24 읽기 지연 — 마지막으로 확인된 적용값 기준)" if out.pending else ""),
created_by=actor,
mall_id=mall_id,
shop_no=shop_no,
source=store.SOURCE_LAST_WRITE if out.pending else store.SOURCE_OBSERVED,
source_revision_id=(last or {}).get("applied_revision_id") if out.pending else None,
)
# 모바일이 PC 와 달랐다면 그것도 남긴다 — 아래 쓰기로 모바일이 PC 와 같아진다.
if desc.mobile_description and desc.mobile_description != desc.description:
st.add_revision(
product_no=product_no,
html_content=desc.mobile_description,
revision_type=store.REVISION_BACKUP,
memo=label + " (모바일 — PC와 달랐던 내용)",
created_by=actor,
mall_id=mall_id,
shop_no=shop_no,
source=store.SOURCE_OBSERVED,
)
if base_fingerprint and base_fingerprint != store.fingerprint(effective):
raise WriteConflict(
"편집하는 동안 카페24 값이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
backup_id=out.backup_id,
)
if skip_if_same and html == effective and set_display is None and set_selling is None:
out.changed = False
return out
# 펜싱 — 잠금이 만료돼 남에게 넘어갔으면 쓰지 않는다.
if not lock.still_mine() or (extra_fence is not None and not extra_fence()):
raise WriteBusy("작업 시간이 길어져 잠금이 만료되었습니다. 카페24에 쓰지 않았습니다 — 다시 시도하세요.",
backup_id=out.backup_id)
out.attempt_id = st.start_attempt(
product_no=int(product_no),
mall_id=mall_id,
shop_no=shop_no,
origin=origin,
schedule_id=schedule_id,
actor=actor,
backup_revision_id=out.backup_id or None,
observed_digest=store.content_digest(current_html) if current_html is not None else "",
base_digest=store.content_digest(effective) if effective is not None else "",
target_digest=store.content_digest(html) if html is not None else "",
# 예약·복원은 내용이 버전(target_revision_id)에 있다 — 즉시 적용만 시도에 보관한다.
target_html=html if (html is not None and not target_revision_id) else "",
target_revision_id=target_revision_id,
set_display=set_display,
set_selling=set_selling,
memo=(memo or "")[:500],
)
try:
updated = products.update_product(
api.client,
product_no,
description=html,
# PC/모바일 구분 안 함 — mobile_description 은 보내지 않고 "PC 와 동일"을 강제.
separated_mobile_description="F" if html is not None else None,
display=set_display,
selling=set_selling,
)
except Exception as exc: # noqa: BLE001 — 분류해서 다시 던진다
known = isinstance(exc, Cafe24Error)
unknown = (not known) or bool(getattr(exc, "maybe_applied", False))
message = str(exc) if known else f"{type(exc).__name__}: {exc}"
try:
st.update_attempt(
out.attempt_id,
status=store.ATTEMPT_UNKNOWN if unknown else store.ATTEMPT_REMOTE_FAILED,
error=message,
only_from=(store.ATTEMPT_STARTED,),
)
except Exception: # noqa: BLE001 — 기록 실패 시 STARTED 로 남는다(= 결과 모름, 안전 쪽)
logger.exception("시도 #%s 결과 기록 실패", out.attempt_id)
kind = RemoteWriteUnknown if unknown else RemoteWriteFailed
raise kind(message, backup_id=out.backup_id, attempt_id=out.attempt_id) from exc
# ── 여기부터는 카페24에 반영된 뒤다. 무엇이 실패해도 "적용 실패"가 아니다. ──
out.updated = updated if isinstance(updated, dict) else {}
errors: list[str] = []
try:
st.update_attempt(
out.attempt_id, status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
remote_updated_at=str(out.updated.get("updated_date") or ""),
only_from=(store.ATTEMPT_STARTED,),
)
except Exception as exc: # noqa: BLE001
logger.exception("시도 #%s REMOTE_OK 기록 실패", out.attempt_id)
errors.append(f"시도 상태: {type(exc).__name__}")
if out.updated.get("product_no"):
_, snap_error = remember_product_write(st, product_no, out.updated)
if snap_error:
errors.append(f"스냅샷: {snap_error}")
try:
out.revision_id = record_attempt(st, {
"id": out.attempt_id, "origin": origin, "actor": actor, "memo": memo,
"target_revision_id": target_revision_id,
"target_digest": store.content_digest(html) if html is not None else "",
})
out.recorded = True
except Exception as exc: # noqa: BLE001
logger.exception("시도 #%s 버전 기록 실패", out.attempt_id)
errors.append(f"버전 기록: {type(exc).__name__}: {exc}")
out.record_error = "; ".join(errors)
if html is not None and wait_confirm:
# 카페24 관리자 API 의 쓰기 직후 읽기 지연을 짧게 흡수(확인 실패는 실패가 아니다).
out.confirmed = products.wait_for_description(api.client, product_no, html)
return out