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 dataforseo backlink, keyword and serp tables (#105176)

Tom Owersaa11b088e6b1
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 37a2cad8cb25..6934c500ab34 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,22 +2270,22 @@ Note: Diffed against both machine-readable specs (v1: 1.6 MB, v2: 7.3 MB), 1062
## DataForSEO — **thin**
-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`
+Today (15): `backlinks`, `backlinks_anchors`, `backlinks_history`, `backlinks_referring_domains`, `backlinks_summary`, `backlinks_timeseries_summary`, `categories`, `competitors_domain`, `domain_rank_overview`, `historical_rank_overview`, `historical_search_volume`, `locations_and_languages`, `ranked_keywords`, `relevant_pages`, `serp_organic`
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)
+- [x] `POST /v3/backlinks/backlinks/live` — the individual backlink rows behind the backlinks_summary aggregate we already sync (high). Sorted by rank and capped at the first few pages, because a large domain has millions of backlinks.
- [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)
+- [x] `POST /v3/dataforseo_labs/google/historical_search_volume/live` — monthly search volume history for tracked keywords (medium). Keyword-scoped, not domain-scoped: it needs keywords configured on the source, and one request covers up to 700 of them.
+- [x] `POST /v3/backlinks/anchors/live` — anchor-text distribution for a target domain (medium)
- [ ] `POST /v3/dataforseo_labs/google/domain_intersection/live and /page_intersection/live` — keyword-gap analysis against the competitors we already sync in competitors_domain (medium)
- [ ] `POST /v3/dataforseo_labs/google/keyword_ideas/live, /keyword_suggestions/live, /related_keywords/live` — keyword expansion sets for opportunity sizing (medium)
- [ ] `POST /v3/backlinks/domain_pages_summary/live and /domain_pages/live` — per-page backlink counts, the page-level breakdown of the domain summary (medium)
-- [ ] `POST /v3/serp/google/organic/live/advanced` — raw SERP snapshots per keyword, the source of rank tracking over time (medium)
+- [x] `POST /v3/serp/google/organic/live/advanced` — raw SERP snapshots per keyword, the source of rank tracking over time (medium). Keyword-scoped and billed per keyword per sync, so it covers the first results page only.
Note: DataForSEO docs are a WordPress site with no OpenAPI, llms.txt or sitemap index; I enumerated all 691 endpoint doc pages from /v3/wp-sitemap-posts-page-1.xml and spot-verified the URL format on https://docs.dataforseo.com/v3/backlinks/backlinks/live/ (POST https://api.dataforseo.com/v3/backlinks/backlinks/live). The API spans SERP (157 pages), DataForSEO Labs (85), Keywords Data (69), AI Optimization (69), Business Data (58), Merchant (47), App Data (36), On-Page (33) and Backlinks (25); five synced tables is a small fraction. Whole families are absent: On-Page site audit, Business Data (Google Business Profile reviews), Merchant, App Data, Content Analysis and Domain Analytics technologies.
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 9af74ddadf36..85ee7d7e0239 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
@@ -145,6 +145,134 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"referring_subnets": "Number of subnets hosting pages that link to the target.",
},
},
+ "backlinks": {
+ "description": "Individual backlinks pointing at each target domain, the link-level detail behind the backlinks_summary aggregate (requires a Backlinks API subscription). Only the highest-ranking backlinks are synced.",
+ "docs_url": "https://docs.dataforseo.com/v3/backlinks/backlinks/live/",
+ "columns": {
+ "target": "The tracked domain this row belongs to, as configured on the source.",
+ "type": "Type of the element, always backlink.",
+ "domain_from": "Domain of the page carrying the link.",
+ "url_from": "URL of the page carrying the link.",
+ "url_from_https": "Whether the linking page is served over HTTPS.",
+ "domain_to": "Domain the link points at.",
+ "url_to": "URL the link points at.",
+ "url_to_https": "Whether the linked page is served over HTTPS.",
+ "tld_from": "Top-level domain of the linking page.",
+ "is_new": "Whether the backlink was found for the first time during the last check.",
+ "is_lost": "Whether the backlink was gone during the last check.",
+ "backlink_spam_score": "Spam score of the backlink, from 0 to 100.",
+ "rank": "Rank this backlink passes to the target, on a 0-1000 scale.",
+ "page_from_rank": "Rank of the linking page, on a 0-1000 scale.",
+ "domain_from_rank": "Rank of the linking domain, on a 0-1000 scale.",
+ "domain_from_platform_type": "Platform types detected on the linking domain (for example cms, blogs, ecommerce).",
+ "domain_from_is_ip": "Whether the linking domain is an IP address.",
+ "domain_from_ip": "IP address hosting the linking domain.",
+ "domain_from_country": "ISO country code of the linking domain.",
+ "page_from_external_links": "Number of external links on the linking page.",
+ "page_from_internal_links": "Number of internal links on the linking page.",
+ "page_from_size": "Size of the linking page in bytes.",
+ "page_from_encoding": "Character encoding of the linking page.",
+ "page_from_language": "Language of the linking page.",
+ "page_from_title": "Title of the linking page.",
+ "page_from_status_code": "HTTP status code returned by the linking page.",
+ "first_seen": "When the crawler first found this backlink.",
+ "prev_seen": "When the crawler saw this backlink before the last check.",
+ "last_seen": "When the crawler last saw this backlink.",
+ "item_type": "How the link is placed on the page (anchor, image, link, meta, canonical, alternate, redirect).",
+ "attributes": "Link attributes, for example nofollow, sponsored, or ugc.",
+ "dofollow": "Whether the link passes ranking value.",
+ "original": "Whether the link was present when the page was first crawled.",
+ "alt": "Alt text, for an image link.",
+ "image_url": "Image URL, for an image link.",
+ "anchor": "Anchor text of the link, or null for a link with no text.",
+ "text_pre": "Text immediately before the anchor.",
+ "text_post": "Text immediately after the anchor.",
+ "semantic_location": "HTML element the link sits in (for example article, section, header).",
+ "links_count": "Number of identical links from the linking page to the same URL.",
+ "group_count": "Number of similar links grouped into this row when a grouping mode is used.",
+ "is_broken": "Whether the link points at an unreachable page.",
+ "url_to_status_code": "HTTP status code returned by the linked page.",
+ "url_to_spam_score": "Spam score of the linked page, from 0 to 100.",
+ "url_to_redirect_target": "Final URL the linked page redirects to.",
+ "ranked_keywords_info": "Counts of keywords the linking page ranks for in the top 3, top 10, and top 100 results.",
+ "is_indirect_link": "Whether the link reaches the target through a redirect or canonical.",
+ "indirect_link_path": "Redirect chain the link follows to reach the target.",
+ },
+ },
+ "backlinks_anchors": {
+ "description": "Anchor text used to link to each target domain, with link volume and quality metrics per anchor (requires a Backlinks API subscription).",
+ "docs_url": "https://docs.dataforseo.com/v3/backlinks/anchors/live/",
+ "columns": {
+ "target": "The tracked domain this row belongs to, as configured on the source.",
+ "type": "Type of the element, always backlinks_anchor.",
+ "anchor": "The anchor text used to link to the target.",
+ "rank": "Rank the backlinks using this anchor pass to the target, on a 0-1000 scale.",
+ "backlinks": "Number of backlinks to the target that use this anchor.",
+ "first_seen": "When the crawler first found a backlink using this anchor.",
+ "lost_date": "When the last backlink using this anchor was lost, or null if one is still live.",
+ "backlinks_spam_score": "Average spam score of the backlinks using this anchor.",
+ "broken_backlinks": "Number of backlinks using this anchor that point at unreachable pages.",
+ "broken_pages": "Number of pages carrying this anchor that return an error.",
+ "referring_domains": "Number of domains linking to the target with this anchor.",
+ "referring_domains_nofollow": "Number of those domains whose links carry a nofollow attribute.",
+ "referring_main_domains": "Number of main (root) domains linking with this anchor.",
+ "referring_main_domains_nofollow": "Number of those main domains whose links carry a nofollow attribute.",
+ "referring_ips": "Number of IP addresses hosting pages that link with this anchor.",
+ "referring_subnets": "Number of subnets hosting pages that link with this anchor.",
+ "referring_pages": "Number of pages linking to the target with this anchor.",
+ "referring_pages_nofollow": "Number of those pages whose links carry a nofollow attribute.",
+ "referring_links_tld": "Count of links using this anchor grouped by top-level domain.",
+ "referring_links_types": "Count of links using this anchor grouped by link type.",
+ "referring_links_attributes": "Count of links using this anchor grouped by link attribute.",
+ "referring_links_platform_types": "Count of links using this anchor grouped by the platform type of the linking site.",
+ "referring_links_semantic_locations": "Count of links using this anchor grouped by the HTML element they sit in.",
+ "referring_links_countries": "Count of links using this anchor grouped by the country of the linking site.",
+ },
+ },
+ "historical_search_volume": {
+ "description": "Monthly Google search volume for each keyword configured on the source, one row per keyword per month.",
+ "docs_url": "https://docs.dataforseo.com/v3/dataforseo_labs/google/historical_search_volume/live/",
+ "columns": {
+ "keyword": "The keyword this row belongs to, as configured on the source and lower-cased by DataForSEO.",
+ "se_type": "Search engine type the volume was collected from (e.g. google).",
+ "location_code": "DataForSEO location identifier the volume is scoped to.",
+ "language_code": "Language identifier the volume is scoped to.",
+ "search_partners": "Whether the volume includes Google partner sites as well as Google search.",
+ "year": "Calendar year of the measurement.",
+ "month": "Calendar month of the measurement (1-12).",
+ "date": "First day of the measurement month (derived from year and month).",
+ "search_volume": "Average monthly searches for the keyword in that month.",
+ },
+ },
+ "serp_organic": {
+ "description": "A snapshot of the Google results page for each keyword configured on the source, one row per SERP element. Covers the first page of results.",
+ "docs_url": "https://docs.dataforseo.com/v3/serp/google/organic/live/advanced/",
+ "columns": {
+ "keyword": "The keyword the results page was fetched for.",
+ "se_domain": "Google domain the results were fetched from (for example google.com).",
+ "location_code": "DataForSEO location identifier the search was run for.",
+ "language_code": "Language identifier the search was run for.",
+ "check_url": "Google URL that reproduces the search.",
+ "datetime": "When the results page was fetched, in UTC.",
+ "type": "Type of the SERP element (organic, paid, featured_snippet, people_also_ask, ai_overview, and others).",
+ "rank_group": "Position within the group of elements of the same type.",
+ "rank_absolute": "Absolute position among all elements on the results page.",
+ "position": "Which side of the results page the element sits on (left or right).",
+ "xpath": "XPath of the element in the results page markup.",
+ "domain": "Domain of the result, for an element that carries a URL.",
+ "title": "Title of the result.",
+ "url": "URL of the result.",
+ "breadcrumb": "Breadcrumb shown under the result title.",
+ "description": "Snippet text shown for the result.",
+ "website_name": "Site name shown for the result.",
+ "is_featured_snippet": "Whether the result is shown as a featured snippet.",
+ "is_image": "Whether the result carries an image.",
+ "is_video": "Whether the result carries a video.",
+ "links": "Sitelinks shown under the result.",
+ "rating": "Review rating shown for the result.",
+ "items": "Nested elements the SERP element is made of, for a grouped element such as a carousel or people_also_ask block.",
+ },
+ },
"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/",
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 7ea728920449..6d1e7f89c4f7 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,5 +1,4 @@
import base64
-import dataclasses
from collections.abc import Callable, Iterator
from typing import Any
@@ -7,6 +6,8 @@ import requests
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.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -29,6 +30,8 @@ MAX_PAGES_PER_TARGET = 5
# unbounded target list lets a saved config fan out into arbitrarily many charged requests per
# scheduled sync.
MAX_TARGETS = 25
+# The SERP table spends one billable request per keyword per sync, so bound the keyword list too.
+MAX_KEYWORDS = 50
REQUEST_TIMEOUT_SECONDS = 120
MAX_RETRIES = 5
@@ -41,11 +44,14 @@ class DataForSEOAPIError(Exception):
"""Raised on permanent body-level errors (auth, funds, invalid request)."""
+@frozen
class DataForSEOResumeConfig:
- # The target currently being fetched and the next page offset within it. Targets are
- # processed in config order, so on resume earlier targets are skipped entirely.
- target: str
+ # Which fan-out value the sync is on and the next page offset within it: `target` for the
+ # target-scoped endpoints, `keyword` for the keyword-scoped ones. Values are processed in
+ # config order, so on resume earlier ones are skipped entirely. Both default to empty so
+ # state written by an older deploy still loads.
+ target: str = ""
+ keyword: str = ""
offset: int = 0
@@ -88,6 +94,30 @@ def validate_targets(targets: str) -> tuple[list[str], str | None]:
return parsed, None
+def parse_keywords(keywords: str) -> list[str]:
+ """Split the user's comma-separated keywords field into a de-duplicated, normalized list.
+
+ DataForSEO lower-cases keywords server-side, so normalizing here keeps the rows we sync
+ keyed the same way the API returns them.
+ """
+ seen: set[str] = set()
+ result: list[str] = []
+ for raw in keywords.split(","):
+ keyword = " ".join(raw.split()).lower()
+ if keyword and keyword not in seen:
+ seen.add(keyword)
+ result.append(keyword)
+ return result
+
+
+def validate_keywords(keywords: str | None) -> tuple[list[str], str | None]:
+ """Parse and bound the keywords field. Returns the parsed list plus a user-facing error, if any."""
+ parsed = parse_keywords(keywords or "")
+ if len(parsed) > MAX_KEYWORDS:
+ return parsed, f"Too many keywords ({len(parsed)}); enter at most {MAX_KEYWORDS} distinct keywords."
+ return parsed, None
+
+
def _raise_for_body_status(status_code: Any, status_message: Any) -> None:
"""Classify a DataForSEO body-level status code (top-level or per-task).
@@ -206,6 +236,61 @@ def _parse_result_rows(results: list[dict[str, Any]], target: str | None) -> Ite
yield {**result, "target": target}
+def _parse_keyword_monthly_searches(results: list[dict[str, Any]], _value: str | None) -> Iterator[dict[str, Any]]:
+ # One request covers every keyword, so the rows carry the keyword from the response rather
+ # than an injected fan-out value. Each keyword's history arrives as a nested
+ # keyword_info.monthly_searches array, which is flattened into one row per month.
+ for result in results:
+ items = result.get("items")
+ if not isinstance(items, list):
+ continue
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ keyword = item.get("keyword")
+ monthly_searches = (item.get("keyword_info") or {}).get("monthly_searches")
+ if not keyword or not isinstance(monthly_searches, list):
+ continue
+ for entry in monthly_searches:
+ if not isinstance(entry, dict):
+ continue
+ year, month = entry.get("year"), entry.get("month")
+ if not isinstance(year, int) or not isinstance(month, int):
+ continue
+ yield {
+ "keyword": keyword,
+ "se_type": item.get("se_type"),
+ "location_code": item.get("location_code"),
+ "language_code": item.get("language_code"),
+ "search_partners": item.get("search_partners"),
+ "year": year,
+ "month": month,
+ # `date` is the injected stable partition column (first day of the month).
+ "date": f"{year:04d}-{month:02d}-01",
+ "search_volume": entry.get("search_volume"),
+ }
+
+
+def _parse_serp_items(results: list[dict[str, Any]], keyword: str | None) -> Iterator[dict[str, Any]]:
+ # Stamp each SERP element with the keyword and the crawl metadata from its result block, so a
+ # snapshot can be told apart from the next one taken for the same keyword.
+ for result in results:
+ items = result.get("items")
+ if not isinstance(items, list):
+ continue
+ context = {
+ "keyword": result.get("keyword") or keyword,
+ "se_domain": result.get("se_domain"),
+ "location_code": result.get("location_code"),
+ "language_code": result.get("language_code"),
+ "check_url": result.get("check_url"),
+ "datetime": result.get("datetime"),
+ }
+ for item in items:
+ if isinstance(item, dict):
+ yield {**item, **context}
+
+
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
@@ -217,17 +302,34 @@ _PARSERS: dict[ParseKind, Callable[[list[dict[str, Any]], str | None], Iterator[
"monthly_items": _parse_monthly_items,
"result_rows": _parse_result_rows,
"lookup_rows": _parse_lookup_rows,
+ "keyword_monthly_searches": _parse_keyword_monthly_searches,
+ "serp_items": _parse_serp_items,
}
def _payload(
config: DataForSEOEndpointConfig,
- target: str,
+ value: str | list[str],
location_name: str,
language_name: str,
offset: int | None = None,
-) -> dict[str, Any]:
- payload: dict[str, Any] = {"target": target, **config.extra_payload}
+) -> dict[str, Any] | None:
+ """Build the single-task request body, or None for the untargeted GET lookups.
+
+ `value` is the endpoint's fan-out value: a target domain, one keyword, or — for the batched
+ keyword endpoint — the whole keyword list.
+ """
+ if config.scope == "global":
+ return None
+
+ payload: dict[str, Any] = dict(config.extra_payload)
+ if config.scope == "target":
+ payload["target"] = value
+ elif config.scope == "keyword":
+ payload["keyword"] = value
+ else:
+ payload["keywords"] = value
+
if config.localized:
payload["location_name"] = location_name
payload["language_name"] = language_name
@@ -247,10 +349,43 @@ def _has_more_pages(results: list[dict[str, Any]], item_count: int, next_offset:
return item_count >= PAGE_SIZE
+def _next_page_offset(
+ config: DataForSEOEndpointConfig,
+ results: list[dict[str, Any]],
+ offset: int,
+ endpoint: str,
+ value: str,
+ logger: FilteringBoundLogger,
+) -> int | None:
+ """Offset of the next page for this fan-out value, or None once it is done."""
+ if not config.paginated:
+ return None
+
+ item_count = sum(len(result.get("items") or []) for result in results)
+ next_offset = offset + item_count
+ if not _has_more_pages(results, item_count, next_offset):
+ return None
+
+ if next_offset >= PAGE_SIZE * MAX_PAGES_PER_TARGET:
+ logger.warning(
+ f"DataForSEO: page cap reached, truncating results. endpoint={endpoint} value={value} "
+ f"rows_fetched={next_offset} max_rows={PAGE_SIZE * MAX_PAGES_PER_TARGET}"
+ )
+ return None
+ return next_offset
+
+
+def _resume_state(config: DataForSEOEndpointConfig, value: str, offset: int) -> DataForSEOResumeConfig:
+ if config.scope == "keyword":
+ return DataForSEOResumeConfig(keyword=value, offset=offset)
+ return DataForSEOResumeConfig(target=value, offset=offset)
+
+
def get_rows(
api_login: str,
api_password: str,
targets: list[str],
+ keywords: list[str],
location_name: str,
language_name: str,
endpoint: str,
@@ -261,64 +396,60 @@ 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))
+ # A lookup has no fan-out and the batched keyword endpoint covers every keyword in one
+ # request, so neither has a cursor to resume from.
+ if config.scope in ("global", "keyword_batch"):
+ payload = _payload(config, keywords, location_name, language_name)
+ rows = list(parser(_request_task(session, config.method, config.path, payload, logger), None))
if rows:
yield rows
return
+ values = keywords if config.scope == "keyword" else targets
+
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ resume_value = (resume.keyword or resume.target) if resume is not None else None
start_index, start_offset = 0, 0
- # If the saved target was removed from the config since the state was written, start over.
- if resume is not None and resume.target in targets:
- start_index = targets.index(resume.target)
+ # If the saved value was removed from the config since the state was written, start over.
+ if resume is not None and resume_value in values:
+ start_index = values.index(resume_value)
start_offset = resume.offset
- logger.debug(f"DataForSEO: resuming endpoint={endpoint} from target={resume.target} offset={resume.offset}")
+ logger.debug(f"DataForSEO: resuming endpoint={endpoint} from value={resume_value} offset={resume.offset}")
- for index in range(start_index, len(targets)):
- target = targets[index]
+ for index in range(start_index, len(values)):
+ value = values[index]
offset = start_offset if index == start_index else 0
- next_target = targets[index + 1] if index + 1 < len(targets) else None
+ next_value = values[index + 1] if index + 1 < len(values) else None
while True:
results = _request_task(
session,
config.method,
config.path,
- _payload(config, target, location_name, language_name, offset),
+ _payload(config, value, location_name, language_name, offset),
logger,
)
- rows = list(parser(results, target))
+ rows = list(parser(results, value))
if rows:
yield rows
- if not config.paginated:
- break
-
- item_count = sum(len(result.get("items") or []) for result in results)
- next_offset = offset + item_count
- if not _has_more_pages(results, item_count, next_offset):
- break
-
- if next_offset >= PAGE_SIZE * MAX_PAGES_PER_TARGET:
- logger.warning(
- f"DataForSEO: page cap reached, truncating results. endpoint={endpoint} target={target} "
- f"rows_fetched={next_offset} max_rows={PAGE_SIZE * MAX_PAGES_PER_TARGET}"
- )
+ next_offset = _next_page_offset(config, results, offset, endpoint, value, logger)
+ if next_offset is None:
break
# Persist AFTER yielding — a crash re-yields the last page rather than skipping it.
- resumable_source_manager.save_state(DataForSEOResumeConfig(target=target, offset=next_offset))
+ resumable_source_manager.save_state(_resume_state(config, value, next_offset))
offset = next_offset
- if next_target is not None:
- resumable_source_manager.save_state(DataForSEOResumeConfig(target=next_target, offset=0))
+ if next_value is not None:
+ resumable_source_manager.save_state(_resume_state(config, next_value, 0))
def dataforseo_source(
api_login: str,
api_password: str,
targets: list[str],
+ keywords: list[str],
location_name: str,
language_name: str,
endpoint: str,
@@ -333,6 +464,7 @@ def dataforseo_source(
api_login=api_login,
api_password=api_password,
targets=targets,
+ keywords=keywords,
location_name=location_name,
language_name=language_name,
endpoint=endpoint,
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 6b2822ba860a..28ac1ce18067 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
@@ -10,7 +10,23 @@ from posthog.dataclasses import frozen
#
# 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", "lookup_rows"]
+ParseKind = Literal[
+ "items",
+ "ranked_keywords",
+ "monthly_items",
+ "result_rows",
+ "lookup_rows",
+ "keyword_monthly_searches",
+ "serp_items",
+]
+
+# What an endpoint is scoped to, which decides what the transport fans out over and which field
+# carries that value in the request payload:
+# target — one request per configured target domain ("target")
+# keyword — one request per configured keyword ("keyword"); the SERP endpoints take one
+# keyword_batch — a single request carrying every configured keyword ("keywords")
+# global — a single untargeted request; the free Labs reference lookups
+EndpointScope = Literal["target", "keyword", "keyword_batch", "global"]
@frozen
@@ -19,14 +35,13 @@ class DataForSEOEndpointConfig:
# Path under the API base (https://api.dataforseo.com/v3).
path: str
kind: ParseKind
- # 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.
+ # Unique across the whole table. A target-scoped endpoint fans out over the user's configured
+ # targets, so the injected `target` is always part of its key; a keyword-scoped one keys on
+ # the keyword instead.
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
+ scope: EndpointScope = "target"
# 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
@@ -128,13 +143,62 @@ DATAFORSEO_ENDPOINTS: dict[str, DataForSEOEndpointConfig] = {
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,
),
+ "backlinks": DataForSEOEndpointConfig(
+ name="backlinks",
+ path="/backlinks/backlinks/live",
+ kind="items",
+ # A page can link to the same URL more than once, with a different anchor or as an image,
+ # so the link endpoints are what identify a row rather than the page pair alone.
+ primary_keys=["target", "url_from", "url_to", "item_type", "anchor"],
+ paginated=True,
+ localized=False,
+ # A large domain has millions of backlinks and the transport keeps only the first few
+ # pages, so sort by rank to make that slice the highest-value links rather than an
+ # arbitrary window that shifts between syncs.
+ extra_payload={"include_subdomains": True, "order_by": ["rank,desc"]},
+ description="Individual backlinks pointing at each target domain, with the linking page, anchor, rank, spam score, and first- and last-seen dates (one row per backlink). Only the highest-ranking backlinks are synced. Requires an active DataForSEO Backlinks API subscription. Full refresh.",
+ should_sync_default=False,
+ ),
+ "backlinks_anchors": DataForSEOEndpointConfig(
+ name="backlinks_anchors",
+ path="/backlinks/anchors/live",
+ kind="items",
+ primary_keys=["target", "anchor"],
+ paginated=True,
+ localized=False,
+ extra_payload={"include_subdomains": True, "order_by": ["backlinks,desc"]},
+ description="Anchor text used to link to each target domain, with per-anchor backlink, referring domain, and spam score metrics (one row per anchor). Requires an active DataForSEO Backlinks API subscription. Full refresh.",
+ should_sync_default=False,
+ ),
+ "historical_search_volume": DataForSEOEndpointConfig(
+ name="historical_search_volume",
+ path="/dataforseo_labs/google/historical_search_volume/live",
+ kind="keyword_monthly_searches",
+ primary_keys=["keyword", "year", "month"],
+ # The endpoint takes up to 700 keywords per request, so every configured keyword fits in
+ # one billed request.
+ scope="keyword_batch",
+ partition_key="date",
+ description="Monthly Google search volume history for each configured keyword (one row per keyword per month). Needs keywords configured on the source. Full refresh.",
+ should_sync_default=False,
+ ),
+ "serp_organic": DataForSEOEndpointConfig(
+ name="serp_organic",
+ path="/serp/google/organic/live/advanced",
+ kind="serp_items",
+ # rank_absolute is the element's position among every element in the keyword's SERP.
+ primary_keys=["keyword", "type", "rank_absolute"],
+ scope="keyword",
+ description="A snapshot of the Google results page for each configured keyword, one row per SERP element with its type, rank, and URL. Covers the first page of results. Needs keywords configured on the source. 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,
+ scope="global",
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.",
),
@@ -144,10 +208,13 @@ DATAFORSEO_ENDPOINTS: dict[str, DataForSEOEndpointConfig] = {
kind="lookup_rows",
primary_keys=["category_code"],
method="GET",
- targeted=False,
+ scope="global",
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.",
),
}
+# The endpoint scopes that sync nothing until keywords are configured on the source.
+KEYWORD_SCOPES: tuple[EndpointScope, ...] = ("keyword", "keyword_batch")
+
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 c1aaaa2027a2..dd5874e145ea 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
@@ -21,9 +21,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo
DataForSEOResumeConfig,
dataforseo_source,
validate_credentials as validate_dataforseo_credentials,
+ validate_keywords,
validate_targets,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.settings import DATAFORSEO_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.settings import (
+ DATAFORSEO_ENDPOINTS,
+ KEYWORD_SCOPES,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dataforseo import (
DataForSEOSourceConfig,
)
@@ -50,6 +54,8 @@ class DataForSEOSource(ResumableSource[DataForSEOSourceConfig, DataForSEOResumeC
Find your API login and password on the [DataForSEO API access page](https://app.dataforseo.com/api-access).
+Add keywords to sync the search volume history and SERP snapshot tables, which are keyword-scoped rather than domain-scoped.
+
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",
@@ -80,6 +86,14 @@ Note: DataForSEO bills per API request, so syncing these tables consumes account
placeholder="example.com, posthog.com",
secret=False,
),
+ SourceFieldInputConfig(
+ name="keywords",
+ label="Keywords (comma-separated)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="product analytics, session replay",
+ secret=False,
+ ),
SourceFieldInputConfig(
name="location_name",
label="Location",
@@ -102,10 +116,10 @@ Note: DataForSEO bills per API request, so syncing these tables consumes account
@property
def connection_host_fields(self) -> list[str]:
- # `targets` selects which domains the stored credential runs paid requests against, so
- # retargeting it must re-require the secret — a preserved credential can't be pointed at
- # attacker-chosen domains without re-entering the password.
- return ["targets"]
+ # `targets` and `keywords` select which paid requests the stored credential runs, so
+ # changing either must re-require the secret — a preserved credential can't be pointed at
+ # attacker-chosen domains or keywords without re-entering the password.
+ return ["targets", "keywords"]
def get_non_retryable_errors(self) -> dict[str, str | None]:
invalid_credentials_message = (
@@ -182,6 +196,10 @@ Note: DataForSEO bills per API request, so syncing these tables consumes account
if targets_error:
return False, targets_error
+ _, keywords_error = validate_keywords(config.keywords)
+ if keywords_error:
+ return False, keywords_error
+
if validate_dataforseo_credentials(config.api_login, config.api_password):
return True, None
@@ -196,15 +214,27 @@ Note: DataForSEO bills per API request, so syncing these tables consumes account
resumable_source_manager: ResumableSourceManager[DataForSEOResumeConfig],
inputs: SourceInputs,
) -> SourceResponse:
- # Re-validate here so a previously-saved oversized target list can't trigger a runaway sync.
+ # Re-validate here so a previously-saved oversized target or keyword list can't trigger a
+ # runaway sync.
targets, targets_error = validate_targets(config.targets)
if targets_error:
raise ValueError(f"DataForSEO source misconfigured: {targets_error}")
+ keywords, keywords_error = validate_keywords(config.keywords)
+ if keywords_error:
+ raise ValueError(f"DataForSEO source misconfigured: {keywords_error}")
+
+ if not keywords and DATAFORSEO_ENDPOINTS[inputs.schema_name].scope in KEYWORD_SCOPES:
+ raise ValueError(
+ f"The {inputs.schema_name} table is keyword-scoped. Add at least one keyword to the "
+ "DataForSEO source, then resync."
+ )
+
return dataforseo_source(
api_login=config.api_login,
api_password=config.api_password,
targets=targets,
+ keywords=keywords,
location_name=(config.location_name or "").strip() or DEFAULT_LOCATION_NAME,
language_name=(config.language_name or "").strip() or DEFAULT_LANGUAGE_NAME,
endpoint=inputs.schema_name,
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 cab0b653510c..375f6a1a8ac4 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
@@ -8,6 +8,7 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.dataforseo import (
DATAFORSEO_BASE_URL,
+ MAX_KEYWORDS,
MAX_PAGES_PER_TARGET,
MAX_TARGETS,
PAGE_SIZE,
@@ -18,17 +19,21 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo
_request_task,
dataforseo_source,
get_rows,
+ parse_keywords,
parse_targets,
validate_credentials,
+ validate_keywords,
validate_targets,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.settings import (
DATAFORSEO_ENDPOINTS,
ENDPOINTS,
+ KEYWORD_SCOPES,
)
-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]
+TARGETED_ENDPOINTS = [name for name, config in DATAFORSEO_ENDPOINTS.items() if config.scope == "target"]
+UNTARGETED_ENDPOINTS = [name for name, config in DATAFORSEO_ENDPOINTS.items() if config.scope != "target"]
+KEYWORD_ENDPOINTS = [name for name, config in DATAFORSEO_ENDPOINTS.items() if config.scope in KEYWORD_SCOPES]
def _resp(body: Any, status: int = 200) -> Any:
@@ -71,6 +76,7 @@ def _drive(
manager: Any,
responses: list[Any],
targets: list[str] | None = None,
+ keywords: list[str] | None = None,
) -> tuple[list[tuple[str, Any]], list[list[dict[str, Any]]]]:
# Drives get_rows with a mocked tracked session, returning ((url, payload) pairs, batches).
# A GET lookup records a None payload.
@@ -95,6 +101,7 @@ def _drive(
api_login="login",
api_password="password",
targets=targets or ["example.com"],
+ keywords=keywords or [],
location_name="United States",
language_name="English",
endpoint=endpoint,
@@ -139,6 +146,40 @@ class TestParseTargets:
assert len(parsed) == MAX_TARGETS
+class TestParseKeywords:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("posthog", ["posthog"]),
+ ("Product Analytics", ["product analytics"]),
+ ("product analytics", ["product analytics"]),
+ ("a, b,, ,a", ["a", "b"]),
+ ("", []),
+ ],
+ )
+ def test_normalizes_and_dedupes(self, raw: str, expected: list[str]) -> None:
+ # DataForSEO lower-cases keywords server-side, so rows come back keyed this way.
+ assert parse_keywords(raw) == expected
+
+ def test_blank_input_is_not_an_error(self) -> None:
+ # The keywords field is optional; only the keyword-scoped tables require it.
+ parsed, error = validate_keywords(None)
+ assert parsed == []
+ assert error is None
+
+ def test_too_many_keywords_is_an_error(self) -> None:
+ raw = ", ".join(f"kw{i}" for i in range(MAX_KEYWORDS + 1))
+ _, error = validate_keywords(raw)
+ assert error is not None
+ assert str(MAX_KEYWORDS) in error
+
+ def test_max_keywords_is_allowed(self) -> None:
+ raw = ", ".join(f"kw{i}" for i in range(MAX_KEYWORDS))
+ parsed, error = validate_keywords(raw)
+ assert error is None
+ assert len(parsed) == MAX_KEYWORDS
+
+
class TestBodyStatusClassification:
@pytest.mark.parametrize("status_code", [None, 20000])
def test_success_codes_pass(self, status_code: int | None) -> None:
@@ -310,6 +351,7 @@ class TestGetRows:
api_login="login",
api_password="password",
targets=["example.com"],
+ keywords=[],
location_name="United States",
language_name="English",
endpoint="ranked_keywords",
@@ -372,6 +414,7 @@ class TestGetRows:
api_login="login",
api_password="password",
targets=["example.com"],
+ keywords=[],
location_name="United States",
language_name="English",
endpoint="domain_rank_overview",
@@ -403,6 +446,28 @@ class TestGetRows:
"/backlinks/referring_domains/live",
{"target": "example.com", "include_subdomains": True, "limit": PAGE_SIZE, "offset": 0},
),
+ (
+ "backlinks",
+ "/backlinks/backlinks/live",
+ {
+ "target": "example.com",
+ "include_subdomains": True,
+ "order_by": ["rank,desc"],
+ "limit": PAGE_SIZE,
+ "offset": 0,
+ },
+ ),
+ (
+ "backlinks_anchors",
+ "/backlinks/anchors/live",
+ {
+ "target": "example.com",
+ "include_subdomains": True,
+ "order_by": ["backlinks,desc"],
+ "limit": PAGE_SIZE,
+ "offset": 0,
+ },
+ ),
("backlinks_history", "/backlinks/history/live", {"target": "example.com"}),
(
"backlinks_timeseries_summary",
@@ -461,6 +526,150 @@ class TestGetRows:
assert "target" not in batches[0][0]
manager.save_state.assert_not_called()
+ def test_historical_search_volume_sends_every_keyword_in_one_request(self) -> None:
+ manager = _manager()
+ item = {
+ "se_type": "google",
+ "keyword": "posthog",
+ "location_code": 2840,
+ "language_code": "en",
+ "search_partners": False,
+ "keyword_info": {
+ "search_volume": 1000,
+ "monthly_searches": [
+ {"year": 2024, "month": 7, "search_volume": 450},
+ {"year": 2024, "month": 6, "search_volume": 300},
+ ],
+ },
+ }
+ calls, batches = _drive(
+ "historical_search_volume",
+ manager,
+ [_resp(_body([_items_result([item])]))],
+ targets=["a.com", "b.com"],
+ keywords=["posthog", "session replay"],
+ )
+
+ # The endpoint takes the whole keyword list, and has no target fan-out to repeat it over.
+ assert calls == [
+ (
+ f"{DATAFORSEO_BASE_URL}/dataforseo_labs/google/historical_search_volume/live",
+ {
+ "keywords": ["posthog", "session replay"],
+ "location_name": "United States",
+ "language_name": "English",
+ },
+ )
+ ]
+ assert batches == [
+ [
+ {
+ "keyword": "posthog",
+ "se_type": "google",
+ "location_code": 2840,
+ "language_code": "en",
+ "search_partners": False,
+ "year": 2024,
+ "month": 7,
+ "date": "2024-07-01",
+ "search_volume": 450,
+ },
+ {
+ "keyword": "posthog",
+ "se_type": "google",
+ "location_code": 2840,
+ "language_code": "en",
+ "search_partners": False,
+ "year": 2024,
+ "month": 6,
+ "date": "2024-06-01",
+ "search_volume": 300,
+ },
+ ]
+ ]
+ manager.save_state.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "item",
+ [
+ {"keyword": "posthog", "keyword_info": {}},
+ {"keyword": "posthog", "keyword_info": {"monthly_searches": [{"year": None, "month": 6}]}},
+ {"keyword": None, "keyword_info": {"monthly_searches": [{"year": 2024, "month": 6}]}},
+ ],
+ )
+ def test_historical_search_volume_skips_rows_it_cannot_key(self, item: dict[str, Any]) -> None:
+ # keyword, year and month are the primary key and year/month also derive the partition
+ # column, so a row missing any of them has nowhere to land.
+ manager = _manager()
+ _, batches = _drive(
+ "historical_search_volume", manager, [_resp(_body([_items_result([item])]))], keywords=["posthog"]
+ )
+
+ assert batches == []
+
+ def test_serp_organic_fans_out_per_keyword_and_stamps_crawl_metadata(self) -> None:
+ manager = _manager()
+ result = {
+ "keyword": "posthog",
+ "se_domain": "google.com",
+ "location_code": 2840,
+ "language_code": "en",
+ "check_url": "https://www.google.com/search?q=posthog",
+ "datetime": "2024-08-11 13:24:34 +00:00",
+ "items_count": 1,
+ "items": [{"type": "organic", "rank_absolute": 1, "domain": "posthog.com"}],
+ }
+ calls, batches = _drive(
+ "serp_organic",
+ manager,
+ [_resp(_body([result])), _resp(_body([{**result, "keyword": "session replay", "items": []}]))],
+ keywords=["posthog", "session replay"],
+ )
+
+ # The SERP endpoint takes one keyword per request and has no limit/offset pagination.
+ assert calls == [
+ (
+ f"{DATAFORSEO_BASE_URL}/serp/google/organic/live/advanced",
+ {"keyword": keyword, "location_name": "United States", "language_name": "English"},
+ )
+ for keyword in ["posthog", "session replay"]
+ ]
+ assert batches == [
+ [
+ {
+ "type": "organic",
+ "rank_absolute": 1,
+ "domain": "posthog.com",
+ "keyword": "posthog",
+ "se_domain": "google.com",
+ "location_code": 2840,
+ "language_code": "en",
+ "check_url": "https://www.google.com/search?q=posthog",
+ "datetime": "2024-08-11 13:24:34 +00:00",
+ }
+ ]
+ ]
+
+ def test_serp_organic_resumes_from_saved_keyword(self) -> None:
+ manager = _manager(DataForSEOResumeConfig(keyword="session replay"))
+ calls, _ = _drive(
+ "serp_organic",
+ manager,
+ [_resp(_body([{"keyword": "session replay", "items": []}]))],
+ keywords=["posthog", "session replay"],
+ )
+
+ assert [payload["keyword"] for _, payload in calls] == ["session replay"]
+
+ def test_serp_organic_saves_the_next_keyword(self) -> None:
+ manager = _manager()
+ responses = [_resp(_body([{"keyword": kw, "items": []}])) for kw in ["posthog", "session replay"]]
+
+ _drive("serp_organic", manager, responses, keywords=["posthog", "session replay"])
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [DataForSEOResumeConfig(keyword="session replay", offset=0)]
+
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))
@@ -477,6 +686,7 @@ class TestDataForSEOSourceResponse:
api_login="login",
api_password="password",
targets=["example.com"],
+ keywords=["posthog"],
location_name="United States",
language_name="English",
endpoint=endpoint,
@@ -500,9 +710,16 @@ class TestDataForSEOSourceResponse:
# 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.
+ @pytest.mark.parametrize("endpoint", KEYWORD_ENDPOINTS)
+ def test_keyword_primary_keys_include_keyword(self, endpoint: str) -> None:
+ # A keyword-scoped endpoint aggregates rows from every configured keyword, so the keyword
+ # must be part of the key for table-wide uniqueness.
+ assert "keyword" in DATAFORSEO_ENDPOINTS[endpoint].primary_keys
+
+ @pytest.mark.parametrize("endpoint", UNTARGETED_ENDPOINTS)
+ def test_untargeted_primary_keys_exclude_target(self, endpoint: str) -> None:
+ # Lookup and keyword-scoped rows carry no target column, so keying on one would key
+ # every row on null.
assert "target" not in DATAFORSEO_ENDPOINTS[endpoint].primary_keys
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 b089c20d4dfe..32dc0c15ce1e 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,9 +7,11 @@ 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.dataforseo import MAX_KEYWORDS
from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.settings import (
DATAFORSEO_ENDPOINTS,
ENDPOINTS,
+ KEYWORD_SCOPES,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.dataforseo.source import DataForSEOSource
@@ -20,6 +22,7 @@ def _make_config(
api_login: str = "login",
api_password: str = "password",
targets: str = "example.com, posthog.com",
+ keywords: str | None = None,
location_name: str | None = None,
language_name: str | None = None,
) -> Any:
@@ -27,6 +30,7 @@ def _make_config(
config.api_login = api_login
config.api_password = api_password
config.targets = targets
+ config.keywords = keywords
config.location_name = location_name
config.language_name = language_name
return config
@@ -39,6 +43,7 @@ class TestDataForSEOSource:
"api_login",
"api_password",
"targets",
+ "keywords",
"location_name",
"language_name",
]
@@ -56,14 +61,16 @@ class TestDataForSEOSource:
assert password_field.required is True
assert input_field("api_login").required is True
assert input_field("targets").required is True
- # Location and language fall back to defaults in the transport when left blank.
+ # Location and language fall back to defaults in the transport when left blank, and only
+ # the keyword-scoped tables need keywords.
+ assert input_field("keywords").required is False
assert input_field("location_name").required is False
assert input_field("language_name").required is False
- def test_connection_host_fields_includes_targets(self) -> None:
- # targets selects which domains the stored credential runs paid requests against, so
- # changing it must force re-entry of the secret.
- assert DataForSEOSource().connection_host_fields == ["targets"]
+ def test_connection_host_fields_cover_every_spend_field(self) -> None:
+ # targets and keywords both select what the stored credential spends paid requests on,
+ # so changing either must force re-entry of the secret.
+ assert DataForSEOSource().connection_host_fields == ["targets", "keywords"]
def test_lists_tables_without_credentials(self) -> None:
# get_schemas is a static endpoint catalog with no I/O, so the public docs can render tables.
@@ -85,13 +92,15 @@ class TestDataForSEOSource:
assert schemas["locations_and_languages"].detected_primary_keys == ["location_code"]
assert schemas["categories"].detected_primary_keys == ["category_code"]
- 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.
+ def test_tables_needing_extra_setup_are_off_by_default(self) -> None:
+ # A table that needs the separate paid Backlinks subscription, or keywords the source
+ # form leaves optional, cannot be part of the default selection that one-shot setup
+ # enables — it would fail the first sync.
schemas = {s.name: s for s in DataForSEOSource().get_schemas(_make_config(), team_id=1)}
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
+ endpoint = DATAFORSEO_ENDPOINTS[name]
+ needs_extra_setup = endpoint.path.startswith("/backlinks/") or endpoint.scope in KEYWORD_SCOPES
+ assert schema.should_sync_default is not needs_extra_setup
def test_get_schemas_filters_by_names(self) -> None:
schemas = DataForSEOSource().get_schemas(_make_config(), team_id=1, names=["ranked_keywords"])
@@ -117,6 +126,17 @@ class TestDataForSEOSource:
assert ok is expected_ok
assert message == expected_message
+ def test_validate_credentials_rejects_too_many_keywords(self) -> None:
+ # The SERP table spends a request per keyword per sync, so an oversized list is reported
+ # at setup rather than on the first bill.
+ config = _make_config(keywords=",".join(f"kw{i}" for i in range(MAX_KEYWORDS + 1)))
+ with patch(f"{MODULE}.validate_dataforseo_credentials", return_value=True) as probe:
+ ok, message = DataForSEOSource().validate_credentials(config, team_id=1)
+ assert ok is False
+ assert message is not None
+ assert str(MAX_KEYWORDS) in message
+ probe.assert_not_called()
+
def test_validate_credentials_skips_probe_without_targets(self) -> None:
with patch(f"{MODULE}.validate_dataforseo_credentials") as probe:
ok, _ = DataForSEOSource().validate_credentials(_make_config(targets=""), team_id=1)
@@ -128,14 +148,19 @@ class TestDataForSEOSource:
inputs.schema_name = "ranked_keywords"
inputs.logger = MagicMock()
manager = MagicMock()
- config = _make_config(targets="https://www.Example.com/, posthog.com")
+ config = _make_config(
+ targets="https://www.Example.com/, posthog.com",
+ keywords="Product Analytics, product analytics",
+ )
with patch(f"{MODULE}.dataforseo_source") as source_fn:
DataForSEOSource().source_for_pipeline(config, manager, inputs)
kwargs = source_fn.call_args.kwargs
assert kwargs["api_login"] == "login"
assert kwargs["api_password"] == "password"
- # Targets are normalized (scheme/www stripped, lower-cased) before handing off.
+ # Targets and keywords are normalized (scheme/www stripped, lower-cased, de-duplicated)
+ # before handing off.
assert kwargs["targets"] == ["example.com", "posthog.com"]
+ assert kwargs["keywords"] == ["product analytics"]
assert kwargs["endpoint"] == "ranked_keywords"
assert kwargs["resumable_source_manager"] is manager
@@ -175,6 +200,27 @@ class TestDataForSEOSource:
DataForSEOSource().source_for_pipeline(oversized, MagicMock(), inputs)
source_fn.assert_not_called()
+ @parameterized.expand([("historical_search_volume",), ("serp_organic",)])
+ def test_source_for_pipeline_rejects_keyword_table_without_keywords(self, schema_name: str) -> None:
+ # A keyword-scoped table has nothing to request without keywords, so it must fail with a
+ # message naming the fix rather than syncing an empty table.
+ inputs = MagicMock()
+ inputs.schema_name = schema_name
+ inputs.logger = MagicMock()
+ with patch(f"{MODULE}.dataforseo_source") as source_fn:
+ with pytest.raises(ValueError, match="Add at least one keyword"):
+ DataForSEOSource().source_for_pipeline(_make_config(keywords=" , "), MagicMock(), inputs)
+ source_fn.assert_not_called()
+
+ def test_source_for_pipeline_allows_missing_keywords_for_target_tables(self) -> None:
+ # Only the keyword-scoped tables need keywords; a domain table must still sync without them.
+ inputs = MagicMock()
+ inputs.schema_name = "ranked_keywords"
+ inputs.logger = MagicMock()
+ with patch(f"{MODULE}.dataforseo_source") as source_fn:
+ DataForSEOSource().source_for_pipeline(_make_config(keywords=None), MagicMock(), inputs)
+ assert source_fn.call_args.kwargs["keywords"] == []
+
@parameterized.expand(
[
("http_401", "401 Client Error: Unauthorized for url: https://api.dataforseo.com"),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dataforseo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dataforseo.py
index 272098901bb0..ba19b3ba4441 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dataforseo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dataforseo.py
@@ -9,5 +9,6 @@ class DataForSEOSourceConfig(config.Config):
api_login: str
api_password: str
targets: str
+ keywords: str | None = None
location_name: str | None = None
language_name: str | None = None