[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:
minaChoi committed 2026-09-16 16:25:02 +09:00
1 parent b76144746b
commit b4085a0e0f
36 files changed
+1320 -84

No files matched your search

+162
View File
@@ -0,0 +1,162 @@
"""장애 알림 — 영구 저장 + 재시도 + 중복 억제.
★ 왜 이 모양인가
잡 큐 소진(JobStatus.DEAD) · BUILD 잡의 업무 실패(게이트 반려가 아닌 렌더·인프라 실패) ·
노래 같은 곁가지의 부분 실패 · 잡 큐 정체를 Teams 로 알린다. 알림을 만드는 자리(worker/runner.py ·
build_service.py · scheduler)는 이 모듈의 send_alert() 하나만 부르면 된다 — 언제 실제로
보낼지, 같은 사유를 몇 번이나 다시 보낼지는 전부 여기서 정한다.
★ 재시도마다 중복 스팸을 내지 않는다 (dedupe)
같은 dedupe_key 로 "아직 안 풀린" 알림이 있으면 새로 만들지 않는다 — 잡이 몇 번을 실패하며
재큐되든 사람에게는 처음 한 통만 간다. 문제가 사라지면(resolve_alert) 그 dedupe_key 는
다시 "풀린" 상태가 되고, 다음에 같은 사유가 또 터지면 새로 알린다.
★ 영구 저장 + 재시도 (outbox)
webhook 전송이 그 자리에서 실패해도(네트워크 순단 등) 알림 자체를 잃지 않는다 — DB 에
PENDING 으로 남기고 process_outbox() 가 백오프를 두고 다시 시도한다. 워커·API 프로세스가
재시작돼도 이 표만 보면 뭐가 안 나갔는지 안다.
★ 비밀·개인정보를 남기지 않는다 (scrub)
detail 은 저장 **전에** 한 번 걸러진다 — 외부 API 예외 메시지가 쿼리스트링에 키를 실어
보내는 경우가 있다(TourAPI·Suno 등). 전화번호·API 키·bearer 토큰·이메일을 마스킹한다.
★ webhook 미설정이면 조용히 아무 일도 안 한다(teams_webhook.is_configured). 서버는 그대로 뜬다.
"""
import os
import re
from datetime import timedelta
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import DBType
from common.logger import LOG
from common.utils.gtime import GTime
from crud import alert_crud
from crud.job_crud import compute_backoff
from services import teams_webhook
# 중복 억제 창(분). 이 시간 안에 같은 dedupe_key 로 또 send_alert 가 불리면 새로 만들지 않는다.
DEDUPE_WINDOW_MIN_ENV = "ALERT_DEDUPE_WINDOW_MIN"
DEFAULT_DEDUPE_WINDOW_MIN = 60
# 재시도 상한. 소진되면 AlertStatus.FAILED — 더 자동으로는 안 보낸다.
MAX_ATTEMPTS = 5
_DETAIL_MAX_LEN = 2000
# ── 비밀·개인정보 마스킹 ──────────────────────────────────────────────────
_RE_QUERY_SECRET = re.compile(
r"(?i)([?&](?:key|token|api[_-]?key|secret|access[_-]?token|auth)=)[^\s&]+"
)
_RE_BEARER = re.compile(r"(?i)\bBearer\s+[A-Za-z0-9\-_.]{8,}")
_RE_KV_SECRET = re.compile(r"(?i)\b(password|passwd|pwd|secret|api[_-]?key)\s*[:=]\s*\S+")
_RE_EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
def _scrub(text: str) -> str:
"""저장 전에 반드시 한 번 거친다. 순서가 중요하다 — 쿼리스트링을 먼저 지워야
그 값이 이메일 형태여도 뒤의 이메일 마스킹이 이중으로 손대지 않는다."""
if not text:
return ""
out = _RE_QUERY_SECRET.sub(r"\1***", text)
out = _RE_BEARER.sub("Bearer ***", out)
out = _RE_KV_SECRET.sub(lambda m: f"{m.group(1)}=***", out)
out = _RE_EMAIL.sub(lambda m: m.group(0)[:2] + "***@***", out)
return out[:_DETAIL_MAX_LEN]
def _dedupe_window_min() -> int:
try:
return int(os.environ.get(DEDUPE_WINDOW_MIN_ENV) or DEFAULT_DEDUPE_WINDOW_MIN)
except ValueError:
return DEFAULT_DEDUPE_WINDOW_MIN
async def send_alert(kind: str, title: str, detail: str = "", dedupe_key: str | None = None) -> None:
"""알림을 큐에 넣는다(즉시 보내지 않는다 — process_outbox 가 보낸다).
★ 즉시 안 보내는 이유: 이 함수는 워커의 실패 처리 경로(예외 발생 지점)에서 불린다.
여기서 동기적으로 webhook 을 때리면 그 지연·재시도가 잡 처리 자체를 늦춘다. 큐에
적재만 하고 별도 스윕(scheduler)이 실제 전송을 맡는다 — 알림 발송 실패가 발행
파이프라인에 영향을 주지 않는다(파일 머리주석의 관심사 분리)."""
try:
async def _op(session):
if dedupe_key:
existing = await alert_crud.latest_unresolved(session, dedupe_key)
if existing is not None:
return # 이미 이 사유로 풀리지 않은 알림이 있다 — 또 만들지 않는다.
await alert_crud.insert(session, {
"kind": kind[:50],
"dedupe_key": dedupe_key[:200] if dedupe_key else None,
"title": title[:200],
"detail": _scrub(detail),
})
await DB_SESSION_MNG.execute_lambda_write(DBType.MAIN.value, _op)
except Exception as ex: # noqa: BLE001 — 알림 적재 실패가 원래 하던 일(잡 처리)을 죽이면 안 된다
LOG.w(f"[alert] 적재 실패(무시하고 계속): {type(ex).__name__}: {ex}")
async def resolve_alert(dedupe_key: str, title: str, detail: str = "") -> None:
"""이 dedupe_key 로 안 풀린 알림이 있으면 "복구됨" 을 한 번 알리고 풀린 것으로 남긴다.
★ 안 풀린 알림이 없으면(애초에 문제가 없었다) 아무것도 하지 않는다 — 정상 상태마다
"복구됨" 을 보내면 그게 새로운 스팸이 된다."""
try:
async def _op(session):
existing = await alert_crud.latest_unresolved(session, dedupe_key)
if existing is None:
return
await alert_crud.mark_resolved(session, existing.alert_id)
await alert_crud.insert(session, {
"kind": "recovery",
"dedupe_key": None, # 복구 알림 자신은 dedupe 대상이 아니다 — 매번 보낸다.
"title": title[:200],
"detail": _scrub(detail),
})
await DB_SESSION_MNG.execute_lambda_write(DBType.MAIN.value, _op)
except Exception as ex: # noqa: BLE001
LOG.w(f"[alert] 복구 알림 적재 실패(무시하고 계속): {type(ex).__name__}: {ex}")
async def process_outbox(limit: int = 20) -> dict:
"""PENDING 알림을 실제로 보낸다. 스케줄러가 주기적으로 부른다(scheduler/jobs.py).
★ 잡 큐의 백오프·소진 규칙(crud/job_crud.compute_backoff)을 그대로 재사용한다 —
"몇 번 실패하면 얼마나 쉬고 언제 포기하나" 를 두 번 설계하지 않는다."""
sent = failed = 0
try:
async def _load(session):
return await alert_crud.due_pending(session, limit)
due = await DB_SESSION_MNG.execute_lambda_write(DBType.MAIN.value, _load)
except Exception as ex: # noqa: BLE001
LOG.w(f"[alert] outbox 조회 실패: {type(ex).__name__}: {ex}")
return {"sent": 0, "failed": 0}
for row in due:
ok = await teams_webhook.send(row.title, row.detail or "")
async def _update(session, row=row, ok=ok):
if ok:
await alert_crud.mark_sent(session, row.alert_id)
else:
attempts = row.attempts + 1
if attempts >= MAX_ATTEMPTS:
await alert_crud.mark_exhausted(session, row.alert_id, attempts)
else:
next_at = GTime.UTC() + timedelta(seconds=compute_backoff(attempts))
await alert_crud.mark_retry(session, row.alert_id, attempts, next_at)
try:
await DB_SESSION_MNG.execute_lambda_write(DBType.MAIN.value, _update)
except Exception as ex: # noqa: BLE001
LOG.w(f"[alert] outbox 갱신 실패 {row.alert_id}: {type(ex).__name__}: {ex}")
continue
if ok:
sent += 1
else:
failed += 1
if sent or failed:
LOG.i(f"[alert] outbox 스윕 — 전송 {sent}건 · 재시도/소진 {failed}건")
return {"sent": sent, "failed": failed}
+34 -2
View File
@@ -76,6 +76,7 @@ class AuthService:
user_id=str(user.user_id),
id=user.id,
role=user.role,
token_version=user.token_version,
)
async def _finish_login(self, user: users) -> Res_Login:
@@ -316,6 +317,10 @@ class AuthService:
res.result.SetResult(ErrorType.ACCOUNT_PROVIDER_CONFLICT)
return res
data["password"] = await GetHashedPW(data["password"])
# ★ 비밀번호를 바꾸면 그 전에 나간 refresh 토큰을 전부 무효화한다 — 안 그러면
# 누군가 비번을 훔쳐 넣어 둔 refresh 토큰이 이 사람이 비번을 바꾼 뒤로도
# 계속 살아 있다(auth_service.refresh_token 이 이 값을 대조한다).
data["token_version"] = (me.token_version or 1) + 1
else:
data.pop("password", None)
# 빈 문자열은 NULL 로 저장(미입력 = 값 비움).
@@ -336,8 +341,35 @@ class AuthService:
return await self.get_me(user_info)
async def refresh_token(self, refresh_token: str) -> Res_RefreshToken:
"""refresh 토큰 → 새 access 토큰.
★ 서명·만료만 보고 DB 를 한 번도 안 읽던 자리다 — 비밀번호를 바꾸거나 계정을
막아도, 이미 나간 refresh 토큰(7일)은 만료 전까지 계속 새 access 토큰을 찍어냈다.
여기서 최신 DB 상태를 한 번 대조한다: 이 토큰의 token_version 이 지금 값과
다르면(bump_token_version 이 불렸다는 뜻) 재발급을 거절한다."""
res = Res_RefreshToken()
# refresh 토큰 검증은 라우터 Depends(IsValidRefreshToken) 에서 1차 수행됨.
# refresh 토큰 검증은 라우터 Depends(IsValidRefreshToken) 에서 1차 수행됨(서명·만료).
user_info = DecodeRefreshToken(refresh_token)
res.access_token = CreateAccessToken(user_info)
err_type, user = await DB_SESSION_MNG.execute_lambda(
users.DBType(),
DBWRType.DB_READ.value,
lambda s: self.user_crud.get_user_by_login_id(s, user_info.id),
)
if err_type != ErrorType.SUCCESS or user is None:
res.result.SetResult(ErrorType.ACCOUNT_NOT_FOUND)
return res
user: users
if user.status != UserStatus.ACTIVE.value:
res.result.SetResult(ErrorType.ACCOUNT_BLOCKED_USER)
return res
# ★ 구버전 토큰(token_version 없이 발급됨)은 UserInfo 기본값 1 로 읽힌다 — DB 컬럼
# 기본값도 1 이라 배포 직후에는 전부 통과한다. bump 가 불린 뒤에만 갈린다.
if user_info.token_version != user.token_version:
res.result.SetResult(ErrorType.ACCOUNT_SESSION_REVOKED)
return res
# ★ 최신 DB 값으로 다시 만든다 — role 이 바뀌었으면 그것도 여기서 따라온다.
res.access_token = CreateAccessToken(self._user_info(user))
return res
@@ -30,6 +30,7 @@ from common.utils.gtime import GTime
from crud.site_crud import SiteCRUD
from crud.place_crud import PlaceCRUD
from services import (
alert_service,
azure_static,
indexnow,
publish_gate,
@@ -155,6 +156,15 @@ async def run_build(job: dict) -> dict:
except Exception as ex: # noqa: BLE001 — 노래 실패가 발행을 죽이면 안 된다
song_result = {"error": f"{type(ex).__name__}: {ex}"}
LOG.w(f"[build] place={place_id} 노래 실패(노래 없이 발행): {type(ex).__name__}: {ex}")
# ★ 발행 자체는 계속되므로(사이트는 노래 없이 나간다) 이건 REJECTED 도 FAILED 도
# 아니다 — 별도 종류(partial_failure)로 알린다. 발행이 실패한 게 아니라는 걸
# 운영자가 첫 줄만 보고 알아야 한다.
await alert_service.send_alert(
kind="partial_failure",
title=f"노래 생성 실패(발행은 계속) — {place_id}",
detail=f"place_id={place_id}\n{song_result['error']}",
dedupe_key=f"song_failed:{place_id}",
)
# ★ 일정(LLM)은 **여기서 직접** 부른다. 이건 잡이라 기다리는 사람이 없다 —
# 캔버스 경로가 잡으로 넘기는 것과 사정이 다르다(local_content_service._ensure_region_stories).
@@ -226,6 +236,15 @@ async def run_build(job: dict) -> dict:
result["build_status"] = "FAILED"
result["error"] = reason
LOG.w(f"[build] place={place_id} v{version_no} 실패: {reason}")
# ★ 게이트 반려(gate is not None)는 알리지 않는다 — 사장님이 값을 안 채웠다고
# 운영자를 부르면 안 된다. 여기서 알리는 건 렌더·인프라가 죽은 "업무 실패"뿐이다.
if gate is None:
await alert_service.send_alert(
kind="build_failed",
title=f"발행 실패 — {place_name or place_id}",
detail=f"place_id={place_id} v{version_no}\n{reason}",
dedupe_key=f"build_failed:{place_id}",
)
return result
# ---- 1차 게이트: 렌더 없이 판정 가능한 것 ----
@@ -348,6 +367,10 @@ async def run_build(job: dict) -> dict:
)
result["build_status"] = "BUILT"
result["routes"] = report.get("routes")
# ★ 빌드가 렌더·인프라 실패 없이 끝났다 — 직전에 build_failed 알림이 안 풀린 채 있었으면
# 지금 풀렸다는 뜻이다(정상 발행이 재개됐다). 알림이 없었으면 resolve_alert 가 조용히
# 아무것도 안 한다(파일 머리주석).
await alert_service.resolve_alert(f"build_failed:{place_id}", f"발행 재개 — {place_name or place_id}")
if want_publish:
# 썸네일은 발행 상태 전이와 같은 UPDATE 에 싣는다 — 못 만들었으면 키를 넣지 않아
+21 -11
View File
@@ -5,6 +5,7 @@
import re
import uuid
from common import collect_diagnostics
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import place_facts as facts_model
from common.database.model.models import place_photos, place_channels, places, place_units
@@ -124,7 +125,7 @@ async def discover_official_site(place, place_id: str) -> str:
try:
candidates = await client.search_local(query)
except Exception as ex: # noqa: BLE001 — 발견 실패가 수집을 죽이면 안 된다
LOG.w(f"[collect] 지역검색 실패(계속) {query!r}: {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("naver_local_search", query, ex)
return "not_found"
match = naver_client.pick_match(place.name, candidates, address)
@@ -168,7 +169,7 @@ async def discover_tour_api(place, place_id: str) -> str:
longitude=place.longitude,
)
except Exception as ex: # noqa: BLE001 — 발견 실패가 수집을 죽이면 안 된다
LOG.w(f"[collect] TourAPI 조회 실패(계속): {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("tour_api", place.name, ex)
return "error"
if not found:
@@ -215,7 +216,7 @@ async def discover_yanolja(place, place_id: str) -> str:
try:
found = await yanolja_adapter.search_by_address(address)
except Exception as ex: # noqa: BLE001 — 발견 실패가 수집을 죽이면 안 된다
LOG.w(f"[collect] 야놀자 검색 실패(계속): {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("yanolja_search", place.name, ex)
return "error"
if not found:
@@ -254,7 +255,7 @@ async def discover_links(place, place_id: str, *, include_perplexity: bool = Fal
if stat["naver_place"] == "resolved":
stat["discovered"] += 1
except Exception as ex: # noqa: BLE001 — 발견 실패가 수집을 죽이면 안 된다
LOG.w(f"[collect] 네이버 플레이스 조회 실패(계속): {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("naver_place", place.name, ex)
stat["naver_place"] = "error"
# TourAPI 도 같은 성격의 '직접 해석' 이다 — 검색모델을 거치지 않고, 키가 있으면 항상 시도한다.
@@ -264,7 +265,7 @@ async def discover_links(place, place_id: str, *, include_perplexity: bool = Fal
if stat["tour_api"] == "resolved":
stat["discovered"] += 1
except Exception as ex: # noqa: BLE001
LOG.w(f"[collect] TourAPI 조회 실패(계속): {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("tour_api", place.name, ex)
stat["tour_api"] = "error"
# 자체 홈페이지 — 네이버 지역검색이 이미 준 값이라 추가 요금이 없다(위 함수 머리주석).
@@ -274,7 +275,7 @@ async def discover_links(place, place_id: str, *, include_perplexity: bool = Fal
if stat["official_site"] == "resolved":
stat["discovered"] += 1
except Exception as ex: # noqa: BLE001
LOG.w(f"[collect] 자체 홈페이지 조회 실패(계속): {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("official_site", place.name, ex)
stat["official_site"] = "error"
# 야놀자(NOL) — 숙박 업종에서만 의미가 있고, 상호 대조 실패 시 등록하지 않는다(위 함수 참고).
@@ -284,7 +285,7 @@ async def discover_links(place, place_id: str, *, include_perplexity: bool = Fal
if stat["yanolja"] == "resolved":
stat["discovered"] += 1
except Exception as ex: # noqa: BLE001
LOG.w(f"[collect] 야놀자 조회 실패(계속): {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("yanolja", place.name, ex)
stat["yanolja"] = "error"
# 오직 요청 옵션으로만 연다. 서버 env 로 일괄 활성화하면 일반 크롤링·재수집에서도
@@ -309,7 +310,7 @@ async def discover_links(place, place_id: str, *, include_perplexity: bool = Fal
return stat
except perplexity.PerplexityError as ex:
# ★ 실패해도 파이프라인을 죽이지 않는다 — 이미 등록된 링크로 크롤링은 계속한다.
LOG.w(f"[collect] URL 발견 실패(계속): {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("perplexity_discover", place.name, ex)
stat["error"] = str(ex)[:200]
return stat
@@ -421,10 +422,10 @@ async def fetch_one(link):
try:
source = await adapter.fetch(link.url)
except Exception as ex:
LOG.w(f"[collect] 수집 실패(계속) {link.url}: {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("fetch", link.url, ex)
return None, "failed"
if not source.ok:
LOG.w(f"[collect] 수집 실패(계속) {link.url}: {source.error}")
collect_diagnostics.note_issue("fetch", link.url, RuntimeError(source.error))
return None, "failed"
return source, "fetched"
@@ -550,6 +551,15 @@ async def store_media(place_id: str, sources: list, unit_map: dict) -> dict:
# ---- 오케스트레이션 --------------------------------------------------------
async def run_collect(job: dict) -> dict:
"""COLLECT 잡 핸들러. 반환값이 jobs.result 에 저장돼 폴링·감사에 쓰인다."""
with collect_diagnostics.collecting():
result = await _run_collect(job)
issues = collect_diagnostics.snapshot()
if issues:
result["issues"] = issues
return result
async def _run_collect(job: dict) -> dict:
payload = job["payload"]
place_id = payload["place_id"]
owner_user_id = payload["owner_user_id"]
@@ -682,7 +692,7 @@ async def run_collect(job: dict) -> dict:
from services import place_research
result["research"] = await place_research.research_place(place, place_id)
except Exception as ex: # noqa: BLE001
LOG.w(f"[collect] 업소 조사 실패(계속): {type(ex).__name__}: {ex}")
collect_diagnostics.note_issue("place_research", place.name, ex)
result["research"] = {"error": f"{type(ex).__name__}: {ex}"}
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
+11 -2
View File
@@ -1,4 +1,5 @@
"""COPY 흐름. 단계 구현: copy_steps / 프롬프트: prompts/copy / 호출·검증: external/gemini_text."""
from common.logger import LOG
from services.copy_steps import CopyAborted, prepare_copy, generate_copy, save_copy, fill_faqs
from services.external import gemini_text
from services.job_progress import JobProgress
@@ -20,8 +21,16 @@ async def run_copy(job: dict) -> dict:
if inputs.catalog is None and not inputs.ungrounded:
raise CopyAborted(note)
else:
async with progress.step("generate"):
copy = await generate_copy(inputs)
try:
async with progress.step("generate"):
copy = await generate_copy(inputs)
except gemini_text.GeminiError as ex:
# ★ 호출 실패는 미설정과 같은 취급이다 — fact 만으로도 편집·발행이 되고
# (publish_gate.check_unique_content), 발행은 고유 콘텐츠 0건으로 막지 않는다.
# 자세한 배경은 DEVLOG.md 참고.
note = f"생성 호출 실패: {ex}"
LOG.w(f"[copy] 생성 실패, fact 만으로 계속: {ex}")
await progress.skip("generate", "generation_failed")
async with progress.step("save"):
result = await save_copy(inputs, copy)
+11 -1
View File
@@ -37,7 +37,7 @@ from common.logger import LOG
from common.utils.gtime import GTime
from crud.place_crud import PlaceCRUD
from crud.site_crud import SiteCRUD
from services import azure_static, indexnow, publish_gate, render_service, site_payload
from services import alert_service, azure_static, indexnow, publish_gate, render_service, site_payload
from services.build_service import ensure_site, load_channel_links
_site_crud = SiteCRUD()
@@ -104,6 +104,15 @@ async def run_rollback(job: dict) -> dict:
result["rolled_back"] = False
result["error"] = reason
LOG.w(f"[rollback] place={place_id} v{target_version} 실패: {reason}")
# ★ 게이트 반려는 알리지 않는다 — build_service._fail 과 같은 규칙(운영자를 부를
# 일이 아니다). 렌더·전환·업로드가 죽은 경우만 알린다.
if gate is None:
await alert_service.send_alert(
kind="build_failed",
title=f"롤백 실패 — {place_id} → v{target_version}",
detail=f"place_id={place_id} target_version={target_version}\n{reason}",
dedupe_key=f"build_failed:{place_id}",
)
return result
# ★ snapshot 을 그대로 옮긴다 — 재수집하지 않는다(파일 머리주석 참조).
@@ -152,6 +161,7 @@ async def run_rollback(job: dict) -> dict:
sites.DBType(), lambda s: _site_crud.update_site(s, site.site_id, site_update)
)
await _log(site.site_id, version.site_version_id, PublishResult.SUCCESS, None, payload.get("requested_by"))
await alert_service.resolve_alert(f"build_failed:{place_id}", f"롤백 성공 — {place_id} → v{target_version}")
result["rolled_back"] = True
LOG.i(f"[rollback] place={place_id} v{target_version} 로 되돌림")
@@ -0,0 +1,69 @@
"""Microsoft Teams Workflows(수신 webhook) 로 어댑티브 카드 한 장을 보낸다.
★ 이 파일은 "HTTP 로 카드 하나 보내기" 딱 그것만 안다 — 언제 보낼지·무엇을 보낼지는
services/alert_service.py 가 정한다(관심사 분리, 재사용). search_console_alerts.py 가
쓰는 별도의 좁은 어댑터와는 다른 자리다 — 그건 색인 감시 전용이고 이건 잡 큐·발행 전반의
장애 알림 전용이다. 카드 포맷이 같은 이유로 합치자는 제안이 오면, 두 기능의 배포 주기가
다르다는 것과(색인 감시는 스케줄러 전용, 이건 워커 코드 곳곳에서 부른다) 지금 결합 이득이
적다는 것을 근거로 우선 보류한다.
★ webhook 이 설정 안 됐으면 보내지 않는다(is_configured). 값이 없어도 서버는 그대로 뜬다 —
운영 연결(실제 채널 지정)은 사용자 승인 후 별도로 한다.
"""
import os
import httpx
from common.logger import LOG
WEBHOOK_URL_ENV = "TEAMS_WEBHOOK_URL"
TIMEOUT_SEC = 10.0
def is_configured() -> bool:
return bool(os.environ.get(WEBHOOK_URL_ENV, "").strip())
def _webhook_url() -> str:
return os.environ.get(WEBHOOK_URL_ENV, "").strip()
def _card(title: str, detail: str) -> dict:
"""Adaptive Card 1.2 — Teams Workflows 가 받는 최소 모양(search_console_alerts.py 와 같은 스키마)."""
return {
"type": "message",
"attachments": [{
"contentType": "application/vnd.microsoft.card.adaptive",
"contentUrl": None,
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
"body": [
{"type": "TextBlock", "text": title, "weight": "Bolder", "wrap": True},
{"type": "TextBlock", "text": detail, "wrap": True},
],
},
}],
}
async def send(title: str, detail: str) -> bool:
"""설정된 경우에만 보낸다. 실패는 로그로 남기고 삼킨다 — 호출측(alert_service)이 재시도를 관리한다.
★ webhook 주소 자체가 인증 수단이다(URL 에 서명이 박혀 있다) — 예외 문자열에 그 URL 이
실릴 수 있어 로그에는 안 남긴다(search_console_alerts.py 와 같은 규칙)."""
url = _webhook_url()
if not url:
return False
if not url.startswith("https://"):
LOG.w("[alert] TEAMS_WEBHOOK_URL_INVALID — https 가 아니다")
return False
try:
async with httpx.AsyncClient(timeout=TIMEOUT_SEC, follow_redirects=False) as client:
response = await client.post(url, json=_card(title, detail))
response.raise_for_status()
return True
except httpx.HTTPError:
LOG.w("[alert] TEAMS_DELIVERY_FAILED")
return False