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 babelforce import source (#71231)

Tom Owersf0c7716a35d8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index b765c68e683f..ce8dab58e011 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -77,6 +77,7 @@ the row lists both.
| aviator | HTTP | requests | ✅ |
| awin | HTTP | requests | ✅ |
| azure_devops | HTTP | requests | ✅ |
+| babelforce | HTTP | requests | ✅ |
| bamboohr | HTTP | requests | ✅ |
| baseten | HTTP | requests | ✅ |
| beamer | HTTP | requests | ✅ |
@@ -612,7 +613,6 @@ doesn't conflict with concurrent PRs.
- aws_cloudtrail
- azure_blob
- azure_table_storage
-- babelforce
- backblaze
- basecamp
- bigcommerce
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/babelforce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/babelforce.py
new file mode 100644
index 000000000000..0ee39e9fb9f2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/babelforce.py
@@ -0,0 +1,258 @@
+import re
+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
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.settings import (
+ BABELFORCE_ENDPOINTS,
+ BabelforceEndpointConfig,
+)
+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
+
+DEFAULT_ENVIRONMENT = "services"
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+# The environment is the babelforce subdomain the customer's account lives on (usually
+# "services", or a custom subdomain for dedicated environments). It becomes part of the
+# request host, so it must be a plain DNS label — anything else could retarget credentials.
+_ENVIRONMENT_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9-]*$")
+
+
+class BabelforceRetryableError(Exception):
+ pass
+
+
+class BabelforceResumeConfig:
+ next_page: int
+ params: dict[str, Any]
+
+
+def is_environment_valid(environment: str) -> bool:
+ return bool(_ENVIRONMENT_RE.match(environment.strip()))
+
+
+def _base_url(environment: str) -> str:
+ environment = environment.strip()
+ if not is_environment_valid(environment):
+ raise ValueError(f"Invalid babelforce environment: {environment!r}")
+ return f"https://{environment.lower()}.babelforce.com/api/v2"
+
+
+def _get_headers(access_id: str, access_token: str) -> dict[str, str]:
+ return {
+ "X-Auth-Access-Id": access_id,
+ "X-Auth-Access-Token": access_token,
+ "Accept": "application/json",
+ }
+
+
+def _make_session(access_id: str, access_token: str) -> requests.Session:
+ # The credentials ride custom `X-Auth-Access-*` headers, which the sampler's name-based
+ # auth-header denylist doesn't cover and which requests would forward on a cross-host
+ # redirect (it only strips `Authorization`), so redact them by value and pin redirects
+ # off. Responses carry customer communications (SMS bodies, phone numbers, recording
+ # URLs) the generic scrubber can't safely clean, so keep them out of sample capture.
+ return make_tracked_session(
+ redact_values=(access_id, access_token),
+ allow_redirects=False,
+ capture=False,
+ )
+
+
+def _to_epoch(value: Any) -> Optional[int]:
+ """Coerce an incremental cursor value to unix seconds for the `dateCreated.start` filter.
+
+ babelforce returns ISO-8601 date-time strings (e.g. "2020-04-16T22:21:38.000Z"), so the
+ persisted watermark is a datetime/string; ints are accepted defensively.
+ """
+ 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())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ if isinstance(value, str):
+ try:
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ try:
+ return int(value)
+ except ValueError:
+ return None
+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return int(dt.timestamp())
+ return None
+
+
+def _build_url(environment: str, path: str, params: dict[str, Any]) -> str:
+ clean_params = {key: value for key, value in params.items() if value is not None}
+ base = f"{_base_url(environment)}{path}"
+ if not clean_params:
+ return base
+ return f"{base}?{urlencode(clean_params)}"
+
+
+def _build_params(
+ config: BabelforceEndpointConfig, from_timestamp: Optional[int], to_timestamp: Optional[int]
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"max": PAGE_SIZE}
+ if config.supports_date_created_filter:
+ # Documented on the call reporting endpoint as unix-second filters. The upper bound is
+ # frozen at sync start so page contents stay stable while new calls arrive mid-sync;
+ # newer rows are picked up by the next run's window.
+ if from_timestamp is not None:
+ params["dateCreated.start"] = from_timestamp
+ if to_timestamp is not None:
+ params["dateCreated.end"] = to_timestamp
+ return params
+
+
+def validate_credentials(environment: str, access_id: str, access_token: str) -> bool:
+ """Confirm the access ID/token pair is valid with a one-row agents listing."""
+ try:
+ response = _make_session(access_id, access_token).get(
+ _build_url(environment, "/agents", {"max": 1}),
+ headers=_get_headers(access_id, access_token),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ environment: str,
+ access_id: str,
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BabelforceResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = BABELFORCE_ENDPOINTS[endpoint]
+ headers = _get_headers(access_id, access_token)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ params = resume_config.params
+ page: Optional[int] = resume_config.next_page
+ logger.debug(f"Babelforce: resuming {endpoint} from page {page}")
+ else:
+ from_timestamp = _to_epoch(db_incremental_field_last_value) if should_use_incremental_field else None
+ to_timestamp = int(time.time()) if config.supports_date_created_filter else None
+ params = _build_params(config, from_timestamp, to_timestamp)
+ # Omit `page` on the first request: the API's first-page index isn't documented, so we
+ # let the server pick it and advance from `pagination.current` in the response.
+ page = None
+
+ @retry(
+ retry=retry_if_exception_type((BabelforceRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = _make_session(access_id, access_token).get(
+ page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS
+ )
+
+ # Rate limits aren't documented publicly; back off on 429s and transient 5xx.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BabelforceRetryableError(
+ f"Babelforce API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Babelforce API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ previous_current: Optional[int] = None
+
+ while True:
+ request_params = dict(params)
+ if page is not None:
+ request_params["page"] = page
+ url = _build_url(environment, config.path, request_params)
+
+ data = fetch_page(url)
+
+ pagination = data.get("pagination") or {}
+ current = pagination.get("current")
+ pages = pagination.get("pages")
+
+ # If the API ignored our `page` param and served the same page again, stop before
+ # re-yielding it rather than looping forever.
+ if previous_current is not None and isinstance(current, int) and current <= previous_current:
+ logger.debug(f"Babelforce: page did not advance for {endpoint} (current={current}); stopping")
+ break
+
+ items = data.get("items") or []
+ if items:
+ yield items
+
+ if not items or not isinstance(current, int):
+ break
+ if isinstance(pages, int) and current >= pages:
+ break
+
+ previous_current = current
+ page = current + 1
+ resumable_source_manager.save_state(BabelforceResumeConfig(next_page=page, params=params))
+
+
+def babelforce_source(
+ environment: str,
+ access_id: str,
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BabelforceResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = BABELFORCE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ environment=environment,
+ access_id=access_id,
+ access_token=access_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],
+ # The reporting API doesn't document a sort order or expose a sort param, so we can't
+ # assume ascending arrival. "desc" makes the pipeline finalize the incremental watermark
+ # only after a fully successful sync, which is correct for any actual ordering; the
+ # server-side dateCreated window bounds what each run re-reads.
+ sort_mode="desc",
+ 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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/canonical_descriptions.py
new file mode 100644
index 000000000000..993fcd80b051
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/canonical_descriptions.py
@@ -0,0 +1,130 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://apps.babelforce.com/developer-hub/manager"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "calls": {
+ "description": "Call reporting records for every inbound and outbound call leg, including timing, state, and finish reason.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier (UUID) of the call.",
+ "parentId": "Identifier of the parent call when this call was created by another call (e.g. a transfer).",
+ "sessionId": "Identifier of the IVR session the call belongs to.",
+ "conversationId": "Identifier of the conversation the call belongs to.",
+ "dateCreated": "When the call was created.",
+ "lastUpdated": "When the call record was last updated.",
+ "dateEstablished": "When the call was answered/established.",
+ "dateFinished": "When the call finished.",
+ "state": "Current state of the call (e.g. ringing, in-progress, bridged, completed, failed).",
+ "finishReason": "Why the call ended (e.g. passive-hangup, timeout, busy, declined, transferred).",
+ "type": "Direction of the call: inbound or outbound.",
+ "from": "The calling phone number.",
+ "to": "The called phone number.",
+ "source": "The system component that created the call.",
+ "domain": "The telephony domain the call was handled on.",
+ "duration": "Total call duration in seconds.",
+ "anonymous": "Whether the caller withheld their number.",
+ "recordings": "Recordings captured during the call.",
+ "bridged": "The agent or endpoint the call was bridged to.",
+ },
+ },
+ "agents": {
+ "description": "Contact center agents, including their line state, presence, and group membership.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier (UUID) of the agent.",
+ "sourceId": "The agent's identifier in an external system (e.g. a CRM or helpdesk).",
+ "agentSource": "The external system the agent is synchronized from.",
+ "name": "Display name of the agent.",
+ "email": "Email address of the agent.",
+ "number": "Phone number calls to this agent are delivered to.",
+ "enabled": "Whether the agent is enabled.",
+ "state": "Current line status of the agent (e.g. available, busy, in-call, wrap-up).",
+ "presence": "The agent's presence information.",
+ "status": "The agent's status information.",
+ "activity": "The agent's current activity.",
+ "available": "Whether the agent is currently available to take calls.",
+ "tags": "Tags assigned to the agent.",
+ "groups": "Agent groups the agent belongs to.",
+ "webrtc": "Whether the agent uses WebRTC for calls.",
+ "dateCreated": "When the agent was created.",
+ "lastUpdated": "When the agent was last updated.",
+ },
+ },
+ "agent_groups": {
+ "description": "Groups used to organize agents for routing and reporting.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier (UUID) of the agent group.",
+ "name": "Name of the agent group.",
+ "tags": "Tags assigned to the agent group.",
+ },
+ },
+ "queues": {
+ "description": "Call queues with their dialing and wrap-up configuration.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier (UUID) of the queue.",
+ "name": "Name of the queue.",
+ "maxDialCount": "Maximum number of agents dialed in parallel.",
+ "wrapUpTime": "Wrap-up time in seconds granted to agents after a call.",
+ "defaultRingTimeout": "Default ring timeout in seconds.",
+ "maxSize": "Maximum number of waiting calls the queue accepts.",
+ "tags": "Tags assigned to the queue.",
+ },
+ },
+ "numbers": {
+ "description": "Service phone numbers configured on the account.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier (UUID) of the service number.",
+ "number": "The phone number.",
+ "sms": "Whether the number supports SMS.",
+ "enabled": "Whether the number is enabled.",
+ "tags": "Tags assigned to the number.",
+ },
+ },
+ "recordings": {
+ "description": "Call recordings and their storage state.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier (UUID) of the recording.",
+ "dateCreated": "When the recording was created.",
+ "lastUpdated": "When the recording was last updated.",
+ "duration": "Recording duration in seconds.",
+ "url": "URL to retrieve the recording.",
+ "tags": "Tags assigned to the recording.",
+ "file": "The stored file backing the recording.",
+ "state": "Storage state of the recording (e.g. stored, failed, recording, missing, stopped).",
+ "call": "The call the recording belongs to.",
+ "agent": "The agent on the recorded call.",
+ },
+ },
+ "sms": {
+ "description": "Inbound and outbound SMS messages.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the SMS message.",
+ "dateCreated": "When the message was created.",
+ "type": "Direction of the message: inbound or outbound.",
+ "from": "The sending phone number.",
+ "to": "The receiving phone number.",
+ "state": "Delivery state of the message (e.g. queued, sent, received, failed).",
+ "source": "The system component that created the message.",
+ "text": "The message body.",
+ "conversationId": "Identifier of the conversation the message belongs to.",
+ },
+ },
+ "conversations": {
+ "description": "Conversations grouping the calls and messages exchanged with a single phone number.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier (UUID) of the conversation.",
+ "dateCreated": "When the conversation was created.",
+ "state": "Current state of the conversation.",
+ "phone": "The customer phone number the conversation is with.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/settings.py
new file mode 100644
index 000000000000..2281153580a4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/settings.py
@@ -0,0 +1,75 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class BabelforceEndpointConfig:
+ name: str
+ path: str
+ primary_key: str = "id"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style
+ # field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ # Whether the endpoint accepts the `dateCreated.start` / `dateCreated.end` unix-timestamp
+ # filters documented on the Manager API's call reporting endpoint.
+ supports_date_created_filter: bool = False
+
+
+# babelforce's Manager API (https://apps.babelforce.com/developer-hub/manager) paginates every
+# list endpoint with `page` + `max` params and wraps rows as {"items": [...], "pagination": {...}}.
+# Only call reporting documents a server-side timestamp filter (`dateCreated.start`/`dateCreated.end`,
+# unix seconds), so incremental sync is enabled there and everything else is full refresh.
+BABELFORCE_ENDPOINTS: dict[str, BabelforceEndpointConfig] = {
+ "calls": BabelforceEndpointConfig(
+ name="calls",
+ path="/calls/reporting",
+ partition_key="dateCreated",
+ supports_date_created_filter=True,
+ incremental_fields=[
+ {
+ "label": "dateCreated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "dateCreated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "agents": BabelforceEndpointConfig(
+ name="agents",
+ path="/agents",
+ ),
+ "agent_groups": BabelforceEndpointConfig(
+ name="agent_groups",
+ path="/agents/groups",
+ ),
+ "queues": BabelforceEndpointConfig(
+ name="queues",
+ path="/queues",
+ ),
+ "numbers": BabelforceEndpointConfig(
+ name="numbers",
+ path="/numbers",
+ ),
+ "recordings": BabelforceEndpointConfig(
+ name="recordings",
+ path="/recordings",
+ ),
+ "sms": BabelforceEndpointConfig(
+ name="sms",
+ path="/sms",
+ partition_key="dateCreated",
+ ),
+ "conversations": BabelforceEndpointConfig(
+ name="conversations",
+ path="/conversations",
+ ),
+}
+
+ENDPOINTS = tuple(BABELFORCE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BABELFORCE_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/source.py
index 630fc516c656..876d9b3225be 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/source.py
@@ -1,30 +1,162 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce import (
+ BabelforceResumeConfig,
+ babelforce_source,
+ is_environment_valid,
+ validate_credentials as validate_babelforce_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BabelforceSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BabelforceSource(SimpleSource[BabelforceSourceConfig]):
+class BabelforceSource(ResumableSource[BabelforceSourceConfig, BabelforceResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BABELFORCE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `environment` is the babelforce subdomain the stored access token is sent to;
+ # retargeting it must re-require the token.
+ return ["environment"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Babelforce authentication failed. Please check your access ID and access token.",
+ "403 Client Error: Forbidden for url": "Babelforce denied access. Please check that your API credentials have manager permissions.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BABELFORCE,
category=DataWarehouseSourceCategory.COMMUNICATION,
label="Babelforce",
+ caption="""Enter your babelforce API credentials to pull your contact center data into the PostHog Data warehouse.
+
+You can create an access ID and access token pair in your babelforce manager app - see babelforce's [authentication guide](https://help.babelforce.com/hc/en-us/articles/6418329977108-Authentication-Best-Practice). The environment is the subdomain your account is served from - usually `services`, unless you are on a dedicated environment with a custom subdomain.""",
iconPath="/static/services/babelforce.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/babelforce",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="environment",
+ label="Environment (subdomain)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="services",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="access_id",
+ label="Access ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: BabelforceSourceConfig,
+ 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, None) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in list(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: BabelforceSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if not is_environment_valid(config.environment):
+ return False, "Babelforce environment must be a subdomain like `services`"
+
+ if validate_babelforce_credentials(config.environment, config.access_id, config.access_token):
+ return True, None
+
+ return False, "Invalid Babelforce API credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BabelforceResumeConfig]:
+ return ResumableSourceManager[BabelforceResumeConfig](inputs, BabelforceResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BabelforceSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BabelforceResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return babelforce_source(
+ environment=config.environment,
+ access_id=config.access_id,
+ access_token=config.access_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/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce.py
new file mode 100644
index 000000000000..41b2dfe67e35
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce.py
@@ -0,0 +1,298 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce import (
+ BabelforceResumeConfig,
+ _build_params,
+ _build_url,
+ _to_epoch,
+ babelforce_source,
+ get_rows,
+ is_environment_valid,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.settings import (
+ BABELFORCE_ENDPOINTS,
+ ENDPOINTS,
+)
+
+
+def _make_manager(resume_state: BabelforceResumeConfig | 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 _page(items: list[dict[str, Any]], current: Optional[int], pages: Optional[int]) -> dict[str, Any]:
+ pagination: dict[str, Any] = {"total": 0, "max": 100}
+ if current is not None:
+ pagination["current"] = current
+ if pages is not None:
+ pagination["pages"] = pages
+ return {"items": items, "pagination": pagination}
+
+
+def _mock_responses(mock_session: mock.MagicMock, pages: list[dict[str, Any]]) -> None:
+ responses = []
+ for page in pages:
+ resp = mock.MagicMock(status_code=200, ok=True)
+ resp.json.return_value = page
+ responses.append(resp)
+ mock_session.return_value.get.side_effect = responses
+
+
+class TestToEpoch:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (1700000000, 1700000000),
+ (1700000000.9, 1700000000),
+ ("1700000000", 1700000000),
+ ("2023-11-14T22:13:20.000Z", 1700000000),
+ ("2023-11-14T22:13:20+00:00", 1700000000),
+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),
+ (date(2023, 11, 15), int(datetime(2023, 11, 15, tzinfo=UTC).timestamp())),
+ ("not-a-date", None),
+ (True, None),
+ ],
+ )
+ def test_to_epoch_values(self, value, expected):
+ assert _to_epoch(value) == expected
+
+
+class TestEnvironmentValidation:
+ @pytest.mark.parametrize(
+ "environment, expected",
+ [
+ ("services", True),
+ ("us-east", True),
+ (" services ", True),
+ ("My-Env-1", True),
+ ("", False),
+ ("-leading-dash", False),
+ ("evil.example.com", False),
+ ("evil/path", False),
+ ("host:8443", False),
+ ("a b", False),
+ ],
+ )
+ def test_is_environment_valid(self, environment, expected):
+ assert is_environment_valid(environment) is expected
+
+ def test_build_url_rejects_invalid_environment(self):
+ with pytest.raises(ValueError):
+ _build_url("evil.example.com", "/agents", {})
+
+
+class TestBuildParams:
+ def test_filter_capable_endpoint_includes_window(self):
+ params = _build_params(BABELFORCE_ENDPOINTS["calls"], from_timestamp=1700000000, to_timestamp=1700000100)
+ assert params["dateCreated.start"] == 1700000000
+ assert params["dateCreated.end"] == 1700000100
+ assert params["max"] == 100
+
+ def test_full_refresh_endpoint_never_gets_window(self):
+ params = _build_params(BABELFORCE_ENDPOINTS["agents"], from_timestamp=1700000000, to_timestamp=1700000100)
+ assert "dateCreated.start" not in params
+ assert "dateCreated.end" not in params
+
+ def test_no_watermark_omits_start(self):
+ params = _build_params(BABELFORCE_ENDPOINTS["calls"], from_timestamp=None, to_timestamp=1700000100)
+ assert "dateCreated.start" not in params
+ assert params["dateCreated.end"] == 1700000100
+
+
+class TestBuildUrl:
+ def test_no_params(self):
+ assert _build_url("services", "/agents", {}) == "https://services.babelforce.com/api/v2/agents"
+
+ def test_drops_none_values_and_encodes(self):
+ url = _build_url("services", "/calls/reporting", {"max": 100, "page": None, "dateCreated.start": 1700000000})
+ assert url == "https://services.babelforce.com/api/v2/calls/reporting?max=100&dateCreated.start=1700000000"
+
+ def test_environment_becomes_subdomain(self):
+ url = _build_url("us-east", "/agents", {})
+ assert url.startswith("https://us-east.babelforce.com/")
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.make_tracked_session"
+ )
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("services", "id", "token") is expected
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.make_tracked_session"
+ )
+ def test_validate_credentials_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("services", "id", "token") is False
+
+
+class TestSessionHardening:
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.make_tracked_session"
+ )
+ def test_sessions_redact_credentials_and_disable_redirects_and_capture(self, mock_session):
+ # The token rides a custom header the sampler's denylist doesn't know and that
+ # requests would forward on a cross-host redirect; dropping any of these would
+ # leak a usable credential into HTTP samples or to a redirect target.
+ response = mock.MagicMock(status_code=200, ok=True)
+ response.json.return_value = _page([], current=1, pages=1)
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("services", "id", "token")
+ list(get_rows("services", "id", "token", "agents", mock.MagicMock(), _make_manager()))
+
+ assert len(mock_session.call_args_list) >= 2
+ for call in mock_session.call_args_list:
+ assert call.kwargs["redact_values"] == ("id", "token")
+ assert call.kwargs["allow_redirects"] is False
+ assert call.kwargs["capture"] is False
+
+
+class TestGetRows:
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.make_tracked_session"
+ )
+ def test_paginates_until_last_page(self, mock_session):
+ _mock_responses(
+ mock_session,
+ [
+ _page([{"id": "1"}, {"id": "2"}], current=1, pages=2),
+ _page([{"id": "3"}], current=2, pages=2),
+ ],
+ )
+
+ manager = _make_manager()
+ batches = list(get_rows("services", "id", "token", "agents", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2", "3"]
+ # First request omits `page` (first-page index is undocumented); second requests page 2.
+ first_url = mock_session.return_value.get.call_args_list[0].args[0]
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert "page=" not in first_url
+ assert "page=2" in second_url
+ # State is saved only while a next page exists.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].next_page == 2
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.make_tracked_session"
+ )
+ def test_resumes_from_saved_state(self, mock_session):
+ _mock_responses(mock_session, [_page([{"id": "9"}], current=5, pages=5)])
+ manager = _make_manager(BabelforceResumeConfig(next_page=5, params={"max": 100, "dateCreated.end": 1700000100}))
+
+ batches = list(get_rows("services", "id", "token", "calls", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["9"]
+ url = mock_session.return_value.get.call_args_list[0].args[0]
+ # The saved window and page are reused so the resumed run continues the same query.
+ assert "page=5" in url
+ assert "dateCreated.end=1700000100" in url
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.make_tracked_session"
+ )
+ def test_stops_without_reyielding_when_page_param_is_ignored(self, mock_session):
+ same_page = _page([{"id": "1"}], current=1, pages=3)
+ _mock_responses(mock_session, [same_page, same_page])
+
+ manager = _make_manager()
+ batches = list(get_rows("services", "id", "token", "sms", mock.MagicMock(), manager))
+
+ # The repeated page is detected and not yielded a second time.
+ assert [item["id"] for batch in batches for item in batch] == ["1"]
+ assert mock_session.return_value.get.call_count == 2
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.make_tracked_session"
+ )
+ def test_stops_when_pagination_current_missing(self, mock_session):
+ _mock_responses(mock_session, [_page([{"id": "1"}], current=None, pages=None)])
+
+ manager = _make_manager()
+ batches = list(get_rows("services", "id", "token", "agents", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["1"]
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.make_tracked_session"
+ )
+ def test_empty_response_yields_nothing(self, mock_session):
+ _mock_responses(mock_session, [_page([], current=1, pages=1)])
+
+ manager = _make_manager()
+ batches = list(get_rows("services", "id", "token", "calls", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.time")
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce.make_tracked_session"
+ )
+ def test_incremental_run_windows_the_query(self, mock_session, mock_time):
+ mock_time.time.return_value = 1700000100
+ _mock_responses(mock_session, [_page([{"id": "1"}], current=1, pages=1)])
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "services",
+ "id",
+ "token",
+ "calls",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2023-11-14T22:13:20.000Z",
+ )
+ )
+
+ url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "dateCreated.start=1700000000" in url
+ assert "dateCreated.end=1700000100" in url
+
+
+class TestBabelforceSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = BABELFORCE_ENDPOINTS[endpoint]
+ response = babelforce_source("services", "id", "token", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ # Reporting order is undocumented, so the watermark must only finalize on completion.
+ assert response.sort_mode == "desc"
+ 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", [c for c in BABELFORCE_ENDPOINTS.values() if c.partition_key])
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ assert config.partition_key == "dateCreated"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce_source.py
new file mode 100644
index 000000000000..39bb274b7f7c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/babelforce/tests/test_babelforce_source.py
@@ -0,0 +1,162 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.babelforce import (
+ BabelforceResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.source import BabelforceSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BabelforceSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestBabelforceSource:
+ def setup_method(self):
+ self.source = BabelforceSource()
+ self.team_id = 123
+ self.config = BabelforceSourceConfig(environment="services", access_id="access-id", access_token="token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BABELFORCE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Babelforce"
+ assert config.label == "Babelforce"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/babelforce.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["environment", "access_id", "access_token"]
+
+ def test_access_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 == "access_token"
+ )
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ def test_environment_is_a_connection_host_field(self):
+ # `environment` decides which host receives the stored token; changing it must force
+ # the editor to re-enter the token or the credential could be exfiltrated.
+ assert self.source.connection_host_fields == ["environment"]
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://services.babelforce.com/api/v2/calls/reporting?max=100",
+ "403 Client Error: Forbidden for url: https://us-east.babelforce.com/api/v2/agents",
+ ],
+ )
+ 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)
+
+ def test_non_retryable_errors_does_not_match_server_errors(self):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(
+ key in "500 Server Error for url: https://services.babelforce.com/api/v2/calls/reporting"
+ 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 call reporting documents a server-side dateCreated filter.
+ assert incremental == {"calls"}
+
+ 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["calls"].incremental_fields == INCREMENTAL_FIELDS["calls"]
+ 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=["calls"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "calls"
+
+ 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, True, None),
+ (False, False, "Invalid Babelforce API credentials"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.source.validate_babelforce_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.environment, self.config.access_id, self.config.access_token)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.source.validate_babelforce_credentials"
+ )
+ def test_validate_credentials_rejects_bad_environment_without_probing(self, mock_validate):
+ config = BabelforceSourceConfig(environment="evil.example.com", access_id="id", access_token="token")
+
+ is_valid, error_message = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is False
+ assert error_message is not None
+ mock_validate.assert_not_called()
+
+ 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 BabelforceResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.source.babelforce_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_babelforce_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "calls"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2023-11-14T22:13:20.000Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_babelforce_source.assert_called_once()
+ kwargs = mock_babelforce_source.call_args.kwargs
+ assert kwargs["environment"] == "services"
+ assert kwargs["access_id"] == "access-id"
+ assert kwargs["access_token"] == "token"
+ assert kwargs["endpoint"] == "calls"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2023-11-14T22:13:20.000Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.babelforce.source.babelforce_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_babelforce_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "agents"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2023-11-14T22:13:20.000Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_babelforce_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index a6449252729e..bb5629acd3d5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -495,7 +495,9 @@ class AzureTableStorageSourceConfig(config.Config):
@config.config
class BabelforceSourceConfig(config.Config):
- pass
+ environment: str
+ access_id: str
+ access_token: str
@config.config