: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Similarweb source (#77130)
Tom Owers481f4ac0d22b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0ed72bb5d161..2185dfae53bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -559,6 +559,7 @@ the row lists both.| shutterstock | HTTP | requests + `rest_source.RESTClient` | ✅ || signoz | HTTP | requests | ✅ || simfin | HTTP | requests | ✅ |+| similarweb | HTTP | requests | ✅ || simplecast | HTTP | requests | ✅ || simplesat | HTTP | requests | ✅ || skyvern | HTTP | requests | ✅ |@@ -1305,7 +1306,6 @@ doesn't conflict with concurrent PRs.- sigma_computing- signnow- sim-- similarweb- simplecast- simplesat- simprodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/similarweb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/similarweb.pyindex d517e271d673..89c46950fdaf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/similarweb.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/similarweb.py@@ -1,9 +1,15 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass SimilarwebSourceConfig(config.Config):- pass+ api_key: str+ domains: str+ country: str | None = None+ granularity: Literal["monthly", "weekly", "daily"] = config.value(default="monthly")+ start_date: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/canonical_descriptions.pynew file mode 100644index 000000000000..ac2d4d74ca92--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/canonical_descriptions.py@@ -0,0 +1,91 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_ENGAGEMENT_DOCS = "https://developers.similarweb.com/reference/visits"++_SHARED_COLUMNS = {+ "domain": "Domain the metric was requested for, as configured on the source.",+ "country": "Country filter the metric was requested with; `world` for worldwide data.",+ "granularity": "Length of the period each row covers: daily, weekly or monthly.",+ "date": "Start of the period the row measures, as a timestamp.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "visits": {+ "description": "Estimated total visits to the domain from desktop and mobile web, per period.",+ "docs_url": _ENGAGEMENT_DOCS,+ "columns": {+ **_SHARED_COLUMNS,+ "visits": "Estimated number of visits in the period, desktop and mobile web combined.",+ },+ },+ "page_views": {+ "description": "Estimated total page views for the domain from desktop and mobile web, per period.",+ "docs_url": "https://developers.similarweb.com/reference/page-views",+ "columns": {+ **_SHARED_COLUMNS,+ "pages_views": "Estimated number of page views in the period. Similarweb returns this field as `pages_views`.",+ },+ },+ "pages_per_visit": {+ "description": "Average number of pages viewed during a visit to the domain, per period.",+ "docs_url": "https://developers.similarweb.com/reference/pages-per-visit",+ "columns": {+ **_SHARED_COLUMNS,+ "pages_per_visit": "Average pages viewed per visit in the period.",+ },+ },+ "average_visit_duration": {+ "description": "Average length of a visit to the domain, in seconds, per period.",+ "docs_url": "https://developers.similarweb.com/reference/average-visit-duration-all-traffic",+ "columns": {+ **_SHARED_COLUMNS,+ "average_visit_duration": "Average visit duration in seconds for the period.",+ },+ },+ "bounce_rate": {+ "description": "Share of visits to the domain that ended without further interaction, per period.",+ "docs_url": "https://developers.similarweb.com/reference/bounce-rate",+ "columns": {+ **_SHARED_COLUMNS,+ "bounce_rate": "Bounce rate for the period as a fraction between 0 and 1.",+ },+ },+ "global_rank": {+ "description": "Similarweb's worldwide traffic rank for the domain, by month. "+ "The endpoint is worldwide and monthly only, so it takes no country or granularity filter.",+ "docs_url": "https://developers.similarweb.com/reference/global-rank",+ "columns": {+ "domain": "Domain the rank was requested for, as configured on the source.",+ "date": "First day of the month the rank applies to, as a timestamp.",+ "global_rank": "Worldwide rank of the domain that month, where 1 is the most visited site.",+ },+ },+ "traffic_sources": {+ "description": "Visits to the domain split by marketing channel and by organic versus paid, per period.",+ "docs_url": "https://developers.similarweb.com/reference/traffic-sources-overview",+ "columns": {+ **_SHARED_COLUMNS,+ "source_type": "Marketing channel the visits came from: Search, Social, Mail, Display Ads, Direct or Referrals.",+ "organic": "Estimated unpaid visits from the channel in the period.",+ "paid": "Estimated paid visits from the channel in the period.",+ },+ },+ "traffic_by_country": {+ "description": "Traffic share and engagement for the domain broken down by visitor country, "+ "aggregated over the whole synced window rather than per period.",+ "docs_url": "https://developers.similarweb.com/reference/geography-total",+ "columns": {+ "domain": "Domain the breakdown was requested for, as configured on the source.",+ "country": "ISO 3166-1 numeric code of the visitors' country.",+ "country_name": "Name of the visitors' country.",+ "share": "Share of the domain's total visits that came from the country, between 0 and 1.",+ "visits": "Estimated visits from the country over the requested window.",+ "pages_per_visit": "Average pages viewed per visit by visitors from the country.",+ "average_time": "Average visit duration in seconds for visitors from the country.",+ "bounce_rate": "Bounce rate for visitors from the country, as a fraction between 0 and 1.",+ "rank": "Rank of the domain within that country's websites.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/settings.pynew file mode 100644index 000000000000..e55c96bc1774--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/settings.py@@ -0,0 +1,142 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://api.similarweb.com"+# Free endpoint (no data credits) that reports the account's remaining credits and data access,+# so credential validation costs the customer nothing.+CAPABILITIES_PATH = "/capabilities"++# Every domain costs one request (and at least one data credit) per table per sync, so an+# unbounded list turns a single sync into an unbounded spend against the customer's credit pool.+MAX_DOMAINS = 50++# Rows per yielded chunk once a table's rows have been collected and ordered.+CHUNK_ROWS = 5000++# Results per page on the offset-paginated endpoints.+PAGE_LIMIT = 100++DEFAULT_COUNTRY = "world"++GRANULARITY_OPTIONS = (+ ("monthly", "Monthly"),+ ("weekly", "Weekly"),+ ("daily", "Daily"),+)++VISITS = "visits"+PAGE_VIEWS = "page_views"+PAGES_PER_VISIT = "pages_per_visit"+AVERAGE_VISIT_DURATION = "average_visit_duration"+BOUNCE_RATE = "bounce_rate"+GLOBAL_RANK = "global_rank"+TRAFFIC_SOURCES = "traffic_sources"+TRAFFIC_BY_COUNTRY = "traffic_by_country"+++@dataclass+class SimilarwebEndpointConfig:+ name: str+ # `{domain}` is substituted with each configured domain.+ path: str+ # Body key holding the endpoint's payload (Similarweb names it after the metric).+ data_key: str+ primary_keys: list[str]+ description: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # `date` is the period the row measures and never moves once published, so partitions+ # don't rewrite on later syncs. `None` for tables whose rows carry no period.+ partition_key: str | None = "date"+ # Whether the endpoint accepts the `country` / `granularity` filters. Rank and geo+ # breakdown endpoints take neither.+ accepts_country: bool = True+ accepts_granularity: bool = True+ # Offset-paginated (`limit`/`offset`) rather than a single full-window response.+ paginated: bool = False+++_ENGAGEMENT_PATH = "/v1/website/{domain}/total-traffic-and-engagement"++SIMILARWEB_ENDPOINTS: dict[str, SimilarwebEndpointConfig] = {+ VISITS: SimilarwebEndpointConfig(+ name=VISITS,+ path=f"{_ENGAGEMENT_PATH}/visits",+ data_key="visits",+ primary_keys=["domain", "country", "granularity", "date"],+ description="Estimated desktop and mobile web visits per period for each configured domain",+ incremental_fields=[incremental_field("date")],+ ),+ PAGE_VIEWS: SimilarwebEndpointConfig(+ name=PAGE_VIEWS,+ path=f"{_ENGAGEMENT_PATH}/page-views",+ # Similarweb returns this series under `pages_views`, not `page_views`.+ data_key="pages_views",+ primary_keys=["domain", "country", "granularity", "date"],+ description="Estimated desktop and mobile web page views per period for each configured domain",+ incremental_fields=[incremental_field("date")],+ ),+ PAGES_PER_VISIT: SimilarwebEndpointConfig(+ name=PAGES_PER_VISIT,+ path=f"{_ENGAGEMENT_PATH}/pages-per-visit",+ data_key="pages_per_visit",+ primary_keys=["domain", "country", "granularity", "date"],+ description="Average number of pages viewed per visit, per period, for each configured domain",+ incremental_fields=[incremental_field("date")],+ ),+ AVERAGE_VISIT_DURATION: SimilarwebEndpointConfig(+ name=AVERAGE_VISIT_DURATION,+ path=f"{_ENGAGEMENT_PATH}/average-visit-duration",+ data_key="average_visit_duration",+ primary_keys=["domain", "country", "granularity", "date"],+ description="Average visit duration in seconds, per period, for each configured domain",+ incremental_fields=[incremental_field("date")],+ ),+ BOUNCE_RATE: SimilarwebEndpointConfig(+ name=BOUNCE_RATE,+ path=f"{_ENGAGEMENT_PATH}/bounce-rate",+ data_key="bounce_rate",+ primary_keys=["domain", "country", "granularity", "date"],+ description="Share of visits that ended without further interaction, per period, for each configured domain",+ incremental_fields=[incremental_field("date")],+ ),+ GLOBAL_RANK: SimilarwebEndpointConfig(+ name=GLOBAL_RANK,+ path="/v1/website/{domain}/global-rank/global-rank",+ data_key="global_rank",+ primary_keys=["domain", "date"],+ description="Monthly worldwide traffic rank for each configured domain",+ incremental_fields=[incremental_field("date")],+ # The rank endpoint is worldwide and monthly only; it takes neither filter.+ accepts_country=False,+ accepts_granularity=False,+ ),+ TRAFFIC_SOURCES: SimilarwebEndpointConfig(+ name=TRAFFIC_SOURCES,+ path="/v1/website/{domain}/traffic-sources/overview-share",+ data_key="visits",+ primary_keys=["domain", "country", "granularity", "source_type", "date"],+ description="Visits split by marketing channel and organic/paid, per period, for each configured domain",+ incremental_fields=[incremental_field("date")],+ ),+ TRAFFIC_BY_COUNTRY: SimilarwebEndpointConfig(+ name=TRAFFIC_BY_COUNTRY,+ path="/v4/website/{domain}/geo/total-traffic-by-country",+ data_key="records",+ primary_keys=["domain", "country"],+ description="Traffic share and engagement per visitor country, aggregated over the synced window",+ # Rows aggregate the whole requested window and carry no period column, so there is+ # nothing to advance a cursor on: full refresh only.+ partition_key=None,+ accepts_country=False,+ accepts_granularity=False,+ paginated=True,+ ),+}++ENDPOINTS = tuple(SIMILARWEB_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SIMILARWEB_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/similarweb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/similarweb.pynew file mode 100644index 000000000000..f6001e7555e8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/similarweb.py@@ -0,0 +1,458 @@+"""Transport for the Similarweb REST API.++Hand-rolled rather than declared through the shared `rest_source` framework: every table fans+out over a list of domains the user types into the source form (Similarweb has no "list my+domains" entity to drive a parent resource from), each response wraps its series under a body+key named after the metric, and the rows need the domain, country and granularity that were+requested stamped onto them because the payload doesn't carry them.+"""++import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote++import requests+from structlog.types import FilteringBoundLogger++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+from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.settings import (+ BASE_URL,+ CAPABILITIES_PATH,+ CHUNK_ROWS,+ DEFAULT_COUNTRY,+ MAX_DOMAINS,+ PAGE_LIMIT,+ SIMILARWEB_ENDPOINTS,+ TRAFFIC_SOURCES,+ SimilarwebEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60++NO_DOMAINS_ERROR = "No domains configured for this Similarweb source"++_MONTH_PATTERN = re.compile(r"^\d{4}-\d{2}$")+_COUNTRY_PATTERN = re.compile(r"^[a-z]{2}$")+++class SimilarwebResumeConfig:+ # Index into the configured domain list that the next request should start from.+ next_domain_index: int+ # Offset within that domain's result set, for the offset-paginated tables.+ next_offset: int = 0+++def parse_domains(raw: Optional[str]) -> list[str]:+ """Split the configured domain list into the bare, lowercase domains the API expects."""+ if not raw:+ return []+ domains: list[str] = []+ seen: set[str] = set()+ for candidate in re.split(r"[,\n]", raw):+ domain = candidate.strip().lower()+ domain = re.sub(r"^https?://", "", domain)+ # Similarweb keys on the bare host: no scheme, no `www.`, no path.+ domain = domain.split("/")[0]+ domain = re.sub(r"^www\.", "", domain)+ if domain and domain not in seen:+ seen.add(domain)+ domains.append(domain)+ return domains+++def normalize_country(country: Optional[str]) -> str:+ normalized = (country or "").strip().lower()+ return normalized or DEFAULT_COUNTRY+++def is_valid_country(country: Optional[str]) -> bool:+ normalized = normalize_country(country)+ return normalized == DEFAULT_COUNTRY or bool(_COUNTRY_PATTERN.match(normalized))+++def coerce_month(value: Any) -> Optional[str]:+ """Coerce a config value or incremental watermark to the `YYYY-MM` the API filters on."""+ if isinstance(value, datetime | date):+ return f"{value.year:04d}-{value.month:02d}"+ if isinstance(value, str):+ stripped = value.strip()+ if _MONTH_PATTERN.match(stripped):+ return stripped+ try:+ return coerce_month(datetime.fromisoformat(stripped))+ except ValueError:+ return None+ return None+++def _parse_row_date(value: Any) -> Optional[datetime]:+ """Parse the API's period label into a timestamp.++ Series endpoints return `YYYY-MM-DD` while the rank endpoint returns `YYYY-MM`; both become+ a UTC timestamp at the start of the period so one typed `date` column works across tables.+ """+ if not isinstance(value, str):+ return None+ stripped = value.strip()+ if _MONTH_PATTERN.match(stripped):+ stripped = f"{stripped}-01"+ try:+ return datetime.fromisoformat(stripped).replace(tzinfo=UTC)+ except ValueError:+ return None+++def _build_params(+ api_key: str,+ config: SimilarwebEndpointConfig,+ country: str,+ granularity: str,+ start_month: Optional[str],+ end_month: Optional[str],+ offset: Optional[int] = None,+) -> dict[str, Any]:+ params: dict[str, Any] = {"api_key": api_key, "format": "json"}+ if config.accepts_country:+ params["country"] = country+ if config.accepts_granularity:+ params["granularity"] = granularity+ # The window params are only meaningful as a pair; with neither, the API returns its+ # default last-28-days window.+ if start_month and end_month:+ params["start_date"] = start_month+ params["end_date"] = end_month+ if config.paginated:+ params["limit"] = PAGE_LIMIT+ params["offset"] = offset or 0+ return params+++def _request(+ session: requests.Session,+ config: SimilarwebEndpointConfig,+ domain: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ url = f"{BASE_URL}{config.path.format(domain=quote(domain, safe=''))}"+ try:+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)+ except requests.RequestException as exc:+ # Connection/timeout exceptions carry the prepared URL — including the api_key query param —+ # and str(exc) is persisted as the import's error, so re-raise with the param-free url only.+ raise type(exc)(f"Similarweb request failed ({type(exc).__name__}) for {url}") from None++ # Similarweb answers 401 with "data not found" — the documented cause is a domain it has no+ # data for, not a bad key (that is 403). One unknown domain shouldn't fail the other domains'+ # rows, so skip it and carry on.+ if response.status_code in (401, 404):+ logger.warning(f"Similarweb: no {config.name} data for '{domain}' (status {response.status_code})")+ return {}++ if not response.ok:+ logger.error(f"Similarweb API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ # Don't use raise_for_status(): it embeds response.url — which carries the api_key query+ # param — into the exception message, and that propagates to the job's stored error, logs,+ # and analytics. Raise with the param-free url instead.+ raise requests.HTTPError(f"Similarweb API returned status {response.status_code} for {url}", response=response)++ body = response.json()+ return body if isinstance(body, dict) else {}+++def _series_rows(+ body: dict[str, Any],+ config: SimilarwebEndpointConfig,+ domain: str,+ country: str,+ granularity: str,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ payload = body.get(config.data_key)+ if not isinstance(payload, list):+ return []++ rows: list[dict[str, Any]] = []+ for item in payload:+ if not isinstance(item, dict):+ continue+ parsed_date = _parse_row_date(item.get("date"))+ if parsed_date is None:+ logger.warning(f"Similarweb: dropping {config.name} row for '{domain}' with unparsable date")+ continue+ row: dict[str, Any] = {"domain": domain, **item, "date": parsed_date}+ if config.accepts_country:+ row["country"] = country+ if config.accepts_granularity:+ row["granularity"] = granularity+ rows.append(row)+ return rows+++def _traffic_sources_rows(+ body: dict[str, Any],+ config: SimilarwebEndpointConfig,+ domain: str,+ country: str,+ granularity: str,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ """Flatten `{"visits": {"<domain>": [{"source_type": ..., "visits": [...]}]}}` into rows."""+ payload = body.get(config.data_key)+ if not isinstance(payload, dict):+ return []++ rows: list[dict[str, Any]] = []+ for channels in payload.values():+ if not isinstance(channels, list):+ continue+ for channel in channels:+ if not isinstance(channel, dict):+ continue+ for point in channel.get("visits") or []:+ if not isinstance(point, dict):+ continue+ parsed_date = _parse_row_date(point.get("date"))+ if parsed_date is None:+ logger.warning(f"Similarweb: dropping traffic_sources row for '{domain}' with unparsable date")+ continue+ rows.append(+ {+ "domain": domain,+ "country": country,+ "granularity": granularity,+ "source_type": channel.get("source_type"),+ "date": parsed_date,+ "organic": point.get("organic"),+ "paid": point.get("paid"),+ }+ )+ return rows+++def _record_rows(body: dict[str, Any], config: SimilarwebEndpointConfig, domain: str) -> list[dict[str, Any]]:+ payload = body.get(config.data_key)+ if not isinstance(payload, list):+ return []+ return [{"domain": domain, **record} for record in payload if isinstance(record, dict)]+++def _resolve_window(+ config: SimilarwebEndpointConfig,+ granularity: str,+ start_date: Optional[str],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> tuple[Optional[str], Optional[str]]:+ """Resolve the `start_date`/`end_date` months to request, or `(None, None)` for the API default."""+ start_month = coerce_month(start_date)++ if should_use_incremental_field:+ watermark = coerce_month(db_incremental_field_last_value)+ if watermark is not None:+ # Re-request the watermark's own month rather than the one after it: the filter is+ # month-granular, and merge dedupes the periods already loaded.+ start_month = max(start_month, watermark) if start_month else watermark++ now = datetime.now(UTC)+ current_month = f"{now.year:04d}-{now.month:02d}"++ if start_month is None:+ # Similarweb's no-date "last 28 days" default is only valid for daily/weekly granularity, so+ # a monthly request must carry an explicit window; fall back to the current month rather than+ # send an invalid monthly/no-date request.+ if config.accepts_granularity and granularity == "monthly":+ return current_month, current_month+ return None, None++ return start_month, current_month+++def _paginated_rows(+ session: requests.Session,+ config: SimilarwebEndpointConfig,+ domains: list[str],+ api_key: str,+ country: str,+ granularity: str,+ start_month: Optional[str],+ end_month: Optional[str],+ resumable_source_manager: ResumableSourceManager[SimilarwebResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume.next_domain_index if resume is not None else 0+ start_offset = resume.next_offset if resume is not None else 0++ for index in range(start_index, len(domains)):+ domain = domains[index]+ offset = start_offset if index == start_index else 0++ while True:+ params = _build_params(api_key, config, country, granularity, start_month, end_month, offset=offset)+ rows = _record_rows(_request(session, config, domain, params, logger), config, domain)+ if rows:+ yield rows+ if len(rows) < PAGE_LIMIT:+ break+ offset += PAGE_LIMIT+ # Saved after the yield so a crash re-fetches the last page (merge dedupes it)+ # rather than skipping it.+ resumable_source_manager.save_state(SimilarwebResumeConfig(next_domain_index=index, next_offset=offset))++ resumable_source_manager.save_state(SimilarwebResumeConfig(next_domain_index=index + 1, next_offset=0))++ resumable_source_manager.clear_state()+++def _series_chunks(+ session: requests.Session,+ config: SimilarwebEndpointConfig,+ domains: list[str],+ api_key: str,+ country: str,+ granularity: str,+ start_month: Optional[str],+ end_month: Optional[str],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Collect every domain's series, then emit it ordered by period.++ Each domain's request returns the whole requested window in one response, so the per-domain+ streams overlap in time. They have to be merged before yielding: the pipeline checkpoints the+ incremental watermark after every batch it receives, so emitting one domain's full history and+ then the next domain's would strand the second domain's older periods behind a watermark that+ has already advanced. The volume is bounded by the domain cap times the periods in the window,+ which stays small for aggregate traffic data.+ """+ rows: list[dict[str, Any]] = []+ for domain in domains:+ params = _build_params(api_key, config, country, granularity, start_month, end_month)+ body = _request(session, config, domain, params, logger)+ if config.name == TRAFFIC_SOURCES:+ rows.extend(_traffic_sources_rows(body, config, domain, country, granularity, logger))+ else:+ rows.extend(_series_rows(body, config, domain, country, granularity, logger))++ rows.sort(key=lambda row: (row["date"], row["domain"]))++ for start in range(0, len(rows), CHUNK_ROWS):+ yield rows[start : start + CHUNK_ROWS]+++def _get_rows(+ api_key: str,+ domains_raw: Optional[str],+ country: Optional[str],+ granularity: str,+ start_date: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SimilarwebResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ domains = parse_domains(domains_raw)+ if not domains:+ raise ValueError(NO_DOMAINS_ERROR)++ config = SIMILARWEB_ENDPOINTS[endpoint]+ normalized_country = normalize_country(country)+ start_month, end_month = _resolve_window(+ config, granularity, start_date, should_use_incremental_field, db_incremental_field_last_value+ )++ # The key rides in a query param, so it has to be named explicitly for redaction.+ session = make_tracked_session(redact_values=(api_key,))++ if config.paginated:+ yield from _paginated_rows(+ session,+ config,+ domains[:MAX_DOMAINS],+ api_key,+ normalized_country,+ granularity,+ start_month,+ end_month,+ resumable_source_manager,+ logger,+ )+ return++ yield from _series_chunks(+ session,+ config,+ domains[:MAX_DOMAINS],+ api_key,+ normalized_country,+ granularity,+ start_month,+ end_month,+ logger,+ )+++def similarweb_source(+ api_key: str,+ domains: Optional[str],+ country: Optional[str],+ granularity: str,+ start_date: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SimilarwebResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ config = SIMILARWEB_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: _get_rows(+ api_key=api_key,+ domains_raw=domains,+ country=country,+ granularity=granularity,+ start_date=start_date,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )+++def validate_credentials(api_key: str) -> tuple[bool, Optional[str]]:+ """Probe the free capabilities endpoint, which costs no data credits."""+ session = make_tracked_session(redact_values=(api_key,))+ try:+ response = session.get(+ f"{BASE_URL}{CAPABILITIES_PATH}",+ params={"api_key": api_key},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except Exception:+ # The exception can carry the prepared request URL, including the api_key query param, so+ # keep it out of the returned message rather than interpolating str(e).+ return False, "Could not reach the Similarweb API. Please retry."++ if response.status_code == 200:+ return True, None+ if response.status_code == 403:+ return False, "Similarweb rejected the API key. Check the key is active and the account has data credits."+ return False, f"Unexpected response from the Similarweb API (status {response.status_code})."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/source.pyindex 61e7bf2fbab5..6181d00e115a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/source.py@@ -1,32 +1,209 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.similarweb import (SimilarwebSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.settings import (+ ENDPOINTS,+ GRANULARITY_OPTIONS,+ INCREMENTAL_FIELDS,+ MAX_DOMAINS,+ SIMILARWEB_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.similarweb import (+ NO_DOMAINS_ERROR,+ SimilarwebResumeConfig,+ coerce_month,+ is_valid_country,+ parse_domains,+ similarweb_source,+ validate_credentials as validate_similarweb_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SimilarwebSource(SimpleSource[SimilarwebSourceConfig]):+class SimilarwebSource(ResumableSource[SimilarwebSourceConfig, SimilarwebResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Similarweb versions each endpoint in its own path segment (the traffic and rank endpoints+ # sit on /v1, the geo breakdown on /v4) rather than exposing one account-wide API version,+ # so there is no single version token to pin.+ api_docs_url = "https://developers.similarweb.com/docs/getting-started"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SIMILARWEB+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "403 Client Error: Forbidden for url": (+ "Similarweb rejected the API key, or the account is out of data credits. "+ "Check both on the API management page in your Similarweb account."+ ),+ NO_DOMAINS_ERROR: "Add one or more domains in the source settings, then re-run the sync.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SimilarwebSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ descriptions={name: endpoint.description for name, endpoint in SIMILARWEB_ENDPOINTS.items()},+ )++ def validate_credentials(+ self,+ config: SimilarwebSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ domains = parse_domains(config.domains)+ if not domains:+ return False, "Add at least one domain to sync, for example posthog.com."+ if len(domains) > MAX_DOMAINS:+ return False, f"Too many domains. List at most {MAX_DOMAINS}."+ if not is_valid_country(config.country):+ return False, "Country must be a two-letter code such as us, or world for worldwide data."+ if config.start_date and coerce_month(config.start_date) is None:+ return False, "Start month must be in YYYY-MM format."++ return validate_similarweb_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SimilarwebResumeConfig]:+ return ResumableSourceManager[SimilarwebResumeConfig](inputs, SimilarwebResumeConfig)++ def source_for_pipeline(+ self,+ config: SimilarwebSourceConfig,+ resumable_source_manager: ResumableSourceManager[SimilarwebResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return similarweb_source(+ api_key=config.api_key,+ domains=config.domains,+ country=config.country,+ granularity=config.granularity,+ start_date=config.start_date,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SIMILARWEB,category=DataWarehouseSourceCategory.ANALYTICS,label="Similarweb",+ keywords=["similar web", "traffic intelligence", "competitor traffic"],+ caption=(+ "Sync estimated traffic, engagement and audience data for any set of domains. "+ "Generate an API key under **API management** in your Similarweb account settings. "+ "The API is a paid add-on, and your plan decides which countries, metrics and "+ "history are available."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/similarweb",iconPath="/static/services/similarweb.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="domains",+ label="Domains",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="posthog.com, example.com",+ secret=False,+ caption=(+ "Comma-separated list of domains to sync. Similarweb has no way to list the "+ f"domains on your account, so every table is built from this list. At most {MAX_DOMAINS}."+ ),+ ),+ SourceFieldInputConfig(+ name="country",+ label="Country",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="world",+ secret=False,+ caption=(+ "Two-letter country code to report on, or `world` for worldwide data. Defaults to `world`."+ ),+ ),+ SourceFieldSelectConfig(+ name="granularity",+ label="Granularity",+ required=True,+ defaultValue="monthly",+ options=[+ SourceFieldSelectConfigOption(label=label, value=value)+ for value, label in GRANULARITY_OPTIONS+ ],+ caption="Daily and weekly data need a plan that includes them.",+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start month",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2024-01",+ secret=False,+ caption=(+ "Earliest month to sync (YYYY-MM). Leave empty to sync only the most recent period. "+ "How far back you can go depends on your plan."+ ),+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.pynew file mode 100644index 000000000000..60f6a8496e7a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb.py@@ -0,0 +1,428 @@+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, Optional, cast++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.settings import (+ GLOBAL_RANK,+ PAGE_LIMIT,+ TRAFFIC_BY_COUNTRY,+ TRAFFIC_SOURCES,+ VISITS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.similarweb import (+ NO_DOMAINS_ERROR,+ SimilarwebResumeConfig,+ coerce_month,+ is_valid_country,+ normalize_country,+ parse_domains,+ similarweb_source,+ validate_credentials,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.similarweb"+++class FakeResumeManager(ResumableSourceManager[SimilarwebResumeConfig]):+ def __init__(self, state: Optional[SimilarwebResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[SimilarwebResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[SimilarwebResumeConfig]:+ return self.state++ def save_state(self, data: SimilarwebResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def _response(status: int = 200, json_body: Any = None) -> mock.MagicMock:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status+ response.ok = 200 <= status < 300+ response.text = ""+ response.json.return_value = json_body if json_body is not None else {}+ if not response.ok:+ errored = requests.Response()+ errored.status_code = status+ response.raise_for_status.side_effect = requests.HTTPError(f"{status} Client Error: for url", response=errored)+ return response+++def _series_body(key: str, points: list[dict[str, Any]]) -> dict[str, Any]:+ return {"meta": {"status": "Success"}, key: points}+++def _session(*responses: mock.MagicMock) -> mock.MagicMock:+ session = mock.MagicMock(spec=requests.Session)+ session.get.side_effect = list(responses)+ return session+++def _run(+ endpoint: str,+ session: mock.MagicMock,+ manager: Optional[FakeResumeManager] = None,+ domains: Optional[str] = "a.com, b.com",+ country: Optional[str] = None,+ granularity: str = "monthly",+ start_date: Optional[str] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> list[list[dict[str, Any]]]:+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ response = similarweb_source(+ api_key="key-123",+ domains=domains,+ country=country,+ granularity=granularity,+ start_date=start_date,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager if manager is not None else FakeResumeManager(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ return list(cast(Iterable[Any], response.items()))+++def _params(session: mock.MagicMock, index: int = 0) -> dict[str, Any]:+ return session.get.call_args_list[index].kwargs["params"]+++def _urls(session: mock.MagicMock) -> list[str]:+ return [call.args[0] for call in session.get.call_args_list]+++class TestSimilarwebTransport:+ @parameterized.expand(+ [+ ("none", None, []),+ ("empty", " ", []),+ ("strips_scheme_www_and_path", "https://www.Example.com/pricing", ["example.com"]),+ ("splits_on_commas_and_newlines", "a.com,\nb.com", ["a.com", "b.com"]),+ ("dedupes", "a.com, www.a.com, b.com", ["a.com", "b.com"]),+ ]+ )+ def test_parse_domains(self, _name: str, raw: Optional[str], expected: list[str]) -> None:+ assert parse_domains(raw) == expected++ @parameterized.expand(+ [+ ("month_string", "2024-03", "2024-03"),+ ("iso_timestamp", "2024-03-15T10:11:12+00:00", "2024-03"),+ ("date_object", date(2024, 3, 15), "2024-03"),+ ("datetime_object", datetime(2024, 3, 15, tzinfo=UTC), "2024-03"),+ ("garbage", "last month", None),+ ("none", None, None),+ ]+ )+ def test_coerce_month(self, _name: str, value: Any, expected: Optional[str]) -> None:+ assert coerce_month(value) == expected++ @parameterized.expand(+ [+ ("blank_defaults_to_world", None, "world", True),+ ("empty_defaults_to_world", " ", "world", True),+ ("two_letter_lowered", "US", "us", True),+ ("three_letter_rejected", "usa", "usa", False),+ ]+ )+ def test_country_normalization(self, _name: str, value: Optional[str], normalized: str, valid: bool) -> None:+ assert normalize_country(value) == normalized+ assert is_valid_country(value) is valid++ def test_no_domains_raises_named_error(self) -> None:+ with pytest.raises(ValueError, match=NO_DOMAINS_ERROR):+ _run(VISITS, _session(), domains="")++ def test_rows_are_ordered_by_period_across_domains(self) -> None:+ # Each domain's request returns its whole window, so the per-domain series overlap in+ # time. The pipeline checkpoints the incremental watermark per batch, so emitting one+ # domain's full history before the next domain's would strand the later domain's older+ # periods behind an already-advanced watermark.+ session = _session(+ _response(+ json_body=_series_body(+ "visits", [{"date": "2024-01-01", "visits": 1}, {"date": "2024-02-01", "visits": 2}]+ )+ ),+ _response(+ json_body=_series_body(+ "visits", [{"date": "2024-01-01", "visits": 3}, {"date": "2024-02-01", "visits": 4}]+ )+ ),+ )++ rows = [row for batch in _run(VISITS, session) for row in batch]++ assert [(row["date"], row["domain"]) for row in rows] == [+ (datetime(2024, 1, 1, tzinfo=UTC), "a.com"),+ (datetime(2024, 1, 1, tzinfo=UTC), "b.com"),+ (datetime(2024, 2, 1, tzinfo=UTC), "a.com"),+ (datetime(2024, 2, 1, tzinfo=UTC), "b.com"),+ ]++ def test_series_rows_carry_the_requested_filters(self) -> None:+ session = _session(_response(json_body=_series_body("visits", [{"date": "2024-01-01", "visits": 9}])))++ rows = _run(VISITS, session, domains="a.com", country="GB", granularity="weekly")[0]++ assert rows == [+ {+ "domain": "a.com",+ "country": "gb",+ "granularity": "weekly",+ "date": datetime(2024, 1, 1, tzinfo=UTC),+ "visits": 9,+ }+ ]+ assert _params(session)["country"] == "gb"+ assert _params(session)["granularity"] == "weekly"++ def test_global_rank_takes_no_filters_and_parses_month_dates(self) -> None:+ session = _session(_response(json_body=_series_body("global_rank", [{"date": "2024-01", "global_rank": 86}])))++ rows = _run(GLOBAL_RANK, session, domains="a.com", country="gb")[0]++ assert rows == [{"domain": "a.com", "date": datetime(2024, 1, 1, tzinfo=UTC), "global_rank": 86}]+ assert "country" not in _params(session)+ assert "granularity" not in _params(session)++ def test_traffic_sources_flattens_channels(self) -> None:+ session = _session(+ _response(+ json_body={+ "meta": {"status": "Success"},+ "visits": {+ "a.com": [+ {+ "source_type": "Search",+ "visits": [{"date": "2024-01-01", "organic": 10.0, "paid": 1.0}],+ },+ {+ "source_type": "Direct",+ "visits": [{"date": "2024-01-01", "organic": 5.0, "paid": 0}],+ },+ ]+ },+ }+ )+ )++ rows = _run(TRAFFIC_SOURCES, session, domains="a.com")[0]++ assert sorted(row["source_type"] for row in rows) == ["Direct", "Search"]+ assert rows[0] == {+ "domain": "a.com",+ "country": "world",+ "granularity": "monthly",+ "source_type": "Search",+ "date": datetime(2024, 1, 1, tzinfo=UTC),+ "organic": 10.0,+ "paid": 1.0,+ }++ @parameterized.expand([("unauthorized", 401), ("not_found", 404)])+ def test_a_domain_without_data_does_not_abort_the_other_domains(self, _name: str, status: int) -> None:+ session = _session(+ _response(status=status),+ _response(json_body=_series_body("visits", [{"date": "2024-01-01", "visits": 7}])),+ )++ rows = [row for batch in _run(VISITS, session) for row in batch]++ assert [row["domain"] for row in rows] == ["b.com"]++ def test_unexpected_status_fails_the_sync(self) -> None:+ session = _session(_response(status=500))++ with pytest.raises(requests.HTTPError):+ _run(VISITS, session, domains="a.com")++ def test_connection_error_is_reraised_without_the_api_key(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.get.side_effect = requests.ConnectionError(+ "Max retries exceeded with url: /v1/website/a.com/...?api_key=key-123&format=json"+ )++ with pytest.raises(requests.ConnectionError) as excinfo:+ _run(VISITS, session, domains="a.com")++ assert "key-123" not in str(excinfo.value)+ assert "Similarweb request failed" in str(excinfo.value)++ def test_rows_with_an_unparsable_period_are_dropped(self) -> None:+ session = _session(+ _response(+ json_body=_series_body(+ "visits", [{"date": "not-a-date", "visits": 1}, {"date": "2024-01-01", "visits": 2}]+ )+ )+ )++ rows = _run(VISITS, session, domains="a.com")[0]++ assert [row["visits"] for row in rows] == [2]++ @parameterized.expand(+ [+ # Monthly has no valid no-date mode, so an unconfigured window falls back to the current+ # month; daily and weekly keep the API's dateless "last 28 days" default.+ ("monthly_no_window_defaults_to_current_month", "monthly", None, False, None, "2024-06", "2024-06"),+ ("daily_no_window_uses_api_default", "daily", None, False, None, None, None),+ ("weekly_no_window_uses_api_default", "weekly", None, False, None, None, None),+ ("configured_start_only", "monthly", "2024-01", False, None, "2024-01", "2024-06"),+ (+ "watermark_wins_when_later",+ "monthly",+ "2024-01",+ True,+ datetime(2024, 4, 20, tzinfo=UTC),+ "2024-04",+ "2024-06",+ ),+ (+ "configured_start_wins_when_later",+ "monthly",+ "2024-05",+ True,+ datetime(2024, 4, 20, tzinfo=UTC),+ "2024-05",+ "2024-06",+ ),+ (+ "watermark_without_configured_start",+ "monthly",+ None,+ True,+ datetime(2024, 4, 20, tzinfo=UTC),+ "2024-04",+ "2024-06",+ ),+ ]+ )+ def test_window_params(+ self,+ _name: str,+ granularity: str,+ start_date: Optional[str],+ should_use_incremental_field: bool,+ last_value: Any,+ expected_start: Optional[str],+ expected_end: Optional[str],+ ) -> None:+ session = _session(_response(json_body=_series_body("visits", [])))++ with freeze_time("2024-06-15"):+ _run(+ VISITS,+ session,+ domains="a.com",+ granularity=granularity,+ start_date=start_date,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=last_value,+ )++ assert _params(session).get("start_date") == expected_start+ assert _params(session).get("end_date") == expected_end++ def test_api_key_is_sent_as_a_query_param_and_registered_for_redaction(self) -> None:+ session = _session(_response(json_body=_series_body("visits", [])))++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:+ list(+ cast(+ Iterable[Any],+ similarweb_source(+ api_key="key-123",+ domains="a.com",+ country=None,+ granularity="monthly",+ start_date=None,+ endpoint=VISITS,+ logger=mock.MagicMock(),+ resumable_source_manager=FakeResumeManager(),+ ).items(),+ )+ )++ assert make_session.call_args.kwargs["redact_values"] == ("key-123",)+ assert _params(session)["api_key"] == "key-123"++ def test_paginated_endpoint_walks_offsets_and_checkpoints_each_page(self) -> None:+ full_page = [{"country": index, "visits": 1} for index in range(PAGE_LIMIT)]+ manager = FakeResumeManager()+ session = _session(+ _response(json_body={"records": full_page}),+ _response(json_body={"records": [{"country": 999, "visits": 2}]}),+ _response(json_body={"records": []}),+ )++ batches = _run(TRAFFIC_BY_COUNTRY, session, manager=manager)++ assert [_params(session, index)["offset"] for index in range(3)] == [0, PAGE_LIMIT, 0]+ assert batches[0][0] == {"domain": "a.com", "country": 0, "visits": 1}+ assert [(state.next_domain_index, state.next_offset) for state in manager.saved] == [+ (0, PAGE_LIMIT),+ (1, 0),+ (2, 0),+ ]+ assert manager.cleared is True++ def test_paginated_endpoint_resumes_from_saved_state(self) -> None:+ manager = FakeResumeManager(SimilarwebResumeConfig(next_domain_index=1, next_offset=PAGE_LIMIT))+ session = _session(_response(json_body={"records": [{"country": 840}]}))++ batches = _run(TRAFFIC_BY_COUNTRY, session, manager=manager)++ assert [url.split("/website/")[1].split("/")[0] for url in _urls(session)] == ["b.com"]+ assert _params(session)["offset"] == PAGE_LIMIT+ assert batches[0][0]["domain"] == "b.com"++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("forbidden", 403, False, "Similarweb rejected the API key"),+ ("server_error", 500, False, "Unexpected response"),+ ]+ )+ def test_validate_credentials_status_mapping(+ self, _name: str, status: int, expected_ok: bool, expected_message: Optional[str]+ ) -> None:+ # A failing status must be reported back to source creation, not raised.+ session = _session(_response(status=status))++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ is_valid, message = validate_credentials("key-123")++ assert is_valid is expected_ok+ if expected_message is None:+ assert message is None+ else:+ assert message is not None and expected_message in message++ def test_validate_credentials_reports_unreachable_api(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.get.side_effect = requests.ConnectionError("boom")++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ is_valid, message = validate_credentials("key-123")++ assert is_valid is False+ assert message is not None and "Could not reach the Similarweb API" in messagediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb_source.pynew file mode 100644index 000000000000..d89e3dbd64c1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/similarweb/tests/test_similarweb_source.py@@ -0,0 +1,167 @@+from typing import Any, cast++from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++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 SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.similarweb import (+ SimilarwebSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.settings import (+ ENDPOINTS,+ MAX_DOMAINS,+ SIMILARWEB_ENDPOINTS,+ TRAFFIC_BY_COUNTRY,+ VISITS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.similarweb import (+ SimilarwebResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.source import SimilarwebSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.similarweb.source"+++def _inputs(schema_name: str = VISITS, **overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ return SourceInputs(**{**defaults, **overrides})+++class TestSimilarwebSource:+ def setup_method(self) -> None:+ self.source = SimilarwebSource()+ self.team_id = 123+ self.config = SimilarwebSourceConfig(api_key="key-123", domains="posthog.com")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SIMILARWEB++ def test_get_source_config_is_released(self) -> None:+ config = self.source.get_source_config++ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.name.value == "Similarweb"+ assert config.iconPath == "/static/services/similarweb.png"++ fields_by_name = {field.name: field for field in config.fields}+ assert set(fields_by_name) == {"api_key", "domains", "country", "granularity", "start_date"}++ api_key = fields_by_name["api_key"]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.required is True+ assert api_key.secret is True+ assert api_key.type == SourceFieldInputConfigType.PASSWORD++ assert cast(SourceFieldInputConfig, fields_by_name["domains"]).required is True+ assert cast(SourceFieldInputConfig, fields_by_name["country"]).required is False+ assert cast(SourceFieldInputConfig, fields_by_name["start_date"]).required is False++ granularity = fields_by_name["granularity"]+ assert isinstance(granularity, SourceFieldSelectConfig)+ assert granularity.defaultValue == "monthly"+ assert [option.value for option in granularity.options] == ["monthly", "weekly", "daily"]++ def test_get_schemas_covers_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ by_name = {schema.name: schema for schema in schemas}+ for name, endpoint in SIMILARWEB_ENDPOINTS.items():+ assert by_name[name].description == endpoint.description+ # The geo breakdown aggregates the whole window into rows with no period column,+ # so it must not advertise a cursor the pipeline would try to advance.+ assert by_name[name].supports_incremental is (name != TRAFFIC_BY_COUNTRY)+ if name != TRAFFIC_BY_COUNTRY:+ assert {field["field"] for field in by_name[name].incremental_fields} == {"date"}++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=[VISITS])+ assert [schema.name for schema in schemas] == [VISITS]++ @parameterized.expand(+ [+ ("no_domains", {"domains": " "}, "Add at least one domain"),+ (+ "too_many_domains",+ {"domains": ",".join(f"d{i}.com" for i in range(MAX_DOMAINS + 1))},+ "Too many domains",+ ),+ ("bad_country", {"country": "usa"}, "two-letter code"),+ ("bad_start_month", {"start_date": "01-2024"}, "YYYY-MM format"),+ ]+ )+ def test_validate_credentials_rejects_bad_settings_without_calling_the_api(+ self, _name: str, overrides: dict[str, Any], expected: str+ ) -> None:+ config = SimilarwebSourceConfig(**{"api_key": "key-123", "domains": "posthog.com", **overrides})++ with mock.patch(f"{MODULE}.validate_similarweb_credentials") as probe:+ is_valid, message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert message is not None and expected in message+ probe.assert_not_called()++ def test_validate_credentials_probes_the_api_when_settings_are_valid(self) -> None:+ with mock.patch(f"{MODULE}.validate_similarweb_credentials", return_value=(True, None)) as probe:+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)++ probe.assert_called_once_with("key-123")++ def test_get_resumable_source_manager_is_bound_to_the_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SimilarwebResumeConfig++ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_primary_keys_identify_a_row_across_domains(self, name: str) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ response = self.source.source_for_pipeline(self.config, manager, _inputs(schema_name=name))++ endpoint = SIMILARWEB_ENDPOINTS[name]+ assert response.name == name+ assert response.primary_keys == endpoint.primary_keys+ # Every table pools rows from every configured domain, so a key without the domain+ # would collapse different domains' rows onto each other on merge.+ assert response.primary_keys is not None and "domain" in response.primary_keys+ assert response.sort_mode == "asc"+ assert response.partition_keys == ([endpoint.partition_key] if endpoint.partition_key else None)++ def test_source_for_pipeline_drops_the_watermark_on_a_full_refresh(self) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = _inputs(should_use_incremental_field=False, db_incremental_field_last_value="2024-04")++ with mock.patch(f"{MODULE}.similarweb_source") as build:+ self.source.source_for_pipeline(self.config, manager, inputs)++ assert build.call_args.kwargs["db_incremental_field_last_value"] is None+ assert build.call_args.kwargs["api_key"] == "key-123"+ assert build.call_args.kwargs["domains"] == "posthog.com"+ assert build.call_args.kwargs["granularity"] == "monthly"++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)+ assert self.source.get_canonical_descriptions() == CANONICAL_DESCRIPTIONS