Files
clean-architecture-backend-…/scripts/verify-httpclient-docs.py
T
DongHyeonka d904d680af fix(scripts): 검사 스크립트와 smoke wrapper의 빈틈을 닫고 자기 시험을 더한다
문제:
- README 「새 서비스로 시작하기」의 이름 바꾸기 명령(`git grep -l ... -- src
  scripts`)이 루트 build.gradle·build-logic의 group, config/spotbugs 목록, registry·
  API surface 스냅숏을 놓쳐, 따라 하면 qualityCheck와 surface 검사가 실패했다.
- check-repo-layout.py의 HISTORY_PREFIXES가 없는 폴더 셋(superpowers, evidence,
  study)을 담고 docs/history·docs/design을 빠뜨렸다. 검사 스크립트 머리말에 누가
  부르는지 없었고, check-repo-layout·check-review-index·verify-httpclient-docs에
  자기 시험이 없었다. check-docs.py docstring은 「검사 여섯」(여덟),
  check-work-docs.py는 lychee를 PR workflow라 했다(main).
- run-compose-runtime-smoke.sh가 lane마다 정적 계약 전체를 다시 돌려 nightly마다
  compose config를 수백 번 렌더링했다. handoff lane의 --force-recreate가 1단계
  재시작 수를 지웠고, ps가 빈 결과면 restarts.txt가 비어 재시작 검사가 통과했다.

고친 것:
- 이름 바꾸기 명령을 그 범위로 넓히고 build-logic 자기 패키지는 그대로 둬도
  된다고 적었다.
- HISTORY_PREFIXES를 지금 기록 폴더 넷으로, 머리말에 부르는 곳, docstring 숫자·
  workflow를 고쳤다. 자기 시험 셋을 더했다(scripts/tests 통과, 옛 목록이면
  HISTORY_PREFIXES 시험이 실패한다).
- smoke는 정적 계약을 실행마다 한 번(두 모드 공통) 돌린다. 재시작 수는
  record_restarts가 단계(phase1, final)를 붙여 쌓고, 살핀 컨테이너가 없거나
  inspect·기록이 실패하면 실패한다(호출이 `|| return 1`이라 함수 안 set -e가
  꺼진다).
- verify-httpclient-docs 자기 시험은 실제 트리 대조(release workflow의 검사)를 하지
  않고 누락 탐지만 본다. scripts/tests는 PR 단계에서 돈다.

Refs: RR9-04-04, RR9-04-17, RR9-04-18, RR9-04-26, RR9-04-27
2026-11-13 06:34:33 +09:00

138 lines
5.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Fail when the HTTP Client Platform's code and documentation have drifted.
Called by: the release workflow (`.gitea/workflows/release.yml`, job `httpclient-documentation`).
The design (§33 "Documentation") requires the support matrix, configuration reference, security
guide and runbook to match the code. Review cannot hold that line by itself, so
this verifier extracts the names that are part of the public contract -- stable exceptions, metric
names, configuration properties, startup violation codes, and transports -- and fails when one
exists in code but nowhere in the documentation.
It deliberately checks one direction only. A name documented but not yet implemented is a plan; a
name implemented but undocumented is a surprise for whoever is on call.
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
PLATFORM = REPO_ROOT / "src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient"
DOCS_DIR = REPO_ROOT / "docs/httpclient"
ENV_FIELD_MANIFEST = REPO_ROOT / "docs/httpclient/env-fields.yaml"
REQUIRED_DOCS = [
"support-matrix.md",
"configuration-reference.md",
"retry-and-ambiguity.md",
"security.md",
"streaming.md",
"operations.md",
"release-checklist.md",
"performance-baseline.md",
"repository-adaptation.md",
]
def read_docs() -> str:
return "\n".join(
(DOCS_DIR / name).read_text(encoding="utf-8") for name in REQUIRED_DOCS
)
def stable_exceptions() -> list[str]:
error_dir = PLATFORM / "api/error"
return sorted(
path.stem
for path in error_dir.glob("Http*Exception.java")
if path.stem != "HttpClientException"
)
def metric_names() -> list[str]:
source = (PLATFORM / "observation/HttpClientObservationNames.java").read_text(encoding="utf-8")
return sorted(set(re.findall(r'"(http\.client\.[a-z_.]+)"', source)))
def violation_codes() -> list[str]:
codes: set[str] = set()
for source_file in [
PLATFORM / "profile/ClientProfileValidator.java",
PLATFORM / "security/TlsPolicyValidator.java",
# The startup validator moved from app-bootstrap into the leaf; the old path made this
# script fail on a missing file before it checked anything.
PLATFORM / "autoconfigure/HttpClientStartupValidator.java",
]:
source = source_file.read_text(encoding="utf-8")
codes.update(re.findall(r'"([A-Z][A-Z0-9_]{4,})"', source))
return sorted(codes)
def configuration_properties() -> list[str]:
"""Every leaf property under `app.httpclient`, nested and dynamic blocks included.
Read from the environment-field manifest rather than from the record source. The manifest is
derived from `HttpClientPlatformSettings` and held to it in both directions by
`HttpClientPlatformEnvManifestTest`, so it cannot drift from the code; parsing the
record here a second time, with a regex, could only agree with it by luck. The previous version
of this function did exactly that and saw eighteen top-level names, which is why a nested pool,
timeout or TLS setting could be added and documented nowhere.
"""
names: set[str] = set()
for line in ENV_FIELD_MANIFEST.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if not stripped.startswith("- field:"):
continue
path = stripped[len("- field:") :].strip()
leaf = path.split(".")[-1]
# `clients[N]` and `allowed-hosts[M]` are documented by name, not by position.
names.add(re.sub(r"\[[NM]\]$", "", leaf))
return sorted(names)
def transports() -> list[str]:
source = (PLATFORM / "profile/TransportType.java").read_text(encoding="utf-8")
body = source[source.index("public enum TransportType") :]
return sorted(set(re.findall(r"^\s{2}([A-Z][A-Z_]*),?$", body, flags=re.MULTILINE)))
def main() -> int:
missing_docs = [name for name in REQUIRED_DOCS if not (DOCS_DIR / name).is_file()]
if missing_docs:
print("FAIL missing documentation file(s): " + ", ".join(missing_docs))
return 1
documentation = read_docs()
failures: list[str] = []
checks = {
"stable exception": stable_exceptions(),
"metric": metric_names(),
"startup violation code": violation_codes(),
"configuration property": configuration_properties(),
"transport": transports(),
}
for kind, names in checks.items():
for name in names:
if name not in documentation:
failures.append(f"{kind} '{name}' exists in code but is not documented")
if failures:
print(f"FAIL httpclient documentation drift ({len(failures)} finding(s)):")
for failure in failures:
print(" - " + failure)
return 1
total = sum(len(names) for names in checks.values())
print(f"PASS httpclient documentation covers {total} code-derived name(s):")
for kind, names in checks.items():
print(f" {kind}: {len(names)}")
return 0
if __name__ == "__main__":
sys.exit(main())