From 515eeab97207fd0c9bd773d42a1640f89b1a79b3 Mon Sep 17 00:00:00 2001 From: Josh Mabry Date: Sun, 25 Oct 2026 18:30:59 -0700 Subject: [PATCH] feat: github view data: detail.py foundation + gated GET /detail/pr route (read-only) --- api.py | 9 ++ detail.py | 126 ++++++++++++++++++++ tests/test_detail_routes.py | 231 ++++++++++++++++++++++++++++++++++++ 3 files changed, 366 insertions(+) create mode 100644 detail.py create mode 100644 tests/test_detail_routes.py diff --git a/api.py b/api.py index 35fe1f4..aeb59be 100644 --- a/api.py +++ b/api.py @@ -198,6 +198,15 @@ async def _issues(repo: str, state: str = "open") -> dict: async def _prs(repo: str, state: str = "open") -> dict: return await fetch_prs(repo, state) + @router.get("/detail/pr") + async def _detail_pr(repo: str, number: int, fresh: int = 0) -> dict: + """One PR's full detail object (``detail.fetch_pr_detail``) — read-only; memoised + a few seconds (``fresh=1`` bypasses the cache). A bad repo / non-positive number + is ``{"error"}`` without touching `gh`.""" + from .detail import fetch_pr_detail + + return await fetch_pr_detail(repo, number, fresh=bool(fresh)) + @router.post("/issue") async def _create_issue(body: dict = Body(...)) -> dict: resolved = await _resolved() diff --git a/detail.py b/detail.py new file mode 100644 index 0000000..2cc72c9 --- /dev/null +++ b/detail.py @@ -0,0 +1,126 @@ +"""Detail-drawer data — host-free async functions behind the gated data routes. + +The in-console PR/issue drawer (epic bd-nm78) needs the FULL object for one PR or +issue, not the lean board row ``api.fetch_prs`` returns. These functions are the data +foundation the drawer cards build on; this card adds the PR detail + its route only +(no UI, no write routes). + +Same contract as ``api.fetch_prs``: every `gh` call goes through ``run_gh``, the repo +is validated with ``bad_repo``, failures are classified with ``check_gh_error``, the +body is parsed with ``parse_json``, and each function returns a ``dict`` (the parsed +object) or ``{"error": "..."}`` — never raises. ``number`` must be a positive int; +anything else is an ``{"error"}`` returned WITHOUT calling `gh`. + +A small in-process TTL cache (``cached``) memoises a detail read for a few seconds, so +the drawer's open + its immediate refreshes don't each fork `gh`. Error results are +never cached, and a caller passes ``fresh=True`` to bypass a live entry. +""" + +from __future__ import annotations + +import time +from collections.abc import Awaitable, Callable + +from .gh_cli import bad_repo, check_gh_error, parse_json, run_gh + +# The JSON fields the drawer needs for one PR — the full merge-readiness picture plus +# the metadata the UI renders (labels / assignees / milestone / review requests / +# linked issues). All verified against `gh pr view --json` on this gh (see the PR body). +_PR_DETAIL_FIELDS = ( + "number,title,state,isDraft,author,body,url,createdAt,updatedAt," + "headRefName,baseRefName,labels,assignees,milestone,reviewRequests," + "reviewDecision,mergeable,mergeStateStatus,latestReviews,additions," + "deletions,changedFiles,files,closingIssuesReferences" +) + +# A PR body can be large; cap what we hand the drawer (and flag the cut) so one giant +# description can't blow the response budget. Matches read_tools._MAX_BODY_CHARS. +_MAX_BODY_CHARS = 60000 + +_DEFAULT_TTL = 15 # seconds — a drawer open + its reflexive refreshes share one `gh` call. + + +# ── the TTL cache ────────────────────────────────────────────────────────────────── + +# key (e.g. ("pr", repo, number)) -> (expiry_monotonic, value). Process-wide and tiny; +# detail reads are bursty (open the drawer, refresh it) and cheap to recompute on miss. +_CACHE: dict[tuple, tuple[float, dict]] = {} + + +def _now() -> float: + """Monotonic clock — never goes backwards on a wall-clock adjustment (patched in tests).""" + return time.monotonic() + + +def clear_cache() -> None: + """Drop every cached entry (tests; a config change that should invalidate reads).""" + _CACHE.clear() + + +async def cached( + key: tuple, + coro_fn: Callable[[], Awaitable[dict]], + ttl: int = _DEFAULT_TTL, + *, + fresh: bool = False, +) -> dict: + """Memoise ``coro_fn()``'s dict result under ``key`` for ``ttl`` seconds. + + - a live entry is returned without awaiting ``coro_fn`` (ONE `gh` call per window); + - an ERROR result (a dict carrying ``"error"``) is never cached — a transient + failure must not pin a drawer to a stale error for the whole TTL; + - ``fresh=True`` bypasses a live entry (and refreshes it from ``coro_fn``). + """ + if not fresh: + hit = _CACHE.get(key) + if hit is not None: + expiry, value = hit + if expiry > _now(): + return value + del _CACHE[key] # expired — fall through and recompute + value = await coro_fn() + if isinstance(value, dict) and "error" not in value: + _CACHE[key] = (_now() + ttl, value) + return value + + +# ── PR detail ─────────────────────────────────────────────────────────────────────── + + +def _positive_int(value) -> bool: + """True only for a real positive int — ``bool`` (an int subclass) and 0/negatives are out.""" + return isinstance(value, int) and not isinstance(value, bool) and value > 0 + + +async def fetch_pr_detail(repo: str, number: int, fresh: bool = False) -> dict: + """The full detail object for ONE pull request as a dict (or ``{"error": "..."}``). + + One ``gh pr view N --repo o/n --json `` call; the parsed dict carries the + merge-readiness picture (``mergeable`` / ``mergeStateStatus`` / ``reviewDecision`` / + ``latestReviews``) and the metadata the drawer renders (labels / assignees / + milestone / review requests / linked issues / files). The body is capped at + 60000 chars with ``body_truncated: true`` set when it's cut. + + Validated and bounded like ``api.fetch_prs``: a bad repo or a non-positive-int + ``number`` is an ``{"error"}`` returned WITHOUT calling `gh`. Memoised through + ``cached`` (``("pr", repo, number)``); ``fresh=True`` bypasses the cache. + """ + if err := bad_repo(repo): + return {"error": err} + if not _positive_int(number): + return {"error": f"Error: PR number must be a positive integer (got {number!r})."} + + async def _run() -> dict: + rc, out, serr = await run_gh(["pr", "view", str(number), "--repo", repo, "--json", _PR_DETAIL_FIELDS]) + if gh_err := check_gh_error(rc, serr, repo=repo): + return {"error": gh_err} + d, perr = parse_json(out, dict) # a non-dict body is an error, never a crash + if perr: + return {"error": perr} + body = d.get("body") + if isinstance(body, str) and len(body) > _MAX_BODY_CHARS: + d["body"] = body[:_MAX_BODY_CHARS] + d["body_truncated"] = True + return d + + return await cached(("pr", repo, number), _run, fresh=fresh) diff --git a/tests/test_detail_routes.py b/tests/test_detail_routes.py new file mode 100644 index 0000000..ff8f7dc --- /dev/null +++ b/tests/test_detail_routes.py @@ -0,0 +1,231 @@ +"""The detail-drawer data foundation — `detail.fetch_pr_detail` + its gated route. + +The data function is tested directly with `run_gh` mocked (argv + bounding + the TTL +cache); the route is tested through FastAPI's TestClient under its real gated prefix, +the same host-free pattern as test_board_view.py. +""" + +from __future__ import annotations + +import json +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from ghplugin.api import build_data_router +from ghplugin.detail import cached, clear_cache, fetch_pr_detail + +_CFG = {"repos": ["o/n"], "default_repo": "o/n"} + +# A representative `gh pr view --json` body — enough to assert the merge-readiness +# picture and metadata survive the round-trip unchanged. +_PR = { + "number": 5, + "title": "Add the drawer", + "state": "OPEN", + "isDraft": False, + "author": {"login": "kj"}, + "body": "## What\nA PR body.", + "url": "https://github.com/o/n/pull/5", + "reviewDecision": "APPROVED", + "mergeable": "MERGEABLE", + "mergeStateStatus": "CLEAN", + "latestReviews": [{"author": {"login": "rev"}, "state": "APPROVED"}], + "files": [{"path": "detail.py", "additions": 100, "deletions": 0}], + "labels": [{"name": "enhancement"}], + "assignees": [{"login": "kj"}], +} + + +@pytest.fixture(autouse=True) +def _clear_detail_cache(): + """The TTL cache is process-wide — isolate every test from its neighbours.""" + clear_cache() + yield + clear_cache() + + +def _app(cfg=None): + app = FastAPI() + app.include_router(build_data_router(cfg or _CFG), prefix="/api/plugins/github") + return app + + +# --- fetch_pr_detail: argv + parse (r1) -------------------------------------- + + +async def test_fetch_pr_detail_one_call_and_full_object(): + fake = AsyncMock(return_value=(0, json.dumps(_PR), "")) + with patch("ghplugin.detail.run_gh", fake): + out = await fetch_pr_detail("o/n", 5) + # The full object comes back — the merge-readiness picture + metadata, not a lean row. + assert out["mergeable"] == "MERGEABLE" + assert out["mergeStateStatus"] == "CLEAN" + assert out["reviewDecision"] == "APPROVED" + assert out["latestReviews"][0]["state"] == "APPROVED" + assert out["files"][0]["path"] == "detail.py" + # Exactly one `gh pr view` call, argv asserted. + fake.assert_called_once() + args = fake.call_args.args[0] + assert args[:6] == ["pr", "view", "5", "--repo", "o/n", "--json"] + fields = args[6] + for f in ( + "mergeable", + "mergeStateStatus", + "reviewDecision", + "latestReviews", + "files", + "closingIssuesReferences", + "milestone", + "reviewRequests", + ): + assert f in fields + + +def test_detail_pr_route_returns_parsed_dict(): + fake = AsyncMock(return_value=(0, json.dumps(_PR), "")) + with patch("ghplugin.detail.run_gh", fake): + body = TestClient(_app()).get("/api/plugins/github/detail/pr", params={"repo": "o/n", "number": 5}).json() + assert body["number"] == 5 and body["mergeStateStatus"] == "CLEAN" + assert body["files"][0]["path"] == "detail.py" + assert fake.call_args.args[0][:3] == ["pr", "view", "5"] + + +# --- validation: no gh call for a bad repo / bad number (r2) ----------------- + + +async def test_bad_repo_and_bad_number_never_call_gh(): + fake = AsyncMock() + with patch("ghplugin.detail.run_gh", fake): + assert "error" in await fetch_pr_detail("nope", 5) # malformed repo + for n in (0, -1, "5", 1.5, True, None): + out = await fetch_pr_detail("o/n", n) + assert "error" in out, f"expected error for number={n!r}" + fake.assert_not_called() + + +def test_route_bad_number_returns_error_and_no_gh_call(): + fake = AsyncMock() + with patch("ghplugin.detail.run_gh", fake): + body = TestClient(_app()).get("/api/plugins/github/detail/pr", params={"repo": "o/n", "number": 0}).json() + assert "error" in body and "positive integer" in body["error"] + fake.assert_not_called() + + +def test_route_bad_repo_returns_error_and_no_gh_call(): + fake = AsyncMock() + with patch("ghplugin.detail.run_gh", fake): + body = TestClient(_app()).get("/api/plugins/github/detail/pr", params={"repo": "bad", "number": 5}).json() + assert "error" in body + fake.assert_not_called() + + +# --- gh failure + a non-dict body are classified, never raise (r3) ----------- + + +async def test_gh_failure_is_classified(): + fake = AsyncMock(return_value=(1, "", "boom")) + with patch("ghplugin.detail.run_gh", fake): + out = await fetch_pr_detail("o/n", 5) + assert out["error"].startswith("Error (gh exit 1)") + + +async def test_non_dict_body_is_an_error_not_a_crash(): + fake = AsyncMock(return_value=(0, "[1, 2, 3]", "")) # gh handed back a list + with patch("ghplugin.detail.run_gh", fake): + out = await fetch_pr_detail("o/n", 5) + assert "error" in out and "expected a JSON dict" in out["error"] + + +async def test_not_found_is_classified(): + fake = AsyncMock(return_value=(1, "", "HTTP 404: Not Found")) + with patch("ghplugin.detail.run_gh", fake): + out = await fetch_pr_detail("o/n", 404) + assert "error" in out and "404" in out["error"] + + +# --- the TTL cache (r4) ------------------------------------------------------ + + +async def test_cache_coalesces_repeated_reads_within_the_window(): + fake = AsyncMock(return_value=(0, json.dumps(_PR), "")) + with patch("ghplugin.detail.run_gh", fake): + a = await fetch_pr_detail("o/n", 5) + b = await fetch_pr_detail("o/n", 5) # within 15s — served from cache + assert a == b + fake.assert_called_once() + + +async def test_error_results_are_never_cached(): + fake = AsyncMock(return_value=(1, "", "transient")) + with patch("ghplugin.detail.run_gh", fake): + await fetch_pr_detail("o/n", 5) + await fetch_pr_detail("o/n", 5) # a cached error would pin the drawer stale + assert fake.call_count == 2 + + +async def test_fresh_bypasses_the_cache(): + fake = AsyncMock(return_value=(0, json.dumps(_PR), "")) + with patch("ghplugin.detail.run_gh", fake): + await fetch_pr_detail("o/n", 5) # warms the cache + await fetch_pr_detail("o/n", 5, fresh=True) # bypasses it + assert fake.call_count == 2 + + +def test_route_fresh_param_bypasses_the_cache(): + fake = AsyncMock(return_value=(0, json.dumps(_PR), "")) + with patch("ghplugin.detail.run_gh", fake): + c = TestClient(_app()) + c.get("/api/plugins/github/detail/pr", params={"repo": "o/n", "number": 5}) + c.get("/api/plugins/github/detail/pr", params={"repo": "o/n", "number": 5}) # cached + c.get("/api/plugins/github/detail/pr", params={"repo": "o/n", "number": 5, "fresh": 1}) # bypass + assert fake.call_count == 2 + + +async def test_expired_entry_is_recomputed(): + """Past the TTL the entry is dropped and `gh` runs again (clock patched forward).""" + fake = AsyncMock(return_value=(0, json.dumps(_PR), "")) + t = [1000.0] + with patch("ghplugin.detail.run_gh", fake), patch("ghplugin.detail._now", lambda: t[0]): + await fetch_pr_detail("o/n", 5) + t[0] += 16 # 16s later — the 15s entry has expired + await fetch_pr_detail("o/n", 5) + assert fake.call_count == 2 + + +async def test_cache_helper_keys_are_independent(): + calls = [] + + async def _one(): + calls.append("one") + return {"v": 1} + + async def _two(): + calls.append("two") + return {"v": 2} + + assert (await cached(("pr", "o/n", 1), _one))["v"] == 1 + assert (await cached(("pr", "o/n", 2), _two))["v"] == 2 + assert (await cached(("pr", "o/n", 1), _one))["v"] == 1 # second (1) is cached + assert calls == ["one", "two"] # _one ran once + + +# --- body cap (r5) ----------------------------------------------------------- + + +async def test_body_over_cap_is_truncated_and_flagged(): + big = {**_PR, "body": "x" * 60001} + fake = AsyncMock(return_value=(0, json.dumps(big), "")) + with patch("ghplugin.detail.run_gh", fake): + out = await fetch_pr_detail("o/n", 5) + assert len(out["body"]) == 60000 + assert out["body_truncated"] is True + + +async def test_body_at_or_under_cap_is_untouched(): + fake = AsyncMock(return_value=(0, json.dumps(_PR), "")) + with patch("ghplugin.detail.run_gh", fake): + out = await fetch_pr_detail("o/n", 5) + assert out["body"] == "## What\nA PR body." + assert "body_truncated" not in out