diff --git a/tests/test_pr_conflict_label.py b/tests/test_pr_conflict_label.py index 19125ee0a..9c9785c71 100644 --- a/tests/test_pr_conflict_label.py +++ b/tests/test_pr_conflict_label.py @@ -4,13 +4,18 @@ A fake GitHub API stands in for the network, so this checks the calls the tool makes: which pull requests get the label, that one whose merge GitHub has not computed yet is asked again and otherwise left alone, that the label is -created only when it is first needed, that `--dry-run` writes nothing, and that the workflow runs the tool without -checking out pull request code. Standard library only; no network, no game files. +created only when it is first needed, that `--dry-run` writes nothing, that a run over every open pull request stays +under the hourly request limit of the workflow's token, and that the workflow runs the tool without checking out +pull request code. Standard library only; no network, no game files. """ +import contextlib +import functools +import io import os import re import sys import unittest +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) @@ -22,22 +27,40 @@ REPO = "owner/name" class FakeApi: """Pull requests as {number: [mergeable answers in order, the last one repeating]} plus their labels.""" - def __init__(self, prs, labeled=(), label_exists=False, closed=()): + def __init__(self, prs, labeled=(), label_exists=False, closed=(), limit=None): self.answers = {n: list(a) for n, a in prs.items()} self.labels = {n: ({pcl.LABEL} if n in labeled else set()) for n in prs} self.closed = set(closed) self.label_exists = label_exists + self.limit = limit # requests this token may make, as GitHub counts them per hour self.calls = [] + def mergeable(self, n): + answers = self.answers[n] + return answers.pop(0) if len(answers) > 1 else answers[0] + def __call__(self, method, path, body=None): self.calls.append((method, path, body)) + if self.limit is not None and len(self.calls) > self.limit: + raise pcl.ApiError(403, "API rate limit exceeded for installation") + if method == "POST" and path == "/graphql": + self.assert_query(body) + numbers = sorted(n for n in self.answers if n not in self.closed) + start = int(body["variables"]["after"] or 0) + names = {True: "MERGEABLE", False: "CONFLICTING", None: "UNKNOWN"} + nodes = [{"number": n, "mergeable": names[self.mergeable(n)], + "labels": {"nodes": [{"name": name} for name in sorted(self.labels[n])]}} + for n in numbers[start:start + 100]] + more = start + 100 < len(numbers) + return {"data": {"repository": {"pullRequests": { + "pageInfo": {"hasNextPage": more, "endCursor": str(start + 100) if more else None}, "nodes": nodes}}}} m = re.fullmatch(rf"/repos/{REPO}/pulls/(\d+)", path) if method == "GET" and m: n = int(m.group(1)) - answers = self.answers[n] - mergeable = answers.pop(0) if len(answers) > 1 else answers[0] - return {"number": n, "state": "closed" if n in self.closed else "open", "mergeable": mergeable, + return {"number": n, "state": "closed" if n in self.closed else "open", "mergeable": self.mergeable(n), "labels": [{"name": name} for name in sorted(self.labels[n])]} + # How the tool listed them before the GraphQL listing: kept so that these tests, run against that version, + # end in its HTTP 403 rather than in "unexpected call". if method == "GET" and path.startswith(f"/repos/{REPO}/pulls?"): page = int(re.search(r"[?&]page=(\d+)", path).group(1)) numbers = sorted(self.answers) @@ -60,8 +83,15 @@ class FakeApi: return None raise AssertionError(f"unexpected call {method} {path}") + def assert_query(self, body): + owner, name = REPO.split("/") + assert (body["variables"]["owner"], body["variables"]["name"]) == (owner, name), body["variables"] + for part in ("states: OPEN", "first: 100", "after: $after", "hasNextPage", "endCursor", "number", "mergeable", + "labels(first: 100)"): + assert part in body["query"], part + def writes(self): - return [c for c in self.calls if c[0] != "GET"] + return [c for c in self.calls if c[0] != "GET" and c[1] != "/graphql"] def run(api, numbers, **kw): @@ -127,9 +157,60 @@ class RunTest(unittest.TestCase): self.assertEqual((done["add"], done["remove"]), ([1], [2])) self.assertEqual(api.writes(), []) - def test_open_pull_numbers_follows_pages(self): - api = FakeApi({n: [True] for n in range(1, 251)}) - self.assertEqual(pcl.open_pull_numbers(api, REPO), list(range(1, 251))) + def test_open_pulls_follows_pages(self): + api = FakeApi({n: [n % 3 != 0 if n % 5 else None] for n in range(1, 251)}, labeled={4, 250}, closed={8}) + pulls = pcl.open_pulls(api, REPO) + self.assertEqual(sorted(pulls), [n for n in range(1, 251) if n != 8]) + self.assertEqual((pulls[1], pulls[3], pulls[4], pulls[5], pulls[250]), + ((True, False), (False, False), (True, True), (None, False), (None, True))) + self.assertEqual(len(api.calls), 3) + + def test_a_graphql_error_is_not_read_as_no_pull_requests(self): + def api(method, path, body=None): + return {"data": {"repository": None}, "errors": [{"type": "NOT_FOUND", "message": "no such repository"}]} + with self.assertRaisesRegex(pcl.ApiError, "no such repository"): + pcl.open_pulls(api, REPO) + + +class AllOpenTest(unittest.TestCase): + """A run over every open pull request, as the workflow starts it.""" + + def main(self, api, *args): + out = io.StringIO() + self.waits = [] + no_wait = functools.partial(pcl.run, sleep=self.waits.append) + with mock.patch.object(pcl, "github_api", lambda token: api), mock.patch.object(pcl, "run", no_wait), \ + mock.patch.dict(os.environ, {"GITHUB_TOKEN": "t"}), contextlib.redirect_stdout(out): + status = pcl.main(["--repo", REPO, *args]) + return status, out.getvalue() + + def test_1500_open_pull_requests_stay_under_the_token_limit(self): + # The workflow's GITHUB_TOKEN gets 1,000 requests an hour for the repository, shared by every run. One GET + # per pull request and attempt spends them: with 1,500 open a single run ended in HTTP 403 before the last. + prs = {n: [True] for n in range(1, 1501)} + prs.update({7: [False], 1200: [False], 1400: [None, False], 1499: [True], 1500: [None]}) + api = FakeApi(prs, labeled={1499, 1500}, limit=1000) + status, text = self.main(api) + self.assertEqual(status, 0) + self.assertEqual(sorted(n for n, names in api.labels.items() if names), [7, 1200, 1400, 1500]) + self.assertIn("1500 checked: 3 labeled, 1 unlabeled, 1 not computed yet", text) + self.assertLessEqual(len(api.calls), 4 * 15 + 5) # 15 pages an attempt, then the label and four changes + self.assertEqual(self.waits, [pcl.LIST_WAIT] * 3) # a listing is cheap: GitHub gets longer between attempts + + def test_a_pull_request_closed_between_two_listings_is_skipped(self): + api = FakeApi({1: [None, False], 2: [None, False]}) + pulls = pcl.open_pulls(api, REPO) + api.closed.add(2) + done = run(api, sorted(pulls), pulls=pulls) + self.assertEqual(done, {"add": [1], "remove": [], "unknown": []}) + self.assertEqual(api.labels, {1: {pcl.LABEL}, 2: set()}) + + def test_one_named_pull_request_is_one_request(self): + api = FakeApi({n: [True] for n in range(1, 301)}, labeled={5}) + status, text = self.main(api, "--pr", "5") + self.assertEqual(status, 0) + self.assertEqual([c[:2] for c in api.calls], [("GET", f"/repos/{REPO}/pulls/5"), + ("DELETE", f"/repos/{REPO}/issues/5/labels/needs%20rebase")]) class WorkflowTest(unittest.TestCase): diff --git a/tools/pr_conflict_label.py b/tools/pr_conflict_label.py index 075985a57..40705cc86 100644 --- a/tools/pr_conflict_label.py +++ b/tools/pr_conflict_label.py @@ -8,8 +8,13 @@ per-pull-request trigger: one run per push to every pull request flooded the rep the ones that cannot be merged as they stand and tells their authors to rebase. GitHub computes `mergeable` in the background and answers `null` until it has, so a pull request whose answer is -still unknown is asked again a few times and otherwise left as it is for the next run. Only the GitHub REST API is -read and written: no pull request code is checked out or run. The token comes from `GITHUB_TOKEN` (or `GH_TOKEN`); `--dry-run` prints the changes and writes nothing. +still unknown is asked again a few times and otherwise left as it is for the next run. A run over every open pull +request reads them 100 per request through the GraphQL API: the workflow's token gets 1,000 requests an hour for the +whole repository, and one request per open pull request on every attempt of every run spent them with several hundred +open, so runs failed with HTTP 403 and the other workflows had none left. A listing is cheap, so its attempts are +LIST_WAIT seconds apart: three waits give GitHub about the minutes a pass of one request per pull request used to, +to compute the merges a push to `main` reset. `--pr` still asks for each one by number. +Only the GitHub API is read and written: no pull request code is checked out or run. The token comes from `GITHUB_TOKEN` (or `GH_TOKEN`); `--dry-run` prints the changes and writes nothing. Standard library only; no game files. """ import argparse @@ -25,6 +30,17 @@ LABEL = "needs rebase" LABEL_COLOR = "d93f0b" LABEL_DESCRIPTION = "Conflicts with the base branch: rebase it on main" API = "https://api.github.com" +# Every open pull request, 100 per request: its number, GitHub's merge answer and its labels. +PULLS_QUERY = """query($owner: String!, $name: String!, $after: String) { + repository(owner: $owner, name: $name) { + pullRequests(states: OPEN, first: 100, after: $after) { + pageInfo { hasNextPage endCursor } + nodes { number mergeable labels(first: 100) { nodes { name } } } + } + } +}""" +MERGEABLE = {"MERGEABLE": True, "CONFLICTING": False} # "UNKNOWN": not computed yet +LIST_WAIT = 60.0 # seconds between the attempts of a run over every open pull request class ApiError(Exception): @@ -34,7 +50,8 @@ class ApiError(Exception): def github_api(token): - """A function (method, path, body=None) -> parsed JSON (or None) that calls the GitHub REST API with `token`.""" + """A function (method, path, body=None) -> parsed JSON (or None) that calls the GitHub API with `token`: REST, + and GraphQL at `/graphql`.""" def call(method, path, body=None): data = None if body is None else json.dumps(body).encode("utf-8") req = urllib.request.Request(API + path, data=data, method=method, headers={ @@ -61,14 +78,23 @@ def decide(mergeable, labeled): return None -def open_pull_numbers(api, repo): - numbers, page = [], 1 +def open_pulls(api, repo): + """{number: (mergeable, labeled)} for every open pull request, read 100 per request. `mergeable` is True, False + or None (not computed yet).""" + owner, _, name = repo.partition("/") + pulls, after = {}, None while True: - batch = api("GET", f"/repos/{repo}/pulls?state=open&per_page=100&page={page}") - numbers += [p["number"] for p in batch] - if len(batch) < 100: - return numbers - page += 1 + answer = api("POST", "/graphql", {"query": PULLS_QUERY, + "variables": {"owner": owner, "name": name, "after": after}}) + if answer.get("errors") or not (answer.get("data") or {}).get("repository"): + raise ApiError(200, json.dumps(answer.get("errors"))[:300]) # GraphQL reports its errors in the body + page = answer["data"]["repository"]["pullRequests"] + for node in page["nodes"]: + labeled = any(label.get("name") == LABEL for label in node["labels"]["nodes"]) + pulls[node["number"]] = (MERGEABLE.get(node["mergeable"]), labeled) + if not page["pageInfo"]["hasNextPage"]: + return pulls + after = page["pageInfo"]["endCursor"] def ensure_label(api, repo): @@ -91,8 +117,14 @@ def apply(api, repo, number, action): raise -def run(api, repo, numbers, dry_run=False, attempts=4, wait=10.0, sleep=time.sleep, out=print): - """Label or unlabel each pull request of `numbers`. Returns {'add': [...], 'remove': [...], 'unknown': [...]}.""" +def run(api, repo, numbers, dry_run=False, attempts=4, wait=None, sleep=time.sleep, out=print, pulls=None): + """Label or unlabel each pull request of `numbers`. Returns {'add': [...], 'remove': [...], 'unknown': [...]}. + + `pulls` is what open_pulls() answered when `numbers` are all the open pull requests: each attempt then reads + them again in pages instead of one request per pull request, LIST_WAIT seconds after the last one (10 seconds + between attempts that ask by number, unless `wait` says otherwise).""" + if wait is None: + wait = 10.0 if pulls is None else LIST_WAIT done = {"add": [], "remove": [], "unknown": []} pending = list(numbers) label_ready = dry_run @@ -100,15 +132,23 @@ def run(api, repo, numbers, dry_run=False, attempts=4, wait=10.0, sleep=time.sle if attempt: sleep(wait) # asking for a pull request starts GitHub's merge computation; give it time unknown = [] + if pulls is not None and attempt: + pulls = open_pulls(api, repo) for number in pending: - pr = api("GET", f"/repos/{repo}/pulls/{number}") - if pr.get("state") != "open": - continue - labeled = any(label.get("name") == LABEL for label in pr.get("labels", [])) - if pr.get("mergeable") is None: + if pulls is None: + pr = api("GET", f"/repos/{repo}/pulls/{number}") + if pr.get("state") != "open": + continue + mergeable = pr.get("mergeable") + labeled = any(label.get("name") == LABEL for label in pr.get("labels", [])) + elif number in pulls: + mergeable, labeled = pulls[number] + else: + continue # closed or merged since it was listed + if mergeable is None: unknown.append(number) continue - action = decide(pr["mergeable"], labeled) + action = decide(mergeable, labeled) if action is None: continue out(f"#{number}: {action} '{LABEL}'" + (" (dry run)" if dry_run else "")) @@ -137,8 +177,9 @@ def main(argv=None): if not args.repo or not token: ap.error("needs --repo (or GITHUB_REPOSITORY) and GITHUB_TOKEN (or GH_TOKEN)") api = github_api(token) - numbers = args.pr or open_pull_numbers(api, args.repo) - done = run(api, args.repo, numbers, dry_run=args.dry_run) + pulls = None if args.pr else open_pulls(api, args.repo) + numbers = args.pr or sorted(pulls) + done = run(api, args.repo, numbers, dry_run=args.dry_run, pulls=pulls) print(f"{len(numbers)} checked: {len(done['add'])} labeled, {len(done['remove'])} unlabeled, " f"{len(done['unknown'])} not computed yet") return 0