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-sources): add six dataforseo tables (#104392)

Tom Owerse4cf7ba395c7
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 372a15bccc47..022644b989a0 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
@@ -2270,15 +2270,15 @@ Note: Diffed against both machine-readable specs (v1: 1.6 MB, v2: 7.3 MB), 1062
## DataForSEO — **thin**
-Today (5): `backlinks_summary`, `competitors_domain`, `domain_rank_overview`, `historical_rank_overview`, `ranked_keywords`
+Today (11): `backlinks_history`, `backlinks_referring_domains`, `backlinks_summary`, `backlinks_timeseries_summary`, `categories`, `competitors_domain`, `domain_rank_overview`, `historical_rank_overview`, `locations_and_languages`, `ranked_keywords`, `relevant_pages`
Diffed against: <https://docs.dataforseo.com/v3/wp-sitemap-posts-page-1.xml>
- [ ] `POST /v3/backlinks/backlinks/live` — the individual backlink rows behind the backlinks_summary aggregate we already sync (high)
-- [ ] `POST /v3/backlinks/referring_domains/live` — referring-domain breakdown with rank and spam score — the standard link-profile dimension table (high)
-- [ ] `POST /v3/dataforseo_labs/locations_and_languages and /v3/dataforseo_labs/categories` — lookup tables resolving the location_code, language_code and category codes stamped on every row we already sync (high)
-- [ ] `POST /v3/dataforseo_labs/google/relevant_pages/live` — top organic landing pages per domain with traffic and keyword counts (high)
-- [ ] `POST /v3/backlinks/history/live and /v3/backlinks/timeseries_summary/live` — backlink profile over time and new/lost link trend, versus the single current snapshot we sync (high)
+- [x] `POST /v3/backlinks/referring_domains/live` — referring-domain breakdown with rank and spam score — the standard link-profile dimension table (high)
+- [x] `GET /v3/dataforseo_labs/locations_and_languages and /v3/dataforseo_labs/categories` — lookup tables resolving the location_code, language_code and category codes stamped on every row we already sync (high). Both are free GET lookups, not POST tasks as first recorded.
+- [x] `POST /v3/dataforseo_labs/google/relevant_pages/live` — top organic landing pages per domain with traffic and keyword counts (high)
+- [x] `POST /v3/backlinks/history/live and /v3/backlinks/timeseries_summary/live` — backlink profile over time and new/lost link trend, versus the single current snapshot we sync (high)
- [ ] `POST /v3/keywords_data/google_ads/search_volume/live` — search volume, CPC and competition per keyword — the base metric for any SEO model (medium)
- [ ] `POST /v3/dataforseo_labs/google/historical_search_volume/live` — monthly search volume history for tracked keywords (medium)
- [ ] `POST /v3/backlinks/anchors/live` — anchor-text distribution for a target domain (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/canonical_descriptions.py
index b5e93990949e..9af74ddadf36 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/canonical_descriptions.py
@@ -70,4 +70,100 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"broken_pages": "Number of target pages that return an error and still receive backlinks.",
},
},
+ "relevant_pages": {
+ "description": "Landing pages of each target domain that rank in Google search results, with traffic and keyword metrics per page.",
+ "docs_url": "https://docs.dataforseo.com/v3/dataforseo_labs/google/relevant_pages/live/",
+ "columns": {
+ "target": "The tracked domain this row belongs to, as configured on the source.",
+ "page_address": "Absolute URL of the ranking page.",
+ "se_type": "Search engine type the metrics were collected from.",
+ "metrics": "Ranking and traffic data for the page grouped by result type (organic, paid), including position distribution buckets (pos_1, pos_2_3, ...), estimated traffic volume (etv), estimated paid traffic cost, keyword count, and counts of new, up, down, and lost rankings.",
+ },
+ },
+ "backlinks_referring_domains": {
+ "description": "Domains linking to each target domain, with link volume and quality metrics per referring domain (requires a Backlinks API subscription).",
+ "docs_url": "https://docs.dataforseo.com/v3/backlinks/referring_domains/live/",
+ "columns": {
+ "target": "The tracked domain this row belongs to, as configured on the source.",
+ "domain": "The referring domain that links to the target.",
+ "type": "Type of the element, always backlinks_referring_domain.",
+ "rank": "Rank the referring domain passes to the target, on a 0-1000 scale.",
+ "backlinks": "Number of backlinks from this domain pointing at the target.",
+ "backlinks_spam_score": "Average spam score of the backlinks from this domain.",
+ "first_seen": "When the crawler first found a backlink from this domain.",
+ "lost_date": "When the last backlink from this domain was lost, or null if it is still live.",
+ "broken_backlinks": "Number of backlinks from this domain that point at unreachable pages.",
+ "broken_pages": "Number of pages on this domain that return an error and still carry backlinks.",
+ "referring_domains": "Number of domains linking to the referring domain.",
+ "referring_main_domains": "Number of main (root) domains linking to the referring domain.",
+ "referring_pages": "Number of pages linking to the referring domain.",
+ "referring_ips": "Number of IP addresses hosting pages that link to the referring domain.",
+ "referring_subnets": "Number of subnets hosting pages that link to the referring domain.",
+ "referring_links_tld": "Count of referring links grouped by top-level domain.",
+ "referring_links_types": "Count of referring links grouped by link type (anchor, image, link, meta, canonical, alternate, redirect).",
+ "referring_links_attributes": "Count of referring links grouped by link attribute (for example nofollow, sponsored).",
+ "referring_links_platform_types": "Count of referring links grouped by the platform type of the linking site.",
+ },
+ },
+ "backlinks_history": {
+ "description": "Month-by-month history of each target domain's backlink profile, from January 2019 onward (requires a Backlinks API subscription).",
+ "docs_url": "https://docs.dataforseo.com/v3/backlinks/history/live/",
+ "columns": {
+ "target": "The tracked domain this row belongs to, as configured on the source.",
+ "type": "Type of the element, always backlinks_history.",
+ "date": "Date the snapshot was stored, in UTC. Metrics are aggregated as of the first day of the month.",
+ "rank": "Domain rank on that date, on a 0-1000 scale.",
+ "backlinks": "Number of backlinks pointing at the target on that date.",
+ "new_backlinks": "Backlinks gained since the previous month. Zero before May 2021.",
+ "lost_backlinks": "Backlinks lost since the previous month. Zero before May 2021.",
+ "new_referring_domains": "Referring domains gained since the previous month. Zero before May 2021.",
+ "lost_referring_domains": "Referring domains lost since the previous month. Zero before May 2021.",
+ "crawled_pages": "Number of pages of the target the crawler had visited.",
+ "info": "Details about the target on that date: server, CMS, platform types, IP address, country, and average spam score.",
+ "internal_links_count": "Total internal links across the crawled pages of the target.",
+ "external_links_count": "Total external links across the crawled pages of the target.",
+ "broken_backlinks": "Number of backlinks pointing at unreachable pages on the target.",
+ },
+ },
+ "backlinks_timeseries_summary": {
+ "description": "Monthly trend of each target domain's link profile, from January 2019 onward (requires a Backlinks API subscription).",
+ "docs_url": "https://docs.dataforseo.com/v3/backlinks/timeseries_summary/live/",
+ "columns": {
+ "target": "The tracked domain this row belongs to, as configured on the source.",
+ "type": "Type of the element, always backlinks_timeseries_summary.",
+ "date": "Last day of the month the metrics cover, in UTC.",
+ "rank": "Target rank for that month, on a 0-1000 scale.",
+ "backlinks": "Number of backlinks pointing at the target.",
+ "backlinks_nofollow": "Number of those backlinks carrying a nofollow attribute.",
+ "referring_pages": "Number of pages linking to the target.",
+ "referring_pages_nofollow": "Number of linking pages with at least one nofollow link to the target.",
+ "referring_domains": "Number of domains linking to the target, counting subdomains separately.",
+ "referring_domains_nofollow": "Number of those domains with at least one nofollow link to the target.",
+ "referring_main_domains": "Number of main (root) domains linking to the target.",
+ "referring_main_domains_nofollow": "Number of those main domains with at least one nofollow link to the target.",
+ "referring_ips": "Number of IP addresses hosting pages that link to the target.",
+ "referring_subnets": "Number of subnets hosting pages that link to the target.",
+ },
+ },
+ "locations_and_languages": {
+ "description": "Reference table of every location DataForSEO Labs supports, with the languages available for each. Resolves the location and language codes carried on the other Labs tables.",
+ "docs_url": "https://docs.dataforseo.com/v3/dataforseo_labs_locations_and_languages/",
+ "columns": {
+ "location_code": "DataForSEO identifier for the location.",
+ "location_name": "Full name of the location.",
+ "location_code_parent": "Code of the superordinate location. Always null, because Country is the only supported location type.",
+ "country_iso_code": "ISO country code of the location.",
+ "location_type": "Type of the location, always Country.",
+ "available_languages": "Languages supported for this location, each with its language_name, language_code, available data sources, and the number of keywords and SERPs held for the location and language pair.",
+ },
+ },
+ "categories": {
+ "description": "Reference table of the DataForSEO Labs category taxonomy. Resolves the category codes carried on the other Labs tables.",
+ "docs_url": "https://docs.dataforseo.com/v3/dataforseo_labs-categories/",
+ "columns": {
+ "category_code": "DataForSEO identifier for the category.",
+ "category_name": "Full name of the category.",
+ "category_code_parent": "Code of the superordinate category, or null for a top-level category.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/dataforseo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/dataforseo.py
index 50ab31fc75f2..7ea728920449 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/dataforseo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/dataforseo.py
@@ -1,6 +1,6 @@
import base64
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from typing import Any
import requests
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.settings import (
DATAFORSEO_ENDPOINTS,
DataForSEOEndpointConfig,
+ ParseKind,
)
DATAFORSEO_BASE_URL = "https://api.dataforseo.com/v3"
@@ -106,15 +107,22 @@ def _raise_for_body_status(status_code: Any, status_message: Any) -> None:
wait=wait_exponential_jitter(initial=2, max=60),
reraise=True,
)
-def _post_task(
+def _request_task(
session: requests.Session,
+ method: str,
path: str,
- payload: dict[str, Any],
+ payload: dict[str, Any] | None,
logger: FilteringBoundLogger,
) -> list[dict[str, Any]]:
- """POST one task to a live endpoint and return the first task's result list."""
+ """Call one endpoint and return the first task's result list.
+
+ Live endpoints take a single-task POST array; the free Labs lookups are plain GETs.
+ """
url = f"{DATAFORSEO_BASE_URL}{path}"
- response = session.post(url, json=[payload], timeout=REQUEST_TIMEOUT_SECONDS)
+ if method == "GET":
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+ else:
+ response = session.post(url, json=[payload], timeout=REQUEST_TIMEOUT_SECONDS)
if response.status_code == 429 or response.status_code >= 500:
raise DataForSEORetryableError(f"DataForSEO API error (retryable): status={response.status_code}, url={url}")
@@ -142,7 +150,7 @@ def _post_task(
return [entry for entry in result if isinstance(entry, dict)]
-def _parse_items(results: list[dict[str, Any]], target: str) -> Iterator[dict[str, Any]]:
+def _parse_items(results: list[dict[str, Any]], target: str | None) -> Iterator[dict[str, Any]]:
for result in results:
items = result.get("items")
if not isinstance(items, list):
@@ -152,7 +160,7 @@ def _parse_items(results: list[dict[str, Any]], target: str) -> Iterator[dict[st
yield {**item, "target": target}
-def _parse_ranked_keywords(results: list[dict[str, Any]], target: str) -> Iterator[dict[str, Any]]:
+def _parse_ranked_keywords(results: list[dict[str, Any]], target: str | None) -> Iterator[dict[str, Any]]:
# Lift the primary-key fields out of the nested keyword_data/ranked_serp_element blocks so
# the table has queryable top-level key columns; the full nested payloads are kept as-is.
for result in results:
@@ -178,7 +186,7 @@ def _parse_ranked_keywords(results: list[dict[str, Any]], target: str) -> Iterat
}
-def _parse_monthly_items(results: list[dict[str, Any]], target: str) -> Iterator[dict[str, Any]]:
+def _parse_monthly_items(results: list[dict[str, Any]], target: str | None) -> Iterator[dict[str, Any]]:
for result in results:
items = result.get("items")
if not isinstance(items, list):
@@ -192,17 +200,23 @@ def _parse_monthly_items(results: list[dict[str, Any]], target: str) -> Iterator
yield {**item, "target": target, "date": date}
-def _parse_result_rows(results: list[dict[str, Any]], target: str) -> Iterator[dict[str, Any]]:
+def _parse_result_rows(results: list[dict[str, Any]], target: str | None) -> Iterator[dict[str, Any]]:
# Backlinks summary carries its fields directly on tasks[].result[] with no nested items.
for result in results:
yield {**result, "target": target}
-_PARSERS = {
+def _parse_lookup_rows(results: list[dict[str, Any]], target: str | None) -> Iterator[dict[str, Any]]:
+ # Lookup tables are global: their rows sit directly on tasks[].result[] and carry no target.
+ yield from results
+
+
+_PARSERS: dict[ParseKind, Callable[[list[dict[str, Any]], str | None], Iterator[dict[str, Any]]]] = {
"items": _parse_items,
"ranked_keywords": _parse_ranked_keywords,
"monthly_items": _parse_monthly_items,
"result_rows": _parse_result_rows,
+ "lookup_rows": _parse_lookup_rows,
}
@@ -247,6 +261,12 @@ def get_rows(
parser = _PARSERS[config.kind]
session = _make_session(api_login, api_password)
+ if not config.targeted:
+ rows = list(parser(_request_task(session, config.method, config.path, None, logger), None))
+ if rows:
+ yield rows
+ return
+
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
start_index, start_offset = 0, 0
# If the saved target was removed from the config since the state was written, start over.
@@ -261,8 +281,12 @@ def get_rows(
next_target = targets[index + 1] if index + 1 < len(targets) else None
while True:
- results = _post_task(
- session, config.path, _payload(config, target, location_name, language_name, offset), logger
+ results = _request_task(
+ session,
+ config.method,
+ config.path,
+ _payload(config, target, location_name, language_name, offset),
+ logger,
)
rows = list(parser(results, target))
if rows:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/settings.py
index 343c83ac612b..6b2822ba860a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/settings.py
@@ -1,6 +1,8 @@
import dataclasses
from typing import Any, Literal
+from posthog.dataclasses import frozen
+
# DataForSEO serves every dataset as a POST "live" endpoint under https://api.dataforseo.com/v3.
# The request body is an array with one task object ({"target": ..., "location_name": ...}) and
# the response nests data as tasks[].result[] (with result[].items[] for most Labs endpoints).
@@ -8,10 +10,10 @@ from typing import Any, Literal
#
# No endpoint exposes a server-side updated-since filter, so every table is full refresh only.
# The `kind` tells the transport how to turn tasks[].result[] into flat rows.
-ParseKind = Literal["items", "ranked_keywords", "monthly_items", "result_rows"]
+ParseKind = Literal["items", "ranked_keywords", "monthly_items", "result_rows", "lookup_rows"]
+@frozen
class DataForSEOEndpointConfig:
name: str
# Path under the API base (https://api.dataforseo.com/v3).
@@ -20,6 +22,11 @@ class DataForSEOEndpointConfig:
# Unique across the whole table. Every endpoint fans out over the user's configured targets,
# so the injected `target` is always part of the key.
primary_keys: list[str]
+ # The Labs reference tables are free GET lookups; every other endpoint is a billed POST task.
+ method: Literal["GET", "POST"] = "POST"
+ # Whether the endpoint is scoped to a target domain. Untargeted endpoints are global lookup
+ # tables: no fan-out, no injected `target`, no pagination.
+ targeted: bool = True
# Whether the endpoint accepts `limit`/`offset` pagination (Labs list endpoints).
paginated: bool = False
# Whether the request payload carries location_name/language_name (Labs endpoints do; the
@@ -79,6 +86,68 @@ DATAFORSEO_ENDPOINTS: dict[str, DataForSEOEndpointConfig] = {
description="Backlink profile summary per target domain: rank, total backlinks, referring domains, IPs, and link attributes (one row per target). Requires an active DataForSEO Backlinks API subscription. Full refresh.",
should_sync_default=False,
),
+ "relevant_pages": DataForSEOEndpointConfig(
+ name="relevant_pages",
+ path="/dataforseo_labs/google/relevant_pages/live",
+ kind="items",
+ primary_keys=["target", "page_address"],
+ paginated=True,
+ description="Landing pages of each target domain that rank in Google, with per-page estimated traffic, keyword counts, and position distribution. Full refresh.",
+ ),
+ "backlinks_referring_domains": DataForSEOEndpointConfig(
+ name="backlinks_referring_domains",
+ path="/backlinks/referring_domains/live",
+ kind="items",
+ primary_keys=["target", "domain"],
+ paginated=True,
+ localized=False,
+ extra_payload={"include_subdomains": True},
+ description="Domains linking to each target domain, with domain rank, backlink and referring counts, spam score, and first-seen and lost dates (one row per referring domain). Requires an active DataForSEO Backlinks API subscription. Full refresh.",
+ should_sync_default=False,
+ ),
+ "backlinks_history": DataForSEOEndpointConfig(
+ name="backlinks_history",
+ path="/backlinks/history/live",
+ kind="items",
+ primary_keys=["target", "date"],
+ localized=False,
+ partition_key="date",
+ description="Month-by-month history of each target domain's backlink profile since January 2019: rank, backlinks, referring domains, and crawl statistics. Requires an active DataForSEO Backlinks API subscription. Full refresh.",
+ should_sync_default=False,
+ ),
+ "backlinks_timeseries_summary": DataForSEOEndpointConfig(
+ name="backlinks_timeseries_summary",
+ path="/backlinks/timeseries_summary/live",
+ kind="items",
+ primary_keys=["target", "date"],
+ localized=False,
+ # Unlike /backlinks/history/live, this endpoint does not default date_from to its documented
+ # minimum, so ask for the full range explicitly.
+ extra_payload={"date_from": "2019-01-30", "group_range": "month", "include_subdomains": True},
+ partition_key="date",
+ description="Monthly trend of each target domain's link profile since January 2019: backlinks, referring domains, pages, IPs, and subnets, with nofollow splits. Requires an active DataForSEO Backlinks API subscription. Full refresh.",
+ should_sync_default=False,
+ ),
+ "locations_and_languages": DataForSEOEndpointConfig(
+ name="locations_and_languages",
+ path="/dataforseo_labs/locations_and_languages",
+ kind="lookup_rows",
+ primary_keys=["location_code"],
+ method="GET",
+ targeted=False,
+ localized=False,
+ description="Reference table of every location DataForSEO Labs supports, with the languages available for each. Resolves the location_code and language_code carried on the other Labs tables. Full refresh.",
+ ),
+ "categories": DataForSEOEndpointConfig(
+ name="categories",
+ path="/dataforseo_labs/categories",
+ kind="lookup_rows",
+ primary_keys=["category_code"],
+ method="GET",
+ targeted=False,
+ localized=False,
+ description="Reference table of the DataForSEO Labs category taxonomy, with each category's parent code. Resolves the category codes carried on the other Labs tables. Full refresh.",
+ ),
}
ENDPOINTS = tuple(DATAFORSEO_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/source.py
index 5a4484875be0..c1aaaa2027a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/source.py
@@ -50,7 +50,7 @@ class DataForSEOSource(ResumableSource[DataForSEOSourceConfig, DataForSEOResumeC
Find your API login and password on the [DataForSEO API access page](https://app.dataforseo.com/api-access).
-Note: DataForSEO bills per API request, so every sync consumes account credits. The backlinks summary table also requires an active Backlinks API subscription.""",
+Note: DataForSEO bills per API request, so syncing these tables consumes account credits. The location and category lookup tables are free. The backlinks tables also need an active Backlinks API subscription.""",
iconPath="/static/services/dataforseo.png",
docsUrl="https://posthog.com/docs/cdp/sources/dataforseo",
fields=cast(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/tests/test_dataforseo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/tests/test_dataforseo.py
index 2d403eb4a8d8..cab0b653510c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/tests/test_dataforseo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/tests/test_dataforseo.py
@@ -14,8 +14,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo
DataForSEOAPIError,
DataForSEOResumeConfig,
DataForSEORetryableError,
- _post_task,
_raise_for_body_status,
+ _request_task,
dataforseo_source,
get_rows,
parse_targets,
@@ -27,6 +27,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo
ENDPOINTS,
)
+TARGETED_ENDPOINTS = [name for name, config in DATAFORSEO_ENDPOINTS.items() if config.targeted]
+LOOKUP_ENDPOINTS = [name for name, config in DATAFORSEO_ENDPOINTS.items() if not config.targeted]
+
def _resp(body: Any, status: int = 200) -> Any:
response = MagicMock()
@@ -69,7 +72,8 @@ def _drive(
responses: list[Any],
targets: list[str] | None = None,
) -> tuple[list[tuple[str, Any]], list[list[dict[str, Any]]]]:
- # Drives get_rows with a mocked tracked session, returning (posted (url, payload) pairs, batches).
+ # Drives get_rows with a mocked tracked session, returning ((url, payload) pairs, batches).
+ # A GET lookup records a None payload.
calls: list[tuple[str, Any]] = []
response_iter = iter(responses)
@@ -77,10 +81,15 @@ def _drive(
calls.append((url, json[0]))
return next(response_iter)
+ def fake_get(url: str, timeout: Any = None, **_kwargs: Any) -> Any:
+ calls.append((url, None))
+ return next(response_iter)
+
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.dataforseo.make_tracked_session"
) as MockSession:
MockSession.return_value.post.side_effect = fake_post
+ MockSession.return_value.get.side_effect = fake_get
batches = list(
get_rows(
api_login="login",
@@ -146,14 +155,14 @@ class TestBodyStatusClassification:
_raise_for_body_status(status_code, "nope")
-class TestPostTask:
+class TestRequestTask:
# Exercise a single attempt via __wrapped__ so the tenacity retry loop (and its real
# backoff sleeps) is not driven.
def _post(self, response: Any) -> list[dict[str, Any]]:
session = MagicMock()
session.post.return_value = response
- return _post_task.__wrapped__( # type: ignore[attr-defined]
- session, "/dataforseo_labs/google/ranked_keywords/live", {"target": "example.com"}, MagicMock()
+ return _request_task.__wrapped__( # type: ignore[attr-defined]
+ session, "POST", "/dataforseo_labs/google/ranked_keywords/live", {"target": "example.com"}, MagicMock()
)
@pytest.mark.parametrize("status", [429, 500, 503])
@@ -182,10 +191,20 @@ class TestPostTask:
def test_wraps_payload_in_array(self) -> None:
session = MagicMock()
session.post.return_value = _resp(_body([]))
- _post_task.__wrapped__(session, "/path", {"target": "example.com"}, MagicMock()) # type: ignore[attr-defined]
+ _request_task.__wrapped__(session, "POST", "/path", {"target": "example.com"}, MagicMock()) # type: ignore[attr-defined]
_, kwargs = session.post.call_args
assert kwargs["json"] == [{"target": "example.com"}]
+ def test_get_sends_no_body(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _resp(_body([{"category_code": 10021}]))
+ result = _request_task.__wrapped__( # type: ignore[attr-defined]
+ session, "GET", "/dataforseo_labs/categories", None, MagicMock()
+ )
+ assert result == [{"category_code": 10021}]
+ session.post.assert_not_called()
+ assert "json" not in session.get.call_args.kwargs
+
class TestGetRows:
def test_items_endpoint_injects_target(self) -> None:
@@ -365,6 +384,91 @@ class TestGetRows:
assert kwargs["headers"]["Authorization"].startswith("Basic ")
assert "password" in kwargs["redact_values"]
+ @pytest.mark.parametrize(
+ ("endpoint", "path", "expected_payload"),
+ [
+ (
+ "relevant_pages",
+ "/dataforseo_labs/google/relevant_pages/live",
+ {
+ "target": "example.com",
+ "location_name": "United States",
+ "language_name": "English",
+ "limit": PAGE_SIZE,
+ "offset": 0,
+ },
+ ),
+ (
+ "backlinks_referring_domains",
+ "/backlinks/referring_domains/live",
+ {"target": "example.com", "include_subdomains": True, "limit": PAGE_SIZE, "offset": 0},
+ ),
+ ("backlinks_history", "/backlinks/history/live", {"target": "example.com"}),
+ (
+ "backlinks_timeseries_summary",
+ "/backlinks/timeseries_summary/live",
+ {
+ "target": "example.com",
+ "date_from": "2019-01-30",
+ "group_range": "month",
+ "include_subdomains": True,
+ },
+ ),
+ ],
+ )
+ def test_request_shape_per_endpoint(self, endpoint: str, path: str, expected_payload: dict[str, Any]) -> None:
+ # The Backlinks API rejects the Labs location/language fields, and neither trend endpoint
+ # accepts limit/offset, so the payload each endpoint sends is asserted in full.
+ manager = _manager()
+ item = {
+ "date": "2020-08-31 00:00:00 +00:00",
+ "domain": "news.example",
+ "page_address": "https://example.com/a",
+ }
+ calls, batches = _drive(endpoint, manager, [_resp(_body([_items_result([item], total_count=1)]))])
+
+ assert calls == [(f"{DATAFORSEO_BASE_URL}{path}", expected_payload)]
+ assert batches == [[{**item, "target": "example.com"}]]
+
+ @pytest.mark.parametrize(
+ ("endpoint", "path", "row"),
+ [
+ (
+ "locations_and_languages",
+ "/dataforseo_labs/locations_and_languages",
+ {"location_code": 2840, "location_name": "United States", "available_languages": []},
+ ),
+ (
+ "categories",
+ "/dataforseo_labs/categories",
+ {"category_code": 10178, "category_name": "Apparel Accessories", "category_code_parent": 10021},
+ ),
+ ],
+ )
+ def test_lookup_endpoints_use_get_and_yield_untargeted_rows(
+ self, endpoint: str, path: str, row: dict[str, Any]
+ ) -> None:
+ manager = _manager()
+ # Two targets and two queued responses catch a lookup falling into the per-target fan-out,
+ # which would duplicate every row and stamp it with a target the API never returned.
+ calls, batches = _drive(
+ endpoint, manager, [_resp(_body([row])), _resp(_body([row]))], targets=["a.com", "b.com"]
+ )
+
+ # A None payload means the call went out as a GET with no body.
+ assert calls == [(f"{DATAFORSEO_BASE_URL}{path}", None)]
+ assert batches == [[row]]
+ assert "target" not in batches[0][0]
+ manager.save_state.assert_not_called()
+
+ def test_lookup_endpoint_ignores_saved_resume_state(self) -> None:
+ # A lookup has no cursor, so state left behind by another endpoint must not skip the call.
+ manager = _manager(DataForSEOResumeConfig(target="a.com", offset=PAGE_SIZE))
+ calls, batches = _drive("categories", manager, [_resp(_body([{"category_code": 1}]))], targets=["a.com"])
+
+ assert len(calls) == 1
+ assert batches == [[{"category_code": 1}]]
+
class TestDataForSEOSourceResponse:
@pytest.mark.parametrize("endpoint", ENDPOINTS)
@@ -390,12 +494,17 @@ class TestDataForSEOSourceResponse:
assert response.partition_mode is None
assert response.partition_keys is None
- @pytest.mark.parametrize("endpoint", ENDPOINTS)
- def test_primary_keys_include_target(self, endpoint: str) -> None:
- # Every endpoint fans out over the configured targets, so the injected target must be
- # part of the key for table-wide uniqueness.
+ @pytest.mark.parametrize("endpoint", TARGETED_ENDPOINTS)
+ def test_targeted_primary_keys_include_target(self, endpoint: str) -> None:
+ # A targeted endpoint fans out over the configured targets, so the injected target must
+ # be part of the key for table-wide uniqueness.
assert "target" in DATAFORSEO_ENDPOINTS[endpoint].primary_keys
+ @pytest.mark.parametrize("endpoint", LOOKUP_ENDPOINTS)
+ def test_lookup_primary_keys_exclude_target(self, endpoint: str) -> None:
+ # Lookup rows carry no target column, so keying on one would key every row on null.
+ assert "target" not in DATAFORSEO_ENDPOINTS[endpoint].primary_keys
+
class TestValidateCredentials:
def _validate(self, response: Any = None, raises: Exception | None = None) -> bool:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/tests/test_dataforseo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/tests/test_dataforseo_source.py
index 3251c250f7e1..b089c20d4dfe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/tests/test_dataforseo_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dataforseo/tests/test_dataforseo_source.py
@@ -7,7 +7,10 @@ from parameterized import parameterized
from products.warehouse_sources.backend.facade.source_config import SourceFieldInputConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
-from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.settings import (
+ DATAFORSEO_ENDPOINTS,
+ ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.source import DataForSEOSource
MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.source"
@@ -78,13 +81,17 @@ class TestDataForSEOSource:
assert schemas["ranked_keywords"].detected_primary_keys == ["target", "keyword", "item_type", "rank_absolute"]
assert schemas["historical_rank_overview"].detected_primary_keys == ["target", "year", "month"]
assert schemas["competitors_domain"].detected_primary_keys == ["target", "domain"]
+ # The lookup tables are global, so they key on their own code rather than on a target.
+ assert schemas["locations_and_languages"].detected_primary_keys == ["location_code"]
+ assert schemas["categories"].detected_primary_keys == ["category_code"]
- def test_backlinks_summary_is_off_by_default(self) -> None:
- # Backlinks requires a separate paid DataForSEO subscription, so it must not be part of
- # the default selection that one-shot setup enables.
+ def test_backlinks_tables_are_off_by_default(self) -> None:
+ # The Backlinks API is a separate paid DataForSEO subscription, so none of its tables may
+ # be part of the default selection that one-shot setup enables.
schemas = {s.name: s for s in DataForSEOSource().get_schemas(_make_config(), team_id=1)}
- assert schemas["backlinks_summary"].should_sync_default is False
- assert all(s.should_sync_default is True for name, s in schemas.items() if name != "backlinks_summary")
+ for name, schema in schemas.items():
+ needs_backlinks_api = DATAFORSEO_ENDPOINTS[name].path.startswith("/backlinks/")
+ assert schema.should_sync_default is not needs_backlinks_api
def test_get_schemas_filters_by_names(self) -> None:
schemas = DataForSEOSource().get_schemas(_make_config(), team_id=1, names=["ranked_keywords"])