: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 matomo import source (#63006)
Tom Owers1dcf48dccaaf
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 3bd8bbba3677..3b5cba5c79ca 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -117,6 +117,7 @@ the row lists both.| mailerlite | HTTP | requests | ✅ || mailgun | HTTP | requests | ✅ || mailjet | HTTP | requests | ✅ |+| matomo | HTTP | requests | ✅ || meta_ads | HTTP | requests | ✅ || mixpanel | HTTP | requests | ✅ || mollie | HTTP | requests | ✅ |@@ -274,7 +275,6 @@ doesn't conflict with concurrent PRs.- lever- lightspeed_retail- marketo-- matomo- microsoft_teams- netsuite- onedrivediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 424fdd8fc7d2..d876bec6f206 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -862,7 +862,9 @@ class MarketoSourceConfig(config.Config):@config.configclass MatomoSourceConfig(config.Config):- pass+ host: str+ site_id: str+ api_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/matomo/matomo.py b/posthog/temporal/data_imports/sources/matomo/matomo.pynew file mode 100644index 000000000000..5e2e6c780d9a--- /dev/null+++ b/posthog/temporal/data_imports/sources/matomo/matomo.py@@ -0,0 +1,282 @@+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.matomo.settings import (+ DEFAULT_BACKFILL_DAYS,+ MATOMO_ENDPOINTS,+ REPORT_LOOKBACK_DAYS,+ VISIT_FINALITY_WINDOW_SECONDS,+)++REQUEST_TIMEOUT_SECONDS = 120+# Matomo Cloud caps Live methods at 200/min and reports at 350/min per IP.+REQUEST_THROTTLE_SECONDS = 0.35+MAX_RETRY_ATTEMPTS = 5+VISITS_PAGE_SIZE = 1000+++class MatomoRetryableError(Exception):+ pass+++class MatomoResumeConfig:+ # Visits: the serverTimestamp cursor of the next minTimestamp request.+ # Reports: the next unfetched day (yyyy-mm-dd).+ min_timestamp: Optional[int] = None+ next_date: 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("Matomo 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 Matomo host: {host}")+ return host+++def hostname_of(host: str) -> str:+ return urlparse(normalize_host(host)).hostname or ""+++def _get_session(api_token: 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).+ return make_tracked_session(redact_values=(api_token,), 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 validate_credentials(host: str, site_id: str, api_token: str) -> bool:+ """Confirm the instance is reachable and the token can read the site."""+ try:+ response = _get_session(api_token).post(+ f"{normalize_host(host)}/index.php",+ data={+ "module": "API",+ "method": "SitesManager.getSiteFromId",+ "idSite": site_id,+ "format": "JSON",+ # The token goes in the POST body, never the query string, so+ # it can't leak into server access logs.+ "token_auth": api_token,+ },+ timeout=15,+ )+ if response.status_code != 200:+ return False+ body = response.json()+ return not (isinstance(body, dict) and body.get("result") == "error")+ except Exception:+ return False+++def get_rows(+ host: str,+ site_id: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MatomoResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = MATOMO_ENDPOINTS[endpoint]+ session = _get_session(api_token)+ api_url = f"{normalize_host(host)}/index.php"++ @retry(+ retry=retry_if_exception_type((MatomoRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+ )+ def call(method: str, extra: dict[str, Any]) -> Any:+ # Throttle every call, including tenacity retries, so a retry storm+ # can't blow past Matomo's per-IP rate limit on top of the backoff.+ time.sleep(REQUEST_THROTTLE_SECONDS)+ response = session.post(+ api_url,+ data={+ "module": "API",+ "method": method,+ "idSite": site_id,+ "format": "JSON",+ "token_auth": api_token,+ **extra,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise MatomoRetryableError(f"Matomo API error (retryable): status={response.status_code}")++ if not response.ok:+ logger.error(f"Matomo API error: status={response.status_code}, body={response.text[:500]}")+ response.raise_for_status()++ body = response.json()+ # Matomo reports application errors as 200s with a result envelope.+ if isinstance(body, dict) and body.get("result") == "error":+ raise ValueError(f"Matomo API error: {body.get('message')}")+ return body++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.kind == "visits":+ min_timestamp = 0+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ try:+ min_timestamp = int(float(db_incremental_field_last_value))+ except (TypeError, ValueError):+ min_timestamp = 0+ if resume_config is not None and resume_config.min_timestamp is not None:+ min_timestamp = max(min_timestamp, resume_config.min_timestamp)+ logger.debug(f"Matomo: resuming visits from minTimestamp {min_timestamp}")++ # Defer visits that may still be in progress so their action list is+ # complete when stored; they're picked up by the next sync instead.+ finality_cutoff = int(datetime.now(tz=UTC).timestamp()) - VISIT_FINALITY_WINDOW_SECONDS++ today = datetime.now(tz=UTC).date()+ if min_timestamp > 0:+ range_start = datetime.fromtimestamp(min_timestamp, tz=UTC).date()+ else:+ range_start = today - timedelta(days=DEFAULT_BACKFILL_DAYS)++ while True:+ batch = call(+ config.method,+ {+ "period": "range",+ "date": f"{range_start.isoformat()},{today.isoformat()}",+ "filter_limit": VISITS_PAGE_SIZE,+ "filter_sort_order": "asc",+ "minTimestamp": min_timestamp,+ },+ )+ if not isinstance(batch, list):+ return+ visits = [row for row in batch if isinstance(row, dict)]++ final_visits = []+ for visit in visits:+ ts = visit.get("serverTimestamp")+ if isinstance(ts, (int, float)) and ts > finality_cutoff:+ continue+ final_visits.append(visit)++ if final_visits:+ yield final_visits++ if len(visits) < VISITS_PAGE_SIZE or not final_visits:+ return++ timestamps = [+ int(v["serverTimestamp"]) for v in final_visits if isinstance(v.get("serverTimestamp"), (int, float))+ ]+ if not timestamps:+ return+ next_min_timestamp = max(timestamps)+ # minTimestamp is inclusive: boundary visits at the max second get+ # refetched next page and deduped on idVisit (fine). But if a full+ # page's visits all fall in a single second, advancing to that+ # second returns the same page forever, so step one second past it+ # to guarantee progress. The only loss is overflow beyond+ # VISITS_PAGE_SIZE visits within that one second — an accepted+ # tradeoff against stalling the sync indefinitely.+ if next_min_timestamp <= min_timestamp or min(timestamps) == next_min_timestamp:+ next_min_timestamp = next_min_timestamp + 1+ min_timestamp = next_min_timestamp+ # Save state AFTER yielding so a crash re-yields the in-flight+ # batch (merge dedupes on idVisit).+ resumable_source_manager.save_state(MatomoResumeConfig(min_timestamp=min_timestamp))++ # Per-day report walk, oldest-first. Recent days re-archive, so+ # incremental runs re-pull a trailing lookback window.+ 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:+ start = watermark - timedelta(days=REPORT_LOOKBACK_DAYS)++ if resume_config is not None and resume_config.next_date:+ resumed = _to_date(resume_config.next_date)+ if resumed is not None and resumed > start:+ start = resumed+ logger.debug(f"Matomo: resuming {endpoint} from {start.isoformat()}")++ day = start+ while day <= today:+ body = call(config.method, {"period": "day", "date": day.isoformat(), "filter_limit": -1})+ rows = body if isinstance(body, list) else ([body] if isinstance(body, dict) and body else [])+ rows = [{**row, "_date": day.isoformat()} for row in rows if isinstance(row, dict)]+ if rows:+ yield rows++ day = day + timedelta(days=1)+ if day <= today:+ # Save state AFTER yielding so a crash re-yields the in-flight day.+ resumable_source_manager.save_state(MatomoResumeConfig(next_date=day.isoformat()))+++def matomo_source(+ host: str,+ site_id: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MatomoResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = MATOMO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ host=host,+ site_id=site_id,+ api_token=api_token,+ 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),+ partition_count=1,+ partition_size=1,+ # Visits are fetched ascending by serverTimestamp; report days are+ # walked oldest-first — both cursors only move forward.+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/matomo/settings.py b/posthog/temporal/data_imports/sources/matomo/settings.pynew file mode 100644index 000000000000..fa182740dcb1--- /dev/null+++ b/posthog/temporal/data_imports/sources/matomo/settings.py@@ -0,0 +1,91 @@+from dataclasses import dataclass, field+from typing import Literal++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Reports for recent days change until archiving completes, so incremental+# syncs re-pull a trailing window and merge on (_date, ...).+REPORT_LOOKBACK_DAYS = 3+# Default history pulled on the first sync of a stream (visits and reports).+DEFAULT_BACKFILL_DAYS = 365+# Visits newer than this are considered possibly still in progress and are+# deferred to the next sync so their action list is complete when stored.+VISIT_FINALITY_WINDOW_SECONDS = 3600++MatomoEndpointKind = Literal["visits", "report"]++_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "_date",+ "type": IncrementalFieldType.Date,+ "field": "_date",+ "field_type": IncrementalFieldType.Date,+ },+]+++@dataclass+class MatomoEndpointConfig:+ name: str+ kind: MatomoEndpointKind+ # Matomo Reporting API method name (everything goes through one RPC-style+ # endpoint: index.php?module=API&method=...).+ method: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++MATOMO_ENDPOINTS: dict[str, MatomoEndpointConfig] = {+ # Raw visit log, cursored on the visit's serverTimestamp via the+ # server-side minTimestamp filter.+ "visits": MatomoEndpointConfig(+ name="visits",+ kind="visits",+ method="Live.getLastVisitsDetails",+ primary_keys=["idVisit"],+ incremental_fields=[+ {+ "label": "serverTimestamp",+ "type": IncrementalFieldType.Numeric,+ "field": "serverTimestamp",+ "field_type": IncrementalFieldType.Numeric,+ },+ ],+ ),+ # Per-day aggregate reports, date-partitioned via period=day&date=...+ # with the day injected as `_date`.+ "visits_summary": MatomoEndpointConfig(+ name="visits_summary",+ kind="report",+ method="VisitsSummary.get",+ primary_keys=["_date"],+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),+ ),+ "actions_summary": MatomoEndpointConfig(+ name="actions_summary",+ kind="report",+ method="Actions.get",+ primary_keys=["_date"],+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),+ ),+ "referrers": MatomoEndpointConfig(+ name="referrers",+ kind="report",+ method="Referrers.getAll",+ primary_keys=["_date", "label"],+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),+ ),+ "countries": MatomoEndpointConfig(+ name="countries",+ kind="report",+ method="UserCountry.getCountry",+ primary_keys=["_date", "label"],+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),+ ),+}++ENDPOINTS = tuple(MATOMO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in MATOMO_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/matomo/source.py b/posthog/temporal/data_imports/sources/matomo/source.pyindex 93a54b0acca5..ae1678a4d739 100644--- a/posthog/temporal/data_imports/sources/matomo/source.py+++ b/posthog/temporal/data_imports/sources/matomo/source.py@@ -1,29 +1,153 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (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.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 MatomoSourceConfig+from posthog.temporal.data_imports.sources.matomo.matomo import (+ MatomoResumeConfig,+ hostname_of,+ matomo_source,+ validate_credentials as validate_matomo_credentials,+)+from posthog.temporal.data_imports.sources.matomo.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class MatomoSource(SimpleSource[MatomoSourceConfig]):+class MatomoSource(ResumableSource[MatomoSourceConfig, MatomoResumeConfig], ValidateDatabaseHostMixin):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MATOMO+ @property+ def connection_host_fields(self) -> list[str]:+ # `host` determines where the stored token is sent; retargeting it+ # must re-require the token.+ return ["host"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Matomo authentication failed. Please check your API token.",+ "403 Client Error: Forbidden for url": "Matomo denied access. Please check your API token's permissions for this site.",+ "Matomo API error:": None,+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.MATOMO,label="Matomo",+ caption="""Connect your Matomo instance to pull your web analytics data into the PostHog Data warehouse.++Works with Matomo Cloud and self-hosted instances. Enter your instance URL (e.g. `https://myorg.matomo.cloud`), the numeric site ID, and an API token created under Administration > Personal > Security > Auth tokens.""",iconPath="/static/services/matomo.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/matomo",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Instance URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://myorg.matomo.cloud",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="site_id",+ label="Site ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="1",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: MatomoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(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: MatomoSourceConfig, 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 Matomo instance URL"+ if not host_valid:+ return False, host_error++ if validate_matomo_credentials(config.host, config.site_id, config.api_token):+ return True, None++ return False, "Invalid Matomo credentials. Check the instance URL, site ID, and API token."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MatomoResumeConfig]:+ return ResumableSourceManager[MatomoResumeConfig](inputs, MatomoResumeConfig)++ def source_for_pipeline(+ self,+ config: MatomoSourceConfig,+ resumable_source_manager: ResumableSourceManager[MatomoResumeConfig],+ 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 Matomo host")++ return matomo_source(+ host=config.host,+ site_id=config.site_id,+ api_token=config.api_token,+ 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/matomo/tests/test_matomo.py b/posthog/temporal/data_imports/sources/matomo/tests/test_matomo.pynew file mode 100644index 000000000000..48c6cbc9a5e3--- /dev/null+++ b/posthog/temporal/data_imports/sources/matomo/tests/test_matomo.py@@ -0,0 +1,285 @@+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.matomo.matomo import (+ VISITS_PAGE_SIZE,+ MatomoResumeConfig,+ get_rows,+ hostname_of,+ matomo_source,+ normalize_host,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.matomo.settings import (+ ENDPOINTS,+ MATOMO_ENDPOINTS,+ REPORT_LOOKBACK_DAYS,+ VISIT_FINALITY_WINDOW_SECONDS,+)++_MODULE = "posthog.temporal.data_imports.sources.matomo.matomo"+++def _make_manager(resume_state: MatomoResumeConfig | 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+ return resp+++def _final_ts(offset_seconds: int = 0) -> int:+ # A timestamp safely older than the finality window.+ return int(datetime.now(tz=UTC).timestamp()) - VISIT_FINALITY_WINDOW_SECONDS - 100 - offset_seconds+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("https://myorg.matomo.cloud", "https://myorg.matomo.cloud"),+ ("myorg.matomo.cloud", "https://myorg.matomo.cloud"),+ ("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)++ def test_hostname_of(self):+ assert hostname_of("https://myorg.matomo.cloud/path") == "myorg.matomo.cloud"+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_credentials(self, mock_session):+ mock_session.return_value.post.return_value = _response({"idsite": "1", "name": "My site"})++ assert validate_credentials("https://myorg.matomo.cloud", "1", "token") is True+ body = mock_session.return_value.post.call_args.kwargs["data"]+ assert body["method"] == "SitesManager.getSiteFromId"+ assert body["token_auth"] == "token"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_error_envelope_fails_validation(self, mock_session):+ mock_session.return_value.post.return_value = _response({"result": "error", "message": "bad token"})++ assert validate_credentials("https://myorg.matomo.cloud", "1", "bad") is False++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_http_error_fails_validation(self, mock_session):+ mock_session.return_value.post.return_value = _response({}, status_code=403)++ assert validate_credentials("https://myorg.matomo.cloud", "1", "token") is False++[email protected](f"{_MODULE}.time.sleep")+class TestVisits:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_short_batch_yields_and_stops(self, mock_session, mock_sleep):+ ts = _final_ts()+ mock_session.return_value.post.return_value = _response(+ [{"idVisit": "1", "serverTimestamp": ts}, {"idVisit": "2", "serverTimestamp": ts + 1}]+ )++ manager = _make_manager()+ batches = list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), manager))++ assert [row["idVisit"] for batch in batches for row in batch] == ["1", "2"]+ body = mock_session.return_value.post.call_args.kwargs["data"]+ assert body["method"] == "Live.getLastVisitsDetails"+ assert body["filter_sort_order"] == "asc"+ assert body["minTimestamp"] == 0+ assert body["token_auth"] == "token"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_page_advances_min_timestamp_cursor(self, mock_session, mock_sleep):+ base = _final_ts(10_000)+ first_page = [{"idVisit": str(i), "serverTimestamp": base + i} for i in range(VISITS_PAGE_SIZE)]+ second_page = [{"idVisit": "last", "serverTimestamp": base + VISITS_PAGE_SIZE}]+ mock_session.return_value.post.side_effect = [_response(first_page), _response(second_page)]++ manager = _make_manager()+ batches = list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), manager))++ assert [len(batch) for batch in batches] == [VISITS_PAGE_SIZE, 1]+ second_body = mock_session.return_value.post.call_args_list[1].kwargs["data"]+ assert second_body["minTimestamp"] == base + VISITS_PAGE_SIZE - 1+ assert [call.args[0].min_timestamp for call in manager.save_state.call_args_list] == [+ base + VISITS_PAGE_SIZE - 1+ ]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_page_at_one_timestamp_steps_past_cursor(self, mock_session, mock_sleep):+ # minTimestamp is inclusive, so a full page whose visits all share the+ # same second must step the cursor forward or it would refetch forever.+ ts = _final_ts(10_000)+ first_page = [{"idVisit": str(i), "serverTimestamp": ts} for i in range(VISITS_PAGE_SIZE)]+ second_page = [{"idVisit": "last", "serverTimestamp": ts + 5}]+ mock_session.return_value.post.side_effect = [_response(first_page), _response(second_page)]++ manager = _make_manager()+ batches = list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), manager))++ assert [len(batch) for batch in batches] == [VISITS_PAGE_SIZE, 1]+ second_body = mock_session.return_value.post.call_args_list[1].kwargs["data"]+ assert second_body["minTimestamp"] == ts + 1+ assert [call.args[0].min_timestamp for call in manager.save_state.call_args_list] == [ts + 1]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_still_active_visits_are_deferred(self, mock_session, mock_sleep):+ now = int(datetime.now(tz=UTC).timestamp())+ mock_session.return_value.post.return_value = _response(+ [+ {"idVisit": "done", "serverTimestamp": _final_ts()},+ {"idVisit": "active", "serverTimestamp": now - 10},+ ]+ )++ batches = list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), _make_manager()))++ assert [row["idVisit"] for batch in batches for row in batch] == ["done"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_watermark_sets_min_timestamp(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response([])++ list(+ get_rows(+ "https://m.example.com",+ "1",+ "token",+ "visits",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ )+ )++ body = mock_session.return_value.post.call_args.kwargs["data"]+ assert body["minTimestamp"] == 1700000000++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resume_state_supersedes_older_watermark(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response([])++ manager = _make_manager(MatomoResumeConfig(min_timestamp=1800000000))+ list(+ get_rows(+ "https://m.example.com",+ "1",+ "token",+ "visits",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ )+ )++ body = mock_session.return_value.post.call_args.kwargs["data"]+ assert body["minTimestamp"] == 1800000000++[email protected](f"{_MODULE}.time.sleep")+class TestReports:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_walks_days_oldest_first_and_injects_date(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response({"nb_visits": 5})++ manager = _make_manager()+ batches = list(+ get_rows(+ "https://m.example.com",+ "1",+ "token",+ "visits_summary",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime.now(tz=UTC).date().isoformat(),+ )+ )++ # Lookback window: REPORT_LOOKBACK_DAYS + 1 days, one row per day.+ assert len(batches) == REPORT_LOOKBACK_DAYS + 1+ dates = [batch[0]["_date"] for batch in batches]+ assert dates == sorted(dates)+ assert all(batch[0]["nb_visits"] == 5 for batch in batches)+ first_body = mock_session.return_value.post.call_args_list[0].kwargs["data"]+ assert first_body["period"] == "day"+ assert first_body["method"] == "VisitsSummary.get"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_list_reports_yield_rows_per_day(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response([{"label": "Direct"}, {"label": "Search"}])++ batches = list(+ get_rows(+ "https://m.example.com",+ "1",+ "token",+ "referrers",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime.now(tz=UTC).date().isoformat(),+ )+ )++ assert all(len(batch) == 2 for batch in batches)+ assert all("_date" in row for batch in batches for row in batch)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resume_date_supersedes_older_start(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response({})++ today = datetime.now(tz=UTC).date().isoformat()+ manager = _make_manager(MatomoResumeConfig(next_date=today))+ list(get_rows("https://m.example.com", "1", "token", "visits_summary", mock.MagicMock(), manager))++ assert mock_session.return_value.post.call_count == 1+ assert mock_session.return_value.post.call_args.kwargs["data"]["date"] == today++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_api_error_envelope_raises(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response({"result": "error", "message": "no access"})++ with pytest.raises(ValueError, match="no access"):+ list(+ get_rows(+ "https://m.example.com",+ "1",+ "token",+ "visits_summary",+ mock.MagicMock(),+ _make_manager(MatomoResumeConfig(next_date=datetime.now(tz=UTC).date().isoformat())),+ )+ )+++class TestMatomoSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = MATOMO_ENDPOINTS[endpoint]+ response = matomo_source("https://m.example.com", "1", "token", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"diff --git a/posthog/temporal/data_imports/sources/matomo/tests/test_matomo_source.py b/posthog/temporal/data_imports/sources/matomo/tests/test_matomo_source.pynew file mode 100644index 000000000000..3dc602f80d9f--- /dev/null+++ b/posthog/temporal/data_imports/sources/matomo/tests/test_matomo_source.py@@ -0,0 +1,162 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import MatomoSourceConfig+from posthog.temporal.data_imports.sources.matomo.matomo import MatomoResumeConfig+from posthog.temporal.data_imports.sources.matomo.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.matomo.source import MatomoSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestMatomoSource:+ def setup_method(self):+ self.source = MatomoSource()+ self.team_id = 123+ self.config = MatomoSourceConfig(host="https://myorg.matomo.cloud", site_id="1", api_token="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.MATOMO++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Matomo"+ assert config.label == "Matomo"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/matomo.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["host", "site_id", "api_token"]++ def test_api_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_connection_host_fields_cover_host(self):+ # The instance URL decides where the stored token gets sent.+ assert self.source.connection_host_fields == ["host"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://myorg.matomo.cloud/index.php",+ "403 Client Error: Forbidden for url: https://myorg.matomo.cloud/index.php",+ "Matomo API error: You can't access this resource",+ ],+ )+ def test_non_retryable_errors_match_known_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ def test_non_retryable_errors_does_not_match_server_errors(self):+ non_retryable_errors = self.source.get_non_retryable_errors()+ error = "500 Server Error for url: https://myorg.matomo.cloud/index.php"+ assert not any(key in error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # Everything is incremental: visits via minTimestamp, reports via the+ # injected per-day _date.+ assert all(schema.supports_incremental for schema in schemas.values())+ assert [f["field"] for f in schemas["visits"].incremental_fields] == ["serverTimestamp"]+ assert [f["field"] for f in schemas["referrers"].incremental_fields] == ["_date"]+ assert schemas["visits"].incremental_fields == INCREMENTAL_FIELDS["visits"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["visits"])+ assert len(schemas) == 1+ assert schemas[0].name == "visits"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @mock.patch("posthog.temporal.data_imports.sources.matomo.source.validate_matomo_credentials")+ @mock.patch.object(MatomoSource, "is_database_host_valid")+ def test_validate_credentials_happy_path(self, mock_host_valid, mock_validate):+ mock_host_valid.return_value = (True, None)+ mock_validate.return_value = True++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is True+ assert error_message is None+ mock_host_valid.assert_called_once_with("myorg.matomo.cloud", self.team_id)+ mock_validate.assert_called_once_with("https://myorg.matomo.cloud", "1", "token")++ @mock.patch.object(MatomoSource, "is_database_host_valid")+ def test_validate_credentials_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error_message == "Host is not allowed"++ def test_validate_credentials_rejects_invalid_url(self):+ config = MatomoSourceConfig(host="ftp://nope", site_id="1", api_token="token")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error_message == "Invalid Matomo instance URL"++ @mock.patch("posthog.temporal.data_imports.sources.matomo.source.validate_matomo_credentials")+ @mock.patch.object(MatomoSource, "is_database_host_valid")+ def test_validate_credentials_bad_token(self, mock_host_valid, mock_validate):+ mock_host_valid.return_value = (True, None)+ mock_validate.return_value = False++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert "Invalid Matomo credentials" in (error_message or "")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is MatomoResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.matomo.source.matomo_source")+ @mock.patch.object(MatomoSource, "is_database_host_valid")+ def test_source_for_pipeline_plumbs_arguments(self, mock_host_valid, mock_matomo_source):+ mock_host_valid.return_value = (True, None)+ inputs = mock.MagicMock()+ inputs.schema_name = "visits"+ inputs.team_id = self.team_id+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1700000000+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_matomo_source.assert_called_once()+ kwargs = mock_matomo_source.call_args.kwargs+ assert kwargs["host"] == "https://myorg.matomo.cloud"+ assert kwargs["site_id"] == "1"+ assert kwargs["api_token"] == "token"+ assert kwargs["endpoint"] == "visits"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == 1700000000++ @mock.patch.object(MatomoSource, "is_database_host_valid")+ def test_source_for_pipeline_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")+ inputs = mock.MagicMock()+ inputs.schema_name = "visits"+ inputs.team_id = self.team_id++ with pytest.raises(ValueError, match="Host is not allowed"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)