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(warehouse-sources): add dixa team, rating, message and activity tables (#105914)

Tom Owers8c75917ca7b7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 4754cd9b1cff..4f4b78c1db29 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2546,14 +2546,14 @@ Note: `/admin/users/list/{flag}.json` is the same user records as `/admin/users.
## Dixa — gaps
-Today (5): `agents`, `conversations`, `endusers`, `queues`, `tags`
+Today (10): `agents`, `conversation_activity_log`, `conversation_messages`, `conversation_ratings`, `conversations`, `endusers`, `queues`, `tags`, `team_members`, `teams`
Diffed against: <https://docs.dixa.io/_spec/openapi/dixa-api/@v1/v1.yaml>
-- [ ] `GET /v1/conversations/{conversationId}/ratings` — CSAT ratings — Dixa's headline quality metric, absent entirely today (high)
-- [ ] `GET /v1/conversations/{conversationId}/messages` — message-level fact table under each synced conversation; needed for response-time and volume analysis (high)
-- [ ] `GET /v1/conversations/activitylog (and /v1/conversations/{id}/activitylog)` — state-transition history (assignment, status changes) driving handling-time metrics (high)
-- [ ] `GET /v1/teams and /v1/teams/{teamId}/agents` — team lookup plus agent↔team membership; agents sync today with no team dimension (high)
+- [x] `GET /v1/conversations/{conversationId}/ratings` — CSAT ratings — Dixa's headline quality metric, absent entirely today (high)
+- [x] `GET /v1/conversations/{conversationId}/messages` — message-level fact table under each synced conversation; needed for response-time and volume analysis (high)
+- [x] `GET /v1/conversations/activitylog (and /v1/conversations/{id}/activitylog)` — state-transition history (assignment, status changes) driving handling-time metrics (high)
+- [x] `GET /v1/teams and /v1/teams/{teamId}/agents` — team lookup plus agent↔team membership; agents sync today with no team dimension (high)
- [ ] `GET /v1/custom-attributes` — lookup resolving custom attribute IDs carried on conversations (medium)
- [ ] `GET /v1/conversations/flows` — lookup resolving the flow/channel ID on each conversation (medium)
- [ ] `GET /v1/conversations/{conversationId}/notes` — internal agent notes attached to synced conversations (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/canonical_descriptions.py
index c5f9e96577af..bd69290a9ebe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/canonical_descriptions.py
@@ -30,6 +30,69 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"tags": "Tags applied to the conversation.",
},
},
+ "conversation_messages": {
+ "description": "A single message exchanged in a conversation, fetched per synced conversation.",
+ "docs_url": "https://docs.dixa.io/openapi/dixa-api/v1/tag/Messages/",
+ "columns": {
+ "id": "Unique identifier for the message.",
+ "conversation_id": "Identifier of the conversation the message belongs to.",
+ "conversation_updated_at": "Time at which the parent conversation was last updated, as a Unix timestamp (ms).",
+ "authorId": "Identifier of the agent or end user who wrote the message.",
+ "externalId": "Identifier the message carries in the originating system, when it has one.",
+ "createdAt": "Time at which the message was created.",
+ "attributes": "Channel-specific payload of the message, including its content, direction and attachments.",
+ },
+ },
+ "conversation_ratings": {
+ "description": "A satisfaction survey response or offer for a conversation. A survey with several questions returns one row per question, all sharing the same rating id.",
+ "docs_url": "https://docs.dixa.io/openapi/dixa-api/v1/tag/Ratings/",
+ "columns": {
+ "id": "Identifier of the survey the rating belongs to. Shared by every question of the same survey.",
+ "conversation_id": "Identifier of the conversation that was rated.",
+ "conversation_updated_at": "Time at which the parent conversation was last updated, as a Unix timestamp (ms).",
+ "ratingScore": "Score the end user gave, absent while the rating is only offered.",
+ "ratingType": "Type of the rating question (Csat, Nps or ThumbsUpOrDown).",
+ "ratingComment": "Free-text comment the end user left with the rating.",
+ "conversationChannel": "Channel the rated conversation came through.",
+ "agentId": "Identifier of the agent the rating is attributed to.",
+ "userId": "Identifier of the end user the survey was sent to.",
+ "ratingStatus": "Status of the rating (Unscheduled, Offered, Rated, Scheduled or Cancelled).",
+ "language": "Language the survey was presented in.",
+ "timestamps": "Times at which the rating was created, scheduled, offered and last modified.",
+ },
+ },
+ "conversation_activity_log": {
+ "description": "A state change on a conversation — assignment, status change, transfer, tagging — across the whole organization.",
+ "docs_url": "https://docs.dixa.io/openapi/dixa-api/v1/tag/Conversations/",
+ "columns": {
+ "id": "Unique identifier for the activity log entry.",
+ "conversationId": "Identifier of the conversation the activity happened on.",
+ "activityTimestamp": "Time at which the activity happened.",
+ "activityType": "Deprecated activity type name.",
+ "_type": "Type of the activity, for example ConversationAssigned or ConversationClosed.",
+ "author": "Agent or end user who caused the activity.",
+ "attributes": "Activity-specific detail, for example the queue a conversation was transferred to.",
+ },
+ },
+ "teams": {
+ "description": "A team that agents are grouped into.",
+ "docs_url": "https://docs.dixa.io/openapi/dixa-api/v1/tag/Teams/",
+ "columns": {
+ "id": "Unique identifier for the team.",
+ "name": "Name of the team.",
+ },
+ },
+ "team_members": {
+ "description": "Membership of an agent or admin in a team. One row per agent per team.",
+ "docs_url": "https://docs.dixa.io/openapi/dixa-api/v1/tag/Teams/",
+ "columns": {
+ "team_id": "Identifier of the team the member belongs to.",
+ "id": "Identifier of the agent or admin.",
+ "name": "Name of the agent or admin.",
+ "email": "Email address of the agent or admin.",
+ "phoneNumber": "Phone number of the agent or admin.",
+ },
+ },
"agents": {
"description": "An agent (team member) in the Dixa account.",
"docs_url": "https://docs.dixa.io/openapi/dixa-api/v1/tag/Agents/",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/dixa.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/dixa.py
index f51a7f5bd727..f98a64f0bd46 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/dixa.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/dixa.py
@@ -1,18 +1,24 @@
+import re
import time
-import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
-from urllib.parse import urlencode, urljoin, urlparse
+from urllib.parse import quote, 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.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.dixa.settings import DIXA_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.dixa.settings import (
+ DIXA_ENDPOINTS,
+ DixaEndpointConfig,
+ DixaFanoutConfig,
+)
DIXA_MAIN_BASE_URL = "https://dev.dixa.io/v1"
DIXA_EXPORT_BASE_URL = "https://exports.dixa.io/v1"
@@ -28,16 +34,21 @@ EXPORT_EPOCH_MS = int(datetime(2015, 1, 1, tzinfo=UTC).timestamp() * 1000)
EXPORT_REQUEST_INTERVAL_SECONDS = 6.5
REQUEST_TIMEOUT_SECONDS = 120
MAX_RETRY_ATTEMPTS = 5
+# Dixa serialises some date-times as `2021-12-01T12:46:36.581Z[GMT]`; the trailing zone id
+# keeps the value from parsing as a timestamp, so it is dropped before the row is yielded.
+_ZONE_ID_SUFFIX = re.compile(r"\[[^\]]+\]$")
class DixaRetryableError(Exception):
pass
+@frozen
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.
+ # API streams persist the opaque next-page URL from meta.next. A fan-out
+ # stream persists its parent walk's position in whichever of the two forms
+ # the parent endpoint uses.
window_start_ms: Optional[int] = None
next_url: Optional[str] = None
@@ -75,6 +86,36 @@ def _to_ms(value: Any) -> Optional[int]:
return None
+def _strip_zone_id(value: Any) -> Any:
+ if isinstance(value, str):
+ return _ZONE_ID_SUFFIX.sub("", value)
+ return value
+
+
+def _normalize_datetime_fields(items: list[dict[str, Any]], fields: tuple[str, ...]) -> list[dict[str, Any]]:
+ if not fields:
+ return items
+ for item in items:
+ for field_name in fields:
+ if field_name in item:
+ item[field_name] = _strip_zone_id(item[field_name])
+ return items
+
+
+def _to_iso8601_ms(value: Any) -> Optional[str]:
+ """Render an incremental cursor value in the `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'` form Dixa's
+ date-time query params take."""
+ if isinstance(value, str):
+ try:
+ value = datetime.fromisoformat(_strip_zone_id(value).replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if not isinstance(value, datetime):
+ return None
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return f"{dt.strftime('%Y-%m-%dT%H:%M:%S')}.{dt.microsecond // 1000:03d}Z"
+
+
def _now_ms() -> int:
return int(datetime.now(UTC).timestamp() * 1000)
@@ -105,6 +146,152 @@ def validate_credentials(api_token: str) -> tuple[bool, Optional[str]]:
)
+def _export_start_ms(
+ resume_config: Optional[DixaResumeConfig],
+ logger: FilteringBoundLogger,
+ endpoint: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> int:
+ if resume_config is not None and resume_config.window_start_ms is not None:
+ logger.debug(f"Dixa: resuming {endpoint} from window start {resume_config.window_start_ms}")
+ return resume_config.window_start_ms
+ if should_use_incremental_field:
+ return _to_ms(db_incremental_field_last_value) or EXPORT_EPOCH_MS
+ return EXPORT_EPOCH_MS
+
+
+def _iter_export_windows(
+ fetch: Callable[..., Any], config: DixaEndpointConfig, window_start: int
+) -> Iterator[tuple[list[dict[str, Any]], int]]:
+ """Walk the Exports API forward in windows, yielding each window's rows and its end.
+
+ The Exports API takes a mandatory time window (max 31 days) and returns the whole window
+ as one JSON array.
+ """
+ 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)}")
+ yield (data if isinstance(data, list) else []), window_end
+ window_start = window_end
+
+
+def _iter_main_pages(
+ fetch: Callable[..., Any], logger: FilteringBoundLogger, start_url: str
+) -> Iterator[tuple[list[dict[str, Any]], Optional[str]]]:
+ """Follow `meta.next` from the main API, yielding each page and the URL after it."""
+ url = start_url
+ while True:
+ data = fetch(url)
+ items = (data.get("data", []) if isinstance(data, dict) else []) or []
+ next_link = (data.get("meta") or {}).get("next") if isinstance(data, dict) else None
+
+ next_url: Optional[str] = None
+ if next_link and items:
+ # meta.next can be a relative path; absolutize against the main host.
+ candidate = 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 _is_dixa_main_host(candidate):
+ next_url = candidate
+ else:
+ logger.warning(f"Dixa: meta.next resolved to unexpected host, stopping pagination: {candidate}")
+
+ yield items, next_url
+
+ if next_url is None:
+ return
+ url = next_url
+
+
+def _main_start_url(
+ config: DixaEndpointConfig,
+ resume_config: Optional[DixaResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> str:
+ if resume_config is not None and resume_config.next_url is not None and _is_dixa_main_host(resume_config.next_url):
+ logger.debug(f"Dixa: resuming {config.name} from URL: {resume_config.next_url}")
+ return resume_config.next_url
+
+ url = f"{DIXA_MAIN_BASE_URL}{config.path}"
+ if config.incremental_param and should_use_incremental_field:
+ watermark = _to_iso8601_ms(db_incremental_field_last_value)
+ if watermark is not None:
+ url = f"{url}?{urlencode({config.incremental_param: watermark})}"
+ return url
+
+
+def _iter_fanout_parents(
+ fetch: Callable[..., Any],
+ parent: DixaEndpointConfig,
+ resume_config: Optional[DixaResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[tuple[list[dict[str, Any]], Optional[DixaResumeConfig]]]:
+ """Yield batches of parent rows with the state to persist once their children are done."""
+ if parent.surface == "export":
+ window_start = _export_start_ms(
+ resume_config, logger, parent.name, should_use_incremental_field, db_incremental_field_last_value
+ )
+ for items, window_end in _iter_export_windows(fetch, parent, window_start):
+ yield items, DixaResumeConfig(window_start_ms=window_end)
+ return
+
+ # A main-surface parent has no time filter of its own, so its walk is never windowed by the
+ # child's watermark — only the Exports API can bound the parent set server-side.
+ start_url = _main_start_url(parent, resume_config, logger, False, None)
+ for items, next_url in _iter_main_pages(fetch, logger, start_url):
+ yield items, DixaResumeConfig(next_url=next_url) if next_url else None
+
+
+def _fan_out_rows(
+ fetch: Callable[..., Any],
+ fetch_child: Callable[..., Any],
+ config: DixaEndpointConfig,
+ fanout: DixaFanoutConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DixaResumeConfig],
+ resume_config: Optional[DixaResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ parent = DIXA_ENDPOINTS[fanout.parent]
+
+ for parent_rows, next_state in _iter_fanout_parents(
+ fetch, parent, resume_config, logger, should_use_incremental_field, db_incremental_field_last_value
+ ):
+ for parent_row in parent_rows:
+ parent_id = parent_row.get(fanout.parent_id_field)
+ if parent_id is None:
+ continue
+
+ injected: dict[str, Any] = {fanout.child_key: parent_id}
+ if fanout.parent_cursor_field and fanout.child_cursor_key:
+ injected[fanout.child_cursor_key] = parent_row.get(fanout.parent_cursor_field)
+
+ child_url = f"{DIXA_MAIN_BASE_URL}{config.path.format(quote(str(parent_id), safe=''))}"
+ for items, _ in _iter_main_pages(fetch_child, logger, child_url):
+ if not items:
+ continue
+ rows = [{**item, **injected} for item in items]
+ yield _normalize_datetime_fields(rows, config.datetime_fields)
+
+ if next_state is not None:
+ resumable_source_manager.save_state(next_state)
+
+
def get_rows(
api_token: str,
endpoint: str,
@@ -122,12 +309,18 @@ def get_rows(
wait=wait_exponential_jitter(initial=5, max=120),
reraise=True,
)
- def fetch(url: str) -> Any:
+ def fetch(url: str, allow_missing: bool = False) -> 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}")
+ # A parent listed earlier in the run can be deleted or anonymized before we reach its
+ # children; skip it rather than failing the whole sync.
+ if allow_missing and response.status_code == 404:
+ logger.debug(f"Dixa: skipping missing resource: {url}")
+ return None
+
if not response.ok:
logger.error(f"Dixa API error: status={response.status_code}, body={response.text}, url={url}")
response.raise_for_status()
@@ -136,68 +329,44 @@ def get_rows(
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 config.fanout is not None:
+
+ def fetch_child(url: str) -> Any:
+ return fetch(url, allow_missing=True) or {}
+
+ yield from _fan_out_rows(
+ fetch,
+ fetch_child,
+ config,
+ config.fanout,
+ logger,
+ resumable_source_manager,
+ resume_config,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ return
+ if config.surface == "export":
+ window_start = _export_start_ms(
+ resume_config, logger, endpoint, should_use_incremental_field, db_incremental_field_last_value
+ )
+ for items, window_end in _iter_export_windows(fetch, config, window_start):
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))
+ resumable_source_manager.save_state(DixaResumeConfig(window_start_ms=window_end))
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 []
-
+ start_url = _main_start_url(
+ config, resume_config, logger, should_use_incremental_field, db_incremental_field_last_value
+ )
+ for items, next_url in _iter_main_pages(fetch, logger, start_url):
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
+ yield _normalize_datetime_fields(items, config.datetime_fields)
+ if next_url is not None:
+ resumable_source_manager.save_state(DixaResumeConfig(next_url=next_url))
def dixa_source(
@@ -220,7 +389,7 @@ def dixa_source(
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
),
- primary_keys=[config.primary_key],
+ primary_keys=list(config.primary_key),
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/settings.py
index a6e0dccc039e..1a3e7aa33282 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/settings.py
@@ -1,10 +1,26 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@frozen
+class DixaFanoutConfig:
+ """Wiring for a child endpoint fetched once per row of a parent endpoint."""
+
+ parent: str
+ # Field on the parent row that fills the child path placeholder.
+ parent_id_field: str
+ # Column the parent id is injected as on every child row.
+ child_key: str
+ # Parent field carried onto each child row to act as the child's incremental cursor.
+ parent_cursor_field: Optional[str] = None
+ child_cursor_key: Optional[str] = None
+
+
+@frozen
class DixaEndpointConfig:
name: str
path: str
@@ -12,10 +28,38 @@ class DixaEndpointConfig:
# 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"
+ primary_key: list[str] = field(default_factory=lambda: ["id"])
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Stable creation-time field used for datetime partitioning (Unix ms).
partition_key: Optional[str] = None
+ fanout: Optional[DixaFanoutConfig] = None
+ # Main-surface query param carrying the incremental watermark, when the
+ # endpoint has a server-side time filter of its own.
+ incremental_param: Optional[str] = None
+ # Fields Dixa serialises as `2021-12-01T12:46:36.581Z[GMT]` — the trailing
+ # zone id is stripped so the column lands as a real timestamp.
+ datetime_fields: tuple[str, ...] = ()
+
+
+CONVERSATION_FANOUT = DixaFanoutConfig(
+ parent="conversations",
+ parent_id_field="id",
+ child_key="conversation_id",
+ parent_cursor_field="updated_at",
+ child_cursor_key="conversation_updated_at",
+)
+
+# Fan-out children inherit the parent conversation's `updated_at` as their cursor: it is the
+# value the Exports API filters on, so an incremental run only re-fetches conversations that
+# changed since the last sync.
+CONVERSATION_FANOUT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "conversation_updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "conversation_updated_at",
+ "field_type": IncrementalFieldType.Integer,
+ },
+]
DIXA_ENDPOINTS: dict[str, DixaEndpointConfig] = {
@@ -33,6 +77,40 @@ DIXA_ENDPOINTS: dict[str, DixaEndpointConfig] = {
},
],
),
+ "conversation_messages": DixaEndpointConfig(
+ name="conversation_messages",
+ path="/conversations/{}/messages",
+ surface="main",
+ primary_key=["conversation_id", "id"],
+ fanout=CONVERSATION_FANOUT,
+ incremental_fields=CONVERSATION_FANOUT_INCREMENTAL_FIELDS,
+ datetime_fields=("createdAt",),
+ ),
+ "conversation_ratings": DixaEndpointConfig(
+ name="conversation_ratings",
+ path="/conversations/{}/ratings",
+ surface="main",
+ # A multi-question survey returns one row per question, all sharing the survey id, so
+ # the rating type is part of what makes a row unique.
+ primary_key=["conversation_id", "id", "ratingType"],
+ fanout=CONVERSATION_FANOUT,
+ incremental_fields=CONVERSATION_FANOUT_INCREMENTAL_FIELDS,
+ ),
+ "conversation_activity_log": DixaEndpointConfig(
+ name="conversation_activity_log",
+ path="/conversations/activitylog",
+ surface="main",
+ incremental_param="fromDatetime",
+ incremental_fields=[
+ {
+ "label": "activityTimestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "activityTimestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ datetime_fields=("activityTimestamp",),
+ ),
"agents": DixaEndpointConfig(
name="agents",
path="/agents",
@@ -53,6 +131,18 @@ DIXA_ENDPOINTS: dict[str, DixaEndpointConfig] = {
path="/tags",
surface="main",
),
+ "teams": DixaEndpointConfig(
+ name="teams",
+ path="/teams",
+ surface="main",
+ ),
+ "team_members": DixaEndpointConfig(
+ name="team_members",
+ path="/teams/{}/agents",
+ surface="main",
+ primary_key=["team_id", "id"],
+ fanout=DixaFanoutConfig(parent="teams", parent_id_field="id", child_key="team_id"),
+ ),
}
ENDPOINTS = tuple(DIXA_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/tests/test_dixa.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/tests/test_dixa.py
index 6a6b13c487ca..0fa2dcc9aa21 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/tests/test_dixa.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/tests/test_dixa.py
@@ -9,6 +9,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa
EXPORT_EPOCH_MS,
EXPORT_WINDOW_MS,
DixaResumeConfig,
+ _to_iso8601_ms,
_to_ms,
dixa_source,
get_rows,
@@ -24,11 +25,11 @@ def _make_manager(resume_state: DixaResumeConfig | None = None) -> mock.MagicMoc
return manager
-def _json_response(body: Any) -> mock.MagicMock:
+def _json_response(body: Any, status_code: int = 200) -> mock.MagicMock:
resp = mock.MagicMock()
resp.json.return_value = body
- resp.status_code = 200
- resp.ok = True
+ resp.status_code = status_code
+ resp.ok = status_code < 400
return resp
@@ -286,7 +287,7 @@ class TestDixaSourceResponse:
response = dixa_source("token", endpoint, mock.MagicMock(), _make_manager())
assert response.name == endpoint
- assert response.primary_keys == [config.primary_key]
+ assert response.primary_keys == config.primary_key
assert response.sort_mode == "asc"
if config.partition_key:
assert response.partition_mode == "datetime"
@@ -299,3 +300,186 @@ class TestDixaSourceResponse:
def test_partition_keys_are_stable_creation_fields(self, config):
if config.partition_key:
assert config.partition_key == "created_at"
+
+
+class TestToIso8601Ms:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2021, 12, 1, 12, 46, 36, 581000, tzinfo=UTC), "2021-12-01T12:46:36.581Z"),
+ # Dixa echoes back its own `...Z[GMT]` serialisation; it must still round-trip.
+ ("2021-12-01T12:46:36.581Z[GMT]", "2021-12-01T12:46:36.581Z"),
+ ("2021-12-01T12:46:36.581Z", "2021-12-01T12:46:36.581Z"),
+ # Naive values are read as UTC rather than dropped.
+ (datetime(2021, 12, 1, 12, 46, 36, 581000), "2021-12-01T12:46:36.581Z"),
+ (None, None),
+ ("not-a-timestamp", None),
+ (1700000000000, None),
+ ],
+ )
+ def test_to_iso8601_ms_values(self, value, expected):
+ assert _to_iso8601_ms(value) == expected
+
+
+class TestActivityLog:
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_incremental_sends_from_datetime_and_strips_zone_id(self, mock_session):
+ mock_session.return_value.get.return_value = _json_response(
+ {"data": [{"id": "a", "activityTimestamp": "2021-12-02T09:00:00.000Z[GMT]"}], "meta": {}}
+ )
+
+ batches = list(
+ get_rows(
+ "token",
+ "conversation_activity_log",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2021, 12, 1, 12, 46, 36, 581000, tzinfo=UTC),
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["fromDatetime"] == ["2021-12-01T12:46:36.581Z"]
+ # The trailing zone id would stop the column parsing as a timestamp.
+ assert batches[0][0]["activityTimestamp"] == "2021-12-02T09:00:00.000Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_full_refresh_omits_the_watermark(self, mock_session):
+ mock_session.return_value.get.return_value = _json_response({"data": [], "meta": {}})
+
+ list(
+ get_rows(
+ "token",
+ "conversation_activity_log",
+ mock.MagicMock(),
+ _make_manager(),
+ db_incremental_field_last_value=datetime(2021, 12, 1, tzinfo=UTC),
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert urlparse(url).query == ""
+
+
+class TestFanOutOverConversations:
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_injects_parent_id_and_cursor_onto_child_rows(self, mock_session, mock_now):
+ mock_now.return_value = EXPORT_EPOCH_MS + 1000
+ mock_session.return_value.get.side_effect = [
+ _json_response([{"id": 1, "updated_at": 1700000000000}, {"id": 2, "updated_at": 1700000000005}]),
+ _json_response({"data": [{"id": "m1", "createdAt": "2021-12-01T12:46:36.581Z[GMT]"}]}),
+ _json_response({"data": [{"id": "m2", "createdAt": "2021-12-02T12:46:36.581Z[GMT]"}]}),
+ ]
+
+ batches = list(get_rows("token", "conversation_messages", mock.MagicMock(), _make_manager()))
+ rows = [row for batch in batches for row in batch]
+
+ assert [(row["id"], row["conversation_id"], row["conversation_updated_at"]) for row in rows] == [
+ ("m1", 1, 1700000000000),
+ ("m2", 2, 1700000000005),
+ ]
+ assert rows[0]["createdAt"] == "2021-12-01T12:46:36.581Z"
+ child_urls = [call.args[0] for call in mock_session.return_value.get.call_args_list[1:]]
+ assert child_urls == [
+ "https://dev.dixa.io/v1/conversations/1/messages",
+ "https://dev.dixa.io/v1/conversations/2/messages",
+ ]
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_incremental_bounds_the_parent_walk_to_the_watermark(self, mock_session, mock_now):
+ watermark = 1700000000000
+ mock_now.return_value = watermark + 1000
+ mock_session.return_value.get.return_value = _json_response([])
+
+ list(
+ get_rows(
+ "token",
+ "conversation_ratings",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+
+ # Only the export parent walk runs, and it starts at the child watermark.
+ assert mock_session.return_value.get.call_count == 1
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["updated_after"] == [str(watermark)]
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_state_saved_once_a_parent_window_is_fully_fanned_out(self, mock_session, mock_now):
+ mock_now.return_value = EXPORT_EPOCH_MS + 1000
+ mock_session.return_value.get.side_effect = [
+ _json_response([{"id": 1, "updated_at": 1700000000000}]),
+ _json_response({"data": [{"id": "m1"}]}),
+ ]
+
+ manager = _make_manager()
+ list(get_rows("token", "conversation_messages", mock.MagicMock(), manager))
+
+ assert [call.args[0].window_start_ms for call in manager.save_state.call_args_list] == [EXPORT_EPOCH_MS + 1000]
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_resumes_the_parent_walk_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", "conversation_messages", 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("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa._now_ms")
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_deleted_conversation_is_skipped_not_fatal(self, mock_session, mock_now):
+ mock_now.return_value = EXPORT_EPOCH_MS + 1000
+ mock_session.return_value.get.side_effect = [
+ _json_response([{"id": 1, "updated_at": 1}, {"id": 2, "updated_at": 2}]),
+ _json_response({"message": "The requested resource could not be found"}, status_code=404),
+ _json_response({"data": [{"id": "m2"}]}),
+ ]
+
+ batches = list(get_rows("token", "conversation_messages", mock.MagicMock(), _make_manager()))
+
+ assert [row["id"] for batch in batches for row in batch] == ["m2"]
+
+
+class TestFanOutOverTeams:
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_team_members_carry_their_team_id(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _json_response({"data": [{"id": "team-a", "name": "Team A"}], "meta": {}}),
+ _json_response({"data": [{"id": "agent-1", "email": "[email protected]"}]}),
+ ]
+
+ batches = list(get_rows("token", "team_members", mock.MagicMock(), _make_manager()))
+ rows = [row for batch in batches for row in batch]
+
+ assert rows == [{"id": "agent-1", "email": "[email protected]", "team_id": "team-a"}]
+ assert mock_session.return_value.get.call_args_list[1].args[0] == "https://dev.dixa.io/v1/teams/team-a/agents"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dixa.dixa.make_tracked_session")
+ def test_parent_pages_are_walked_before_the_next_page(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _json_response({"data": [{"id": "team-a"}], "meta": {"next": "/v1/teams?pageKey=abc"}}),
+ _json_response({"data": [{"id": "agent-1"}]}),
+ _json_response({"data": [{"id": "team-b"}], "meta": {}}),
+ _json_response({"data": [{"id": "agent-2"}]}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "team_members", mock.MagicMock(), manager))
+
+ assert [row["team_id"] for batch in batches for row in batch] == ["team-a", "team-b"]
+ # The parent cursor is only persisted once its page's children have been yielded.
+ assert [call.args[0].next_url for call in manager.save_state.call_args_list] == [
+ "https://dev.dixa.io/v1/teams?pageKey=abc"
+ ]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/tests/test_dixa_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/tests/test_dixa_source.py
index cb9ffacc2eeb..5c24a67d2603 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/tests/test_dixa_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dixa/tests/test_dixa_source.py
@@ -39,5 +39,12 @@ class TestDixaSource:
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"}
+ # Everything incremental is filtered server-side: the exports surface by updated_after
+ # (directly, or via the parent walk a fan-out child rides), the activity log by
+ # fromDatetime. The plain main-API lookups have no time filter at all.
+ assert incremental == {
+ "conversations",
+ "conversation_messages",
+ "conversation_ratings",
+ "conversation_activity_log",
+ }