Merge branch 'fix/cafe24-status-read-lag'
This commit is contained in:
@@ -26,6 +26,8 @@
|
||||
- **카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 값을 돌려준다(읽기 지연)** — 우리 캐시 문제가 아니다.
|
||||
- 상세설명: 카페24 값이 최근 revision 중 하나와 같으면 지연으로 보고 마지막 MANUAL/SCHEDULED 를 표시·지문 기준으로 씀(`store.resolve_description`).
|
||||
- 스칼라(상품명·가격·이미지·진열/판매): PUT 응답 스냅샷(`cafe24_products.last_write_snapshot`, 마이그레이션 004)과 GET 의 `updated_date` 를 비교해 덮어씌움(`store.overlay_recent_write`).
|
||||
- 진열/판매만 바꾼 PUT 은 `updated_date` 가 안 오를 수 있음 → **같은 시각 + 값 다름 = 지연**.
|
||||
- 단건 GET 뿐 아니라 **목록·예약 미리보기도 보정** 필수(`store.overlay_product_rows`). 빠뜨리면 "진열/중지 바꿔도 반영 안 됨"으로 보임.
|
||||
- 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분).
|
||||
- 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다.
|
||||
- API 문서 예제는 apidocs.cafe24.com 청크 JS 에서 추출(예전 `/docs/code` JSON 은 404).
|
||||
|
||||
@@ -663,6 +663,27 @@ class Cafe24Store:
|
||||
return {}
|
||||
return dict(row["last_write_snapshot"])
|
||||
|
||||
def get_recent_product_snapshots(self, grace_minutes: int) -> dict[int, dict[str, Any]]:
|
||||
"""유예시간 안에 쓴 상품들의 product 스냅샷 섹션 {product_no: {"data", "written_at"}}.
|
||||
|
||||
목록 화면이 상품마다 따로 조회하지 않고 한 번에 지연 보정하기 위한 것이다.
|
||||
섹션별 written_at 판정은 store.overlay_recent_write 가 다시 한다.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT product_no, last_write_snapshot -> 'product' AS product
|
||||
FROM cafe24_products
|
||||
WHERE last_written_at >= now() - make_interval(mins => %s)
|
||||
AND last_write_snapshot ? 'product'
|
||||
""",
|
||||
(max(0, int(grace_minutes)),),
|
||||
).fetchall()
|
||||
return {
|
||||
int(r["product_no"]): dict(r["product"])
|
||||
for r in rows if isinstance(r.get("product"), dict)
|
||||
}
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 상세페이지 HTML 버전 (append-only — UPDATE/DELETE 하지 않는다)
|
||||
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
||||
|
||||
@@ -328,6 +328,13 @@ def product_list(request: Request) -> HTMLResponse:
|
||||
error = ""
|
||||
try:
|
||||
raw_rows, truncated = products.list_all_products(api.client, product_name=keyword)
|
||||
# 목록 API 도 쓰기 직후 한동안 예전 값을 준다 — 진열/판매 등을 최근 쓰기로 보정한다.
|
||||
try:
|
||||
snapshots = st.get_recent_product_snapshots(read_lag_grace_minutes())
|
||||
except Exception: # noqa: BLE001 — 보정 실패는 목록 표시를 막지 않는다
|
||||
logger.exception("카페24 최근 쓰기 스냅샷 조회 실패")
|
||||
snapshots = {}
|
||||
raw_rows = store.overlay_product_rows(raw_rows, snapshots, grace_minutes=read_lag_grace_minutes())
|
||||
st.upsert_products([products.normalize_product(r) for r in raw_rows])
|
||||
total = len(raw_rows)
|
||||
rows = [_row_for_list(r) for r in raw_rows]
|
||||
|
||||
@@ -26,7 +26,7 @@ from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config,
|
||||
|
||||
from . import store, writes
|
||||
from .common import base_ctx, guard
|
||||
from .routes_products import _no_store
|
||||
from .routes_products import _no_store, load_product
|
||||
|
||||
logger = logging.getLogger("cafe24.schedules")
|
||||
|
||||
@@ -187,7 +187,7 @@ def schedule_current_flags(request: Request, product_no: int) -> dict:
|
||||
st, _user = require_store(request)
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
raw = products.get_product(api.client, product_no)
|
||||
raw, _ = load_product(st, api, product_no) # 방금 바꾼 진열/판매가 지연으로 예전 값이 되지 않게
|
||||
except Cafe24Error as exc:
|
||||
return {"product_no": product_no, "error": str(exc)}
|
||||
normalized = products.normalize_product(raw)
|
||||
|
||||
@@ -640,6 +640,12 @@ def overlay_recent_write(
|
||||
보다 GET 의 updated_date 가 **이전**이면 GET 이 아직 예전 레코드를 돌려주는
|
||||
것이다. 우리 서버 시계와 비교하지 않으므로 시계 차이에 영향받지 않는다.
|
||||
날짜가 없어 판정할 수 없으면 카페24 값을 그대로 둔다.
|
||||
|
||||
두 updated_date 가 **같을** 때: 카페24는 진열/판매만 바꾼 PUT 에서 updated_date 를
|
||||
올리지 않을 수 있다. 그러면 지연된 GET 도 같은 시각을 돌려주므로 "같다 = 따라잡음"
|
||||
으로 보면 예전 진열/판매가 그대로 보인다(실제 발생 — 바꿔도 반영 안 된 것처럼 보임).
|
||||
같은 시각인데 값이 다르면 카페24 기준으로 그 뒤 수정된 근거가 없으므로 지연으로 본다.
|
||||
GET 이 **이후** 시각이면 관리자 등에서 다시 고친 것 — 카페24 값을 믿는다.
|
||||
반환: (병합된 상품 dict, 지연 여부)
|
||||
"""
|
||||
if not snapshot:
|
||||
@@ -648,7 +654,9 @@ def overlay_recent_write(
|
||||
return fetched, False
|
||||
fetched_at = _as_aware(fetched.get("updated_date"))
|
||||
snap_at = _as_aware(snapshot.get("updated_date"))
|
||||
if fetched_at is None or snap_at is None or fetched_at >= snap_at:
|
||||
if fetched_at is None or snap_at is None or fetched_at > snap_at:
|
||||
return fetched, False
|
||||
if fetched_at == snap_at and not _snapshot_differs(fetched, snapshot):
|
||||
return fetched, False
|
||||
merged = dict(fetched)
|
||||
for key in SNAPSHOT_FIELDS:
|
||||
@@ -658,6 +666,50 @@ def overlay_recent_write(
|
||||
return merged, True
|
||||
|
||||
|
||||
def _snapshot_differs(fetched: dict, snapshot: dict) -> bool:
|
||||
"""GET 에 있는 스냅샷 필드 중 값이 다른 것이 있는가(문자열로 비교 — 둘 다 카페24 원본 모양)."""
|
||||
for key in SNAPSHOT_FIELDS:
|
||||
if key == "updated_date" or key not in snapshot or key not in fetched:
|
||||
continue
|
||||
if fetched[key] is None:
|
||||
continue
|
||||
if str(fetched[key]) != str(snapshot[key]):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def overlay_product_rows(
|
||||
rows: list[dict],
|
||||
snapshots: dict,
|
||||
*,
|
||||
grace_minutes: int,
|
||||
now: datetime | None = None,
|
||||
) -> list[dict]:
|
||||
"""목록(GET /admin/products) 행마다 최근 쓰기 스냅샷을 덮어씌운다.
|
||||
|
||||
snapshots: {product_no: {"data": 스냅샷, "written_at": ISO}} — 스냅샷 product 섹션.
|
||||
목록 API 도 단건 GET 과 똑같이 읽기 지연이 있다. 보정하지 않으면 진열/판매를 바꾼
|
||||
뒤 목록을 다시 불러올 때 예전 상태로 보이고(필터에 걸려 사라지기도 한다), 그 값이
|
||||
캐시(cafe24_products)에도 다시 저장된다.
|
||||
"""
|
||||
if not snapshots:
|
||||
return rows
|
||||
out: list[dict] = []
|
||||
for row in rows:
|
||||
try:
|
||||
no = int(row.get("product_no") or 0)
|
||||
except (TypeError, ValueError):
|
||||
no = 0
|
||||
section = snapshots.get(no) if no else None
|
||||
if isinstance(section, dict) and section.get("data"):
|
||||
row, _ = overlay_recent_write(
|
||||
row, snapshot=section.get("data"), written_at=section.get("written_at"),
|
||||
grace_minutes=grace_minutes, now=now,
|
||||
)
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
# ── 품목 스냅샷: 코드별 · 필드별 병합 ──
|
||||
# 스냅샷 모양: {variant_code: {필드: 값, ..., "_at": ISO, "_deleted": bool,
|
||||
# "options": [{name,value}...], "_options_before": [...]}}
|
||||
|
||||
@@ -193,6 +193,9 @@ class MemoryStore:
|
||||
def get_write_snapshot(self, product_no):
|
||||
return dict(self.snapshots.get(int(product_no), {}))
|
||||
|
||||
def get_recent_product_snapshots(self, grace_minutes):
|
||||
return {no: dict(snap["product"]) for no, snap in self.snapshots.items() if snap.get("product")}
|
||||
|
||||
# ── 예약 ──
|
||||
def add_schedule(self, **fields):
|
||||
sid = next(self._ids)
|
||||
|
||||
@@ -1127,6 +1127,71 @@ def test_product_snapshot_keeps_only_scalar_fields():
|
||||
assert snap == {"product_name": "A", "price": "1.00", "display": "T"}
|
||||
|
||||
|
||||
def test_overlay_same_updated_date_but_different_flags_is_lag():
|
||||
# 카페24는 진열/판매만 바꾼 PUT 에서 updated_date 를 안 올릴 수 있다 — 같은 시각에 값이
|
||||
# 다르면 지연이다(예전엔 "같다 = 따라잡음"으로 봐서 바꾼 진열/판매가 되돌아 보였다).
|
||||
fetched = {"display": "T", "selling": "T", "updated_date": "2026-09-18T10:00:00+09:00"}
|
||||
snap = {"display": "F", "selling": "T", "updated_date": "2026-09-18T10:00:00+09:00"}
|
||||
merged, stale = store.overlay_recent_write(fetched, snapshot=snap, written_at=now_kst(), grace_minutes=60)
|
||||
assert stale is True and merged["display"] == "F"
|
||||
|
||||
|
||||
def test_overlay_same_updated_date_and_same_values_is_caught_up():
|
||||
fetched = {"display": "F", "price": "1.00", "updated_date": "2026-09-18T10:00:00+09:00"}
|
||||
snap = {"display": "F", "price": "1.00", "updated_date": "2026-09-18T10:00:00+09:00"}
|
||||
merged, stale = store.overlay_recent_write(fetched, snapshot=snap, written_at=now_kst(), grace_minutes=60)
|
||||
assert stale is False and merged is fetched
|
||||
|
||||
|
||||
def test_overlay_product_rows_fixes_lagging_list():
|
||||
rows = [
|
||||
{"product_no": 1, "display": "T", "selling": "T", "updated_date": "2026-09-18T10:00:00+09:00"},
|
||||
{"product_no": 2, "display": "T", "selling": "T", "updated_date": "2026-09-18T10:00:00+09:00"},
|
||||
]
|
||||
snaps = {1: {"data": {"display": "T", "selling": "F", "updated_date": "2026-09-18T10:00:00+09:00"},
|
||||
"written_at": now_kst().isoformat()}}
|
||||
out = store.overlay_product_rows(rows, snaps, grace_minutes=60)
|
||||
assert out[0]["selling"] == "F"
|
||||
assert out[1] is rows[1]
|
||||
assert store.overlay_product_rows(rows, {}, grace_minutes=60) is rows
|
||||
|
||||
|
||||
def test_status_toggle_survives_read_lag_without_updated_date_bump():
|
||||
"""진열/판매 배지 → PUT → 다시 열어도(단건·목록) 바꾼 값이 보인다.
|
||||
|
||||
실물 재현 조건: PUT 이 updated_date 를 올리지 않고, GET 은 한동안 예전 값을 준다.
|
||||
"""
|
||||
from app.modules.cafe24 import routes_products
|
||||
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24()
|
||||
api = fakes.FakeApi(cafe)
|
||||
cafe._tick = lambda: None # 진열/판매만 바꾸면 updated_date 그대로
|
||||
cafe.stale = dict(cafe.state) # GET 은 바꾸기 전 값(읽기 지연)
|
||||
orig = (routes_products.require_store, routes_products.build_cafe24_api)
|
||||
routes_products.require_store = lambda request: (st, {"email": "a@b.c"})
|
||||
routes_products.build_cafe24_api = lambda _st: api
|
||||
try:
|
||||
res = routes_products.product_status(None, 131, {"field": "selling", "value": False})
|
||||
assert res == {"ok": True, "display": True, "selling": False}
|
||||
assert cafe.state["selling"] == "F"
|
||||
assert cafe.puts()[-1][2]["request"] == {"selling": "F"}
|
||||
|
||||
product, stale = routes_products.load_product(st, api, 131)
|
||||
assert stale is True and products.normalize_product(product)["selling"] is False
|
||||
|
||||
rows = store.overlay_product_rows(
|
||||
[dict(cafe.stale)], st.get_recent_product_snapshots(60), grace_minutes=60
|
||||
)
|
||||
assert products.normalize_product(rows[0])["selling"] is False
|
||||
|
||||
# 다시 켜기 — 값은 요청한 결과값 그대로(뒤집기 아님)
|
||||
res = routes_products.product_status(None, 131, {"field": "selling", "value": True})
|
||||
assert res["selling"] is True and cafe.state["selling"] == "T"
|
||||
finally:
|
||||
routes_products.require_store, routes_products.build_cafe24_api = orig
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 기본 정보 · 옵션 · 품목 입력 검증
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -232,6 +232,9 @@ def resolve_effective(
|
||||
# ════════════════════════════════════════════════════════════
|
||||
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, ""
|
||||
|
||||
@@ -420,7 +420,7 @@ cafe24_oauth_tokens 저장
|
||||
| 대상 | 우리가 남기는 것 | 지연 판정 | 구현 |
|
||||
| --- | --- | --- | --- |
|
||||
| 상세설명 HTML | MANUAL/SCHEDULED revision (+ 적용 직전 BACKUP) | 카페24 값이 유예시간 안의 **revision 중 하나와 같으면** 지연(pending) → 마지막 쓰기를 표시하고 그 지문을 쓴다. 마지막 쓰기와 같으면 synced. 우리가 모르는 값이면 external(관리자에서 직접 고침) → 카페24 값 표시 | `store.resolve_description`, `routes_products.resolve_description`, DB `revision_digests`(md5) |
|
||||
| 상품명·가격·이미지·진열/판매 | PUT 응답을 `cafe24_products.last_write_snapshot.product` 에 저장 | GET 의 `updated_date` 가 스냅샷의 `updated_date` 보다 **이전**이면 지연 → 스냅샷 값으로 덮어씀. 카페24 자신의 시각끼리 비교하므로 서버 시계와 무관 | `store.overlay_recent_write`, `routes_products.load_product` |
|
||||
| 상품명·가격·이미지·진열/판매 | PUT 응답을 `cafe24_products.last_write_snapshot.product` 에 저장 | GET 의 `updated_date` 가 스냅샷의 `updated_date` 보다 **이전**이면 지연 → 스냅샷 값으로 덮어씀. **같은 시각인데 값이 다르면**(진열/판매만 바꾼 PUT 은 `updated_date` 를 안 올릴 수 있음)도 지연. **이후**면 관리자 수정 → 카페24 값. 카페24 자신의 시각끼리 비교하므로 서버 시계와 무관. **목록**도 같은 보정(`get_recent_product_snapshots` 한 번 조회) — 안 하면 진열/판매 변경 뒤 목록·필터가 예전 값으로 보이고 캐시도 예전 값으로 덮인다 | `store.overlay_recent_write`, `store.overlay_product_rows`, `routes_products.load_product`·목록, 예약 미리보기 |
|
||||
| 옵션 | PUT/POST 응답을 `…snapshot.options` 에 저장 | 유예시간 안이면 스냅샷 우선 | `routes_product_info._apply_options_snapshot` |
|
||||
| 품목 | 보낸 값(+응답)을 `…snapshot.variants` 에 코드별 누적 | 유예시간 안이면 해당 코드의 필드만 덮어씀 | `routes_product_info._apply_variant_snapshot` |
|
||||
|
||||
|
||||
Reference in New Issue
Block a user