plotroom 0.1.0__py3-none-any.whl
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.
- plotroom/__init__.py +0 -0
- plotroom/__main__.py +8 -0
- plotroom/_secret_file.py +8 -0
- plotroom/adapters/__init__.py +0 -0
- plotroom/adapters/claude_desktop.py +219 -0
- plotroom/adapters/embedding_http.py +175 -0
- plotroom/adapters/github/__init__.py +337 -0
- plotroom/adapters/github/app_credential.py +209 -0
- plotroom/adapters/github/ci.py +738 -0
- plotroom/adapters/github/commit_statuses.py +63 -0
- plotroom/adapters/github/deployments.py +213 -0
- plotroom/adapters/github/details.py +867 -0
- plotroom/adapters/github/issue_details.py +368 -0
- plotroom/adapters/github/junit.py +210 -0
- plotroom/adapters/github/junit_xml.py +162 -0
- plotroom/adapters/github/kodus_review.py +347 -0
- plotroom/adapters/github/pr_details.py +192 -0
- plotroom/adapters/github/pull_comparison.py +108 -0
- plotroom/adapters/github/read.py +530 -0
- plotroom/adapters/github/ticket_tree.py +336 -0
- plotroom/adapters/mcp/__init__.py +5 -0
- plotroom/adapters/mcp/proxy.py +722 -0
- plotroom/adapters/mcp/server.py +931 -0
- plotroom/adapters/openrouter.py +151 -0
- plotroom/adapters/store_sqlite/__init__.py +6 -0
- plotroom/adapters/store_sqlite/actions_sql.py +148 -0
- plotroom/adapters/store_sqlite/asks_sql.py +153 -0
- plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
- plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
- plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
- plotroom/adapters/store_sqlite/claims_sql.py +54 -0
- plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
- plotroom/adapters/store_sqlite/github_sql.py +331 -0
- plotroom/adapters/store_sqlite/goals_sql.py +57 -0
- plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
- plotroom/adapters/store_sqlite/items_sql.py +129 -0
- plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
- plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
- plotroom/adapters/store_sqlite/migrate.py +194 -0
- plotroom/adapters/store_sqlite/migrations/env.py +36 -0
- plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
- plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
- plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
- plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
- plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
- plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
- plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
- plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
- plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
- plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
- plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
- plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
- plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
- plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
- plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
- plotroom/adapters/store_sqlite/routes_sql.py +26 -0
- plotroom/adapters/store_sqlite/search_sql.py +116 -0
- plotroom/adapters/store_sqlite/store.py +623 -0
- plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
- plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
- plotroom/adapters/switchboard.py +152 -0
- plotroom/adapters/usage_fixture.py +11 -0
- plotroom/adapters/work_items_bmad.py +256 -0
- plotroom/adapters/work_items_github_issues.py +323 -0
- plotroom/app/__init__.py +0 -0
- plotroom/app/bridge.py +162 -0
- plotroom/app/clerk_import.py +349 -0
- plotroom/app/cli.py +290 -0
- plotroom/app/clock.py +12 -0
- plotroom/app/config.py +984 -0
- plotroom/app/daemon_start.py +453 -0
- plotroom/app/lock.py +77 -0
- plotroom/app/logging.py +93 -0
- plotroom/app/portfile.py +218 -0
- plotroom/app/runtime.py +518 -0
- plotroom/app/serve.py +671 -0
- plotroom/app/session_intake.py +51 -0
- plotroom/app/sqlite_floor.py +35 -0
- plotroom/app/tokens.py +265 -0
- plotroom/core/__init__.py +0 -0
- plotroom/core/actions.py +67 -0
- plotroom/core/ask_checks.py +124 -0
- plotroom/core/asks.py +123 -0
- plotroom/core/branch_updates.py +207 -0
- plotroom/core/bridge.py +112 -0
- plotroom/core/briefs.py +83 -0
- plotroom/core/budgets.py +182 -0
- plotroom/core/catalog.py +464 -0
- plotroom/core/checklists.py +151 -0
- plotroom/core/claims.py +296 -0
- plotroom/core/clerk_import.py +379 -0
- plotroom/core/commands.py +85 -0
- plotroom/core/deploy_window.py +21 -0
- plotroom/core/envelope.py +20 -0
- plotroom/core/events.py +227 -0
- plotroom/core/github.py +306 -0
- plotroom/core/github_projection.py +310 -0
- plotroom/core/goal_language.py +374 -0
- plotroom/core/goal_projection.py +146 -0
- plotroom/core/human_queue.py +119 -0
- plotroom/core/intake.py +106 -0
- plotroom/core/kodus_review.py +53 -0
- plotroom/core/lanes.py +281 -0
- plotroom/core/ledger.py +808 -0
- plotroom/core/merge_controller.py +344 -0
- plotroom/core/merge_flakes.py +422 -0
- plotroom/core/merge_gate.py +724 -0
- plotroom/core/merge_lane.py +70 -0
- plotroom/core/merge_overlap.py +76 -0
- plotroom/core/next_items.py +60 -0
- plotroom/core/operator_goals.py +103 -0
- plotroom/core/outbox.py +70 -0
- plotroom/core/pull_overlaps.py +152 -0
- plotroom/core/reports.py +62 -0
- plotroom/core/roles.py +100 -0
- plotroom/core/routing.py +55 -0
- plotroom/core/run_reports.py +53 -0
- plotroom/core/search.py +266 -0
- plotroom/core/search_sources.py +94 -0
- plotroom/core/snapshot.py +204 -0
- plotroom/core/trigger_actions.py +89 -0
- plotroom/core/triggers.py +550 -0
- plotroom/core/unit_of_work.py +541 -0
- plotroom/core/watchers.py +35 -0
- plotroom/core/work_items.py +23 -0
- plotroom/core/writer.py +164 -0
- plotroom/ports/__init__.py +6 -0
- plotroom/ports/clock.py +12 -0
- plotroom/ports/github_write.py +72 -0
- plotroom/ports/search.py +197 -0
- plotroom/ports/session_reader.py +23 -0
- plotroom/ports/store.py +323 -0
- plotroom/ports/usage_meter.py +35 -0
- plotroom/ports/work_items.py +22 -0
- plotroom/py.typed +0 -0
- plotroom-0.1.0.dist-info/METADATA +230 -0
- plotroom-0.1.0.dist-info/RECORD +150 -0
- plotroom-0.1.0.dist-info/WHEEL +4 -0
- plotroom-0.1.0.dist-info/entry_points.txt +2 -0
- plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""Read-only GitHub pull request intake."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
8
|
+
from datetime import UTC, datetime, timedelta
|
|
9
|
+
from email.utils import parsedate_to_datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Protocol, cast, runtime_checkable
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from plotroom._secret_file import read_secret_file
|
|
17
|
+
from plotroom.core.events import format_time
|
|
18
|
+
from plotroom.core.github import (
|
|
19
|
+
DETAILS,
|
|
20
|
+
PULL_REQUESTS,
|
|
21
|
+
FetchRetry,
|
|
22
|
+
ObservedPull,
|
|
23
|
+
valid_git_sha,
|
|
24
|
+
)
|
|
25
|
+
from plotroom.core.ledger import Ledger
|
|
26
|
+
from plotroom.ports.clock import Clock
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger("plotroom.github")
|
|
29
|
+
RECONCILE_EVERY = 60
|
|
30
|
+
POLL_OVERLAP = timedelta(minutes=5)
|
|
31
|
+
GITHUB_API = "https://api.github.com"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class GitHubUnavailable(Exception):
|
|
35
|
+
"""A provider error with a message safe to expose to the project."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class GitHubRateLimited(GitHubUnavailable):
|
|
39
|
+
def __init__(self, headers: httpx.Headers) -> None:
|
|
40
|
+
super().__init__("GitHub rate limit reached")
|
|
41
|
+
self._retry_after = headers.get("Retry-After")
|
|
42
|
+
self._reset = (
|
|
43
|
+
headers.get("X-RateLimit-Reset")
|
|
44
|
+
if headers.get("X-RateLimit-Remaining") == "0"
|
|
45
|
+
else None
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def retry_at(self, now: datetime, fallback: int) -> datetime:
|
|
49
|
+
if self._retry_after is not None:
|
|
50
|
+
try:
|
|
51
|
+
if self._retry_after.isdecimal():
|
|
52
|
+
return now + timedelta(seconds=max(1, int(self._retry_after)))
|
|
53
|
+
parsed = parsedate_to_datetime(self._retry_after)
|
|
54
|
+
return max(now + timedelta(seconds=1), parsed.replace(tzinfo=parsed.tzinfo or UTC))
|
|
55
|
+
except ValueError, OverflowError:
|
|
56
|
+
pass
|
|
57
|
+
if self._reset is not None:
|
|
58
|
+
try:
|
|
59
|
+
return max(
|
|
60
|
+
now + timedelta(seconds=1), datetime.fromtimestamp(int(self._reset), tz=UTC)
|
|
61
|
+
)
|
|
62
|
+
except ValueError, OverflowError, OSError:
|
|
63
|
+
pass
|
|
64
|
+
return now + timedelta(seconds=fallback)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def is_rate_limited(response: httpx.Response) -> bool:
|
|
68
|
+
if response.status_code == 429:
|
|
69
|
+
return True
|
|
70
|
+
if response.status_code != 403:
|
|
71
|
+
return False
|
|
72
|
+
if response.headers.get("X-RateLimit-Remaining") == "0" or "Retry-After" in response.headers:
|
|
73
|
+
return True
|
|
74
|
+
try:
|
|
75
|
+
payload: Any = response.json()
|
|
76
|
+
except ValueError, UnicodeError, RecursionError:
|
|
77
|
+
return False
|
|
78
|
+
message = cast("dict[str, Any]", payload).get("message") if isinstance(payload, dict) else None
|
|
79
|
+
return isinstance(message, str) and "rate limit" in message.lower()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def is_github_api_url(value: str) -> bool:
|
|
83
|
+
if value == GITHUB_API:
|
|
84
|
+
return True
|
|
85
|
+
try:
|
|
86
|
+
url = urlsplit(value)
|
|
87
|
+
return (
|
|
88
|
+
url.scheme == "http"
|
|
89
|
+
and url.hostname in ("127.0.0.1", "::1")
|
|
90
|
+
and url.port is not None
|
|
91
|
+
and url.username is None
|
|
92
|
+
and not (url.path or url.query or url.fragment)
|
|
93
|
+
and value == f"http://{url.netloc}"
|
|
94
|
+
)
|
|
95
|
+
except ValueError:
|
|
96
|
+
return False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class GitHubCredential(Protocol):
|
|
100
|
+
"""Supply the bearer for repository reads."""
|
|
101
|
+
|
|
102
|
+
async def token(self) -> str: ...
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@runtime_checkable
|
|
106
|
+
class _RejectableCredential(Protocol):
|
|
107
|
+
async def reject(self, token: str) -> None: ...
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def repository_client(
|
|
111
|
+
credential: GitHubCredential, *, transport: httpx.AsyncBaseTransport | None = None
|
|
112
|
+
) -> httpx.AsyncClient:
|
|
113
|
+
hooks: dict[str, list[Callable[[httpx.Response], Awaitable[None]]]] = {}
|
|
114
|
+
if isinstance(credential, _RejectableCredential):
|
|
115
|
+
rejecting = credential
|
|
116
|
+
|
|
117
|
+
async def reject_unauthorized(response: httpx.Response) -> None:
|
|
118
|
+
if response.status_code == 401:
|
|
119
|
+
scheme, _, token = response.request.headers.get("Authorization", "").partition(" ")
|
|
120
|
+
if scheme.casefold() == "bearer" and token:
|
|
121
|
+
await rejecting.reject(token)
|
|
122
|
+
|
|
123
|
+
hooks["response"] = [reject_unauthorized]
|
|
124
|
+
return httpx.AsyncClient(
|
|
125
|
+
timeout=15, follow_redirects=False, trust_env=False, transport=transport, event_hooks=hooks
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def github_secret_name(project_id: str) -> str:
|
|
130
|
+
return f"PLOTROOM_{project_id.upper().replace('-', '_')}_GITHUB_TOKEN"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class LocalGitHubCredential:
|
|
134
|
+
def __init__(self, name: str, environment: Mapping[str, str], file: Path | None) -> None:
|
|
135
|
+
self._name = name
|
|
136
|
+
self._env = environment
|
|
137
|
+
self._file = file
|
|
138
|
+
|
|
139
|
+
async def token(self) -> str:
|
|
140
|
+
candidate = self._env.get(self._name, "").strip()
|
|
141
|
+
if not candidate and self._file is not None:
|
|
142
|
+
try:
|
|
143
|
+
candidate = await read_secret_file(self._file)
|
|
144
|
+
except OSError, UnicodeError:
|
|
145
|
+
raise GitHubUnavailable(
|
|
146
|
+
f"cannot read the configured GitHub token file ({self._name})"
|
|
147
|
+
) from None
|
|
148
|
+
if not candidate:
|
|
149
|
+
raise GitHubUnavailable(f"GitHub token missing ({self._name})")
|
|
150
|
+
if (
|
|
151
|
+
not candidate.isascii()
|
|
152
|
+
or not candidate.isprintable()
|
|
153
|
+
or any(c.isspace() for c in candidate)
|
|
154
|
+
):
|
|
155
|
+
raise GitHubUnavailable(f"GitHub token is invalid ({self._name})")
|
|
156
|
+
return candidate
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _pull(value: Any) -> ObservedPull:
|
|
160
|
+
if not isinstance(value, dict):
|
|
161
|
+
raise ValueError("expected a pull request object")
|
|
162
|
+
row = cast("dict[str, Any]", value)
|
|
163
|
+
number, state, updated_at = row.get("number"), row.get("state"), row.get("updated_at")
|
|
164
|
+
head: Any = row.get("head")
|
|
165
|
+
body = row.get("body")
|
|
166
|
+
if (
|
|
167
|
+
type(number) is not int
|
|
168
|
+
or not 0 < number <= 2**63 - 1
|
|
169
|
+
or state not in ("open", "closed")
|
|
170
|
+
or not isinstance(updated_at, str)
|
|
171
|
+
or "merged_at" not in row
|
|
172
|
+
or not isinstance(head, dict)
|
|
173
|
+
or (body is not None and not isinstance(body, str))
|
|
174
|
+
):
|
|
175
|
+
raise ValueError("incomplete pull request")
|
|
176
|
+
fields = cast("dict[str, Any]", head)
|
|
177
|
+
branch, sha = fields.get("ref"), fields.get("sha")
|
|
178
|
+
if not isinstance(branch, str) or not branch or not isinstance(sha, str) or not sha:
|
|
179
|
+
raise ValueError("incomplete pull request head")
|
|
180
|
+
merged_at = row["merged_at"]
|
|
181
|
+
if merged_at is not None and (state != "closed" or not isinstance(merged_at, str)):
|
|
182
|
+
raise ValueError("invalid merged pull request")
|
|
183
|
+
normalized = format_time(datetime.fromisoformat(updated_at))
|
|
184
|
+
head_repo: Any = fields.get("repo")
|
|
185
|
+
full_name: Any = (
|
|
186
|
+
cast("dict[str, Any]", head_repo).get("full_name") if isinstance(head_repo, dict) else None
|
|
187
|
+
)
|
|
188
|
+
head_repository = full_name.lower() if isinstance(full_name, str) and full_name else None
|
|
189
|
+
draft = row.get("draft")
|
|
190
|
+
if draft is not None and type(draft) is not bool:
|
|
191
|
+
raise ValueError("invalid pull request draft state")
|
|
192
|
+
merge_sha = row.get("merge_commit_sha")
|
|
193
|
+
if merged_at is not None and merge_sha is not None and not valid_git_sha(merge_sha):
|
|
194
|
+
raise ValueError("invalid merge commit SHA")
|
|
195
|
+
return ObservedPull(
|
|
196
|
+
number,
|
|
197
|
+
branch,
|
|
198
|
+
sha,
|
|
199
|
+
head_repository,
|
|
200
|
+
"merged" if merged_at is not None else state,
|
|
201
|
+
normalized,
|
|
202
|
+
body or "",
|
|
203
|
+
draft,
|
|
204
|
+
merge_sha if merged_at is not None else None,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class PullRequestFetcher:
|
|
209
|
+
"""Fetch one resource. Pagination stays on the configured repository endpoint."""
|
|
210
|
+
|
|
211
|
+
def __init__(self, api_url: str, repository: str) -> None:
|
|
212
|
+
self._endpoint = httpx.URL(f"{api_url}/repos/{repository}/pulls")
|
|
213
|
+
|
|
214
|
+
async def fetch(
|
|
215
|
+
self, client: httpx.AsyncClient, token: str, floor: str | None
|
|
216
|
+
) -> tuple[ObservedPull, ...]:
|
|
217
|
+
query = {"state": "all", "sort": "updated", "direction": "desc", "per_page": "100"}
|
|
218
|
+
page = 1
|
|
219
|
+
pulls: dict[int, ObservedPull] = {}
|
|
220
|
+
while True:
|
|
221
|
+
response = await client.get(
|
|
222
|
+
self._endpoint,
|
|
223
|
+
params={**query, "page": str(page)},
|
|
224
|
+
headers={
|
|
225
|
+
"Authorization": f"Bearer {token}",
|
|
226
|
+
"Accept": "application/vnd.github+json",
|
|
227
|
+
"X-GitHub-Api-Version": "2026-03-10",
|
|
228
|
+
},
|
|
229
|
+
)
|
|
230
|
+
if is_rate_limited(response):
|
|
231
|
+
raise GitHubRateLimited(response.headers)
|
|
232
|
+
if response.status_code in (401, 403, 404):
|
|
233
|
+
raise GitHubUnavailable("GitHub denied access to the configured repository")
|
|
234
|
+
if response.status_code != 200:
|
|
235
|
+
raise GitHubUnavailable(
|
|
236
|
+
f"GitHub pull request poll returned HTTP {response.status_code}"
|
|
237
|
+
)
|
|
238
|
+
try:
|
|
239
|
+
rows: Any = response.json()
|
|
240
|
+
if not isinstance(rows, list):
|
|
241
|
+
raise ValueError("expected a list of pull requests")
|
|
242
|
+
reached_floor = False
|
|
243
|
+
for row in cast("list[Any]", rows):
|
|
244
|
+
observed = _pull(row)
|
|
245
|
+
if floor is not None and observed.updated_at < floor:
|
|
246
|
+
reached_floor = True
|
|
247
|
+
continue
|
|
248
|
+
previous = pulls.get(observed.number)
|
|
249
|
+
if previous is None or previous.updated_at < observed.updated_at:
|
|
250
|
+
pulls[observed.number] = observed
|
|
251
|
+
except ValueError, OverflowError:
|
|
252
|
+
raise GitHubUnavailable(
|
|
253
|
+
"GitHub returned an invalid pull request response"
|
|
254
|
+
) from None
|
|
255
|
+
link = response.links.get("next")
|
|
256
|
+
if link is None or reached_floor:
|
|
257
|
+
return tuple(pulls.values())
|
|
258
|
+
# GitHub can use its numeric repository route in Link. Only the page number
|
|
259
|
+
# is needed, so every authenticated request stays on the configured endpoint.
|
|
260
|
+
try:
|
|
261
|
+
next_page = int(httpx.URL(link["url"]).params["page"])
|
|
262
|
+
except KeyError, ValueError, httpx.InvalidURL:
|
|
263
|
+
raise GitHubUnavailable("GitHub returned invalid pull request pagination") from None
|
|
264
|
+
if next_page != page + 1:
|
|
265
|
+
raise GitHubUnavailable("GitHub returned invalid pull request pagination")
|
|
266
|
+
page = next_page
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class GitHubPoller:
|
|
270
|
+
def __init__(
|
|
271
|
+
self,
|
|
272
|
+
ledger: Ledger,
|
|
273
|
+
clock: Clock,
|
|
274
|
+
repo: str,
|
|
275
|
+
credential: GitHubCredential,
|
|
276
|
+
fetcher: PullRequestFetcher,
|
|
277
|
+
seconds: int,
|
|
278
|
+
) -> None:
|
|
279
|
+
self._ledger = ledger
|
|
280
|
+
self._clock = clock
|
|
281
|
+
self._repo = repo
|
|
282
|
+
self._credential = credential
|
|
283
|
+
self._fetcher = fetcher
|
|
284
|
+
self._seconds = seconds
|
|
285
|
+
self._retry_at: datetime | None = None
|
|
286
|
+
|
|
287
|
+
async def poll(self, client: httpx.AsyncClient) -> bool:
|
|
288
|
+
retry = await self._ledger.fetch_retry(self._repo, PULL_REQUESTS)
|
|
289
|
+
detail_retry = await self._ledger.fetch_retry(self._repo, DETAILS)
|
|
290
|
+
self._retry_at = max(
|
|
291
|
+
(datetime.fromisoformat(row.until) for row in (retry, detail_retry) if row),
|
|
292
|
+
default=None,
|
|
293
|
+
)
|
|
294
|
+
if self._retry_at is not None and self._clock.now() < self._retry_at:
|
|
295
|
+
await self._ledger.set_github_error("GitHub rate limit reached")
|
|
296
|
+
return False
|
|
297
|
+
baseline = await self._ledger.fetch_cursor(self._repo, PULL_REQUESTS)
|
|
298
|
+
# Inclusive overlap tolerates equal timestamps and rows moving between pages.
|
|
299
|
+
# A periodic full reconciliation also refreshes old records.
|
|
300
|
+
floor = None
|
|
301
|
+
if baseline and baseline.watermark and baseline.generation % RECONCILE_EVERY:
|
|
302
|
+
floor = format_time(datetime.fromisoformat(baseline.watermark) - POLL_OVERLAP)
|
|
303
|
+
try:
|
|
304
|
+
token = await self._credential.token()
|
|
305
|
+
pulls = await self._fetcher.fetch(client, token, floor)
|
|
306
|
+
except (GitHubUnavailable, httpx.RequestError) as exc:
|
|
307
|
+
if isinstance(exc, GitHubRateLimited):
|
|
308
|
+
backoff = retry.next_backoff if retry is not None else 60
|
|
309
|
+
self._retry_at = exc.retry_at(self._clock.now(), backoff)
|
|
310
|
+
deadline = FetchRetry(format_time(self._retry_at), min(backoff * 2, 900))
|
|
311
|
+
await self._ledger.run(
|
|
312
|
+
"system", lambda uow: uow.save_fetch_retry(self._repo, PULL_REQUESTS, deadline)
|
|
313
|
+
)
|
|
314
|
+
reason = str(exc) if isinstance(exc, GitHubUnavailable) else "GitHub request failed"
|
|
315
|
+
if self._ledger.github_error != reason:
|
|
316
|
+
log.warning(reason, extra={"project": self._ledger.project_id})
|
|
317
|
+
await self._ledger.set_github_error(reason)
|
|
318
|
+
return False
|
|
319
|
+
as_of = format_time(self._clock.now())
|
|
320
|
+
committed = await self._ledger.commit_github_pull_poll(self._repo, baseline, pulls, as_of)
|
|
321
|
+
if committed:
|
|
322
|
+
self._retry_at = None
|
|
323
|
+
return committed
|
|
324
|
+
|
|
325
|
+
async def run(
|
|
326
|
+
self, after_pull: Callable[[httpx.AsyncClient], Awaitable[None]] | None = None
|
|
327
|
+
) -> None:
|
|
328
|
+
async with repository_client(self._credential) as client:
|
|
329
|
+
while True:
|
|
330
|
+
committed = await self.poll(client)
|
|
331
|
+
if committed and after_pull is not None:
|
|
332
|
+
await after_pull(client)
|
|
333
|
+
if self._retry_at is None:
|
|
334
|
+
delay = self._seconds
|
|
335
|
+
else:
|
|
336
|
+
delay = max(self._seconds, (self._retry_at - self._clock.now()).total_seconds())
|
|
337
|
+
await asyncio.sleep(delay)
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""Mint repository-scoped GitHub App installation tokens from a mounted key."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import base64
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from datetime import datetime, timedelta
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
from cryptography.exceptions import UnsupportedAlgorithm
|
|
14
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
15
|
+
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
|
16
|
+
|
|
17
|
+
from plotroom._secret_file import read_secret_file
|
|
18
|
+
from plotroom.adapters.github import (
|
|
19
|
+
GITHUB_API,
|
|
20
|
+
GitHubRateLimited,
|
|
21
|
+
GitHubUnavailable,
|
|
22
|
+
is_rate_limited,
|
|
23
|
+
)
|
|
24
|
+
from plotroom.ports.clock import Clock
|
|
25
|
+
|
|
26
|
+
_READ_PERMISSIONS = {
|
|
27
|
+
"actions": "read",
|
|
28
|
+
"checks": "read",
|
|
29
|
+
"contents": "read",
|
|
30
|
+
"deployments": "read",
|
|
31
|
+
"issues": "read",
|
|
32
|
+
"pull_requests": "read",
|
|
33
|
+
}
|
|
34
|
+
_BEARER = re.compile(r"[A-Za-z0-9._~-]+")
|
|
35
|
+
_MAX_RESPONSE_BYTES = 64 * 1024
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _base64url(value: bytes) -> bytes:
|
|
39
|
+
return base64.urlsafe_b64encode(value).rstrip(b"=")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _app_jwt(pem: str, client_id: str, now: datetime) -> str:
|
|
43
|
+
key = serialization.load_pem_private_key(pem.encode("utf-8"), password=None)
|
|
44
|
+
if not isinstance(key, rsa.RSAPrivateKey):
|
|
45
|
+
raise ValueError("an RSA key is required")
|
|
46
|
+
timestamp = int(now.timestamp())
|
|
47
|
+
claims = {"iss": client_id, "iat": timestamp - 60, "exp": timestamp + 540}
|
|
48
|
+
unsigned = b".".join(
|
|
49
|
+
(
|
|
50
|
+
_base64url(b'{"alg":"RS256","typ":"JWT"}'),
|
|
51
|
+
_base64url(json.dumps(claims, separators=(",", ":")).encode("utf-8")),
|
|
52
|
+
)
|
|
53
|
+
)
|
|
54
|
+
signature = key.sign(unsigned, padding.PKCS1v15(), hashes.SHA256())
|
|
55
|
+
return b".".join((unsigned, _base64url(signature))).decode("ascii")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class _InstallationToken:
|
|
60
|
+
value: str = field(repr=False)
|
|
61
|
+
refresh_at: datetime
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
async def _response_payload(
|
|
65
|
+
response: httpx.Response, expected_status: int, error: str
|
|
66
|
+
) -> dict[str, Any]:
|
|
67
|
+
if response.status_code == 429 or (
|
|
68
|
+
response.status_code == 403
|
|
69
|
+
and (
|
|
70
|
+
response.headers.get("X-RateLimit-Remaining") == "0"
|
|
71
|
+
or "Retry-After" in response.headers
|
|
72
|
+
)
|
|
73
|
+
):
|
|
74
|
+
raise GitHubRateLimited(response.headers)
|
|
75
|
+
if response.status_code not in (expected_status, 403):
|
|
76
|
+
raise GitHubUnavailable(error)
|
|
77
|
+
if response.headers.get("Content-Encoding", "identity").lower() != "identity":
|
|
78
|
+
# Avoid decompressing a large response before enforcing the byte limit.
|
|
79
|
+
raise GitHubUnavailable(error)
|
|
80
|
+
|
|
81
|
+
body = bytearray()
|
|
82
|
+
async for chunk in response.aiter_bytes(chunk_size=4096):
|
|
83
|
+
if len(body) + len(chunk) > _MAX_RESPONSE_BYTES:
|
|
84
|
+
raise GitHubUnavailable(error)
|
|
85
|
+
body.extend(chunk)
|
|
86
|
+
if response.status_code == 403:
|
|
87
|
+
if is_rate_limited(httpx.Response(403, content=bytes(body))):
|
|
88
|
+
raise GitHubRateLimited(response.headers)
|
|
89
|
+
raise GitHubUnavailable(error)
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
payload: Any = json.loads(body)
|
|
93
|
+
except ValueError, RecursionError:
|
|
94
|
+
raise GitHubUnavailable(error) from None
|
|
95
|
+
if not isinstance(payload, dict):
|
|
96
|
+
raise GitHubUnavailable(error)
|
|
97
|
+
return cast("dict[str, Any]", payload)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class GitHubAppCredential:
|
|
101
|
+
def __init__(
|
|
102
|
+
self,
|
|
103
|
+
client_id: str,
|
|
104
|
+
installation_id: int,
|
|
105
|
+
key_file: Path,
|
|
106
|
+
repository: str,
|
|
107
|
+
api_url: str,
|
|
108
|
+
clock: Clock,
|
|
109
|
+
) -> None:
|
|
110
|
+
if api_url != GITHUB_API:
|
|
111
|
+
raise ValueError("GitHub App credentials require https://api.github.com")
|
|
112
|
+
if type(installation_id) is not int or installation_id < 1:
|
|
113
|
+
raise ValueError("GitHub App credentials require a positive installation ID")
|
|
114
|
+
self._client_id = client_id
|
|
115
|
+
self._key_file = key_file
|
|
116
|
+
self._owner, self._repository = repository.split("/", 1)
|
|
117
|
+
self._installation = f"{GITHUB_API}/app/installations/{installation_id}"
|
|
118
|
+
self._clock = clock
|
|
119
|
+
self._lock = asyncio.Lock()
|
|
120
|
+
self._last_now: datetime | None = None
|
|
121
|
+
self._cached: _InstallationToken | None = None
|
|
122
|
+
|
|
123
|
+
def _now(self) -> datetime:
|
|
124
|
+
current = self._clock.now()
|
|
125
|
+
if self._last_now is not None and current < self._last_now:
|
|
126
|
+
self._cached = None
|
|
127
|
+
raise GitHubUnavailable("GitHub App credential clock moved backward")
|
|
128
|
+
self._last_now = current
|
|
129
|
+
return current
|
|
130
|
+
|
|
131
|
+
async def token(self) -> str:
|
|
132
|
+
async with self._lock:
|
|
133
|
+
now = self._now()
|
|
134
|
+
if self._cached is not None and now < self._cached.refresh_at:
|
|
135
|
+
return self._cached.value
|
|
136
|
+
self._cached = None
|
|
137
|
+
self._cached = await self._refresh()
|
|
138
|
+
return self._cached.value
|
|
139
|
+
|
|
140
|
+
async def reject(self, token: str) -> None:
|
|
141
|
+
async with self._lock:
|
|
142
|
+
if self._cached is not None and self._cached.value == token:
|
|
143
|
+
self._cached = None
|
|
144
|
+
|
|
145
|
+
async def _refresh(self) -> _InstallationToken:
|
|
146
|
+
try:
|
|
147
|
+
pem = await read_secret_file(self._key_file)
|
|
148
|
+
jwt = await asyncio.to_thread(_app_jwt, pem, self._client_id, self._now())
|
|
149
|
+
except OSError, ValueError, TypeError, UnsupportedAlgorithm:
|
|
150
|
+
raise GitHubUnavailable(
|
|
151
|
+
"Cannot read or sign with the configured GitHub App key"
|
|
152
|
+
) from None
|
|
153
|
+
|
|
154
|
+
headers = {
|
|
155
|
+
"Authorization": f"Bearer {jwt}",
|
|
156
|
+
"Accept": "application/vnd.github+json",
|
|
157
|
+
"Accept-Encoding": "identity",
|
|
158
|
+
"X-GitHub-Api-Version": "2026-03-10",
|
|
159
|
+
}
|
|
160
|
+
try:
|
|
161
|
+
async with httpx.AsyncClient(
|
|
162
|
+
timeout=15, follow_redirects=False, trust_env=False
|
|
163
|
+
) as client:
|
|
164
|
+
async with client.stream("GET", self._installation, headers=headers) as response:
|
|
165
|
+
installation = await _response_payload(
|
|
166
|
+
response, 200, "Cannot read the configured GitHub App installation"
|
|
167
|
+
)
|
|
168
|
+
account: Any = installation.get("account")
|
|
169
|
+
login = (
|
|
170
|
+
cast("dict[str, Any]", account).get("login")
|
|
171
|
+
if isinstance(account, dict)
|
|
172
|
+
else None
|
|
173
|
+
)
|
|
174
|
+
if not isinstance(login, str) or login.casefold() != self._owner.casefold():
|
|
175
|
+
raise GitHubUnavailable(
|
|
176
|
+
"GitHub App installation does not own the configured repository"
|
|
177
|
+
)
|
|
178
|
+
async with client.stream(
|
|
179
|
+
"POST",
|
|
180
|
+
f"{self._installation}/access_tokens",
|
|
181
|
+
headers=headers,
|
|
182
|
+
json={"repositories": [self._repository], "permissions": _READ_PERMISSIONS},
|
|
183
|
+
) as response:
|
|
184
|
+
payload = await _response_payload(
|
|
185
|
+
response, 201, "Cannot mint a GitHub App installation token"
|
|
186
|
+
)
|
|
187
|
+
except httpx.RequestError:
|
|
188
|
+
raise GitHubUnavailable("GitHub App credential request failed") from None
|
|
189
|
+
|
|
190
|
+
value, expiry = payload.get("token"), payload.get("expires_at")
|
|
191
|
+
if (
|
|
192
|
+
not isinstance(value, str)
|
|
193
|
+
or not _BEARER.fullmatch(value)
|
|
194
|
+
or not isinstance(expiry, str)
|
|
195
|
+
):
|
|
196
|
+
raise GitHubUnavailable("GitHub returned an invalid installation token")
|
|
197
|
+
try:
|
|
198
|
+
expires_at = datetime.fromisoformat(expiry)
|
|
199
|
+
except ValueError:
|
|
200
|
+
raise GitHubUnavailable(
|
|
201
|
+
"GitHub returned an invalid installation token expiry"
|
|
202
|
+
) from None
|
|
203
|
+
now = self._now()
|
|
204
|
+
if expires_at.utcoffset() is None or expires_at <= now:
|
|
205
|
+
raise GitHubUnavailable("GitHub returned an expired or invalid installation token")
|
|
206
|
+
# Scale the refresh margin down for short-lived tokens and preserve the fixed
|
|
207
|
+
# upper bound for GitHub's usual one-hour lifetime.
|
|
208
|
+
leeway = min(timedelta(minutes=1), (expires_at - now) / 5)
|
|
209
|
+
return _InstallationToken(value, expires_at - leeway)
|