Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 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 one pull request's review runs 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.

```python
import asyncio
Expand Down Expand Up @@ -102,6 +102,25 @@ the wait returns `TIMED_OUT` immediately.

`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head.

## Listing a pull request's reviews

`list_pull_request_reviews` reads one page of a pull request's review runs. `iter_pull_request_reviews` follows continuation cursors lazily, as `iter_reviews` does, keeping the organization, repository, pull request, and filters on every request.

```python
import os
from uuid import UUID

with ProoflineClient() as client:
for review in client.iter_pull_request_reviews(
UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]),
"owner/name",
42,
):
print(review.id, review.status)
```

Use `async for` with `AsyncProoflineClient`. Pass `filters=` to narrow the runs and `page_size`, `max_pages`, and `max_items` to bound the traversal. An empty or repeated continuation cursor raises `ProoflineError` with type `urn:proofline:sdk:invalid-pagination`, and exhausting the page or item bound while a cursor remains raises `urn:proofline:sdk:pagination-limit`, so a partial traversal never looks complete.

## Review exports

`export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`.
Expand Down
74 changes: 74 additions & 0 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,43 @@ 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 recorded review run of one pull request across pages."""
_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)
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 @@ -936,6 +973,43 @@ 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 recorded review run of one pull request across pages."""
_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)
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
70 changes: 70 additions & 0 deletions tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ async def collect(client: Client, **kwargs: Any) -> list[Any]:
return list(iterator)


async def collect_pr(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)


class Clock:
def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None:
self.now = 100.0
Expand Down Expand Up @@ -1863,6 +1870,69 @@ def respond(request: Request, index: int) -> Reply:
assert raised.value.type == "urn:proofline:sdk:pagination-limit"


@MODES
async def test_pull_request_cursor_pagination_preserves_filters_and_refuses_cycles_or_bounds(
mode: str,
) -> None:
path = f"/api/v1/organizations/{ORG}/reviews/pr/repo%2Fname/42"

def respond(request: Request, index: int) -> Reply:
assert urlsplit(request.path).path == path
assert request.headers["Authorization"] == f"Bearer {TOKEN}"
query = parse_qs(urlsplit(request.path).query)
assert query["repository"] == [str(REPOSITORY)]
assert query["status"] == ["COMPLETED"]
assert query["limit"] == ["2"]
assert query["query"] == [STRUCTURED_QUERY]
assert query["search"] == ["text & space"]
if index == 0:
assert "cursor" not in query
else:
assert query["cursor"] == ["opaque+/cursor"]
return Reply(
body=page(cursor="opaque+/cursor" if index == 0 else None, truncated=index == 0)
)

with Server(respond) as server:
async with session(mode, server.url) as client:
items = await collect_pr(
client,
page_size=2,
filters={
"repository": REPOSITORY,
"status": "COMPLETED",
"query": STRUCTURED_QUERY,
"search": "text & space",
},
)
assert [item.id for item in items] == [REVIEW, REVIEW]
assert len(server.requests) == 2
for cursor in ["repeated", None]:
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_pr(client)
assert raised.value.type == "urn:proofline:sdk:invalid-pagination"
assert len(server.requests) <= 2
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_pr(client, max_pages=2)
assert raised.value.type == "urn:proofline:sdk:pagination-limit"
assert len(server.requests) == 2
two_items = page()
two_items["items"].append(dict(two_items["items"][0]))
with Server(lambda request, index: Reply(body=two_items)) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as raised:
await collect_pr(client, max_items=1, filters={"cursor": "initial"})
assert raised.value.type == "urn:proofline:sdk:pagination-limit"


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