pr-proof 0.0.0-stage → 0.1.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/Procfile +2 -0
- package/README.md +300 -2
- package/app/__init__.py +1 -0
- package/app/api/__init__.py +1 -0
- package/app/api/cli.py +35 -0
- package/app/api/github.py +168 -0
- package/app/api/history.py +123 -0
- package/app/api/main.py +95 -0
- package/app/api/queue.py +45 -0
- package/app/api/responses.py +28 -0
- package/app/api/signature.py +19 -0
- package/app/api/sync.py +189 -0
- package/app/api/sync_rules_pure.py +71 -0
- package/app/api/webhook.py +172 -0
- package/app/setup/__init__.py +4 -0
- package/app/setup/cli.py +90 -0
- package/app/setup/configure.py +735 -0
- package/app/setup/files.py +104 -0
- package/app/setup/github_setup.py +153 -0
- package/app/setup/install_hints.json +32 -0
- package/app/setup/setup_pure.py +344 -0
- package/app/setup/start.py +113 -0
- package/app/shared/__init__.py +1 -0
- package/app/shared/comment_pure.py +29 -0
- package/app/shared/config.py +106 -0
- package/app/shared/db_pure.py +339 -0
- package/app/shared/embed_models_pure.py +55 -0
- package/app/shared/feedback_pure.py +84 -0
- package/app/shared/github_auth.py +74 -0
- package/app/shared/job_pure.py +43 -0
- package/app/shared/notify.py +97 -0
- package/app/shared/ops_alert_pure.py +38 -0
- package/app/shared/state_keys_pure.py +24 -0
- package/app/shared/version.py +27 -0
- package/app/worker/__init__.py +1 -0
- package/app/worker/access_pure.py +180 -0
- package/app/worker/ai/__init__.py +1 -0
- package/app/worker/ai/claude_cli.py +684 -0
- package/app/worker/ai/mcp_relay.py +42 -0
- package/app/worker/ai/path_hook.py +103 -0
- package/app/worker/ai/tool_server.py +139 -0
- package/app/worker/ai/workdir.py +333 -0
- package/app/worker/base_config.py +173 -0
- package/app/worker/budget.py +100 -0
- package/app/worker/cache_key_pure.py +34 -0
- package/app/worker/call_budget_pure.py +132 -0
- package/app/worker/checker_authoring_pure.py +599 -0
- package/app/worker/checker_pure.py +196 -0
- package/app/worker/cli.py +97 -0
- package/app/worker/command.py +191 -0
- package/app/worker/command_pure.py +38 -0
- package/app/worker/coverage.py +123 -0
- package/app/worker/coverage_pure.py +202 -0
- package/app/worker/deps.py +22 -0
- package/app/worker/diff_pure.py +419 -0
- package/app/worker/doc_rules_pure.py +201 -0
- package/app/worker/doc_rules_report.py +979 -0
- package/app/worker/eval_run_pure.py +241 -0
- package/app/worker/evaluation.py +151 -0
- package/app/worker/feedback.py +448 -0
- package/app/worker/feedback_pure.py +131 -0
- package/app/worker/feedback_report_pure.py +90 -0
- package/app/worker/feedback_triage.py +85 -0
- package/app/worker/feedback_triage_pure.py +363 -0
- package/app/worker/fix/__init__.py +1 -0
- package/app/worker/fix/decide.py +197 -0
- package/app/worker/fix/feedback_fix_pure.py +125 -0
- package/app/worker/fix/fix_decision_pure.py +386 -0
- package/app/worker/fix/fix_pure.py +70 -0
- package/app/worker/fix/mechanical_fix.py +214 -0
- package/app/worker/fix/model_fix.py +575 -0
- package/app/worker/fix/model_fix_pure.py +593 -0
- package/app/worker/fix/proposal.py +584 -0
- package/app/worker/fix/proposal_pure.py +103 -0
- package/app/worker/fix/scope.py +40 -0
- package/app/worker/fix/scope_pure.py +222 -0
- package/app/worker/generated_tests_pure.py +442 -0
- package/app/worker/github.py +471 -0
- package/app/worker/graph.py +963 -0
- package/app/worker/guard.py +91 -0
- package/app/worker/lang/__init__.py +0 -0
- package/app/worker/lang/install_pure.py +25 -0
- package/app/worker/lang/python.py +862 -0
- package/app/worker/loop.py +200 -0
- package/app/worker/main.py +76 -0
- package/app/worker/markdown_pure.py +29 -0
- package/app/worker/mcp_pure.py +150 -0
- package/app/worker/memory.py +503 -0
- package/app/worker/merged_fix_pure.py +236 -0
- package/app/worker/pr_check_report_pure.py +201 -0
- package/app/worker/pr_description_report_pure.py +112 -0
- package/app/worker/preflight.py +125 -0
- package/app/worker/rag_pure.py +285 -0
- package/app/worker/rag_switch_pure.py +203 -0
- package/app/worker/records.py +207 -0
- package/app/worker/records_pure.py +239 -0
- package/app/worker/repo.py +588 -0
- package/app/worker/repo_config_pure.py +269 -0
- package/app/worker/report.py +300 -0
- package/app/worker/retry.py +65 -0
- package/app/worker/rule_pure.py +223 -0
- package/app/worker/rule_reading_pure.py +503 -0
- package/app/worker/rules/__init__.py +1 -0
- package/app/worker/rules/checkers.py +615 -0
- package/app/worker/rules/detect.py +154 -0
- package/app/worker/rules/doc_rules.py +301 -0
- package/app/worker/rules/doc_sections_pure.py +168 -0
- package/app/worker/rules/judge.py +410 -0
- package/app/worker/rules/judge_pure.py +627 -0
- package/app/worker/rules/pr_check.py +404 -0
- package/app/worker/rules/pr_check_pure.py +922 -0
- package/app/worker/rules/pr_description.py +218 -0
- package/app/worker/rules/pr_description_pure.py +743 -0
- package/app/worker/rules/rules.py +314 -0
- package/app/worker/rules/run_check.py +95 -0
- package/app/worker/rules/run_check_pure.py +219 -0
- package/app/worker/rules/tool_choice_pure.py +135 -0
- package/app/worker/sandbox/__init__.py +1 -0
- package/app/worker/sandbox/checker_runner.py +412 -0
- package/app/worker/sandbox/container.py +130 -0
- package/app/worker/sandbox/docker_cli.py +170 -0
- package/app/worker/sandbox/safe_read.py +32 -0
- package/app/worker/sandbox/toolcache.py +425 -0
- package/app/worker/state.py +602 -0
- package/app/worker/test_lines.py +77 -0
- package/app/worker/test_run_pure.py +133 -0
- package/app/worker/text_edit_pure.py +66 -0
- package/app/worker/tools_pure.py +152 -0
- package/app/worker/update.py +305 -0
- package/app/worker/violation_pure.py +33 -0
- package/bin/pr-proof.js +173 -0
- package/docker/sandbox/Dockerfile +12 -0
- package/docker/sandbox/coveragerc +19 -0
- package/docker-compose.yml +5 -0
- package/package.json +31 -4
- package/pyproject.toml +60 -0
package/app/api/main.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""진입점: FastAPI 앱. `uvicorn app.api.main:app --port 8765`.
|
|
2
|
+
|
|
3
|
+
웹훅을 받고, 같은 프로세스에서 동기화 루프를 주기적으로 돌린다 (docs/DESIGN.md F2).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
import contextlib
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
11
|
+
from contextlib import asynccontextmanager
|
|
12
|
+
|
|
13
|
+
from fastapi import FastAPI, Request
|
|
14
|
+
from fastapi.responses import JSONResponse
|
|
15
|
+
from redis import Redis
|
|
16
|
+
from redis.exceptions import RedisError
|
|
17
|
+
|
|
18
|
+
from app.api import sync, webhook
|
|
19
|
+
from app.api.history import History
|
|
20
|
+
from app.shared import config
|
|
21
|
+
from app.shared.ops_alert_pure import Kind
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
async def sync_loop(
|
|
27
|
+
settings: config.PipelineConfig,
|
|
28
|
+
redis: Redis,
|
|
29
|
+
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
|
30
|
+
) -> None:
|
|
31
|
+
"""시작할 때 한 번, 이후 interval_minutes마다 동기화한다. gh 호출은 스레드에서 돌려
|
|
32
|
+
웹훅 응답을 막지 않는다. 한 번 실패해도 루프는 계속 돈다. 두 주기 연속으로 gh 로그인이나
|
|
33
|
+
Redis가 실패하면 macOS 알림을 띄운다 (6-4)."""
|
|
34
|
+
history = History(settings.db_path)
|
|
35
|
+
failing: frozenset[Kind] = frozenset()
|
|
36
|
+
while True:
|
|
37
|
+
current: frozenset[Kind] = frozenset()
|
|
38
|
+
try:
|
|
39
|
+
result = await asyncio.to_thread(sync.run_once, settings, redis, history)
|
|
40
|
+
current = result.environment
|
|
41
|
+
if result.enqueued:
|
|
42
|
+
log.info("동기화로 등록: %s", result.enqueued)
|
|
43
|
+
except RedisError:
|
|
44
|
+
log.exception("동기화 실패: Redis")
|
|
45
|
+
current = frozenset({"redis"})
|
|
46
|
+
except Exception: # 루프가 죽으면 동기화가 조용히 멈춘다
|
|
47
|
+
log.exception("동기화 실패")
|
|
48
|
+
sync.alert_lasting(failing, current, settings.data_dir)
|
|
49
|
+
failing = current
|
|
50
|
+
await sleep(settings.sync.interval_minutes * 60)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@asynccontextmanager
|
|
54
|
+
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
55
|
+
settings = config.load_config()
|
|
56
|
+
app.state.secret = config.read_secret(config.WEBHOOK_SECRET)
|
|
57
|
+
app.state.allowed_repos = frozenset(settings.repos)
|
|
58
|
+
app.state.redis = Redis.from_url(settings.redis_url)
|
|
59
|
+
task = None
|
|
60
|
+
if settings.sync.interval_minutes > 0:
|
|
61
|
+
task = asyncio.create_task(sync_loop(settings, app.state.redis))
|
|
62
|
+
yield
|
|
63
|
+
if task is not None:
|
|
64
|
+
task.cancel()
|
|
65
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
66
|
+
await task
|
|
67
|
+
app.state.redis.close()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
app = FastAPI(lifespan=lifespan)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@app.get("/healthz")
|
|
74
|
+
def healthz() -> dict[str, str]:
|
|
75
|
+
return {"status": "ok"}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@app.post("/webhook/github")
|
|
79
|
+
async def github_webhook(request: Request) -> JSONResponse:
|
|
80
|
+
body = await request.body()
|
|
81
|
+
try:
|
|
82
|
+
payload = json.loads(body) if body else {}
|
|
83
|
+
except json.JSONDecodeError:
|
|
84
|
+
payload = {}
|
|
85
|
+
result = webhook.handle(
|
|
86
|
+
body=body,
|
|
87
|
+
payload=payload,
|
|
88
|
+
event=request.headers.get("X-GitHub-Event"),
|
|
89
|
+
delivery_id=request.headers.get("X-GitHub-Delivery"),
|
|
90
|
+
signature_header=request.headers.get("X-Hub-Signature-256"),
|
|
91
|
+
secret=request.app.state.secret,
|
|
92
|
+
allowed_repos=request.app.state.allowed_repos,
|
|
93
|
+
redis=request.app.state.redis,
|
|
94
|
+
)
|
|
95
|
+
return JSONResponse(result.body, status_code=result.status_code)
|
package/app/api/queue.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""작업 등록: 최신 head 기록, delivery·작업 키 중복 방지, RQ 큐 등록."""
|
|
2
|
+
|
|
3
|
+
from typing import Final, Literal
|
|
4
|
+
|
|
5
|
+
from redis import Redis
|
|
6
|
+
from rq import Queue, Retry
|
|
7
|
+
|
|
8
|
+
from app.shared import state_keys_pure
|
|
9
|
+
from app.shared.job_pure import PRJob
|
|
10
|
+
|
|
11
|
+
WORKER_FUNCTION: Final = "app.worker.main.handle"
|
|
12
|
+
# 환경 오류는 워커가 예외를 올려 이 간격으로 다시 시도한다. 상한이 있어 무한 반복하지 않는다
|
|
13
|
+
RETRY_INTERVALS: Final = (60, 300, 900)
|
|
14
|
+
JOB_TIMEOUT_SECONDS: Final = 30 * 60
|
|
15
|
+
|
|
16
|
+
EnqueueResult = Literal["queued", "duplicate"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def seen_delivery(redis: Redis, delivery_id: str) -> bool:
|
|
20
|
+
"""이미 받은 delivery면 True. 처음이면 기록하고 False."""
|
|
21
|
+
key = state_keys_pure.delivery(delivery_id)
|
|
22
|
+
return not redis.set(key, "1", nx=True, ex=state_keys_pure.DELIVERY_TTL_SECONDS)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def clear_job(redis: Redis, job: PRJob) -> None:
|
|
26
|
+
"""죽은 워커가 남긴 작업 키를 지운다. 동기화가 생존 확인이 끊긴 작업을 다시 넣을 때 쓴다."""
|
|
27
|
+
redis.delete(state_keys_pure.job(job.dedup_key))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def enqueue(redis: Redis, job: PRJob) -> EnqueueResult:
|
|
31
|
+
"""작업을 큐에 넣는다. 같은 작업이 대기·실행 중이면 넣지 않는다."""
|
|
32
|
+
if job.kind == "update" and job.head_sha:
|
|
33
|
+
# 낡은 작업 확인용. 같은 작업이 이미 있어도 최신 head는 갱신한다
|
|
34
|
+
redis.set(state_keys_pure.latest_head(job.repo, job.pr_number), job.head_sha)
|
|
35
|
+
if not redis.set(
|
|
36
|
+
state_keys_pure.job(job.dedup_key), "1", nx=True, ex=state_keys_pure.JOB_TTL_SECONDS
|
|
37
|
+
):
|
|
38
|
+
return "duplicate"
|
|
39
|
+
Queue(state_keys_pure.QUEUE_NAME, connection=redis).enqueue(
|
|
40
|
+
WORKER_FUNCTION,
|
|
41
|
+
job.model_dump_json(),
|
|
42
|
+
retry=Retry(max=len(RETRY_INTERVALS), interval=list(RETRY_INTERVALS)),
|
|
43
|
+
job_timeout=JOB_TIMEOUT_SECONDS,
|
|
44
|
+
)
|
|
45
|
+
return "queued"
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""웹훅 응답. GitHub에는 처리 결과와 무관하게 빨리 응답한다 (서명 실패만 401)."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from app.shared.job_pure import PRJob
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class WebhookResponse:
|
|
11
|
+
status_code: int
|
|
12
|
+
body: dict[str, Any] = field(default_factory=dict)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def unauthorized() -> WebhookResponse:
|
|
16
|
+
return WebhookResponse(401, {"status": "invalid_signature"})
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def duplicate_delivery() -> WebhookResponse:
|
|
20
|
+
return WebhookResponse(202, {"status": "duplicate_delivery"})
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def ignored(reason: str) -> WebhookResponse:
|
|
24
|
+
return WebhookResponse(202, {"status": "ignored", "reason": reason})
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def accepted(job: PRJob, result: str) -> WebhookResponse:
|
|
28
|
+
return WebhookResponse(202, {"status": result, "job": job.dedup_key})
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""GitHub 웹훅 서명 검증 (X-Hub-Signature-256)."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
from typing import Final
|
|
6
|
+
|
|
7
|
+
PREFIX: Final = "sha256="
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def verify(secret: str, body: bytes, header: str | None) -> bool:
|
|
11
|
+
if not header or not header.startswith(PREFIX):
|
|
12
|
+
return False
|
|
13
|
+
expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
|
|
14
|
+
return hmac.compare_digest(expected, header.removeprefix(PREFIX))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def sign(secret: str, body: bytes) -> str:
|
|
18
|
+
"""테스트와 수동 재전송용 서명."""
|
|
19
|
+
return PREFIX + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
|
package/app/api/sync.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""동기화 한 번: 열린 PR의 head ↔ 처리 기록 비교 → 빠진 것만 PRJob → 큐 (docs/DESIGN.md F2).
|
|
2
|
+
|
|
3
|
+
웹훅을 놓쳤을 때(로컬 서버가 꺼져 있던 동안 등) 보충한다. 다시 넣을지는 sync_rules_pure가 정한다.
|
|
4
|
+
놓친 명령은 현재 head 커밋 뒤에 달린 것 중 워커가 처리하지 않은 것만 넣는다. 권한 확인은
|
|
5
|
+
웹훅과 같은 함수(app/shared/comment_pure.command_in_comment)로 한다.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from datetime import UTC, datetime, timedelta
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from redis import Redis
|
|
15
|
+
|
|
16
|
+
from app.api import github, queue
|
|
17
|
+
from app.api.history import History
|
|
18
|
+
from app.api.sync_rules_pure import EnqueueReason, enqueue_reason
|
|
19
|
+
from app.api.webhook import PIPELINE_BRANCH_PREFIX
|
|
20
|
+
from app.shared import github_auth, version
|
|
21
|
+
from app.shared import notify as macos
|
|
22
|
+
from app.shared.comment_pure import command_in_comment
|
|
23
|
+
from app.shared.config import PipelineConfig
|
|
24
|
+
from app.shared.feedback_pure import feedback_in_comment
|
|
25
|
+
from app.shared.job_pure import PRJob
|
|
26
|
+
from app.shared.ops_alert_pure import Kind
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class SyncResult:
|
|
33
|
+
enqueued: list[tuple[str, int, EnqueueReason | str]] = field(default_factory=list)
|
|
34
|
+
failed_repos: list[str] = field(default_factory=list)
|
|
35
|
+
# 사람이 해야 풀리는 환경 오류로 보이는 것. 조회가 실패했고 `gh auth status`도 실패하면 gh_login
|
|
36
|
+
# (토큰 방식이면 gh_token)
|
|
37
|
+
environment: frozenset[Kind] = frozenset()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def run_once(
|
|
41
|
+
settings: PipelineConfig,
|
|
42
|
+
redis: Redis,
|
|
43
|
+
history: History,
|
|
44
|
+
*,
|
|
45
|
+
list_prs: Callable[[str], list[github.OpenPR]] = github.list_open_prs,
|
|
46
|
+
head_time: Callable[[str, str], str] = github.head_commit_time,
|
|
47
|
+
list_comments: Callable[[str, int, str], list[github.PRComment]] = github.list_comments_since,
|
|
48
|
+
list_feedback: Callable[[str, int], list[github.FeedbackItem]] = github.list_feedback,
|
|
49
|
+
auth_ok: Callable[[], bool] = github.auth_ok,
|
|
50
|
+
auth_kind: Callable[[], Kind] = github_auth.alert_kind,
|
|
51
|
+
now: datetime | None = None,
|
|
52
|
+
pipeline_commit: str | None = None,
|
|
53
|
+
) -> SyncResult:
|
|
54
|
+
now = now or datetime.now(UTC)
|
|
55
|
+
if pipeline_commit is None:
|
|
56
|
+
pipeline_commit = version.current()
|
|
57
|
+
backoff = timedelta(minutes=settings.sync.env_error_backoff_minutes)
|
|
58
|
+
heartbeat_timeout = timedelta(minutes=settings.sync.heartbeat_timeout_minutes)
|
|
59
|
+
result = SyncResult()
|
|
60
|
+
for repo in settings.repos:
|
|
61
|
+
try:
|
|
62
|
+
prs = list_prs(repo)
|
|
63
|
+
except github.GitHubReadError as e:
|
|
64
|
+
log.warning("동기화: %s 조회 실패, 다음 주기에 다시 한다: %s", repo, e)
|
|
65
|
+
result.failed_repos.append(repo)
|
|
66
|
+
continue
|
|
67
|
+
open_numbers = {pr.number for pr in prs}
|
|
68
|
+
for number in sorted(history.prs_with_open_proposals(repo) - open_numbers):
|
|
69
|
+
# 원본 PR이 닫혔는데 close 웹훅을 놓쳤다. 워커가 남은 제안 PR을 닫는다
|
|
70
|
+
job = PRJob(repo=repo, pr_number=number, kind="close", source="sync")
|
|
71
|
+
if queue.enqueue(redis, job) == "queued":
|
|
72
|
+
result.enqueued.append((repo, number, "closed_pr"))
|
|
73
|
+
# 받아들인 코멘트의 수정안이 머지됐는데 웹훅을 놓쳤다. 원래 PR이 이미 닫혔어도 넣는다
|
|
74
|
+
# (수정안을 머지한 뒤 원래 PR도 머지됐을 수 있다). 머지됐는지는 워커가 GitHub에서 본다
|
|
75
|
+
for number in sorted(history.prs_awaiting_resolve(repo)):
|
|
76
|
+
job = PRJob(repo=repo, pr_number=number, kind="resolve", source="sync")
|
|
77
|
+
if queue.enqueue(redis, job) == "queued":
|
|
78
|
+
result.enqueued.append((repo, number, "awaiting_resolve"))
|
|
79
|
+
for pr in prs:
|
|
80
|
+
if pr.head_ref.startswith(PIPELINE_BRANCH_PREFIX):
|
|
81
|
+
continue
|
|
82
|
+
try:
|
|
83
|
+
_missed_commands(repo, pr, redis, history, result, head_time, list_comments)
|
|
84
|
+
except github.GitHubReadError as e:
|
|
85
|
+
log.warning("동기화: %s#%s 명령 조회 실패: %s", repo, pr.number, e)
|
|
86
|
+
runs = history.runs_for(repo, pr.number, pr.head_sha)
|
|
87
|
+
# 승인을 기다리는 외부 작성자의 PR은 코멘트도 처리하지 않는다. 넣으면 주기마다
|
|
88
|
+
# 승인 안내를 다시 달고 blocked 기록이 쌓인다 (8.6)
|
|
89
|
+
if not (runs and runs[-1].state == "blocked"):
|
|
90
|
+
try:
|
|
91
|
+
_unhandled_feedback(repo, pr, redis, history, result, list_feedback)
|
|
92
|
+
except github.GitHubReadError as e:
|
|
93
|
+
log.warning("동기화: %s#%s 코멘트 조회 실패: %s", repo, pr.number, e)
|
|
94
|
+
reason = enqueue_reason(
|
|
95
|
+
runs, now, env_error_backoff=backoff, heartbeat_timeout=heartbeat_timeout,
|
|
96
|
+
pipeline_commit=pipeline_commit,
|
|
97
|
+
) # fmt: skip
|
|
98
|
+
if reason is None:
|
|
99
|
+
continue
|
|
100
|
+
job = PRJob(
|
|
101
|
+
repo=repo,
|
|
102
|
+
pr_number=pr.number,
|
|
103
|
+
kind="update",
|
|
104
|
+
head_sha=pr.head_sha,
|
|
105
|
+
base_sha=pr.base_sha,
|
|
106
|
+
source="sync",
|
|
107
|
+
author_login=pr.author_login or None,
|
|
108
|
+
)
|
|
109
|
+
if reason == "dead_worker":
|
|
110
|
+
queue.clear_job(redis, job)
|
|
111
|
+
if queue.enqueue(redis, job) == "queued":
|
|
112
|
+
result.enqueued.append((repo, pr.number, reason))
|
|
113
|
+
if result.failed_repos and not auth_ok():
|
|
114
|
+
result.environment = frozenset({auth_kind()})
|
|
115
|
+
return result
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def alert_lasting(previous: frozenset[Kind], current: frozenset[Kind], data_dir: Path) -> None:
|
|
119
|
+
"""동기화가 두 주기 연속으로 본 환경 오류만 알린다. 한 번의 네트워크 끊김은 다음 주기에 풀리고,
|
|
120
|
+
워커의 재시도에 해당하는 것이 동기화에는 다음 주기뿐이다. 같은 종류는 30분에 한 번이다."""
|
|
121
|
+
for kind in sorted(previous & current):
|
|
122
|
+
macos.send(kind, data_dir)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _missed_commands(
|
|
126
|
+
repo: str,
|
|
127
|
+
pr: github.OpenPR,
|
|
128
|
+
redis: Redis,
|
|
129
|
+
history: History,
|
|
130
|
+
result: SyncResult,
|
|
131
|
+
head_time: Callable[[str, str], str],
|
|
132
|
+
list_comments: Callable[[str, int, str], list[github.PRComment]],
|
|
133
|
+
) -> None:
|
|
134
|
+
"""현재 head 뒤에 달린, 아직 처리하지 않은 명령을 넣는다.
|
|
135
|
+
|
|
136
|
+
이전 커밋에 단 /fix를 뒤늦게 실행하지 않는다.
|
|
137
|
+
"""
|
|
138
|
+
since = head_time(repo, pr.head_sha)
|
|
139
|
+
handled = history.handled_command_ids(repo, pr.number)
|
|
140
|
+
for comment in list_comments(repo, pr.number, since):
|
|
141
|
+
command, _ = command_in_comment(comment.body, comment.author_association)
|
|
142
|
+
if command is None or comment.id in handled:
|
|
143
|
+
continue
|
|
144
|
+
job = PRJob(
|
|
145
|
+
repo=repo,
|
|
146
|
+
pr_number=pr.number,
|
|
147
|
+
kind="command",
|
|
148
|
+
command=command,
|
|
149
|
+
comment_id=comment.id,
|
|
150
|
+
source="sync",
|
|
151
|
+
author_login=pr.author_login or None,
|
|
152
|
+
commenter_association=comment.author_association or None,
|
|
153
|
+
commenter_login=comment.login or None,
|
|
154
|
+
)
|
|
155
|
+
if queue.enqueue(redis, job) == "queued":
|
|
156
|
+
result.enqueued.append((repo, pr.number, "missed_command"))
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _unhandled_feedback(
|
|
160
|
+
repo: str,
|
|
161
|
+
pr: github.OpenPR,
|
|
162
|
+
redis: Redis,
|
|
163
|
+
history: History,
|
|
164
|
+
result: SyncResult,
|
|
165
|
+
list_feedback: Callable[[str, int], list[github.FeedbackItem]],
|
|
166
|
+
) -> None:
|
|
167
|
+
"""다룰 코멘트 중 워커가 처리하지 않은 것이 하나라도 있으면 PR마다 feedback 작업 하나를 넣는다.
|
|
168
|
+
|
|
169
|
+
어떤 코멘트인지는 싣지 않는다(워커가 GitHub에서 읽는다). 웹훅이 오지 않았거나 이 기능이 생기기
|
|
170
|
+
전에 달린 코멘트도 여기서 걸리므로 `/recheck`가 필요 없다. 거르는 규칙은 웹훅과 같은 함수다.
|
|
171
|
+
"""
|
|
172
|
+
handled = history.handled_feedback_keys(repo, pr.number, pr.head_sha)
|
|
173
|
+
for item in list_feedback(repo, pr.number):
|
|
174
|
+
if (item.kind, item.id) in handled:
|
|
175
|
+
continue
|
|
176
|
+
if not feedback_in_comment(item.body, item.author_association, item.login)[0]:
|
|
177
|
+
continue
|
|
178
|
+
job = PRJob(
|
|
179
|
+
repo=repo,
|
|
180
|
+
pr_number=pr.number,
|
|
181
|
+
kind="feedback",
|
|
182
|
+
head_sha=pr.head_sha,
|
|
183
|
+
base_sha=pr.base_sha,
|
|
184
|
+
source="sync",
|
|
185
|
+
author_login=pr.author_login or None,
|
|
186
|
+
)
|
|
187
|
+
if queue.enqueue(redis, job) == "queued":
|
|
188
|
+
result.enqueued.append((repo, pr.number, "unhandled_feedback"))
|
|
189
|
+
return
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""동기화가 같은 head를 다시 넣을지 정하는 규칙 (docs/DESIGN.md F2 "끝난 상태별 재등록 규칙").
|
|
2
|
+
|
|
3
|
+
재시도 횟수는 작업 하나 안에서만 세므로, 동기화가 runs의 끝난 상태를 보고 다시 넣을지 정해야
|
|
4
|
+
환경 오류가 끝없이 반복되지 않는다.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from datetime import UTC, datetime, timedelta
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
EnqueueReason = Literal[
|
|
13
|
+
"no_record", "env_error_backoff", "dead_worker", "cancelled", "new_pipeline"
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class RunSnapshot:
|
|
19
|
+
state: str # app/shared/db_pure.RunState
|
|
20
|
+
heartbeat_at: datetime
|
|
21
|
+
finished_at: datetime | None
|
|
22
|
+
pipeline_commit: str | None = None # 그 검사를 돌린 파이프라인 코드의 커밋. 옛 기록은 None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _utc(value: datetime) -> datetime:
|
|
26
|
+
"""SQLite는 시간대를 저장하지 않으므로 시간대 없는 값은 UTC로 본다."""
|
|
27
|
+
return value if value.tzinfo else value.replace(tzinfo=UTC)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def enqueue_reason(
|
|
31
|
+
runs: Sequence[RunSnapshot],
|
|
32
|
+
now: datetime,
|
|
33
|
+
*,
|
|
34
|
+
env_error_backoff: timedelta,
|
|
35
|
+
heartbeat_timeout: timedelta,
|
|
36
|
+
pipeline_commit: str = "",
|
|
37
|
+
) -> EnqueueReason | None:
|
|
38
|
+
"""같은 PR·head의 runs(오래된 것부터)를 보고, 다시 넣을 이유를 돌려준다. 넣지 않으면 None.
|
|
39
|
+
|
|
40
|
+
pipeline_commit은 지금 도는 파이프라인 코드의 커밋이다. 끝난 결과(done, error)가 모두 다른
|
|
41
|
+
커밋의 코드가 낸 것이면 `/recheck` 없이 다시 검사한다(배포 뒤 열린 PR의 결과가 옛 코드의 것으로
|
|
42
|
+
남지 않게). 커밋을 모르면(빈 문자열) 이 규칙을 쓰지 않는다. 지금 코드로 한 번 끝나면 그 기록이
|
|
43
|
+
남아 다시 넣지 않는다.
|
|
44
|
+
"""
|
|
45
|
+
if not runs:
|
|
46
|
+
return "no_record"
|
|
47
|
+
last = runs[-1]
|
|
48
|
+
settled = [run for run in runs if run.state in ("done", "error")]
|
|
49
|
+
by_old_code = bool(pipeline_commit) and all(
|
|
50
|
+
run.pipeline_commit != pipeline_commit for run in settled
|
|
51
|
+
)
|
|
52
|
+
stale = bool(settled) and by_old_code # 끝난 결과가 있지만 모두 옛 코드의 것이다
|
|
53
|
+
if stale and last.state in ("done", "error"):
|
|
54
|
+
return "new_pipeline"
|
|
55
|
+
if not stale and any(run.state == "done" for run in runs):
|
|
56
|
+
return None # 결과가 이미 있다. 새 커밋이 올 때만 검사한다
|
|
57
|
+
if last.state == "blocked":
|
|
58
|
+
# 신뢰되지 않은 작성자의 PR이라 승인을 기다린다 (8.6). 승인(`/recheck <커밋>`)이나 새 커밋이
|
|
59
|
+
# 와야 다시 검사한다. 주기마다 다시 넣지 않는다
|
|
60
|
+
return None
|
|
61
|
+
if last.state == "error":
|
|
62
|
+
# 파이프라인 버그나 시간 초과는 같은 커밋으로 다시 돌려도 같은 결과다. 새 커밋 때만 검사한다
|
|
63
|
+
return None
|
|
64
|
+
if last.state == "env_error":
|
|
65
|
+
finished = _utc(last.finished_at or last.heartbeat_at)
|
|
66
|
+
return "env_error_backoff" if now - finished >= env_error_backoff else None
|
|
67
|
+
if last.state == "running":
|
|
68
|
+
return "dead_worker" if now - _utc(last.heartbeat_at) >= heartbeat_timeout else None
|
|
69
|
+
if last.state == "cancelled":
|
|
70
|
+
return "cancelled" # 이 head가 다시 최신인데 결과가 없다
|
|
71
|
+
return None
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""웹훅 한 건: 서명 검증 → 이벤트 해석 → 중복 제거 → 큐 등록 (docs/DESIGN.md F1)."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, Final
|
|
5
|
+
|
|
6
|
+
from redis import Redis
|
|
7
|
+
|
|
8
|
+
from app.api import queue, responses, signature
|
|
9
|
+
from app.shared.comment_pure import command_in_comment
|
|
10
|
+
from app.shared.feedback_pure import feedback_in_comment, fix_branch_pr
|
|
11
|
+
from app.shared.job_pure import PRJob
|
|
12
|
+
|
|
13
|
+
UPDATE_ACTIONS: Final = frozenset({"opened", "reopened", "synchronize", "ready_for_review"})
|
|
14
|
+
PIPELINE_BRANCH_PREFIX: Final = "pipeline/"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Ignored:
|
|
19
|
+
reason: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def parse_event(
|
|
23
|
+
event: str, payload: dict[str, Any], delivery_id: str | None, allowed_repos: frozenset[str]
|
|
24
|
+
) -> PRJob | Ignored:
|
|
25
|
+
"""GitHub 이벤트를 작업으로 바꾼다. 처리하지 않을 이벤트는 Ignored와 이유를 돌려준다."""
|
|
26
|
+
sent = (payload.get("repository") or {}).get("full_name")
|
|
27
|
+
# GitHub의 계정·저장소 이름은 대소문자를 가리지 않는다. 설정에 다른 대소문자로 적혀 있어도 같은
|
|
28
|
+
# 저장소이고, 작업에는 설정에 적힌 철자를 쓴다(동기화가 만드는 작업과 같은 이름이 되게)
|
|
29
|
+
repo = next(
|
|
30
|
+
(r for r in allowed_repos if isinstance(sent, str) and r.casefold() == sent.casefold()),
|
|
31
|
+
None,
|
|
32
|
+
)
|
|
33
|
+
if repo is None:
|
|
34
|
+
return Ignored(f"허용 목록에 없는 리포: {sent}")
|
|
35
|
+
action = payload.get("action")
|
|
36
|
+
|
|
37
|
+
if event == "pull_request":
|
|
38
|
+
pr = payload["pull_request"]
|
|
39
|
+
ref = pr["head"]["ref"]
|
|
40
|
+
if ref.startswith(PIPELINE_BRANCH_PREFIX):
|
|
41
|
+
# 머지된 수정안만 원래 PR의 스레드를 해결하는 작업이 된다. 해결은 워커가 한다
|
|
42
|
+
original = fix_branch_pr(ref)
|
|
43
|
+
if action == "closed" and pr.get("merged") and original is not None:
|
|
44
|
+
return PRJob(
|
|
45
|
+
repo=repo, pr_number=original, kind="resolve", source="webhook",
|
|
46
|
+
delivery_id=delivery_id,
|
|
47
|
+
) # fmt: skip
|
|
48
|
+
return Ignored("파이프라인 제안 PR")
|
|
49
|
+
if action in UPDATE_ACTIONS:
|
|
50
|
+
kind = "update"
|
|
51
|
+
elif action == "closed":
|
|
52
|
+
kind = "close"
|
|
53
|
+
else:
|
|
54
|
+
return Ignored(f"처리하지 않는 동작: pull_request.{action}")
|
|
55
|
+
return PRJob(
|
|
56
|
+
repo=repo,
|
|
57
|
+
pr_number=pr["number"],
|
|
58
|
+
kind=kind,
|
|
59
|
+
head_sha=pr["head"]["sha"],
|
|
60
|
+
base_sha=pr["base"]["sha"],
|
|
61
|
+
source="webhook",
|
|
62
|
+
delivery_id=delivery_id,
|
|
63
|
+
author_association=pr.get("author_association"),
|
|
64
|
+
author_login=(pr.get("user") or {}).get("login"),
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
if event == "issue_comment":
|
|
68
|
+
comment, issue = payload["comment"], payload["issue"]
|
|
69
|
+
if action != "created":
|
|
70
|
+
return Ignored(f"처리하지 않는 동작: issue_comment.{action}")
|
|
71
|
+
if "pull_request" not in issue:
|
|
72
|
+
return Ignored("PR이 아닌 이슈의 코멘트")
|
|
73
|
+
command, reason = command_in_comment(comment.get("body"), comment.get("author_association"))
|
|
74
|
+
if command is None:
|
|
75
|
+
return _feedback_job(
|
|
76
|
+
repo,
|
|
77
|
+
issue["number"],
|
|
78
|
+
comment,
|
|
79
|
+
None,
|
|
80
|
+
None,
|
|
81
|
+
delivery_id,
|
|
82
|
+
reason,
|
|
83
|
+
author=issue,
|
|
84
|
+
)
|
|
85
|
+
return PRJob(
|
|
86
|
+
repo=repo,
|
|
87
|
+
pr_number=issue["number"],
|
|
88
|
+
kind="command",
|
|
89
|
+
command=command,
|
|
90
|
+
comment_id=comment["id"],
|
|
91
|
+
source="webhook",
|
|
92
|
+
delivery_id=delivery_id,
|
|
93
|
+
author_association=issue.get("author_association"),
|
|
94
|
+
author_login=(issue.get("user") or {}).get("login"),
|
|
95
|
+
commenter_association=comment.get("author_association"),
|
|
96
|
+
commenter_login=(comment.get("user") or {}).get("login"),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
if event in ("pull_request_review", "pull_request_review_comment"):
|
|
100
|
+
wanted = "submitted" if event == "pull_request_review" else "created"
|
|
101
|
+
if action != wanted:
|
|
102
|
+
return Ignored(f"처리하지 않는 동작: {event}.{action}")
|
|
103
|
+
pr = payload["pull_request"]
|
|
104
|
+
if pr["head"]["ref"].startswith(PIPELINE_BRANCH_PREFIX):
|
|
105
|
+
return Ignored("파이프라인 제안 PR")
|
|
106
|
+
text = payload["review"] if event == "pull_request_review" else payload["comment"]
|
|
107
|
+
return _feedback_job(
|
|
108
|
+
repo,
|
|
109
|
+
pr["number"],
|
|
110
|
+
text,
|
|
111
|
+
pr["head"]["sha"],
|
|
112
|
+
pr["base"]["sha"],
|
|
113
|
+
delivery_id,
|
|
114
|
+
"",
|
|
115
|
+
author=pr,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
return Ignored(f"처리하지 않는 이벤트: {event}")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _feedback_job(
|
|
122
|
+
repo: str,
|
|
123
|
+
pr_number: int,
|
|
124
|
+
text: dict[str, Any],
|
|
125
|
+
head_sha: str | None,
|
|
126
|
+
base_sha: str | None,
|
|
127
|
+
delivery_id: str | None,
|
|
128
|
+
command_reason: str,
|
|
129
|
+
*,
|
|
130
|
+
author: dict[str, Any],
|
|
131
|
+
) -> PRJob | Ignored:
|
|
132
|
+
"""다룰 코멘트면 feedback 작업, 아니면 Ignored. 어떤 코멘트인지는 싣지 않는다(워커가 읽는다).
|
|
133
|
+
|
|
134
|
+
issue_comment는 먼저 명령인지 본다. 명령(`/`로 시작하는 글)은 여기서 받지 않고, 무시 이유는
|
|
135
|
+
명령 쪽의 이유(command_reason, 예: 권한 없음)를 그대로 쓴다.
|
|
136
|
+
"""
|
|
137
|
+
login = (text.get("user") or {}).get("login")
|
|
138
|
+
ok, reason = feedback_in_comment(text.get("body"), text.get("author_association"), login)
|
|
139
|
+
if not ok:
|
|
140
|
+
return Ignored(command_reason if reason == "명령" and command_reason else reason)
|
|
141
|
+
return PRJob(
|
|
142
|
+
repo=repo,
|
|
143
|
+
pr_number=pr_number,
|
|
144
|
+
kind="feedback",
|
|
145
|
+
head_sha=head_sha,
|
|
146
|
+
base_sha=base_sha,
|
|
147
|
+
source="webhook",
|
|
148
|
+
delivery_id=delivery_id,
|
|
149
|
+
author_association=author.get("author_association"),
|
|
150
|
+
author_login=(author.get("user") or {}).get("login"),
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def handle(
|
|
155
|
+
*,
|
|
156
|
+
body: bytes,
|
|
157
|
+
payload: dict[str, Any],
|
|
158
|
+
event: str | None,
|
|
159
|
+
delivery_id: str | None,
|
|
160
|
+
signature_header: str | None,
|
|
161
|
+
secret: str,
|
|
162
|
+
allowed_repos: frozenset[str],
|
|
163
|
+
redis: Redis,
|
|
164
|
+
) -> responses.WebhookResponse:
|
|
165
|
+
if not signature.verify(secret, body, signature_header):
|
|
166
|
+
return responses.unauthorized()
|
|
167
|
+
if delivery_id and queue.seen_delivery(redis, delivery_id):
|
|
168
|
+
return responses.duplicate_delivery()
|
|
169
|
+
parsed = parse_event(event or "", payload, delivery_id, allowed_repos)
|
|
170
|
+
if isinstance(parsed, Ignored):
|
|
171
|
+
return responses.ignored(parsed.reason)
|
|
172
|
+
return responses.accepted(parsed, queue.enqueue(redis, parsed))
|