Skip to content
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ with ProoflineClient(os.environ["PROOFLINE_TOKEN"]) as client:

When no token is passed, the clients read `PROOFLINE_TOKEN` from the environment, keep the token in memory, and redact it from diagnostic output.

With `AsyncProoflineClient`, use `await` for a single result, such as `await client.list_reviews(organization_id)` for one page. Use `async for` with `iter_reviews` to read individual reviews across pages, or with `iter_export_pages` to read export pages. The async client supports asyncio and Trio. For a Trio application, install Trio alongside the SDK.
With `AsyncProoflineClient`, use `await` for a single result, such as `await client.list_reviews(organization_id)` for one page. Use `async for` with `iter_reviews` to read individual reviews across pages, with `iter_pull_request_reviews` to read the reviews of one pull request, or with `iter_export_pages` to read export pages. `iter_reviews` and `iter_pull_request_reviews` raise a pagination-limit error once `max_pages` or `max_items` is exceeded, after some items may already have been yielded; `page_size` only sets the size of each request. The async client supports asyncio and Trio. For a Trio application, install Trio alongside the SDK.

```python
import asyncio
Expand Down
106 changes: 87 additions & 19 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,32 @@ def _review_url(base_url: str, organization_id: UUID, review_id: UUID) -> str:


def _page_limits(page_size: int, max_pages: int, max_items: int) -> None:
if not 1 <= page_size <= 100 or not 1 <= max_pages <= 1_000 or not 1 <= max_items <= 100_000:
if (
any(
isinstance(n, bool) or not isinstance(n, int) for n in (page_size, max_pages, max_items)
)
or not 1 <= page_size <= 100
or not 1 <= max_pages <= 1_000
or not 1 <= max_items <= 100_000
):
raise ValueError(
"Pagination requires page_size 1..100, max_pages 1..1000, max_items 1..100000."
)


def _iter_start(
page_size: int, max_pages: int, max_items: int, filters: ReviewFilters | None
) -> tuple[ReviewFilters, set[str]]:
"""Validate the bounds; return a private copy of the filters and the cursors already seen."""
_page_limits(page_size, max_pages, max_items)
params: ReviewFilters = {}
if filters:
params.update(filters)
params["limit"] = page_size
cursor = params.get("cursor")
return params, {cursor} if cursor else set()


def _head_commit(value: str | None) -> None:
# Only a full SHA names one exact commit; a branch or an abbreviation does not.
if value is not None and (
Expand Down Expand Up @@ -516,15 +536,7 @@ def iter_reviews(
max_items: int = 10_000,
filters: ReviewFilters | None = None,
) -> Iterator[ReviewSummary]:
_page_limits(page_size, max_pages, max_items)
params: ReviewFilters = {}
if filters:
params.update(filters)
params["limit"] = page_size
seen: set[str] = set()
cursor = params.get("cursor")
if cursor:
seen.add(cursor)
params, seen = _iter_start(page_size, max_pages, max_items, filters)
count = 0
for _ in range(max_pages):
page = self.list_reviews(organization_id, **params)
Expand All @@ -539,6 +551,38 @@ def iter_reviews(
params["cursor"] = cursor
raise _pagination_limit()

def iter_pull_request_reviews(
self,
organization_id: UUID,
repository: str,
pull_request_number: int,
*,
page_size: int = 100,
max_pages: int = 100,
max_items: int = 10_000,
filters: ReviewFilters | None = None,
) -> Iterator[ReviewSummary]:
"""Stream every review of one pull request, following cursors across pages.

Takes the same bounds and refusals as ``iter_reviews``.
"""
params, seen = _iter_start(page_size, max_pages, max_items, filters)
count = 0
for _ in range(max_pages):
page = self.list_pull_request_reviews(
organization_id, repository, pull_request_number, filters=params
)
for item in page.items:
if count == max_items:
raise _pagination_limit()
yield item
count += 1
cursor = _next_cursor(page, seen)
if cursor is None:
return
params["cursor"] = cursor
raise _pagination_limit()

def wait_for_review(
self,
organization_id: UUID,
Expand Down Expand Up @@ -913,15 +957,7 @@ async def iter_reviews(
max_items: int = 10_000,
filters: ReviewFilters | None = None,
) -> AsyncIterator[ReviewSummary]:
_page_limits(page_size, max_pages, max_items)
params: ReviewFilters = {}
if filters:
params.update(filters)
params["limit"] = page_size
seen: set[str] = set()
cursor = params.get("cursor")
if cursor:
seen.add(cursor)
params, seen = _iter_start(page_size, max_pages, max_items, filters)
count = 0
for _ in range(max_pages):
page = await self.list_reviews(organization_id, **params)
Expand All @@ -936,6 +972,38 @@ async def iter_reviews(
params["cursor"] = cursor
raise _pagination_limit()

async def iter_pull_request_reviews(
self,
organization_id: UUID,
repository: str,
pull_request_number: int,
*,
page_size: int = 100,
max_pages: int = 100,
max_items: int = 10_000,
filters: ReviewFilters | None = None,
) -> AsyncIterator[ReviewSummary]:
"""Stream every review of one pull request, following cursors across pages.

Takes the same bounds and refusals as ``iter_reviews``.
"""
params, seen = _iter_start(page_size, max_pages, max_items, filters)
count = 0
for _ in range(max_pages):
page = await self.list_pull_request_reviews(
organization_id, repository, pull_request_number, filters=params
)
for item in page.items:
if count == max_items:
raise _pagination_limit()
yield item
count += 1
cursor = _next_cursor(page, seen)
if cursor is None:
return
params["cursor"] = cursor
raise _pagination_limit()

async def wait_for_review(
self,
organization_id: UUID,
Expand Down
110 changes: 109 additions & 1 deletion tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
import time
import tomllib
import traceback
from collections.abc import AsyncIterator
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from copy import deepcopy
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -1863,6 +1864,113 @@ def respond(request: Request, index: int) -> Reply:
assert raised.value.type == "urn:proofline:sdk:pagination-limit"


SECOND_REVIEW = "00000000-0000-4000-8000-000000000099"


async def collect_pull_request(client: Client, **kwargs: Any) -> list[Any]:
iterator = client.iter_pull_request_reviews(ORG, "repo/name", 42, **kwargs)
if hasattr(iterator, "__aiter__"):
return [item async for item in iterator]
return list(iterator)


@MODES
async def test_pull_request_review_iterator_follows_cursors_and_preserves_filters(
mode: str,
) -> None:
def respond(request: Request, index: int) -> Reply:
url = urlsplit(request.path)
assert url.path == f"/api/v1/organizations/{ORG}/reviews/pr/repo%2Fname/42"
assert request.headers["Authorization"] == f"Bearer {TOKEN}"
query = parse_qs(url.query)
assert query["repository"] == [str(REPOSITORY)]
assert query["status"] == ["COMPLETED"]
assert query["limit"] == ["2"]
assert query["search"] == ["text & space"]
if index == 0:
assert "cursor" not in query
else:
assert query["cursor"] == ["opaque+/cursor"]
body = page(cursor="opaque+/cursor" if index == 0 else None, truncated=index == 0)
body["items"][0]["id"] = SECOND_REVIEW if index else str(REVIEW)
return Reply(body=body)

with Server(respond) as server:
async with session(mode, server.url) as client:
filters: dict[str, Any] = {
"repository": REPOSITORY,
"status": "COMPLETED",
"search": "text & space",
}
original = deepcopy(filters)
items = await collect_pull_request(client, page_size=2, filters=filters)
assert filters == original
assert [str(item.id) for item in items] == [str(REVIEW), SECOND_REVIEW]
assert len(server.requests) == 2


@MODES
async def test_pull_request_review_iterator_refuses_cycles_and_bounds(mode: str) -> None:
for cursor, requests in [("repeated", 2), (None, 1)]:
with Server(
lambda request, index: Reply(body=page(cursor=cursor, truncated=True))
) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as raised:
await collect_pull_request(client)
assert raised.value.type == "urn:proofline:sdk:invalid-pagination"
assert len(server.requests) == requests
with Server(
lambda request, index: Reply(body=page(cursor=str(index), truncated=True))
) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as raised:
await collect_pull_request(client, max_pages=2)
assert raised.value.type == "urn:proofline:sdk:pagination-limit"
assert len(server.requests) == 2
with Server(
lambda request, index: Reply(body=page(cursor="initial", truncated=True))
) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as raised:
await collect_pull_request(client, filters={"cursor": "initial"})
assert raised.value.type == "urn:proofline:sdk:invalid-pagination"
assert len(server.requests) == 1

def one_item_pages(last: int) -> Callable[[Request, int], Reply]:
return lambda request, index: Reply(
body=page(cursor=None if index == last else f"c{index}", truncated=index != last)
)

# Two items fit under max_items=2; the cap only trips on the third.
with Server(one_item_pages(1)) as server:
async with session(mode, server.url) as client:
assert len(await collect_pull_request(client, max_items=2)) == 2
assert len(server.requests) == 2
with Server(one_item_pages(2)) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as raised:
await collect_pull_request(client, max_items=2)
assert raised.value.type == "urn:proofline:sdk:pagination-limit"
assert len(server.requests) == 3
async with session(mode, "https://unused.example") as client:
with pytest.raises(ValueError):
await collect_pull_request(client, page_size=0)


@MODES
@pytest.mark.parametrize("name", ["page_size", "max_pages", "max_items"])
@pytest.mark.parametrize("bound", [True, 1.5, 2.0, "2"])
async def test_review_iterators_require_integer_bounds(mode: str, name: str, bound: Any) -> None:
with Server(lambda request, index: Reply(body=page())) as server:
async with session(mode, server.url) as client:
with pytest.raises(ValueError, match="Pagination requires"):
await collect(client, **{name: bound})
with pytest.raises(ValueError, match="Pagination requires"):
await collect_pull_request(client, **{name: bound})
assert not server.requests


def test_token_environment_and_https_origin_rejection(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("PROOFLINE_TOKEN", TOKEN)
with ProoflineClient() as client:
Expand Down