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 honeybadger import source (#71223)

Tom Owers8c3e5b163af2
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 f21fc263d8e5..3a1d3a5c9c19 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -234,6 +234,7 @@ the row lists both.
| heroku | HTTP | requests | ✅ |
| hetzner | HTTP | requests | ✅ |
| hibob | HTTP | requests | ✅ |
+| honeybadger | HTTP | requests | ✅ |
| honeycomb | HTTP | requests | ✅ |
| humanitix | HTTP | requests | ✅ |
| hubplanner | HTTP | requests | ✅ |
@@ -702,6 +703,7 @@ doesn't conflict with concurrent PRs.
- high_level
- hightouch
- honeybadger
+- honeycomb
- hoorayhr
- hubplanner
- humanitix
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 35a6afb14c7d..d3fd061a31e9 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
@@ -1971,7 +1971,7 @@ class HightouchSourceConfig(config.Config):
@config.config
class HoneybadgerSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/canonical_descriptions.py
new file mode 100644
index 000000000000..6be7180d4e34
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/canonical_descriptions.py
@@ -0,0 +1,96 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "A container that holds all your Honeybadger data for a single app or service.",
+ "docs_url": "https://docs.honeybadger.io/api/projects/",
+ "columns": {
+ "id": "Unique identifier for the project.",
+ "name": "Name of the project.",
+ "active": "Whether the project is active.",
+ "created_at": "When the project was created.",
+ "earliest_notice_at": "Timestamp of the earliest error occurrence retained for the project.",
+ "last_notice_at": "Timestamp of the most recent error occurrence in the project.",
+ "environments": "Environments the project has reported errors from (e.g. development, production).",
+ "fault_count": "Total number of errors (faults) in the project.",
+ "unresolved_fault_count": "Number of unresolved errors (faults) in the project.",
+ "owner": "The account that owns the project (id, email, name).",
+ "teams": "Teams with access to the project.",
+ "users": "Users with access to the project.",
+ "sites": "Uptime checks configured for the project.",
+ "token": "The project's API token used for error reporting.",
+ },
+ },
+ "faults": {
+ "description": "An error ('fault') grouping many individual occurrences (notices). Called an error in the Honeybadger UI.",
+ "docs_url": "https://docs.honeybadger.io/api/faults/",
+ "columns": {
+ "id": "Unique identifier for the fault.",
+ "project_id": "Identifier of the project the fault belongs to.",
+ "klass": "The error class name (e.g. RuntimeError).",
+ "message": "The error message.",
+ "action": "The controller action (or function) in which the error occurred.",
+ "component": "The controller or component in which the error occurred.",
+ "environment": "The environment the error occurred in (e.g. production).",
+ "created_at": "When the fault was first recorded.",
+ "last_notice_at": "When the most recent occurrence of the fault was recorded.",
+ "notices_count": "Number of occurrences recorded for the fault.",
+ "comments_count": "Number of comments on the fault.",
+ "resolved": "Whether the fault has been marked as resolved.",
+ "resolve_on_deploy": "Whether the fault will be marked as resolved on the next deploy.",
+ "ignored": "Whether the fault has been ignored.",
+ "assignee": "The user assigned to the fault (id, email, name).",
+ "tags": "Tags applied to the fault.",
+ "url": "Link to the fault in the Honeybadger UI.",
+ },
+ },
+ "notices": {
+ "description": "A single occurrence of an error, including request context and backtrace. Called an error occurrence in the Honeybadger UI.",
+ "docs_url": "https://docs.honeybadger.io/api/faults/#get-a-list-of-notices",
+ "columns": {
+ "id": "Unique identifier (UUID) for the notice.",
+ "fault_id": "Identifier of the fault this occurrence belongs to.",
+ "project_id": "Identifier of the project the notice belongs to.",
+ "created_at": "When the occurrence was recorded.",
+ "message": "The full error message for this occurrence.",
+ "environment": "Host environment details (environment name, hostname, project root).",
+ "request": "Request context: action, component, params, session, url, and user context.",
+ "web_environment": "Rack/CGI-style environment variables for the request.",
+ "cookies": "Cookies sent with the request.",
+ "backtrace": "Stack trace frames (file, line number, method).",
+ "application_trace": "Stack trace frames limited to application code.",
+ "url": "Link to the notice in the Honeybadger UI.",
+ },
+ },
+ "deploys": {
+ "description": "A deployment recorded for a project, used to correlate errors with releases.",
+ "docs_url": "https://docs.honeybadger.io/api/deployments/",
+ "columns": {
+ "id": "Unique identifier for the deploy.",
+ "project_id": "Identifier of the project that was deployed.",
+ "environment": "The environment that was deployed (e.g. production).",
+ "repository": "The repository that was deployed.",
+ "revision": "The revision (e.g. git SHA or tag) that was deployed.",
+ "local_username": "Username of the person who triggered the deployment.",
+ "created_at": "When the deployment was recorded.",
+ },
+ },
+ "sites": {
+ "description": "An uptime check ('site') configured for a project.",
+ "docs_url": "https://docs.honeybadger.io/api/uptime/",
+ "columns": {
+ "id": "Unique identifier (UUID) for the site.",
+ "project_id": "Identifier of the project the uptime check belongs to.",
+ "name": "Name of the uptime check.",
+ "url": "URL that is checked.",
+ "state": "Current state of the site (up or down).",
+ "active": "Whether the check is currently running.",
+ "frequency": "Number of minutes between checks.",
+ "match": "Status code or text used to determine a passing check, depending on match_type.",
+ "match_type": "How a passing check is determined (success, exact, include, or exclude).",
+ "last_checked_at": "When the site was last checked.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/honeybadger.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/honeybadger.py
new file mode 100644
index 000000000000..4d99b8fb1a75
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/honeybadger.py
@@ -0,0 +1,378 @@
+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, urlparse
+
+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.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.honeybadger.settings import (
+ HONEYBADGER_ENDPOINTS,
+ HoneybadgerEndpointConfig,
+)
+
+HONEYBADGER_BASE_URL = "https://app.honeybadger.io/v2"
+_API_ORIGIN = urlparse(HONEYBADGER_BASE_URL)
+# Honeybadger caps list page sizes at 25 (default and max).
+PAGE_LIMIT = 25
+REQUEST_TIMEOUT = 60
+# Longest single in-attempt sleep when the hourly quota (360 req/hour) is exhausted. If the
+# window resets further out, the retries exhaust and the activity fails; Temporal retries it
+# later and the resumable state picks the sync back up where it left off.
+MAX_RATE_LIMIT_SLEEP_SECONDS = 60.0
+
+
+class HoneybadgerRetryableError(Exception):
+ pass
+
+
+class HoneybadgerResumeConfig:
+ # Next page URL to fetch. None means "start the bookmarked resource at its first page".
+ next_url: str | None = None
+ # Stable id bookmarks (not positional indexes) so resources added/removed between a crash
+ # and the retry can't resume us into the wrong project/fault.
+ project_id: int | None = None
+ fault_id: int | None = None
+
+
+def _make_session(api_key: str) -> requests.Session:
+ # Honeybadger authenticates with HTTP Basic auth: personal token as username, blank password.
+ # Exclude requests from HTTP sample capture: project responses carry a live project token and
+ # notice responses can contain session cookies and other auth data the name-based sample
+ # scrubbers don't recognise.
+ session = make_tracked_session(headers={"Accept": "application/json"}, capture=False)
+ session.auth = (api_key, "")
+ return session
+
+
+def _build_url(base_url: str, params: dict[str, Any]) -> str:
+ if not params:
+ return base_url
+ return f"{base_url}?{urlencode(params)}"
+
+
+def _to_unix_timestamp(value: Any) -> int:
+ """Convert an incremental cursor value to the Unix timestamp Honeybadger's filters expect."""
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return int(aware.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ if isinstance(value, int | float):
+ return int(value)
+ return int(datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp())
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ HoneybadgerRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=2, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:
+ # Every fetched URL — including `links.next` from responses and resume URLs replayed from
+ # Redis — must stay on the Honeybadger API origin: the session carries the user's token as
+ # Basic auth, so following a foreign URL would hand the credential to that host (and is an
+ # SSRF primitive).
+ parsed = urlparse(url)
+ if parsed.scheme != _API_ORIGIN.scheme or parsed.netloc != _API_ORIGIN.netloc:
+ raise ValueError(f"Refusing to fetch non-Honeybadger URL: {url}")
+
+ response = session.get(url, timeout=REQUEST_TIMEOUT)
+
+ # Honeybadger signals both auth failure and rate-limit exhaustion with a 403; only the
+ # rate-limited one carries an exhausted X-RateLimit-Remaining header. Sleep toward the
+ # window reset (bounded) and retry; a genuine permission 403 falls through to
+ # raise_for_status so get_non_retryable_errors can stop the sync.
+ if response.status_code == 403 and response.headers.get("X-RateLimit-Remaining") == "0":
+ delay = MAX_RATE_LIMIT_SLEEP_SECONDS
+ reset_header = response.headers.get("X-RateLimit-Reset")
+ if reset_header:
+ try:
+ delay = min(max(float(reset_header) - time.time(), 1.0), MAX_RATE_LIMIT_SLEEP_SECONDS)
+ except ValueError:
+ pass
+ logger.warning(f"Honeybadger: rate limited, sleeping {delay:.0f}s before retrying. url={url}")
+ time.sleep(delay)
+ raise HoneybadgerRetryableError(f"Honeybadger API rate limited: url={url}")
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise HoneybadgerRetryableError(f"Honeybadger API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Honeybadger API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> bool:
+ try:
+ response = _make_session(api_key).get(f"{HONEYBADGER_BASE_URL}/projects", timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _collect_ids(session: requests.Session, first_url: str, logger: FilteringBoundLogger) -> list[Any]:
+ """Walk every page of a list endpoint and return the ids, following `links.next`."""
+ ids: list[Any] = []
+ url: str | None = first_url
+ while url:
+ data = _fetch_page(session, url, logger)
+ ids.extend(item["id"] for item in data.get("results") or [])
+ next_url = (data.get("links") or {}).get("next")
+ url = next_url if next_url != url else None
+ return ids
+
+
+def _build_params(
+ config: HoneybadgerEndpointConfig,
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": PAGE_LIMIT}
+
+ if not should_use_incremental_field or db_incremental_field_last_value is None:
+ return params
+
+ field_name = incremental_field or config.default_incremental_field
+ query_param = config.incremental_params.get(field_name) if field_name else None
+ if query_param is None:
+ # No server-side filter for the chosen cursor — walk the full history and let the
+ # merge dedupe on the primary key rather than silently filtering on the wrong field.
+ logger.warning(
+ f"Honeybadger: no server-side filter for incremental field '{field_name}' on "
+ f"endpoint '{config.name}', running without a time filter"
+ )
+ return params
+
+ params[query_param] = _to_unix_timestamp(db_incremental_field_last_value)
+ return params
+
+
+def _iter_pages(
+ session: requests.Session,
+ first_url: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[tuple[list[dict], str | None]]:
+ """Yield (results, next_url) per page. The docs note a `next` link may point at an empty
+ page, so empty results don't terminate the walk — only a missing `next` link does."""
+ url: str | None = first_url
+ while url:
+ data = _fetch_page(session, url, logger)
+ results = data.get("results") or []
+ next_url = (data.get("links") or {}).get("next")
+ if next_url == url:
+ next_url = None
+ yield results, next_url
+ url = next_url
+
+
+def _get_project_rows(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HoneybadgerResumeConfig],
+ resume: HoneybadgerResumeConfig | None,
+ params: dict[str, Any],
+) -> Iterator[list[dict]]:
+ first_url = (
+ resume.next_url if resume and resume.next_url else _build_url(f"{HONEYBADGER_BASE_URL}/projects", params)
+ )
+ for results, next_url in _iter_pages(session, first_url, logger):
+ if not results:
+ continue
+ yield results
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last
+ # page rather than skipping it — merge dedupes on the primary key.
+ if next_url:
+ resumable_source_manager.save_state(HoneybadgerResumeConfig(next_url=next_url))
+
+
+def _get_project_child_rows(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HoneybadgerResumeConfig],
+ resume: HoneybadgerResumeConfig | None,
+ config: HoneybadgerEndpointConfig,
+ params: dict[str, Any],
+) -> Iterator[list[dict]]:
+ """Fan out over every project and page through the per-project child endpoint."""
+ project_ids = _collect_ids(session, _build_url(f"{HONEYBADGER_BASE_URL}/projects", {"limit": PAGE_LIMIT}), logger)
+
+ # Resolve the saved project bookmark to the projects still to process. If the bookmarked
+ # project no longer exists, start over — merge dedupes re-pulled rows on the primary key.
+ remaining = project_ids
+ resume_url: str | None = None
+ if resume is not None and resume.project_id is not None and resume.project_id in project_ids:
+ remaining = project_ids[project_ids.index(resume.project_id) :]
+ resume_url = resume.next_url
+
+ for index, project_id in enumerate(remaining):
+ first_url = resume_url or _build_url(
+ f"{HONEYBADGER_BASE_URL}{config.path.format(project_id=project_id)}", params
+ )
+ resume_url = None # only the resumed-into project uses the saved URL
+
+ for results, next_url in _iter_pages(session, first_url, logger):
+ if not results:
+ continue
+ # Inject the parent project id: sites don't carry it, and it's part of the
+ # composite primary key. Faults/deploys already include it (theirs wins).
+ yield [{"project_id": project_id, **item} for item in results]
+ if next_url:
+ resumable_source_manager.save_state(HoneybadgerResumeConfig(next_url=next_url, project_id=project_id))
+
+ # Advance the bookmark so a crash between projects resumes at the next one.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(HoneybadgerResumeConfig(project_id=remaining[index + 1]))
+
+
+def _get_notice_rows(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HoneybadgerResumeConfig],
+ resume: HoneybadgerResumeConfig | None,
+ config: HoneybadgerEndpointConfig,
+ params: dict[str, Any],
+) -> Iterator[list[dict]]:
+ """Two-level fan-out: projects -> faults -> notices.
+
+ On incremental syncs the notice watermark also bounds the fault enumeration
+ (`occurred_after`): only faults whose last notice is newer than the watermark can have new
+ notices, which keeps the per-fault request count away from the 360 req/hour quota.
+ """
+ project_ids = _collect_ids(session, _build_url(f"{HONEYBADGER_BASE_URL}/projects", {"limit": PAGE_LIMIT}), logger)
+
+ fault_params: dict[str, Any] = {"limit": PAGE_LIMIT}
+ created_after = params.get("created_after")
+ if created_after is not None:
+ fault_params["occurred_after"] = created_after
+
+ remaining_projects = project_ids
+ resume_fault_id: int | None = None
+ resume_url: str | None = None
+ if resume is not None and resume.project_id is not None and resume.project_id in project_ids:
+ remaining_projects = project_ids[project_ids.index(resume.project_id) :]
+ resume_fault_id = resume.fault_id
+ resume_url = resume.next_url
+
+ for project_index, project_id in enumerate(remaining_projects):
+ fault_ids = _collect_ids(
+ session,
+ _build_url(f"{HONEYBADGER_BASE_URL}/projects/{project_id}/faults", fault_params),
+ logger,
+ )
+
+ remaining_faults = fault_ids
+ if resume_fault_id is not None and resume_fault_id in fault_ids:
+ remaining_faults = fault_ids[fault_ids.index(resume_fault_id) :]
+ else:
+ # No (or unresolvable) fault bookmark: the saved page URL belongs to a fault we're
+ # not resuming into, so it must not seed another fault's pagination.
+ resume_url = None
+ resume_fault_id = None # only the resumed-into project uses the fault bookmark
+
+ for fault_index, fault_id in enumerate(remaining_faults):
+ first_url = resume_url or _build_url(
+ f"{HONEYBADGER_BASE_URL}{config.path.format(project_id=project_id, fault_id=fault_id)}", params
+ )
+ resume_url = None
+
+ for results, next_url in _iter_pages(session, first_url, logger):
+ if not results:
+ continue
+ yield [{"project_id": project_id, **item} for item in results]
+ if next_url:
+ resumable_source_manager.save_state(
+ HoneybadgerResumeConfig(next_url=next_url, project_id=project_id, fault_id=fault_id)
+ )
+
+ if fault_index + 1 < len(remaining_faults):
+ resumable_source_manager.save_state(
+ HoneybadgerResumeConfig(project_id=project_id, fault_id=remaining_faults[fault_index + 1])
+ )
+
+ if project_index + 1 < len(remaining_projects):
+ resumable_source_manager.save_state(
+ HoneybadgerResumeConfig(project_id=remaining_projects[project_index + 1])
+ )
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HoneybadgerResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict]]:
+ config = HONEYBADGER_ENDPOINTS[endpoint]
+ # One session reused across every page (and every fanned-out project/fault) so urllib3
+ # keeps the connection alive instead of re-handshaking per request.
+ session = _make_session(api_key)
+
+ params = _build_params(
+ config, logger, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.fan_out_over_faults:
+ yield from _get_notice_rows(session, logger, resumable_source_manager, resume, config, params)
+ elif "{project_id}" in config.path:
+ yield from _get_project_child_rows(session, logger, resumable_source_manager, resume, config, params)
+ else:
+ yield from _get_project_rows(session, logger, resumable_source_manager, resume, params)
+
+
+def honeybadger_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HoneybadgerResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = HONEYBADGER_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ 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,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ # Honeybadger lists return newest-first (deploys/notices document it; faults default to
+ # creation-time order with no ascending option). desc also fits the fan-out: the
+ # incremental watermark is only finalized once the whole run completes, so a partial
+ # run can't advance it past projects/faults it never reached.
+ 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/honeybadger/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/settings.py
new file mode 100644
index 000000000000..0f3af7dad708
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/settings.py
@@ -0,0 +1,92 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class HoneybadgerEndpointConfig:
+ name: str
+ # Path template under the v2 base URL; `{project_id}` / `{fault_id}` are filled in by the fan-out.
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Incremental field name -> query param that server-side filters on it (Unix timestamp).
+ incremental_params: dict[str, str] = field(default_factory=dict)
+ default_incremental_field: str | None = None
+ partition_key: str | None = None # Stable creation-time field; never a mutating timestamp
+ fan_out_over_faults: bool = False # Two-level fan-out: projects -> faults -> {endpoint}
+ should_sync_default: bool = True
+
+
+_created_at_field: IncrementalField = {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+HONEYBADGER_ENDPOINTS: dict[str, HoneybadgerEndpointConfig] = {
+ "projects": HoneybadgerEndpointConfig(
+ name="projects",
+ path="/projects",
+ # The projects list has no server-side timestamp filter, so it's full refresh only.
+ incremental_fields=[],
+ ),
+ "faults": HoneybadgerEndpointConfig(
+ name="faults",
+ path="/projects/{project_id}/faults",
+ # Fault ids look globally unique, but the API doesn't document that — include the
+ # parent project id so the key is unique table-wide across the fan-out.
+ primary_keys=["project_id", "id"],
+ incremental_fields=[
+ _created_at_field,
+ {
+ "label": "last_notice_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "last_notice_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ # `created_after` only picks up new faults; `occurred_after` (filters on the fault's
+ # last notice) also re-pulls existing faults that reoccurred, keeping counts fresh.
+ incremental_params={"created_at": "created_after", "last_notice_at": "occurred_after"},
+ default_incremental_field="last_notice_at",
+ partition_key="created_at",
+ ),
+ "notices": HoneybadgerEndpointConfig(
+ name="notices",
+ path="/projects/{project_id}/faults/{fault_id}/notices",
+ # Notice ids are UUIDs.
+ primary_keys=["id"],
+ incremental_fields=[_created_at_field],
+ incremental_params={"created_at": "created_after"},
+ default_incremental_field="created_at",
+ partition_key="created_at",
+ fan_out_over_faults=True,
+ # One request per fault minimum against a 360 req/hour quota — opt-in only.
+ should_sync_default=False,
+ ),
+ "deploys": HoneybadgerEndpointConfig(
+ name="deploys",
+ path="/projects/{project_id}/deploys",
+ primary_keys=["project_id", "id"],
+ incremental_fields=[_created_at_field],
+ incremental_params={"created_at": "created_after"},
+ default_incremental_field="created_at",
+ partition_key="created_at",
+ ),
+ "sites": HoneybadgerEndpointConfig(
+ name="sites",
+ path="/projects/{project_id}/sites",
+ # Site ids are UUIDs; keep the parent project id in the key anyway for consistency.
+ primary_keys=["project_id", "id"],
+ # The sites (uptime checks) list has no server-side timestamp filter.
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(HONEYBADGER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in HONEYBADGER_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/source.py
index 25ae6222f4b1..b10ecd7666a6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/source.py
@@ -1,19 +1,43 @@
-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.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 HoneybadgerSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.honeybadger import (
+ HoneybadgerResumeConfig,
+ honeybadger_source,
+ validate_credentials as validate_honeybadger_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.settings import (
+ ENDPOINTS,
+ HONEYBADGER_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HoneybadgerSource(SimpleSource[HoneybadgerSourceConfig]):
+class HoneybadgerSource(ResumableSource[HoneybadgerSourceConfig, HoneybadgerResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HONEYBADGER
@@ -24,7 +48,104 @@ class HoneybadgerSource(SimpleSource[HoneybadgerSourceConfig]):
name=SchemaExternalDataSourceType.HONEYBADGER,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Honeybadger",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Honeybadger personal authentication token to pull your error monitoring data (projects, errors, occurrences, deployments, and uptime checks) into the PostHog Data warehouse.
+
+You can find your personal authentication token on your [Honeybadger profile page](https://app.honeybadger.io/users/edit).
+
+Note that Honeybadger's API is limited to 360 requests per hour, so large backfills (especially of the notices table) can take a while.""",
iconPath="/static/services/honeybadger.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/honeybadger",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Personal authentication token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # Honeybadger also answers rate-limited requests with a 403, but those are converted to
+ # a retryable error before raise_for_status runs (see honeybadger.py), so a 403
+ # HTTPError here can only be a credential/permission problem.
+ return {
+ "401 Client Error: Unauthorized for url: https://app.honeybadger.io": "Your Honeybadger authentication token is invalid or has been revoked. Copy a valid personal authentication token from your Honeybadger profile page, then reconnect.",
+ "403 Client Error: Forbidden for url: https://app.honeybadger.io": "Honeybadger denied access with this authentication token. Copy a valid personal authentication token from your Honeybadger profile page, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: HoneybadgerSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "notices":
+ return (
+ "One row per error occurrence. Fetched per fault, so syncing large accounts is slow "
+ "against Honeybadger's 360 requests/hour limit — prefer incremental sync"
+ )
+ return None
+
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ supports_append=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=HONEYBADGER_ENDPOINTS[endpoint].should_sync_default,
+ description=_description(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: HoneybadgerSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_honeybadger_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Honeybadger authentication token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HoneybadgerResumeConfig]:
+ return ResumableSourceManager[HoneybadgerResumeConfig](inputs, HoneybadgerResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HoneybadgerSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HoneybadgerResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return honeybadger_source(
+ api_key=config.api_key,
+ 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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/tests/test_honeybadger.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/tests/test_honeybadger.py
new file mode 100644
index 000000000000..aec71420b1f6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/tests/test_honeybadger.py
@@ -0,0 +1,493 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+import requests
+from tenacity import wait_none
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.honeybadger import (
+ HONEYBADGER_BASE_URL,
+ MAX_RATE_LIMIT_SLEEP_SECONDS,
+ HoneybadgerResumeConfig,
+ HoneybadgerRetryableError,
+ _build_params,
+ _fetch_page,
+ _to_unix_timestamp,
+ get_rows,
+ honeybadger_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.settings import HONEYBADGER_ENDPOINTS
+
+# 2023-11-14T22:13:20Z
+WATERMARK_TS = 1_700_000_000
+WATERMARK = datetime.fromtimestamp(WATERMARK_TS, tz=UTC)
+
+# tenacity exposes the undecorated function via `__wrapped__`, so status classification can be
+# tested without paying the retry waits; it's not part of the wrapped callable's type.
+_fetch_page_once = _fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+def _response(payload: Any = None, status: int = 200, headers: dict[str, str] | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ response.headers = headers or {}
+ response.json.return_value = payload if payload is not None else {}
+ response.text = json.dumps(payload) if payload is not None else ""
+ if status >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(
+ f"{status} Client Error: error for url: {HONEYBADGER_BASE_URL}", response=response
+ )
+ else:
+ response.raise_for_status.side_effect = None
+ return response
+
+
+class FakeSession:
+ """Maps exact request URLs to canned page payloads and records the call order."""
+
+ def __init__(self, routes: dict[str, Any]) -> None:
+ self.routes = routes
+ self.calls: list[str] = []
+
+ def get(self, url: str, timeout: Any = None) -> MagicMock:
+ self.calls.append(url)
+ assert url in self.routes, f"unexpected request: {url}"
+ return _response(self.routes[url])
+
+
+def _make_manager(resume: HoneybadgerResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _run(
+ routes: dict[str, Any],
+ endpoint: str,
+ manager: MagicMock | None = None,
+ **kwargs: Any,
+) -> tuple[list[list[dict]], FakeSession, MagicMock]:
+ session = FakeSession(routes)
+ manager = manager if manager is not None else _make_manager()
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.honeybadger._make_session",
+ return_value=session,
+ ):
+ batches = list(
+ get_rows(
+ api_key="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+ return batches, session, manager
+
+
+class TestHoneybadger:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (WATERMARK, WATERMARK_TS),
+ (datetime(2023, 11, 14, 22, 13, 20), WATERMARK_TS), # naive datetimes are treated as UTC
+ (date(2023, 11, 14), 1_699_920_000),
+ (WATERMARK_TS, WATERMARK_TS),
+ (float(WATERMARK_TS), WATERMARK_TS),
+ ("2023-11-14T22:13:20Z", WATERMARK_TS),
+ ("2023-11-14T22:13:20+00:00", WATERMARK_TS),
+ ],
+ )
+ def test_to_unix_timestamp(self, value: Any, expected: int) -> None:
+ assert _to_unix_timestamp(value) == expected
+
+ def test_build_params_full_refresh(self) -> None:
+ params = _build_params(HONEYBADGER_ENDPOINTS["faults"], MagicMock(), False, WATERMARK, None)
+ assert params == {"limit": 25}
+
+ def test_build_params_defaults_to_endpoint_default_field(self) -> None:
+ params = _build_params(HONEYBADGER_ENDPOINTS["faults"], MagicMock(), True, WATERMARK, None)
+ assert params == {"limit": 25, "occurred_after": WATERMARK_TS}
+
+ def test_build_params_honors_user_chosen_field(self) -> None:
+ params = _build_params(HONEYBADGER_ENDPOINTS["faults"], MagicMock(), True, WATERMARK, "created_at")
+ assert params == {"limit": 25, "created_after": WATERMARK_TS}
+
+ def test_build_params_unknown_field_falls_back_to_full_walk(self) -> None:
+ logger = MagicMock()
+ params = _build_params(HONEYBADGER_ENDPOINTS["faults"], logger, True, WATERMARK, "not_a_field")
+ assert params == {"limit": 25}
+ logger.warning.assert_called_once()
+
+ @pytest.mark.parametrize("status", [429, 500, 502])
+ def test_fetch_page_raises_retryable_on_transient_statuses(self, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(None, status=status)
+ with pytest.raises(HoneybadgerRetryableError):
+ _fetch_page_once(session, f"{HONEYBADGER_BASE_URL}/projects", MagicMock())
+
+ @pytest.mark.parametrize("status", [401, 403, 404])
+ def test_fetch_page_raises_http_error_on_permanent_statuses(self, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(None, status=status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_once(session, f"{HONEYBADGER_BASE_URL}/projects", MagicMock())
+
+ @pytest.mark.parametrize(
+ ("reset_offset", "expected_sleep"),
+ [
+ (30, 30.0),
+ (100_000, MAX_RATE_LIMIT_SLEEP_SECONDS), # capped
+ (-10, 1.0), # already reset — minimal sleep
+ ],
+ )
+ def test_fetch_page_rate_limit_sleeps_toward_reset_and_retries(
+ self, reset_offset: int, expected_sleep: float
+ ) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(
+ None, status=403, headers={"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": str(1_000 + reset_offset)}
+ )
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.honeybadger.time.time",
+ return_value=1_000.0,
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.honeybadger.time.sleep"
+ ) as mock_sleep,
+ ):
+ with pytest.raises(HoneybadgerRetryableError):
+ _fetch_page_once(session, f"{HONEYBADGER_BASE_URL}/projects", MagicMock())
+ mock_sleep.assert_called_once_with(expected_sleep)
+
+ def test_fetch_page_retries_transient_error_then_succeeds(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [_response(None, status=500), _response({"results": [{"id": 1}]})]
+ result = _fetch_page.retry_with(wait=wait_none())(session, f"{HONEYBADGER_BASE_URL}/projects", MagicMock()) # type: ignore[attr-defined]
+ assert result == {"results": [{"id": 1}]}
+ assert session.get.call_count == 2
+
+ def test_fetch_page_does_not_retry_auth_403(self) -> None:
+ # A 403 without an exhausted quota header is a credential problem, not a rate limit.
+ session = MagicMock()
+ session.get.return_value = _response(None, status=403)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page.retry_with(wait=wait_none())(session, f"{HONEYBADGER_BASE_URL}/projects", MagicMock()) # type: ignore[attr-defined]
+ assert session.get.call_count == 1
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "https://evil.com/v2/projects",
+ "http://app.honeybadger.io/v2/projects", # https only — Basic auth in cleartext otherwise
+ "https://app.honeybadger.io.evil.com/v2/projects",
+ "https://[email protected]/v2/projects",
+ ],
+ )
+ def test_fetch_page_refuses_off_origin_urls(self, url: str) -> None:
+ # A poisoned `links.next` or tampered resume URL must never receive the credentialed
+ # session — the request is refused before it is sent.
+ session = MagicMock()
+ with pytest.raises(ValueError, match="Refusing to fetch"):
+ _fetch_page_once(session, url, MagicMock())
+ session.get.assert_not_called()
+
+ @pytest.mark.parametrize(("status", "expected"), [(200, True), (403, False)])
+ def test_validate_credentials(self, status: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _response({}, status=status)
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.honeybadger._make_session",
+ return_value=session,
+ ):
+ assert validate_credentials("token") is expected
+
+ def test_validate_credentials_swallows_connection_errors(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.honeybadger._make_session",
+ return_value=session,
+ ):
+ assert validate_credentials("token") is False
+
+ def test_projects_paginates_and_checkpoints(self) -> None:
+ next_url = f"{HONEYBADGER_BASE_URL}/projects?limit=25&page=2"
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {
+ "results": [{"id": 1}, {"id": 2}],
+ "links": {"next": next_url},
+ },
+ next_url: {"results": [{"id": 3}], "links": {}},
+ }
+
+ batches, _, manager = _run(routes, "projects")
+
+ assert batches == [[{"id": 1}, {"id": 2}], [{"id": 3}]]
+ manager.save_state.assert_called_once_with(HoneybadgerResumeConfig(next_url=next_url))
+
+ def test_projects_resumes_from_saved_url(self) -> None:
+ next_url = f"{HONEYBADGER_BASE_URL}/projects?limit=25&page=2"
+ routes = {next_url: {"results": [{"id": 3}], "links": {}}}
+
+ batches, session, _ = _run(
+ routes, "projects", manager=_make_manager(HoneybadgerResumeConfig(next_url=next_url))
+ )
+
+ assert batches == [[{"id": 3}]]
+ assert session.calls == [next_url]
+
+ def test_projects_skips_empty_page_with_next_link(self) -> None:
+ # The docs allow a `next` link that resolves to an empty page; the walk must follow
+ # `next` links and not yield empty batches.
+ next_url = f"{HONEYBADGER_BASE_URL}/projects?limit=25&page=2"
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [], "links": {"next": next_url}},
+ next_url: {"results": [{"id": 1}], "links": {}},
+ }
+
+ batches, _, _ = _run(routes, "projects")
+
+ assert batches == [[{"id": 1}]]
+
+ def test_faults_fan_out_over_projects(self) -> None:
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 1}, {"id": 2}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25": {
+ "results": [{"id": 10, "project_id": 1}],
+ "links": {},
+ },
+ f"{HONEYBADGER_BASE_URL}/projects/2/faults?limit=25": {
+ "results": [{"id": 20, "project_id": 2}],
+ "links": {},
+ },
+ }
+
+ batches, _, manager = _run(routes, "faults")
+
+ assert batches == [[{"id": 10, "project_id": 1}], [{"id": 20, "project_id": 2}]]
+ # Bookmark advanced to the next project so a crash between projects resumes there.
+ manager.save_state.assert_called_once_with(HoneybadgerResumeConfig(project_id=2))
+
+ def test_sites_rows_gain_parent_project_id(self) -> None:
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 7}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/7/sites?limit=25": {
+ "results": [{"id": "site-uuid", "name": "Main site"}],
+ "links": {},
+ },
+ }
+
+ batches, _, _ = _run(routes, "sites")
+
+ assert batches == [[{"project_id": 7, "id": "site-uuid", "name": "Main site"}]]
+
+ @pytest.mark.parametrize(
+ ("incremental_field", "expected_param"),
+ [
+ (None, "occurred_after"), # endpoint default: last_notice_at
+ ("created_at", "created_after"),
+ ("last_notice_at", "occurred_after"),
+ ],
+ )
+ def test_faults_incremental_uses_server_side_filter(
+ self, incremental_field: str | None, expected_param: str
+ ) -> None:
+ child_url = f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25&{expected_param}={WATERMARK_TS}"
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 1}], "links": {}},
+ child_url: {"results": [{"id": 10, "project_id": 1}], "links": {}},
+ }
+
+ _, session, _ = _run(
+ routes,
+ "faults",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=WATERMARK,
+ incremental_field=incremental_field,
+ )
+
+ assert child_url in session.calls
+
+ def test_fan_out_resumes_from_project_bookmark(self) -> None:
+ resume_url = f"{HONEYBADGER_BASE_URL}/projects/2/faults?limit=25&page=5"
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 1}, {"id": 2}, {"id": 3}], "links": {}},
+ resume_url: {"results": [{"id": 20, "project_id": 2}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/3/faults?limit=25": {
+ "results": [{"id": 30, "project_id": 3}],
+ "links": {},
+ },
+ }
+
+ batches, session, _ = _run(
+ routes,
+ "faults",
+ manager=_make_manager(HoneybadgerResumeConfig(next_url=resume_url, project_id=2)),
+ )
+
+ # Project 1 is skipped, project 2 resumes at its saved page, project 3 starts fresh.
+ assert f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25" not in session.calls
+ assert batches == [[{"id": 20, "project_id": 2}], [{"id": 30, "project_id": 3}]]
+
+ def test_fan_out_restarts_when_bookmarked_project_vanished(self) -> None:
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 1}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25": {
+ "results": [{"id": 10, "project_id": 1}],
+ "links": {},
+ },
+ }
+
+ batches, _, _ = _run(
+ routes,
+ "faults",
+ manager=_make_manager(HoneybadgerResumeConfig(next_url="https://app.honeybadger.io/stale", project_id=99)),
+ )
+
+ assert batches == [[{"id": 10, "project_id": 1}]]
+
+ def test_notices_fan_out_over_projects_and_faults(self) -> None:
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 1}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25": {"results": [{"id": 10}, {"id": 11}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/1/faults/10/notices?limit=25": {
+ "results": [{"id": "uuid-1", "fault_id": 10}],
+ "links": {},
+ },
+ f"{HONEYBADGER_BASE_URL}/projects/1/faults/11/notices?limit=25": {
+ "results": [{"id": "uuid-2", "fault_id": 11}],
+ "links": {},
+ },
+ }
+
+ batches, _, manager = _run(routes, "notices")
+
+ assert batches == [
+ [{"project_id": 1, "id": "uuid-1", "fault_id": 10}],
+ [{"project_id": 1, "id": "uuid-2", "fault_id": 11}],
+ ]
+ manager.save_state.assert_called_once_with(HoneybadgerResumeConfig(project_id=1, fault_id=11))
+
+ def test_notices_incremental_bounds_fault_enumeration(self) -> None:
+ # The notice watermark is also applied as `occurred_after` on the fault listing:
+ # faults whose last notice predates the watermark can't have new notices.
+ faults_url = f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25&occurred_after={WATERMARK_TS}"
+ notices_url = f"{HONEYBADGER_BASE_URL}/projects/1/faults/10/notices?limit=25&created_after={WATERMARK_TS}"
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 1}], "links": {}},
+ faults_url: {"results": [{"id": 10}], "links": {}},
+ notices_url: {"results": [{"id": "uuid-1", "fault_id": 10}], "links": {}},
+ }
+
+ _, session, _ = _run(
+ routes,
+ "notices",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=WATERMARK,
+ incremental_field="created_at",
+ )
+
+ assert faults_url in session.calls
+ assert notices_url in session.calls
+
+ def test_notices_resume_from_fault_bookmark(self) -> None:
+ resume_url = f"{HONEYBADGER_BASE_URL}/projects/1/faults/11/notices?limit=25&page=3"
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 1}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25": {"results": [{"id": 10}, {"id": 11}], "links": {}},
+ resume_url: {"results": [{"id": "uuid-2", "fault_id": 11}], "links": {}},
+ }
+
+ batches, session, _ = _run(
+ routes,
+ "notices",
+ manager=_make_manager(HoneybadgerResumeConfig(next_url=resume_url, project_id=1, fault_id=11)),
+ )
+
+ # Fault 10 is skipped; fault 11 resumes at its saved page URL.
+ assert f"{HONEYBADGER_BASE_URL}/projects/1/faults/10/notices?limit=25" not in session.calls
+ assert batches == [[{"project_id": 1, "id": "uuid-2", "fault_id": 11}]]
+
+ def test_notices_discards_saved_url_when_bookmarked_fault_vanished(self) -> None:
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 1}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25": {"results": [{"id": 10}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/1/faults/10/notices?limit=25": {
+ "results": [{"id": "uuid-1", "fault_id": 10}],
+ "links": {},
+ },
+ }
+
+ batches, session, _ = _run(
+ routes,
+ "notices",
+ manager=_make_manager(
+ HoneybadgerResumeConfig(next_url="https://app.honeybadger.io/stale", project_id=1, fault_id=99)
+ ),
+ )
+
+ # The stale fault's page URL must not seed another fault's pagination.
+ assert "https://app.honeybadger.io/stale" not in session.calls
+ assert batches == [[{"project_id": 1, "id": "uuid-1", "fault_id": 10}]]
+
+ def test_mid_fault_checkpoint_saved_after_yield(self) -> None:
+ next_url = f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25&page=2"
+ routes = {
+ f"{HONEYBADGER_BASE_URL}/projects?limit=25": {"results": [{"id": 1}], "links": {}},
+ f"{HONEYBADGER_BASE_URL}/projects/1/faults?limit=25": {
+ "results": [{"id": 10, "project_id": 1}],
+ "links": {"next": next_url},
+ },
+ next_url: {"results": [{"id": 11, "project_id": 1}], "links": {}},
+ }
+ manager = _make_manager()
+ session = FakeSession(routes)
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.honeybadger._make_session",
+ return_value=session,
+ ):
+ rows = get_rows(api_key="token", endpoint="faults", logger=MagicMock(), resumable_source_manager=manager)
+ # State is only saved AFTER the first batch is yielded (it runs when the consumer
+ # pulls again), so a crash re-yields the batch instead of skipping it.
+ next(rows)
+ manager.save_state.assert_not_called()
+ next(rows)
+ manager.save_state.assert_called_once_with(HoneybadgerResumeConfig(next_url=next_url, project_id=1))
+ list(rows)
+
+ @pytest.mark.parametrize(
+ ("endpoint", "expected_primary_keys", "expected_partition_keys"),
+ [
+ ("projects", ["id"], None),
+ ("faults", ["project_id", "id"], ["created_at"]),
+ ("notices", ["id"], ["created_at"]),
+ ("deploys", ["project_id", "id"], ["created_at"]),
+ ("sites", ["project_id", "id"], None),
+ ],
+ )
+ def test_source_response_shape(
+ self, endpoint: str, expected_primary_keys: list[str], expected_partition_keys: list[str] | None
+ ) -> None:
+ response = honeybadger_source(
+ api_key="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(spec=ResumableSourceManager),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == expected_primary_keys
+ assert response.sort_mode == "desc"
+ assert response.partition_keys == expected_partition_keys
+ assert response.partition_mode == ("datetime" if expected_partition_keys else None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/tests/test_honeybadger_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/tests/test_honeybadger_source.py
new file mode 100644
index 000000000000..32e86e5d4d38
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeybadger/tests/test_honeybadger_source.py
@@ -0,0 +1,180 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+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 HoneybadgerSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.honeybadger import (
+ HoneybadgerResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.source import HoneybadgerSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "faults",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestHoneybadgerSource:
+ def setup_method(self) -> None:
+ self.source = HoneybadgerSource()
+ self.team_id = 123
+ self.config = HoneybadgerSourceConfig(api_key="test-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.HONEYBADGER
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Honeybadger"
+ assert config.label == "Honeybadger"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/honeybadger.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/honeybadger"
+
+ assert len(config.fields) == 1
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ [
+ "401 Client Error: Unauthorized for url: https://app.honeybadger.io",
+ "403 Client Error: Forbidden for url: https://app.honeybadger.io",
+ ],
+ )
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_names_and_sync_support(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+
+ for endpoint in ("faults", "notices", "deploys"):
+ assert schemas[endpoint].supports_incremental is True
+ assert schemas[endpoint].supports_append is True
+ assert len(schemas[endpoint].incremental_fields) > 0
+
+ for endpoint in ("projects", "sites"):
+ assert schemas[endpoint].supports_incremental is False
+ assert schemas[endpoint].supports_append is False
+ assert schemas[endpoint].incremental_fields == []
+
+ def test_notices_are_opt_in_by_default(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ # Notices fan out one request per fault against a 360 req/hour quota, so they must
+ # not be part of the default table selection.
+ assert schemas["notices"].should_sync_default is False
+ assert all(schema.should_sync_default for name, schema in schemas.items() if name != "notices")
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["faults"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "faults"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # The public docs table catalog must build from the static endpoint list with no I/O.
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ (True, True, None),
+ (False, False, "Invalid Honeybadger authentication token"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.source.validate_honeybadger_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: bool,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key)
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is HoneybadgerResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.source.honeybadger_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ logger = mock.MagicMock()
+ inputs = _make_inputs(
+ schema_name="deploys",
+ logger=logger,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-01-01T00:00:00Z",
+ incremental_field="created_at",
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ api_key="test-token",
+ endpoint="deploys",
+ logger=logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-01-01T00:00:00Z",
+ incremental_field="created_at",
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.honeybadger.source.honeybadger_source"
+ )
+ def test_source_for_pipeline_drops_cursor_when_not_incremental(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="2024-01-01T00:00:00Z",
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None