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): implement the serpstat import source (#111911)

Tom Owers79db738c3c3b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index d6f281481551..e4eca8708448 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -678,6 +678,7 @@ the row lists both.
| sentinelone | HTTP | requests | ✅ |
| sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |
| sequenzy | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| serpstat | HTTP | requests | ✅ |
| servicem8 | HTTP | requests + `rest_source.RESTClient` | ✅ |
| servicenow | HTTP | requests | ✅ |
| sevdesk | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -1376,7 +1377,6 @@ doesn't conflict with concurrent PRs.
- semrush
- sendpulse
- senseforce
-- serpstat
- service_fusion
- servicetitan
- servicetrade
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/serpstat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/serpstat.py
index 8d5091d9c984..dd58018d1567 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/serpstat.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/serpstat.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SerpstatSourceConfig(config.Config):
- pass
+ api_key: str
+ project_id: str
+ project_region_id: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/canonical_descriptions.py
new file mode 100644
index 000000000000..415dfc06ac3f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/canonical_descriptions.py
@@ -0,0 +1,70 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import DOCS_BASE, ENDPOINTS
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "Projects available to the Serpstat account.",
+ "docs_url": DOCS_BASE + ENDPOINTS["projects"].docs_slug,
+ "columns": {
+ "project_id": "The project identifier.",
+ "project_name": "The project name.",
+ "domain": "The domain associated with the project.",
+ "created_at": "The date and time when the project was created.",
+ "group": "The project group.",
+ "type": "The account's role in the project: owner or reader.",
+ },
+ },
+ "project_keywords": {
+ "description": "Keywords configured for the selected Rank Tracker project.",
+ "docs_url": DOCS_BASE + ENDPOINTS["project_keywords"].docs_slug,
+ "columns": {
+ "project_id": "The configured project identifier.",
+ "id": "The internal identifier for the project keyword.",
+ "keyword_id": "The keyword identifier.",
+ "value": "The keyword text.",
+ "added": "The date and time when the keyword was added.",
+ "tags": "Tag names associated with the keyword.",
+ "urls": "Target URLs for rank checks in each region.",
+ "region": "The tracking status for each project region.",
+ },
+ },
+ "project_regions": {
+ "description": "Search regions and their status for the selected Rank Tracker project.",
+ "docs_url": DOCS_BASE + ENDPOINTS["project_regions"].docs_slug,
+ "columns": {
+ "project_id": "The configured project identifier.",
+ "id": "The project region identifier.",
+ "active": "Whether tracking is active for this region.",
+ "serpType": "The search result type: organic or paid.",
+ "deviceType": "The device type: desktop or mobile.",
+ "searchEngine": "The search engine used for tracking.",
+ "country": "The country used for search results.",
+ "region": "The region used for search results.",
+ "city": "The city used for search results.",
+ "langCode": "The language code used for search results.",
+ },
+ },
+ "project_tags": {
+ "description": "Tags created in the selected Rank Tracker project.",
+ "docs_url": DOCS_BASE + ENDPOINTS["project_tags"].docs_slug,
+ "columns": {
+ "project_id": "The configured project identifier.",
+ "tag_uuid": "The unique tag identifier.",
+ "tag": "The tag name.",
+ },
+ },
+ "project_positions": {
+ "description": "Keyword positions for the configured project region during the last seven days, grouped by keyword.",
+ "docs_url": DOCS_BASE + ENDPOINTS["project_positions"].docs_slug,
+ "columns": {
+ "project_id": "The configured project identifier.",
+ "keyword_id": "The keyword identifier.",
+ "value": "The keyword text.",
+ "added": "The date and time when the keyword was added.",
+ "regions": "Position history, URLs, traffic estimates, and search volume for each returned region.",
+ "tags": "Tag names associated with the keyword.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/serpstat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/serpstat.py
new file mode 100644
index 000000000000..60df4f81216a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/serpstat.py
@@ -0,0 +1,128 @@
+import time
+from datetime import UTC, date, datetime, timedelta
+from typing import Any
+
+import structlog
+from requests import Request, Response
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.serpstat import (
+ SerpstatSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import (
+ ENDPOINTS,
+ MAX_PAGES,
+ PAGE_SIZE,
+ POSITION_HISTORY_DAYS,
+ REQUEST_INTERVAL_SECONDS,
+ RESPONSE_ACTIONS,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+@frozen
+class SerpstatResumeConfig:
+ page: int
+ date_to: str
+
+
+class SerpstatPaginator(PageNumberPaginator):
+ def init_request(self, request: Request) -> None:
+ # JSON-RPC puts pagination inside params, rather than at the body root.
+ request.json["params"]["page"] = self.page
+
+ def update_request(self, request: Request) -> None:
+ time.sleep(REQUEST_INTERVAL_SECONDS)
+ self.init_request(request)
+
+ def update_state(self, response: Response, data: list[Any] | None = None) -> None:
+ super().update_state(response, data)
+ if self.maximum_page == MAX_PAGES and self.page > MAX_PAGES and data:
+ logger.info("serpstat_page_cap_reached", maximum_page=self.maximum_page)
+
+
+def serpstat_resource(
+ config: SerpstatSourceConfig,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ api_version: str,
+ manager: ResumableSourceManager[SerpstatResumeConfig] | None = None,
+ credential_check: bool = False,
+) -> Resource:
+ settings = ENDPOINTS[endpoint]
+ resume = manager.load_state() if manager is not None and manager.can_resume() else None
+ date_to = resume.date_to if resume else datetime.now(UTC).date().isoformat()
+ params: dict[str, Any] = {}
+ if settings.project_param:
+ params[settings.project_param] = int(config.project_id)
+ if settings.total_pages_path:
+ params[settings.size_param] = 20 if credential_check else PAGE_SIZE
+ if endpoint in ("project_keywords", "project_positions"):
+ params.update(sort="added", order="asc")
+ if endpoint == "project_positions":
+ params.update(
+ project_region_ids=[int(config.project_region_id)],
+ date_from=(date.fromisoformat(date_to) - timedelta(days=POSITION_HISTORY_DAYS - 1)).isoformat(),
+ date_to=date_to,
+ )
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": f"https://api.serpstat.com/{api_version}/",
+ "auth": {"type": "api_key", "name": "token", "api_key": config.api_key, "location": "query"},
+ "allow_redirects": False,
+ "allowed_hosts": [],
+ "request_timeout": (10.0, 60.0),
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "table_format": "delta",
+ "write_disposition": "replace",
+ "primary_key": list(settings.primary_keys),
+ "endpoint": {
+ "path": "",
+ "method": "POST",
+ "json": {"id": "posthog", "method": settings.method, "params": params},
+ "data_selector": settings.selector,
+ "data_selector_required": True,
+ "paginator": SerpstatPaginator(
+ base_page=1,
+ total_path=settings.total_pages_path,
+ maximum_page=1 if credential_check else MAX_PAGES,
+ )
+ if settings.total_pages_path
+ else "single_page",
+ "response_actions": RESPONSE_ACTIONS,
+ },
+ }
+ ],
+ }
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if manager is not None and state is not None:
+ manager.save_state(SerpstatResumeConfig(page=int(state["page"]), date_to=date_to))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state={"page": resume.page} if resume else None,
+ )
+ if settings.project_param:
+ resource.add_map(lambda row: {**row, "project_id": int(config.project_id)})
+ return resource
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/settings.py
new file mode 100644
index 000000000000..ef30a0da6a05
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/settings.py
@@ -0,0 +1,88 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
+
+PAGE_SIZE = 100
+MAX_PAGES = 5
+POSITION_HISTORY_DAYS = 7
+REQUEST_INTERVAL_SECONDS = 1.0
+DOCS_BASE = "https://api-docs.serpstat.com/docs/serpstat-public-api/"
+
+
+@frozen
+class SerpstatEndpoint:
+ method: str
+ primary_keys: tuple[str, ...]
+ docs_slug: str
+ selector: str = "result.data"
+ project_param: str | None = "project_id"
+ total_pages_path: str | None = None
+ size_param: str = "size"
+ partition_key: str | None = None
+
+
+ENDPOINTS = {
+ "projects": SerpstatEndpoint(
+ method="ProjectProcedure.getProjects",
+ primary_keys=("project_id",),
+ docs_slug="3ezca25cnkqw5-get-projects",
+ project_param=None,
+ total_pages_path="result.summary_info.page_total",
+ partition_key="created_at",
+ ),
+ "project_keywords": SerpstatEndpoint(
+ method="RtApiProcedure.getProjectKeywords",
+ primary_keys=("project_id", "id"),
+ docs_slug="c0a938de406c8-get-project-keywords",
+ total_pages_path="result.summary_info.pages_count",
+ partition_key="added",
+ ),
+ "project_regions": SerpstatEndpoint(
+ method="RtApiSearchEngineProcedure.getProjectRegions",
+ primary_keys=("project_id", "id"),
+ docs_slug="f57863602271e-get-project-regions",
+ selector="result.regions",
+ project_param="projectId",
+ ),
+ "project_tags": SerpstatEndpoint(
+ method="RtApiProcedure.getProjectTags",
+ primary_keys=("project_id", "tag_uuid"),
+ docs_slug="233a6b97f4943-get-project-tags",
+ ),
+ "project_positions": SerpstatEndpoint(
+ method="RtApiProcedure.getProjectPositions",
+ primary_keys=("project_id", "keyword_id"),
+ docs_slug="e78a1e5708d44-get-project-positions",
+ total_pages_path="result.summary_info.pages_count",
+ size_param="page_size",
+ partition_key="added",
+ ),
+}
+
+AUTH_ERROR = "Serpstat authentication failed. Check your API token and API access for your plan."
+QUOTA_ERROR = "Serpstat API credits are exhausted. Add credits or wait for your allowance to reset."
+REQUEST_ERROR = "Serpstat rejected the request. Check your project ID, region ID, and API access."
+
+_RATE_LIMIT_RESPONSE_ACTIONS: list[ResponseAction] = [
+ {"content": message, "action": "retry", "message": "Serpstat request rate exceeded. Try again later."}
+ for message in ("Query frequency exceeded", "Too many queries")
+]
+
+RESPONSE_ACTIONS: list[ResponseAction] = [
+ *_RATE_LIMIT_RESPONSE_ACTIONS,
+ {"json_field": "error.code", "json_values": [429, -429], "action": "retry"},
+ {"json_field": "error.code", "json_values": [500, -32603], "action": "retry"},
+ {"status_code": 401, "action": "raise", "message": AUTH_ERROR},
+ {"status_code": 402, "action": "raise", "message": QUOTA_ERROR},
+ {"json_field": "error.code", "json_values": [-32012, 32012, 402], "action": "raise", "message": QUOTA_ERROR},
+ {"content": "Not enough credits", "action": "raise", "message": QUOTA_ERROR},
+ {"content": "Plan credit exceeded", "action": "raise", "message": QUOTA_ERROR},
+ {"content": "Pricing plan credits exceeded", "action": "raise", "message": QUOTA_ERROR},
+ {"json_field": "error.code", "json_values": [-32020, 401, 403], "action": "raise", "message": AUTH_ERROR},
+ {"status_code": 403, "action": "raise", "message": AUTH_ERROR},
+ {"content": "Invalid token", "action": "raise", "message": AUTH_ERROR},
+ {"content": "Problems with authorization", "action": "raise", "message": AUTH_ERROR},
+ {"content": "API not allowed for your plan", "action": "raise", "message": AUTH_ERROR},
+ {"status_code": 400, "action": "raise", "message": REQUEST_ERROR},
+ {"content": '"error"', "action": "raise", "message": REQUEST_ERROR},
+]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/source.py
index c119e1e8b5dc..fdcdd41218de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/source.py
@@ -1,27 +1,182 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from requests import RequestException
+
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.serpstat import (
SerpstatSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.serpstat import (
+ SerpstatResumeConfig,
+ serpstat_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import (
+ AUTH_ERROR,
+ DOCS_BASE,
+ ENDPOINTS,
+ QUOTA_ERROR,
+ REQUEST_ERROR,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SerpstatSource(SimpleSource[SerpstatSourceConfig]):
+class SerpstatSource(ResumableSource[SerpstatSourceConfig, SerpstatResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = ("v4",)
+ default_version = "v4"
+ api_docs_url = f"{DOCS_BASE}jenasqbwtxdlr-introduction-to-serpstat-api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SERPSTAT
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {message: message for message in (AUTH_ERROR, QUOTA_ERROR, REQUEST_ERROR)}
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SerpstatSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return [
+ SourceSchema(
+ name=name,
+ supports_incremental=False,
+ supports_append=False,
+ detected_primary_keys=list(endpoint.primary_keys),
+ description=CANONICAL_DESCRIPTIONS[name]["description"],
+ )
+ for name, endpoint in ENDPOINTS.items()
+ if names is None or name in names
+ ]
+
+ def validate_credentials(
+ self,
+ config: SerpstatSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ for label, value in (("project ID", config.project_id), ("project region ID", config.project_region_id)):
+ try:
+ if int(value) <= 0:
+ raise ValueError
+ except (ValueError, TypeError):
+ return False, f"Enter a positive integer for the Serpstat {label}."
+ try:
+ list(
+ serpstat_resource(
+ config, "projects", team_id, "", self.resolve_api_version(api_version), credential_check=True
+ )
+ )
+ except ValueError as error:
+ message = str(error)
+ return False, message if message in self.get_non_retryable_errors() else REQUEST_ERROR
+ except (RequestException, RESTClientRetryableError):
+ return False, "Could not reach Serpstat. Try again later."
+ return True, None
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SerpstatResumeConfig]:
+ return ResumableSourceManager(inputs, SerpstatResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SerpstatSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SerpstatResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ endpoint = ENDPOINTS[inputs.schema_name]
+ resource = serpstat_resource(
+ config,
+ inputs.schema_name,
+ inputs.team_id,
+ inputs.job_id,
+ self.resolve_api_version(inputs.api_version),
+ resumable_source_manager,
+ )
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=list(endpoint.primary_keys),
+ partition_keys=[endpoint.partition_key] if endpoint.partition_key else None,
+ partition_mode="datetime" if endpoint.partition_key else None,
+ partition_format="month" if endpoint.partition_key else None,
+ sort_mode="asc" if inputs.schema_name in ("project_keywords", "project_positions") else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.SERPSTAT,
- category=DataWarehouseSourceCategory.ADVERTISING,
+ category=DataWarehouseSourceCategory.ANALYTICS,
label="Serpstat",
iconPath="/static/services/serpstat.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/serpstat",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "Create an API token on your [Serpstat profile](https://serpstat.com/users/profile/). "
+ "API access requires the Team plan or higher. "
+ "Syncs use your account's API units when Serpstat applies a charge. "
+ "Serpstat lists these methods as free of API credit charges. "
+ "Paginated tables include up to 500 records. Positions cover the last seven days for one project region."
+ ),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="project_id",
+ label="Project ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="123456",
+ secret=False,
+ caption="Copy the project ID from the URL of your Serpstat Rank Tracker report.",
+ ),
+ SourceFieldInputConfig(
+ name="project_region_id",
+ label="Project region ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="123456",
+ secret=False,
+ caption="Use the region ID from the Serpstat getProjectRegions method.",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat.py
new file mode 100644
index 000000000000..28827a1fc23a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat.py
@@ -0,0 +1,267 @@
+import json
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import PreparedRequest, Response, Session
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.serpstat import (
+ SerpstatSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.serpstat import (
+ SerpstatResumeConfig,
+ serpstat_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import (
+ AUTH_ERROR,
+ MAX_PAGES,
+ PAGE_SIZE,
+ QUOTA_ERROR,
+ REQUEST_ERROR,
+)
+
+CONFIG = SerpstatSourceConfig(api_key="example-token+/", project_id="123", project_region_id="456")
+
+
+def request_json(request: PreparedRequest) -> dict[str, Any]:
+ assert request.body is not None
+ return json.loads(request.body)
+
+
+def transport() -> Iterator[tuple[list[PreparedRequest], list[tuple[int, dict[str, Any]]]]]:
+ sent: list[PreparedRequest] = []
+ responses: list[tuple[int, dict[str, Any]]] = []
+
+ def send(request: PreparedRequest, **kwargs: Any) -> Response:
+ sent.append(request)
+ status, body = responses.pop(0)
+ response = Response()
+ response.status_code = status
+ assert request.url is not None
+ response.url = request.url
+ response.request = request
+ response.headers["Content-Type"] = "application/json"
+ response._content = json.dumps(body).encode()
+ return response
+
+ with Session() as session:
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session",
+ return_value=session,
+ ),
+ patch.object(session, "send", side_effect=send),
+ ):
+ yield sent, responses
+
+
+ ("endpoint", "method", "params", "result", "row"),
+ [
+ (
+ "projects",
+ "ProjectProcedure.getProjects",
+ {"size": 100, "page": 1},
+ {"data": [{"project_id": "123"}], "summary_info": {"page_total": 1}},
+ {"project_id": "123"},
+ ),
+ (
+ "project_keywords",
+ "RtApiProcedure.getProjectKeywords",
+ {"project_id": 123, "size": 100, "page": 1, "sort": "added", "order": "asc"},
+ {"data": [{"id": 7, "keyword_id": 8}], "summary_info": {"pages_count": 1}},
+ {"id": 7, "keyword_id": 8, "project_id": 123},
+ ),
+ (
+ "project_regions",
+ "RtApiSearchEngineProcedure.getProjectRegions",
+ {"projectId": 123},
+ {"projectId": 123, "regions": [{"id": 456, "active": True}]},
+ {"id": 456, "active": True, "project_id": 123},
+ ),
+ (
+ "project_tags",
+ "RtApiProcedure.getProjectTags",
+ {"project_id": 123},
+ {"data": [{"tag_uuid": "example-tag", "tag": "blog"}]},
+ {"tag_uuid": "example-tag", "tag": "blog", "project_id": 123},
+ ),
+ (
+ "project_positions",
+ "RtApiProcedure.getProjectPositions",
+ {
+ "project_id": 123,
+ "project_region_ids": [456],
+ "page_size": 100,
+ "page": 1,
+ "sort": "added",
+ "order": "asc",
+ "date_from": "2026-09-29",
+ "date_to": "2026-10-05",
+ },
+ {
+ "data": [{"keyword_id": 8, "regions": [{"project_region_id": 456, "positions": []}]}],
+ "summary_info": {"pages_count": 1},
+ },
+ {"keyword_id": 8, "project_id": 123, "regions": [{"project_region_id": 456, "positions": []}]},
+ ),
+ ],
+)
+def test_request_and_rows(
+ transport: tuple[list[PreparedRequest], list[tuple[int, dict[str, Any]]]],
+ endpoint: str,
+ method: str,
+ params: dict[str, Any],
+ result: dict[str, Any],
+ row: dict[str, Any],
+) -> None:
+ sent, responses = transport
+ responses.append((200, {"id": "posthog", "result": result}))
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SerpstatResumeConfig(page=1, date_to="2026-10-05")
+ resource = serpstat_resource(CONFIG, endpoint, 1, "test-job", "v4", manager)
+ assert list(resource) == [[row]]
+ assert len(sent) == 1
+ request = sent[0]
+ assert request.method == "POST"
+ assert request.url is not None
+ assert urlsplit(request.url).path == "/v4/"
+ assert parse_qs(urlsplit(request.url).query) == {"token": [CONFIG.api_key]}
+ assert "Authorization" not in request.headers
+ assert request.headers["Content-Type"] == "application/json"
+ assert request_json(request) == {"id": "posthog", "method": method, "params": params}
+ manager.save_state.assert_not_called()
+
+
[email protected]("endpoint,total_key", [("projects", "page_total"), ("project_keywords", "pages_count")])
[email protected]("start_page,terminal", [(1, "total"), (2, "empty"), (MAX_PAGES, "cap")])
+def test_pagination_resume_and_caps(
+ transport: tuple[list[PreparedRequest], list[tuple[int, dict[str, Any]]]],
+ endpoint: str,
+ total_key: str,
+ start_page: int,
+ terminal: str,
+) -> None:
+ sent, responses = transport
+ total = start_page + 1 if terminal == "total" else 100
+ row = {"id": 1, "project_id": "123"}
+ responses.append((200, {"result": {"data": [row] * PAGE_SIZE, "summary_info": {total_key: total}}}))
+ if terminal != "cap":
+ responses.append(
+ (200, {"result": {"data": [row] if terminal == "total" else [], "summary_info": {total_key: total}}})
+ )
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = start_page != 1
+ manager.load_state.return_value = SerpstatResumeConfig(page=start_page, date_to="2026-01-02")
+ list(serpstat_resource(CONFIG, endpoint, 1, "test-job", "v4", manager))
+ assert [request_json(request)["params"]["page"] for request in sent] == (
+ [start_page] if terminal == "cap" else [start_page, start_page + 1]
+ )
+ assert manager.save_state.call_count == (0 if terminal == "cap" else 1)
+ if terminal != "cap":
+ assert manager.save_state.call_args.args[0].page == start_page + 1
+ if start_page == 1:
+ manager.load_state.assert_not_called()
+
+
+def test_positions_resume_keeps_original_date_window(
+ transport: tuple[list[PreparedRequest], list[tuple[int, dict[str, Any]]]],
+) -> None:
+ sent, responses = transport
+ responses.extend(
+ [
+ (200, {"result": {"data": [{"keyword_id": 1}], "summary_info": {"pages_count": 3}}}),
+ (200, {"result": {"data": [{"keyword_id": 2}], "summary_info": {"pages_count": 3}}}),
+ ]
+ )
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SerpstatResumeConfig(page=2, date_to="2025-01-01")
+ list(serpstat_resource(CONFIG, "project_positions", 1, "test-job", "v4", manager))
+ for request in sent:
+ params = request_json(request)["params"]
+ assert params["date_from"] == "2024-12-26"
+ assert params["date_to"] == "2025-01-01"
+ manager.save_state.assert_called_once_with(SerpstatResumeConfig(page=3, date_to="2025-01-01"))
+
+
+ "status,code,message,expected",
+ [
+ (200, -32020, "Invalid token!", AUTH_ERROR),
+ (200, -32602, "Invalid token", AUTH_ERROR),
+ (401, 401, "Unauthorized", AUTH_ERROR),
+ (403, 403, "Problems with authorization", AUTH_ERROR),
+ (200, -32012, "Credits exceeded", QUOTA_ERROR),
+ (200, 32012, "Credits exceeded", QUOTA_ERROR),
+ (200, 403, "Not enough credits", QUOTA_ERROR),
+ (200, 402, "Pricing plan credits exceeded", QUOTA_ERROR),
+ (402, 402, "Payment required", QUOTA_ERROR),
+ (200, -32602, "Invalid project ID", REQUEST_ERROR),
+ (400, 400, "Invalid request", REQUEST_ERROR),
+ ],
+)
+def test_errors_fail_without_exposing_vendor_message(
+ transport: tuple[list[PreparedRequest], list[tuple[int, dict[str, Any]]]],
+ status: int,
+ code: int,
+ message: str,
+ expected: str,
+) -> None:
+ sent, responses = transport
+ responses.append((status, {"error": {"code": code, "message": message + " " + CONFIG.api_key}}))
+ with pytest.raises(ValueError) as error:
+ list(serpstat_resource(CONFIG, "projects", 1, "test-job", "v4"))
+ assert str(error.value) == expected
+ assert len(sent) == 1
+
+
+ "status,code,message",
+ [
+ (200, -32000, "Query frequency exceeded"),
+ (200, 429, "Too many queries"),
+ (429, 429, "Rate limit"),
+ (503, 500, "Unavailable"),
+ ],
+)
+def test_transient_errors_use_framework_retry(
+ transport: tuple[list[PreparedRequest], list[tuple[int, dict[str, Any]]]],
+ status: int,
+ code: int,
+ message: str,
+) -> None:
+ sent, responses = transport
+ responses.extend(
+ [
+ (status, {"error": {"code": code, "message": message}}),
+ (200, {"result": {"data": [], "summary_info": {"page_total": 0}}}),
+ ]
+ )
+ assert list(serpstat_resource(CONFIG, "projects", 1, "test-job", "v4")) == []
+ assert len(sent) == 2
+
+
+def test_missing_result_fails_instead_of_replacing_table_with_empty_data(
+ transport: tuple[list[PreparedRequest], list[tuple[int, dict[str, Any]]]],
+) -> None:
+ _, responses = transport
+ responses.append((200, {"id": "posthog", "result": {"unexpected": []}}))
+ with pytest.raises(ValueError):
+ list(serpstat_resource(CONFIG, "projects", 1, "test-job", "v4"))
+
+
+def test_credential_check_stops_after_one_free_page(
+ transport: tuple[list[PreparedRequest], list[tuple[int, dict[str, Any]]]],
+) -> None:
+ sent, responses = transport
+ responses.append((200, {"result": {"data": [{"project_id": "123"}], "summary_info": {"page_total": 50}}}))
+ list(serpstat_resource(CONFIG, "projects", 1, "", "v4", credential_check=True))
+ assert len(sent) == 1
+ assert request_json(sent[0])["params"] == {"page": 1, "size": 20}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat_source.py
new file mode 100644
index 000000000000..bc981f7a9123
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/serpstat/tests/test_serpstat_source.py
@@ -0,0 +1,63 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.serpstat import (
+ SerpstatSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.settings import AUTH_ERROR, QUOTA_ERROR
+from products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.source import SerpstatSource
+
+RESOURCE = "products.warehouse_sources.backend.temporal.data_imports.sources.serpstat.source.serpstat_resource"
+
+
[email protected]("field", ["project_id", "project_region_id"])
[email protected]("value", ["", "0", "-1", "abc", "1.5"])
+def test_invalid_ids_do_not_call_api(field: str, value: str) -> None:
+ config = SerpstatSourceConfig.from_dict(
+ {"api_key": "example-token", "project_id": "123", "project_region_id": "456", field: value}
+ )
+ with patch(RESOURCE) as resource:
+ valid, error = SerpstatSource().validate_credentials(config, 1)
+ assert not valid
+ assert error is not None
+ assert "positive integer" in error
+ resource.assert_not_called()
+
+
+ "failure,expected",
+ [
+ (None, (True, None)),
+ (ValueError(AUTH_ERROR), (False, AUTH_ERROR)),
+ (ValueError(QUOTA_ERROR), (False, QUOTA_ERROR)),
+ (RESTClientRetryableError("Unavailable"), (False, "Could not reach Serpstat. Try again later.")),
+ ],
+)
+def test_credential_results(failure: Exception | None, expected: tuple[bool, str | None]) -> None:
+ config = SerpstatSourceConfig(api_key="example-token", project_id="123", project_region_id="456")
+ with patch(RESOURCE, side_effect=failure, return_value=[]) as resource:
+ assert SerpstatSource().validate_credentials(config, 1) == expected
+ resource.assert_called_once_with(config, "projects", 1, "", "v4", credential_check=True)
+
+
[email protected]("incremental", [False, True])
+def test_pipeline_does_not_apply_unavailable_incremental_filter(incremental: bool) -> None:
+ config = SerpstatSourceConfig(api_key="example-token", project_id="123", project_region_id="456")
+ inputs = MagicMock(
+ schema_name="project_keywords",
+ team_id=1,
+ job_id="test-job",
+ api_version=None,
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value="2026-01-01",
+ )
+ manager = MagicMock()
+ with patch(RESOURCE) as resource:
+ response = SerpstatSource().source_for_pipeline(config, manager, inputs)
+ resource.assert_called_once_with(config, "project_keywords", 1, "test-job", "v4", manager)
+ assert response.primary_keys == ["project_id", "id"]
+ assert response.partition_keys == ["added"]
+ assert response.sort_mode == "asc"