Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse): add gitea comments, timeline, reviews and workflow runs tables (#109111)

Tom Owersf4c76982a4b2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 038a646facad..9746921ece2e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3581,10 +3581,10 @@ Today (6): `commits`, `issues`, `labels`, `milestones`, `pull_requests`, `releas
Diffed against: <https://demo.gitea.com/swagger.v1.json>
-- [ ] `/repos/{owner}/{repo}/issues/comments` — repo-wide issue and PR comments in one listable call — the main discussion signal, entirely absent (high)
-- [ ] `/repos/{owner}/{repo}/pulls/{index}/reviews` — PR review verdicts and reviewers, required for any review-throughput analysis (high)
-- [ ] `/repos/{owner}/{repo}/actions/runs` — Gitea Actions CI runs — no CI data is synced at all today (high)
-- [ ] `/repos/{owner}/{repo}/issues/{index}/timeline` — state and assignment transition history behind issue cycle time (high)
+- [x] `/repos/{owner}/{repo}/issues/comments` — repo-wide issue and PR comments in one listable call — the main discussion signal, entirely absent (high)
+- [x] `/repos/{owner}/{repo}/pulls/{index}/reviews` — PR review verdicts and reviewers, required for any review-throughput analysis (high)
+- [x] `/repos/{owner}/{repo}/actions/runs` — Gitea Actions CI runs — no CI data is synced at all today (high)
+- [x] `/repos/{owner}/{repo}/issues/{index}/timeline` — state and assignment transition history behind issue cycle time (high)
- [ ] `/repos/{owner}/{repo}/actions/jobs` — job-level CI granularity for duration and failure attribution (medium)
- [ ] `/repos/{owner}/{repo}/branches` — branch inventory with protection and last-commit metadata (medium)
- [ ] `/repos/{owner}/{repo}/tags` — git tags — releases are synced but the underlying tags are not (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/canonical_descriptions.py
index ae17c9297c75..b87e5af518b6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/canonical_descriptions.py
@@ -118,4 +118,83 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"closed_at": "When the milestone was closed, if it is closed.",
},
},
+ "issue_comments": {
+ "description": "Comments on issues and pull requests in the repository.",
+ "docs_url": "https://docs.gitea.com/api/1.24/#tag/issue/operation/issueGetRepoComments",
+ "columns": {
+ "id": "Unique identifier of the comment across the Gitea instance.",
+ "issue_number": "Number of the issue or pull request the comment belongs to.",
+ "body": "Comment text in Markdown.",
+ "user": "User who wrote the comment.",
+ "original_author": "Author name from the original platform, for comments migrated into Gitea.",
+ "assets": "Files attached to the comment.",
+ "issue_url": "API URL of the issue the comment belongs to. Empty for pull request comments.",
+ "pull_request_url": "API URL of the pull request the comment belongs to. Empty for issue comments.",
+ "html_url": "Web URL of the comment on the Gitea instance.",
+ "created_at": "When the comment was created.",
+ "updated_at": "When the comment was last updated.",
+ },
+ },
+ "issue_timeline": {
+ "description": "Every event on the repository's issues: comments, state changes, label, assignee, and milestone changes, references, and more.",
+ "docs_url": "https://docs.gitea.com/api/1.24/#tag/issue/operation/issueGetCommentsAndTimeline",
+ "columns": {
+ "id": "Unique identifier of the timeline event across the Gitea instance.",
+ "issue_number": "Number of the issue the event belongs to.",
+ "type": "Kind of event, e.g. comment, close, reopen, label, assignees, milestone, or change_title.",
+ "user": "User who caused the event.",
+ "body": "Comment text for comment events.",
+ "assignee": "User assigned or unassigned by an assignee event.",
+ "removed_assignee": "Whether an assignee event removed the assignee instead of adding one.",
+ "label": "Label added or removed by a label event.",
+ "milestone": "Milestone set by a milestone event.",
+ "old_milestone": "Milestone replaced by a milestone event.",
+ "old_title": "Previous title for a title change event.",
+ "new_title": "New title for a title change event.",
+ "ref_issue": "Issue or pull request that referenced this issue.",
+ "ref_commit_sha": "Commit that referenced this issue.",
+ "created_at": "When the event happened.",
+ "updated_at": "When the event was last updated.",
+ },
+ },
+ "reviews": {
+ "description": "Reviews submitted on the repository's pull requests.",
+ "docs_url": "https://docs.gitea.com/api/1.24/#tag/repository/operation/repoListPullReviews",
+ "columns": {
+ "id": "Unique identifier of the review across the Gitea instance.",
+ "pull_request_number": "Number of the pull request the review belongs to.",
+ "user": "User who submitted the review.",
+ "state": "Review verdict: APPROVED, REQUEST_CHANGES, COMMENT, PENDING, or REQUEST_REVIEW.",
+ "body": "Review summary text in Markdown.",
+ "commit_id": "SHA of the commit the review was made against.",
+ "comments_count": "Number of line comments in the review.",
+ "official": "Whether the review counts toward the branch protection approval rules.",
+ "stale": "Whether new commits were pushed after the review.",
+ "dismissed": "Whether the review was dismissed.",
+ "submitted_at": "When the review was submitted.",
+ "updated_at": "When the review was last updated.",
+ "html_url": "Web URL of the review on the Gitea instance.",
+ },
+ },
+ "workflow_runs": {
+ "description": "Gitea Actions workflow runs in the repository. Needs Gitea 1.25 or later.",
+ "docs_url": "https://docs.gitea.com/api/1.25/#tag/repository/operation/getWorkflowRuns",
+ "columns": {
+ "id": "Unique identifier of the workflow run.",
+ "run_number": "Sequential number of the run within the repository.",
+ "run_attempt": "Attempt number of the run, incremented on each re-run.",
+ "display_title": "Title shown for the run.",
+ "path": "Workflow file and the ref the run was for, as `<workflow>@<ref>`.",
+ "event": "Event that triggered the run, e.g. push or pull_request.",
+ "status": "Run status: queued, waiting, in_progress, or completed.",
+ "conclusion": "Run result once completed: success, failure, cancelled, or skipped.",
+ "head_branch": "Branch the run was triggered on.",
+ "head_sha": "SHA of the commit the run was triggered on.",
+ "actor": "User whose action triggered the run.",
+ "trigger_actor": "User who started the current attempt of the run.",
+ "started_at": "When the current attempt of the run started.",
+ "completed_at": "When the current attempt of the run completed.",
+ "html_url": "Web URL of the run on the Gitea instance.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/gitea.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/gitea.py
index f3a7755cc8e9..e4f3a19fbdb3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/gitea.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/gitea.py
@@ -3,7 +3,7 @@ import dataclasses
from collections.abc import AsyncIterator, Callable, Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
-from urllib.parse import urlencode, urlparse
+from urllib.parse import parse_qsl, urlencode, urlparse
import pyarrow as pa
import requests
@@ -11,6 +11,8 @@ from asgiref.sync import async_to_sync
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
ExternalWebhookInfo,
WebhookCreationResult,
@@ -42,7 +44,7 @@ class GiteaRetryableError(Exception):
pass
[email protected](frozen=True)
class GiteaResumeConfig:
next_url: str
@@ -126,6 +128,52 @@ def _parse_next_url(link_header: str) -> str | None:
return None
+def _parse_total_count(response: requests.Response, data: Any) -> int | None:
+ total: Any = data.get("total_count") if isinstance(data, dict) else response.headers.get("X-Total-Count")
+ try:
+ return int(total)
+ except (TypeError, ValueError):
+ return None
+
+
+def _with_page(url: str, page: int) -> str:
+ parsed = urlparse(url)
+ params = [(key, value) for key, value in parse_qsl(parsed.query) if key != "page"]
+ params.append(("page", str(page)))
+ return parsed._replace(query=urlencode(params)).geturl()
+
+
+def _next_page_url(
+ config: GiteaEndpointConfig,
+ url: str,
+ response: requests.Response,
+ data: Any,
+ page_length: int,
+ largest_page_length: int,
+) -> str | None:
+ if config.pagination == "link_header":
+ return _parse_next_url(response.headers.get("Link", ""))
+ if config.pagination == "unpaged":
+ return None
+
+ page = int(dict(parse_qsl(urlparse(url).query)).get("page") or 1)
+ total = _parse_total_count(response, data)
+ if total is None:
+ return None if page_length == 0 else _with_page(url, page + 1)
+ # Visible rows are a conservative proxy for the server's possibly-clamped page size.
+ # Falling back to one also bounds a walk whose backing rows are all filtered out.
+ effective_page_length = max(largest_page_length, 1)
+ if (page - 1) * effective_page_length + page_length >= total:
+ return None
+ return _with_page(url, page + 1)
+
+
+@frozen
+class _Page:
+ rows: list[dict[str, Any]]
+ next_url: str | None
+
+
def _format_timestamp(value: Any) -> str:
"""Format an incremental cursor as the RFC 3339 Z form Gitea's `since` expects."""
if isinstance(value, datetime):
@@ -142,14 +190,18 @@ def _build_initial_url(
repository: str,
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
+ index: int | None = None,
) -> str:
- params: dict[str, Any] = {"limit": PAGE_SIZE, **config.extra_params}
+ params: dict[str, Any] = {**config.extra_params}
+ if config.pagination != "unpaged":
+ params["limit"] = PAGE_SIZE
# `since` is inclusive, so the boundary row is re-fetched and deduped by primary key
# on merge — safer than missing a row updated in the same second as the watermark.
if config.supports_since and should_use_incremental_field and db_incremental_field_last_value is not None:
params["since"] = _format_timestamp(db_incremental_field_last_value)
- path = config.path.format(repository=repository)
- return f"{_api_url(base_url, path)}?{urlencode(params)}"
+ path = config.path.format(repository=repository, index=index)
+ url = _api_url(base_url, path)
+ return f"{url}?{urlencode(params)}" if params else url
def validate_credentials(base_url: str, access_token: str, repository: str) -> tuple[bool, str | None]:
@@ -204,9 +256,20 @@ def _flatten_commit(item: dict[str, Any]) -> dict[str, Any]:
return item
+def _add_comment_issue_number(item: dict[str, Any]) -> dict[str, Any]:
+ """Derive the issue or pull request number from the comment's URL, as the list carries no
+ other reference to it. Pull request comments leave issue_url empty."""
+ url = item.get("issue_url") or item.get("pull_request_url")
+ tail = url.rstrip("/").rsplit("/", 1)[-1] if isinstance(url, str) else ""
+ item["issue_number"] = int(tail) if tail.isdigit() else None
+ return item
+
+
def _get_item_mapper(endpoint: str) -> Callable[[dict[str, Any]], dict[str, Any]] | None:
if endpoint == "commits":
return _flatten_commit
+ if endpoint == "issue_comments":
+ return _add_comment_issue_number
return None
@@ -241,6 +304,82 @@ def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogge
return response
+def _iter_pages(
+ session: requests.Session,
+ url: str,
+ config: GiteaEndpointConfig,
+ base_url: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[_Page]:
+ """Yield each page and its successor URL, starting from ``url``."""
+ largest_page_length = 0
+ while True:
+ response = _fetch_page(session, url, logger)
+ data = response.json()
+ items = data.get(config.data_selector) if config.data_selector and isinstance(data, dict) else data
+ if not isinstance(items, list):
+ return
+
+ largest_page_length = max(largest_page_length, len(items))
+ next_url = _next_page_url(config, url, response, data, len(items), largest_page_length)
+ if next_url is not None:
+ next_url = _pinned_url(base_url, next_url)
+
+ yield _Page(rows=[item for item in items if isinstance(item, dict)], next_url=next_url)
+
+ if not next_url:
+ return
+ url = next_url
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ base_url: str,
+ repository: str,
+ config: GiteaEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GiteaResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ assert config.parent is not None and config.parent_number_column is not None
+ parent_config = GITEA_ENDPOINTS[config.parent]
+
+ # Resume state holds the next parent page: every child of the pages before it is written.
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ parent_url = _pinned_url(base_url, resume_config.next_url)
+ logger.debug(f"Gitea: resuming {config.name} fan-out from parent URL: {parent_url}")
+ else:
+ parent_url = _build_initial_url(
+ parent_config, base_url, repository, should_use_incremental_field, db_incremental_field_last_value
+ )
+
+ for parent_page in _iter_pages(session, parent_url, parent_config, base_url, logger):
+ for parent in parent_page.rows:
+ number = parent.get("number")
+ if not isinstance(number, int):
+ continue
+ child_url = _build_initial_url(
+ config, base_url, repository, should_use_incremental_field, db_incremental_field_last_value, number
+ )
+ try:
+ for child_page in _iter_pages(session, child_url, config, base_url, logger):
+ for row in child_page.rows:
+ row[config.parent_number_column] = number
+ if child_page.rows:
+ yield child_page.rows
+ except requests.HTTPError as e:
+ # The parent was deleted after the parent page was listed.
+ if e.response is not None and e.response.status_code == 404:
+ logger.debug(f"Gitea: {config.parent} #{number} not found, skipping {config.name}")
+ continue
+ raise
+
+ if parent_page.next_url:
+ resumable_source_manager.save_state(GiteaResumeConfig(next_url=parent_page.next_url))
+
+
def get_rows(
base_url: str,
access_token: str,
@@ -253,6 +392,20 @@ def get_rows(
) -> Iterator[list[dict[str, Any]]]:
config = GITEA_ENDPOINTS[endpoint]
session = _get_session(access_token)
+
+ if config.parent is not None:
+ yield from _get_fan_out_rows(
+ session,
+ base_url,
+ repository,
+ config,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ return
+
item_mapper = _get_item_mapper(endpoint)
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
@@ -264,27 +417,20 @@ def get_rows(
config, base_url, repository, should_use_incremental_field, db_incremental_field_last_value
)
- while True:
- response = _fetch_page(session, url, logger)
- data = response.json()
- if not isinstance(data, list) or not data:
- return
-
- rows = [item_mapper(item) if item_mapper else item for item in data if isinstance(item, dict)]
- next_url = _parse_next_url(response.headers.get("Link", ""))
- if next_url is not None:
- next_url = _pinned_url(base_url, next_url)
-
- if rows:
- yield rows
-
- if not next_url:
- return
-
- # Save state AFTER yielding so a crash re-yields the in-flight page
- # (merge dedupes on primary key).
- resumable_source_manager.save_state(GiteaResumeConfig(next_url=next_url))
- url = next_url
+ try:
+ for page in _iter_pages(session, url, config, base_url, logger):
+ rows = [item_mapper(item) for item in page.rows] if item_mapper else page.rows
+ if rows:
+ yield rows
+
+ if page.next_url:
+ # Save state AFTER yielding so a crash re-yields the in-flight page
+ # (merge dedupes on primary key).
+ resumable_source_manager.save_state(GiteaResumeConfig(next_url=page.next_url))
+ except requests.HTTPError as e:
+ if config.not_found_error and e.response is not None and e.response.status_code == 404:
+ raise ValueError(config.not_found_error) from e
+ raise
def _make_webhook_dedupe_transformer(primary_key: str, version_keys: list[str]) -> Callable[[pa.Table], pa.Table]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/settings.py
index e456096ddf85..ced94a7bb6ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/settings.py
@@ -8,7 +8,7 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
PAGE_SIZE = 50
-@dataclass
+@dataclass(frozen=True)
class GiteaEndpointConfig:
name: str
path: str # Path template with a {repository} (owner/repo) placeholder
@@ -24,6 +24,20 @@ class GiteaEndpointConfig:
supports_since: bool = False
# Extra static query params merged into every request.
extra_params: dict[str, str] = field(default_factory=dict)
+ # How the endpoint signals a next page. Several list endpoints send no Link header, only
+ # X-Total-Count (or a body `total_count`), so they page by number against that total.
+ # "unpaged" endpoints return every row when `page` is omitted. Use it where the endpoint
+ # drops rows after paging, because there a short or empty page is not the last page.
+ pagination: Literal["link_header", "total_count", "unpaged"] = "link_header"
+ # Key of the row list when the response wraps it in an object.
+ data_selector: Optional[str] = None
+ # Parent endpoint whose rows fan out to this one; `path` then also has an {index}
+ # placeholder filled with each parent row's `number`.
+ parent: Optional[str] = None
+ # Column that carries the parent's `number` onto each child row.
+ parent_number_column: Optional[str] = None
+ # Error raised instead of the generic "Repository not found" when the endpoint 404s.
+ not_found_error: Optional[str] = None
# Webhook event name (the X-Gitea-Event header value) that can feed this table, if any.
webhook_event: Optional[str] = None
# Ordered columns (newest-first, NULLs last) ranking webhook events that share a primary
@@ -110,6 +124,76 @@ GITEA_ENDPOINTS: dict[str, GiteaEndpointConfig] = {
extra_params={"state": "all"},
incremental_fields=[],
),
+ "issue_comments": GiteaEndpointConfig(
+ name="issue_comments",
+ # Repo-wide plain comments on issues and pull requests. Rows arrive oldest-created
+ # first while `since` filters server-side on the comment's updated time, so the
+ # watermark persists at end of run (desc).
+ path="/repos/{repository}/issues/comments",
+ pagination="total_count",
+ partition_key="created_at",
+ supports_since=True,
+ sort_mode="desc",
+ default_incremental_field="updated_at",
+ incremental_fields=[
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "issue_timeline": GiteaEndpointConfig(
+ name="issue_timeline",
+ # Every event on an issue (comments, state changes, label and assignee changes, ...).
+ # Adding a timeline event bumps the issue's updated time, so an incremental run only
+ # fans out over issues updated since the watermark. A plain comment edit does not bump
+ # it; the issue_comments table carries those edits.
+ path="/repos/{repository}/issues/{index}/timeline",
+ parent="issues",
+ parent_number_column="issue_number",
+ # Gitea drops cross-references the token can't read after paging.
+ pagination="unpaged",
+ partition_key="created_at",
+ supports_since=True,
+ sort_mode="desc",
+ default_incremental_field="updated_at",
+ incremental_fields=[
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "reviews": GiteaEndpointConfig(
+ name="reviews",
+ # No time filter on reviews or on the parent /pulls list: full refresh only.
+ # `submitted_at` is the review's creation time, so it is stable.
+ path="/repos/{repository}/pulls/{index}/reviews",
+ parent="pull_requests",
+ parent_number_column="pull_request_number",
+ # Gitea drops other users' pending reviews after paging.
+ pagination="unpaged",
+ partition_key="submitted_at",
+ incremental_fields=[],
+ ),
+ "workflow_runs": GiteaEndpointConfig(
+ name="workflow_runs",
+ # Gitea Actions runs, newest first. No time filter: full refresh only. No partition
+ # key: the API exposes no creation time, and `started_at` resets on a re-run.
+ path="/repos/{repository}/actions/runs",
+ pagination="total_count",
+ data_selector="workflow_runs",
+ sort_mode="desc",
+ incremental_fields=[],
+ not_found_error=(
+ "Gitea Actions runs are unavailable for this repository. "
+ "Syncing workflow runs needs Gitea 1.25 or later with Actions enabled on the repository."
+ ),
+ ),
}
ENDPOINTS = tuple(GITEA_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/source.py
index 3c8b5b5ea29f..dee47f0220a3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/source.py
@@ -164,6 +164,7 @@ If automatic creation failed, your token needs admin access to the repository
"403 Client Error": "Your Gitea token does not have permission to access this resource. Please check the token's scopes and repository access.",
"404 Client Error": "Repository not found. Please verify the instance URL, repository name, and token access.",
"Invalid Gitea instance URL": "The Gitea instance URL is invalid. Please enter the instance's canonical https URL.",
+ "Gitea Actions runs are unavailable": "Gitea Actions runs are unavailable for this repository. Upgrade the instance to Gitea 1.25 or later and enable Actions on the repository, or turn off the workflow_runs table.",
}
def get_schemas(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea.py
index d601d87a2804..4e1a84907a17 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea.py
@@ -6,9 +6,11 @@ import pytest
from unittest import mock
import pyarrow as pa
+import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.gitea import (
GiteaResumeConfig,
+ _add_comment_issue_number,
_flatten_commit,
_make_webhook_dedupe_transformer,
_parse_next_url,
@@ -283,6 +285,139 @@ class TestGetRows:
# The commit timestamp survives as the cursor/partition column.
assert row["created"] == "2024-01-01T00:00:00Z"
+ @pytest.mark.parametrize(
+ "endpoint, page_1, page_2, headers",
+ [
+ ("issue_comments", [{"id": 1}, {"id": 2}], [{"id": 3}], {"X-Total-Count": "3"}),
+ (
+ "workflow_runs",
+ {"total_count": 3, "workflow_runs": [{"id": 3}, {"id": 2}]},
+ {"total_count": 3, "workflow_runs": [{"id": 1}]},
+ {},
+ ),
+ ],
+ )
+ @mock.patch(f"{_MODULE}.PAGE_SIZE", 2)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_total_count_pagination_pages_by_number_without_link_header(
+ self, mock_session, endpoint, page_1, page_2, headers
+ ):
+ mock_session.return_value.get.side_effect = [
+ _response(page_1, headers=headers),
+ _response(page_2, headers=headers),
+ ]
+ manager = _make_manager()
+
+ batches = list(get_rows(BASE_URL, "tok", REPO, endpoint, mock.MagicMock(), manager))
+
+ assert sorted(row["id"] for batch in batches for row in batch) == [1, 2, 3]
+ # The total is covered after page 2, so no third request goes out.
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert len(urls) == 2
+ assert "page=2" in urls[1]
+ assert [call.args[0].next_url for call in manager.save_state.call_args_list] == [urls[1]]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_workflow_runs_not_found_raises_actions_unavailable(self, mock_session):
+ not_found = _response({"message": "Not Found"}, status_code=404)
+ not_found.raise_for_status.side_effect = requests.HTTPError("404 Client Error", response=not_found)
+ mock_session.return_value.get.return_value = not_found
+
+ with pytest.raises(ValueError, match="Gitea Actions runs are unavailable"):
+ list(get_rows(BASE_URL, "tok", REPO, "workflow_runs", mock.MagicMock(), _make_manager()))
+
+
+class TestFanOut:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_timeline_fans_out_over_issues_in_one_unpaged_request_each(self, mock_session):
+ issues_page_2 = f"{BASE_URL}/api/v1/repos/{REPO}/issues?limit=50&page=2"
+ deleted_issue = _response({"message": "Not Found"}, status_code=404)
+ deleted_issue.raise_for_status.side_effect = requests.HTTPError("404 Client Error", response=deleted_issue)
+ responses = {
+ f"/repos/{REPO}/issues?": [
+ _response([{"number": 1}, {"number": 2}], headers={"Link": f'<{issues_page_2}>; rel="next"'}),
+ _response([{"number": 3}]),
+ ],
+ f"/repos/{REPO}/issues/1/timeline": [_response([{"id": 10}, {"id": 11}], headers={"X-Total-Count": "2"})],
+ f"/repos/{REPO}/issues/2/timeline": [deleted_issue],
+ f"/repos/{REPO}/issues/3/timeline": [_response([{"id": 30}])],
+ }
+
+ def get(url, timeout):
+ return next(responses[key].pop(0) for key in responses if key in url)
+
+ mock_session.return_value.get.side_effect = get
+ manager = _make_manager()
+
+ batches = list(
+ get_rows(
+ BASE_URL,
+ "tok",
+ REPO,
+ "issue_timeline",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ )
+ )
+
+ assert [row for batch in batches for row in batch] == [
+ {"id": 10, "issue_number": 1},
+ {"id": 11, "issue_number": 1},
+ {"id": 30, "issue_number": 3},
+ ]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ timeline_urls = [url for url in urls if "/timeline" in url]
+ assert len(timeline_urls) == 3
+ # Gitea drops rows from a timeline page after paging, and its X-Total-Count is the
+ # filtered page length, so a paged walk can stop early. Without `page` the endpoint
+ # returns the whole timeline in one response.
+ assert not any("page=" in url or "limit=" in url for url in timeline_urls)
+ # The watermark bounds both the parent issues and each issue's timeline.
+ assert all("since=2024-01-02T00%3A00%3A00Z" in url for url in [urls[0], *timeline_urls])
+ assert "type=issues" in urls[0]
+ # State points at the next parent page once every child of the current one is yielded.
+ assert [call.args[0].next_url for call in manager.save_state.call_args_list] == [issues_page_2]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resume_starts_from_saved_parent_page(self, mock_session):
+ resume_url = f"{BASE_URL}/api/v1/repos/{REPO}/pulls?limit=50&page=4"
+ mock_session.return_value.get.side_effect = [
+ _response([{"number": 9}]),
+ _response([{"id": 90}]),
+ ]
+
+ batches = list(
+ get_rows(
+ BASE_URL,
+ "tok",
+ REPO,
+ "reviews",
+ mock.MagicMock(),
+ _make_manager(GiteaResumeConfig(next_url=resume_url)),
+ )
+ )
+
+ assert batches == [[{"id": 90, "pull_request_number": 9}]]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls[0] == resume_url
+ # Gitea drops other users' pending reviews after paging, so reviews are fetched unpaged.
+ assert urls[1] == f"{BASE_URL}/api/v1/repos/{REPO}/pulls/9/reviews"
+
+
+class TestAddCommentIssueNumber:
+ @pytest.mark.parametrize(
+ "item, expected",
+ [
+ ({"issue_url": f"{BASE_URL}/{REPO}/issues/12", "pull_request_url": ""}, 12),
+ ({"issue_url": "", "pull_request_url": f"{BASE_URL}/{REPO}/pulls/7"}, 7),
+ ({"issue_url": None, "pull_request_url": None}, None),
+ ],
+ )
+ def test_derives_number_from_url(self, item, expected):
+ assert _add_comment_issue_number(item)["issue_number"] == expected
+
class TestFlattenCommit:
def test_missing_nested_objects_do_not_crash(self):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_source.py
index 5376df881c45..0e80d26f24a6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_source.py
@@ -44,6 +44,7 @@ class TestGiteaSource:
"401 Client Error: Unauthorized for url: https://gitea.example.com/api/v1/repos/owner/repo/issues",
"403 Client Error: Forbidden for url: https://gitea.example.com/api/v1/repos/owner/repo/issues",
"404 Client Error: Not Found for url: https://gitea.example.com/api/v1/repos/owner/repo",
+ "Gitea Actions runs are unavailable for this repository. Syncing workflow runs needs Gitea 1.25 or later with Actions enabled on the repository.",
],
)
def test_non_retryable_errors_match_known_failures(self, observed_error):
@@ -65,7 +66,12 @@ class TestGiteaSource:
assert {schema.name for schema in schemas} == set(ENDPOINTS)
by_name = {schema.name: schema for schema in schemas}
# Only the endpoints with a real server-side `since` filter are incremental.
- assert {name for name, schema in by_name.items() if schema.supports_incremental} == {"issues", "commits"}
+ assert {name for name, schema in by_name.items() if schema.supports_incremental} == {
+ "issues",
+ "commits",
+ "issue_comments",
+ "issue_timeline",
+ }
assert {name for name, schema in by_name.items() if schema.supports_webhooks} == {"issues", "pull_requests"}
assert by_name["issues"].incremental_fields == INCREMENTAL_FIELDS["issues"]