:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement hellobaton import source (#67796)
Tom Owerscaed11b5bf6a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 434818ced74b..8c53c68c66bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -169,6 +169,7 @@ the row lists both.| greenhouse | HTTP | requests | ✅ || guardian | HTTP | requests | ✅ || guru | HTTP | requests | ✅ |+| hellobaton | HTTP | requests | ✅ || hibob | HTTP | requests | ✅ || hubspot | HTTP | requests | ✅ || hugging_face | HTTP | requests | ✅ |@@ -444,7 +445,6 @@ doesn't conflict with concurrent PRs.- harness- heap- height-- hellobaton- helpscout- hibob- high_leveldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 2790d053fc4f..bd153c77ec9a 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@@ -1514,7 +1514,8 @@ class HeightSourceConfig(config.Config):@config.configclass HellobatonSourceConfig(config.Config):- pass+ company: str+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/canonical_descriptions.pynew file mode 100644index 000000000000..3203627836ec--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/canonical_descriptions.py@@ -0,0 +1,210 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://app.hellobaton.com/api/redoc/"++# Descriptions sourced from Baton's (Hellobaton's) API reference and the tap-hellobaton schemas.+# Baton is a customer onboarding / implementation-management platform: projects run through phases+# and milestones, work is tracked as tasks with time entries, and companies/users are the actors.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "activity": {+ "description": "Audit-log style activity events recording changes to Baton objects (who did what to which record).",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the activity event.",+ "type": "The kind of activity that occurred.",+ "group": "Grouping key that ties related activity events together.",+ "parent": "Identifier of the parent object the activity relates to.",+ "child": "Identifier of the child object the activity relates to.",+ "actor": "User who performed the activity.",+ "project": "Project the activity belongs to.",+ "parent_type": "Object type of the parent record.",+ "child_type": "Object type of the child record.",+ "meta": "Additional structured metadata about the event.",+ "created": "Timestamp when the activity event was recorded.",+ "modified": "Timestamp when the activity event was last modified.",+ },+ },+ "companies": {+ "description": "Companies (customer accounts) tracked in Baton.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the company.",+ "name": "Company name.",+ "type": "Company classification/type.",+ "created": "Timestamp when the company was created.",+ "modified": "Timestamp when the company was last modified.",+ },+ },+ "milestones": {+ "description": "Milestones within a project — grouped deliverables with a target completion date.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the milestone.",+ "title": "Milestone title.",+ "description": "Milestone description.",+ "project": "Project this milestone belongs to.",+ "task_list": "Identifiers of tasks that make up the milestone.",+ "phase": "Phase this milestone is part of.",+ "deadline_fixed": "Whether the milestone deadline is fixed.",+ "deadline_datetime": "Target completion date/time for the milestone.",+ "risk_profiles": "Risk profiles associated with the milestone.",+ "start_datetime": "When work on the milestone starts.",+ "finish_datetime": "When the milestone is expected to finish.",+ "created_from": "Source object the milestone was created from.",+ "duration": "Estimated duration of the milestone.",+ "created": "Timestamp when the milestone was created.",+ "modified": "Timestamp when the milestone was last modified.",+ },+ },+ "phases": {+ "description": "Phases that projects move through during an implementation.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the phase.",+ "name": "Phase name.",+ "order": "Ordinal position of the phase in the sequence.",+ "created": "Timestamp when the phase was created.",+ "modified": "Timestamp when the phase was last modified.",+ },+ },+ "projects": {+ "description": "Onboarding/implementation projects — the central object in Baton.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the project.",+ "title": "Project title.",+ "status": "Current status of the project.",+ "phase": "Current phase the project is in.",+ "companies": "Companies associated with the project.",+ "creator": "User who created the project.",+ "annual_contract_value": "Annual contract value tied to the project.",+ "cost": "Cost associated with the project.",+ "implementation_budget": "Budgeted implementation effort for the project.",+ "estimated_duration": "Estimated duration of the project.",+ "archived": "Whether the project is archived.",+ "created_from_template": "Template the project was created from.",+ "milestone_list": "Identifiers of the project's milestones.",+ "task_list": "Identifiers of the project's tasks.",+ "time_entry_list": "Identifiers of the project's time entries.",+ "start_datetime": "Planned start date/time of the project.",+ "started_datetime": "Actual start date/time of the project.",+ "deadline_datetime": "Target completion date/time of the project.",+ "completed_datetime": "When the project was completed.",+ "created": "Timestamp when the project was created.",+ "modified": "Timestamp when the project was last modified.",+ },+ },+ "project_attachments": {+ "description": "Files attached to projects.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the attachment.",+ "project": "Project the file is attached to.",+ "url": "Download URL of the attachment.",+ "label": "Display label for the attachment.",+ "type": "Type of the attachment.",+ "is_sow": "Whether the attachment is a statement of work.",+ "original_filename": "Original filename of the uploaded file.",+ "created_by": "User who uploaded the attachment.",+ "created": "Timestamp when the attachment was created.",+ "modified": "Timestamp when the attachment was last modified.",+ },+ },+ "tasks": {+ "description": "Tasks — the unit of work within a project, grouped under milestones.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the task.",+ "title": "Task title.",+ "description": "Task description.",+ "project": "Project the task belongs to.",+ "milestone": "Milestone the task belongs to.",+ "status": "Current status of the task.",+ "dependencies": "Other tasks this task depends on.",+ "created_by": "User who created the task.",+ "assigned_to": "User the task is assigned to.",+ "estimated_duration": "Estimated duration of the task.",+ "start_datetime": "Planned start date/time of the task.",+ "due_datetime": "Due date/time of the task.",+ "started_datetime": "Actual start date/time of the task.",+ "finished_datetime": "When the task was finished.",+ "time_entry_list": "Identifiers of time entries logged against the task.",+ "attachment_list": "Identifiers of files attached to the task.",+ "created": "Timestamp when the task was created.",+ "modified": "Timestamp when the task was last modified.",+ },+ },+ "task_attachments": {+ "description": "Files attached to tasks, including deliverables that may require approval.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the attachment.",+ "task": "Task the file is attached to.",+ "url": "Download URL of the attachment.",+ "label": "Display label for the attachment.",+ "type": "Type of the attachment.",+ "deliverable": "Whether the attachment is a deliverable.",+ "requires_approval": "Whether the attachment requires approval.",+ "approved": "Whether the attachment has been approved.",+ "original_filename": "Original filename of the uploaded file.",+ "created_by": "User who uploaded the attachment.",+ "created": "Timestamp when the attachment was created.",+ "modified": "Timestamp when the attachment was last modified.",+ },+ },+ "templates": {+ "description": "Project templates used to spin up new implementation projects.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the template.",+ "title": "Template title.",+ "status": "Status of the template.",+ "cost": "Default cost for projects created from the template.",+ "annual_contract_value": "Default annual contract value for the template.",+ "implementation_budget": "Default implementation budget for the template.",+ "estimated_duration": "Default estimated duration for the template.",+ "phase": "Default phase for projects created from the template.",+ "creator": "User who created the template.",+ "task_list": "Identifiers of the template's tasks.",+ },+ },+ "time_entries": {+ "description": "Time logged by users against projects and tasks.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the time entry.",+ "user": "User the time is logged for.",+ "created_by": "User who created the time entry.",+ "project": "Project the time is logged against.",+ "task": "Task the time is logged against.",+ "rate": "Billing rate for the time entry.",+ "started_at": "When the tracked time started.",+ "ended_at": "When the tracked time ended.",+ "reference_date": "The date the time entry applies to.",+ "billable": "Whether the time entry is billable.",+ "calculated_duration": "Duration calculated from start/end times.",+ "inputted_duration": "Duration entered manually by the user.",+ "notes": "Free-text notes on the time entry.",+ },+ },+ "users": {+ "description": "Users in the Baton account — both internal team members and customer contacts.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the user.",+ "first_name": "User's first name.",+ "last_name": "User's last name.",+ "email": "User's email address.",+ "account_type": "The user's account type.",+ "job_title": "User's job title.",+ "company": "Company the user belongs to.",+ "avatar_url": "URL of the user's avatar image.",+ "created_by": "User who created this user record.",+ "signed_up_at": "When the user signed up.",+ "created": "Timestamp when the user was created.",+ "modified": "Timestamp when the user was last modified.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/hellobaton.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/hellobaton.pynew file mode 100644index 000000000000..f9c5d0ec8626--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/hellobaton.py@@ -0,0 +1,188 @@+import re+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode, urlsplit, urlunsplit++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.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.hellobaton.settings import (+ HELLOBATON_ENDPOINTS,+ PER_PAGE,+ HellobatonEndpointConfig,+)++HELLOBATON_API_PATH = "/api"++# A single DNS label: letters, digits, hyphens. Rejects anything that could retarget the host+# (slashes, `@`, dots) so the stored API key is only ever sent to `<company>.hellobaton.com`.+_COMPANY_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")+++class HellobatonRetryableError(Exception):+ pass+++class HellobatonResumeConfig:+ # Next 1-indexed page to fetch. None means "start from page 1".+ next_page: int | None = None+++def normalize_company(company: str) -> str:+ """Reduce user input to a bare, validated Baton company (instance) label.++ Accepts either the full host (``yourcompany.hellobaton.com``) or the bare company+ (``yourcompany``). Raises ``ValueError`` on anything that isn't a single DNS label so the+ API key can never be retargeted away from ``<company>.hellobaton.com``.+ """+ cleaned = company.strip().removeprefix("https://").removeprefix("http://")+ cleaned = cleaned.strip("/")+ cleaned = cleaned.removesuffix(".hellobaton.com")+ if not _COMPANY_RE.match(cleaned):+ raise ValueError(+ f"Invalid Baton company: {company!r}. Enter just your company instance, e.g. 'yourcompany' "+ "for yourcompany.hellobaton.com."+ )+ return cleaned+++def _base_url(company: str) -> str:+ return f"https://{normalize_company(company)}.hellobaton.com{HELLOBATON_API_PATH}"+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{base_url}{path}"+ return f"{base_url}{path}?{urlencode(params)}"+++def _scrub_url(url: str | None) -> str:+ # The api_key rides in the query string, so strip the query before the URL reaches any error+ # message or log line — otherwise a non-2xx response would leak the credential into job errors.+ # The host and path stay intact so `get_non_retryable_errors()` can still match on them.+ if not url:+ return ""+ parts = urlsplit(url)+ return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))+++@retry(+ retry=retry_if_exception_type((HellobatonRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:+ response = session.get(url, timeout=60)++ # Baton rate limits at 1000 req/min per API key; 429 and transient 5xx are retryable.+ if response.status_code == 429 or response.status_code >= 500:+ raise HellobatonRetryableError(+ f"Baton API error (retryable): status={response.status_code}, url={_scrub_url(url)}"+ )++ if not response.ok:+ logger.error(f"Baton API error: status={response.status_code}, body={response.text}, url={_scrub_url(url)}")+ # Raise with the api_key scrubbed from the URL rather than calling raise_for_status(), whose+ # message embeds the full credential-bearing URL.+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {_scrub_url(response.url)}",+ response=response,+ )++ return response.json()+++def get_rows(+ company: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HellobatonResumeConfig],+) -> Iterator[Any]:+ config = HELLOBATON_ENDPOINTS[endpoint]+ base_url = _base_url(company)+ # Baton authenticates via the api_key query param (not a header) and re-requires it on every page.+ params: dict[str, Any] = {"api_key": api_key, "page_size": PER_PAGE}+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # The api_key travels in the query string, so redact it from logged URLs and captured samples.+ session = make_tracked_session(redact_values=(api_key,) if api_key else ())++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume is not None and resume.next_page else 1+ if page > 1:+ logger.debug(f"Baton: resuming {endpoint} from page {page}")++ while True:+ data = _fetch_page(session, _build_url(base_url, config.path, {**params, "page": page}), logger)+ items = data.get("results", [])+ if not items:+ break++ # Baton's cursor is a full `next` URL; its absence is the definitive end-of-pages signal.+ has_more = bool(data.get("next"))++ for item in items:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes on the primary key.+ if has_more:+ resumable_source_manager.save_state(HellobatonResumeConfig(next_page=page + 1))++ if not has_more:+ break+ page += 1++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def hellobaton_source(+ company: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HellobatonResumeConfig],+) -> SourceResponse:+ config: HellobatonEndpointConfig = HELLOBATON_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ company=company,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ 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,+ )+++def validate_credentials(company: str, api_key: str) -> tuple[bool, int | None]:+ """Probe Baton's `/projects/` list with a 1-row page to confirm the API key is genuine.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error. Raises+ ``ValueError`` if the company is malformed so the caller can surface a precise message.+ """+ url = _build_url(_base_url(company), "/projects/", {"api_key": api_key, "page_size": 1})+ try:+ session = make_tracked_session(redact_values=(api_key,) if api_key else ())+ response = session.get(url, timeout=10)+ except Exception:+ return False, None+ return response.status_code == 200, response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/settings.pynew file mode 100644index 000000000000..c7d7f9f1b27e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/settings.py@@ -0,0 +1,40 @@+from dataclasses import dataclass, field+from typing import Optional++# Baton's DRF PageNumberPagination defaults to and caps page size at 100. Always request the max+# to minimise round trips; the server ignores unknown params so this is safe even if it changes.+PER_PAGE = 100+++@dataclass+class HellobatonEndpointConfig:+ name: str+ path: str # Path under /api, with the trailing slash Baton's router requires (a 301 otherwise)+ # Stable creation-time field to partition by. None when the resource exposes no reliably+ # non-null created_at style field (partitioning on a nullable field rewrites partitions).+ partition_key: Optional[str] = "created"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++# Baton exposes no server-side `updated_since`/`modified_after` filter and the tap-hellobaton Singer+# tap and Airbyte connector both ship full-refresh only, so every endpoint is full refresh here.+HELLOBATON_ENDPOINTS: dict[str, HellobatonEndpointConfig] = {+ "activity": HellobatonEndpointConfig(name="activity", path="/activity/"),+ "companies": HellobatonEndpointConfig(name="companies", path="/companies/"),+ "milestones": HellobatonEndpointConfig(name="milestones", path="/milestones/"),+ "phases": HellobatonEndpointConfig(name="phases", path="/phases/"),+ "projects": HellobatonEndpointConfig(name="projects", path="/projects/"),+ "project_attachments": HellobatonEndpointConfig(name="project_attachments", path="/project_attachments/"),+ "tasks": HellobatonEndpointConfig(name="tasks", path="/tasks/"),+ "task_attachments": HellobatonEndpointConfig(name="task_attachments", path="/task_attachments/"),+ # Templates carry no non-null created/modified timestamp, so there's no stable partition key.+ "templates": HellobatonEndpointConfig(name="templates", path="/templates/", partition_key=None),+ # Time entries have no `created` field; `reference_date` is the stable non-null date they cover.+ "time_entries": HellobatonEndpointConfig(+ name="time_entries", path="/time_entries/", partition_key="reference_date"+ ),+ "users": HellobatonEndpointConfig(name="users", path="/users/"),+}++ENDPOINTS = tuple(HELLOBATON_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/source.pyindex 0baadaeb0244..93178125e6d0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/source.py@@ -1,30 +1,157 @@-from typing import cast+from typing import Optional, castfrom 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.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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HellobatonSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.hellobaton import (+ HellobatonResumeConfig,+ hellobaton_source,+ validate_credentials as validate_hellobaton_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.settings import (+ ENDPOINTS,+ HELLOBATON_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HellobatonSource(SimpleSource[HellobatonSourceConfig]):+class HellobatonSource(ResumableSource[HellobatonSourceConfig, HellobatonResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HELLOBATON+ @property+ def connection_host_fields(self) -> list[str]:+ # The API key is sent to `<company>.hellobaton.com`, so changing the company must re-require it.+ return ["company"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.HELLOBATON,category=DataWarehouseSourceCategory.PRODUCTIVITY,- label="Hellobaton",- iconPath="/static/services/hellobaton.png",- fields=cast(list[FieldType], []),+ label="Baton",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Baton (Hellobaton) company instance and API key to pull your onboarding and implementation data into the PostHog Data warehouse.++Your company instance is the subdomain of your Baton URL — for `yourcompany.hellobaton.com`, enter `yourcompany`.++Generate an API key in Baton under the **API** section of your account settings. The key inherits your account permissions, so it can read every record you can see.""",+ iconPath="/static/services/hellobaton.png",+ docsUrl="https://posthog.com/docs/cdp/sources/hellobaton",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="company",+ label="Company instance",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="yourcompany",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can never fix a credential/permission problem, so fail the sync. Match the+ # stable status text, not the per-request path/query.+ "401 Client Error: Unauthorized": "Your Baton API key is invalid or has been revoked. Generate a new key in your Baton account settings, then reconnect.",+ "403 Client Error: Forbidden": "Your Baton API key is missing the permissions needed to sync this data. Check the key's account permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: HellobatonSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = HELLOBATON_ENDPOINTS[endpoint]+ # Baton exposes no server-side time filter, so every endpoint is full refresh only.+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(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: HellobatonSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ ok, status_code = validate_hellobaton_credentials(config.company, config.api_key)+ except ValueError as e:+ return False, str(e)++ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid Baton API key"+ return False, "Could not connect to Baton with the provided company instance and API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HellobatonResumeConfig]:+ return ResumableSourceManager[HellobatonResumeConfig](inputs, HellobatonResumeConfig)++ def source_for_pipeline(+ self,+ config: HellobatonSourceConfig,+ resumable_source_manager: ResumableSourceManager[HellobatonResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return hellobaton_source(+ company=config.company,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/tests/test_hellobaton.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/tests/test_hellobaton.pynew file mode 100644index 000000000000..7da6d8b45120--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/tests/test_hellobaton.py@@ -0,0 +1,249 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton import hellobaton+from products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.hellobaton import (+ PER_PAGE,+ HellobatonResumeConfig,+ _build_url,+ _fetch_page,+ get_rows,+ normalize_company,+)+++class TestNormalizeCompany:+ @parameterized.expand(+ [+ ("bare", "acme", "acme"),+ ("full_host", "acme.hellobaton.com", "acme"),+ ("https_url", "https://acme.hellobaton.com", "acme"),+ ("trailing_slash", "acme.hellobaton.com/", "acme"),+ ("with_hyphen", "acme-corp", "acme-corp"),+ ("whitespace", " acme ", "acme"),+ ]+ )+ def test_valid_companies(self, _name: str, value: str, expected: str) -> None:+ assert normalize_company(value) == expected++ @parameterized.expand(+ [+ ("path_injection", "acme/../evil"),+ ("host_injection", "acme.evil.com"),+ ("userinfo_injection", "[email protected]"),+ ("empty", ""),+ ("space_inside", "ac me"),+ ("trailing_hyphen", "acme-"),+ ]+ )+ def test_invalid_companies_raise(self, _name: str, value: str) -> None:+ with pytest.raises(ValueError):+ normalize_company(value)+++class TestBuildUrl:+ def test_no_params(self) -> None:+ assert (+ _build_url("https://acme.hellobaton.com/api", "/projects/", {})+ == "https://acme.hellobaton.com/api/projects/"+ )++ def test_encodes_params(self) -> None:+ url = _build_url("https://acme.hellobaton.com/api", "/projects/", {"api_key": "k", "page": 2})+ assert url == "https://acme.hellobaton.com/api/projects/?api_key=k&page=2"+++class _FakeResumableManager:+ def __init__(self, state: HellobatonResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[HellobatonResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> HellobatonResumeConfig | None:+ return self._state++ def save_state(self, data: HellobatonResumeConfig) -> None:+ self.saved.append(data)+++class _FakeBatcher:+ """Yields one batch per item so save-after-yield behavior is observable without 2000+ rows."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self._rows: list[dict] = []++ def batch(self, row: dict) -> None:+ self._rows.append(row)++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return len(self._rows) > 0++ def get_table(self) -> list[dict]:+ rows = self._rows+ self._rows = []+ return rows+++def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, logger: Any) -> dict:+ fetched.append(url)+ return pages[url]++ monkeypatch.setattr(hellobaton, "_fetch_page", fake_fetch)+ return fetched+++def _collect(monkeypatch: Any, manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:+ monkeypatch.setattr(hellobaton, "Batcher", _FakeBatcher)+ rows: list[dict] = []+ for batch in get_rows(+ company="acme",+ api_key="key",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++class TestGetRows:+ def test_paginates_until_next_is_absent(self, monkeypatch: Any) -> None:+ pages = {+ f"https://acme.hellobaton.com/api/projects/?api_key=key&page_size={PER_PAGE}&page=1": {+ "results": [{"id": 1}, {"id": 2}],+ "next": "https://acme.hellobaton.com/api/projects/?page=2",+ },+ f"https://acme.hellobaton.com/api/projects/?api_key=key&page_size={PER_PAGE}&page=2": {+ "results": [{"id": 3}],+ "next": None,+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="projects")++ assert [r["id"] for r in rows] == [1, 2, 3]+ assert fetched == list(pages)++ def test_sends_api_key_and_page_size_on_every_page(self, monkeypatch: Any) -> None:+ pages = {+ f"https://acme.hellobaton.com/api/projects/?api_key=key&page_size={PER_PAGE}&page=1": {+ "results": [{"id": 1}],+ "next": "https://acme.hellobaton.com/api/projects/?page=2",+ },+ f"https://acme.hellobaton.com/api/projects/?api_key=key&page_size={PER_PAGE}&page=2": {+ "results": [{"id": 2}],+ "next": None,+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(monkeypatch, _FakeResumableManager(), endpoint="projects")++ # Baton re-requires the api_key query param on paginated requests, not just the first page.+ assert all("api_key=key" in url for url in fetched)++ def test_saves_resume_state_after_each_yielded_page(self, monkeypatch: Any) -> None:+ pages = {+ f"https://acme.hellobaton.com/api/projects/?api_key=key&page_size={PER_PAGE}&page=1": {+ "results": [{"id": 1}],+ "next": "https://acme.hellobaton.com/api/projects/?page=2",+ },+ f"https://acme.hellobaton.com/api/projects/?api_key=key&page_size={PER_PAGE}&page=2": {+ "results": [{"id": 2}],+ "next": None,+ },+ }+ _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ _collect(monkeypatch, manager, endpoint="projects")++ # State is saved only while more pages remain (page 1 -> next_page 2), never on the last page.+ assert manager.saved == [HellobatonResumeConfig(next_page=2)]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ pages = {+ f"https://acme.hellobaton.com/api/tasks/?api_key=key&page_size={PER_PAGE}&page=2": {+ "results": [{"id": 2}],+ "next": None,+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(HellobatonResumeConfig(next_page=2)), endpoint="tasks")++ assert [r["id"] for r in rows] == [2]+ assert fetched == [f"https://acme.hellobaton.com/api/tasks/?api_key=key&page_size={PER_PAGE}&page=2"]++ def test_stops_on_empty_results(self, monkeypatch: Any) -> None:+ pages: dict[str, Any] = {+ f"https://acme.hellobaton.com/api/companies/?api_key=key&page_size={PER_PAGE}&page=1": {+ "results": [],+ "next": None,+ },+ }+ _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="companies")++ assert rows == []+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("bad_gateway", 502), ("server_error", 500)])+ def test_retryable_status_is_retried(self, _name: str, status_code: int) -> None:+ # 429 and 5xx are transient (rate limit / server blip); the page must retry, then succeed.+ bad = MagicMock()+ bad.status_code = status_code+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"results": [], "next": None}++ session = MagicMock()+ session.get.side_effect = [bad, good]++ with patch.object(_fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = _fetch_page(session, "https://acme.hellobaton.com/api/projects/", MagicMock())++ assert result == {"results": [], "next": None}+ assert session.get.call_count == 2++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_without_retry(self, _name: str, status_code: int) -> None:+ # A 4xx (bad key, missing scope, deleted resource) can never be fixed by retrying.+ response = requests.Response()+ response.status_code = status_code++ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ _fetch_page(session, "https://acme.hellobaton.com/api/projects/", MagicMock())++ def test_raised_error_scrubs_api_key_but_keeps_status_text(self) -> None:+ # The api_key rides in the query string, so a failing request must not leak it into the+ # raised HTTPError, while still exposing the status text get_non_retryable_errors matches on.+ response = requests.Response()+ response.status_code = 401+ response.reason = "Unauthorized"+ response.url = "https://acme.hellobaton.com/api/projects/?api_key=supersecret&page=1"++ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError) as exc_info:+ _fetch_page(session, response.url, MagicMock())++ message = str(exc_info.value)+ assert "supersecret" not in message+ assert "api_key" not in message+ assert "401 Client Error: Unauthorized" in message++ assert session.get.call_count == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/tests/test_hellobaton_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/tests/test_hellobaton_source.pynew file mode 100644index 000000000000..be696a7fec0f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hellobaton/tests/test_hellobaton_source.py@@ -0,0 +1,153 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HellobatonSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.hellobaton import (+ HellobatonResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.settings import (+ ENDPOINTS,+ HELLOBATON_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.source import HellobatonSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestHellobatonSource:+ def setup_method(self):+ self.source = HellobatonSource()+ self.team_id = 123+ self.config = HellobatonSourceConfig(company="acme", api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.HELLOBATON++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Hellobaton"+ assert config.label == "Baton"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Kept behind unreleasedSource until the source has been exercised against live accounts.+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/hellobaton.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hellobaton"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["company", "api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_company_listed_as_connection_host_field(self):+ # The API key is sent to <company>.hellobaton.com, so retargeting the company must re-require it.+ assert self.source.connection_host_fields == ["company"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://acme.hellobaton.com/api/projects/?api_key=key&page_size=100&page=1",+ "403 Client Error: Forbidden for url: https://acme.hellobaton.com/api/tasks/?api_key=key&page_size=100&page=1",+ ],+ )+ 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_error",+ [+ "429 Client Error: Too Many Requests for url: https://acme.hellobaton.com/api/projects/",+ "500 Server Error: Internal Server Error for url: https://acme.hellobaton.com/api/projects/",+ "HTTPSConnectionPool(host='acme.hellobaton.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_are_all_full_refresh(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for schema in schemas.values():+ # Baton exposes no server-side time filter, so nothing supports incremental/append.+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["projects"])+ assert len(schemas) == 1+ assert schemas[0].name == "projects"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(HELLOBATON_ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid Baton API key"),+ ((False, 403), False, "Could not connect to Baton with the provided company instance and API key"),+ ((False, None), False, "Could not connect to Baton with the provided company instance and API key"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.source.validate_hellobaton_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("acme", "key")++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.source.validate_hellobaton_credentials"+ )+ def test_validate_credentials_surfaces_bad_company(self, mock_validate):+ mock_validate.side_effect = ValueError("Invalid Baton company: 'a/b'.")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert "Invalid Baton company" in (error_message or "")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is HellobatonResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hellobaton.source.hellobaton_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_hellobaton_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "projects"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_hellobaton_source.assert_called_once()+ kwargs = mock_hellobaton_source.call_args.kwargs+ assert kwargs["company"] == "acme"+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "projects"+ assert kwargs["resumable_source_manager"] is manager