6dae0e45c9
되돌리기(자동 복원)는 요청대로 만들지 않았다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이며, 한 예약에서 상세페이지 HTML·진열·판매를 각각 고를 수 있다. 셋 다 "변경 없음"인 예약은 DB CHECK 로 막는다. 등록은 편집기 아래 「예약 적용」에서 한다. HTML 을 적용하는 예약이면 그 시점의 편집기 내용을 DRAFT revision 으로 저장해 고정한다 — 이후 편집기를 더 고쳐도 예약된 내용이 바뀌지 않아야 한다. 단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로 화면에서 본 값이 그대로 저장된다. 예약 폼은 적용 폼과 형제로 두고(폼 중첩 불가) 편집기 내용을 JS 가 hidden 에 복사한다. 실행은 web 이 아니라 worker 다(app/modules/cafe24/worker.py, compose 서비스 dbx-cafe24-worker, --loop 60). 웹 요청 안에서 기다리면 프록시 타임아웃·재기동에 무너지고, 브라우저를 닫으면 실행되지 않는다. worker 는 claim_due_schedule 로 한 건씩 FOR UPDATE SKIP LOCKED 로 잠그고 PROCESSING 으로 바꾼 뒤 잠금을 푼다. worker 가 둘 떠도 같은 예약을 두 번 적용하지 않고, 긴 API 호출 동안 DB 잠금을 쥐지 않는다. 적용 순서는 화면 편집과 같다(현재값 재조회 → BACKUP → PUT → 감사로그). HTML 없이 진열/판매만 바꾸는 예약은 상세설명을 읽지도 백업하지도 않는다. 실패는 1분→5분→15분 재시도 후 FAILED 확정이며, 한 건의 오류로 worker 가 죽지 않는다. 진열/판매를 한 번의 PUT 으로 함께 보내려고 products.update_product 를 추가했다 (update_descriptions 는 이 함수로 위임). None 인 필드는 payload 에서 빼므로 "건드리지 않음"이 그대로 표현된다. DB: scripts/sql/cafe24_db_002_schedule_flags.sql (멱등) — set_display/set_selling BOOLEAN NULL 추가 + 아무것도 하지 않는 예약 금지 제약. 되돌리기용 end_* 컬럼은 쓰지 않지만 삭제하지 않는다(파괴적). 시각은 KST 로 해석한다(datetime-local 은 타임존이 없다). 과거는 거부하되 폼을 채우는 동안 시간이 흐른 경우를 위해 1분 여유를 뒀다. 검증: 유닛테스트 66개 통과(신규 15개 — 3-상태 파싱, KST 해석·과거 거부·1분 여유, 요약 문구, payload 의 T/F 와 None 생략, 바꿀 것 없으면 미호출, worker 의 성공 경로 (백업+PC/모바일 동시+진열만 전송)·상태만 변경 시 백업 생략·재시도 후 최종 실패· 버전 누락 시 크래시 대신 실패·처리할 것 없을 때 종료). 예약 목록/편집기 예약 폼 렌더 확인. 라우트 16개. 실제 예약 실행은 서버 배포 후 확인 필요. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
483 lines
20 KiB
Python
483 lines
20 KiB
Python
"""cafe24_db PostgreSQL 저장소.
|
|
|
|
- 드라이버: psycopg 3 (`psycopg[binary,pool]`) — 다른 모듈과 동일 패턴.
|
|
- 연결 정보: 환경변수 `CAFE24_DB_URL`
|
|
(예: postgresql://cafe24_app:<pwd>@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
|
|
from contextlib import contextmanager
|
|
from datetime import date, datetime
|
|
from typing import Any, Iterator
|
|
|
|
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",
|
|
)
|
|
|
|
|
|
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()
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 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)
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 상세페이지 HTML 버전 (append-only — UPDATE/DELETE 하지 않는다)
|
|
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
|
# ════════════════════════════════════════════════════════════
|
|
def add_revision(
|
|
self,
|
|
*,
|
|
product_no: int,
|
|
html_content: str,
|
|
revision_type: str,
|
|
memo: str = "",
|
|
created_by: str = "",
|
|
) -> int:
|
|
with self._pool.connection() as conn:
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO cafe24_product_revisions
|
|
(product_no, html_content, revision_type, memo, created_by)
|
|
VALUES (%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 "",
|
|
),
|
|
).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 일 수 있어 길이만 계산해서 준다."""
|
|
with self._pool.connection() as conn:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
|
length(html_content) AS html_length
|
|
FROM cafe24_product_revisions
|
|
WHERE product_no = %s
|
|
ORDER BY created_at DESC, id DESC
|
|
LIMIT %s
|
|
""",
|
|
(int(product_no), max(1, min(int(limit), 200))),
|
|
).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)
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 예약 (지정 시각에 상세페이지·진열/판매 적용)
|
|
# 되돌리기는 쓰지 않으므로 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 = "",
|
|
) -> int:
|
|
with self._pool.connection() as conn:
|
|
row = conn.execute(
|
|
"""
|
|
INSERT INTO cafe24_product_schedules
|
|
(product_no, scheduled_at, revision_id, set_display, set_selling,
|
|
memo, created_by)
|
|
VALUES (%s,%s,%s,%s,%s,%s,%s)
|
|
RETURNING id
|
|
""",
|
|
(
|
|
int(product_no),
|
|
scheduled_at,
|
|
revision_id,
|
|
set_display,
|
|
set_selling,
|
|
(memo or "")[:500],
|
|
created_by or "",
|
|
),
|
|
).fetchone()
|
|
return int(row["id"]) if row else 0
|
|
|
|
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
|
|
|
|
@contextmanager
|
|
def claim_due_schedule(self, *, now: datetime) -> Iterator[dict[str, Any] | None]:
|
|
"""실행할 예약 1건을 잡아 PROCESSING 으로 바꾼다(worker 전용).
|
|
|
|
`FOR UPDATE SKIP LOCKED` 로 잠그므로 worker 가 여러 개 떠 있어도 같은 예약을
|
|
두 번 실행하지 않는다. 재시도 대기(next_retry_at)가 남아 있으면 건너뛴다.
|
|
"""
|
|
with self._pool.connection() as conn:
|
|
with conn.transaction():
|
|
row = conn.execute(
|
|
"""
|
|
SELECT * 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 not None:
|
|
conn.execute(
|
|
"""
|
|
UPDATE cafe24_product_schedules
|
|
SET status = 'PROCESSING', started_at = now(), last_error = ''
|
|
WHERE id = %s
|
|
""",
|
|
(row["id"],),
|
|
)
|
|
yield dict(row) if row is not None else None
|
|
|
|
def finish_schedule(
|
|
self,
|
|
schedule_id: int,
|
|
*,
|
|
status: str,
|
|
error: str = "",
|
|
next_retry_at: datetime | None = None,
|
|
retry_count: int | None = None,
|
|
) -> None:
|
|
"""예약 종료 처리. 재시도로 되돌릴 때는 status='PENDING' + next_retry_at."""
|
|
with self._pool.connection() as conn:
|
|
conn.execute(
|
|
"""
|
|
UPDATE cafe24_product_schedules
|
|
SET status = %s,
|
|
last_error = %s,
|
|
next_retry_at = %s,
|
|
retry_count = COALESCE(%s, retry_count),
|
|
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
|
THEN now() ELSE completed_at END
|
|
WHERE id = %s
|
|
""",
|
|
(
|
|
store.normalize_schedule_status(status),
|
|
(error or "")[:1000],
|
|
next_retry_at,
|
|
retry_count,
|
|
store.normalize_schedule_status(status),
|
|
int(schedule_id),
|
|
),
|
|
)
|
|
|
|
# ════════════════════════════════════════════════════════════
|
|
# 직렬화 — 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"]
|