:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement firehydrant import source (#66744)
Tom Owers081628091360
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ad7598147554..f6a5d33cf263 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -145,6 +145,7 @@ the row lists both.| finnhub | HTTP | requests | ✅ || finnworlds | HTTP | requests | ✅ || fleetio | HTTP | requests | ✅ |+| firehydrant | HTTP | requests | ✅ || front | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ || github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |@@ -399,7 +400,6 @@ doesn't conflict with concurrent PRs.- finage- firebase- firebolt-- firehydrant- flexmail- flexport- float_appdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/api_inventory.mdnew file mode 100644index 000000000000..5dfaa8f4d43c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/api_inventory.md@@ -0,0 +1,44 @@+# FireHydrant API inventory++Source: <https://docs.firehydrant.com/reference/firehydrant-api> and the official OpenAPI spec+(<https://raw.githubusercontent.com/firehydrant/firehydrant-typescript-sdk/main/openapi.yaml>).++- **Base URL:** `https://api.firehydrant.io/` (EU: `https://api.eu.firehydrant.io/`). Endpoints live under `/v1/`.+- **Auth:** `Authorization: Bearer <api_key>` (bot token or personal API key). Keys default to Owner-level scope.+- **Pagination:** `?page=<n>&per_page=<n>` (`per_page` max 200). Responses are `{ "data": [...], "pagination": { "count", "page", "items", "pages", "last", "prev", "next" } }`. `pagination.next` is the next page number, or null on the last page. A few endpoints return a single unpaginated response.+- **Rate limit:** 50 requests / 10 s per account (~300/min). 429 responses carry a `Retry-After` header.+- **Incremental:** No uniform server-side `updated_after` cursor across resources. `/v1/incidents` accepts `created_at_or_after` / `updated_after` filters, but these could not be curl-verified without live credentials, so all endpoints ship full refresh (matching Airbyte's connector).++## Endpoints implemented++| Schema name | Path | Primary key | Partition key (created_at?) |+| ------------------------ | ------------------------------- | ----------- | ------------------------------- |+| incidents | `/v1/incidents` | id | created_at |+| alerts | `/v1/alerts` | id | — (no created_at) |+| changes | `/v1/changes` | id | created_at |+| change_events | `/v1/changes/events` | id | created_at |+| environments | `/v1/environments` | id | created_at |+| functionalities | `/v1/functionalities` | id | created_at |+| services | `/v1/services` | id | created_at |+| teams | `/v1/teams` | id | created_at |+| users | `/v1/users` | id | created_at |+| incident_roles | `/v1/incident_roles` | id | created_at |+| incident_types | `/v1/incident_types` | id | created_at |+| incident_tags | `/v1/incident_tags` | name | — (only `name`) |+| priorities | `/v1/priorities` | slug | created_at |+| severities | `/v1/severities` | slug | created_at |+| custom_field_definitions | `/v1/custom_fields/definitions` | field_id | — (no created_at) |+| integrations | `/v1/integrations` | id | created_at |+| runbooks | `/v1/runbooks` | id | created_at |+| runbook_executions | `/v1/runbooks/executions` | id | created_at |+| webhooks | `/v1/webhooks` | id | created_at |+| signals_on_call | `/v1/signals_on_call` | id | — (undocumented response shape) |+| post_mortem_reports | `/v1/post_mortems/reports` | id | created_at |+| scheduled_maintenances | `/v1/scheduled_maintenances` | id | created_at |+| task_lists | `/v1/task_lists` | id | created_at |+| checklist_templates | `/v1/checklist_templates` | id | created_at |++## Future enhancements++- Incremental sync on `/v1/incidents` via `created_at_or_after` / `updated_after` once the filter behavior and default sort order can be curl-verified against a live account.+- Webhook ingestion: FireHydrant exposes programmatic webhook management (`/v1/webhooks`), so a `WebhookSource` layer could deliver incident/alert deltas event-driven.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/canonical_descriptions.pynew file mode 100644index 000000000000..fd4eea37393b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/canonical_descriptions.py@@ -0,0 +1,241 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Curated table/column descriptions sourced from the FireHydrant API docs+# (https://docs.firehydrant.com/reference/firehydrant-api). Keys are the endpoint/schema names+# returned by `get_schemas`. Partial coverage is fine — anything not listed falls back to LLM+# enrichment with the docs_url as context.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "incidents": {+ "description": "Incidents declared in FireHydrant, including their lifecycle, severity, impact, and assignments.",+ "docs_url": "https://docs.firehydrant.com/reference/list_incidents",+ "columns": {+ "id": "UUID of the incident.",+ "name": "Name of the incident.",+ "number": "Sequential incident number.",+ "summary": "Short summary of the incident.",+ "description": "Detailed description of the incident.",+ "current_milestone": "Slug of the incident's current lifecycle milestone.",+ "severity": "Severity assigned to the incident.",+ "priority": "Priority assigned to the incident.",+ "created_at": "The time the incident was opened.",+ "started_at": "The time the incident started.",+ "discarded_at": "The time the incident was archived, if any.",+ "incident_url": "URL of the incident in FireHydrant.",+ },+ },+ "alerts": {+ "description": "Alerts ingested by FireHydrant, including Signals alerts and third-party alerts.",+ "docs_url": "https://docs.firehydrant.com/reference/list_alerts",+ "columns": {+ "id": "UUID of the alert.",+ "summary": "Summary of the alert.",+ "description": "Description of the alert.",+ "status": "Current status of the alert.",+ "priority": "Priority of the alert.",+ "started_at": "The time the alert started.",+ "ended_at": "The time the alert ended, if any.",+ },+ },+ "changes": {+ "description": "Changes tracked in FireHydrant that may be correlated with incidents.",+ "docs_url": "https://docs.firehydrant.com/reference/list_changes",+ "columns": {+ "id": "UUID of the change.",+ "created_at": "The time the change record was created.",+ "updated_at": "The time the change record was last updated.",+ },+ },+ "change_events": {+ "description": "Discrete change events (e.g. deploys) recorded in FireHydrant.",+ "docs_url": "https://docs.firehydrant.com/reference/list_change_events",+ "columns": {+ "id": "UUID of the change event.",+ "summary": "Summary of the change event.",+ "starts_at": "The time the change event started.",+ "ends_at": "The time the change event ended.",+ "created_at": "The time the change event was created.",+ },+ },+ "environments": {+ "description": "Environments (e.g. production, staging) defined in your FireHydrant catalog.",+ "docs_url": "https://docs.firehydrant.com/reference/list_environments",+ "columns": {+ "id": "UUID of the environment.",+ "name": "Name of the environment.",+ "slug": "URL-friendly identifier for the environment.",+ "created_at": "The time the environment was created.",+ },+ },+ "functionalities": {+ "description": "Functionalities (capabilities your product provides) defined in your FireHydrant catalog.",+ "docs_url": "https://docs.firehydrant.com/reference/list_functionalities",+ "columns": {+ "id": "UUID of the functionality.",+ "name": "Name of the functionality.",+ "slug": "URL-friendly identifier for the functionality.",+ "created_at": "The time the functionality was created.",+ },+ },+ "services": {+ "description": "Services in your FireHydrant service catalog.",+ "docs_url": "https://docs.firehydrant.com/reference/list_services",+ "columns": {+ "id": "UUID of the service.",+ "name": "Name of the service.",+ "slug": "URL-friendly identifier for the service.",+ "created_at": "The time the service was created.",+ },+ },+ "teams": {+ "description": "Teams configured in FireHydrant.",+ "docs_url": "https://docs.firehydrant.com/reference/list_teams",+ "columns": {+ "id": "UUID of the team.",+ "name": "Name of the team.",+ "slug": "URL-friendly identifier for the team.",+ "created_at": "The time the team was created.",+ },+ },+ "users": {+ "description": "Users in your FireHydrant organization.",+ "docs_url": "https://docs.firehydrant.com/reference/list_users",+ "columns": {+ "id": "UUID of the user.",+ "name": "Name of the user.",+ "email": "Email address of the user.",+ "created_at": "The time the user was created.",+ },+ },+ "incident_roles": {+ "description": "Incident roles (e.g. Incident Commander) defined in FireHydrant.",+ "docs_url": "https://docs.firehydrant.com/reference/list_incident_roles",+ "columns": {+ "id": "UUID of the incident role.",+ "name": "Name of the incident role.",+ "created_at": "The time the incident role was created.",+ },+ },+ "incident_types": {+ "description": "Incident types that pre-fill incident attributes when declared.",+ "docs_url": "https://docs.firehydrant.com/reference/list_incident_types",+ "columns": {+ "id": "UUID of the incident type.",+ "name": "Name of the incident type.",+ "created_at": "The time the incident type was created.",+ },+ },+ "incident_tags": {+ "description": "Tags that can be applied to incidents.",+ "docs_url": "https://docs.firehydrant.com/reference/list_incident_tags",+ "columns": {+ "name": "Name of the tag (its unique identifier).",+ },+ },+ "priorities": {+ "description": "Incident priorities (e.g. P1, P2) defined in FireHydrant.",+ "docs_url": "https://docs.firehydrant.com/reference/list_priorities",+ "columns": {+ "slug": "Unique slug for the priority (e.g. P1).",+ "description": "Description of the priority.",+ "position": "Ordering position of the priority.",+ "created_at": "The time the priority was created.",+ },+ },+ "severities": {+ "description": "Incident severities defined in FireHydrant.",+ "docs_url": "https://docs.firehydrant.com/reference/list_severities",+ "columns": {+ "slug": "Unique slug for the severity (e.g. SEV1).",+ "description": "Description of the severity.",+ "position": "Ordering position of the severity.",+ "color": "Display color for the severity.",+ "created_at": "The time the severity was created.",+ },+ },+ "custom_field_definitions": {+ "description": "Definitions of the custom fields available on incidents.",+ "docs_url": "https://docs.firehydrant.com/reference/list_custom_fields_definitions",+ "columns": {+ "field_id": "Unique identifier for the custom field definition.",+ "slug": "URL-friendly identifier for the custom field.",+ },+ },+ "integrations": {+ "description": "Integrations connected to your FireHydrant organization.",+ "docs_url": "https://docs.firehydrant.com/reference/list_integrations",+ "columns": {+ "id": "UUID of the integration.",+ "created_at": "The time the integration was created.",+ },+ },+ "runbooks": {+ "description": "Runbooks that automate incident response steps.",+ "docs_url": "https://docs.firehydrant.com/reference/list_runbooks",+ "columns": {+ "id": "UUID of the runbook.",+ "name": "Name of the runbook.",+ "created_at": "The time the runbook was created.",+ },+ },+ "runbook_executions": {+ "description": "Executions of runbooks against incidents.",+ "docs_url": "https://docs.firehydrant.com/reference/list_runbooks_executions",+ "columns": {+ "id": "UUID of the runbook execution.",+ "created_at": "The time the runbook execution started.",+ },+ },+ "webhooks": {+ "description": "Webhooks configured to receive FireHydrant events.",+ "docs_url": "https://docs.firehydrant.com/reference/list_webhooks",+ "columns": {+ "id": "UUID of the webhook.",+ "created_at": "The time the webhook was created.",+ },+ },+ "signals_on_call": {+ "description": "FireHydrant Signals on-call schedules across the organization.",+ "docs_url": "https://docs.firehydrant.com/reference/list_signals_on_call",+ "columns": {+ "id": "Identifier of the on-call schedule.",+ },+ },+ "post_mortem_reports": {+ "description": "Retrospective (post-mortem) reports generated for incidents.",+ "docs_url": "https://docs.firehydrant.com/reference/list_post_mortems_reports",+ "columns": {+ "id": "UUID of the retrospective report.",+ "name": "Name of the retrospective report.",+ "created_at": "The time the report was created.",+ },+ },+ "scheduled_maintenances": {+ "description": "Scheduled maintenance windows tracked in FireHydrant.",+ "docs_url": "https://docs.firehydrant.com/reference/list_scheduled_maintenances",+ "columns": {+ "id": "UUID of the scheduled maintenance.",+ "name": "Name of the scheduled maintenance.",+ "created_at": "The time the scheduled maintenance was created.",+ },+ },+ "task_lists": {+ "description": "Reusable task lists that can be attached to incidents.",+ "docs_url": "https://docs.firehydrant.com/reference/list_task_lists",+ "columns": {+ "id": "UUID of the task list.",+ "name": "Name of the task list.",+ "created_at": "The time the task list was created.",+ },+ },+ "checklist_templates": {+ "description": "Checklist templates used during incident response.",+ "docs_url": "https://docs.firehydrant.com/reference/list_checklist_templates",+ "columns": {+ "id": "UUID of the checklist template.",+ "name": "Name of the checklist template.",+ "created_at": "The time the checklist template was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/firehydrant.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/firehydrant.pynew file mode 100644index 000000000000..1c7baeef008b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/firehydrant.py@@ -0,0 +1,199 @@+import time+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++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.firehydrant.settings import FIREHYDRANT_ENDPOINTS++# FireHydrant accounts are region-pinned: US accounts live on api.firehydrant.io, EU accounts on the+# data-residency host. The stored API key only authenticates against its own region's host.+BASE_URLS: dict[str, str] = {+ "us": "https://api.firehydrant.io",+ "eu": "https://api.eu.firehydrant.io",+}+DEFAULT_REGION = "us"+# FireHydrant caps per_page at 200. 100 keeps each response comfortably small while halving the+# request count versus the default page size.+PAGE_SIZE = 100+# Cap how long we'll honor a Retry-After before falling back to tenacity's own backoff.+MAX_RETRY_AFTER_SECONDS = 60+++class FireHydrantRetryableError(Exception):+ """Raised for transient FireHydrant API failures (429 / 5xx) that should be retried."""+++class FireHydrantResumeConfig:+ # The next 1-indexed page to fetch. FireHydrant paginates with `page` / `per_page` query params and+ # returns a `pagination.next` page number (or null) in each response body.+ next_page: int+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def base_url_for_region(region: str | None) -> str:+ return BASE_URLS.get((region or DEFAULT_REGION).lower(), BASE_URLS[DEFAULT_REGION])+++def _build_url(base_url: str, path: str, page: int) -> str:+ query = urlencode({"page": page, "per_page": PAGE_SIZE})+ return f"{base_url}{path}?{query}"+++def _fetch_page_once(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any] | list[Any]:+ response = session.get(url, headers=headers, timeout=60)++ if response.status_code == 429:+ # FireHydrant returns a Retry-After header when the 50-req/10s account limit is exceeded.+ # Honor it (bounded), then raise so tenacity retries.+ retry_after = response.headers.get("Retry-After")+ delay = min(int(retry_after), MAX_RETRY_AFTER_SECONDS) if retry_after and retry_after.isdigit() else 1+ logger.warning(f"FireHydrant rate limited (429): sleeping {delay}s before retry, url={url}")+ time.sleep(delay)+ raise FireHydrantRetryableError(f"FireHydrant rate limited: url={url}")++ if response.status_code >= 500:+ raise FireHydrantRetryableError(f"FireHydrant API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Don't log the raw body on auth failures — keep it out of job logs in case the API echoes+ # anything sensitive. Other 4xx bodies carry no credentials and are useful for debugging. The+ # url holds only the path and pagination params (the token lives in the Authorization header).+ if response.status_code in (401, 403):+ logger.error(f"FireHydrant auth error: status={response.status_code}, url={url}")+ else:+ logger.error(f"FireHydrant API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++# Retry transport failures and retryable statuses (429 / 5xx) with bounded exponential backoff. The+# core request logic lives in `_fetch_page_once` so it can be unit-tested without tenacity's waits.+_fetch_page = retry(+ retry=retry_if_exception_type((FireHydrantRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)(_fetch_page_once)+++def validate_credentials(api_key: str, region: str | None = None) -> tuple[bool, str | None]:+ """Probe the authenticated ping endpoint to confirm the token is genuine.++ Only a 200 proves the key is real and usable. A 403 means the request reached FireHydrant but the+ token lacks the required permissions — we surface that as a permissions failure rather than+ silently accepting an unverified key (which would let a broken source register as authenticated).+ """+ url = f"{base_url_for_region(region)}/v1/ping"+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=10)+ except Exception:+ return False, "Could not reach the FireHydrant API. Please try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid FireHydrant API key"+ if response.status_code == 403:+ return (+ False,+ "Your FireHydrant API key is missing the permissions needed to access this data. "+ "Grant the required permissions in your FireHydrant settings, then reconnect.",+ )+ return False, f"FireHydrant API returned an unexpected status: {response.status_code}"+++def _extract_items(payload: dict[str, Any] | list[Any]) -> list[dict[str, Any]]:+ """Pull the row list out of a FireHydrant response.++ Paginated endpoints wrap rows in a top-level `data` array; a few endpoints return a bare list or an+ object with no `data` key, so we degrade gracefully rather than assume a single shape.+ """+ if isinstance(payload, list):+ return payload+ data = payload.get("data")+ if isinstance(data, list):+ return data+ return []+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FireHydrantResumeConfig],+ region: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = FIREHYDRANT_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ base_url = base_url_for_region(region)+ # One session reused across every page so urllib3 keeps the connection alive instead of+ # re-handshaking per request. Redact the token so it never lands in logged URLs or HTTP samples.+ # `retry=Retry(total=0)` disables the adapter's own retries so tenacity is the single retry+ # authority — otherwise adapter and tenacity backoffs would stack and could bypass the+ # `MAX_RETRY_AFTER_SECONDS` cap on `Retry-After`.+ session = make_tracked_session(retry=Retry(total=0), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else 1++ while True:+ payload = _fetch_page(session, _build_url(base_url, config.path, page), headers, logger)+ items = _extract_items(payload)+ if items:+ yield items++ pagination = payload.get("pagination", {}) if isinstance(payload, dict) else {}+ next_page = pagination.get("next")+ if not next_page:+ break++ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge+ # dedupes the re-pulled rows on the primary key.+ resumable_source_manager.save_state(FireHydrantResumeConfig(next_page=next_page))+ page = next_page+++def firehydrant_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FireHydrantResumeConfig],+ region: str | None = None,+) -> SourceResponse:+ config = FIREHYDRANT_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ region=region,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/settings.pynew file mode 100644index 000000000000..f66ccfe81d97--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/settings.py@@ -0,0 +1,62 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class FireHydrantEndpointConfig:+ path: str+ # Field to partition by. Must be a STABLE creation timestamp (never updated_at), and only set+ # when the endpoint's entity actually returns it — several FireHydrant resources don't.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ should_sync_default: bool = True+++# Endpoint catalog. Paths are the FireHydrant v1 REST collection endpoints (verified against the+# official OpenAPI spec). Every endpoint is full refresh only: FireHydrant exposes no uniform+# server-side `updated_after` cursor across resources, so we don't advertise incremental fields here+# (matching Airbyte's connector, which is also full-refresh only). `/v1/incidents` does accept+# `created_at_or_after` / `updated_after` filters, but we couldn't curl-verify they actually filter+# (no live credentials), so incremental sync for incidents is left as a future enhancement.+FIREHYDRANT_ENDPOINTS: dict[str, FireHydrantEndpointConfig] = {+ "incidents": FireHydrantEndpointConfig(path="/v1/incidents", partition_key="created_at"),+ "alerts": FireHydrantEndpointConfig(path="/v1/alerts"),+ "changes": FireHydrantEndpointConfig(path="/v1/changes", partition_key="created_at"),+ "change_events": FireHydrantEndpointConfig(path="/v1/changes/events", partition_key="created_at"),+ "environments": FireHydrantEndpointConfig(path="/v1/environments", partition_key="created_at"),+ "functionalities": FireHydrantEndpointConfig(path="/v1/functionalities", partition_key="created_at"),+ "services": FireHydrantEndpointConfig(path="/v1/services", partition_key="created_at"),+ "teams": FireHydrantEndpointConfig(path="/v1/teams", partition_key="created_at"),+ "users": FireHydrantEndpointConfig(path="/v1/users", partition_key="created_at"),+ "incident_roles": FireHydrantEndpointConfig(path="/v1/incident_roles", partition_key="created_at"),+ "incident_types": FireHydrantEndpointConfig(path="/v1/incident_types", partition_key="created_at"),+ # TagEntity only carries `name`; it has no id or created_at, so the name is the natural key.+ "incident_tags": FireHydrantEndpointConfig(path="/v1/incident_tags", primary_keys=["name"]),+ # PriorityEntity / SeverityEntity are keyed by their human-readable slug, not a UUID.+ "priorities": FireHydrantEndpointConfig(path="/v1/priorities", primary_keys=["slug"], partition_key="created_at"),+ "severities": FireHydrantEndpointConfig(path="/v1/severities", primary_keys=["slug"], partition_key="created_at"),+ "custom_field_definitions": FireHydrantEndpointConfig(+ path="/v1/custom_fields/definitions", primary_keys=["field_id"]+ ),+ "integrations": FireHydrantEndpointConfig(path="/v1/integrations", partition_key="created_at"),+ "runbooks": FireHydrantEndpointConfig(path="/v1/runbooks", partition_key="created_at"),+ "runbook_executions": FireHydrantEndpointConfig(path="/v1/runbooks/executions", partition_key="created_at"),+ "webhooks": FireHydrantEndpointConfig(path="/v1/webhooks", partition_key="created_at"),+ # Undocumented response shape in the spec; handled defensively in transport. No created_at to partition on.+ "signals_on_call": FireHydrantEndpointConfig(path="/v1/signals_on_call"),+ "post_mortem_reports": FireHydrantEndpointConfig(path="/v1/post_mortems/reports", partition_key="created_at"),+ "scheduled_maintenances": FireHydrantEndpointConfig(path="/v1/scheduled_maintenances", partition_key="created_at"),+ "task_lists": FireHydrantEndpointConfig(path="/v1/task_lists", partition_key="created_at"),+ "checklist_templates": FireHydrantEndpointConfig(path="/v1/checklist_templates", partition_key="created_at"),+}++ENDPOINTS = tuple(FIREHYDRANT_ENDPOINTS.keys())++# Every endpoint is full refresh only — no advertised incremental options. Kept as an explicit map so+# the source class and tests can reason about it the same way as other sources.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FIREHYDRANT_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/source.pyindex 77a7a2d1b1e6..bf13a80ce4ee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/source.py@@ -1,30 +1,158 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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.firehydrant.firehydrant import (+ BASE_URLS,+ FireHydrantResumeConfig,+ firehydrant_source,+ validate_credentials as validate_firehydrant_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.settings import (+ ENDPOINTS,+ FIREHYDRANT_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FireHydrantSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FireHydrantSource(SimpleSource[FireHydrantSourceConfig]):+class FireHydrantSource(ResumableSource[FireHydrantSourceConfig, FireHydrantResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FIREHYDRANT+ @property+ def connection_host_fields(self) -> list[str]:+ # `region` picks the host the stored API key is sent to. Retargeting it must re-require the+ # secret so a preserved key can't be aimed at a different regional endpoint without re-entry.+ return ["region"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FIRE_HYDRANT,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="FireHydrant",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your FireHydrant API key to pull your incident management data into the PostHog Data warehouse.++You can create a bot token or personal API key in your [FireHydrant API keys settings](https://app.firehydrant.io/organizations/api_keys). Bot tokens are recommended for automation that isn't tied to a specific user.""",iconPath="/static/services/firehydrant.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/firehydrant",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.firehydrant.io)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api.eu.firehydrant.io)", value="eu"),+ ],+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can never satisfy a credential problem, so stop the sync. Match the stable status+ # text and base host, not the per-request path/query. Derive from BASE_URLS so a newly added+ # region stays covered without updating two places.+ unauthorized = "Your FireHydrant API key is invalid or has been revoked. Create a new API key in your FireHydrant settings, then reconnect."+ forbidden = "Your FireHydrant API key is missing the permissions needed to sync this data. Grant the required permissions in your FireHydrant settings, then reconnect."+ errors: dict[str, str | None] = {}+ for base_url in BASE_URLS.values():+ errors[f"401 Client Error: Unauthorized for url: {base_url}"] = unauthorized+ errors[f"403 Client Error: Forbidden for url: {base_url}"] = forbidden+ return errors++ def get_schemas(+ self,+ config: FireHydrantSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = FIREHYDRANT_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ # FireHydrant has no uniform server-side incremental cursor, so every endpoint is+ # full refresh only.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ detected_primary_keys=endpoint_config.primary_keys,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: FireHydrantSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_firehydrant_credentials(config.api_key, config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FireHydrantResumeConfig]:+ return ResumableSourceManager[FireHydrantResumeConfig](inputs, FireHydrantResumeConfig)++ def source_for_pipeline(+ self,+ config: FireHydrantSourceConfig,+ resumable_source_manager: ResumableSourceManager[FireHydrantResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return firehydrant_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ region=config.region,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant.pynew file mode 100644index 000000000000..05169d46bc46--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant.py@@ -0,0 +1,316 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant import firehydrant+from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.firehydrant import (+ PAGE_SIZE,+ FireHydrantResumeConfig,+ _build_url,+ _extract_items,+ base_url_for_region,+ firehydrant_source,+ get_rows,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.settings import (+ ENDPOINTS,+ FIREHYDRANT_ENDPOINTS,+)+++class _FakeResumableManager:+ def __init__(self, state: FireHydrantResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[FireHydrantResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> FireHydrantResumeConfig | None:+ return self._state++ def save_state(self, data: FireHydrantResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[str, Any],+ endpoint: str,+ region: str | None = None,+) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(firehydrant, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for batch in get_rows(+ api_key="fhb_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ region=region,+ ):+ rows.extend(batch)+ return rows+++class TestBuildUrl:+ @parameterized.expand(+ [+ # region -> host: EU accounts are pinned to the data-residency host, so an unknown or+ # missing region must fall back to the US default rather than a wrong host.+ ("default_us", None, "https://api.firehydrant.io"),+ ("us", "us", "https://api.firehydrant.io"),+ ("eu", "eu", "https://api.eu.firehydrant.io"),+ ("unknown_falls_back", "apac", "https://api.firehydrant.io"),+ ]+ )+ def test_includes_page_and_per_page(self, _name: str, region: str | None, base_host: str) -> None:+ url = _build_url(base_url_for_region(region), "/v1/incidents", 3)+ assert url == f"{base_host}/v1/incidents?page=3&per_page={PAGE_SIZE}"+++class TestExtractItems:+ @parameterized.expand(+ [+ ("wrapped_data", {"data": [{"id": "1"}], "pagination": {}}, [{"id": "1"}]),+ ("bare_list", [{"id": "1"}, {"id": "2"}], [{"id": "1"}, {"id": "2"}]),+ ("missing_data_key", {"pagination": {}}, []),+ ("data_not_a_list", {"data": {"id": "1"}}, []),+ ]+ )+ def test_extract_items(self, _name: str, payload: Any, expected: list[dict]) -> None:+ assert _extract_items(payload) == expected+++class TestGetRows:+ def test_follows_page_pagination(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.firehydrant.io/v1/incidents?page=1&per_page=100": {+ "data": [{"id": "i1"}, {"id": "i2"}],+ "pagination": {"page": 1, "next": 2, "last": 2},+ },+ "https://api.firehydrant.io/v1/incidents?page=2&per_page=100": {+ "data": [{"id": "i3"}],+ "pagination": {"page": 2, "next": None, "last": 2},+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "incidents")+ assert rows == [{"id": "i1"}, {"id": "i2"}, {"id": "i3"}]++ def test_single_unpaginated_response_terminates(self, monkeypatch: Any) -> None:+ # signals_on_call and similar endpoints may return a single page with no `next`.+ pages = {+ "https://api.firehydrant.io/v1/signals_on_call?page=1&per_page=100": {+ "data": [{"id": "s1"}],+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "signals_on_call")+ assert rows == [{"id": "s1"}]++ def test_state_saved_after_each_page_with_next(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ "https://api.firehydrant.io/v1/services?page=1&per_page=100": {+ "data": [{"id": "a"}],+ "pagination": {"next": 2},+ },+ "https://api.firehydrant.io/v1/services?page=2&per_page=100": {+ "data": [{"id": "b"}],+ "pagination": {"next": 3},+ },+ "https://api.firehydrant.io/v1/services?page=3&per_page=100": {+ "data": [{"id": "c"}],+ "pagination": {"next": None},+ },+ }+ _collect(manager, monkeypatch, pages, "services")+ # State saved only when a next page exists — not after the final page.+ assert [s.next_page for s in manager.saved] == [2, 3]++ def test_region_routes_requests_to_eu_host(self, monkeypatch: Any) -> None:+ # EU accounts only answer on the data-residency host; if get_rows ignored region it would hit+ # the US host and every EU sync would fail.+ pages = {+ "https://api.eu.firehydrant.io/v1/incidents?page=1&per_page=100": {+ "data": [{"id": "eu1"}],+ "pagination": {"next": None},+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "incidents", region="eu")+ assert rows == [{"id": "eu1"}]++ def test_resume_from_saved_state(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(FireHydrantResumeConfig(next_page=2))+ pages = {+ "https://api.firehydrant.io/v1/services?page=2&per_page=100": {+ "data": [{"id": "b"}],+ "pagination": {"next": None},+ },+ }+ rows = _collect(manager, monkeypatch, pages, "services")+ # Resumes at page 2 (page 1 is never requested), proving the saved cursor is honored.+ assert rows == [{"id": "b"}]+++class TestFireHydrantSource:+ @parameterized.expand(list(ENDPOINTS))+ def test_source_response_matches_endpoint_config(self, endpoint: str) -> None:+ config = FIREHYDRANT_ENDPOINTS[endpoint]+ response = firehydrant_source(+ api_key="fhb_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_partition_keys_are_stable_creation_fields(self) -> None:+ # A partition key that changes (updated_at/lastSeen) rewrites partitions every sync.+ for config in FIREHYDRANT_ENDPOINTS.values():+ if config.partition_key:+ assert config.partition_key == "created_at"++ @parameterized.expand(+ [+ ("priorities", ["slug"]),+ ("severities", ["slug"]),+ ("incident_tags", ["name"]),+ ("custom_field_definitions", ["field_id"]),+ ("incidents", ["id"]),+ ]+ )+ def test_endpoint_specific_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:+ assert FIREHYDRANT_ENDPOINTS[endpoint].primary_keys == expected_keys+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ # Only a 200 proves the key is real and usable — a 403 means it reached FireHydrant but+ # lacks permissions, so we reject it rather than register an unverified credential.+ ("forbidden_rejected", 403, False),+ ("unauthorized", 401, False),+ ("unexpected", 500, False),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected_valid: bool) -> None:+ response = requests.Response()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response++ with patch.object(firehydrant, "make_tracked_session", lambda *a, **k: session):+ valid, _error = firehydrant.validate_credentials("fhb_test")+ assert valid is expected_valid++ def test_network_error_is_invalid(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(firehydrant, "make_tracked_session", lambda *a, **k: session)++ valid, error = firehydrant.validate_credentials("fhb_test")+ assert valid is False+ assert error is not None++ @parameterized.expand(+ [+ ("default_us", None, "https://api.firehydrant.io/v1/ping"),+ ("eu", "eu", "https://api.eu.firehydrant.io/v1/ping"),+ ]+ )+ def test_probes_region_host(self, _name: str, region: str | None, expected_url: str) -> None:+ # The key is only valid against its own region's host, so validation must probe there.+ response = requests.Response()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response++ with patch.object(firehydrant, "make_tracked_session", lambda *a, **k: session):+ firehydrant.validate_credentials("fhb_test", region=region)+ assert session.get.call_args.args[0] == expected_url+++class TestCredentialRedaction:+ """The token must be registered for redaction so it can't leak into logged URLs or HTTP samples."""++ def test_validate_credentials_redacts_api_key(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_session(*args: Any, **kwargs: Any) -> MagicMock:+ captured.update(kwargs)+ response = requests.Response()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response+ return session++ monkeypatch.setattr(firehydrant, "make_tracked_session", fake_session)+ firehydrant.validate_credentials("fhb_secret")+ assert captured.get("redact_values") == ("fhb_secret",)++ def test_get_rows_redacts_api_key(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_session(*args: Any, **kwargs: Any) -> MagicMock:+ captured.update(kwargs)+ return MagicMock()++ monkeypatch.setattr(firehydrant, "make_tracked_session", fake_session)+ monkeypatch.setattr(firehydrant, "_fetch_page", lambda *a, **k: {"data": [], "pagination": {}})++ list(+ get_rows(+ api_key="fhb_secret",+ endpoint="incidents",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert captured.get("redact_values") == ("fhb_secret",)+++class TestFetchPageRetries:+ def _session_returning(self, status_code: int, headers: dict[str, str] | None = None) -> MagicMock:+ response = requests.Response()+ response.status_code = status_code+ response.headers.update(headers or {})+ session = MagicMock()+ session.get.return_value = response+ return session++ # Tested through `_fetch_page_once` (the undecorated core) so tenacity's waits don't run.+ _URL = "https://api.firehydrant.io/v1/incidents?page=1&per_page=100"++ def test_rate_limit_honors_retry_after_then_raises_retryable(self, monkeypatch: Any) -> None:+ slept: list[int] = []+ monkeypatch.setattr(firehydrant.time, "sleep", lambda s: slept.append(s))+ session = self._session_returning(429, {"Retry-After": "7"})++ with pytest.raises(firehydrant.FireHydrantRetryableError):+ firehydrant._fetch_page_once(session, self._URL, {}, MagicMock())++ assert slept == [7]++ def test_server_error_is_retryable(self) -> None:+ session = self._session_returning(503)+ with pytest.raises(firehydrant.FireHydrantRetryableError):+ firehydrant._fetch_page_once(session, self._URL, {}, MagicMock())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant_source.pynew file mode 100644index 000000000000..70736c278906--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant_source.py@@ -0,0 +1,169 @@+from typing import Any++from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.firehydrant import (+ FireHydrantResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.settings import (+ ENDPOINTS,+ FIREHYDRANT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.source import FireHydrantSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config() -> Any:+ return MagicMock(api_key="fhb_test", region="us")+++class TestFireHydrantSourceConfig:+ def test_source_type(self) -> None:+ assert FireHydrantSource().source_type == ExternalDataSourceType.FIREHYDRANT++ def test_get_source_config_basics(self) -> None:+ config = FireHydrantSource().get_source_config+ assert config.label == "FireHydrant"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/firehydrant"+ # A finished source must not be hidden behind the unreleased flag.+ assert not config.unreleasedSource++ def test_api_key_field_is_secret_password(self) -> None:+ fields = FireHydrantSource().get_source_config.fields+ api_key = fields[0]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.name == "api_key"+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.required is True+ assert api_key.secret is True++ def test_region_field_offers_us_and_eu(self) -> None:+ # EU accounts are region-pinned; a missing EU option would leave those customers unable to+ # connect. Region is also a connection-host field so retargeting re-requires the key.+ region = next(f for f in FireHydrantSource().get_source_config.fields if isinstance(f, SourceFieldSelectConfig))+ assert region.name == "region"+ assert {o.value for o in region.options} == {"us", "eu"}+ assert region.defaultValue == "us"+ assert FireHydrantSource().connection_host_fields == ["region"]++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static catalog with no I/O, so the public docs table catalog can render.+ assert FireHydrantSource.lists_tables_without_credentials is True+++class TestGetSchemas:+ def test_returns_every_endpoint_full_refresh_only(self) -> None:+ schemas = FireHydrantSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False++ def test_detected_primary_keys_match_settings(self) -> None:+ schemas = {s.name: s for s in FireHydrantSource().get_schemas(_config(), team_id=1)}+ for name, config in FIREHYDRANT_ENDPOINTS.items():+ assert schemas[name].detected_primary_keys == config.primary_keys++ def test_names_filter(self) -> None:+ schemas = FireHydrantSource().get_schemas(_config(), team_id=1, names=["incidents", "services"])+ assert {s.name for s in schemas} == {"incidents", "services"}++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = FireHydrantSource().get_documented_tables()+ by_name = {t["name"]: t for t in tables}+ assert set(by_name) == set(ENDPOINTS)+ # Canonical descriptions are surfaced and full refresh is always an available method.+ assert by_name["incidents"]["description"]+ assert "Full refresh" in by_name["incidents"]["sync_methods"]+ assert by_name["priorities"]["primary_keys"] == ["slug"]+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.firehydrant.io/v1/incidents?page=1&per_page=100",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.firehydrant.io/v1/runbooks?page=1&per_page=100",+ ),+ (+ "unauthorized_eu",+ "401 Client Error: Unauthorized for url: https://api.eu.firehydrant.io/v1/incidents?page=1&per_page=100",+ ),+ (+ "forbidden_eu",+ "403 Client Error: Forbidden for url: https://api.eu.firehydrant.io/v1/runbooks?page=1&per_page=100",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = FireHydrantSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.firehydrant.io', port=443): Read timed out."),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.firehydrant.io/v1/incidents",+ ),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = FireHydrantSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestResumableWiring:+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock(team_id=1, job_id="job-1", logger=MagicMock())+ manager = FireHydrantSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is FireHydrantResumeConfig++ def test_source_for_pipeline_plumbs_api_key_and_schema(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_source(**kwargs: Any) -> str:+ captured.update(kwargs)+ return "sentinel"++ import products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.source as source_module++ monkeypatch.setattr(source_module, "firehydrant_source", fake_source)++ manager = MagicMock()+ inputs = MagicMock(schema_name="incidents", logger=MagicMock())+ result: Any = FireHydrantSource().source_for_pipeline(_config(), manager, inputs)++ assert result == "sentinel"+ assert captured["api_key"] == "fhb_test"+ assert captured["endpoint"] == "incidents"+ assert captured["resumable_source_manager"] is manager+ assert captured["region"] == "us"+++class TestValidateCredentials:+ def test_delegates_to_transport(self, monkeypatch: Any) -> None:+ import products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.source as source_module++ monkeypatch.setattr(source_module, "validate_firehydrant_credentials", lambda key, region=None: (True, None))+ valid, error = FireHydrantSource().validate_credentials(_config(), team_id=1)+ assert valid is True+ assert error is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 08a95d1c4f80..7a48804f0072 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@@ -1175,7 +1175,8 @@ class FinnworldsSourceConfig(config.Config):@config.configclass FireHydrantSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")@config.config