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): add BugHerd source (#73208)

Tom Owers92851362e4a9
diff --git a/frontend/public/services/bugherd.png b/frontend/public/services/bugherd.png
index c5736e43b50d..4723749e0088 100644
Binary files a/frontend/public/services/bugherd.png and b/frontend/public/services/bugherd.png differ
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 f24ab0835d71..53fd2c251164 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -102,6 +102,7 @@ the row lists both.
| brex | HTTP | requests | ✅ |
| browser_use | HTTP | requests | ✅ |
| browserbase | HTTP | requests | ✅ |
+| bugherd | HTTP | requests + `rest_source.RESTClient` | ✅ |
| bugsnag | HTTP | requests | ✅ |
| buildbetter | HTTP | requests | ✅ |
| buildkite | HTTP | requests | ✅ |
@@ -795,7 +796,6 @@ doesn't conflict with concurrent PRs.
- breezy_hr
- browse_ai
- buffer
-- bugherd
- buildium
- buttondown
- buy_me_a_coffee
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/bugherd.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/bugherd.py
new file mode 100644
index 000000000000..3d7edb2364d9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/bugherd.py
@@ -0,0 +1,217 @@
+import dataclasses
+from collections.abc import Callable, Iterable
+from datetime import UTC, datetime
+from typing import Any, Optional, cast
+
+from requests.exceptions import RequestException
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.settings import (
+ BUGHERD_BASE_URL,
+ BUGHERD_ENDPOINTS,
+ BugherdEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+ IncrementalConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+REQUEST_TIMEOUT_SECONDS = 30
+
+
+class BugherdResumeConfig:
+ page: int
+
+
+def _format_bugherd_datetime(value: Any) -> str:
+ """Format a date/datetime-like value as the ISO 8601 `YYYY-MM-DDTHH:MM:SSZ` string
+ BugHerd's `updated_since`/`created_since` filters document. Falls back to `str(value)`
+ for values that are already a formatted string (e.g. our own `initial_value` seed)."""
+ normalized = coerce_datetime_to_utc(value)
+ if normalized is None:
+ return str(value)
+ capped = min(normalized, datetime.now(UTC))
+ return capped.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _incremental_window(field_name: str, query_param: str) -> IncrementalConfig:
+ return {
+ "cursor_path": field_name,
+ "start_param": query_param,
+ "initial_value": "1970-01-01T00:00:00Z",
+ "convert": _format_bugherd_datetime,
+ }
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": BUGHERD_BASE_URL,
+ # BugHerd auth is the API key as the Basic Auth username with the literal string
+ # "x" as the password.
+ "auth": {"type": "http_basic", "username": api_key, "password": "x"},
+ "headers": {"Accept": "application/json"},
+ }
+
+
+def _list_paginator(config: BugherdEndpointConfig) -> PageNumberPaginator | SinglePagePaginator:
+ if not config.paginated:
+ return SinglePagePaginator()
+ # Pages start at 1; an empty array signals the last page (no total-page count is
+ # documented), so we rely on the paginator's default stop-on-empty-page behaviour.
+ return PageNumberPaginator(base_page=1, page_param="page")
+
+
+def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
+ """Probe Show Organization -- the cheapest authenticated call, with no query params."""
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ f"{BUGHERD_BASE_URL}/api_v2/organization.json",
+ auth=(api_key, "x"),
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except RequestException as exc:
+ return False, f"Could not reach the BugHerd API: {exc}"
+
+ if response.status_code == 401:
+ return False, "Invalid BugHerd API key."
+ if response.status_code != 200:
+ return False, f"BugHerd API returned an unexpected status ({response.status_code})."
+
+ return True, None
+
+
+def _resource(
+ config: BugherdEndpointConfig,
+ should_use_incremental_field: bool,
+ incremental_field: str | None,
+) -> EndpointResource:
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "data_selector": config.data_selector,
+ "paginator": _list_paginator(config),
+ }
+
+ use_merge = should_use_incremental_field and bool(config.incremental_fields)
+ if use_merge:
+ field_name = incremental_field or config.default_incremental_field or config.incremental_fields[0]["field"]
+ query_param = config.incremental_query_params[field_name]
+ endpoint_config["incremental"] = _incremental_window(field_name, query_param)
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_merge else "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+
+
+def _make_source_response(config: BugherdEndpointConfig, items_fn: Callable[[], Iterable[Any]]) -> SourceResponse:
+ primary_keys = config.primary_key if isinstance(config.primary_key, list) else [config.primary_key]
+ return SourceResponse(
+ name=config.name,
+ items=items_fn,
+ primary_keys=primary_keys,
+ sort_mode=config.sort_mode,
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ 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 bugherd_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BugherdResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = BUGHERD_ENDPOINTS[endpoint]
+ client_config = _client_config(api_key)
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"page": resume_config.page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(BugherdResumeConfig(page=int(state["page"])))
+
+ if config.fanout is not None:
+ parent_config = BUGHERD_ENDPOINTS[config.fanout.parent_name]
+ resource = cast(
+ Any,
+ build_dependent_resource(
+ endpoint_configs=BUGHERD_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=client_config,
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_config_factory=lambda field_name: _incremental_window(
+ field_name, config.incremental_query_params[field_name]
+ ),
+ # BugHerd's list endpoints have no client-configurable page-size param.
+ page_size_param=None,
+ parent_endpoint_extra={
+ "paginator": _list_paginator(parent_config),
+ "data_selector": parent_config.data_selector,
+ },
+ child_endpoint_extra={
+ "paginator": _list_paginator(config),
+ "data_selector": config.data_selector,
+ },
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+ dependent_resource = cast(Iterable[Any], resource)
+ return _make_source_response(config, lambda: dependent_resource)
+
+ rest_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": {},
+ "resources": [_resource(config, should_use_incremental_field, incremental_field)],
+ }
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ return _make_source_response(config, lambda: resource)
+
+
+__all__ = ["bugherd_source", "validate_credentials", "BugherdResumeConfig"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/canonical_descriptions.py
new file mode 100644
index 000000000000..4257bd6d1f40
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/canonical_descriptions.py
@@ -0,0 +1,76 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_API_DOCS_URL = "https://docs.bugherd.com/api"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Organization": {
+ "description": "Top-level details about your BugHerd organization.",
+ "docs_url": _API_DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the organization.",
+ "name": "The organization's display name.",
+ },
+ },
+ "Users": {
+ "description": "Team members and guests who belong to your BugHerd organization.",
+ "docs_url": _API_DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "email": "The user's email address.",
+ "display_name": "The user's display name.",
+ "avatar_url": "URL of the user's avatar image.",
+ },
+ },
+ "Projects": {
+ "description": "Websites/projects tracked for visual feedback and bug reporting in BugHerd.",
+ "docs_url": _API_DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the project.",
+ "name": "The project's display name.",
+ "created_at": "Timestamp when the project was created.",
+ "devurl": "Primary website URL for the project.",
+ "is_active": "Whether the project is active.",
+ "is_public": "Whether public feedback is enabled on the project.",
+ "has_custom_columns": "Whether the project has custom kanban columns beyond the defaults.",
+ "guests_see_guests": "Whether guests can see other guests' feedback.",
+ "owner_name": "The name of the project's owner.",
+ "sites": "The website URLs associated with the project.",
+ "api_key": "The project-scoped API key used by the BugHerd feedback widget.",
+ "allow_guests_change_task_status": "Whether guests are permitted to change a task's status.",
+ "assign_guests": "Whether guests can be assigned to tasks.",
+ },
+ },
+ "Tasks": {
+ "description": "Bug reports and feedback items ('tasks') logged against a project's kanban board.",
+ "docs_url": _API_DOCS_URL,
+ "columns": {
+ "id": "Globally unique task ID.",
+ "local_task_id": "Project-scoped task number, shown as #number in the BugHerd UI.",
+ "project_id": "ID of the project the task belongs to.",
+ "created_at": "Timestamp when the task was created.",
+ "updated_at": "Timestamp when the task was last updated.",
+ "closed_at": "Timestamp when the task was closed, if applicable.",
+ "deleted_at": "Timestamp when the task was deleted, if applicable.",
+ "title": "The task's title.",
+ "description": "The task's description.",
+ "status": "Status column name the task is in (e.g. backlog, todo, doing, done, closed, or a custom column name).",
+ "status_id": "Numeric status/column ID. 0=backlog, 1=todo, 2=doing, 4=done, 5=closed; values above 5 indicate a custom column.",
+ "priority": "Priority label (not set, critical, important, normal, minor).",
+ "priority_id": "Numeric priority ID corresponding to `priority`.",
+ "site": "The website the task was logged on.",
+ "url": "The specific page path the task was logged on.",
+ "tag_names": "Tags applied to the task.",
+ "external_id": "Optional external reference ID set via the API (e.g. a linked issue key).",
+ "requester_email": "Email address of the person who reported the task.",
+ "requester_id": "User ID of the person who reported the task, if they are a known user.",
+ "assigned_to_id": "User ID the task is assigned to, if any.",
+ "assignee_ids": "User IDs assigned to the task.",
+ "due_at": "Timestamp the task is due, if set.",
+ "column_id": "ID of the kanban column the task currently sits in.",
+ "secret_link": "Unguessable public URL for the task; no login required.",
+ "admin_link": "Task board URL for the task; login required.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/settings.py
new file mode 100644
index 000000000000..d42ec7555297
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/settings.py
@@ -0,0 +1,94 @@
+from dataclasses import dataclass, field
+from typing import Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+BUGHERD_BASE_URL = "https://www.bugherd.com"
+
+# Tasks is the only endpoint that fans out from Projects today.
+PROJECT_ID_FANOUT = DependentEndpointConfig(
+ parent_name="Projects",
+ resolve_param="project_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "project_id"},
+)
+
+
+@dataclass
+class BugherdEndpointConfig:
+ name: str
+ path: str
+ data_selector: str
+ primary_key: str | list[str] = "id"
+ # BugHerd list endpoints return a fixed ~100 rows/page with no client-configurable
+ # size param, so `page_size` is unused (kept only to satisfy the fan-out helper's
+ # structural typing) and `paginated=False` is only for the single-object Organization
+ # endpoint.
+ page_size: int = 100
+ paginated: bool = True
+ partition_key: str | None = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ # Maps an advertised incremental field name to the query param BugHerd's API actually
+ # filters on for it (e.g. `updated_at` -> `updated_since`).
+ incremental_query_params: dict[str, str] = field(default_factory=dict)
+ sort_mode: Literal["asc", "desc"] = "asc"
+ fanout: DependentEndpointConfig | None = None
+
+
+BUGHERD_ENDPOINTS: dict[str, BugherdEndpointConfig] = {
+ "Organization": BugherdEndpointConfig(
+ name="Organization",
+ path="/api_v2/organization.json",
+ data_selector="organization",
+ paginated=False,
+ ),
+ # Small, full-refresh dimension table. BugHerd documents an `updated_since` filter on
+ # this endpoint, but the User response schema exposes no timestamp field to checkpoint
+ # a watermark from, so we sync it in full each run rather than risk a cursor that never
+ # advances.
+ "Users": BugherdEndpointConfig(
+ name="Users",
+ path="/api_v2/users.json",
+ data_selector="users",
+ ),
+ "Projects": BugherdEndpointConfig(
+ name="Projects",
+ path="/api_v2/projects.json",
+ data_selector="projects",
+ partition_key="created_at",
+ ),
+ "Tasks": BugherdEndpointConfig(
+ name="Tasks",
+ path="/api_v2/projects/{project_id}/tasks.json",
+ data_selector="tasks",
+ # `id` is the globally unique task ID (see the "Show Task (Global)" endpoint, which
+ # looks tasks up by this field alone), unique across every project -- no composite
+ # key needed even though this is a fan-out child.
+ primary_key="id",
+ partition_key="created_at",
+ incremental_fields=[
+ incremental_field("updated_at"),
+ incremental_field("created_at"),
+ ],
+ default_incremental_field="updated_at",
+ incremental_query_params={"updated_at": "updated_since", "created_at": "created_since"},
+ # BugHerd's docs don't state a default sort order for this endpoint. Pagination is
+ # page-number based (not a cursor token), so the `updated_since`/`created_since`
+ # filter -- part of the base request params, not paginator state -- stays in effect
+ # on every page regardless of ordering; an unconfirmed sort only risks uneven
+ # batching, not a corrupted watermark.
+ fanout=PROJECT_ID_FANOUT,
+ ),
+}
+
+ENDPOINTS = tuple(BUGHERD_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BUGHERD_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/source.py
index 48aa51530f22..78abab067f7a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/source.py
@@ -1,13 +1,37 @@
-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.bugherd.bugherd import (
+ BugherdResumeConfig,
+ bugherd_source,
+ validate_credentials as validate_bugherd_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.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,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bugherd import (
BugherdSourceConfig,
)
@@ -15,18 +39,93 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BugherdSource(SimpleSource[BugherdSourceConfig]):
+class BugherdSource(ResumableSource[BugherdSourceConfig, BugherdResumeConfig]):
+ # `get_schemas` iterates a static endpoint catalog with no I/O -- safe for public docs.
+ lists_tables_without_credentials = True
+ api_docs_url = "https://docs.bugherd.com/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BUGHERD
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your BugHerd API key is invalid or has been revoked. Generate a new key under Settings > General Settings and reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: BugherdSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: BugherdSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_bugherd_credentials(config.api_key, schema_name=schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BugherdResumeConfig]:
+ return ResumableSourceManager[BugherdResumeConfig](inputs, BugherdResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BugherdSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BugherdResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return bugherd_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BUGHERD,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="BugHerd",
+ caption="""Enter your BugHerd API key to sync your organization, projects, tasks, and users into the PostHog Data warehouse.
+
+Find your API key in BugHerd under **Settings > General Settings** (organization owner/admin access is required).""",
+ docsUrl="https://posthog.com/docs/cdp/sources/bugherd",
iconPath="/static/services/bugherd.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["bug tracking", "qa"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/tests/test_bugherd.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/tests/test_bugherd.py
new file mode 100644
index 000000000000..1422210edf18
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/tests/test_bugherd.py
@@ -0,0 +1,334 @@
+from datetime import UTC, datetime
+from typing import Any, cast
+
+from unittest.mock import MagicMock, Mock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd import (
+ BugherdResumeConfig,
+ _format_bugherd_datetime,
+ _incremental_window,
+ _resource,
+ bugherd_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.settings import BUGHERD_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class _FakeDltResource:
+ """Stand-in for a DltResource returned by ``rest_api_resources``.
+
+ ``process_parent_data_item`` injects parent fields as ``_<parent_resource>_<field>``
+ (see ``make_parent_key_name``), so test rows carry those prefixed keys to exercise
+ ``build_dependent_resource``'s rename mapper.
+ """
+
+ def __init__(self, name: str, rows: list[dict]) -> None:
+ self.name = name
+ self._rows = rows
+
+ def add_map(self, mapper: Any) -> "_FakeDltResource":
+ self._rows = [mapper(dict(row)) for row in self._rows]
+ return self
+
+ def __iter__(self):
+ return iter(self._rows)
+
+
+def _response(status_code: int = 200, text: str = "") -> Mock:
+ response = Mock()
+ response.status_code = status_code
+ response.text = text
+ return response
+
+
+class TestFormatBugherdDatetime:
+ def test_formats_naive_datetime_as_utc(self) -> None:
+ assert _format_bugherd_datetime(datetime(2024, 1, 15, 9, 30, 0)) == "2024-01-15T09:30:00Z"
+
+ def test_formats_aware_datetime_converted_to_utc(self) -> None:
+ aware = datetime(2024, 1, 15, 9, 30, 0, tzinfo=UTC)
+ assert _format_bugherd_datetime(aware) == "2024-01-15T09:30:00Z"
+
+ def test_caps_future_datetime_to_now(self) -> None:
+ far_future = datetime(2999, 1, 1, tzinfo=UTC)
+ formatted = _format_bugherd_datetime(far_future)
+ assert formatted != "2999-01-01T00:00:00Z"
+ assert datetime.strptime(formatted, "%Y-%m-%dT%H:%M:%SZ") <= datetime.now(UTC).replace(tzinfo=None)
+
+ def test_passes_through_already_formatted_string(self) -> None:
+ # Our own `initial_value` seed round-trips through `convert` on the first sync.
+ assert _format_bugherd_datetime("1970-01-01T00:00:00Z") == "1970-01-01T00:00:00Z"
+
+
+class TestIncrementalWindow:
+ @parameterized.expand(
+ [
+ ("updated_at", "updated_since"),
+ ("created_at", "created_since"),
+ ]
+ )
+ def test_shape(self, field_name: str, query_param: str) -> None:
+ window = _incremental_window(field_name, query_param)
+
+ assert window["cursor_path"] == field_name
+ assert window["start_param"] == query_param
+ assert window["initial_value"] == "1970-01-01T00:00:00Z"
+ assert window["convert"] is _format_bugherd_datetime
+
+
+class TestResource:
+ def test_organization_uses_single_page_paginator(self) -> None:
+ resource = _resource(
+ BUGHERD_ENDPOINTS["Organization"], should_use_incremental_field=False, incremental_field=None
+ )
+
+ assert resource["name"] == "Organization"
+ assert resource["write_disposition"] == "replace"
+ endpoint = cast(dict[str, Any], resource["endpoint"])
+ assert endpoint["path"] == "/api_v2/organization.json"
+ assert endpoint["data_selector"] == "organization"
+ assert isinstance(endpoint["paginator"], SinglePagePaginator)
+ assert "incremental" not in endpoint
+
+ def test_users_is_full_refresh_with_page_paginator(self) -> None:
+ resource = _resource(BUGHERD_ENDPOINTS["Users"], should_use_incremental_field=True, incremental_field=None)
+
+ # Users has no incremental_fields declared, so should_use_incremental_field is ignored.
+ assert resource["write_disposition"] == "replace"
+ endpoint = cast(dict[str, Any], resource["endpoint"])
+ assert isinstance(endpoint["paginator"], PageNumberPaginator)
+ assert "incremental" not in endpoint
+
+ def test_tasks_default_incremental_field_maps_to_updated_since(self) -> None:
+ resource = _resource(BUGHERD_ENDPOINTS["Tasks"], should_use_incremental_field=True, incremental_field=None)
+
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ endpoint = cast(dict[str, Any], resource["endpoint"])
+ assert endpoint["incremental"]["start_param"] == "updated_since"
+
+ def test_tasks_honours_explicit_incremental_field_choice(self) -> None:
+ resource = _resource(
+ BUGHERD_ENDPOINTS["Tasks"], should_use_incremental_field=True, incremental_field="created_at"
+ )
+
+ endpoint = cast(dict[str, Any], resource["endpoint"])
+ assert endpoint["incremental"]["start_param"] == "created_since"
+
+ def test_tasks_full_refresh_when_incremental_disabled(self) -> None:
+ resource = _resource(BUGHERD_ENDPOINTS["Tasks"], should_use_incremental_field=False, incremental_field=None)
+
+ assert resource["write_disposition"] == "replace"
+ assert "incremental" not in cast(dict[str, Any], resource["endpoint"])
+
+
+class TestValidateCredentials:
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.make_tracked_session")
+ def test_valid_key(self, mock_make_session) -> None:
+ mock_make_session.return_value.get.return_value = _response(200)
+
+ assert validate_credentials("valid-key") == (True, None)
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.make_tracked_session")
+ def test_invalid_key(self, mock_make_session) -> None:
+ mock_make_session.return_value.get.return_value = _response(401)
+
+ assert validate_credentials("bad-key") == (False, "Invalid BugHerd API key.")
+
+ @parameterized.expand([(500,), (503,), (403,)])
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.make_tracked_session")
+ def test_other_status_is_reported(self, status_code: int, mock_make_session) -> None:
+ mock_make_session.return_value.get.return_value = _response(status_code)
+
+ result = validate_credentials("key")
+
+ assert result == (False, f"BugHerd API returned an unexpected status ({status_code}).")
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.make_tracked_session")
+ def test_network_error_returns_false(self, mock_make_session) -> None:
+ from requests.exceptions import ConnectionError
+
+ mock_make_session.return_value.get.side_effect = ConnectionError("boom")
+
+ result = validate_credentials("key")
+
+ assert result == (False, "Could not reach the BugHerd API: boom")
+
+
+class TestBugherdSourceTopLevel:
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.rest_api_resource")
+ def test_organization_builds_response(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ resp = bugherd_source(
+ api_key="key", endpoint="Organization", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ assert resp.name == "Organization"
+ assert resp.primary_keys == ["id"]
+ assert resp.partition_mode is None
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.rest_api_resource")
+ def test_projects_partitions_on_created_at(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ resp = bugherd_source(
+ api_key="key", endpoint="Projects", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ assert resp.partition_mode == "datetime"
+ assert resp.partition_keys == ["created_at"]
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.rest_api_resource")
+ def test_flat_endpoint_seeds_paginator_from_saved_page(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BugherdResumeConfig(page=3)
+
+ bugherd_source(api_key="key", endpoint="Users", team_id=1, job_id="job-1", resumable_source_manager=manager)
+
+ _, kwargs = mock_rest_api_resource.call_args
+ assert kwargs["initial_paginator_state"] == {"page": 3}
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.rest_api_resource")
+ def test_flat_endpoint_does_not_load_state_when_cannot_resume(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ bugherd_source(api_key="key", endpoint="Users", team_id=1, job_id="job-1", resumable_source_manager=manager)
+
+ manager.load_state.assert_not_called()
+ _, kwargs = mock_rest_api_resource.call_args
+ assert kwargs["initial_paginator_state"] is None
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.rest_api_resource")
+ def test_flat_endpoint_saves_checkpoint_via_resume_hook(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ bugherd_source(api_key="key", endpoint="Users", team_id=1, job_id="job-1", resumable_source_manager=manager)
+
+ _, kwargs = mock_rest_api_resource.call_args
+ resume_hook = kwargs["resume_hook"]
+ resume_hook({"page": 5})
+
+ manager.save_state.assert_called_once_with(BugherdResumeConfig(page=5))
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.rest_api_resource")
+ def test_flat_endpoint_resume_hook_ignores_terminal_state(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ bugherd_source(api_key="key", endpoint="Users", team_id=1, job_id="job-1", resumable_source_manager=manager)
+
+ _, kwargs = mock_rest_api_resource.call_args
+ kwargs["resume_hook"](None)
+
+ manager.save_state.assert_not_called()
+
+ def test_client_config_uses_http_basic_auth_with_x_password(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.rest_api_resource"
+ ) as mock_rest_api_resource:
+ mock_rest_api_resource.return_value = Mock()
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ bugherd_source(
+ api_key="secret-key", endpoint="Projects", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ (rest_config, *_rest), _ = mock_rest_api_resource.call_args
+ assert rest_config["client"]["auth"] == {
+ "type": "http_basic",
+ "username": "secret-key",
+ "password": "x",
+ }
+
+
+class TestBugherdFanout:
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
+ )
+ def test_tasks_row_format_renames_parent_id_to_project_id(self, mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = [
+ _FakeDltResource("Projects", [{"id": "1000"}]),
+ _FakeDltResource("Tasks", [{"id": "98765", "_Projects_id": "1000"}]),
+ ]
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ resp = bugherd_source(
+ api_key="key", endpoint="Tasks", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ rows = list(cast(Any, resp.items()))
+ assert len(rows) == 1
+ row = rows[0]
+ assert row["project_id"] == "1000"
+ assert "_Projects_id" not in row
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.build_dependent_resource")
+ def test_tasks_fanout_has_no_page_size_param(self, mock_build) -> None:
+ mock_build.return_value = iter([])
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ bugherd_source(api_key="key", endpoint="Tasks", team_id=1, job_id="job-1", resumable_source_manager=manager)
+
+ _, kwargs = mock_build.call_args
+ assert kwargs["page_size_param"] is None
+ assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], PageNumberPaginator)
+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], PageNumberPaginator)
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.build_dependent_resource")
+ def test_tasks_incremental_passes_window_factory_mapped_to_created_since(self, mock_build) -> None:
+ mock_build.return_value = iter([])
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ bugherd_source(
+ api_key="key",
+ endpoint="Tasks",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+
+ _, kwargs = mock_build.call_args
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["incremental_field"] == "created_at"
+ window = kwargs["incremental_config_factory"]("created_at")
+ assert window["start_param"] == "created_since"
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd.build_dependent_resource")
+ def test_tasks_fanout_seeds_resume_state_and_wires_hook(self, mock_build) -> None:
+ mock_build.return_value = iter([])
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BugherdResumeConfig(page=2)
+
+ bugherd_source(api_key="key", endpoint="Tasks", team_id=1, job_id="job-1", resumable_source_manager=manager)
+
+ _, kwargs = mock_build.call_args
+ assert kwargs["initial_paginator_state"] == {"page": 2}
+
+ kwargs["resume_hook"]({"page": 4})
+ manager.save_state.assert_called_once_with(BugherdResumeConfig(page=4))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/tests/test_bugherd_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/tests/test_bugherd_source.py
new file mode 100644
index 000000000000..b64f4149a837
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/tests/test_bugherd_source.py
@@ -0,0 +1,178 @@
+from unittest.mock import Mock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.bugherd import BugherdResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.source import BugherdSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bugherd import (
+ BugherdSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestBugherdSourceConfig:
+ def setup_method(self) -> None:
+ self.source = BugherdSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.BUGHERD
+
+ def test_source_config_is_released_and_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ # A finished source must ship with no `unreleasedSource` flag — see
+ # implementing-warehouse-sources skill.
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_source_config_has_single_api_key_field(self) -> None:
+ config = self.source.get_source_config
+
+ assert len(config.fields) == 1
+ field = config.fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_key"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas iterates a static endpoint catalog with no I/O.
+ assert self.source.lists_tables_without_credentials is True
+
+
+class TestBugherdSourceSchemas:
+ def setup_method(self) -> None:
+ self.source = BugherdSource()
+
+ def test_get_schemas_returns_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(config=Mock(), team_id=1)
+
+ names = {schema.name for schema in schemas}
+ assert names == {"Organization", "Users", "Projects", "Tasks"}
+
+ @parameterized.expand(["Organization", "Users", "Projects"])
+ def test_dimension_endpoints_are_full_refresh_only(self, endpoint: str) -> None:
+ schemas = self.source.get_schemas(config=Mock(), team_id=1, names=[endpoint])
+
+ assert len(schemas) == 1
+ assert schemas[0].supports_incremental is False
+ assert schemas[0].incremental_fields == []
+
+ def test_tasks_supports_incremental_with_two_field_choices(self) -> None:
+ schemas = self.source.get_schemas(config=Mock(), team_id=1, names=["Tasks"])
+
+ assert len(schemas) == 1
+ assert schemas[0].supports_incremental is True
+ fields = {f["field"] for f in schemas[0].incremental_fields}
+ assert fields == {"updated_at", "created_at"}
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(config=Mock(), team_id=1, names=["Projects"])
+
+ assert [schema.name for schema in schemas] == ["Projects"]
+
+
+class TestBugherdSourceCredentialValidation:
+ def setup_method(self) -> None:
+ self.source = BugherdSource()
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.source.validate_bugherd_credentials"
+ )
+ def test_validate_credentials_delegates_to_transport(self, mock_validate) -> None:
+ mock_validate.return_value = (True, None)
+ config = BugherdSourceConfig(api_key="test-key")
+
+ result = self.source.validate_credentials(config, team_id=1)
+
+ assert result == (True, None)
+ mock_validate.assert_called_once_with("test-key", schema_name=None)
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.source.validate_bugherd_credentials"
+ )
+ def test_validate_credentials_forwards_schema_name(self, mock_validate) -> None:
+ mock_validate.return_value = (False, "missing scope")
+ config = BugherdSourceConfig(api_key="test-key")
+
+ result = self.source.validate_credentials(config, team_id=1, schema_name="Tasks")
+
+ assert result == (False, "missing scope")
+ mock_validate.assert_called_once_with("test-key", schema_name="Tasks")
+
+
+class TestBugherdSourceNonRetryableErrors:
+ def setup_method(self) -> None:
+ self.source = BugherdSource()
+
+ def test_non_retryable_errors_includes_unauthorized(self) -> None:
+ assert "401 Client Error" in self.source.get_non_retryable_errors()
+
+
+class TestBugherdSourcePipelinePlumbing:
+ def setup_method(self) -> None:
+ self.source = BugherdSource()
+
+ def test_get_resumable_source_manager_returns_bound_manager(self) -> None:
+ inputs = Mock()
+ inputs.team_id = 1
+ inputs.job_id = "job-1"
+ inputs.logger = Mock()
+
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BugherdResumeConfig
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.source.bugherd_source")
+ def test_source_for_pipeline_forwards_arguments(self, mock_bugherd_source) -> None:
+ mock_bugherd_source.return_value = Mock()
+ config = BugherdSourceConfig(api_key="test-key")
+ inputs = Mock()
+ inputs.schema_name = "Tasks"
+ inputs.team_id = 42
+ inputs.job_id = "job-42"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2025-01-01T00:00:00Z"
+ inputs.incremental_field = "updated_at"
+ manager = Mock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ mock_bugherd_source.assert_called_once_with(
+ api_key="test-key",
+ endpoint="Tasks",
+ team_id=42,
+ job_id="job-42",
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2025-01-01T00:00:00Z",
+ incremental_field="updated_at",
+ )
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bugherd.source.bugherd_source")
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_bugherd_source) -> None:
+ mock_bugherd_source.return_value = Mock()
+ config = BugherdSourceConfig(api_key="test-key")
+ inputs = Mock()
+ inputs.schema_name = "Projects"
+ inputs.team_id = 42
+ inputs.job_id = "job-42"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "should-be-ignored"
+ inputs.incremental_field = None
+ manager = Mock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ _, kwargs = mock_bugherd_source.call_args
+ assert kwargs["db_incremental_field_last_value"] is None
+
+
+def test_bugherd_resume_config_requires_page() -> None:
+ resume_config = BugherdResumeConfig(page=7)
+ assert resume_config.page == 7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bugherd.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bugherd.py
index 4efa679a1583..4f4eaee3fe9b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bugherd.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bugherd.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class BugherdSourceConfig(config.Config):
- pass
+ api_key: str