[feat] solution/backend: 서치콘솔 자동 제출·색인 상태 추적 추가

사이트 발행 성공과 Google 색인 관측은 별도 상태다. 외부 API 장애로 발행이 실패하거나 재시작 때 추적 정보가 사라지지 않도록 분리.

- Google 클라이언트·배치·DB·Teams 알림 모듈 분리
- 기존 스케줄러 연결, 재시도·중복 실행 방지와 선택 설정 추가
- ORM·초기 DDL·마이그레이션·운영 설정 문서 동시 갱신

검증: 관련 59건 통과, compose 설정·diff 검사 통과. 추가 회귀 23건 통과, 기존 발행 검수 실패 1건은 변경 전 코드에서도 재현. 운영 배포·Google/Teams 실호출 미실행.
This commit is contained in:
minaChoi committed 2026-09-15 14:50:30 +09:00
1 parent 9773bc0496
commit 3f47d5ecd2
20 files changed
+1354 -2

No files matched your search

@@ -0,0 +1,43 @@
"""Teams Workflow 수신용. 원문 오류/인증 정보는 메시지에 싣지 않는다."""
from datetime import timedelta
import httpx
from common.logger import LOG
def alert_reason(row, now, days: int) -> str | None:
if row.alerted_at and now - row.alerted_at < timedelta(days=1):
return None
if row.error_code:
return f"조회/제출 실패: {row.error_code}"
if (row.inspection or {}).get("verdict") == "PASS":
return None
if now - row.published_at >= timedelta(days=days):
return f"발행 후 {days}일 이상 색인 미확인"
return None
async def send_alert(webhook_url: str, page_url: str, reason: str) -> bool:
if not webhook_url:
return False
if not webhook_url.startswith("https://"):
LOG.w("[search-console] ALERT_URL_INVALID")
return False
payload = {"type": "message", "attachments": [{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {"type": "AdaptiveCard", "version": "1.2", "body": [
{"type": "TextBlock", "text": "Google 색인 확인 필요", "weight": "Bolder"},
{"type": "TextBlock", "text": page_url, "wrap": True},
{"type": "TextBlock", "text": reason, "wrap": True},
]},
}]}
try:
async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client:
response = await client.post(webhook_url, json=payload)
response.raise_for_status()
return True
except httpx.HTTPError:
# webhook 주소 자체가 인증 수단이므로 예외 문자열도 로그에 남기지 않는다.
LOG.w("[search-console] ALERT_DELIVERY_FAILED")
return False
@@ -0,0 +1,164 @@
"""Google Search Console REST 클라이언트 — 사이트맵 제출 · URL 색인 상태 조회.
PUT https://www.googleapis.com/webmasters/v3/sites/{siteUrl}/sitemaps/{feedpath}
POST https://searchconsole.googleapis.com/v1/urlInspection/index:inspect
자세한 계약은 docs/SEARCH_CONSOLE_CLIENT.md.
★ `SearchConsoleError` 는 `code` 문자열만 담는다 — Google 응답 본문·토큰·키·원본
예외 메시지는 절대 싣지 않는다.
★ `inspectionResult`·`indexStatusResult` 가 없거나 빈 응답은 "미색인"으로
넘겨짚지 않고 예외로 끊는다 — 검사 실패와 색인 결과를 구분 못하면 오판이 된다.
"""
from __future__ import annotations
import asyncio
from typing import Any
from urllib.parse import quote
import httpx
SITEMAPS_BASE = "https://www.googleapis.com/webmasters/v3/sites"
INSPECT_URL = "https://searchconsole.googleapis.com/v1/urlInspection/index:inspect"
SCOPES = ["https://www.googleapis.com/auth/webmasters"]
TIMEOUT_SEC = 20.0
AUTH_REFRESH_TIMEOUT_SEC = 20.0
class SearchConsoleError(RuntimeError):
"""code 만 담는다 — Google 응답 본문·토큰·키는 여기 실으면 안 된다."""
def __init__(self, code: str):
self.code = code
super().__init__(code)
def _service_account_credentials(credentials_file: str):
"""lazy import — 미설치여도 이 모듈의 import 자체는 죽지 않는다."""
from google.oauth2 import service_account
return service_account.Credentials.from_service_account_file(credentials_file, scopes=SCOPES)
def _refresh_sync(credentials) -> None:
"""동기 토큰 갱신. `asyncio.to_thread` 로 감싸 부른다.
`Request.__call__` 기본 타임아웃(120s)을 그대로 두면 만료된 키·막힌 네트워크에서
오래 걸릴 수 있다 — 매 요청에 상한을 강제로 덮어씌운다(호출측이 넘긴 값 포함)."""
import requests
from google.auth.transport.requests import Request
with requests.Session() as session:
original_request = session.request
def _request_with_timeout(*args, **kwargs):
kwargs["timeout"] = AUTH_REFRESH_TIMEOUT_SEC
return original_request(*args, **kwargs)
session.request = _request_with_timeout
credentials.refresh(Request(session=session))
def _status_error_code(status_code: int) -> str:
if status_code == 401:
return "unauthorized"
if status_code == 403:
return "forbidden"
if status_code == 429:
return "rate_limited"
if 500 <= status_code < 600:
return "server_error"
return f"http_{status_code}"
def _transport_error_code(ex: httpx.HTTPError) -> str:
if isinstance(ex, httpx.TimeoutException):
return "timeout"
return "transport_error"
class SearchConsoleClient:
def __init__(self, credentials_file: str, *, transport: httpx.AsyncBaseTransport | None = None):
self._credentials_file = credentials_file
self._client = httpx.AsyncClient(timeout=TIMEOUT_SEC, transport=transport)
self._credentials: Any = None
self._auth_lock = asyncio.Lock()
async def __aenter__(self) -> "SearchConsoleClient":
return self
async def __aexit__(self, exc_type, exc, tb) -> None:
await self.aclose()
async def aclose(self) -> None:
await self._client.aclose()
async def submit_sitemap(self, property_url: str, sitemap_url: str) -> None:
url = f"{SITEMAPS_BASE}/{quote(property_url, safe='')}/sitemaps/{quote(sitemap_url, safe='')}"
headers = await self._auth_headers()
res = await self._put(url, headers)
self._raise_for_status(res)
async def inspect_url(self, property_url: str, page_url: str) -> dict[str, Any]:
headers = await self._auth_headers()
body = {"inspectionUrl": page_url, "siteUrl": property_url}
res = await self._post(INSPECT_URL, headers, body)
self._raise_for_status(res)
return _index_status_result(res)
async def _put(self, url: str, headers: dict[str, str]) -> httpx.Response:
try:
return await self._client.put(url, headers=headers)
except httpx.HTTPError as ex:
raise SearchConsoleError(_transport_error_code(ex)) from None
async def _post(self, url: str, headers: dict[str, str], body: dict[str, Any]) -> httpx.Response:
try:
return await self._client.post(url, headers=headers, json=body)
except httpx.HTTPError as ex:
raise SearchConsoleError(_transport_error_code(ex)) from None
def _raise_for_status(self, res: httpx.Response) -> None:
if not res.is_success:
raise SearchConsoleError(_status_error_code(res.status_code))
async def _auth_headers(self) -> dict[str, str]:
token = await self._access_token()
return {"Authorization": f"Bearer {token}"}
async def _access_token(self) -> str:
credentials = self._load_credentials()
if not getattr(credentials, "valid", False):
async with self._auth_lock:
if not getattr(credentials, "valid", False):
try:
await asyncio.to_thread(_refresh_sync, credentials)
except Exception:
raise SearchConsoleError("auth_failed") from None
token = getattr(credentials, "token", None)
if not token:
raise SearchConsoleError("auth_failed")
return token
def _load_credentials(self) -> Any:
if self._credentials is None:
try:
self._credentials = _service_account_credentials(self._credentials_file)
except Exception:
raise SearchConsoleError("invalid_credentials_file") from None
return self._credentials
def _index_status_result(res: httpx.Response) -> dict[str, Any]:
try:
data = res.json()
except ValueError:
raise SearchConsoleError("invalid_json") from None
inspection_result = data.get("inspectionResult") if isinstance(data, dict) else None
if not isinstance(inspection_result, dict):
raise SearchConsoleError("missing_inspection_result")
index_status_result = inspection_result.get("indexStatusResult")
if not isinstance(index_status_result, dict) or not index_status_result:
raise SearchConsoleError("missing_index_status_result")
return index_status_result
@@ -0,0 +1,129 @@
"""발행 감지 → 사이트맵 제출 → 색인 조회 → 알림. 발행 잡과 별도 트랜잭션이다."""
import asyncio
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone
import httpx
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import DBType
from common.logger import LOG
from crud import search_console_crud as store
from services import site_payload
from services.search_console_alerts import alert_reason, send_alert
from services.search_console_client import SearchConsoleClient, SearchConsoleError
from services.search_console_settings import load_settings, belongs_to_property
async def run_scheduled_check():
try:
settings = load_settings()
if settings is None:
return
await DB_SESSION_MNG.execute_lambda_write(
DBType.MAIN.value, lambda session: run_batch(session, settings),
)
except Exception:
# 크론 실패가 API/발행에 전파되지 않고 다음 주기에 재시도된다.
LOG.w("[search-console] BATCH_FAILED — 설정 및 DB 마이그레이션 확인 필요")
async def run_batch(session, settings):
if not await store.lock_batch(session):
return
if not belongs_to_property(site_payload.publish_origin() + "/sitemap.xml", settings.property_url):
raise SearchConsoleError("PROPERTY_MISMATCH")
await register_publications(session, settings)
rows = await store.due_sites(session, settings.property_url)
if not rows:
return
async with SearchConsoleClient(settings.credentials_file) as client:
submitted = set()
for row in rows:
await check_site(client, row, settings, submitted)
await session.flush()
async def register_publications(session, settings):
for site, place, version in await store.new_publications(session, settings.property_url):
slug = site_payload.publish_slug(place, site)
page_url = f"{site_payload.publish_origin()}/s/{slug}"
if not belongs_to_property(page_url, settings.property_url):
LOG.w("[search-console] PROPERTY_MISMATCH")
continue
await store.register(session, {
"site_id": site.site_id, "site_version_id": version.site_version_id,
"property_url": settings.property_url, "page_url": page_url,
"published_at": site.published_at,
})
async def read_sitemap(sitemap_url: str) -> set[str]:
try:
async with httpx.AsyncClient(timeout=20, follow_redirects=False) as client:
async with client.stream("GET", sitemap_url) as response:
response.raise_for_status()
body = bytearray()
async for chunk in response.aiter_bytes():
body.extend(chunk)
if len(body) > 5_000_000:
raise SearchConsoleError("SITEMAP_TOO_LARGE")
root = ET.fromstring(body)
return {(item.text or "").strip() for item in root.iter(
"{http://www.sitemaps.org/schemas/sitemap/0.9}loc"
)}
except (httpx.HTTPError, ET.ParseError):
raise SearchConsoleError("SITEMAP_UNAVAILABLE") from None
async def submit_sitemap(client, row, submitted: set):
if row.sitemap_submitted_at:
return
sitemap_url = site_payload.publish_origin() + "/sitemap.xml"
# 디스크가 아니라 실제 공개 URL을 확인한다. 업로드 지연 시 Google에 먼저 알리지 않는다.
urls = await read_sitemap(sitemap_url)
if row.page_url not in urls:
raise SearchConsoleError("URL_NOT_IN_SITEMAP")
if sitemap_url not in submitted:
await client.submit_sitemap(row.property_url, sitemap_url)
submitted.add(sitemap_url)
row.sitemap_submitted_at = datetime.now(timezone.utc)
def record_inspection(row, inspection: dict, now):
row.inspection = inspection
row.inspected_at = now
row.error_code = None
row.failures = 0
if inspection.get("verdict") == "PASS":
row.first_indexed_at = row.first_indexed_at or now
row.next_check_at = now + timedelta(days=1)
def record_error(row, code: str, now):
row.error_code = code
row.failures = (row.failures or 0) + 1
hours = min(24, 2 ** min(row.failures - 1, 5))
row.next_check_at = now + timedelta(hours=hours)
async def check_site(client, row, settings, submitted: set):
now = datetime.now(timezone.utc)
try:
if not belongs_to_property(row.page_url, settings.property_url):
raise SearchConsoleError("PROPERTY_MISMATCH")
async with asyncio.timeout(90):
await submit_sitemap(client, row, submitted)
inspection = await client.inspect_url(row.property_url, row.page_url)
record_inspection(row, inspection, now)
except SearchConsoleError as ex:
record_error(row, ex.code, now)
except TimeoutError:
record_error(row, "CHECK_TIMEOUT", now)
except Exception:
record_error(row, "CHECK_FAILED", now)
reason = alert_reason(row, now, settings.alert_days)
if reason:
LOG.w(f"[search-console] site={row.site_id} {reason}")
if await send_alert(settings.alert_url, row.page_url, reason):
row.alerted_at = now
@@ -0,0 +1,43 @@
"""Google 로그인 설정과 분리한다. 서비스 계정 키는 서버 파일로만 읽는다."""
import os
from dataclasses import dataclass
from urllib.parse import urlsplit
@dataclass(frozen=True)
class SearchConsoleSettings:
property_url: str
credentials_file: str
alert_url: str = ""
alert_days: int = 7
def load_settings() -> SearchConsoleSettings | None:
if os.environ.get("GSC_ENABLED") != "1":
return None
prop = os.environ.get("GSC_PROPERTY_URL", "").strip()
key_file = os.environ.get("GSC_CREDENTIALS_FILE", "").strip()
if not prop or not key_file:
raise ValueError("GSC_CONFIG_MISSING")
parsed = urlsplit(prop)
domain_property = prop.startswith("sc-domain:") and bool(prop.removeprefix("sc-domain:"))
root_property = (parsed.scheme == "https" and parsed.hostname and parsed.path == "/"
and not parsed.query and not parsed.fragment and not parsed.username)
if not domain_property and not root_property:
raise ValueError("GSC_PROPERTY_INVALID")
days = int(os.environ.get("GSC_ALERT_DAYS", "7"))
if days < 1:
raise ValueError("GSC_ALERT_DAYS_INVALID")
return SearchConsoleSettings(prop, key_file, os.environ.get("GSC_ALERT_WEBHOOK_URL", ""), days)
def belongs_to_property(page_url: str, property_url: str) -> bool:
parsed = urlsplit(page_url)
if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
return False
if parsed.query or parsed.fragment:
return False
if property_url.startswith("sc-domain:"):
domain = property_url.removeprefix("sc-domain:").lower()
return bool(domain) and (parsed.hostname == domain or parsed.hostname.endswith("." + domain))
return page_url.startswith(property_url)