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 bunny import source (#66728)

Tom Owers9dc4343707e5
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 1429c6dccbb4..39ae36944b9a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -74,6 +74,7 @@ the row lists both.
| bugsnag | HTTP | requests | ✅ |
| buildbetter | HTTP | requests | ✅ |
| buildkite | HTTP | requests | ✅ |
+| bunny | HTTP | requests | ✅ |
| buzzsprout | HTTP | requests | ✅ |
| calendly | HTTP | requests | ✅ |
| campaign_monitor | HTTP | requests | ✅ |
@@ -332,7 +333,6 @@ doesn't conflict with concurrent PRs.
- braintrust
- branch
- breezy_hr
-- bunny
- cal_com
- callrail
- campaign_manager_360
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/bunny.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/bunny.py
new file mode 100644
index 000000000000..edb475394008
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/bunny.py
@@ -0,0 +1,147 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+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.bunny.settings import BUNNY_ENDPOINTS
+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
+
+BUNNY_BASE_URL = "https://api.bunny.net"
+# The list endpoints accept perPage 5..1000; 1000 minimises round trips for the typically small
+# zone/library tables.
+PER_PAGE = 1000
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an account API key is genuine. The AccessKey is account-wide, so
+# one probe validates access to every Core API list endpoint.
+DEFAULT_PROBE_PATH = "/pullzone"
+
+
+class BunnyRetryableError(Exception):
+ pass
+
+
+class BunnyResumeConfig:
+ # Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed
+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `Id`.
+ next_page: int = 1
+
+
+def _headers(access_key: str) -> dict[str, str]:
+ return {"AccessKey": access_key, "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((BunnyRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ page: int,
+ per_page: int,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ # Always request page>=1 so the API returns the paginated envelope
+ # ({Items, CurrentPage, TotalItems, HasMoreItems}); page=0 would return a bare array.
+ response = session.get(
+ f"{BUNNY_BASE_URL}{path}",
+ params={"page": page, "perPage": per_page},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BunnyRetryableError(f"bunny.net API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"bunny.net API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ access_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BunnyResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = BUNNY_ENDPOINTS[endpoint]
+ # `redact_values` masks the account key in logged URLs and captured samples.
+ session = make_tracked_session(headers=_headers(access_key), redact_values=(access_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.next_page if resume else 1
+ if resume and resume.next_page > 1:
+ logger.debug(f"bunny.net: resuming {endpoint} from page {page}")
+
+ while True:
+ data = _fetch_page(session, config.path, page, PER_PAGE, logger)
+
+ # `Items` is always present in the paginated envelope; missing it means a malformed
+ # response, so fail loudly rather than silently advancing the cursor past lost rows.
+ items = data["Items"]
+ if items:
+ yield items
+
+ if not data.get("HasMoreItems", False):
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(BunnyResumeConfig(next_page=page))
+
+
+def bunny_source(
+ access_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BunnyResumeConfig],
+) -> SourceResponse:
+ config = BUNNY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_key=access_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def check_access(access_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single list endpoint to validate the account API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise. bunny.net returns clean HTTP status codes
+ (401 for ``Authorization has been denied``), so no body sniffing is needed.
+ """
+ session = make_tracked_session(headers=_headers(access_key), redact_values=(access_key,))
+ try:
+ response = session.get(f"{BUNNY_BASE_URL}{path}", params={"page": 1, "perPage": 5}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to bunny.net: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"bunny.net returned HTTP {response.status_code}"
+
+ return 200, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/canonical_descriptions.py
new file mode 100644
index 000000000000..ea590752e259
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/canonical_descriptions.py
@@ -0,0 +1,74 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the bunny.net Core API docs (https://docs.bunny.net/reference).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "pull_zones": {
+ "description": "A bunny.net pull zone — the CDN configuration that caches and serves content from an origin.",
+ "docs_url": "https://docs.bunny.net/reference/pullzonepublic_index",
+ "columns": {
+ "Id": "The unique ID of the pull zone.",
+ "Name": "The name (and default hostname prefix) of the pull zone.",
+ "OriginUrl": "The origin URL the pull zone pulls content from.",
+ "Enabled": "Whether the pull zone is currently enabled.",
+ "Suspended": "Whether the pull zone has been suspended.",
+ "Hostnames": "The hostnames linked to this pull zone.",
+ "StorageZoneId": "The ID of the storage zone used as the origin, if any.",
+ "MonthlyBandwidthLimit": "The monthly bandwidth limit in bytes (0 = unlimited).",
+ "MonthlyBandwidthUsed": "The amount of bandwidth used this month, in bytes.",
+ "MonthlyCharges": "The total charges accrued for this pull zone this month.",
+ "Type": "The pull zone tier (0 = Standard / Premium, 1 = Volume).",
+ "UserId": "The ID of the account that owns the pull zone.",
+ },
+ },
+ "storage_zones": {
+ "description": "A bunny.net storage zone — replicated edge storage for files served via pull zones.",
+ "docs_url": "https://docs.bunny.net/reference/storagezonepublic_index",
+ "columns": {
+ "Id": "The ID of the storage zone.",
+ "Name": "The name of the storage zone.",
+ "UserId": "The ID of the account that owns the storage zone.",
+ "DateModified": "The date the storage zone was last modified.",
+ "Deleted": "Whether the storage zone has been deleted.",
+ "StorageUsed": "The amount of storage used, in bytes.",
+ "FilesStored": "The number of files stored in the zone.",
+ "Region": "The main storage region code of the zone.",
+ "ReplicationRegions": "The regions the zone is replicated to.",
+ "ZoneTier": "The storage tier (0 = Standard / HDD, 1 = Edge / SSD).",
+ },
+ },
+ "dns_zones": {
+ "description": "A bunny.net DNS zone — a managed domain and its DNS records.",
+ "docs_url": "https://docs.bunny.net/reference/dnszonepublic_index",
+ "columns": {
+ "Id": "The unique ID of the DNS zone.",
+ "Domain": "The domain name managed by this zone.",
+ "Records": "The DNS records configured in the zone.",
+ "DateCreated": "The date the DNS zone was created.",
+ "DateModified": "The date the DNS zone was last modified.",
+ "NameserversDetected": "Whether bunny.net's nameservers have been detected for the domain.",
+ "CustomNameserversEnabled": "Whether custom nameservers are enabled.",
+ "DnsSecEnabled": "Whether DNSSEC is enabled for the zone.",
+ "LoggingEnabled": "Whether DNS query logging is enabled.",
+ },
+ },
+ "video_libraries": {
+ "description": "A bunny.net Stream video library — a container of videos with its own delivery and encoding settings.",
+ "docs_url": "https://docs.bunny.net/reference/videolibrarypublic_index",
+ "columns": {
+ "Id": "The unique ID of the video library.",
+ "Name": "The name of the video library.",
+ "DateCreated": "The date the video library was created.",
+ "VideoCount": "The number of videos in the library.",
+ "TrafficUsage": "The amount of streaming traffic used, in bytes.",
+ "StorageUsage": "The amount of storage used by the library, in bytes.",
+ "ReplicationRegions": "The regions the library is replicated to.",
+ "PullZoneId": "The ID of the pull zone used to deliver the library's content.",
+ "StorageZoneId": "The ID of the storage zone backing the library.",
+ "EnabledResolutions": "The video resolutions enabled for encoding.",
+ "EncodingTier": "The encoding tier configured for the library.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/settings.py
new file mode 100644
index 000000000000..2590a04ef43c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/settings.py
@@ -0,0 +1,26 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+
+@dataclass
+class BunnyEndpointConfig:
+ name: str
+ path: str
+ # bunny.net object IDs are globally unique within an account, so `Id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["Id"])
+ # A stable (never-rewritten) datetime field to partition by. Only set where the object
+ # actually exposes a creation timestamp — never `DateModified`, which changes on every edit.
+ partition_key: Optional[str] = None
+
+
+# bunny.net Core API list endpoints. All are full-refresh only: the list endpoints expose no
+# server-side `updated_after`-style filter, so there is no genuine incremental cursor to advance
+# (a client-side scan of every page would cost the same as a full refresh — see the skill).
+BUNNY_ENDPOINTS: dict[str, BunnyEndpointConfig] = {
+ "pull_zones": BunnyEndpointConfig(name="pull_zones", path="/pullzone"),
+ "storage_zones": BunnyEndpointConfig(name="storage_zones", path="/storagezone"),
+ "dns_zones": BunnyEndpointConfig(name="dns_zones", path="/dnszone", partition_key="DateCreated"),
+ "video_libraries": BunnyEndpointConfig(name="video_libraries", path="/videolibrary", partition_key="DateCreated"),
+}
+
+ENDPOINTS = tuple(BUNNY_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/source.py
index 68e4c3d837d4..51b49139e4e3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/source.py
@@ -1,19 +1,39 @@
-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.bunny.bunny import (
+ BunnyResumeConfig,
+ bunny_source,
+ check_access,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.settings import BUNNY_ENDPOINTS, ENDPOINTS
+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 BunnySourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BunnySource(SimpleSource[BunnySourceConfig]):
+class BunnySource(ResumableSource[BunnySourceConfig, BunnyResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BUNNY
@@ -24,7 +44,96 @@ class BunnySource(SimpleSource[BunnySourceConfig]):
name=SchemaExternalDataSourceType.BUNNY,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Bunny.net",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your bunny.net account API key to pull your bunny.net data into the PostHog Data warehouse.
+
+You can find your account API key under **Account Settings → API** in the [bunny.net dashboard](https://dash.bunny.net/account/settings). This single key grants read access to the Core API (pull zones, storage zones, DNS zones, and Stream video libraries).
+""",
iconPath="/static/services/bunny.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/bunny",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_key",
+ label="Account API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked account API key surfaces 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.
+ "401 Client Error: Unauthorized for url: https://api.bunny.net": "Your bunny.net account API key is invalid or has been revoked. Generate a new key under Account Settings → API, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.bunny.net": "Your bunny.net account API key does not have access to this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: BunnySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — bunny.net's list endpoints expose no server-side
+ # timestamp filter, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: BunnySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The account API key is account-wide, so a single probe validates access to every schema;
+ # there is no per-endpoint scope to check.
+ status, message = check_access(config.access_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid bunny.net account API key"
+ return False, message or "Could not validate bunny.net account API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BunnyResumeConfig]:
+ return ResumableSourceManager[BunnyResumeConfig](inputs, BunnyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BunnySourceConfig,
+ resumable_source_manager: ResumableSourceManager[BunnyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in BUNNY_ENDPOINTS:
+ raise ValueError(f"Unknown bunny.net schema '{inputs.schema_name}'")
+
+ return bunny_source(
+ access_key=config.access_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/tests/test_bunny.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/tests/test_bunny.py
new file mode 100644
index 000000000000..10432c72e2cb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/tests/test_bunny.py
@@ -0,0 +1,208 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bunny import bunny
+from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.bunny import (
+ BunnyResumeConfig,
+ BunnyRetryableError,
+ bunny_source,
+ check_access,
+ get_rows,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.settings import BUNNY_ENDPOINTS, ENDPOINTS
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = bunny._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: BunnyResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[BunnyResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> BunnyResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: BunnyResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(items: list[dict], has_more: bool) -> dict[str, Any]:
+ return {"Items": items, "CurrentPage": 1, "TotalItems": len(items), "HasMoreItems": has_more}
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, dict], endpoint: str = "pull_zones"
+ ) -> list[dict]:
+ def fake_fetch(session: Any, path: str, page: int, per_page: int, logger: Any) -> dict:
+ return pages[page]
+
+ monkeypatch.setattr(bunny, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(bunny, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ access_key="bunny-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_yields_items_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {1: _page([{"Id": 1}, {"Id": 2}], has_more=False)})
+ assert rows == [{"Id": 1}, {"Id": 2}]
+ # No further pages, so no resume state is persisted.
+ assert manager.saved == []
+
+ def test_follows_pagination_until_has_more_is_false(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ 1: _page([{"Id": 1}], has_more=True),
+ 2: _page([{"Id": 2}], has_more=True),
+ 3: _page([{"Id": 3}], has_more=False),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"Id": 1}, {"Id": 2}, {"Id": 3}]
+
+ def test_saves_next_page_after_yielding_each_batch(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ 1: _page([{"Id": 1}], has_more=True),
+ 2: _page([{"Id": 2}], has_more=False),
+ }
+ self._collect(manager, monkeypatch, pages)
+ # State is saved AFTER page 1 is yielded (pointing at page 2), and never for the final page.
+ assert [s.next_page for s in manager.saved] == [2]
+
+ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(BunnyResumeConfig(next_page=2))
+ pages = {
+ # Page 1 must never be fetched on resume.
+ 2: _page([{"Id": 2}], has_more=True),
+ 3: _page([{"Id": 3}], has_more=False),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"Id": 2}, {"Id": 3}]
+
+ def test_empty_items_does_not_yield(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {1: _page([], has_more=False)})
+ assert rows == []
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body or {}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(BunnyRetryableError):
+ _fetch_page_unwrapped(session, "/pullzone", 1, 1000, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/pullzone", 1, 1000, MagicMock())
+
+ def test_success_returns_json_body(self) -> None:
+ body = _page([{"Id": 1}], has_more=False)
+ session = self._session_returning(200, body)
+ result = _fetch_page_unwrapped(session, "/pullzone", 1, 1000, MagicMock())
+ assert result == body
+
+ def test_request_uses_page_and_per_page_params(self) -> None:
+ session = self._session_returning(200, _page([], has_more=False))
+ _fetch_page_unwrapped(session, "/dnszone", 3, 1000, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"page": 3, "perPage": 1000}
+
+
+class TestCheckAccess:
+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ monkeypatch.setattr(bunny, "make_tracked_session", lambda **kwargs: session)
+ return session
+
+ @pytest.mark.parametrize(
+ "status, ok, expected_status, expected_message",
+ [
+ (200, True, 200, None),
+ (401, False, 401, None),
+ (403, False, 403, None),
+ (500, False, 500, "bunny.net returned HTTP 500"),
+ ],
+ )
+ def test_status_mapping(
+ self, status: int, ok: bool, expected_status: int, expected_message: str | None, monkeypatch: Any
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ self._patch_session(monkeypatch, response)
+ assert check_access("bunny-key") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:
+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))
+ status, message = check_access("bunny-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+
+class TestBunnySourceResponse:
+ @parameterized.expand(
+ [
+ ("pull_zones", None),
+ ("storage_zones", None),
+ ("dns_zones", "DateCreated"),
+ ("video_libraries", "DateCreated"),
+ ]
+ )
+ def test_partitioning_matches_endpoint_config(self, endpoint: str, partition_key: str | None) -> None:
+ response = bunny_source(
+ access_key="bunny-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["Id"]
+ if partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ # bunny.net IDs are globally unique, so a single `Id` key is sufficient table-wide.
+ assert all(config.primary_keys == ["Id"] for config in BUNNY_ENDPOINTS.values())
+ assert set(BUNNY_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/tests/test_bunny_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/tests/test_bunny_source.py
new file mode 100644
index 000000000000..e7ba2a68bd5c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/tests/test_bunny_source.py
@@ -0,0 +1,155 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.bunny import BunnyResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.source import BunnySource
+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 BunnySourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestBunnySource:
+ def setup_method(self) -> None:
+ self.source = BunnySource()
+ self.team_id = 123
+ self.config = BunnySourceConfig(access_key="bunny-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.BUNNY
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Bunny"
+ assert config.label == "Bunny.net"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/bunny"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["access_key"]
+
+ def test_access_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret `access_key` itself; the base URL is hardcoded and the account
+ # is implicit in the key. There is no non-secret field that retargets where the key is sent,
+ # so an editor cannot reuse a preserved key against a different account without re-entering it.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static catalog with no I/O, so the public docs can render the table list.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # bunny.net's list endpoints have no server-side timestamp filter, so every schema is full refresh.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["dns_zones"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "dns_zones"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ # Exercises the credential-free catalog path used by the posthog.com docs.
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.bunny.net/pullzone?page=1&perPage=1000",
+ "403 Client Error: Forbidden for url: https://api.bunny.net/dnszone?page=2&perPage=1000",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "unrelated_error",
+ [
+ "500 Server Error: Internal Server Error for url: https://api.bunny.net/pullzone",
+ "HTTPSConnectionPool(host='api.bunny.net', port=443): Read timed out.",
+ "429 Client Error: Too Many Requests for url: https://api.bunny.net/storagezone",
+ ],
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "status, expected_valid, expected_message",
+ [
+ (200, True, None),
+ (401, False, "Invalid bunny.net account API key"),
+ (403, False, "Invalid bunny.net account API key"),
+ (500, False, "bunny.net returned HTTP 500"),
+ (0, False, "Could not connect to bunny.net: boom"),
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bunny.source.check_access")
+ def test_validate_credentials(
+ self,
+ mock_check: mock.MagicMock,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ message = (
+ "bunny.net returned HTTP 500"
+ if status == 500
+ else ("Could not connect to bunny.net: boom" if status == 0 else None)
+ )
+ mock_check.return_value = (status, message)
+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)
+ assert is_valid is expected_valid
+ assert returned == expected_message
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bunny.source.check_access")
+ def test_validate_credentials_probes_the_account_key(self, mock_check: mock.MagicMock) -> None:
+ # The account API key is account-wide, so validation probes the key, not a per-schema scope.
+ mock_check.return_value = (200, None)
+ self.source.validate_credentials(self.config, self.team_id, schema_name="dns_zones")
+ mock_check.assert_called_once_with("bunny-key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BunnyResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bunny.source.bunny_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_bunny_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "pull_zones"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_bunny_source.assert_called_once()
+ kwargs = mock_bunny_source.call_args.kwargs
+ assert kwargs["access_key"] == "bunny-key"
+ assert kwargs["endpoint"] == "pull_zones"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown bunny.net schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
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 adede6289c7f..f445a188ebdf 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
@@ -520,7 +520,7 @@ class BuildkiteSourceConfig(config.Config):
@config.config
class BunnySourceConfig(config.Config):
- pass
+ access_key: str
@config.config