-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathgithub_client.py
More file actions
216 lines (190 loc) · 7.62 KB
/
Copy pathgithub_client.py
File metadata and controls
216 lines (190 loc) · 7.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""GitHub API wrapper using httpx (T009).
Uses BOT_PAT for mutations (labels, comments, close) and
GITHUB_TOKEN for search queries (rate limiting).
"""
from __future__ import annotations
import asyncio
import logging
import random
from typing import Any
import httpx
logger = logging.getLogger(__name__)
# Retry configuration per spec: base 1s, factor 2×, max 3, jitter ±500ms
MAX_RETRIES = 3
BASE_DELAY = 1.0
BACKOFF_FACTOR = 2.0
JITTER_MS = 500
API_BASE = "https://api.github.com"
class GitHubClient:
"""Wrapper around GitHub REST API with retry and state checking."""
def __init__(
self,
bot_pat: str,
github_token: str,
repo_owner: str,
repo_name: str,
) -> None:
self._repo_owner = repo_owner
self._repo_name = repo_name
headers_common = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28"}
self._bot_client = httpx.AsyncClient(
base_url=API_BASE,
headers={**headers_common, "Authorization": f"Bearer {bot_pat}"},
)
self._search_client = httpx.AsyncClient(
base_url=API_BASE,
headers={**headers_common, "Authorization": f"Bearer {github_token}"},
)
async def close(self) -> None:
await self._bot_client.aclose()
await self._search_client.aclose()
def _repo_url(self, path: str) -> str:
return f"/repos/{self._repo_owner}/{self._repo_name}{path}"
async def _request_with_retry(
self,
client: httpx.AsyncClient,
method: str,
url: str,
**kwargs: Any,
) -> httpx.Response:
"""Execute request with exponential backoff on 403/429."""
last_response: httpx.Response | None = None
for attempt in range(MAX_RETRIES + 1):
response = await getattr(client, method)(url, **kwargs)
if response.status_code not in (403, 429):
return response
last_response = response
if attempt < MAX_RETRIES:
delay = BASE_DELAY * (BACKOFF_FACTOR ** attempt)
jitter = random.uniform(-JITTER_MS / 1000, JITTER_MS / 1000)
await asyncio.sleep(max(0, delay + jitter))
assert last_response is not None
last_response.raise_for_status()
return last_response # unreachable, but satisfies type checker
async def add_labels(self, issue_number: int, labels: list[str]) -> None:
response = await self._request_with_retry(
self._bot_client,
"post",
self._repo_url(f"/issues/{issue_number}/labels"),
json=labels,
)
response.raise_for_status()
async def post_comment(self, issue_number: int, body: str) -> None:
# Safety net: check if bot already commented (prevent duplicate spam)
bot_login = await self._get_bot_login()
if bot_login:
existing = await self._request_with_retry(
self._search_client,
"get",
self._repo_url(f"/issues/{issue_number}/comments"),
params={"per_page": 100},
)
if existing.status_code == 200:
comments = existing.json()
if any(c.get("user", {}).get("login") == bot_login for c in comments):
logger.warning(
"Duplicate comment blocked: bot '%s' already commented on #%d",
bot_login, issue_number,
)
return
response = await self._request_with_retry(
self._bot_client,
"post",
self._repo_url(f"/issues/{issue_number}/comments"),
json={"body": body},
)
response.raise_for_status()
async def _get_bot_login(self) -> str | None:
"""Get the authenticated bot's login name. Cached after first call."""
if not hasattr(self, "_bot_login_cached"):
try:
response = await self._bot_client.get("/user")
if response.status_code == 200:
self._bot_login_cached: str | None = response.json().get("login")
else:
self._bot_login_cached = None
except Exception:
self._bot_login_cached = None
return self._bot_login_cached
async def close_issue(self, issue_number: int) -> None:
response = await self._request_with_retry(
self._bot_client,
"patch",
self._repo_url(f"/issues/{issue_number}"),
json={"state": "closed"},
)
response.raise_for_status()
async def search_issues_by_author(self, username: str, since_hours: int = 24) -> int:
"""Count issues opened by user in the last N hours using GitHub Search API."""
from datetime import datetime, timedelta, timezone
since = (datetime.now(timezone.utc) - timedelta(hours=since_hours)).strftime("%Y-%m-%dT%H:%M:%S")
query = f"author:{username} type:issue repo:{self._repo_owner}/{self._repo_name} created:>={since}"
response = await self._request_with_retry(
self._search_client,
"get",
"/search/issues",
params={"q": query},
)
response.raise_for_status()
return response.json().get("total_count", 0)
async def set_assignee(self, issue_number: int, username: str) -> None:
"""Assign a user to an issue."""
response = await self._request_with_retry(
self._bot_client,
"post",
self._repo_url(f"/issues/{issue_number}/assignees"),
json={"assignees": [username]},
)
response.raise_for_status()
async def get_closed_issues_since(
self, since_iso: str, labels: list[str] | None = None
) -> list[dict[str, Any]]:
"""Get closed issues since a given ISO date, optionally filtered by labels."""
params: dict[str, Any] = {
"state": "closed",
"since": since_iso,
"per_page": 100,
}
if labels:
params["labels"] = ",".join(labels)
all_issues: list[dict[str, Any]] = []
page = 1
while True:
params["page"] = page
response = await self._request_with_retry(
self._search_client,
"get",
self._repo_url("/issues"),
params=params,
)
response.raise_for_status()
issues = response.json()
if not issues:
break
all_issues.extend(issues)
if len(issues) < 100:
break
page += 1
return all_issues
async def bot_has_commented(self, issue_number: int, bot_username: str) -> bool:
"""Check if the bot has already commented on this issue."""
response = await self._request_with_retry(
self._search_client,
"get",
self._repo_url(f"/issues/{issue_number}/comments"),
params={"per_page": 100},
)
if response.status_code == 404:
return False
response.raise_for_status()
comments = response.json()
return any(
c.get("user", {}).get("login") == bot_username for c in comments
)
async def get_issue_state(self, issue_number: int) -> str:
"""Get current issue state. Returns 'deleted' if 404/410."""
response = await self._bot_client.get(self._repo_url(f"/issues/{issue_number}"))
if response.status_code in (404, 410):
return "deleted"
response.raise_for_status()
return response.json().get("state", "unknown")