Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement dixa import source (#62910)

Tom Owersc2f318cdca1e
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 7e955e9d20cd..11839bc2d046 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -85,6 +85,7 @@ the row lists both.
| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) |
| datadog | HTTP | requests | ✅ |
| delighted | HTTP | requests | ✅ |
+| dixa | HTTP | requests | ✅ |
| doit | HTTP | requests | ✅ |
| drip | HTTP | requests | ✅ |
| freshdesk | HTTP | requests | ✅ |
@@ -252,7 +253,6 @@ doesn't conflict with concurrent PRs.
- db2
- deel
- display_video_360
-- dixa
- docusign
- dropbox
- dynamics365
diff --git a/posthog/temporal/data_imports/sources/dixa/dixa.py b/posthog/temporal/data_imports/sources/dixa/dixa.py
new file mode 100644
index 000000000000..4bab9b7a252a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/dixa/dixa.py
@@ -0,0 +1,232 @@
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urljoin, 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.dixa.settings import DIXA_ENDPOINTS
+
+DIXA_MAIN_BASE_URL = "https://dev.dixa.io/v1"
+DIXA_EXPORT_BASE_URL = "https://exports.dixa.io/v1"
+# Hosts we will send the Bearer token to. meta.next pagination URLs and
+# resumed state are validated against this so a tampered/absolute URL can't
+# exfiltrate the token to an attacker-controlled host.
+DIXA_MAIN_HOST = urlparse(DIXA_MAIN_BASE_URL).netloc
+# Export queries cannot span more than 31 days; stay safely under.
+EXPORT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000
+# Dixa has no created-before-2015 data; full exports start here.
+EXPORT_EPOCH_MS = int(datetime(2015, 1, 1, tzinfo=UTC).timestamp() * 1000)
+# conversation_export allows only 10 requests/minute per org token.
+EXPORT_REQUEST_INTERVAL_SECONDS = 6.5
+REQUEST_TIMEOUT_SECONDS = 120
+MAX_RETRY_ATTEMPTS = 5
+
+
+class DixaRetryableError(Exception):
+ pass
+
+
+class DixaResumeConfig:
+ # Export streams persist the start of the next time window (Unix ms); main
+ # API streams persist the opaque next-page URL from meta.next.
+ window_start_ms: Optional[int] = None
+ next_url: Optional[str] = None
+
+
+def _get_session(api_token: str) -> requests.Session:
+ # allow_redirects=False so a redirect response can't reroute the Bearer
+ # token to a different host.
+ return make_tracked_session(
+ headers={"Authorization": f"Bearer {api_token}"},
+ redact_values=(api_token,),
+ allow_redirects=False,
+ )
+
+
+def _is_dixa_main_host(url: str) -> bool:
+ return urlparse(url).netloc == DIXA_MAIN_HOST
+
+
+def _to_ms(value: Any) -> Optional[int]:
+ """Coerce an incremental cursor value to Unix milliseconds for export filters."""
+ if value is None or isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ return int(value)
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return int(dt.timestamp() * 1000)
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _now_ms() -> int:
+ return int(datetime.now(UTC).timestamp() * 1000)
+
+
+def validate_credentials(api_token: str) -> tuple[bool, Optional[str]]:
+ """Probe the API token with a cheap agents listing.
+
+ Returns ``(is_valid, error_message)``. Only an explicit auth rejection
+ (401/403) is reported as an invalid token — transient failures (429, 5xx,
+ network errors) get a distinct message so a working token isn't mislabelled
+ as wrong when Dixa is merely unreachable.
+ """
+ try:
+ response = _get_session(api_token).get(
+ f"{DIXA_MAIN_BASE_URL}/agents",
+ timeout=10,
+ )
+ except Exception:
+ return False, "Could not reach Dixa to validate the API token. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Invalid Dixa API token"
+ return (
+ False,
+ f"Dixa returned an unexpected response ({response.status_code}) while validating the API token. Please try again.",
+ )
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DixaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = DIXA_ENDPOINTS[endpoint]
+ session = _get_session(api_token)
+
+ @retry(
+ retry=retry_if_exception_type((DixaRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=5, max=120),
+ reraise=True,
+ )
+ def fetch(url: str) -> Any:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise DixaRetryableError(f"Dixa API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Dixa API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.surface == "export":
+ # The Exports API takes a mandatory time window (max 31 days) and
+ # returns the whole window as one JSON array — walk windows forward
+ # from the watermark (or Dixa's epoch on a full export).
+ if resume_config is not None and resume_config.window_start_ms is not None:
+ window_start = resume_config.window_start_ms
+ logger.debug(f"Dixa: resuming {endpoint} from window start {window_start}")
+ elif should_use_incremental_field:
+ window_start = _to_ms(db_incremental_field_last_value) or EXPORT_EPOCH_MS
+ else:
+ window_start = EXPORT_EPOCH_MS
+
+ is_first_window = True
+ while window_start < _now_ms():
+ window_end = min(window_start + EXPORT_WINDOW_MS, _now_ms())
+ params = {"updated_after": window_start, "updated_before": window_end}
+ # conversation_export is rate limited to 10 req/min — space requests
+ # out, but don't penalise the first request of the run (the limit
+ # hasn't been touched yet).
+ if not is_first_window:
+ time.sleep(EXPORT_REQUEST_INTERVAL_SECONDS)
+ is_first_window = False
+ data = fetch(f"{DIXA_EXPORT_BASE_URL}{config.path}?{urlencode(params)}")
+ items = data if isinstance(data, list) else []
+
+ if items:
+ yield items
+
+ window_start = window_end
+ # Save state AFTER yielding the window so a crash re-yields it
+ # (merge dedupes on primary key) rather than skipping it.
+ resumable_source_manager.save_state(DixaResumeConfig(window_start_ms=window_start))
+ return
+
+ if resume_config is not None and resume_config.next_url is not None and _is_dixa_main_host(resume_config.next_url):
+ url: str = resume_config.next_url
+ logger.debug(f"Dixa: resuming {endpoint} from URL: {url}")
+ else:
+ url = f"{DIXA_MAIN_BASE_URL}{config.path}"
+
+ while True:
+ data = fetch(url)
+ items = data.get("data", []) if isinstance(data, dict) else []
+ items = items or []
+
+ if items:
+ yield items
+
+ next_link = (data.get("meta") or {}).get("next") if isinstance(data, dict) else None
+ if not next_link or not items:
+ break
+
+ # meta.next can be a relative path; absolutize against the main host.
+ next_url = urljoin(DIXA_MAIN_BASE_URL, next_link)
+ # urljoin returns an absolute meta.next unchanged, so a tampered URL
+ # pointing elsewhere would otherwise receive the Bearer token. Stop
+ # paginating if it doesn't resolve to the Dixa main host.
+ if not _is_dixa_main_host(next_url):
+ logger.warning(f"Dixa: meta.next resolved to unexpected host, stopping pagination: {next_url}")
+ break
+ resumable_source_manager.save_state(DixaResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def dixa_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DixaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = DIXA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ 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=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ 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,
+ # Export windows advance chronologically, so the watermark (max
+ # updated_at per batch) only moves forward.
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/dixa/settings.py b/posthog/temporal/data_imports/sources/dixa/settings.py
new file mode 100644
index 000000000000..0bc085c5bbc9
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/dixa/settings.py
@@ -0,0 +1,62 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class DixaEndpointConfig:
+ name: str
+ path: str
+ # Dixa has two API surfaces: the main API (dev.dixa.io/v1, cursor-paginated
+ # dimension tables) and the Exports API (exports.dixa.io/v1, time-windowed
+ # bulk arrays with strict per-minute rate limits).
+ surface: Literal["main", "export"]
+ primary_key: str = "id"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field used for datetime partitioning (Unix ms).
+ partition_key: Optional[str] = None
+
+
+DIXA_ENDPOINTS: dict[str, DixaEndpointConfig] = {
+ "conversations": DixaEndpointConfig(
+ name="conversations",
+ path="/conversation_export",
+ surface="export",
+ partition_key="created_at",
+ incremental_fields=[
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ ),
+ "agents": DixaEndpointConfig(
+ name="agents",
+ path="/agents",
+ surface="main",
+ ),
+ "endusers": DixaEndpointConfig(
+ name="endusers",
+ path="/endusers",
+ surface="main",
+ ),
+ "queues": DixaEndpointConfig(
+ name="queues",
+ path="/queues",
+ surface="main",
+ ),
+ "tags": DixaEndpointConfig(
+ name="tags",
+ path="/tags",
+ surface="main",
+ ),
+}
+
+ENDPOINTS = tuple(DIXA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in DIXA_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/dixa/source.py b/posthog/temporal/data_imports/sources/dixa/source.py
index 56ca8c94d4df..f8b651156e57 100644
--- a/posthog/temporal/data_imports/sources/dixa/source.py
+++ b/posthog/temporal/data_imports/sources/dixa/source.py
@@ -1,29 +1,114 @@
-from typing import cast
+from typing import Optional, cast
from 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.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.dixa.dixa import (
+ DixaResumeConfig,
+ dixa_source,
+ validate_credentials as validate_dixa_credentials,
+)
+from posthog.temporal.data_imports.sources.dixa.settings import ENDPOINTS, INCREMENTAL_FIELDS
from posthog.temporal.data_imports.sources.generated_configs import DixaSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DixaSource(SimpleSource[DixaSourceConfig]):
+class DixaSource(ResumableSource[DixaSourceConfig, DixaResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DIXA
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://dev.dixa.io": "Dixa authentication failed. Please check your API token.",
+ "401 Client Error: Unauthorized for url: https://exports.dixa.io": "Dixa authentication failed. Please check your API token.",
+ "403 Client Error: Forbidden for url: https://dev.dixa.io": "Dixa denied access. Please check that your API token has the required permissions.",
+ "403 Client Error: Forbidden for url: https://exports.dixa.io": "Dixa denied access. Please check that your API token has the required permissions.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.DIXA,
label="Dixa",
+ caption="""Enter your Dixa API token to pull your Dixa customer service data into the PostHog Data warehouse.
+
+An admin can generate an API token in Dixa under Settings > Integrations > API Tokens. The same token covers both the main API (agents, queues, tags, end users) and the Exports API (conversations). Note that conversation exports are rate limited to 10 requests per minute, so large historical backfills take a while.""",
iconPath="/static/services/dixa.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/dixa",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: DixaSourceConfig,
+ 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: DixaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_dixa_credentials(config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DixaResumeConfig]:
+ return ResumableSourceManager[DixaResumeConfig](inputs, DixaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DixaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DixaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return dixa_source(
+ 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/dixa/tests/test_dixa.py b/posthog/temporal/data_imports/sources/dixa/tests/test_dixa.py
new file mode 100644
index 000000000000..6e814942dbc1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/dixa/tests/test_dixa.py
@@ -0,0 +1,301 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.dixa.dixa import (
+ EXPORT_EPOCH_MS,
+ EXPORT_WINDOW_MS,
+ DixaResumeConfig,
+ _to_ms,
+ dixa_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.dixa.settings import DIXA_ENDPOINTS, ENDPOINTS
+
+
+def _make_manager(resume_state: DixaResumeConfig | 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 _json_response(body: Any) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = body
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
[email protected](autouse=True)
+def _no_sleep():
+ with mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.time.sleep"):
+ yield
+
+
+class TestToMs:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (1700000000000, 1700000000000),
+ (1700000000000.9, 1700000000000),
+ ("1700000000000", 1700000000000),
+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000000),
+ (date(2023, 11, 15), int(datetime(2023, 11, 15, tzinfo=UTC).timestamp() * 1000)),
+ ("not-a-number", None),
+ (True, None),
+ ],
+ )
+ def test_to_ms_values(self, value, expected):
+ assert _to_ms(value) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid, expected_message",
+ [
+ (200, True, None),
+ (401, False, "Invalid Dixa API token"),
+ (403, False, "Invalid Dixa API token"),
+ # Transient failures must not be reported as an invalid token.
+ (
+ 429,
+ False,
+ "Dixa returned an unexpected response (429) while validating the API token. Please try again.",
+ ),
+ (
+ 500,
+ False,
+ "Dixa returned an unexpected response (500) while validating the API token. Please try again.",
+ ),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected_valid, expected_message):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("token") == (expected_valid, expected_message)
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_validate_credentials_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("token") == (
+ False,
+ "Could not reach Dixa to validate the API token. Please try again.",
+ )
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_validate_credentials_disables_redirects(self, mock_session):
+ response = mock.MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("token")
+
+ assert mock_session.call_args.kwargs["allow_redirects"] is False
+
+
+class TestGetRowsExport:
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_walks_time_windows_from_epoch_on_full_export(self, mock_session, mock_now):
+ # Two 30-day windows cover the configured "now".
+ mock_now.return_value = EXPORT_EPOCH_MS + EXPORT_WINDOW_MS + 1000
+ mock_session.return_value.get.side_effect = [
+ _json_response([{"id": "1", "updated_at": EXPORT_EPOCH_MS + 5}]),
+ _json_response([{"id": "2", "updated_at": EXPORT_EPOCH_MS + EXPORT_WINDOW_MS + 5}]),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "conversations", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2"]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ first_query = parse_qs(urlparse(urls[0]).query)
+ assert first_query["updated_after"] == [str(EXPORT_EPOCH_MS)]
+ assert first_query["updated_before"] == [str(EXPORT_EPOCH_MS + EXPORT_WINDOW_MS)]
+ second_query = parse_qs(urlparse(urls[1]).query)
+ assert second_query["updated_after"] == [str(EXPORT_EPOCH_MS + EXPORT_WINDOW_MS)]
+ # Window end clamps to "now".
+ assert second_query["updated_before"] == [str(EXPORT_EPOCH_MS + EXPORT_WINDOW_MS + 1000)]
+ # State saved after each window, pointing at the next window start.
+ assert [call.args[0].window_start_ms for call in manager.save_state.call_args_list] == [
+ EXPORT_EPOCH_MS + EXPORT_WINDOW_MS,
+ EXPORT_EPOCH_MS + EXPORT_WINDOW_MS + 1000,
+ ]
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.time.sleep")
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_does_not_sleep_before_first_window(self, mock_session, mock_now, mock_sleep):
+ # Two windows: no sleep before the first request, one sleep before the second.
+ mock_now.return_value = EXPORT_EPOCH_MS + EXPORT_WINDOW_MS + 1000
+ mock_session.return_value.get.side_effect = [
+ _json_response([{"id": "1", "updated_at": EXPORT_EPOCH_MS + 5}]),
+ _json_response([{"id": "2", "updated_at": EXPORT_EPOCH_MS + EXPORT_WINDOW_MS + 5}]),
+ ]
+
+ list(get_rows("token", "conversations", mock.MagicMock(), _make_manager()))
+
+ assert mock_session.return_value.get.call_count == 2
+ assert mock_sleep.call_count == 1
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_incremental_starts_from_watermark(self, mock_session, mock_now):
+ watermark = 1700000000000
+ mock_now.return_value = watermark + 1000
+ mock_session.return_value.get.return_value = _json_response([])
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "token",
+ "conversations",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["updated_after"] == [str(watermark)]
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_resumes_from_saved_window(self, mock_session, mock_now):
+ resume_start = 1700000000000
+ mock_now.return_value = resume_start + 1000
+ mock_session.return_value.get.return_value = _json_response([])
+
+ manager = _make_manager(DixaResumeConfig(window_start_ms=resume_start))
+ list(get_rows("token", "conversations", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["updated_after"] == [str(resume_start)]
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_caught_up_watermark_makes_no_requests(self, mock_session, mock_now):
+ now = 1700000000000
+ mock_now.return_value = now
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "token",
+ "conversations",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=now,
+ )
+ )
+
+ assert batches == []
+ mock_session.return_value.get.assert_not_called()
+
+
+class TestGetRowsMain:
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_paginates_via_meta_next_and_absolutizes(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _json_response({"data": [{"id": "1"}], "meta": {"next": "/v1/endusers?pageKey=abc"}}),
+ _json_response({"data": [{"id": "2"}], "meta": {}}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "endusers", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2"]
+ manager.save_state.assert_called_once()
+ saved_url = manager.save_state.call_args.args[0].next_url
+ assert saved_url == "https://dev.dixa.io/v1/endusers?pageKey=abc"
+ assert mock_session.return_value.get.call_args_list[1].args[0] == saved_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_resumes_from_saved_url(self, mock_session):
+ mock_session.return_value.get.return_value = _json_response({"data": [], "meta": {}})
+
+ resume_url = "https://dev.dixa.io/v1/endusers?pageKey=resume"
+ manager = _make_manager(DixaResumeConfig(next_url=resume_url))
+ list(get_rows("token", "endusers", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_empty_page_with_next_link_stops(self, mock_session):
+ mock_session.return_value.get.return_value = _json_response(
+ {"data": [], "meta": {"next": "/v1/endusers?pageKey=loop"}}
+ )
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "endusers", mock.MagicMock(), manager))
+
+ assert batches == []
+ assert mock_session.return_value.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_meta_next_to_foreign_host_stops_pagination(self, mock_session):
+ # An absolute meta.next pointing off-host must not receive the token.
+ mock_session.return_value.get.side_effect = [
+ _json_response({"data": [{"id": "1"}], "meta": {"next": "https://attacker.example/collect"}}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "endusers", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["1"]
+ assert mock_session.return_value.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_resume_url_on_foreign_host_falls_back_to_default(self, mock_session):
+ mock_session.return_value.get.return_value = _json_response({"data": [], "meta": {}})
+
+ manager = _make_manager(DixaResumeConfig(next_url="https://attacker.example/collect"))
+ list(get_rows("token", "endusers", mock.MagicMock(), manager))
+
+ # Falls back to the default main-host URL rather than the tampered one.
+ requested_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert urlparse(requested_url).netloc == "dev.dixa.io"
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_session_disables_redirects(self, mock_session):
+ mock_session.return_value.get.return_value = _json_response({"data": [], "meta": {}})
+
+ list(get_rows("token", "endusers", mock.MagicMock(), _make_manager()))
+
+ assert mock_session.call_args.kwargs["allow_redirects"] is False
+
+
+class TestDixaSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = DIXA_ENDPOINTS[endpoint]
+ response = dixa_source("token", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("config", list(DIXA_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key == "created_at"
diff --git a/posthog/temporal/data_imports/sources/dixa/tests/test_dixa_source.py b/posthog/temporal/data_imports/sources/dixa/tests/test_dixa_source.py
new file mode 100644
index 000000000000..df4d2bf3f5ee
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/dixa/tests/test_dixa_source.py
@@ -0,0 +1,146 @@
+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.dixa.dixa import DixaResumeConfig
+from posthog.temporal.data_imports.sources.dixa.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.dixa.source import DixaSource
+from posthog.temporal.data_imports.sources.generated_configs import DixaSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestDixaSource:
+ def setup_method(self):
+ self.source = DixaSource()
+ self.team_id = 123
+ self.config = DixaSourceConfig(api_token="api-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.DIXA
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Dixa"
+ assert config.label == "Dixa"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/dixa.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["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
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://dev.dixa.io/v1/agents",
+ "401 Client Error: Unauthorized for url: https://exports.dixa.io/v1/conversation_export",
+ "403 Client Error: Forbidden for url: https://exports.dixa.io/v1/conversation_export",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_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)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://dev.dixa.io/v1/agents",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only the exports surface has server-side updated_after filtering.
+ assert incremental == {"conversations"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["conversations"].incremental_fields == INCREMENTAL_FIELDS["conversations"]
+ assert [f["field"] for f in schemas["conversations"].incremental_fields] == ["updated_at"]
+ assert schemas["agents"].incremental_fields == []
+ assert schemas["agents"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["conversations"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "conversations"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ ((False, "Invalid Dixa API token"), False, "Invalid Dixa API token"),
+ (
+ (False, "Could not reach Dixa to validate the API token. Please try again."),
+ False,
+ "Could not reach Dixa to validate the API token. Please try again.",
+ ),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.source.validate_dixa_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_token)
+
+ 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 DixaResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.source.dixa_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_dixa_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "conversations"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000000
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_dixa_source.assert_called_once()
+ kwargs = mock_dixa_source.call_args.kwargs
+ assert kwargs["api_token"] == "api-token"
+ assert kwargs["endpoint"] == "conversations"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000000
+
+ @mock.patch("posthog.temporal.data_imports.sources.dixa.source.dixa_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_dixa_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "agents"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000000
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_dixa_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index a7e758a2cc7d..99cf2d8cf8a0 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -533,7 +533,7 @@ class DisplayVideo360SourceConfig(config.Config):
@config.config
class DixaSourceConfig(config.Config):
- pass
+ api_token: str
@config.config