fix(performance): 메타 연결 테스트 진단이 잘리던 문제
- 비밀값 가림(redact_text)의 기본 300자 한도에서 긴 메타 원문·안내 뒤의 [진단]이 "[진…"으로 잘렸다. - 연결 테스트 문구를 [진단] 먼저 + 메타 원문(긴 안내 주소 제거) 뒤로 바꾸고, 광고 연동 오류 문구 한도를 ad_sync.AD_MESSAGE_MAX(1200자)로. - 테스트: 설정 연결 테스트 경로(AdSyncService)에서 진단 전체·순서·주소 제거·토큰 미포함 확인. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -260,7 +260,7 @@ class MetaAdsSource(AdSource):
|
|||||||
"관리자·개발자 역할인지 확인하세요.")
|
"관리자·개발자 역할인지 확인하세요.")
|
||||||
else:
|
else:
|
||||||
todo = "토큰 정보를 메타에서 읽지 못해 원인을 좁히지 못했습니다 — 토큰 권한(ads_read)과 광고 계정 배정을 확인하세요."
|
todo = "토큰 정보를 메타에서 읽지 못해 원인을 좁히지 못했습니다 — 토큰 권한(ads_read)과 광고 계정 배정을 확인하세요."
|
||||||
return " [진단] " + " · ".join(lines + [todo]) if lines else " [진단] " + todo
|
return "[진단] " + " · ".join(lines + [todo])
|
||||||
|
|
||||||
# ── 연결 테스트 · 가져오기 ─────────────────────────────
|
# ── 연결 테스트 · 가져오기 ─────────────────────────────
|
||||||
def test_connection(self, ctx: AdapterContext) -> str:
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
@@ -273,8 +273,11 @@ class MetaAdsSource(AdSource):
|
|||||||
info = self._get(ctx, client, f"{API_BASE}/{version}/act_{acc}",
|
info = self._get(ctx, client, f"{API_BASE}/{version}/act_{acc}",
|
||||||
{**auth, "fields": "name,currency,timezone_name,account_status"})
|
{**auth, "fields": "name,currency,timezone_name,account_status"})
|
||||||
except AuthFailed as exc: # 권한 오류(#200 등) — 메타에 토큰 정보를 물어 원인을 덧붙인다
|
except AuthFailed as exc: # 권한 오류(#200 등) — 메타에 토큰 정보를 물어 원인을 덧붙인다
|
||||||
base = str(exc).replace(_DIAG_HINT, "")
|
# 진단(고칠 곳)을 맨 앞에, 메타 원문은 짧게 뒤에 — 길면 화면·기록에서 뒤가 잘리므로(2026-10-16 "[진…" 잘림)
|
||||||
raise AuthFailed(base + self._diagnose(ctx, client, version, auth, accounts)) from None
|
original = str(exc).split(" — ")[0]
|
||||||
|
original = re.sub(r",?\s*refer to https?://\S+(?: for details)?", "", original)
|
||||||
|
raise AuthFailed(self._diagnose(ctx, client, version, auth, accounts)
|
||||||
|
+ f" (메타 원문: {original})") from None
|
||||||
cur = str(info.get("currency") or "?")
|
cur = str(info.get("currency") or "?")
|
||||||
not_krw = not_krw or cur != "KRW"
|
not_krw = not_krw or cur != "KRW"
|
||||||
status = _ACCOUNT_STATUS.get(info.get("account_status"), "")
|
status = _ACCOUNT_STATUS.get(info.get("account_status"), "")
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ from .security.redact import redact_text
|
|||||||
logger = logging.getLogger("performance.ad_sync")
|
logger = logging.getLogger("performance.ad_sync")
|
||||||
|
|
||||||
AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for)
|
AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for)
|
||||||
|
AD_MESSAGE_MAX = 1200 # 광고 연동 오류 문구 길이 한도(비밀값 가린 뒤)
|
||||||
_locks: dict[str, threading.Lock] = {}
|
_locks: dict[str, threading.Lock] = {}
|
||||||
_locks_guard = threading.Lock()
|
_locks_guard = threading.Lock()
|
||||||
|
|
||||||
@@ -57,7 +58,8 @@ class AdSyncService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def _message(exc: Exception, ctx: AdapterContext) -> str:
|
def _message(exc: Exception, ctx: AdapterContext) -> str:
|
||||||
known = getattr(ctx.credentials, "known_secrets", lambda: [])()
|
known = getattr(ctx.credentials, "known_secrets", lambda: [])()
|
||||||
return redact_text(str(getattr(exc, "message", "") or exc), known)
|
# 광고 연동 오류는 고칠 곳 안내·진단이 붙어 길다 — 기본 300자에서 자르면 안내가 잘린다(2026-10-16 메타 #200 진단)
|
||||||
|
return redact_text(str(getattr(exc, "message", "") or exc), known, max_len=AD_MESSAGE_MAX)
|
||||||
|
|
||||||
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
|
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
|
||||||
cleared: set[str] | None = None) -> dict[str, Any]:
|
cleared: set[str] | None = None) -> dict[str, Any]:
|
||||||
|
|||||||
@@ -304,3 +304,29 @@ def test_diag_hint_only_outside_connection_test(monkeypatch):
|
|||||||
assert ma._DIAG_HINT in str(info.value) and "[진단]" not in str(info.value)
|
assert ma._DIAG_HINT in str(info.value) and "[진단]" not in str(info.value)
|
||||||
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE)
|
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE)
|
||||||
assert ma._DIAG_HINT not in msg
|
assert ma._DIAG_HINT not in msg
|
||||||
|
|
||||||
|
|
||||||
|
def test_connection_test_shows_full_diagnosis_first(monkeypatch):
|
||||||
|
"""설정 [연결 테스트](AdSyncService) 문구 — 진단이 맨 앞, 잘리지 않음, 메타 원문의 긴 주소는 뺌(2026-10-16 "[진…" 잘림)."""
|
||||||
|
long_denied = {"error": {"code": 200, "message": "(#200) Ad account owner has NOT grant ads_management or ads_read permission, "
|
||||||
|
"refer to https://developers.facebook.com/docs/marketing-api/get-started/authorization/"
|
||||||
|
"#permissions-and-features for details"}}
|
||||||
|
|
||||||
|
def handler(req):
|
||||||
|
if req.url.path.endswith("/debug_token"):
|
||||||
|
return httpx.Response(200, json=_debug(["ads_read"]))
|
||||||
|
if req.url.path.endswith("/me/adaccounts"):
|
||||||
|
return httpx.Response(200, json={"data": []})
|
||||||
|
return httpx.Response(400, json=long_denied)
|
||||||
|
|
||||||
|
_install(monkeypatch, handler)
|
||||||
|
store = FakeStore()
|
||||||
|
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
|
||||||
|
svc._ctx = lambda code, values=None, user="", cleared=None: _ctx(account_ids="1111111111,2222222222")
|
||||||
|
res = svc.test_connection("meta")
|
||||||
|
msg = res["message"]
|
||||||
|
assert not res["ok"] and res["status"] == "auth_failed"
|
||||||
|
assert msg.startswith("[진단]") and not msg.endswith("…") and len(msg) > 300 # 예전 300자 한도면 잘렸을 길이
|
||||||
|
assert "배정되지 않은 계정: act_1111111111, act_2222222222" in msg and "자산 할당" in msg
|
||||||
|
assert "(메타 원문: 메타 API 오류(200): (#200) Ad account owner has NOT grant" in msg
|
||||||
|
assert "https://" not in msg and ma._DIAG_HINT not in msg and TOKEN not in msg
|
||||||
|
|||||||
@@ -416,6 +416,8 @@
|
|||||||
입력한 계정이 안 보임 → 시스템 사용자 [자산 할당]에서 광고 계정 배정 후 토큰 재발급 / 권한이 다른 계정에만 → 대상 포함해 재발급 /
|
입력한 계정이 안 보임 → 시스템 사용자 [자산 할당]에서 광고 계정 배정 후 토큰 재발급 / 권한이 다른 계정에만 → 대상 포함해 재발급 /
|
||||||
다 맞음 → 앱 쪽(비즈니스에 앱 연결·Marketing API 제품·제한 액세스면 토큰 주인이 앱 관리자·개발자인지). 진단 조회 실패는 무시(덧붙이는 정보).
|
다 맞음 → 앱 쪽(비즈니스에 앱 연결·Marketing API 제품·제한 액세스면 토큰 주인이 앱 관리자·개발자인지). 진단 조회 실패는 무시(덧붙이는 정보).
|
||||||
광고비 탭 불러오기에서 난 권한 오류엔 "[연결 테스트]가 원인을 진단" 안내를 붙인다(`_DIAG_HINT`).
|
광고비 탭 불러오기에서 난 권한 오류엔 "[연결 테스트]가 원인을 진단" 안내를 붙인다(`_DIAG_HINT`).
|
||||||
|
연결 테스트 문구는 **[진단]을 맨 앞에**, 메타 원문은 짧게(긴 안내 주소 뺌) 뒤에. 광고 연동 오류 문구 길이 한도는 `ad_sync.AD_MESSAGE_MAX`(1200자,
|
||||||
|
비밀값 가린 뒤) — 예전엔 공용 기본 300자에서 잘려 진단이 "[진…" 으로 끊겼다.
|
||||||
- **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도),
|
- **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도),
|
||||||
기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값.
|
기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값.
|
||||||
- **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일,
|
- **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일,
|
||||||
|
|||||||
Reference in New Issue
Block a user