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(data-warehouse): add ahrefs site explorer and project tables (#116124)

Tom Owers6197530e2807
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 cc74be1ffffe..729129fb2f4f 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
@@ -286,15 +286,15 @@ Note: Parsed collection GET operations from the official OpenAPI spec, including
## Ahrefs — **thin**
-Today (3): `site_audit_health_scores`, `site_audit_issues`, `site_audit_pages`
+Today (7): `backlinks`, `domain_rating_history`, `metrics_history`, `projects`, `site_audit_health_scores`, `site_audit_issues`, `site_audit_pages`
Diffed against: <https://docs.ahrefs.com/openapi.json>
-- [ ] `Projects (GET /v3/management/projects)` — provides project metadata for joining audit project IDs to target websites (high)
+- [x] `Projects (GET /v3/management/projects)` — provides project metadata for joining audit project IDs to target websites (high)
- [ ] `Organic keywords (GET /v3/site-explorer/organic-keywords)` — tracks search positions, traffic, and keyword value for SEO reports (high)
-- [ ] `Backlinks (GET /v3/site-explorer/all-backlinks)` — supports link acquisition, loss, and link quality analysis (high)
-- [ ] `Metrics history (GET /v3/site-explorer/metrics-history)` — measures organic traffic and traffic value trends over time (high)
-- [ ] `Domain Rating history (GET /v3/site-explorer/domain-rating-history)` — tracks the vendor's core authority metric alongside audit health (high)
+- [x] `Backlinks (GET /v3/site-explorer/all-backlinks)` — supports link acquisition, loss, and link quality analysis (high)
+- [x] `Metrics history (GET /v3/site-explorer/metrics-history)` — measures organic traffic and traffic value trends over time (high)
+- [x] `Domain Rating history (GET /v3/site-explorer/domain-rating-history)` — tracks the vendor's core authority metric alongside audit health (high)
- [ ] `Rank Tracker overview (GET /v3/rank-tracker/overview)` — measures tracked keyword rankings and visibility by project (high)
- [ ] `Referring domains (GET /v3/site-explorer/refdomains)` — measures unique linking domains and their authority (medium)
- [ ] `Top pages (GET /v3/site-explorer/top-pages)` — identifies pages that drive organic traffic and revenue opportunities (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py
index 02b8632ab1b3..26f1f82579de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py
@@ -1,12 +1,13 @@
from collections.abc import Iterator
-from typing import cast
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, cast
import structlog
from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.settings import (
API_BASE_URL,
ENDPOINTS,
- MAX_PAGE_ROWS,
+ HISTORY_DAYS,
NON_RETRYABLE_ERRORS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
@@ -70,48 +71,123 @@ def validate_credentials(api_key: str) -> tuple[bool, str | None]:
return True, None
-def ahrefs_source(api_key: str, project_id: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:
+def _site_audit_target(api_key: str, project_id: str) -> dict[str, Any]:
+ client = RESTClient(base_url=API_BASE_URL, auth=BearerTokenAuth(token=api_key), request_timeout=(10, 60))
+ for page in client.paginate(
+ path="site-audit/projects",
+ params={"output": "json", "project_id": project_id},
+ data_selector="healthscores",
+ data_selector_required=True,
+ paginator=SinglePagePaginator(),
+ hooks=create_response_hooks(RESPONSE_ACTIONS),
+ ):
+ for row in page:
+ if row.get("target_url"):
+ return row
+ raise ValueError("ahrefs_project_not_found")
+
+
+def _target_params(api_key: str, project_id: str, names: list[str]) -> dict[str, str]:
+ if not names:
+ return {}
+ project = _site_audit_target(api_key, project_id)
+ values = {
+ "target": project["target_url"],
+ "mode": project.get("target_mode"),
+ "protocol": project.get("target_protocol"),
+ }
+ return {name: value for name, value in values.items() if name in names and value}
+
+
+def _history_start(should_use_incremental_field: bool, last_value: Any, today: date) -> str:
+ if should_use_incremental_field and last_value:
+ if isinstance(last_value, datetime):
+ return last_value.date().isoformat()
+ if isinstance(last_value, date):
+ return last_value.isoformat()
+ return date.fromisoformat(str(last_value)[:10]).isoformat()
+ return (today - timedelta(days=HISTORY_DAYS)).isoformat()
+
+
+def _unique_rows(page: list[dict[str, object]], primary_keys: list[str]) -> list[dict[str, object]]:
+ seen: set[tuple[object, ...]] = set()
+ rows = []
+ for row in page:
+ key = tuple(row.get(field) for field in primary_keys)
+ if key not in seen:
+ seen.add(key)
+ rows.append(row)
+ return rows
+
+
+def ahrefs_source(
+ api_key: str,
+ project_id: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceResponse:
settings = schema_for_resource(ENDPOINTS, endpoint)
normalized_project_id = str(int(project_id))
+ project_scoped = settings.get("project_scoped", True)
+ history = settings.get("history", False)
+ row_limit = settings["params"].get("limit")
def add_project_id(row: dict[str, object]) -> dict[str, object]:
return {**row, "project_id": normalized_project_id}
- config: RESTAPIConfig = {
- "client": {
- "base_url": API_BASE_URL,
- "auth": {"type": "bearer", "token": api_key},
- "paginator": "single_page",
- "request_timeout": (10, 60),
- },
- "resources": [
- {
- "name": endpoint,
- "write_disposition": "replace",
- "endpoint": {
- "path": settings["path"],
- "data_selector": settings["data_selector"],
- "data_selector_required": True,
- "params": {"output": "json", "project_id": normalized_project_id, **settings["params"]},
- "response_actions": RESPONSE_ACTIONS,
- },
- "data_map": add_project_id,
- }
- ],
- }
- resource = rest_api_resource(config, team_id, job_id, None)
-
def items() -> Iterator[list[dict[str, object]]]:
+ params: dict[str, Any] = {
+ "output": "json",
+ **settings["params"],
+ **_target_params(api_key, normalized_project_id, settings.get("target_params", [])),
+ }
+ if project_scoped and not settings.get("target_params"):
+ params["project_id"] = normalized_project_id
+ if history:
+ params["date_from"] = _history_start(
+ should_use_incremental_field, db_incremental_field_last_value, datetime.now(UTC).date()
+ )
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": API_BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": "single_page",
+ "request_timeout": (10, 60),
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if history and should_use_incremental_field
+ else "replace",
+ "endpoint": {
+ "path": settings["path"],
+ "data_selector": settings["data_selector"],
+ "data_selector_required": True,
+ "params": params,
+ "response_actions": RESPONSE_ACTIONS,
+ },
+ "data_map": add_project_id if project_scoped else None,
+ }
+ ],
+ }
+ resource = rest_api_resource(config, team_id, job_id, None)
for page in resource:
- if endpoint == "site_audit_pages" and len(page) >= MAX_PAGE_ROWS:
- logger.info("ahrefs_page_sample_limit_reached", team_id=team_id, limit=MAX_PAGE_ROWS)
- page = page[:MAX_PAGE_ROWS]
+ if row_limit is not None and len(page) >= int(row_limit):
+ logger.info("ahrefs_sample_limit_reached", team_id=team_id, endpoint=endpoint, limit=row_limit)
+ page = page[: int(row_limit)]
+ page = _unique_rows(page, settings["primary_keys"])
+ if history:
+ page = sorted(page, key=lambda row: str(row.get("date") or ""))
yield page
return SourceResponse(
name=endpoint,
items=items,
primary_keys=settings["primary_keys"],
- sort_mode=None,
+ sort_mode="asc" if history else None,
supports_resume=False,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py
index f9d91508f1a7..612aac27dfe0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py
@@ -46,4 +46,69 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"is_html": "Whether the resource has an HTML content type.",
},
},
+ "projects": {
+ "description": "Projects in the Ahrefs workspace, with the target each project tracks.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/management/get-projects",
+ "columns": {
+ "project_id": "Unique identifier of the project.",
+ "project_name": "Name of the project.",
+ "url": "URL of the project's target.",
+ "mode": "Scope of the target: exact, prefix, domain, or subdomains.",
+ "protocol": "Protocol of the target: both, http, or https.",
+ "access": "Access level of the project: private or shared.",
+ "owned_by": "Email of the project owner.",
+ "verified": "Whether the project is verified.",
+ "keyword_count": "Number of Rank Tracker keywords in the project.",
+ "folder": "Innermost folder that contains the project.",
+ },
+ },
+ "domain_rating_history": {
+ "description": "Monthly Domain Rating of the selected Site Audit project's target.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/site-explorer/get-domain-rating-history",
+ "columns": {
+ "project_id": "Identifier of the selected Site Audit project.",
+ "date": "Start of the period the rating covers.",
+ "domain_rating": "Strength of the target's backlink profile compared to other websites, from 0 to 100.",
+ },
+ },
+ "metrics_history": {
+ "description": "Monthly organic and paid search traffic estimates for the selected Site Audit project's target.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/site-explorer/get-metrics-history",
+ "columns": {
+ "project_id": "Identifier of the selected Site Audit project.",
+ "date": "Start of the period the metrics cover.",
+ "org_traffic": "Estimated monthly visitors from organic search.",
+ "org_cost": "Estimated cost of the monthly organic search traffic, in USD cents.",
+ "paid_traffic": "Estimated monthly visitors from paid search.",
+ "paid_cost": "Estimated cost of the monthly paid search traffic, in USD cents.",
+ },
+ },
+ "backlinks": {
+ "description": "Live backlinks to the selected Site Audit project's target, strongest referring domains first.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/site-explorer/get-all-backlinks",
+ "columns": {
+ "project_id": "Identifier of the selected Site Audit project.",
+ "url_from": "URL of the page that contains the link.",
+ "url_to": "URL the link points to.",
+ "anchor": "Clickable text of the link.",
+ "title": "HTML title of the referring page.",
+ "link_type": "Kind of link, for example text, image, redirect, or canonical.",
+ "http_code": "HTTP status code returned when the referring page was crawled.",
+ "domain_rating_source": "Domain Rating of the referring domain.",
+ "url_rating_source": "URL Rating of the referring page.",
+ "is_dofollow": "Whether the link has no nofollow attribute.",
+ "is_nofollow": "Whether the link or the referring page has the nofollow attribute.",
+ "is_ugc": "Whether the link has the user-generated content attribute.",
+ "is_sponsored": "Whether the link has the sponsored attribute.",
+ "is_content": "Whether the link is in the main content of the page.",
+ "is_new": "Whether the link was found in the last crawl.",
+ "is_spam": "Whether the link comes from a known spam domain.",
+ "name_source": "Full referring domain name, including subdomains.",
+ "root_name_source": "Root domain name of the referring domain.",
+ "links_external": "Number of external links on the referring page.",
+ "first_seen": "Date the referring page was first found.",
+ "first_seen_link": "Date the link to the target was first found on the referring page.",
+ "last_visited": "Date a live link to the target was last verified.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py
index 08979cdd35e0..ef6a74f56515 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py
@@ -1,7 +1,37 @@
-from typing import TypedDict
+from typing import NotRequired, TypedDict
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
API_BASE_URL = "https://api.ahrefs.com/v3"
MAX_PAGE_ROWS = 100
+MAX_BACKLINK_ROWS = 1000
+# History rows cost API units and plans cap how far back history goes, so a first sync reads a bounded window.
+HISTORY_DAYS = 180
+
+BACKLINK_FIELDS = (
+ "url_from",
+ "url_to",
+ "anchor",
+ "title",
+ "link_type",
+ "http_code",
+ "domain_rating_source",
+ "url_rating_source",
+ "is_dofollow",
+ "is_nofollow",
+ "is_ugc",
+ "is_sponsored",
+ "is_content",
+ "is_new",
+ "is_spam",
+ "name_source",
+ "root_name_source",
+ "links_external",
+ "first_seen",
+ "first_seen_link",
+ "last_visited",
+)
class EndpointSettings(TypedDict):
@@ -10,6 +40,11 @@ class EndpointSettings(TypedDict):
primary_keys: list[str]
params: dict[str, str | int]
description: str
+ # Account-level tables don't take the configured Site Audit project.
+ project_scoped: NotRequired[bool]
+ # Site Explorer reports query the selected project's target with these parameters.
+ target_params: NotRequired[list[str]]
+ history: NotRequired[bool]
ENDPOINTS: dict[str, EndpointSettings] = {
@@ -38,16 +73,72 @@ ENDPOINTS: dict[str, EndpointSettings] = {
},
"description": f"The first {MAX_PAGE_ROWS} crawled URLs, ordered by URL. Requires verified project ownership.",
},
+ "projects": {
+ "path": "management/projects",
+ "data_selector": "projects",
+ "primary_keys": ["project_id"],
+ "params": {},
+ "description": "Every project in the Ahrefs workspace, with its target URL, scope, and protocol.",
+ "project_scoped": False,
+ },
+ "domain_rating_history": {
+ "path": "site-explorer/domain-rating-history",
+ "data_selector": "domain_ratings",
+ "primary_keys": ["project_id", "date"],
+ "params": {"history_grouping": "monthly"},
+ "description": "Monthly Domain Rating of the selected project's target.",
+ "target_params": ["target"],
+ "history": True,
+ },
+ "metrics_history": {
+ "path": "site-explorer/metrics-history",
+ "data_selector": "metrics",
+ "primary_keys": ["project_id", "date"],
+ "params": {
+ "select": "date,org_traffic,org_cost,paid_traffic,paid_cost",
+ "history_grouping": "monthly",
+ },
+ "description": "Monthly organic and paid search traffic and traffic value of the selected project's target.",
+ "target_params": ["target", "mode", "protocol"],
+ "history": True,
+ },
+ "backlinks": {
+ "path": "site-explorer/all-backlinks",
+ "data_selector": "backlinks",
+ "primary_keys": ["project_id", "url_from", "url_to"],
+ "params": {
+ "select": ",".join(BACKLINK_FIELDS),
+ "limit": MAX_BACKLINK_ROWS,
+ "order_by": "domain_rating_source:desc",
+ "history": "live",
+ "aggregation": "similar_links",
+ },
+ "description": (
+ f"Up to {MAX_BACKLINK_ROWS} live backlinks to the selected project's target, "
+ "strongest referring domains first."
+ ),
+ "target_params": ["target", "mode", "protocol"],
+ },
+}
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: [incremental_field("date", IncrementalFieldType.Date)]
+ for name, endpoint in ENDPOINTS.items()
+ if endpoint.get("history")
}
AUTH_ERROR = "Ahrefs authentication failed. Check your API key in Account settings > API keys."
ACCESS_ERROR = "Ahrefs denied access. Check your plan, project access, and verified ownership for page data."
QUOTA_ERROR = "Ahrefs API units are exhausted. Increase your API key or workspace limit, or wait for renewal."
+PROJECT_NOT_FOUND_ERROR = (
+ "Ahrefs returned no target for the Site Audit project. Check the project ID and that the project has a target URL."
+)
NON_RETRYABLE_ERRORS: dict[str, str | None] = {
"ahrefs_invalid_api_key": AUTH_ERROR,
"ahrefs_access_denied": ACCESS_ERROR,
"ahrefs_quota_exceeded": QUOTA_ERROR,
+ "ahrefs_project_not_found": PROJECT_NOT_FOUND_ERROR,
"401 Client Error": AUTH_ERROR,
"403 Client Error": ACCESS_ERROR,
"402 Client Error": QUOTA_ERROR,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py
index fc7a37fbdf14..f30c7e571a91 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py
@@ -16,6 +16,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.can
)
from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.settings import (
ENDPOINTS,
+ HISTORY_DAYS,
+ INCREMENTAL_FIELDS,
+ MAX_BACKLINK_ROWS,
MAX_PAGE_ROWS,
NON_RETRYABLE_ERRORS,
)
@@ -60,7 +63,11 @@ class AhrefsSource(SimpleSource[AhrefsSourceConfig]):
api_version: str | None = None,
) -> list[SourceSchema]:
return build_endpoint_schemas(
- ENDPOINTS, {}, names, descriptions={name: endpoint["description"] for name, endpoint in ENDPOINTS.items()}
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ merge_only=INCREMENTAL_FIELDS.keys(),
+ descriptions={name: endpoint["description"] for name, endpoint in ENDPOINTS.items()},
)
def validate_credentials(
@@ -75,7 +82,15 @@ class AhrefsSource(SimpleSource[AhrefsSourceConfig]):
return validate_ahrefs_credentials(config.api_key)
def source_for_pipeline(self, config: AhrefsSourceConfig, inputs: SourceInputs) -> SourceResponse:
- return ahrefs_source(config.api_key, config.project_id, inputs.schema_name, inputs.team_id, inputs.job_id)
+ return ahrefs_source(
+ config.api_key,
+ config.project_id,
+ inputs.schema_name,
+ inputs.team_id,
+ inputs.job_id,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,
+ )
@property
def get_source_config(self) -> SourceConfig:
@@ -88,10 +103,13 @@ class AhrefsSource(SimpleSource[AhrefsSourceConfig]):
caption=(
"Requires an Ahrefs Lite plan or higher. "
"Create an API key in [Account settings > API keys](https://app.ahrefs.com/account/api-keys). "
- "Syncs use your account's API units. Health scores are free. "
+ "Syncs use your account's API units. Health scores and projects are free. "
"Issues and pages each cost 50 units per request. "
+ "Metrics history costs 10 units per metric for each month returned. "
f"Each sync imports the latest crawl, with a sample of up to {MAX_PAGE_ROWS} pages. "
- "Page data requires verified project ownership."
+ "Page data requires verified project ownership. "
+ "Domain Rating, metrics history, and backlinks report on the Site Audit project's target. "
+ f"History tables start {HISTORY_DAYS} days back, and backlinks import up to {MAX_BACKLINK_ROWS} live links."
),
fields=cast(
list[FieldType],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
index f4c54cc13b06..bf447da392b6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
@@ -4,12 +4,14 @@ from typing import Any, cast
from urllib.parse import parse_qs, urlparse
import pytest
+import time_machine
from unittest.mock import MagicMock, patch
from requests import Response, Session
from requests.exceptions import HTTPError
from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.ahrefs import validate_credentials
+from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.settings import BACKLINK_FIELDS, ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.source import AhrefsSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientRetryableError,
@@ -53,24 +55,36 @@ def send() -> Iterator[MagicMock]:
[
(
"site_audit_health_scores",
- "projects",
+ "site-audit/projects",
"healthscores",
{"project_id": "123", "health_score": 95, "date": None},
- {},
+ {"project_id": ["123"]},
),
(
"site_audit_issues",
- "issues",
+ "site-audit/issues",
"issues",
{"issue_id": "missing_title", "crawled": 3},
- {},
+ {"project_id": ["123"]},
),
(
"site_audit_pages",
- "page-explorer",
+ "site-audit/page-explorer",
"pages",
{"url": "https://example.com/", "http_code": 200, "title": ["Example"]},
- {"limit": ["100"], "select": ["url,http_code,title,depth,is_html"], "order_by": ["url:asc"]},
+ {
+ "project_id": ["123"],
+ "limit": ["100"],
+ "select": ["url,http_code,title,depth,is_html"],
+ "order_by": ["url:asc"],
+ },
+ ),
+ (
+ "projects",
+ "management/projects",
+ "projects",
+ {"project_id": "999", "project_name": "Other site", "url": "https://example.org/"},
+ {},
),
],
)
@@ -93,18 +107,113 @@ def test_snapshot_request_and_terminal_page(
inputs.db_incremental_field_last_value = "2026-01-01"
result = AhrefsSource().source_for_pipeline(AhrefsSourceConfig(api_key="test-key", project_id="00123"), inputs)
- assert list(cast(Iterable[Any], result.items())) == ([] if empty else [[{**row, "project_id": "123"}]])
+ expected_row = {**row, "project_id": "123"} if "project_id" in expected_params else row
+ assert list(cast(Iterable[Any], result.items())) == ([] if empty else [[expected_row]])
send.assert_called_once()
assert send.call_args.kwargs["timeout"] == (10, 60)
request = send.call_args.args[0]
assert request.method == "GET"
assert request.headers["Authorization"] == "Bearer test-key"
- assert urlparse(request.url).path == f"/v3/site-audit/{path}"
- assert parse_qs(urlparse(request.url).query) == {
- "output": ["json"],
- "project_id": ["123"],
- **expected_params,
- }
+ assert urlparse(request.url).path == f"/v3/{path}"
+ assert parse_qs(urlparse(request.url).query) == {"output": ["json"], **expected_params}
+
+
+TARGET = {
+ "project_id": "123",
+ "target_url": "https://example.com/",
+ "target_mode": "domain",
+ "target_protocol": "https",
+}
+
+
+ ("table", "selector", "rows", "expected_rows", "expected_params"),
+ [
+ (
+ "domain_rating_history",
+ "domain_ratings",
+ [{"date": "2026-09-01", "domain_rating": 51.0}, {"date": "2026-08-01", "domain_rating": 50.5}],
+ [{"date": "2026-08-01", "domain_rating": 50.5}, {"date": "2026-09-01", "domain_rating": 51.0}],
+ {"history_grouping": ["monthly"]},
+ ),
+ (
+ "metrics_history",
+ "metrics",
+ [{"date": "2026-09-01", "org_traffic": 20}, {"date": "2026-08-01", "org_traffic": 10}],
+ [{"date": "2026-08-01", "org_traffic": 10}, {"date": "2026-09-01", "org_traffic": 20}],
+ {
+ "select": ["date,org_traffic,org_cost,paid_traffic,paid_cost"],
+ "history_grouping": ["monthly"],
+ "mode": ["domain"],
+ "protocol": ["https"],
+ },
+ ),
+ (
+ "backlinks",
+ "backlinks",
+ [
+ {"url_from": "https://a.example/", "url_to": "https://example.com/", "anchor": "first"},
+ {"url_from": "https://a.example/", "url_to": "https://example.com/", "anchor": "second"},
+ {"url_from": "https://b.example/", "url_to": "https://example.com/", "anchor": "other"},
+ ],
+ [
+ {"url_from": "https://a.example/", "url_to": "https://example.com/", "anchor": "first"},
+ {"url_from": "https://b.example/", "url_to": "https://example.com/", "anchor": "other"},
+ ],
+ {
+ "select": [",".join(BACKLINK_FIELDS)],
+ "limit": ["1000"],
+ "order_by": ["domain_rating_source:desc"],
+ "history": ["live"],
+ "aggregation": ["similar_links"],
+ "mode": ["domain"],
+ "protocol": ["https"],
+ },
+ ),
+ ],
+)
+ ("last_value", "expected_date_from"),
+ [(None, "2026-04-16"), ("2026-08-01", "2026-08-01")],
+)
+@time_machine.travel("2026-10-13T12:00:00Z", tick=False)
+def test_target_report_resolves_site_audit_target(
+ table: str,
+ selector: str,
+ rows: list[dict[str, object]],
+ expected_rows: list[dict[str, object]],
+ expected_params: dict[str, list[str]],
+ last_value: str | None,
+ expected_date_from: str,
+) -> None:
+ result = SourceDriver(AhrefsSource(), AhrefsSourceConfig(api_key="test-key", project_id="00123")).run(
+ table,
+ [ScriptedResponse(json={"healthscores": [TARGET]}), ScriptedResponse(json={selector: rows})],
+ incremental_field="date" if last_value else None,
+ db_incremental_field_last_value=last_value,
+ )
+
+ assert result.raised is None
+ assert result.rows == [{**row, "project_id": "123"} for row in expected_rows]
+ target_request, report_request = result.requests
+ assert target_request.path == "/v3/site-audit/projects"
+ assert target_request.query["project_id"] == ("123",)
+ assert report_request.path == f"/v3/{ENDPOINTS[table]['path']}"
+ query = {name: list(values) for name, values in report_request.query.items()}
+ history_params = {"date_from": [expected_date_from]} if table != "backlinks" else {}
+ assert query == {"output": ["json"], "target": ["https://example.com/"], **expected_params, **history_params}
+
+
[email protected]("healthscores", [[], [{"project_id": "123", "target_url": None}]])
+def test_target_report_without_site_audit_target_fails_permanently(healthscores: list[dict[str, object]]) -> None:
+ source = AhrefsSource()
+ result = SourceDriver(source, AhrefsSourceConfig(api_key="test-key", project_id="123")).run(
+ "backlinks", [ScriptedResponse(json={"healthscores": healthscores})]
+ )
+ assert isinstance(result.raised, ValueError)
+ mapped = source.get_non_retryable_errors()[str(result.raised)]
+ assert mapped is not None and "project ID" in mapped
+ assert len(result.requests) == 1
@pytest.mark.parametrize("count", [99, 100, 101])