: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): implement plausible import source (#65637)
Tom Owerse565fe5a974d
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 0508332ffdba..c7d76feb5eda 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -158,6 +158,7 @@ the row lists both.| pinterest_ads | HTTP | requests | ✅ || pipedrive | HTTP | requests | ✅ || plain | HTTP | requests | ✅ |+| plausible | HTTP | requests | ✅ || polar | HTTP | requests | ✅ || plaid | HTTP | requests | ✅ || postgres | DB protocol | psycopg | ➖ |@@ -560,7 +561,6 @@ doesn't conflict with concurrent PRs.- piwik- planetscale- planhat-- plausible- polygon- poplardiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 5741b33b04df..f9276026cfce 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -2383,7 +2383,9 @@ class PlanhatSourceConfig(config.Config):@config.configclass PlausibleSourceConfig(config.Config):- pass+ api_key: str+ site_id: str+ host: str | None = None@config.configdiff --git a/posthog/temporal/data_imports/sources/plausible/canonical_descriptions.py b/posthog/temporal/data_imports/sources/plausible/canonical_descriptions.pynew file mode 100644index 000000000000..731799576427--- /dev/null+++ b/posthog/temporal/data_imports/sources/plausible/canonical_descriptions.py@@ -0,0 +1,112 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++_DOCS_URL = "https://plausible.io/docs/stats-api"++# Metrics returned by the standard breakdown reports (everything except `goals`).+_STANDARD_METRIC_COLUMNS = {+ "date": "The day the metrics are aggregated over (YYYY-MM-DD), in the site's timezone.",+ "visitors": "Number of unique visitors.",+ "visits": "Number of visits/sessions.",+ "pageviews": "Number of pageview events.",+ "bounce_rate": "Percentage of visits with a single page interaction (0-100).",+ "visit_duration": "Average visit duration in seconds.",+ "events": "Number of events (pageviews plus custom events).",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "timeseries": {+ "description": "Site-wide traffic metrics aggregated per day.",+ "docs_url": _DOCS_URL,+ "columns": dict(_STANDARD_METRIC_COLUMNS),+ },+ "sources": {+ "description": "Daily traffic metrics broken down by acquisition source (channel).",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "source": "The traffic source / channel a visit came from."},+ },+ "referrers": {+ "description": "Daily traffic metrics broken down by full referrer URL.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "referrer": "The full referrer URL a visit came from."},+ },+ "utm_sources": {+ "description": "Daily traffic metrics broken down by the utm_source query parameter.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "utm_source": "Value of the utm_source query parameter."},+ },+ "utm_mediums": {+ "description": "Daily traffic metrics broken down by the utm_medium query parameter.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "utm_medium": "Value of the utm_medium query parameter."},+ },+ "utm_campaigns": {+ "description": "Daily traffic metrics broken down by the utm_campaign query parameter.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "utm_campaign": "Value of the utm_campaign query parameter."},+ },+ "utm_terms": {+ "description": "Daily traffic metrics broken down by the utm_term query parameter.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "utm_term": "Value of the utm_term query parameter."},+ },+ "utm_contents": {+ "description": "Daily traffic metrics broken down by the utm_content query parameter.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "utm_content": "Value of the utm_content query parameter."},+ },+ "pages": {+ "description": "Daily traffic metrics broken down by page path.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "page": "The page path of the pageview."},+ },+ "entry_pages": {+ "description": "Daily traffic metrics broken down by the first page of each visit.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "entry_page": "The first page path visited in a session."},+ },+ "exit_pages": {+ "description": "Daily traffic metrics broken down by the last page of each visit.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "exit_page": "The last page path visited in a session."},+ },+ "countries": {+ "description": "Daily traffic metrics broken down by visitor country.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "country": "ISO 3166-1 alpha-2 country code of the visitor."},+ },+ "regions": {+ "description": "Daily traffic metrics broken down by visitor region.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "region": "ISO 3166-2 region code of the visitor."},+ },+ "cities": {+ "description": "Daily traffic metrics broken down by visitor city.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "city": "GeoNames ID of the visitor's city."},+ },+ "browsers": {+ "description": "Daily traffic metrics broken down by browser.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "browser": "The visitor's browser."},+ },+ "operating_systems": {+ "description": "Daily traffic metrics broken down by operating system.",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "os": "The visitor's operating system."},+ },+ "devices": {+ "description": "Daily traffic metrics broken down by device type (screen size class).",+ "docs_url": _DOCS_URL,+ "columns": {**_STANDARD_METRIC_COLUMNS, "device": "Device type: Desktop, Mobile, Tablet, or Laptop."},+ },+ "goals": {+ "description": "Daily goal conversions broken down by goal.",+ "docs_url": _DOCS_URL,+ "columns": {+ "date": "The day the metrics are aggregated over (YYYY-MM-DD), in the site's timezone.",+ "goal": "The configured goal name (custom event or pageview goal).",+ "visitors": "Number of unique visitors who converted the goal.",+ "events": "Number of times the goal was converted.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/plausible/plausible.py b/posthog/temporal/data_imports/sources/plausible/plausible.pynew file mode 100644index 000000000000..762ddb6e31b5--- /dev/null+++ b/posthog/temporal/data_imports/sources/plausible/plausible.py@@ -0,0 +1,261 @@+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.plausible.settings import (+ DEFAULT_BACKFILL_DAYS,+ PLAUSIBLE_ENDPOINTS,+ REPORT_LOOKBACK_DAYS,+ PlausibleEndpointConfig,+)++# Plausible Cloud; self-hosted instances override this via the source's host field.+PLAUSIBLE_DEFAULT_HOST = "https://plausible.io"+QUERY_PATH = "/api/v2/query"++# Stats API v2 caps pagination.limit at 10000 rows per page.+DEFAULT_PAGE_LIMIT = 10000+REQUEST_TIMEOUT_SECONDS = 120+# Default rate limit is 600 requests/hour per API key. We can't enforce a global budget here, so we+# add a light per-request throttle and lean on retry/backoff to absorb 429s.+REQUEST_THROTTLE_SECONDS = 0.25+MAX_RETRY_ATTEMPTS = 5+++class PlausibleRetryableError(Exception):+ pass+++class PlausibleResumeConfig:+ # Offset of the next page to fetch within the current query.+ offset: int = 0+ # The date window the in-flight query was issued for, pinned so resuming mid-pagination keeps a+ # consistent total_rows/ordering instead of shifting when "today" moves.+ date_range_start: Optional[str] = None+ date_range_end: Optional[str] = None+++def normalize_host(host: str) -> str:+ """Normalize the instance URL and reject anything that isn't plain http(s)."""+ host = host.strip()+ if not host:+ raise ValueError("Plausible host is required")+ if "://" not in host:+ host = f"https://{host}"+ host = host.rstrip("/")+ parsed = urlparse(host)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise ValueError(f"Invalid Plausible host: {host}")+ return host+++def resolve_host(host: Optional[str]) -> str:+ """Default an empty host to Plausible Cloud, then normalize it."""+ return normalize_host(host or PLAUSIBLE_DEFAULT_HOST)+++def hostname_of(host: Optional[str]) -> str:+ return urlparse(resolve_host(host)).hostname or ""+++def _get_session(api_key: str) -> requests.Session:+ # `host` is user-supplied, so pin redirects off: validation and the outbound request must stay+ # on the same target (SSRF defense-in-depth). The key is redacted from logged URLs/samples.+ return make_tracked_session(+ headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},+ redact_values=(api_key,),+ allow_redirects=False,+ )+++def _to_date(value: Any) -> Optional[date]:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()+ except ValueError:+ return None+ return None+++def _build_query(config: PlausibleEndpointConfig, site_id: str, start: date, end: date, offset: int) -> dict[str, Any]:+ return {+ "site_id": site_id,+ "metrics": config.metrics,+ "date_range": [start.isoformat(), end.isoformat()],+ "dimensions": config.dimensions,+ # Ascending by day so the pipeline's incremental watermark only ever advances forward.+ "order_by": [["time:day", "asc"]],+ "pagination": {"limit": DEFAULT_PAGE_LIMIT, "offset": offset},+ "include": {"total_rows": True},+ }+++def _normalize_row(config: PlausibleEndpointConfig, result: dict[str, Any]) -> dict[str, Any]:+ """Flatten a Stats API result ({dimensions: [...], metrics: [...]}) into a named-column dict."""+ row: dict[str, Any] = {}+ # Direct access (not .get) so a malformed response missing dimensions — and therefore the `date`+ # primary key — fails fast instead of ingesting unkeyed rows.+ for name, value in zip(config.column_names, result["dimensions"]):+ row[name] = value+ for name, value in zip(config.metrics, result["metrics"]):+ row[name] = value+ return row+++@retry(+ retry=retry_if_exception_type((PlausibleRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+)+def _query(+ session: requests.Session, url: str, payload: dict[str, Any], logger: FilteringBoundLogger+) -> dict[str, Any]:+ # Throttle every call, including tenacity retries, so a retry storm can't blow past the rate+ # limit on top of the backoff.+ time.sleep(REQUEST_THROTTLE_SECONDS)+ response = session.post(url, json=payload, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise PlausibleRetryableError(f"Plausible API error (retryable): status={response.status_code}")++ if not response.ok:+ logger.error(f"Plausible API error: status={response.status_code}, body={response.text[:500]}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(host: Optional[str], site_id: str, api_key: str) -> tuple[bool, str | None]:+ """Confirm the instance is reachable and the key can read the site's stats."""+ try:+ response = _get_session(api_key).post(+ f"{resolve_host(host)}{QUERY_PATH}",+ # Cheapest possible probe: one metric over a short relative range, no dimensions.+ json={"site_id": site_id, "metrics": ["visitors"], "date_range": "7d"},+ timeout=15,+ )+ except Exception:+ return False, "Could not reach Plausible. Check the host URL."++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Plausible rejected the API key. Check the key and that it has the stats read scope."+ if response.status_code == 404:+ return False, "Plausible could not find that site. Check the site domain (site ID)."++ try:+ message = response.json().get("error")+ except Exception:+ message = None+ return False, message or f"Plausible returned status {response.status_code}."+++def get_rows(+ host: Optional[str],+ site_id: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PlausibleResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = PLAUSIBLE_ENDPOINTS[endpoint]+ session = _get_session(api_key)+ url = f"{resolve_host(host)}{QUERY_PATH}"++ today = datetime.now(tz=UTC).date()+ start = today - timedelta(days=DEFAULT_BACKFILL_DAYS)+ if should_use_incremental_field:+ watermark = _to_date(db_incremental_field_last_value)+ if watermark is not None:+ # Recent days re-aggregate as visits arrive, so re-pull a trailing window and let merge+ # on the (date, ...) primary key overwrite the changed rows.+ start = watermark - timedelta(days=REPORT_LOOKBACK_DAYS)+ end = today+ offset = 0++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ resumed_start = _to_date(resume_config.date_range_start)+ resumed_end = _to_date(resume_config.date_range_end)+ if resumed_start is not None:+ start = resumed_start+ if resumed_end is not None:+ end = resumed_end+ offset = resume_config.offset or 0+ logger.debug(f"Plausible: resuming {endpoint} from offset={offset}, range={start}..{end}")++ if start > end:+ start = end++ while True:+ body = _query(session, url, _build_query(config, site_id, start, end, offset), logger)+ results = body.get("results", []) or []++ rows = [_normalize_row(config, result) for result in results]+ if rows:+ yield rows++ total_rows = body.get("meta", {}).get("total_rows")+ next_offset = offset + DEFAULT_PAGE_LIMIT+ reached_end = len(results) < DEFAULT_PAGE_LIMIT or (total_rows is not None and next_offset >= total_rows)+ if reached_end:+ break++ offset = next_offset+ # Save AFTER yielding so a crash resumes on the next unfetched page (already-yielded rows+ # are deduped by the primary key on merge).+ resumable_source_manager.save_state(+ PlausibleResumeConfig(offset=offset, date_range_start=start.isoformat(), date_range_end=end.isoformat())+ )+++def plausible_source(+ host: Optional[str],+ site_id: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PlausibleResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = PLAUSIBLE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ host=host,+ site_id=site_id,+ api_key=api_key,+ 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=list(config.primary_keys),+ # Reports are pulled oldest-day-first (order_by time:day asc), so the cursor only moves forward.+ sort_mode="asc",+ partition_mode="datetime",+ partition_format="month",+ partition_keys=["date"],+ )diff --git a/posthog/temporal/data_imports/sources/plausible/settings.py b/posthog/temporal/data_imports/sources/plausible/settings.pynew file mode 100644index 000000000000..9cf44e3b36a2--- /dev/null+++ b/posthog/temporal/data_imports/sources/plausible/settings.py@@ -0,0 +1,100 @@+from dataclasses import dataclass, field++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Aggregates for recent days keep changing as visits arrive, so incremental syncs re-pull a+# trailing window and merge on (date, ...dimensions).+REPORT_LOOKBACK_DAYS = 7+# History pulled on the first sync of a stream.+DEFAULT_BACKFILL_DAYS = 365++# Metrics requested for every report. These are the standard Plausible Stats API v2 metrics that+# are valid across visit and event dimensions. Goal/conversion-specific metrics live on their own+# endpoints because they aren't valid for the generic breakdowns.+DEFAULT_METRICS = ["visitors", "visits", "pageviews", "bounce_rate", "visit_duration", "events"]++# The day bucket every report is grouped by — must be the first dimension so `order_by` can sort+# on it and the pipeline can slide the date window incrementally.+TIME_DIMENSION = "time:day"++_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+ },+]+++def dimension_to_column(dimension: str) -> str:+ """Map a Plausible query dimension to the flat column name we store it under.++ `time:day` becomes `date`; every other dimension uses the part after the colon+ (e.g. `visit:source` -> `source`, `event:page` -> `page`, `visit:os` -> `os`).+ """+ if dimension == TIME_DIMENSION:+ return "date"+ return dimension.split(":", 1)[-1]+++@dataclass+class PlausibleEndpointConfig:+ name: str+ # Plausible Stats API v2 query dimensions. `time:day` is prepended automatically, so list only+ # the breakdown dimension(s) here (empty for the plain daily timeseries).+ breakdown_dimensions: list[str] = field(default_factory=list)+ metrics: list[str] = field(default_factory=lambda: list(DEFAULT_METRICS))+ should_sync_default: bool = True++ @property+ def dimensions(self) -> list[str]:+ return [TIME_DIMENSION, *self.breakdown_dimensions]++ @property+ def column_names(self) -> list[str]:+ return [dimension_to_column(d) for d in self.dimensions]++ @property+ def primary_keys(self) -> list[str]:+ # Every dimension column (always including `date`) forms the composite key, so rows stay+ # unique table-wide across days and breakdown values.+ return self.column_names++ @property+ def incremental_fields(self) -> list[IncrementalField]:+ return list(_DATE_INCREMENTAL_FIELDS)+++PLAUSIBLE_ENDPOINTS: dict[str, PlausibleEndpointConfig] = {+ "timeseries": PlausibleEndpointConfig(name="timeseries"),+ "sources": PlausibleEndpointConfig(name="sources", breakdown_dimensions=["visit:source"]),+ "referrers": PlausibleEndpointConfig(name="referrers", breakdown_dimensions=["visit:referrer"]),+ "utm_sources": PlausibleEndpointConfig(name="utm_sources", breakdown_dimensions=["visit:utm_source"]),+ "utm_mediums": PlausibleEndpointConfig(name="utm_mediums", breakdown_dimensions=["visit:utm_medium"]),+ "utm_campaigns": PlausibleEndpointConfig(name="utm_campaigns", breakdown_dimensions=["visit:utm_campaign"]),+ "utm_terms": PlausibleEndpointConfig(name="utm_terms", breakdown_dimensions=["visit:utm_term"]),+ "utm_contents": PlausibleEndpointConfig(name="utm_contents", breakdown_dimensions=["visit:utm_content"]),+ "pages": PlausibleEndpointConfig(name="pages", breakdown_dimensions=["event:page"]),+ "entry_pages": PlausibleEndpointConfig(name="entry_pages", breakdown_dimensions=["visit:entry_page"]),+ "exit_pages": PlausibleEndpointConfig(name="exit_pages", breakdown_dimensions=["visit:exit_page"]),+ "countries": PlausibleEndpointConfig(name="countries", breakdown_dimensions=["visit:country"]),+ "regions": PlausibleEndpointConfig(name="regions", breakdown_dimensions=["visit:region"]),+ "cities": PlausibleEndpointConfig(name="cities", breakdown_dimensions=["visit:city"]),+ "browsers": PlausibleEndpointConfig(name="browsers", breakdown_dimensions=["visit:browser"]),+ "operating_systems": PlausibleEndpointConfig(name="operating_systems", breakdown_dimensions=["visit:os"]),+ "devices": PlausibleEndpointConfig(name="devices", breakdown_dimensions=["visit:device"]),+ # Goal conversions: `event:goal` is only valid with goal-compatible metrics, so it carries its+ # own reduced metric set rather than the generic breakdown set.+ "goals": PlausibleEndpointConfig(+ name="goals",+ breakdown_dimensions=["event:goal"],+ metrics=["visitors", "events"],+ ),+}++ENDPOINTS = tuple(PLAUSIBLE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PLAUSIBLE_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/plausible/source.py b/posthog/temporal/data_imports/sources/plausible/source.pyindex 49a71f2ed046..c2bf959bf81c 100644--- a/posthog/temporal/data_imports/sources/plausible/source.py+++ b/posthog/temporal/data_imports/sources/plausible/source.py@@ -1,31 +1,161 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions+from posthog.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixinfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import PlausibleSourceConfig+from posthog.temporal.data_imports.sources.plausible.plausible import (+ PlausibleResumeConfig,+ hostname_of,+ plausible_source,+ validate_credentials as validate_plausible_credentials,+)+from posthog.temporal.data_imports.sources.plausible.settings import ENDPOINTS, INCREMENTAL_FIELDS, PLAUSIBLE_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class PlausibleSource(SimpleSource[PlausibleSourceConfig]):+class PlausibleSource(ResumableSource[PlausibleSourceConfig, PlausibleResumeConfig], ValidateDatabaseHostMixin):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PLAUSIBLE+ @property+ def connection_host_fields(self) -> list[str]:+ # `host` determines where the stored API key is sent; retargeting it must re-require the key.+ return ["host"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Plausible API key is invalid or has been revoked. Create a new key in your Plausible account settings, then reconnect.",+ "403 Client Error": "Your Plausible API key is missing the stats read scope needed to sync this data. Grant it in your Plausible account settings, then reconnect.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.PLAUSIBLE,category=DataWarehouseSourceCategory.ANALYTICS,label="Plausible",+ caption="""Connect Plausible Analytics to pull your web analytics into the PostHog Data warehouse.++Works with Plausible Cloud and self-hosted instances. Create an API key under **Account settings → API keys** with the `stats read` scope, then enter your site's domain (e.g. `example.com`). Leave the host blank for Plausible Cloud, or set it to your instance URL for self-hosted (e.g. `https://plausible.example.com`).""",iconPath="/static/services/plausible.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/plausible",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="site_id",+ label="Site domain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="example.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="host",+ label="Host (self-hosted only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://plausible.io",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.plausible.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: PlausibleSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint)+ return SourceSchema(+ name=endpoint,+ # date_range is a genuine server-side filter, so every report supports incremental+ # syncing by sliding the window forward.+ supports_incremental=incremental_fields is not None,+ supports_append=incremental_fields is not None,+ incremental_fields=incremental_fields or [],+ should_sync_default=PLAUSIBLE_ENDPOINTS[endpoint].should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: PlausibleSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), team_id)+ except ValueError:+ return False, "Invalid Plausible host URL"+ if not host_valid:+ return False, host_error++ return validate_plausible_credentials(config.host, config.site_id, config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PlausibleResumeConfig]:+ return ResumableSourceManager[PlausibleResumeConfig](inputs, PlausibleResumeConfig)++ def source_for_pipeline(+ self,+ config: PlausibleSourceConfig,+ resumable_source_manager: ResumableSourceManager[PlausibleResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), inputs.team_id)+ if not host_valid:+ raise ValueError(host_error or "Invalid Plausible host")++ return plausible_source(+ host=config.host,+ site_id=config.site_id,+ api_key=config.api_key,+ 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,)diff --git a/posthog/temporal/data_imports/sources/plausible/tests/test_plausible.py b/posthog/temporal/data_imports/sources/plausible/tests/test_plausible.pynew file mode 100644index 000000000000..104a2a010fbe--- /dev/null+++ b/posthog/temporal/data_imports/sources/plausible/tests/test_plausible.py@@ -0,0 +1,251 @@+from datetime import UTC, datetime, timedelta+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.plausible import plausible as plausible_module+from posthog.temporal.data_imports.sources.plausible.plausible import (+ PlausibleResumeConfig,+ _normalize_row,+ get_rows,+ hostname_of,+ normalize_host,+ plausible_source,+ resolve_host,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.plausible.settings import (+ ENDPOINTS,+ PLAUSIBLE_ENDPOINTS,+ REPORT_LOOKBACK_DAYS,+)++_MODULE = "posthog.temporal.data_imports.sources.plausible.plausible"+++def _make_manager(resume_state: PlausibleResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: Any, status_code: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = status_code < 400+ resp.text = str(body)+ return resp+++def _result(dimensions: list[Any], metrics: list[Any]) -> dict[str, Any]:+ return {"dimensions": dimensions, "metrics": metrics}+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("https://plausible.io", "https://plausible.io"),+ ("plausible.example.com", "https://plausible.example.com"),+ ("https://analytics.example.com/", "https://analytics.example.com"),+ ("http://analytics.internal:8080", "http://analytics.internal:8080"),+ ],+ )+ def test_valid_hosts(self, value, expected):+ assert normalize_host(value) == expected++ @pytest.mark.parametrize("value", ["", " ", "ftp://example.com", "https://"])+ def test_invalid_hosts_raise(self, value):+ with pytest.raises(ValueError):+ normalize_host(value)++ @pytest.mark.parametrize("value", [None, ""])+ def test_resolve_host_defaults_to_cloud(self, value):+ assert resolve_host(value) == "https://plausible.io"++ def test_hostname_of(self):+ assert hostname_of("https://analytics.example.com/path") == "analytics.example.com"+ assert hostname_of(None) == "plausible.io"+++class TestNormalizeRow:+ def test_maps_dimensions_and_metrics_to_named_columns(self):+ config = PLAUSIBLE_ENDPOINTS["sources"]+ row = _normalize_row(config, _result(["2024-01-01", "Google"], [10, 12, 30, 0.5, 60, 40]))++ assert row == {+ "date": "2024-01-01",+ "source": "Google",+ "visitors": 10,+ "visits": 12,+ "pageviews": 30,+ "bounce_rate": 0.5,+ "visit_duration": 60,+ "events": 40,+ }++ def test_timeseries_has_only_date_dimension(self):+ config = PLAUSIBLE_ENDPOINTS["timeseries"]+ row = _normalize_row(config, _result(["2024-01-01"], [10, 12, 30, 0.5, 60, 40]))++ assert row["date"] == "2024-01-01"+ assert "source" not in row+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_credentials(self, mock_session):+ mock_session.return_value.post.return_value = _response({"results": [{"metrics": [1]}]})++ ok, error = validate_credentials("https://plausible.io", "example.com", "key")+ assert ok is True+ assert error is None+ body = mock_session.return_value.post.call_args.kwargs["json"]+ assert body["site_id"] == "example.com"+ assert body["metrics"] == ["visitors"]+ headers = mock_session.call_args.kwargs["headers"]+ assert headers["Authorization"] == "Bearer key"++ @pytest.mark.parametrize(+ "status_code, fragment",+ [+ (401, "API key"),+ (403, "API key"),+ (404, "site"),+ (400, "status 400"),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_failure_status_codes(self, mock_session, status_code, fragment):+ mock_session.return_value.post.return_value = _response({}, status_code=status_code)++ ok, error = validate_credentials("https://plausible.io", "example.com", "bad")+ assert ok is False+ assert error is not None and fragment in error++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_unreachable_host(self, mock_session):+ mock_session.return_value.post.side_effect = Exception("dns failure")++ ok, error = validate_credentials("https://bad.example", "example.com", "key")+ assert ok is False+ assert error is not None and "reach" in error++[email protected](f"{_MODULE}.time.sleep")+class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_builds_query_and_yields_normalized_rows(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response(+ {"results": [_result(["2024-01-01", "Google"], [10, 12, 30, 0.5, 60, 40])], "meta": {"total_rows": 1}}+ )++ batches = list(+ get_rows("https://plausible.io", "example.com", "key", "sources", mock.MagicMock(), _make_manager())+ )++ rows = [row for batch in batches for row in batch]+ assert rows == [+ {+ "date": "2024-01-01",+ "source": "Google",+ "visitors": 10,+ "visits": 12,+ "pageviews": 30,+ "bounce_rate": 0.5,+ "visit_duration": 60,+ "events": 40,+ }+ ]+ body = mock_session.return_value.post.call_args.kwargs["json"]+ assert body["dimensions"] == ["time:day", "visit:source"]+ assert body["order_by"] == [["time:day", "asc"]]+ assert body["include"] == {"total_rows": True}+ assert body["pagination"]["offset"] == 0++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_paginates_until_short_page_and_saves_state(self, mock_session, mock_sleep):+ # Shrink the page size so two small pages exercise the offset pagination loop.+ with mock.patch.object(plausible_module, "DEFAULT_PAGE_LIMIT", 2):+ page1 = {+ "results": [_result(["2024-01-01"], [1, 1, 1, 0, 0, 1]), _result(["2024-01-02"], [2, 2, 2, 0, 0, 2])],+ "meta": {"total_rows": 3},+ }+ page2 = {"results": [_result(["2024-01-03"], [3, 3, 3, 0, 0, 3])], "meta": {"total_rows": 3}}+ mock_session.return_value.post.side_effect = [_response(page1), _response(page2)]++ manager = _make_manager()+ batches = list(+ get_rows("https://plausible.io", "example.com", "key", "timeseries", mock.MagicMock(), manager)+ )++ assert [len(batch) for batch in batches] == [2, 1]+ # The second request advances the offset past the first page.+ second_body = mock_session.return_value.post.call_args_list[1].kwargs["json"]+ assert second_body["pagination"]["offset"] == 2+ # State is saved once, after the first page, pointing at the next offset.+ assert [call.args[0].offset for call in manager.save_state.call_args_list] == [2]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_watermark_slides_window_back_by_lookback(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response({"results": [], "meta": {"total_rows": 0}})++ list(+ get_rows(+ "https://plausible.io",+ "example.com",+ "key",+ "timeseries",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-06-01",+ )+ )++ body = mock_session.return_value.post.call_args.kwargs["json"]+ expected_start = (datetime(2024, 6, 1, tzinfo=UTC).date() - timedelta(days=REPORT_LOOKBACK_DAYS)).isoformat()+ assert body["date_range"][0] == expected_start++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resume_state_pins_offset_and_window(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response({"results": [], "meta": {"total_rows": 0}})++ manager = _make_manager(+ PlausibleResumeConfig(offset=4, date_range_start="2024-01-01", date_range_end="2024-01-31")+ )+ list(get_rows("https://plausible.io", "example.com", "key", "timeseries", mock.MagicMock(), manager))++ body = mock_session.return_value.post.call_args.kwargs["json"]+ assert body["pagination"]["offset"] == 4+ assert body["date_range"] == ["2024-01-01", "2024-01-31"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_http_error_raises(self, mock_session, mock_sleep):+ error_response = _response({"error": "bad query"}, status_code=400)+ error_response.raise_for_status.side_effect = Exception("400 Client Error")+ mock_session.return_value.post.return_value = error_response++ with pytest.raises(Exception, match="400 Client Error"):+ list(+ get_rows("https://plausible.io", "example.com", "key", "timeseries", mock.MagicMock(), _make_manager())+ )+++class TestPlausibleSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = PLAUSIBLE_ENDPOINTS[endpoint]+ response = plausible_source(+ "https://plausible.io", "example.com", "key", endpoint, mock.MagicMock(), _make_manager()+ )++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert "date" in (response.primary_keys or [])+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["date"]diff --git a/posthog/temporal/data_imports/sources/plausible/tests/test_plausible_source.py b/posthog/temporal/data_imports/sources/plausible/tests/test_plausible_source.pynew file mode 100644index 000000000000..bce0443be5d9--- /dev/null+++ b/posthog/temporal/data_imports/sources/plausible/tests/test_plausible_source.py@@ -0,0 +1,146 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import SourceFieldInputConfig++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.plausible.plausible import PlausibleResumeConfig+from posthog.temporal.data_imports.sources.plausible.settings import ENDPOINTS, PLAUSIBLE_ENDPOINTS+from posthog.temporal.data_imports.sources.plausible.source import PlausibleSource++from products.data_warehouse.backend.types import ExternalDataSourceType++_MODULE = "posthog.temporal.data_imports.sources.plausible.source"+++def _config(host: str | None = None) -> mock.MagicMock:+ config = mock.MagicMock()+ config.api_key = "key"+ config.site_id = "example.com"+ config.host = host+ return config+++def _inputs(**overrides: Any) -> mock.MagicMock:+ inputs = mock.MagicMock()+ inputs.schema_name = "timeseries"+ inputs.team_id = 1+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = None+ for key, value in overrides.items():+ setattr(inputs, key, value)+ return inputs+++class TestSourceConfig:+ def test_source_type(self):+ assert PlausibleSource().source_type == ExternalDataSourceType.PLAUSIBLE++ def test_get_source_config_fields(self):+ config = PlausibleSource().get_source_config++ assert config.label == "Plausible"+ field_names = {field.name for field in config.fields}+ assert field_names == {"api_key", "site_id", "host"}++ by_name = {field.name: field for field in config.fields}+ assert all(isinstance(field, SourceFieldInputConfig) for field in by_name.values())+ api_key, site_id, host = by_name["api_key"], by_name["site_id"], by_name["host"]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert isinstance(site_id, SourceFieldInputConfig)+ assert isinstance(host, SourceFieldInputConfig)+ assert api_key.required is True+ assert api_key.secret is True+ assert site_id.required is True+ # Host is optional so Plausible Cloud users can leave it blank.+ assert host.required is False++ def test_connection_host_fields(self):+ # The API key is sent to `host`, so retargeting it must re-require secrets.+ assert PlausibleSource().connection_host_fields == ["host"]++ def test_non_retryable_errors_cover_auth(self):+ errors = PlausibleSource().get_non_retryable_errors()+ assert "401 Client Error" in errors+ assert "403 Client Error" in errors+++class TestGetSchemas:+ def test_all_endpoints_present_and_incremental(self):+ schemas = PlausibleSource().get_schemas(_config(), team_id=1)++ assert {s.name for s in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is True+ assert [f["field"] for f in schema.incremental_fields] == ["date"]++ def test_names_filter(self):+ schemas = PlausibleSource().get_schemas(_config(), team_id=1, names=["sources", "pages"])+ assert {s.name for s in schemas} == {"sources", "pages"}+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.validate_plausible_credentials")+ def test_valid(self, mock_validate):+ mock_validate.return_value = (True, None)+ source = PlausibleSource()+ with mock.patch.object(source, "is_database_host_valid", return_value=(True, None)):+ assert source.validate_credentials(_config(), team_id=1) == (True, None)++ @mock.patch(f"{_MODULE}.validate_plausible_credentials")+ def test_invalid_credentials_surface_message(self, mock_validate):+ mock_validate.return_value = (False, "Plausible rejected the API key.")+ source = PlausibleSource()+ with mock.patch.object(source, "is_database_host_valid", return_value=(True, None)):+ ok, error = source.validate_credentials(_config(), team_id=1)+ assert ok is False+ assert error == "Plausible rejected the API key."++ def test_unsafe_host_blocked(self):+ source = PlausibleSource()+ with mock.patch.object(source, "is_database_host_valid", return_value=(False, "Host not allowed")):+ ok, error = source.validate_credentials(_config(host="http://10.0.0.1"), team_id=1)+ assert ok is False+ assert error == "Host not allowed"+++class TestResumableAndPipeline:+ def test_get_resumable_source_manager_bound_to_data_class(self):+ manager = PlausibleSource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PlausibleResumeConfig++ @mock.patch(f"{_MODULE}.plausible_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_plausible_source):+ source = PlausibleSource()+ manager = mock.MagicMock()+ inputs = _inputs(should_use_incremental_field=True, db_incremental_field_last_value="2024-06-01")++ with mock.patch.object(source, "is_database_host_valid", return_value=(True, None)):+ source.source_for_pipeline(_config(), manager, inputs)++ kwargs = mock_plausible_source.call_args.kwargs+ assert kwargs["site_id"] == "example.com"+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "timeseries"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-06-01"++ @mock.patch(f"{_MODULE}.plausible_source")+ def test_source_for_pipeline_rejects_unsafe_host(self, mock_plausible_source):+ source = PlausibleSource()+ with mock.patch.object(source, "is_database_host_valid", return_value=(False, "Host not allowed")):+ with pytest.raises(ValueError, match="Host not allowed"):+ source.source_for_pipeline(_config(host="http://10.0.0.1"), mock.MagicMock(), _inputs())+++class TestCanonicalDescriptions:+ def test_descriptions_keyed_by_endpoint_names(self):+ descriptions = PlausibleSource().get_canonical_descriptions()+ # Every endpoint should have a curated description.+ assert set(descriptions.keys()) == set(PLAUSIBLE_ENDPOINTS.keys())+ for entry in descriptions.values():+ assert entry.get("description")+ assert "date" in entry.get("columns", {})