: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
from typing import Optional, cast
from products.warehouse_sources.sources.matomo._config import MatomoSourceConfig
from products.warehouse_sources.sources.matomo.matomo import (
MatomoResumeConfig,
hostname_of,
matomo_source,
validate_credentials as validate_matomo_credentials,
)
from products.warehouse_sources.sources.matomo.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.sources.sdk import (
CanonicalDescriptions,
DataWarehouseSourceCategory,
ExternalDataSourceType,
FieldType,
ProductKey,
ReleaseStatus,
ResumableSource,
ResumableSourceManager,
SourceConfig,
SourceFieldInputConfig,
SourceFieldInputConfigType,
SourceInputs,
SourceRegistry,
SourceResponse,
SourceSchema,
ValidateDatabaseHostMixin,
build_endpoint_schemas,
detect,
)
@SourceRegistry.register
class MatomoSource(ResumableSource[MatomoSourceConfig, MatomoResumeConfig], ValidateDatabaseHostMixin):
codebase_detection = detect(
env=("^MATOMO_", "^NEXT_PUBLIC_MATOMO_URL$", "^NEXT_PUBLIC_MATOMO_SITE_ID$"),
script_hosts=("cdn.matomo.cloud", "cdn.innocraft.cloud"),
npm=(
"matomo-tracker",
"vue-matomo",
"ngx-matomo-client",
"@ngx-matomo/tracker",
"@ngx-matomo/router",
"@socialgouv/matomo-next",
"@datapunt/matomo-tracker-react",
"@datapunt/matomo-tracker-js",
"@jonkoops/matomo-tracker",
"@jonkoops/matomo-tracker-react",
"matomo-tracker-react-native",
"matomo-tracker-for-react",
"docusaurus-plugin-matomo",
"astro-matomo",
"@openmost/nuxt-matomo",
"piwik-react-router",
"piwik-tracker",
),
pypi=("piwikapi", "piwik-tracker", "django-matomo", "matomo-api"),
cocoapods=("MatomoTracker", "PiwikTracker"),
composer=(
"matomo/matomo-php-tracker",
"piwik/piwik-php-tracker",
"matomo/matomo",
"visualappeal/matomo-php-api",
"webfactory/piwik-bundle",
),
maven=(
"org.piwik.java.tracking:matomo-java-tracker",
"org.piwik.java.tracking:matomo-java-tracker-core",
"org.piwik.java.tracking:matomo-java-tracker-java11",
"org.piwik.java.tracking:matomo-java-tracker-java17",
"org.piwik.java.tracking:matomo-java-tracker-servlet",
"org.piwik.java.tracking:matomo-java-tracker-servlet-jakarta",
"org.piwik.java.tracking:matomo-java-tracker-servlet-javax",
"org.piwik.java.tracking:matomo-java-tracker-spring-boot-starter",
"org.piwik.java.tracking:piwik-java-tracker",
"com.github.matomo-org:matomo-sdk-android",
),
pub=("matomo_tracker", "matomo"),
rubygems=("autometal-piwik", "piwik_analytics"),
swiftpm=("github.com/matomo-org/matomo-sdk-ios",),
alternative_to=(ProductKey.WEB_ANALYTICS,),
)
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
api_docs_url = "https://developer.matomo.org/api-reference/reporting-api"
@property
def 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.",
# The instance's own HTTPS certificate has expired. This is a problem with the
# customer's Matomo host, not PostHog's request, and every retry hits the same
# expired cert until they renew it.
"certificate has expired": "PostHog could not connect to your Matomo instance because its SSL certificate has expired. Renew the certificate on your Matomo host, then try again.",
# Every call goes to the one reporting endpoint, and Matomo answers a method it does
# not know with a 200 error envelope, so a 404 means the instance URL points at
# something that is not a Matomo instance, or at one that is gone. The URL is fixed
# until the customer edits it, so every retry replays the same 404.
"404 Client Error: Not Found for url": (
"PostHog couldn't find a Matomo instance at the URL configured for this source. "
"Check the instance URL, then reconnect."
),
"Matomo API error:": None,
}
def get_retryable_errors(self) -> set[str]:
# A 429 or 5xx is retried internally; if those retries still exhaust, the failure is
# transient and self-recovering, so let Temporal retry the activity without surfacing
# it as tracked exception noise.
return {"Matomo API error (retryable)"}
def get_retry_exhausted_errors(self) -> dict[str, str]:
# Once Temporal's retries are spent too, the job keeps the internal marker above as its
# customer-facing error, down to the raw HTTP status. Name the failure instead.
return {
"Matomo API error (retryable)": (
"Matomo kept returning temporary errors, such as rate limits, so this sync run did "
"not finish. This usually clears on its own and the next sync runs on schedule."
),
}
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.MATOMO,
category=DataWarehouseSourceCategory.ANALYTICS,
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",
docsUrl="https://posthog.com/docs/cdp/sources/matomo",
releaseStatus=ReleaseStatus.GA,
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_canonical_descriptions(self) -> CanonicalDescriptions:
from products.warehouse_sources.sources.matomo.canonical_descriptions import CANONICAL_DESCRIPTIONS
return CANONICAL_DESCRIPTIONS
def get_schemas(
self,
config: MatomoSourceConfig,
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)
def validate_credentials(
self,
config: MatomoSourceConfig,
team_id: int,
schema_name: Optional[str] = None,
api_version: str | None = 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,
)