[fix] solution: 온보딩 생성·크롤링 진단·장애 알림 묶음
운영 번들 자동 로그인 자격증명 유출, 온보딩 COPY 잡이 Gemini 429 로 죽던 것, 크롤링 실패가 로그에만 남던 것을 한 번에 정리한다. 실측(2026-09-15 밤, 킹서버): 사진분석 배치가 Gemini 분당 쿼터를 다 써서 같은 키를 쓰는 온보딩 COPY 잡도 같이 429 를 맞고 DEAD 로 갔다 — 확인된 fact 만으로도 편집·발행이 되는데 잡을 죽일 이유가 없었다. - solution/frontend: `VITE_AUTO_LOGIN_ID`·`PW` 를 운영 진입점에 안 넘긴다(자동 로그인은 dev 서버 전용) + `Step5Generating` 겉모습을 이전 카드 스타일로, 데이터는 실제 잡 진행(useGenerationJob) 그대로 - solution/backend: copy_service — Gemini 호출 실패해도 잡을 안 죽이고 fact 만으로 계속. db_session_manager — 유니크 제약 충돌(정상 경로) 로그를 ERROR → WARN. worker/runner + alert_service + teams_webhook — 잡 dead-letter·발행 실패·큐 정체를 Teams 로 알림(영구 저장 + 재시도 + dedupe). `/readyz` 추가. collect_diagnostics(신규) — 크롤링 채널별 실패를 jobs.result 에 구조화해서 싣는다. - postgres-init: 0015(users token_version) · 0016(alert_outbox) 마이그레이션 검증: 백엔드 pytest 759 passed. tsc(solution/frontend) 통과. Teams 알림 실채널 수신 확인.
This commit is contained in:
1 parent
b76144746b
commit
b4085a0e0f
36 files changed
+1320
-84
No files matched your search
@@ -0,0 +1,59 @@
|
||||
"""수집(크롤링) 중 실패를 jobs.result 에 구조화해서 싣는다 — 워커 로그 grep 없이 확인용.
|
||||
|
||||
★ contextvars 로 든다 — 실패 지점이 흩어진 여러 함수에 리스트를 관통시키지 않는다.
|
||||
자세한 배경은 DEVLOG.md 참고.
|
||||
"""
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
from common.logger import LOG
|
||||
|
||||
_current: ContextVar[list["CollectIssue"] | None] = ContextVar("_collect_issues", default=None)
|
||||
|
||||
# jobs.result 는 DB 에 그대로 쌓인다 — 예외 메시지가 길어지는(HTML 응답 전체를 문 등) 경우가
|
||||
# 있어 상한을 둔다. 잘린 메시지도 원인 파악엔 충분하고, 전체는 여전히 로그에 남는다.
|
||||
_MAX_MESSAGE = 500
|
||||
_MAX_TARGET = 200
|
||||
|
||||
|
||||
@dataclass
|
||||
class CollectIssue:
|
||||
stage: str # 어느 단계에서(예: "naver_place" · "tour_api" · "yanolja" · "static_html")
|
||||
target: str # 무엇을 하다가(URL·검색어 등)
|
||||
error_type: str # 예외 클래스명
|
||||
message: str # 예외 메시지
|
||||
|
||||
|
||||
@contextmanager
|
||||
def collecting():
|
||||
"""run_collect() 진입부에서 한 번 연다. 중첩 호출은 바깥 것을 그대로 쓴다."""
|
||||
token = _current.set([])
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_current.reset(token)
|
||||
|
||||
|
||||
def note_issue(stage: str, target: str, ex: Exception) -> CollectIssue:
|
||||
"""실패 한 건을 기록하고 기존과 같은 형식으로 로그도 남긴다.
|
||||
|
||||
collecting() 없이 불러도 죽지 않는다 — 그때는 기록만 안 되고 로그는 그대로 남는다
|
||||
(단발 호출·테스트 호환)."""
|
||||
issue = CollectIssue(
|
||||
stage=stage,
|
||||
target=target[:_MAX_TARGET],
|
||||
error_type=type(ex).__name__,
|
||||
message=str(ex)[:_MAX_MESSAGE],
|
||||
)
|
||||
issues = _current.get()
|
||||
if issues is not None:
|
||||
issues.append(issue)
|
||||
LOG.w(f"[collect] {stage} 실패(계속) {issue.target}: {issue.error_type}: {issue.message}")
|
||||
return issue
|
||||
|
||||
|
||||
def snapshot() -> list[dict]:
|
||||
"""지금까지 쌓인 실패 목록. run_collect() 가 끝에서 jobs.result 에 싣는다."""
|
||||
issues = _current.get()
|
||||
return [asdict(i) for i in issues] if issues else []
|
||||
@@ -113,7 +113,10 @@ class DBSessionManager(Singleton):
|
||||
return ErrorType.SUCCESS
|
||||
except IntegrityError as ex:
|
||||
await db.rollback()
|
||||
LOG.e_no_callstack(f"duplicated. {ex}")
|
||||
# ★ 유니크 제약 충돌은 호출부가 "이미 있음"으로 처리하는 정상 경로다
|
||||
# (services/collect_service.py `_add_link`). ERROR 로 찍지 않는다 — 진짜 못
|
||||
# 보던 무결성 오류는 아래 일반 Exception 갈래로 간다.
|
||||
LOG.w(f"duplicated. {ex}")
|
||||
return ErrorType.DB_ALREADY_SAME_KEY
|
||||
except Exception as ex:
|
||||
await db.rollback()
|
||||
|
||||
@@ -80,6 +80,12 @@ class users(MainTableMixin, MAIN_BASE):
|
||||
# 컬럼이 NOT NULL 이면 그 경로가 통째로 깨진다(init.sql 의 DEFAULT 1 과 같은 값).
|
||||
provider = Column(SmallInteger, nullable=False, server_default=text("1"), default=AuthProvider.LOCAL.value)
|
||||
provider_uid = Column(String(255), nullable=True) # 구글 sub — 이메일이 바뀌어도 같은 사람인지 판단하는 유일한 키
|
||||
# ★ refresh 토큰 무효화 키. JWT(access·refresh 둘 다)의 sub 에 이 값을 같이 싣는다
|
||||
# (common/models/gmodel.py UserInfo). refresh_token() 이 DB 의 지금 값과 대조해서,
|
||||
# 달라졌으면(비밀번호 변경 등으로 bump_token_version 이 불렸으면) 재발급을 거절한다.
|
||||
# ★ access 토큰 자체는 검사하지 않는다 — 그건 30분짜리라 노출 창이 이미 좁다. 문제는
|
||||
# refresh 토큰(7일)이 DB 를 한 번도 안 보고 계속 access 토큰을 찍어 내던 것이었다.
|
||||
token_version = Column(SmallInteger, nullable=False, server_default=text("1"), default=1)
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -473,6 +479,29 @@ class site_search_status(MainTableMixin, MAIN_BASE):
|
||||
alerted_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
|
||||
class alert_outbox(MainTableMixin, MAIN_BASE):
|
||||
"""장애 알림 발송함 — services/alert_service.py 가 쓰고 읽는다.
|
||||
|
||||
★ 왜 영구 저장하나: 워커 프로세스가 죽으면 메모리에만 쌓아 둔 알림은 그대로 사라진다.
|
||||
장애가 나서 죽었는데 그 장애를 알릴 메시지까지 같이 잃으면 본말전도다.
|
||||
★ dedupe_key + 최근 전송 시각으로 재시도마다 중복 스팸을 막는다(alert_service.send_alert) —
|
||||
같은 사유가 몇 분 간격으로 계속 터져도 사람에게는 한 통만 간다.
|
||||
★ resolved_at 은 "복구 알림"의 근거다 — 이 키로 마지막에 안 풀린 알림이 있으면
|
||||
다음 정상 상태에서 복구 메시지를 한 번 보내고 이 값을 채운다."""
|
||||
|
||||
__tablename__ = "alert_outbox"
|
||||
alert_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
kind = Column(String(50), nullable=False) # job_dead · build_failed · partial_failure · queue_stuck · recovery …
|
||||
dedupe_key = Column(String(200), nullable=True)
|
||||
title = Column(String(200), nullable=False)
|
||||
detail = Column(Text, nullable=True) # 이미 비밀·개인정보를 걷어낸 텍스트만 들어온다(alert_service._scrub)
|
||||
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=1) # AlertStatus: 1=pending 2=sent 3=failed(소진)
|
||||
attempts = Column(SmallInteger, nullable=False, server_default=text("0"), default=0)
|
||||
next_attempt_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
|
||||
sent_at = Column(DateTime(timezone=True), nullable=True)
|
||||
resolved_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
|
||||
class site_sections(MainTableMixin, MAIN_BASE):
|
||||
"""섹션 하나의 콘텐츠. **JSON import/export 의 단위**다.
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ class ErrorType(Enum):
|
||||
ACCOUNT_PROVIDER_CONFLICT = auto() # 이미 다른 로그인 수단으로 가입된 이메일 — 자동 연결하지 않는다(DECISIONS 1절)
|
||||
OAUTH_NOT_CONFIGURED = auto() # GOOGLE_CLIENT_ID 미설정 — 구글 로그인만 꺼진다
|
||||
OAUTH_INVALID_TOKEN = auto() # 구글 ID 토큰 서명·수신자·만료 검증 실패
|
||||
ACCOUNT_SESSION_REVOKED = auto() # ★ refresh 토큰의 token_version 이 지금 DB 값과 다르다 — 그 뒤로 무효화됐다(비밀번호 변경 등)
|
||||
|
||||
# 사업장(places) 관련 에러
|
||||
PLACE_NOT_FOUND = 1200
|
||||
@@ -452,3 +453,11 @@ class JobStatus(CodeEnum):
|
||||
|
||||
# claim 대상이 되는 활성 상태. dedupe 부분 유니크 인덱스의 조건과 같아야 한다.
|
||||
ACTIVE_JOB_STATUSES = {JobStatus.PENDING, JobStatus.RUNNING}
|
||||
|
||||
|
||||
class AlertStatus(CodeEnum):
|
||||
"""alert_outbox.status 코드값. services/alert_service.py 가 이 상태로 재시도를 판단한다."""
|
||||
|
||||
PENDING = 1 # 아직 안 보냄(다음 process_outbox 스윕에서 시도)
|
||||
SENT = 2 # 전송 성공
|
||||
FAILED = 3 # 재시도 상한 소진 — 더 시도하지 않는다(사람이 outbox 를 봐야 한다)
|
||||
@@ -70,11 +70,15 @@ class UserInfo(StructModel):
|
||||
user_id: str # users.user_id (uuid) — 데이터 스코프 키. 사업장은 owner_user_id 로 이 값에 매인다
|
||||
id: str # users.id (로그인 아이디) — get_me 재조회 키
|
||||
role: int # users.role (UserRole) — 권한 게이트(최고관리자 등) 판단 키
|
||||
token_version: int # users.token_version — refresh 토큰 무효화 키(auth_service.refresh_token 이 대조)
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__()
|
||||
# 구버전 토큰(role 미포함) 도 디코딩되도록 기본값을 먼저 깔고 kwargs 로 덮어쓴다.
|
||||
# 구버전 토큰(role·token_version 미포함) 도 디코딩되도록 기본값을 먼저 깔고 kwargs 로
|
||||
# 덮어쓴다. token_version 기본값은 DB 컬럼 기본값(1)과 같아야 한다 — 배포 순간 옛
|
||||
# 토큰이 전부 "버전이 다르다"로 거절되는 것을 막는다.
|
||||
self.role = UserRole.USER.value
|
||||
self.token_version = 1
|
||||
for dictionary in args:
|
||||
for key in dictionary:
|
||||
setattr(self, key, dictionary[key])
|
||||
|
||||
Reference in new issue
Block a user