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(bunny): sync cdn statistics, storage zone usage and stream videos (#100180)

Tom Owers68d3bf70d8f9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 48d782becd87..a3f39837d00a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1088,14 +1088,14 @@ Note: Buildkite publishes a complete machine-readable docs index at /docs/llms.t
## Bunny — gaps
-Today (4): `dns_zones`, `pull_zones`, `storage_zones`, `video_libraries`
+Today (9): `dns_zones`, `pull_zones`, `statistics`, `storage_zone_egress`, `storage_zone_statistics`, `storage_zones`, `video_libraries`, `video_library_statistics`, `videos`
Diffed against: <https://core-api-public-docs.b-cdn.net/docs/v3/public.json>
-- [ ] `GET /statistics` — account-wide bandwidth, requests, and cache hit rate over time — Bunny's headline metric and entirely absent today (high)
-- [ ] `GET /storagezone/{id}/statistics and /statistics/egress` — storage usage and egress per zone; the cost driver for the storage_zones we already sync (high)
-- [ ] `GET /library/{libraryId}/videos (Stream API)` — child table of video_libraries we already sync — the individual videos, with status, size, and view counts (high)
-- [ ] `GET /library/{libraryId}/statistics (Stream API)` — views, watch time, and bandwidth per video library — the core Stream analytics object (high)
+- [x] `GET /statistics` — account-wide bandwidth, requests, and cache hit rate over time — Bunny's headline metric and entirely absent today (high)
+- [x] `GET /storagezone/{id}/statistics and /statistics/egress` — storage usage and egress per zone; the cost driver for the storage_zones we already sync (high)
+- [x] `GET /library/{libraryId}/videos (Stream API)` — child table of video_libraries we already sync — the individual videos, with status, size, and view counts (high)
+- [x] `GET /library/{libraryId}/statistics (Stream API)` — views, watch time, and bandwidth per video library — the core Stream analytics object (high)
- [ ] `GET /dnszone/{zoneId}/records` — lookup/child table resolving the DNS zones we already sync into individual records (high)
- [ ] `GET /dnszone/{id}/statistics` — DNS query volume per zone, the only usage metric for the DNS product (medium)
- [ ] `GET /library/{libraryId}/collections (Stream API)` — lookup resolving the collection IDs carried on videos (medium)
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
index fbaffd6c57d5..49f42675e536 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/bunny.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/bunny.py
@@ -1,28 +1,50 @@
import dataclasses
+from collections.abc import Callable, Iterable, Iterator
+from datetime import datetime
from typing import Any, Optional
from requests import Response
-from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.settings import BUNNY_ENDPOINTS
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.settings import (
+ BUNNY_ENDPOINTS,
+ DATE_FROM_PARAM,
+ BunnyEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
+ RESTClient,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import create_auth
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
PageNumberPaginator,
+ SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
BUNNY_BASE_URL = "https://api.bunny.net"
+# The Stream API answers on its own host and authenticates per video library rather than per
+# account, so it needs its own client even though it is the same vendor.
+BUNNY_STREAM_BASE_URL = "https://video.bunnycdn.com"
# The list endpoints accept perPage 5..1000; 1000 minimises round trips for the typically small
# zone/library tables.
PER_PAGE = 1000
# 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"
+# The statistics endpoints take an ISO-8601 UTC instant for their `dateFrom` bound.
+DATE_FROM_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
+# The per-library Stream keys `/videolibrary` carries, best first: read-only is all the Stream
+# endpoints we call need.
+STREAM_KEY_FIELDS = ("ReadOnlyApiKey", "ApiKey")
@dataclasses.dataclass
@@ -32,6 +54,16 @@ class BunnyResumeConfig:
next_page: int = 1
+@frozen
+class BunnyEndpointCall:
+ """One request an endpoint has to make: the client that carries the right credential for it,
+ the resolved path, and the parent columns stamped onto each row it returns."""
+
+ client: RESTClient
+ path: str
+ injected: dict[str, Any]
+
+
class BunnyHasMoreItemsPaginator(PageNumberPaginator):
"""Page-number paginator that stops on bunny.net's explicit ``HasMoreItems`` flag.
@@ -50,33 +82,229 @@ class BunnyHasMoreItemsPaginator(PageNumberPaginator):
self._has_next_page = isinstance(body, dict) and bool(body.get("HasMoreItems", False))
+def _paginator_for(config: BunnyEndpointConfig) -> BasePaginator:
+ if config.charts is not None:
+ return SinglePagePaginator()
+ if config.stream_api:
+ # The Stream list envelope reports total ITEMS and carries no "more items" flag, so the
+ # walk ends on the first empty page instead.
+ return PageNumberPaginator(base_page=1)
+ # Always request page>=1 so the Core API returns the paginated envelope
+ # ({Items, CurrentPage, TotalItems, HasMoreItems}); page=0 would return a bare array.
+ return BunnyHasMoreItemsPaginator(base_page=1)
+
+
+def _client_config(access_key: str, base_url: str = BUNNY_BASE_URL) -> ClientConfig:
+ return {
+ "base_url": base_url,
+ # The AccessKey travels via the framework auth config so its value is redacted from
+ # logged URLs and captured samples; only the non-secret Accept header is set here.
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "api_key", "api_key": access_key, "name": "AccessKey", "location": "header"},
+ }
+
+
+def _rest_client(access_key: str, base_url: str = BUNNY_BASE_URL) -> RESTClient:
+ """The same client the framework builds from ``_client_config``, for the fan-out that can't
+ be expressed declaratively. Read off the config so the two paths can't drift apart."""
+ config = _client_config(access_key, base_url)
+ return RESTClient(
+ base_url=config["base_url"],
+ headers=config["headers"],
+ auth=create_auth(config["auth"]),
+ )
+
+
+def _request_params(config: BunnyEndpointConfig, date_from: Optional[str] = None) -> dict[str, Any]:
+ if config.charts is not None:
+ return {**config.params, DATE_FROM_PARAM: date_from}
+ return {config.page_size_param: PER_PAGE, **config.params}
+
+
+def _date_from(db_incremental_field_last_value: Any) -> Optional[str]:
+ """The ``dateFrom`` bound an incremental run asks from, or None to take the vendor default.
+
+ bunny.net returns the last 30 days when no bound is sent, so a first run seeds 30 days and
+ each later run asks only from the newest point the table already holds. That point's own
+ bucket comes back again and upserts on the primary key, which is what settles an interval
+ that was still in progress when it was first read.
+ """
+ value = parse_datetime_value(db_incremental_field_last_value)
+ if value is None:
+ return None
+ return value.strftime(DATE_FROM_FORMAT)
+
+
+def _stream_access_key(library: dict[str, Any]) -> Optional[str]:
+ """The Stream key for one video library, or None when the row carries neither.
+
+ video.bunnycdn.com authenticates against the library's own key, so the account key that
+ listed the libraries cannot reach it.
+ """
+ for field_name in STREAM_KEY_FIELDS:
+ value = library.get(field_name)
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+def _iter_parent_rows(client: RESTClient, parent: BunnyEndpointConfig) -> Iterator[dict[str, Any]]:
+ for page in client.paginate(
+ parent.path,
+ params=_request_params(parent),
+ data_selector=parent.items_selector,
+ data_selector_required=True,
+ paginator=_paginator_for(parent),
+ ):
+ yield from page
+
+
+def _endpoint_calls(access_key: str, config: BunnyEndpointConfig) -> Iterator[BunnyEndpointCall]:
+ """Every call this endpoint has to make.
+
+ One call for a top-level endpoint, one per parent row for a fan-out child — which on the
+ Stream API also means a client holding that library's own key. A library with no usable key
+ is skipped rather than failing the whole table.
+ """
+ core_client = _rest_client(access_key)
+ if config.parent is None:
+ yield BunnyEndpointCall(client=core_client, path=config.path, injected={})
+ return
+
+ for parent_row in _iter_parent_rows(core_client, BUNNY_ENDPOINTS[config.parent.endpoint]):
+ parent_id = parent_row.get(config.parent.id_field)
+ if parent_id is None:
+ continue
+ injected = {config.parent.id_column: parent_id}
+ path = config.path.format(id=parent_id)
+ if not config.stream_api:
+ yield BunnyEndpointCall(client=core_client, path=path, injected=injected)
+ continue
+ stream_key = _stream_access_key(parent_row)
+ if stream_key is not None:
+ client = _rest_client(stream_key, BUNNY_STREAM_BASE_URL)
+ yield BunnyEndpointCall(client=client, path=path, injected=injected)
+
+
+def _chart_rows(
+ body: Any, charts: dict[str, str], timestamp_column: str, injected: dict[str, Any]
+) -> list[dict[str, Any]]:
+ """Pivot a statistics body — one ``{timestamp: value}`` map per chart — into one row per
+ timestamp, sorted oldest first.
+
+ Every row carries every chart column so a batch converts to a single Arrow schema even when
+ the charts cover different ranges.
+ """
+ rows: dict[datetime, dict[str, Any]] = {}
+ for chart_name, column in charts.items():
+ points = body.get(chart_name) if isinstance(body, dict) else None
+ if not isinstance(points, dict):
+ continue
+ for raw_timestamp, value in points.items():
+ timestamp = parse_datetime_value(raw_timestamp)
+ if timestamp is None:
+ continue
+ row = rows.setdefault(
+ timestamp,
+ {**injected, timestamp_column: timestamp, **dict.fromkeys(charts.values())},
+ )
+ row[column] = value
+ return [rows[timestamp] for timestamp in sorted(rows)]
+
+
+def _chart_pages(
+ access_key: str, config: BunnyEndpointConfig, timestamp_column: str, date_from: Optional[str]
+) -> Iterator[list[dict[str, Any]]]:
+ charts = config.charts or {}
+ for call in _endpoint_calls(access_key, config):
+ params = _request_params(config, date_from)
+ for page in call.client.paginate(call.path, params=params, paginator=_paginator_for(config)):
+ for body in page:
+ rows = _chart_rows(body, charts, timestamp_column, call.injected)
+ if rows:
+ yield rows
+
+
+def _fanout_list_pages(access_key: str, config: BunnyEndpointConfig) -> Iterator[list[dict[str, Any]]]:
+ for call in _endpoint_calls(access_key, config):
+ for page in call.client.paginate(
+ call.path,
+ params=_request_params(config),
+ data_selector=config.items_selector,
+ data_selector_required=True,
+ paginator=_paginator_for(config),
+ ):
+ if page:
+ yield [{**call.injected, **row} for row in page]
+
+
+def _resume_page(manager: ResumableSourceManager[BunnyResumeConfig]) -> Optional[dict[str, Any]]:
+ """The paginator state a retried attempt picks up from, or None to start at the first page."""
+ if not manager.can_resume():
+ return None
+ resume = manager.load_state()
+ return None if resume is None else {"page": resume.next_page}
+
+
+def _save_checkpoint(manager: ResumableSourceManager[BunnyResumeConfig], state: Optional[dict[str, Any]]) -> None:
+ # Persist only while more pages remain; saved AFTER a page is yielded so a crash re-fetches
+ # from the next page (already-yielded pages are persisted) and merge dedupes the re-pulled
+ # page on the primary key.
+ if state and state.get("page") is not None:
+ manager.save_state(BunnyResumeConfig(next_page=int(state["page"])))
+
+
+def _source_response(
+ config: BunnyEndpointConfig,
+ items: Callable[[], Iterable[Any]],
+ column_hints: Optional[dict[str, Any]] = None,
+) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=items,
+ 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,
+ sort_mode=config.sort_mode,
+ column_hints=column_hints,
+ )
+
+
def bunny_source(
access_key: str,
endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[BunnyResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = BUNNY_ENDPOINTS[endpoint]
+ # Only the top-level list endpoints checkpoint: their page number is the whole cursor. A
+ # fan-out walk would need the parent's position too, which page-number state cannot carry,
+ # so those tables restart from the first parent instead.
+ if config.charts is not None:
+ if config.timestamp_column is None:
+ raise ValueError(f"Statistics endpoint '{endpoint}' needs a timestamp column")
+ timestamp_column = config.timestamp_column
+ date_from = _date_from(db_incremental_field_last_value)
+ return _source_response(config, lambda: _chart_pages(access_key, config, timestamp_column, date_from))
+
+ if config.parent is not None:
+ return _source_response(config, lambda: _fanout_list_pages(access_key, config))
+
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": BUNNY_BASE_URL,
- # The AccessKey travels via the framework auth config so its value is redacted from
- # logged URLs and captured samples; only the non-secret Accept header is set here.
- "headers": {"Accept": "application/json"},
- "auth": {"type": "api_key", "api_key": access_key, "name": "AccessKey", "location": "header"},
- # Always request page>=1 so the API returns the paginated envelope
- # ({Items, CurrentPage, TotalItems, HasMoreItems}); page=0 would return a bare array.
- "paginator": BunnyHasMoreItemsPaginator(base_page=1),
- },
+ "client": {**_client_config(access_key), "paginator": _paginator_for(config)},
"resources": [
{
"name": endpoint,
"endpoint": {
"path": config.path,
- "params": {"perPage": PER_PAGE},
- "data_selector": "Items",
+ "params": _request_params(config),
+ "data_selector": config.items_selector,
# `Items` is always present in the paginated envelope; missing it means a
# malformed response, so fail loudly rather than silently syncing 0 rows.
"data_selector_required": True,
@@ -85,39 +313,16 @@ def bunny_source(
],
}
- initial_paginator_state: Optional[dict[str, Any]] = None
- if resumable_source_manager.can_resume():
- resume = resumable_source_manager.load_state()
- if resume is not None:
- initial_paginator_state = {"page": resume.next_page}
-
- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- # Persist only while more pages remain; saved AFTER a page is yielded so a crash
- # re-fetches from the next page (already-yielded pages are persisted) and merge
- # dedupes the re-pulled page on the primary key.
- if state and state.get("page") is not None:
- resumable_source_manager.save_state(BunnyResumeConfig(next_page=int(state["page"])))
-
resource = rest_api_resource(
rest_config,
team_id,
job_id,
- None, # every bunny.net endpoint is full refresh — no incremental cursor
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
+ None, # the list endpoints are full refresh — no incremental cursor
+ resume_hook=lambda state: _save_checkpoint(resumable_source_manager, state),
+ initial_paginator_state=_resume_page(resumable_source_manager),
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- 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,
- column_hints=resource.column_hints,
- )
+ return _source_response(config, lambda: resource, column_hints=resource.column_hints)
def check_access(access_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[bool, Optional[int]]:
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
index ea590752e259..bab2efab0c70 100644
--- 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
@@ -71,4 +71,84 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"EncodingTier": "The encoding tier configured for the library.",
},
},
+ "statistics": {
+ "description": "Account-wide CDN traffic for one time bucket: bandwidth, requests, cache hit rate and error counts.",
+ "docs_url": "https://docs.bunny.net/reference/statisticspublic_index",
+ "columns": {
+ "Timestamp": "The start of the interval the values cover.",
+ "BandwidthUsed": "The bandwidth served in the interval, in bytes.",
+ "BandwidthCached": "The part of the served bandwidth answered from cache, in bytes.",
+ "CacheHitRate": "The share of requests answered from cache, as a percentage.",
+ "RequestsServed": "The number of requests served in the interval.",
+ "PullRequestsPulled": "The number of requests that had to be pulled from the origin.",
+ "OriginTraffic": "The traffic received from the origin, in bytes.",
+ "OriginResponseTime": "The median origin response time, in milliseconds.",
+ "OriginShieldBandwidthUsed": "The bandwidth served through origin shield, in bytes.",
+ "OriginShieldInternalBandwidthUsed": "The internal origin shield bandwidth, in bytes.",
+ "Error3xx": "The number of 3xx responses served in the interval.",
+ "Error4xx": "The number of 4xx responses served in the interval.",
+ "Error5xx": "The number of 5xx responses served in the interval.",
+ },
+ },
+ "storage_zone_statistics": {
+ "description": "Storage used and files stored by one storage zone, for one time bucket.",
+ "docs_url": "https://docs.bunny.net/reference/storagezonepublic_statistics",
+ "columns": {
+ "StorageZoneId": "The ID of the storage zone the values belong to.",
+ "Timestamp": "The start of the interval the values cover.",
+ "StorageUsed": "The storage used by the zone, in bytes.",
+ "FileCount": "The number of files stored in the zone.",
+ },
+ },
+ "storage_zone_egress": {
+ "description": "Download traffic out of one storage zone, split by protocol, for one time bucket.",
+ "docs_url": "https://docs.bunny.net/reference/storagezonepublic_egressstatistics",
+ "columns": {
+ "StorageZoneId": "The ID of the storage zone the values belong to.",
+ "Timestamp": "The start of the interval the values cover.",
+ "HttpEgress": "Download traffic served over HTTP, in bytes.",
+ "S3Egress": "Download traffic served over S3, in bytes.",
+ "S3PresignedEgress": "Download traffic served over presigned S3 URLs, in bytes.",
+ "FtpEgress": "Download traffic served over FTP, in bytes.",
+ "SftpEgress": "Download traffic served over SFTP, in bytes.",
+ "TotalEgress": "Download traffic served over all protocols, in bytes.",
+ },
+ },
+ "videos": {
+ "description": "A single video in a bunny.net Stream video library, with its encoding state and viewing totals.",
+ "docs_url": "https://docs.bunny.net/reference/video_list",
+ "columns": {
+ "videoLibraryId": "The ID of the video library the video belongs to.",
+ "guid": "The unique ID of the video.",
+ "title": "The title of the video.",
+ "description": "The description of the video.",
+ "dateUploaded": "The date the video was uploaded.",
+ "views": "The number of views the video received.",
+ "isPublic": "Whether the video is publicly accessible.",
+ "length": "The duration of the video, in seconds.",
+ "status": "The processing status of the video.",
+ "framerate": "The framerate of the video.",
+ "width": "The width of the original video file.",
+ "height": "The height of the original video file.",
+ "availableResolutions": "The resolutions that finished encoding and can be played.",
+ "outputCodecs": "The output codecs generated for the video.",
+ "thumbnailCount": "The number of thumbnails generated for the video.",
+ "encodeProgress": "Encoding progress, from 0 to 100.",
+ "storageSize": "The storage used by the video, in bytes.",
+ "hasMP4Fallback": "Whether MP4 fallback files were generated.",
+ "collectionId": "The ID of the collection the video belongs to.",
+ "averageWatchTime": "The average watch time of the video, in seconds.",
+ "totalWatchTime": "The total watch time of the video, in seconds.",
+ },
+ },
+ "video_library_statistics": {
+ "description": "Views and watch time for one Stream video library, for one time bucket.",
+ "docs_url": "https://docs.bunny.net/reference/video_getvideostatistics",
+ "columns": {
+ "videoLibraryId": "The ID of the video library the values belong to.",
+ "timestamp": "The start of the interval the values cover.",
+ "views": "The number of playback starts in the interval.",
+ "watchTime": "The time viewers spent watching in the interval, in seconds.",
+ },
+ },
}
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
index 2590a04ef43c..76be944af701 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bunny/settings.py
@@ -1,8 +1,22 @@
-from dataclasses import dataclass, field
-from typing import Optional
+from dataclasses import field
+from typing import Any, Optional
+from posthog.dataclasses import frozen
-@dataclass
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@frozen
+class BunnyParentConfig:
+ """A list endpoint whose rows a child endpoint is reached once per."""
+
+ endpoint: str
+ id_field: str
+ id_column: str
+
+
+@frozen
class BunnyEndpointConfig:
name: str
path: str
@@ -11,16 +25,140 @@ class BunnyEndpointConfig:
# 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
+ # Stream endpoints answer on a different host and authenticate with the per-library key
+ # `/videolibrary` carries, not the account API key.
+ stream_api: bool = False
+ # Static query params sent with every request to this endpoint.
+ params: dict[str, Any] = field(default_factory=dict)
+ # The envelope key holding the rows of a paginated list response.
+ items_selector: str = "Items"
+ page_size_param: str = "perPage"
+ # Set when the endpoint is reached once per row of a parent list endpoint, with the parent's
+ # id formatted into `path`.
+ parent: Optional[BunnyParentConfig] = None
+ # Set for the statistics endpoints, whose body is a set of charts keyed by timestamp rather
+ # than a list of objects. Maps each API chart property to the column its points land in.
+ charts: Optional[dict[str, str]] = None
+ # The column a chart's timestamp lands in. Doubles as the incremental cursor.
+ timestamp_column: Optional[str] = None
+ sort_mode: SortMode = "asc"
+
+# The statistics endpoints all take the same server-side start filter.
+DATE_FROM_PARAM = "dateFrom"
-# 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.net Core API list endpoints are full-refresh only: they 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).
+# The statistics endpoints do filter on `dateFrom`, so their tables sync incrementally on the
+# chart timestamp — which is also how they keep history past the 30 days bunny.net returns by
+# default.
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"),
+ "statistics": BunnyEndpointConfig(
+ name="statistics",
+ path="/statistics",
+ primary_keys=["Timestamp"],
+ partition_key="Timestamp",
+ timestamp_column="Timestamp",
+ # Every chart defaults to off, so each one this table has a column for is asked for by
+ # name. Geographic distribution and user balance history are left out: they are keyed by
+ # country and by account event, not by the timestamp this table is grained on.
+ params={
+ "loadBandwidthUsed": "true",
+ "loadRequestsServed": "true",
+ "loadOriginTraffic": "true",
+ "loadOriginResponseTimes": "true",
+ "loadOriginShieldBandwidth": "true",
+ "loadErrors": "true",
+ },
+ charts={
+ "BandwidthUsedChart": "BandwidthUsed",
+ "BandwidthCachedChart": "BandwidthCached",
+ "CacheHitRateChart": "CacheHitRate",
+ "RequestsServedChart": "RequestsServed",
+ "PullRequestsPulledChart": "PullRequestsPulled",
+ "OriginTrafficChart": "OriginTraffic",
+ "OriginResponseTimeChart": "OriginResponseTime",
+ "OriginShieldBandwidthUsedChart": "OriginShieldBandwidthUsed",
+ "OriginShieldInternalBandwidthUsedChart": "OriginShieldInternalBandwidthUsed",
+ "Error3xxChart": "Error3xx",
+ "Error4xxChart": "Error4xx",
+ "Error5xxChart": "Error5xx",
+ },
+ ),
+ "storage_zone_statistics": BunnyEndpointConfig(
+ name="storage_zone_statistics",
+ path="/storagezone/{id}/statistics",
+ primary_keys=["StorageZoneId", "Timestamp"],
+ partition_key="Timestamp",
+ timestamp_column="Timestamp",
+ parent=BunnyParentConfig(endpoint="storage_zones", id_field="Id", id_column="StorageZoneId"),
+ charts={"StorageUsedChart": "StorageUsed", "FileCountChart": "FileCount"},
+ # Rows arrive grouped by storage zone, so the table as a whole is not in timestamp order.
+ # "desc" holds the watermark until the run finishes, otherwise a run cut short mid-walk
+ # would advance it past zones it never reached.
+ sort_mode="desc",
+ ),
+ "storage_zone_egress": BunnyEndpointConfig(
+ name="storage_zone_egress",
+ path="/storagezone/{id}/statistics/egress",
+ primary_keys=["StorageZoneId", "Timestamp"],
+ partition_key="Timestamp",
+ timestamp_column="Timestamp",
+ parent=BunnyParentConfig(endpoint="storage_zones", id_field="Id", id_column="StorageZoneId"),
+ charts={
+ "HttpEgressChart": "HttpEgress",
+ "S3EgressChart": "S3Egress",
+ "S3PresignedEgressChart": "S3PresignedEgress",
+ "FtpEgressChart": "FtpEgress",
+ "SftpEgressChart": "SftpEgress",
+ "TotalEgressChart": "TotalEgress",
+ },
+ sort_mode="desc",
+ ),
+ "videos": BunnyEndpointConfig(
+ name="videos",
+ path="/library/{id}/videos",
+ # `guid` is only documented as unique inside its library, so the library id is part of
+ # the key — a fan-out child aggregates rows from every parent into one table.
+ primary_keys=["videoLibraryId", "guid"],
+ partition_key="dateUploaded",
+ stream_api=True,
+ params={"orderBy": "date"},
+ items_selector="items",
+ page_size_param="itemsPerPage",
+ parent=BunnyParentConfig(endpoint="video_libraries", id_field="Id", id_column="videoLibraryId"),
+ ),
+ "video_library_statistics": BunnyEndpointConfig(
+ name="video_library_statistics",
+ path="/library/{id}/statistics",
+ primary_keys=["videoLibraryId", "timestamp"],
+ partition_key="timestamp",
+ stream_api=True,
+ timestamp_column="timestamp",
+ parent=BunnyParentConfig(endpoint="video_libraries", id_field="Id", id_column="videoLibraryId"),
+ # The country breakdowns the same body carries are keyed by country rather than by time,
+ # so they belong to a different grain and are left out of this table.
+ charts={"viewsChart": "views", "watchTimeChart": "watchTime"},
+ sort_mode="desc",
+ ),
}
ENDPOINTS = tuple(BUNNY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: [
+ {
+ "label": config.timestamp_column,
+ "type": IncrementalFieldType.DateTime,
+ "field": config.timestamp_column,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+ for name, config in BUNNY_ENDPOINTS.items()
+ if config.timestamp_column is not None
+}
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 9c2733ac5bea..68b8036f794d 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
@@ -14,7 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.bunn
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.bunny.settings import (
+ BUNNY_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
@@ -82,6 +86,10 @@ You can find your account API key under **Account Settings → API** in the [bun
# 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.",
+ # The Stream tables authenticate with the per-library key the account key reads off
+ # `/videolibrary`, so their auth failures come back from the Stream host instead.
+ "401 Client Error: Unauthorized for url: https://video.bunnycdn.com": "A bunny.net video library rejected its API key. Regenerate the library's key in the Stream dashboard, then re-run the sync.",
+ "403 Client Error: Forbidden for url: https://video.bunnycdn.com": "A bunny.net video library API key does not have access to this data. Check the library's key permissions, then re-run the sync.",
}
def get_schemas(
@@ -93,9 +101,11 @@ You can find your account API key under **Account Settings → API** in the [bun
force_refresh: bool = False,
api_version: str | None = None,
) -> 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.
- return build_endpoint_schemas(ENDPOINTS, {}, names)
+ # The list endpoints are full refresh only — they expose no server-side timestamp
+ # filter, so there is no incremental cursor to advance. The statistics endpoints do
+ # filter on `dateFrom`, and merge only: appending would re-add a row per run for every
+ # interval the window still covers.
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=tuple(INCREMENTAL_FIELDS))
def validate_credentials(
self, config: BunnySourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
@@ -129,4 +139,7 @@ You can find your account API key under **Account Settings → API** in the [bun
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
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
index 75ee2ee84e8a..d99099000287 100644
--- 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
@@ -1,4 +1,6 @@
import json
+import dataclasses
+from datetime import UTC, datetime
from typing import Any
import pytest
@@ -10,6 +12,7 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.bunny import (
BUNNY_BASE_URL,
+ BUNNY_STREAM_BASE_URL,
PER_PAGE,
BunnyResumeConfig,
bunny_source,
@@ -46,6 +49,25 @@ def _response(
return resp
+def _raw_response(body: Any, *, status_code: int = 200) -> Response:
+ """A response whose whole body is the row payload (the statistics endpoints)."""
+ resp = Response()
+ resp.status_code = status_code
+ resp.url = f"{BUNNY_BASE_URL}/statistics"
+ resp.reason = "Error" if status_code >= 400 else "OK"
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _stream_response(items: list[dict[str, Any]]) -> Response:
+ """A Stream API list envelope, which is lower-cased and carries no ``HasMoreItems``."""
+ return _raw_response({"items": items, "totalItems": len(items), "currentPage": 1, "itemsPerPage": PER_PAGE})
+
+
+def _utc(day: int) -> datetime:
+ return datetime(2024, 5, day, tzinfo=UTC)
+
+
def _make_manager(resume_state: BunnyResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -53,35 +75,43 @@ def _make_manager(resume_state: BunnyResumeConfig | None = None) -> mock.MagicMo
return manager
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and return a list that captures each request's params AT SEND TIME.
[email protected](frozen=True)
+class _Sent:
+ url: str
+ params: dict[str, Any]
+ auth: Any
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[_Sent]:
+ """Wire a mock session and return a list that captures each request AT SEND TIME.
``request.params`` is a single dict mutated in place across pages, so inspecting it after the run
shows only the final state — snapshot a copy when each request is prepared instead.
"""
session.headers = {}
- param_snapshots: list[dict[str, Any]] = []
+ sent: list[_Sent] = []
def _prepare(request: Any) -> mock.MagicMock:
- param_snapshots.append(dict(request.params or {}))
+ sent.append(_Sent(url=request.url, params=dict(request.params or {}), auth=request.auth))
return mock.MagicMock()
session.prepare_request.side_effect = _prepare
session.send.side_effect = responses
- return param_snapshots
+ return sent
def _rows(source_response) -> list[dict[str, Any]]:
return [row for page in source_response.items() for row in page]
-def _source(manager: mock.MagicMock, endpoint: str = "pull_zones"):
+def _source(manager: mock.MagicMock, endpoint: str = "pull_zones", last_value: Any = None):
return bunny_source(
access_key="bunny-key",
endpoint=endpoint,
team_id=1,
job_id="j",
resumable_source_manager=manager,
+ db_incremental_field_last_value=last_value,
)
@@ -89,21 +119,21 @@ class TestPagination:
@mock.patch(CLIENT_SESSION_PATCH)
def test_single_page_yields_items_and_stops(self, MockSession) -> None:
session = MockSession.return_value
- params = _wire(session, [_response([{"Id": 1}, {"Id": 2}], has_more=False)])
+ sent = _wire(session, [_response([{"Id": 1}, {"Id": 2}], has_more=False)])
manager = _make_manager()
rows = _rows(_source(manager))
assert rows == [{"Id": 1}, {"Id": 2}]
assert session.send.call_count == 1
- assert params[0] == {"page": 1, "perPage": PER_PAGE}
+ assert sent[0].params == {"page": 1, "perPage": PER_PAGE}
# No further pages, so no resume state is persisted.
manager.save_state.assert_not_called()
@mock.patch(CLIENT_SESSION_PATCH)
def test_follows_pagination_until_has_more_is_false(self, MockSession) -> None:
session = MockSession.return_value
- params = _wire(
+ sent = _wire(
session,
[
_response([{"Id": 1}], has_more=True),
@@ -116,8 +146,8 @@ class TestPagination:
rows = _rows(_source(manager))
assert rows == [{"Id": 1}, {"Id": 2}, {"Id": 3}]
- assert [p["page"] for p in params] == [1, 2, 3]
- assert all(p["perPage"] == PER_PAGE for p in params)
+ assert [s.params["page"] for s in sent] == [1, 2, 3]
+ assert all(s.params["perPage"] == PER_PAGE for s in sent)
@mock.patch(CLIENT_SESSION_PATCH)
def test_saves_next_page_after_yielding_each_batch(self, MockSession) -> None:
@@ -134,13 +164,13 @@ class TestPagination:
def test_resumes_from_saved_page(self, MockSession) -> None:
session = MockSession.return_value
# Page 1 must never be fetched on resume.
- params = _wire(session, [_response([{"Id": 2}], has_more=True), _response([{"Id": 3}], has_more=False)])
+ sent = _wire(session, [_response([{"Id": 2}], has_more=True), _response([{"Id": 3}], has_more=False)])
manager = _make_manager(BunnyResumeConfig(next_page=2))
rows = _rows(_source(manager))
assert rows == [{"Id": 2}, {"Id": 3}]
- assert [p["page"] for p in params] == [2, 3]
+ assert [s.params["page"] for s in sent] == [2, 3]
@mock.patch(CLIENT_SESSION_PATCH)
def test_empty_page_with_has_more_continues(self, MockSession) -> None:
@@ -167,22 +197,14 @@ class TestPagination:
@mock.patch(CLIENT_SESSION_PATCH)
def test_access_key_travels_via_redacting_auth(self, MockSession) -> None:
session = MockSession.return_value
- session.headers = {}
- captured_auth: list[Any] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- captured_auth.append(request.auth)
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = [_response([{"Id": 1}], has_more=False)]
+ sent = _wire(session, [_response([{"Id": 1}], has_more=False)])
_rows(_source(_make_manager()))
# The secret goes through the framework auth (value-redacted in logs), not plain headers.
- assert captured_auth[0].api_key == "bunny-key"
- assert captured_auth[0].name == "AccessKey"
- assert captured_auth[0].location == "header"
+ assert sent[0].auth.api_key == "bunny-key"
+ assert sent[0].auth.name == "AccessKey"
+ assert sent[0].auth.location == "header"
assert session.headers.get("Accept") == "application/json"
assert "AccessKey" not in session.headers
@@ -248,18 +270,25 @@ class TestCheckAccess:
class TestBunnySourceResponse:
@parameterized.expand(
[
- ("pull_zones", None),
- ("storage_zones", None),
- ("dns_zones", "DateCreated"),
- ("video_libraries", "DateCreated"),
+ ("pull_zones", ["Id"], None),
+ ("storage_zones", ["Id"], None),
+ ("dns_zones", ["Id"], "DateCreated"),
+ ("video_libraries", ["Id"], "DateCreated"),
+ ("statistics", ["Timestamp"], "Timestamp"),
+ ("storage_zone_statistics", ["StorageZoneId", "Timestamp"], "Timestamp"),
+ ("storage_zone_egress", ["StorageZoneId", "Timestamp"], "Timestamp"),
+ ("videos", ["videoLibraryId", "guid"], "dateUploaded"),
+ ("video_library_statistics", ["videoLibraryId", "timestamp"], "timestamp"),
]
)
@mock.patch(CLIENT_SESSION_PATCH)
- def test_partitioning_matches_endpoint_config(self, endpoint: str, partition_key: str | None, MockSession) -> None:
+ def test_partitioning_matches_endpoint_config(
+ self, endpoint: str, primary_keys: list[str], partition_key: str | None, MockSession
+ ) -> None:
MockSession.return_value.headers = {}
response = _source(_make_manager(), endpoint=endpoint)
assert response.name == endpoint
- assert response.primary_keys == ["Id"]
+ assert response.primary_keys == primary_keys
if partition_key is None:
assert response.partition_mode is None
assert response.partition_keys is None
@@ -267,7 +296,218 @@ class TestBunnySourceResponse:
assert response.partition_mode == "datetime"
assert response.partition_keys == [partition_key]
- def test_every_endpoint_uses_id_primary_key(self) -> None:
+ def test_top_level_endpoints_use_the_globally_unique_id(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())
+ top_level = [c for c in BUNNY_ENDPOINTS.values() if c.parent is None and c.charts is None]
+ assert all(config.primary_keys == ["Id"] for config in top_level)
assert set(BUNNY_ENDPOINTS) == set(ENDPOINTS)
+
+ def test_fanout_children_carry_their_parent_id_in_the_key(self) -> None:
+ # A child aggregates rows from every parent into one table, so a key unique only within a
+ # parent seeds duplicate rows that every later merge multi-matches.
+ children = [c for c in BUNNY_ENDPOINTS.values() if c.parent is not None]
+ assert children
+ assert all(config.parent is not None and config.parent.id_column in config.primary_keys for config in children)
+
+ def test_fanout_tables_defer_the_watermark_to_the_end_of_the_run(self) -> None:
+ # Their rows arrive grouped by parent, so the table is not in timestamp order and a run cut
+ # short mid-walk must not leave the watermark past parents it never reached.
+ for config in BUNNY_ENDPOINTS.values():
+ if config.parent is not None and config.timestamp_column is not None:
+ assert config.sort_mode == "desc"
+
+
+CHART_COLUMNS = set((BUNNY_ENDPOINTS["statistics"].charts or {}).values())
+
+
+class TestAccountStatistics:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_pivots_charts_into_one_row_per_timestamp(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _raw_response(
+ {
+ # Deliberately out of order, and the two charts cover different days.
+ "BandwidthUsedChart": {"2024-05-02T00:00:00": 20, "2024-05-01T00:00:00": 10},
+ "RequestsServedChart": {"2024-05-02T00:00:00": 7},
+ "TotalBandwidthUsed": 30,
+ }
+ )
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), endpoint="statistics"))
+
+ assert [row["Timestamp"] for row in rows] == [_utc(1), _utc(2)]
+ assert [row["BandwidthUsed"] for row in rows] == [10, 20]
+ assert [row["RequestsServed"] for row in rows] == [None, 7]
+ # Every row carries every chart column, so a batch converts to one Arrow schema even
+ # when the charts cover different ranges.
+ assert all(set(row) == CHART_COLUMNS | {"Timestamp"} for row in rows)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_asks_for_the_charts_without_a_date_bound(self, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire(session, [_raw_response({"BandwidthUsedChart": {"2024-05-01T00:00:00": 1}})])
+
+ _rows(_source(_make_manager(), endpoint="statistics"))
+
+ assert session.send.call_count == 1
+ assert sent[0].url == f"{BUNNY_BASE_URL}/statistics"
+ # Each chart defaults to off, so a missing load flag silently returns an empty column.
+ assert sent[0].params["loadBandwidthUsed"] == "true"
+ assert sent[0].params["loadRequestsServed"] == "true"
+ assert "dateFrom" not in sent[0].params
+
+ @parameterized.expand(
+ [
+ ("datetime", datetime(2024, 5, 2, 3, 4, 5, tzinfo=UTC)),
+ # The pipeline persists the watermark as a string for some sources.
+ ("string", "2024-05-02T03:04:05+00:00"),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_asks_from_the_watermark(self, _name: str, last_value: Any, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire(session, [_raw_response({"BandwidthUsedChart": {}})])
+
+ _rows(_source(_make_manager(), endpoint="statistics", last_value=last_value))
+
+ assert sent[0].params["dateFrom"] == "2024-05-02T03:04:05Z"
+
+
+class TestStorageZoneFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_calls_each_zone_and_stamps_its_id_on_every_row(self, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire(
+ session,
+ [
+ _response([{"Id": 11}, {"Id": 22}], has_more=False),
+ _raw_response(
+ {"StorageUsedChart": {"2024-05-01T00:00:00": 5}, "FileCountChart": {"2024-05-01T00:00:00": 2}}
+ ),
+ _raw_response({"StorageUsedChart": {"2024-05-01T00:00:00": 9}}),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), endpoint="storage_zone_statistics"))
+
+ assert [s.url for s in sent] == [
+ f"{BUNNY_BASE_URL}/storagezone",
+ f"{BUNNY_BASE_URL}/storagezone/11/statistics",
+ f"{BUNNY_BASE_URL}/storagezone/22/statistics",
+ ]
+ assert rows == [
+ {"StorageZoneId": 11, "Timestamp": _utc(1), "StorageUsed": 5, "FileCount": 2},
+ {"StorageZoneId": 22, "Timestamp": _utc(1), "StorageUsed": 9, "FileCount": None},
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_egress_splits_the_protocols_into_columns(self, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire(
+ session,
+ [
+ _response([{"Id": 11}], has_more=False),
+ _raw_response(
+ {
+ "HttpEgressChart": {"2024-05-01T00:00:00": 3},
+ "TotalEgressChart": {"2024-05-01T00:00:00": 3},
+ "TotalEgress": 3,
+ }
+ ),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), endpoint="storage_zone_egress"))
+
+ assert sent[1].url == f"{BUNNY_BASE_URL}/storagezone/11/statistics/egress"
+ assert rows == [
+ {
+ "StorageZoneId": 11,
+ "Timestamp": _utc(1),
+ "HttpEgress": 3,
+ "S3Egress": None,
+ "S3PresignedEgress": None,
+ "FtpEgress": None,
+ "SftpEgress": None,
+ "TotalEgress": 3,
+ }
+ ]
+
+
+class TestStreamFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_videos_use_the_library_key_against_the_stream_host(self, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire(
+ session,
+ [
+ _response([{"Id": 7, "ReadOnlyApiKey": "lib-ro", "ApiKey": "lib-rw"}], has_more=False),
+ _stream_response([{"guid": "g1", "videoLibraryId": 7}]),
+ _stream_response([]),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), endpoint="videos"))
+
+ assert rows == [{"guid": "g1", "videoLibraryId": 7}]
+ # The account key lists the libraries; the Stream host only accepts the library's own key.
+ assert sent[0].auth.api_key == "bunny-key"
+ assert sent[1].url == f"{BUNNY_STREAM_BASE_URL}/library/7/videos"
+ assert sent[1].auth.api_key == "lib-ro"
+ assert sent[1].params == {"page": 1, "itemsPerPage": PER_PAGE, "orderBy": "date"}
+ # The Stream envelope carries no "more items" flag, so the walk ends on an empty page.
+ assert [s.params["page"] for s in sent[1:]] == [1, 2]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_falls_back_to_the_read_write_library_key(self, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire(
+ session,
+ [
+ _response([{"Id": 7, "ReadOnlyApiKey": "", "ApiKey": "lib-rw"}], has_more=False),
+ _stream_response([]),
+ ],
+ )
+
+ _rows(_source(_make_manager(), endpoint="videos"))
+
+ assert sent[1].auth.api_key == "lib-rw"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_library_without_a_key_is_skipped(self, MockSession) -> None:
+ session = MockSession.return_value
+ # A library we cannot authenticate against must not fail the whole table.
+ _wire(session, [_response([{"Id": 7}], has_more=False)])
+
+ rows = _rows(_source(_make_manager(), endpoint="videos"))
+
+ assert rows == []
+ assert session.send.call_count == 1
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_library_statistics_pivot_onto_the_library_id(self, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire(
+ session,
+ [
+ _response([{"Id": 7, "ReadOnlyApiKey": "lib-ro"}], has_more=False),
+ _raw_response(
+ {
+ "viewsChart": {"2024-05-01T00:00:00": 4},
+ "watchTimeChart": {"2024-05-01T00:00:00": 120},
+ "countryViewCounts": {"US": 4},
+ }
+ ),
+ ],
+ )
+
+ rows = _rows(_source(_make_manager(), endpoint="video_library_statistics"))
+
+ assert sent[1].url == f"{BUNNY_STREAM_BASE_URL}/library/7/statistics"
+ # The country breakdown is a different grain and stays out of this table.
+ assert rows == [{"videoLibraryId": 7, "timestamp": _utc(1), "views": 4, "watchTime": 120}]
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
index 20f53cbd2de5..b941594c8c53 100644
--- 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
@@ -3,7 +3,10 @@ from unittest import mock
from posthog.schema import ReleaseStatus, SourceFieldInputConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.bunny.source import BunnySource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bunny import BunnySourceConfig
@@ -36,13 +39,17 @@ class TestBunnySource:
# 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_marks_only_the_statistics_tables_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert set(schemas) == set(ENDPOINTS)
+ # The list endpoints have no server-side timestamp filter, so they stay full refresh.
+ assert {name for name, s in schemas.items() if s.supports_incremental} == set(INCREMENTAL_FIELDS)
+ # Appending would re-add a row per run for every interval the statistics window still covers.
+ assert all(s.supports_append is False for s in schemas.values())
+ assert all(
+ [f["field"] for f in schema.incremental_fields] == [f["field"] for f in INCREMENTAL_FIELDS.get(name, [])]
+ for name, schema in schemas.items()
+ )
def test_documented_tables_render_for_public_docs(self) -> None:
# Exercises the credential-free catalog path used by the posthog.com docs.
@@ -55,6 +62,8 @@ class TestBunnySource:
[
"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",
+ "401 Client Error: Unauthorized for url: https://video.bunnycdn.com/library/7/videos?page=1",
+ "403 Client Error: Forbidden for url: https://video.bunnycdn.com/library/7/statistics",
],
)
def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
@@ -103,12 +112,17 @@ class TestBunnySource:
self.source.validate_credentials(self.config, self.team_id, schema_name="dns_zones")
mock_check.assert_called_once_with("bunny-key")
+ @pytest.mark.parametrize("should_use_incremental_field, expected_last_value", [(True, "2024-05-02"), (False, None)])
@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:
+ def test_source_for_pipeline_plumbs_arguments(
+ self, mock_bunny_source: mock.MagicMock, should_use_incremental_field: bool, expected_last_value: str | None
+ ) -> None:
inputs = mock.MagicMock()
inputs.schema_name = "pull_zones"
inputs.team_id = self.team_id
inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = should_use_incremental_field
+ inputs.db_incremental_field_last_value = "2024-05-02"
manager = mock.MagicMock()
self.source.source_for_pipeline(self.config, manager, inputs)
@@ -120,6 +134,8 @@ class TestBunnySource:
assert kwargs["team_id"] == self.team_id
assert kwargs["job_id"] == "job-1"
assert kwargs["resumable_source_manager"] is manager
+ # A full refresh must go out with no watermark, whatever the schema last recorded.
+ assert kwargs["db_incremental_field_last_value"] == expected_last_value
def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
inputs = mock.MagicMock()