"""cafe24_db PostgreSQL 저장소. - 드라이버: psycopg 3 (`psycopg[binary,pool]`) — 다른 모듈과 동일 패턴. - 연결 정보: 환경변수 `CAFE24_DB_URL` (예: postgresql://cafe24_app:@postgres-db:5432/cafe24_db) - 스키마는 앱이 만들지 않는다. `scripts/sql/cafe24_db_init.sql` 을 superuser 가 사전 적용한다. 앱 계정(cafe24_app)은 CRUD 권한만 받는다. - 연결 풀은 lazy open — 부팅 시 DB 가 잠시 끊겨도 컨테이너가 죽지 않게. 토큰 값은 이 계층에 도달하기 전 이미 Fernet 암호문이다(평문 취급 금지). API 로그에는 토큰/시크릿을 넣지 않는다. """ from __future__ import annotations import logging import uuid from contextlib import contextmanager from datetime import date, datetime from typing import Any, Iterator from psycopg import errors as pg_errors from psycopg.rows import dict_row from psycopg_pool import ConnectionPool from app.timezone import KST from . import store logger = logging.getLogger("cafe24.db") # save_token_row / TokenLock.save 에서 부분 갱신을 허용하는 컬럼 화이트리스트. # 여기 없는 키는 무시한다(임의 컬럼 주입 방지). _TOKEN_FIELDS: tuple[str, ...] = ( "access_token", "refresh_token", "access_token_expires_at", "refresh_token_expires_at", "scopes", "last_refreshed_at", "last_error", "connected_by", ) def _flag_bool(value: Any, default: bool) -> bool: """카페24 'T'/'F' 또는 bool → bool.""" if isinstance(value, bool): return value text = str(value or "").strip().upper() if text in ("T", "TRUE", "1"): return True if text in ("F", "FALSE", "0"): return False return default class TokenLock: """token_lock() 이 넘겨주는 핸들. 잠긴 행 조회 + 같은 트랜잭션 안 저장.""" def __init__(self, conn: Any, mall_id: str, row: dict[str, Any] | None): self._conn = conn self._mall_id = mall_id self.row = row def save(self, **fields: Any) -> None: _update_token_row(self._conn, self._mall_id, fields) def _update_token_row(conn: Any, mall_id: str, fields: dict[str, Any]) -> None: """UPSERT. 주어진 컬럼만 갱신한다(부분 갱신).""" allowed = {k: v for k, v in fields.items() if k in _TOKEN_FIELDS} if not allowed: return columns = list(allowed.keys()) placeholders = ", ".join(["%s"] * len(columns)) assignments = ", ".join(f"{col} = EXCLUDED.{col}" for col in columns) conn.execute( f""" INSERT INTO cafe24_oauth_tokens (mall_id, {", ".join(columns)}) VALUES (%s, {placeholders}) ON CONFLICT (mall_id) DO UPDATE SET {assignments} """, (mall_id, *[allowed[col] for col in columns]), ) class Cafe24Store: def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5): self._pool = ConnectionPool( conninfo=dsn, min_size=min_size, max_size=max_size, kwargs={"row_factory": dict_row, "autocommit": True}, open=False, ) self._pool.open(wait=False) def close(self) -> None: self._pool.close() # ════════════════════════════════════════════════════════════ # 마이그레이션 005(쓰기 안전장치) 적용 여부 # 쓰기 경로는 잠금·시도 기록 없이 카페24에 쓰지 않는다 — 적용 전이면 거부한다. # 읽기 경로는 005 가 없어도 동작하게 둔다(배포 순서가 어긋나도 화면은 열린다). # ════════════════════════════════════════════════════════════ _schema_ok = False def write_schema_ready(self) -> bool: if self._schema_ok: return True with self._pool.connection() as conn: row = conn.execute( """ SELECT to_regclass('public.cafe24_write_locks') IS NOT NULL AND to_regclass('public.cafe24_write_attempts') IS NOT NULL AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'cafe24_product_schedules' AND column_name = 'lease_token') AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'cafe24_product_revisions' AND column_name = 'source') AS ok """ ).fetchone() self._schema_ok = bool(row and row.get("ok")) return self._schema_ok # ════════════════════════════════════════════════════════════ # 쓰기 잠금 (lease) — 웹 여러 프로세스 + 예약 worker 가 공유한다. # 같은 lock_key 는 한 번에 하나만 잡는다. 만료(expires_at)가 지나면 다른 쪽이 # 가져갈 수 있다(잡은 프로세스가 죽어도 영구히 막히지 않는다). 원격 쓰기 직전 # renew_lock 으로 "아직 내 잠금인가"를 확인한다(펜싱) — 아니면 쓰지 않는다. # ════════════════════════════════════════════════════════════ def acquire_lock(self, key: str, *, owner: str, purpose: str, ttl_seconds: int) -> str | None: """잠금을 잡으면 token, 남이 잡고 있으면 None.""" token = uuid.uuid4().hex with self._pool.connection() as conn: row = conn.execute( """ INSERT INTO cafe24_write_locks (lock_key, owner, token, purpose, acquired_at, expires_at) VALUES (%s, %s, %s, %s, now(), now() + %s * interval '1 second') ON CONFLICT (lock_key) DO UPDATE SET owner = EXCLUDED.owner, token = EXCLUDED.token, purpose = EXCLUDED.purpose, acquired_at = now(), expires_at = EXCLUDED.expires_at WHERE cafe24_write_locks.expires_at < now() RETURNING token """, (key, (owner or "")[:200], token, (purpose or "")[:200], max(1, int(ttl_seconds))), ).fetchone() return str(row["token"]) if row else None def renew_lock(self, key: str, token: str, *, ttl_seconds: int) -> bool: """아직 내 잠금이고 만료 전이면 연장하고 True. 이미 넘어갔으면 False.""" with self._pool.connection() as conn: row = conn.execute( """ UPDATE cafe24_write_locks SET expires_at = now() + %s * interval '1 second' WHERE lock_key = %s AND token = %s AND expires_at > now() RETURNING lock_key """, (max(1, int(ttl_seconds)), key, token), ).fetchone() return row is not None def release_lock(self, key: str, token: str) -> None: with self._pool.connection() as conn: conn.execute( "DELETE FROM cafe24_write_locks WHERE lock_key = %s AND token = %s", (key, token), ) def lock_holder(self, key: str) -> dict[str, Any]: """지금 잠금을 잡고 있는 쪽(안내 문구용). 없거나 만료됐으면 {}.""" with self._pool.connection() as conn: row = conn.execute( """ SELECT owner, purpose, acquired_at, expires_at FROM cafe24_write_locks WHERE lock_key = %s AND expires_at > now() """, (key,), ).fetchone() return self._serialize(row) # ════════════════════════════════════════════════════════════ # 쓰기 시도 기록 (cafe24_write_attempts) — 운영용 가변 표. # 원격 PUT 직전에 STARTED 로 남기고, 결과에 따라 상태를 바꾼다. # ════════════════════════════════════════════════════════════ _ATTEMPT_FIELDS: tuple[str, ...] = ( "product_no", "mall_id", "shop_no", "origin", "schedule_id", "actor", "backup_revision_id", "observed_digest", "base_digest", "target_digest", "target_html", "target_revision_id", "set_display", "set_selling", "memo", ) def start_attempt(self, **fields: Any) -> int: cols = [k for k in self._ATTEMPT_FIELDS if k in fields] values = [fields[k] for k in cols] with self._pool.connection() as conn: row = conn.execute( f""" INSERT INTO cafe24_write_attempts ({", ".join(cols)}, status) VALUES ({", ".join(["%s"] * len(cols))}, %s) RETURNING id """, (*values, store.ATTEMPT_STARTED), ).fetchone() return int(row["id"]) if row else 0 def update_attempt( self, attempt_id: int, *, status: str | None = None, error: str | None = None, remote_updated_at: str | None = None, remote_ok: bool = False, resolved_by: str | None = None, only_from: tuple[str, ...] | None = None, ) -> bool: """상태 전이. only_from 을 주면 그 상태에서만 바꾼다(늦게 도착한 갱신 무시).""" sets: list[str] = [] args: list[Any] = [] if status is not None: sets.append("status = %s") args.append(status) if error is not None: sets.append("error = %s") args.append((error or "")[:1000]) if remote_updated_at is not None: sets.append("remote_updated_at = %s") args.append(str(remote_updated_at or "")) if remote_ok: sets.append("remote_at = COALESCE(remote_at, now())") if resolved_by is not None: sets.append("resolved_by = %s") args.append(resolved_by[:200]) if not sets: return False where = "id = %s" args.append(int(attempt_id)) if only_from: where += " AND status = ANY(%s)" args.append(list(only_from)) with self._pool.connection() as conn: row = conn.execute( f"UPDATE cafe24_write_attempts SET {', '.join(sets)} WHERE {where} RETURNING id", args, ).fetchone() return row is not None def record_attempt_revision( self, attempt_id: int, *, revision_type: str, memo: str, created_by: str, source: str = "", source_revision_id: int | None = None, ) -> int: """원격 반영된 시도의 버전(MANUAL/SCHEDULED/ROLLBACK)을 남기고 RECORDED 로 바꾼다. 한 트랜잭션에서 한다 — 시도 행을 잠그고, 이미 기록돼 있으면 그 버전 id 를 돌려준다 (기록 복구가 두 번 돌아도 버전이 둘 생기지 않는다). 내용은 시도에 보관한 target_html(없으면 target_revision_id 의 내용)이다. 기록 뒤 target_html 은 비운다. """ with self._pool.connection() as conn: with conn.transaction(): att = conn.execute( """ SELECT a.*, COALESCE(NULLIF(a.target_html, ''), t.html_content, '') AS body FROM cafe24_write_attempts a LEFT JOIN cafe24_product_revisions t ON t.id = a.target_revision_id WHERE a.id = %s FOR UPDATE OF a """, (int(attempt_id),), ).fetchone() if att is None: return 0 if att.get("applied_revision_id"): return int(att["applied_revision_id"]) row = conn.execute( """ INSERT INTO cafe24_product_revisions (product_no, html_content, revision_type, memo, created_by, mall_id, shop_no, source, source_revision_id) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id """, ( int(att["product_no"]), att["body"] or "", store.normalize_revision_type(revision_type), (memo or "")[:500], created_by or "", att.get("mall_id") or "", int(att.get("shop_no") or 1), source or "", source_revision_id, ), ).fetchone() revision_id = int(row["id"]) conn.execute( """ UPDATE cafe24_write_attempts SET status = %s, applied_revision_id = %s, target_html = '', remote_at = COALESCE(remote_at, now()) WHERE id = %s """, (store.ATTEMPT_RECORDED, revision_id, int(attempt_id)), ) return revision_id def get_attempt(self, attempt_id: int) -> dict[str, Any]: with self._pool.connection() as conn: row = conn.execute( "SELECT * FROM cafe24_write_attempts WHERE id = %s", (int(attempt_id),) ).fetchone() return self._serialize(row) def latest_attempt_for_schedule(self, schedule_id: int) -> dict[str, Any]: with self._pool.connection() as conn: row = conn.execute( """ SELECT * FROM cafe24_write_attempts WHERE schedule_id = %s ORDER BY created_at DESC, id DESC LIMIT 1 """, (int(schedule_id),), ).fetchone() return self._serialize(row) def open_attempts(self, product_no: int, *, since: datetime) -> list[dict[str, Any]]: """결과 확정이 필요한 시도(STARTED/REMOTE_OK/UNKNOWN), 유예시간 안, 오래된 순. 005 적용 전이면 빈 목록(읽기 경로는 막지 않는다).""" try: with self._pool.connection() as conn: rows = conn.execute( """ SELECT id, product_no, origin, schedule_id, actor, status, target_digest, target_revision_id, backup_revision_id, set_display, set_selling, error, created_at, remote_at, memo FROM cafe24_write_attempts WHERE product_no = %s AND status = ANY(%s) AND created_at >= %s ORDER BY created_at ASC, id ASC """, (int(product_no), list(store.ATTEMPT_OPEN), since), ).fetchall() except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn): return [] return [self._serialize(r) for r in rows] def attempts_needing_record(self, *, since: datetime, limit: int = 20) -> list[dict[str, Any]]: """원격 반영됐는데 버전 기록이 안 된 시도(REMOTE_OK) — worker 가 기록을 채운다.""" with self._pool.connection() as conn: rows = conn.execute( """ SELECT id, product_no, origin, schedule_id, actor, memo, target_revision_id, target_digest FROM cafe24_write_attempts WHERE status = %s AND created_at >= %s ORDER BY created_at ASC, id ASC LIMIT %s """, (store.ATTEMPT_REMOTE_OK, since, max(1, int(limit))), ).fetchall() return [self._serialize(r) for r in rows] def write_lineage(self, product_no: int, *, since: datetime, limit: int = 30) -> list[dict[str, Any]]: """원격 반영이 **확인된** 상세설명 쓰기(REMOTE_OK/RECORDED), 최신 순. 읽기 지연 판정의 유일한 근거다. 충돌로 거절된 적용의 백업, 예약 초안, 실패·결과 모름 시도는 들어오지 않는다. 첫 행에만 html_content(마지막으로 쓴 HTML)를 채운다. created_at 은 원격 반영 시각(remote_at)이다. 005 적용 전이면 빈 목록. """ try: with self._pool.connection() as conn: rows = conn.execute( """ SELECT id, origin, actor, status, schedule_id, observed_digest, base_digest, target_digest, remote_updated_at, remote_at, applied_revision_id, target_revision_id FROM cafe24_write_attempts WHERE product_no = %s AND status = ANY(%s) AND target_digest <> '' AND remote_at >= %s ORDER BY remote_at DESC, id DESC LIMIT %s """, (int(product_no), list(store.ATTEMPT_CONFIRMED), since, max(1, int(limit))), ).fetchall() if not rows: return [] top = conn.execute( """ SELECT COALESCE(NULLIF(a.target_html, ''), r.html_content, t.html_content, '') AS body FROM cafe24_write_attempts a LEFT JOIN cafe24_product_revisions r ON r.id = a.applied_revision_id LEFT JOIN cafe24_product_revisions t ON t.id = a.target_revision_id WHERE a.id = %s """, (rows[0]["id"],), ).fetchone() except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn): return [] out: list[dict[str, Any]] = [] for index, row in enumerate(rows): item = dict(row) at = item.get("remote_at") if isinstance(at, datetime) and at.tzinfo is None: at = at.replace(tzinfo=KST) item["created_at"] = at item["created_by"] = item.get("actor") or "" item["html_content"] = (top or {}).get("body", "") if index == 0 else "" out.append(item) return out # ════════════════════════════════════════════════════════════ # OAuth 토큰 — app/integrations/cafe24/tokens.py 가 요구하는 3개 메서드 # ════════════════════════════════════════════════════════════ def get_token_row(self, mall_id: str) -> dict[str, Any] | None: with self._pool.connection() as conn: return conn.execute( "SELECT * FROM cafe24_oauth_tokens WHERE mall_id = %s", (mall_id,), ).fetchone() def save_token_row(self, *, mall_id: str, **fields: Any) -> None: with self._pool.connection() as conn: _update_token_row(conn, mall_id, fields) @contextmanager def token_lock(self, mall_id: str) -> Iterator[TokenLock]: """토큰 행을 FOR UPDATE 로 잠근 채 작업. web 컨테이너와 worker 컨테이너가 동시에 refresh 하는 것을 막는다 (카페24는 refresh token 을 회전시키므로 동시 갱신 시 한쪽이 무효화됨). 행이 아직 없으면 row=None 으로 넘어간다. """ with self._pool.connection() as conn: with conn.transaction(): row = conn.execute( "SELECT * FROM cafe24_oauth_tokens WHERE mall_id = %s FOR UPDATE", (mall_id,), ).fetchone() yield TokenLock(conn, mall_id, row) def disconnect(self, mall_id: str) -> None: """연결 해제 — 토큰만 지운다(이력/예약은 보존).""" with self._pool.connection() as conn: conn.execute("DELETE FROM cafe24_oauth_tokens WHERE mall_id = %s", (mall_id,)) # ════════════════════════════════════════════════════════════ # API 호출 로그 (Cafe24Client 가 주입받아 호출) # ⚠️ Authorization/토큰/시크릿은 절대 기록하지 않는다. # ════════════════════════════════════════════════════════════ def log_api_call( self, *, endpoint: str, method: str, product_no: int | None, http_status: int | None, result: str, error_message: str, duration_ms: int, ) -> None: with self._pool.connection() as conn: conn.execute( """ INSERT INTO cafe24_api_logs (endpoint, method, product_no, http_status, result, error_message, duration_ms) VALUES (%s,%s,%s,%s,%s,%s,%s) """, (endpoint, method, product_no, http_status, result, error_message, duration_ms), ) def list_api_logs(self, *, limit: int = 100) -> list[dict[str, Any]]: with self._pool.connection() as conn: rows = conn.execute( """ SELECT * FROM cafe24_api_logs ORDER BY created_at DESC, id DESC LIMIT %s """, (max(1, min(int(limit), 500)),), ).fetchall() return [self._serialize(r) for r in rows] # ════════════════════════════════════════════════════════════ # 작업 감사 로그 # ════════════════════════════════════════════════════════════ def log_audit( self, *, actor: str, action: str, product_no: int | None = None, revision_id: int | None = None, schedule_id: int | None = None, result: str = "", detail: str = "", ) -> None: with self._pool.connection() as conn: self._insert_audit( conn, actor=actor, action=action, product_no=product_no, revision_id=revision_id, schedule_id=schedule_id, result=result, detail=detail, ) @staticmethod def _insert_audit( conn: Any, *, actor: str, action: str, product_no: int | None = None, revision_id: int | None = None, schedule_id: int | None = None, result: str = "", detail: str = "", ) -> None: """호출자의 트랜잭션에 합류시키기 위해 conn 을 받는 정적 헬퍼.""" conn.execute( """ INSERT INTO cafe24_audit_logs (actor, action, product_no, revision_id, schedule_id, result, detail) VALUES (%s,%s,%s,%s,%s,%s,%s) """, (actor, action, product_no, revision_id, schedule_id, result, detail[:1000]), ) def list_audit_logs(self, *, limit: int = 100) -> list[dict[str, Any]]: with self._pool.connection() as conn: rows = conn.execute( """ SELECT * FROM cafe24_audit_logs ORDER BY created_at DESC, id DESC LIMIT %s """, (max(1, min(int(limit), 500)),), ).fetchall() return [self._serialize(r) for r in rows] # ════════════════════════════════════════════════════════════ # 상품 캐시 # source of truth 는 언제나 카페24다. 이 표는 목록 조회 결과를 담아두는 # 곳이며, 예약·로그 화면에서 API 호출 없이 상품명을 보여줄 때 쓴다. # 상세설명(HTML)은 여기 넣지 않는다(cafe24_product_revisions 담당). # ════════════════════════════════════════════════════════════ def upsert_products(self, rows: list[dict[str, Any]]) -> int: """정규화된 상품 dict 목록(products.normalize_product 결과)을 UPSERT.""" valid = [r for r in rows if int(r.get("product_no") or 0) > 0] if not valid: return 0 with self._pool.connection() as conn: with conn.cursor() as cur: cur.executemany( """ INSERT INTO cafe24_products (product_no, product_code, product_name, display, selling, last_synced_at) VALUES (%s,%s,%s,%s,%s, now()) ON CONFLICT (product_no) DO UPDATE SET product_code = EXCLUDED.product_code, product_name = EXCLUDED.product_name, display = EXCLUDED.display, selling = EXCLUDED.selling, last_synced_at = now() """, [ ( int(r["product_no"]), str(r.get("product_code") or ""), str(r.get("product_name") or ""), bool(r.get("display", True)), bool(r.get("selling", True)), ) for r in valid ], ) return len(valid) def get_cached_product(self, product_no: int) -> dict[str, Any]: with self._pool.connection() as conn: row = conn.execute( "SELECT * FROM cafe24_products WHERE product_no = %s", (int(product_no),), ).fetchone() return self._serialize(row) # ── 쓰기 직후 스냅샷 (읽기 지연 보정용) ── # 카페24 PUT 응답의 상품 값을 남겨 둔다. GET 이 아직 예전 레코드를 돌려주는 # 동안(updated_date 가 스냅샷보다 이전) 이 값으로 화면을 덮어씌운다. # 마이그레이션 004 의 두 컬럼(last_write_snapshot, last_written_at)을 쓴다. # 스냅샷 JSON 모양: # {"product": {"data": {...store.SNAPSHOT_FIELDS...}, "written_at": ISO}, # "options": {"data": {...GET/PUT options 응답..., "_before_signature", "_recent_values"}, # "written_at": ISO}, # "variants": {"data": {variant_code: {필드..., "_at", "_deleted"?}}, "written_at": ISO}} # 섹션별로 따로 갱신한다(가격만 바꿨는데 옵션 스냅샷이 사라지면 안 된다). # 품목은 코드별·필드별로 병합한다(store.merge_variant_snapshot). 품목 전체 초기화 # (옵션 삭제·재생성)는 replace=True 로 명시한다 — {} 를 넘기는 것은 "변경 없음"이다. def save_write_snapshot(self, product_no: int, section: str, data: Any, *, replace: bool = False) -> None: from psycopg.types.json import Jsonb # noqa: WPS433 no = int(product_no) if no <= 0 or section not in ("product", "options", "variants"): return now_iso = datetime.now(KST).isoformat(timespec="seconds") with self._pool.connection() as conn: with conn.transaction(): # 행이 없으면 먼저 만든다 — FOR UPDATE 가 잠글 행이 있어야 동시 저장이 # 서로의 병합 결과를 덮지 않는다. conn.execute( "INSERT INTO cafe24_products (product_no) VALUES (%s) ON CONFLICT (product_no) DO NOTHING", (no,), ) row = conn.execute( "SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s FOR UPDATE", (no,), ).fetchone() current = dict(row["last_write_snapshot"]) if row and row.get("last_write_snapshot") else {} if section == "variants": previous = (current.get("variants") or {}).get("data") or {} data = store.merge_variant_snapshot( previous, data if isinstance(data, dict) else {}, at=now_iso, replace=replace ) current[section] = {"data": data, "written_at": now_iso} product = data if section == "product" and isinstance(data, dict) else {} conn.execute( """ INSERT INTO cafe24_products (product_no, product_code, product_name, display, selling, last_synced_at, last_write_snapshot, last_written_at) VALUES (%s, %s, %s, %s, %s, now(), %s, now()) ON CONFLICT (product_no) DO UPDATE SET product_code = COALESCE(NULLIF(EXCLUDED.product_code, ''), cafe24_products.product_code), product_name = COALESCE(NULLIF(EXCLUDED.product_name, ''), cafe24_products.product_name), display = CASE WHEN %s THEN EXCLUDED.display ELSE cafe24_products.display END, selling = CASE WHEN %s THEN EXCLUDED.selling ELSE cafe24_products.selling END, last_synced_at = now(), last_write_snapshot = EXCLUDED.last_write_snapshot, last_written_at = now() """, ( no, str(product.get("product_code") or ""), str(product.get("product_name") or ""), _flag_bool(product.get("display"), True), _flag_bool(product.get("selling"), True), Jsonb(current), bool(product), bool(product), ), ) def get_write_snapshot(self, product_no: int) -> dict[str, Any]: """섹션별 스냅샷 dict. 없으면 {}.""" with self._pool.connection() as conn: row = conn.execute( "SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s", (int(product_no),), ).fetchone() if not row or not row.get("last_write_snapshot"): 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 을 남기는 것이 유일한 복구 수단이다. # 읽기 지연 판정은 이 표가 아니라 cafe24_write_attempts(확인된 쓰기)를 본다 — # 여기에는 충돌로 거절된 적용의 백업·예약 초안처럼 카페24에 올라간 적 없는 값도 # 들어 있기 때문이다(write_lineage 참고). # 메타데이터(마이그레이션 005): mall_id·shop_no(복원 시 일치 검사), source # (BACKUP 이 카페24 관측값인지, 지연 중이라 마지막 확인된 쓰기인지), source_revision_id. # ════════════════════════════════════════════════════════════ def add_revision( self, *, product_no: int, html_content: str, revision_type: str, memo: str = "", created_by: str = "", mall_id: str = "", shop_no: int = 1, source: str = "", source_revision_id: int | None = None, ) -> int: with self._pool.connection() as conn: row = conn.execute( """ INSERT INTO cafe24_product_revisions (product_no, html_content, revision_type, memo, created_by, mall_id, shop_no, source, source_revision_id) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id """, ( int(product_no), html_content or "", store.normalize_revision_type(revision_type), (memo or "")[:500], created_by or "", mall_id or "", int(shop_no or 1), source or "", source_revision_id, ), ).fetchone() return int(row["id"]) if row else 0 def list_revisions(self, product_no: int, *, limit: int = 20) -> list[dict[str, Any]]: """버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다. 005 적용 전이면 출처(source) 없이 돌려준다(읽기 경로는 막지 않는다).""" sql = """ SELECT id, product_no, revision_type, memo, created_by, created_at, length(html_content) AS html_length{extra} FROM cafe24_product_revisions WHERE product_no = %s ORDER BY created_at DESC, id DESC LIMIT %s """ args = (int(product_no), max(1, min(int(limit), 200))) try: with self._pool.connection() as conn: rows = conn.execute(sql.format(extra=", source, source_revision_id, mall_id"), args).fetchall() except pg_errors.UndefinedColumn: with self._pool.connection() as conn: rows = conn.execute(sql.format(extra=""), args).fetchall() return [self._serialize(r) for r in rows] def get_revision(self, revision_id: int) -> dict[str, Any]: """버전 1건 전체(HTML 포함). 복원/비교용.""" with self._pool.connection() as conn: row = conn.execute( "SELECT * FROM cafe24_product_revisions WHERE id = %s", (int(revision_id),), ).fetchone() return self._serialize(row) # ════════════════════════════════════════════════════════════ # 디자인 보관함 FTP 파일 버전 (append-only) — 모바일 스와이프 # (product-swiper.js), PC/모바일 상품상세 템플릿(detail.html) 등. # 상품이 아니라 FTP 파일이라 별도 테이블을 쓴다 # (cafe24_product_revisions.product_no 는 NOT NULL). file_key 로 파일을 # 구분한다 — "swiper" / "mobile_detail" / "pc_detail" (config.py 의 # DESIGN_FILE_SPECS 키와 일치해야 한다). # ════════════════════════════════════════════════════════════ def add_design_revision( self, *, file_key: str, content: str, revision_type: str, memo: str = "", created_by: str = "", ) -> int: with self._pool.connection() as conn: row = conn.execute( """ INSERT INTO cafe24_swiper_revisions (file_key, content, revision_type, memo, created_by) VALUES (%s,%s,%s,%s,%s) RETURNING id """, ( file_key, content or "", store.normalize_revision_type(revision_type), (memo or "")[:500], created_by or "", ), ).fetchone() return int(row["id"]) if row else 0 def list_design_revisions(self, file_key: str, *, limit: int = 20) -> list[dict[str, Any]]: """버전 목록. content 는 커질 수 있어 길이만 계산해서 준다.""" with self._pool.connection() as conn: rows = conn.execute( """ SELECT id, revision_type, memo, created_by, created_at, length(content) AS html_length FROM cafe24_swiper_revisions WHERE file_key = %s ORDER BY created_at DESC, id DESC LIMIT %s """, (file_key, max(1, min(int(limit), 200))), ).fetchall() return [self._serialize(r) for r in rows] # ════════════════════════════════════════════════════════════ # 예약 (지정 시각에 상세페이지·진열/판매 적용) # 되돌리기는 쓰지 않으므로 end_* 컬럼은 건드리지 않는다. # ════════════════════════════════════════════════════════════ def create_schedule( self, *, product_no: int, scheduled_at: datetime, revision_id: int | None, set_display: bool | None, set_selling: bool | None, memo: str = "", created_by: str = "", image: bytes | None = None, image_type: str = "", image_name: str = "", ) -> int: """예약 등록. image 가 있으면 파일을 cafe24_schedule_images 에 같은 트랜잭션으로 남긴다(006). 이미지 없는 예약은 006 컬럼을 쓰지 않는다 — 마이그레이션 전에도 기존 예약 등록이 깨지지 않게. """ cols = ["product_no", "scheduled_at", "revision_id", "set_display", "set_selling", "memo", "created_by"] vals: list[Any] = [int(product_no), scheduled_at, revision_id, set_display, set_selling, (memo or "")[:500], created_by or ""] if image: cols += ["image_type", "image_name"] vals += [image_type, (image_name or "")[:200]] with self._pool.connection() as conn: with conn.transaction(): row = conn.execute( f"INSERT INTO cafe24_product_schedules ({', '.join(cols)}) " # noqa: S608 — 고정 컬럼명만 f"VALUES ({', '.join(['%s'] * len(cols))}) RETURNING id", vals, ).fetchone() if row and image: conn.execute( "INSERT INTO cafe24_schedule_images (schedule_id, data) VALUES (%s, %s)", (row["id"], image), ) return int(row["id"]) if row else 0 def get_schedule_image(self, schedule_id: int) -> bytes: """예약 대표 이미지 파일. 없으면 b"".""" with self._pool.connection() as conn: row = conn.execute( "SELECT data FROM cafe24_schedule_images WHERE schedule_id = %s", (int(schedule_id),) ).fetchone() return bytes(row["data"]) if row else b"" def list_schedules(self, *, limit: int = 200) -> list[dict[str, Any]]: """예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순.""" with self._pool.connection() as conn: rows = conn.execute( """ SELECT s.*, p.product_name, (s.revision_id IS NOT NULL) AS has_html FROM cafe24_product_schedules s LEFT JOIN cafe24_products p ON p.product_no = s.product_no ORDER BY (s.status = 'PENDING') DESC, CASE WHEN s.status = 'PENDING' THEN s.scheduled_at END ASC, s.scheduled_at DESC, s.id DESC LIMIT %s """, (max(1, min(int(limit), 500)),), ).fetchall() return [self._serialize(r) for r in rows] def cancel_schedule(self, schedule_id: int, *, actor: str = "") -> bool: """대기 중인 예약만 취소한다. 실행 중/완료된 것은 건드리지 않는다.""" with self._pool.connection() as conn: with conn.transaction(): row = conn.execute( """ UPDATE cafe24_product_schedules SET status = 'CANCELLED', completed_at = now() WHERE id = %s AND status = 'PENDING' RETURNING id, product_no """, (int(schedule_id),), ).fetchone() if row is None: return False self._insert_audit( conn, actor=actor, action="schedule_cancel", product_no=row["product_no"], schedule_id=row["id"], result="SUCCESS", ) return True # ── 예약 실행 lease (마이그레이션 005) ── # PROCESSING 은 lease_expires_at 까지만 유효하다. worker 가 죽으면 만료 후 # claim_expired_schedules 로 다른(또는 재기동한) worker 가 가져가 시도 기록을 보고 # 성공/재시도/확인 필요로 나눈다(worker.recover_expired). 모든 상태 변경은 # lease_token 이 맞을 때만 한다 — 만료 뒤 늦게 끝난 worker 가 결과를 덮지 않게. def claim_due_schedule(self, *, now: datetime, owner: str, ttl_seconds: int) -> dict[str, Any] | None: """실행할 예약 1건을 잡아 PROCESSING + lease 로 바꾼다(worker 전용). `FOR UPDATE SKIP LOCKED` 로 잠그므로 worker 가 여러 개 떠 있어도 같은 예약을 두 번 잡지 않는다. 재시도 대기(next_retry_at)가 남아 있으면 건너뛴다. 반환 행의 lease_token 으로 renew/finish 한다. """ token = uuid.uuid4().hex with self._pool.connection() as conn: with conn.transaction(): row = conn.execute( """ SELECT id FROM cafe24_product_schedules WHERE status = 'PENDING' AND scheduled_at <= %s AND (next_retry_at IS NULL OR next_retry_at <= %s) ORDER BY scheduled_at ASC, id ASC LIMIT 1 FOR UPDATE SKIP LOCKED """, (now, now), ).fetchone() if row is None: return None claimed = conn.execute( """ UPDATE cafe24_product_schedules SET status = 'PROCESSING', started_at = now(), last_error = '', lease_owner = %s, lease_token = %s, lease_expires_at = now() + %s * interval '1 second' WHERE id = %s RETURNING * """, ((owner or "")[:200], token, max(1, int(ttl_seconds)), row["id"]), ).fetchone() return dict(claimed) if claimed else None def claim_expired_schedules( self, *, owner: str, ttl_seconds: int, legacy_minutes: int, limit: int = 20 ) -> list[dict[str, Any]]: """lease 가 만료된 PROCESSING 예약을 이 worker 에게 다시 lease 한다(복구 전용). lease 컬럼이 비어 있는 옛 행(005 이전에 PROCESSING 이 된 것)은 started_at 이 legacy_minutes 보다 오래됐으면 만료로 본다. """ with self._pool.connection() as conn: with conn.transaction(): rows = conn.execute( """ WITH picked AS ( SELECT id FROM cafe24_product_schedules WHERE status = 'PROCESSING' AND (lease_expires_at < now() OR (lease_expires_at IS NULL AND COALESCE(started_at, updated_at) < now() - %s * interval '1 minute')) ORDER BY id LIMIT %s FOR UPDATE SKIP LOCKED ) UPDATE cafe24_product_schedules s SET lease_owner = %s, lease_token = md5(random()::text || clock_timestamp()::text || s.id::text), lease_expires_at = now() + %s * interval '1 second' FROM picked WHERE s.id = picked.id RETURNING s.* """, (max(1, int(legacy_minutes)), max(1, int(limit)), (owner or "")[:200], max(1, int(ttl_seconds))), ).fetchall() return [dict(r) for r in rows] def renew_schedule_lease(self, schedule_id: int, token: str, *, ttl_seconds: int) -> bool: """아직 내 lease 면 연장하고 True. 만료돼 넘어갔으면 False — 카페24에 쓰지 않는다.""" with self._pool.connection() as conn: row = conn.execute( """ UPDATE cafe24_product_schedules SET lease_expires_at = now() + %s * interval '1 second' WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s AND lease_expires_at > now() RETURNING id """, (max(1, int(ttl_seconds)), int(schedule_id), token), ).fetchone() return row is not None def finish_schedule( self, schedule_id: int, *, token: str, status: str, error: str = "", next_retry_at: datetime | None = None, retry_count: int | None = None, ) -> bool: """예약 종료 처리(lease 가 내 것일 때만). 재시도로 되돌릴 때는 status='PENDING' + next_retry_at. 반환: 반영했으면 True. lease 를 잃었으면 False(다른 worker 가 복구 중 — 덮지 않는다). """ normalized = store.normalize_schedule_status(status) with self._pool.connection() as conn: row = conn.execute( """ UPDATE cafe24_product_schedules SET status = %s, last_error = %s, next_retry_at = %s, retry_count = COALESCE(%s, retry_count), lease_owner = '', lease_token = '', lease_expires_at = NULL, completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED') THEN now() ELSE completed_at END WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s RETURNING id """, (normalized, (error or "")[:1000], next_retry_at, retry_count, normalized, int(schedule_id), token), ).fetchone() return row is not None def get_schedule(self, schedule_id: int) -> dict[str, Any]: with self._pool.connection() as conn: row = conn.execute( "SELECT * FROM cafe24_product_schedules WHERE id = %s", (int(schedule_id),) ).fetchone() return self._serialize(row) def review_schedule( self, schedule_id: int, *, status: str, note: str, actor: str, action: str ) -> dict[str, Any]: """확인 필요(NEEDS_REVIEW) 예약을 사람이 확정한다 — SUCCESS / FAILED / PENDING(다시 실행). SUCCESS 가 아니면 그 예약의 열린 쓰기 시도(STARTED/UNKNOWN)를 ABANDONED 로 닫는다 (반영 안 됨으로 확정 / 재실행으로 대체). SUCCESS 면 호출부가 버전 기록을 채운다. 반환: 바뀐 예약 행. NEEDS_REVIEW 가 아니었으면 {}. """ normalized = store.normalize_schedule_status(status) with self._pool.connection() as conn: with conn.transaction(): row = conn.execute( """ UPDATE cafe24_product_schedules SET status = %s, last_error = %s, next_retry_at = CASE WHEN %s = 'PENDING' THEN now() ELSE NULL END, completed_at = CASE WHEN %s IN ('SUCCESS','FAILED') THEN now() ELSE NULL END WHERE id = %s AND status = 'NEEDS_REVIEW' RETURNING * """, (normalized, (note or "")[:1000], normalized, normalized, int(schedule_id)), ).fetchone() if row is None: return {} if normalized != store.STATUS_SUCCESS: conn.execute( """ UPDATE cafe24_write_attempts SET status = %s, resolved_by = %s WHERE schedule_id = %s AND status = ANY(%s) """, (store.ATTEMPT_ABANDONED, (actor or "")[:200], int(schedule_id), [store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN]), ) self._insert_audit( conn, actor=actor, action=f"schedule_review:{action}", product_no=row["product_no"], schedule_id=row["id"], result="SUCCESS", detail=note, ) return self._serialize(row) # ════════════════════════════════════════════════════════════ # 직렬화 — datetime → KST ISO, date → ISO (다른 모듈과 동일) # ════════════════════════════════════════════════════════════ @staticmethod def _serialize(row: dict[str, Any] | None) -> dict[str, Any]: if not row: return {} out = dict(row) for key, value in list(out.items()): if isinstance(value, datetime): aware = value if value.tzinfo else value.replace(tzinfo=KST) out[key] = aware.astimezone(KST).isoformat(timespec="seconds") elif isinstance(value, date): out[key] = value.isoformat() return out __all__ = ["Cafe24Store", "TokenLock", "store"]