diff --git a/README.md b/README.md index 4e6fbaf0..88691a5f 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,28 @@ coroutines. The [SDK guide](https://proofline.sh/docs/sdks/) and Licensed under the Apache License, Version 2.0. The generated models under `proofline/_generated` carry the MIT license of the generator templates. +## Exports + +`export_reviews` reads one CSV or NDJSON page through the existing bounded transport. +It returns the original text, decoded rows, dataset version, settled horizon and +optional next cursor. CSV cells remain strings, including nested JSON cells; +NDJSON retains JSON values. Export tokens need `analytics:read`. +Repeat with the returned cursor and the same dataset, window, format and grouping. +A missing next cursor marks the last page. Each CSV page includes its own header. + +```python +from uuid import UUID + +with ProoflineClient() as client: + page = client.export_reviews( + UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]), "reviews", + from_time="2026-10-01T00:00:00Z", to_time="2026-10-25T00:00:00Z", + format="csv", + ) + print(page.text, end="") + # Continue with cursor=page.next_cursor when it is not None. +``` + ## Coverage uploads Use a repository-restricted token with `coverage:write` and current repository write diff --git a/proofline/__init__.py b/proofline/__init__.py index 4a7d3a52..4d2f1ee6 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -32,6 +32,7 @@ from ._transport import VERSION as __version__ from ._transport import ProoflineError from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters +from .exports import ExportDataset, ExportFormat, ExportPage from .outcomes import AssessmentGap, CheckGap, ReviewOutcome __all__ = [ @@ -47,6 +48,9 @@ "CustomerAssessmentDetail", "CustomerFinding", "CustomerReviewDetail", + "ExportDataset", + "ExportFormat", + "ExportPage", "FileReviewRequest", "FileReviewResponse", "PatchReviewRequest", diff --git a/proofline/_transport.py b/proofline/_transport.py index 0eabf2fa..eea1d28d 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -21,7 +21,7 @@ from ._sync_http import IO_DEADLINE from ._sync_http import Transport as SyncHTTPTransport -VERSION = "1.0.0" +VERSION = "1.0.1" MAX_RESPONSE_BYTES = 8 * 1024 * 1024 WEEKDAY = r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)" FULL_WEEKDAY = r"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)" diff --git a/proofline/client.py b/proofline/client.py index 8c0b4eb6..cdd4554b 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -69,6 +69,7 @@ from ._generated.models.stop_response import StopResponse from ._generated.types import UNSET, Response, Unset from ._transport import ProoflineError +from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .outcomes import ReviewOutcome, outcome T = TypeVar("T") @@ -246,6 +247,43 @@ def _call( except Exception: raise _malformed() from None + def export_reviews( + self, + organization_id: UUID, + dataset: ExportDataset, + *, + from_time: str, + to_time: str, + format: ExportFormat = "ndjson", + cursor: str | None = None, + group_by: str | None = None, + ) -> ExportPage: + """Read one export page. Repeat with next_cursor and the same filters.""" + if dataset not in ( + "reviews", + "finding_outcomes", + "finding_validations", + "spend", + "findings", + ): + raise ValueError("Unknown export dataset.") + if format not in ("csv", "ndjson"): + raise ValueError("Export format must be csv or ndjson.") + params = {"from": from_time, "to": to_time, "format": format} + if cursor is not None: + params["cursor"] = cursor + if group_by is not None: + params["group_by"] = group_by + try: + response = self._http.get( + f"/api/v1/organizations/{organization_id}/exports/{dataset}", + params=params, + headers={"Accept": "text/csv" if format == "csv" else "application/x-ndjson"}, + ) + return decode_export(response, format) + except httpx.HTTPError as error: + raise _network(error) from None + def list_reviews(self, organization_id: UUID, **filters: Unpack[ReviewFilters]) -> ReviewPage: return self._call(list_reviews.sync_detailed, ReviewPage, organization_id, **filters) @@ -541,6 +579,43 @@ async def _call( except Exception: raise _malformed() from None + async def export_reviews( + self, + organization_id: UUID, + dataset: ExportDataset, + *, + from_time: str, + to_time: str, + format: ExportFormat = "ndjson", + cursor: str | None = None, + group_by: str | None = None, + ) -> ExportPage: + """Read one export page. Repeat with next_cursor and the same filters.""" + if dataset not in ( + "reviews", + "finding_outcomes", + "finding_validations", + "spend", + "findings", + ): + raise ValueError("Unknown export dataset.") + if format not in ("csv", "ndjson"): + raise ValueError("Export format must be csv or ndjson.") + params = {"from": from_time, "to": to_time, "format": format} + if cursor is not None: + params["cursor"] = cursor + if group_by is not None: + params["group_by"] = group_by + try: + response = await self._http.get( + f"/api/v1/organizations/{organization_id}/exports/{dataset}", + params=params, + headers={"Accept": "text/csv" if format == "csv" else "application/x-ndjson"}, + ) + return decode_export(response, format) + except httpx.HTTPError as error: + raise _network(error) from None + async def list_reviews( self, organization_id: UUID, **filters: Unpack[ReviewFilters] ) -> ReviewPage: diff --git a/proofline/exports.py b/proofline/exports.py new file mode 100644 index 00000000..a274dd23 --- /dev/null +++ b/proofline/exports.py @@ -0,0 +1,62 @@ +"""Bounded export pages, with their original text and continuation metadata.""" + +from __future__ import annotations + +import csv +import io +import json +from dataclasses import dataclass +from datetime import datetime +from typing import Any, Literal + +import httpx + +from ._transport import ProoflineError + +ExportDataset = Literal["reviews", "finding_outcomes", "finding_validations", "spend", "findings"] +ExportFormat = Literal["csv", "ndjson"] + + +@dataclass(frozen=True) +class ExportPage: + format: ExportFormat + text: str + rows: list[dict[str, Any]] + version: int + settled_until: str + next_cursor: str | None + + +def decode_export(response: httpx.Response, format: ExportFormat) -> ExportPage: + try: + media = "text/csv" if format == "csv" else "application/x-ndjson" + if ( + response.headers.get("content-type", "").split(";")[0].strip() != media + or response.headers.get("x-proofline-export-version") != "1" + ): + raise ValueError + horizon = response.headers["x-proofline-export-settled-until"] + if datetime.fromisoformat(horizon.replace("Z", "+00:00")).tzinfo is None: + raise ValueError + text = response.content.decode("utf-8") + if format == "csv": + records = list(csv.reader(io.StringIO(text, newline=""), strict=True)) + columns = records.pop(0) + if len(set(columns)) != len(columns) or any( + len(row) != len(columns) for row in records + ): + raise ValueError + rows = [dict(zip(columns, row, strict=True)) for row in records] + else: + rows = [json.loads(line) for line in text.splitlines() if line.strip()] + if any(not isinstance(row, dict) or str(row.get("dataset_version")) != "1" for row in rows): + raise ValueError + return ExportPage( + format, text, rows, 1, horizon, response.headers.get("x-proofline-export-next-cursor") + ) + except (ValueError, KeyError, IndexError, UnicodeError, csv.Error): + raise ProoflineError( + response.status_code, + "urn:proofline:sdk:invalid-response", + "The export body or metadata is invalid.", + ) from None diff --git a/pyproject.toml b/pyproject.toml index 1b8debba..e6f12097 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "proofline-sdk" -version = "1.0.0" +version = "1.0.1" description = "Typed synchronous and asynchronous clients for the Proofline review API" readme = "README.md" license = "Apache-2.0 AND MIT" diff --git a/scripts/contracts.py b/scripts/contracts.py index 3b3e7378..e681909c 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -42,8 +42,9 @@ def main() -> None: if isinstance(node, ast.ClassDef) and node.name in {"ProoflineClient", "AsyncProoflineClient"} } - if clients != {"ProoflineClient": declared, "AsyncProoflineClient": declared}: - raise SystemExit("Both client facades must expose exactly the generated public operations.") + public = declared | {"export_reviews"} + if clients != {"ProoflineClient": public, "AsyncProoflineClient": public}: + raise SystemExit("Both client facades must expose the JSON operations and metadata export.") prohibited = {"safe", "passed", "clean"} for path in (ROOT / "proofline").rglob("*.py"): for node in ast.walk(ast.parse(path.read_text())): diff --git a/scripts/generate.py b/scripts/generate.py index 7aaed9b0..4f246ea8 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -84,8 +84,12 @@ def generate(destination: Path) -> None: raise SystemExit(f"Generation requires ruff=={RUFF_VERSION}.") version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"] document = json.loads(DOCUMENT.read_text()) - if document["info"]["version"] != version: - raise SystemExit("The SDK version must match the public API version.") + package_version = tuple(map(int, version.split("."))) + api_version = tuple(map(int, document["info"]["version"].split("."))) + if package_version[:2] != api_version[:2] or package_version[2] < api_version[2]: + raise SystemExit( + "The SDK must follow the public API major/minor and not precede its patch." + ) env = dict(os.environ) env["PATH"] = str(Path(sys.executable).parent) + os.pathsep + env.get("PATH", "") with tempfile.TemporaryDirectory(prefix="proofline-json-contract-") as temporary: diff --git a/scripts/install_smoke.py b/scripts/install_smoke.py index 77e12a66..821c5017 100644 --- a/scripts/install_smoke.py +++ b/scripts/install_smoke.py @@ -24,8 +24,8 @@ def main() -> None: if not Path(proofline.__file__).resolve().is_relative_to(Path(sys.prefix).resolve()): raise SystemExit("The smoke test must import the installed artifact, not checkout source.") - assert importlib.metadata.version("proofline-sdk") == "1.0.0" - assert proofline.__version__ == "1.0.0" + assert importlib.metadata.version("proofline-sdk") == "1.0.1" + assert proofline.__version__ == "1.0.1" calls: list[str] = [] finding = { "id": str(FINDING), @@ -79,7 +79,7 @@ def log_message(self, format: str, *args: object) -> None: def do_GET(self) -> None: assert self.headers["Authorization"] == f"Bearer {TOKEN}" - assert self.headers["User-Agent"] == "proofline-python/1.0.0" + assert self.headers["User-Agent"] == "proofline-python/1.0.1" calls.append(self.path) body = finding if "/findings/" in self.path else review payload = json.dumps(body).encode() diff --git a/tests/http_server.py b/tests/http_server.py index 05cc078c..455674f7 100644 --- a/tests/http_server.py +++ b/tests/http_server.py @@ -68,7 +68,8 @@ def dispatch(self) -> None: ) time.sleep(reply.header_pause) self.send_response(reply.status) - self.send_header("Content-Type", "application/json") + if "Content-Type" not in reply.headers: + self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(payload))) for key, value in reply.headers.items(): self.send_header(key, value) diff --git a/tests/test_http.py b/tests/test_http.py index f44e157d..e9a20751 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -281,7 +281,7 @@ def respond(request: Request, index: int) -> Reply: assert len({request.peer_port for request in server.requests}) == 1 for request in server.requests: assert request.headers["Authorization"] == f"Bearer {TOKEN}" - assert request.headers["User-Agent"] == "proofline-python/1.0.0" + assert request.headers["User-Agent"] == "proofline-python/1.0.1" assert request.headers["Accept-Encoding"] == "identity" assert "Cookie" not in request.headers assert "Content-Type" not in request.headers @@ -1332,3 +1332,42 @@ def test_token_environment_and_https_origin_rejection(monkeypatch: pytest.Monkey ProoflineClient(TOKEN, base_url=origin) with ProoflineClient(TOKEN, base_url="http://[::1]:8080"): pass + + +@MODES +async def test_export_pages_preserve_csv_and_refuse_foreign_cursor(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + query = parse_qs(urlsplit(request.path).query) + assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/findings?") + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + if query.get("cursor") == ["refused"]: + return Reply(status=404, body={"detail": "not found"}) + is_csv = query.get("format") == ["csv"] + return Reply( + body=( + b'dataset_version,claim\r\n1,"comma, quote "" and\nnewline"\r\n' + if is_csv + else b'{"dataset_version":1,"claim":"hello"}\n' + ), + headers={ + "Content-Type": "text/csv" if is_csv else "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + "X-Proofline-Export-Next-Cursor": "opaque/+cursor", + }, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + kwargs = {"from_time": "2026-10-01T00:00:00Z", "to_time": "2026-10-25T00:00:00Z"} + exported = await call(client, "export_reviews", ORG, "findings", format="csv", **kwargs) + assert exported.rows[0]["claim"] == 'comma, quote " and\nnewline' + assert exported.next_cursor == "opaque/+cursor" + exported = await call( + client, "export_reviews", ORG, "findings", cursor=exported.next_cursor, **kwargs + ) + assert exported.rows[0]["dataset_version"] == 1 + assert "cursor=opaque%2F%2Bcursor" in server.requests[1].path + with pytest.raises(ProoflineError) as caught: + await call(client, "export_reviews", ORG, "findings", cursor="refused", **kwargs) + assert caught.value.status == 404