: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(warehouse_sources): add four bunny.net tables (#101633)
Tom Owersef28eeab1fe6
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.mdindex 21b732eb609c..db622260dd2c 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@@ -1110,7 +1110,7 @@ Note: Buildkite publishes a complete machine-readable docs index at /docs/llms.t## Bunny — gaps-Today (9): `dns_zones`, `pull_zones`, `statistics`, `storage_zone_egress`, `storage_zone_statistics`, `storage_zones`, `video_libraries`, `video_library_statistics`, `videos`+Today (13): `dns_records`, `dns_zone_statistics`, `dns_zones`, `pull_zone_logs`, `pull_zones`, `statistics`, `storage_zone_egress`, `storage_zone_statistics`, `storage_zones`, `video_collections`, `video_libraries`, `video_library_statistics`, `videos`Diffed against: <https://core-api-public-docs.b-cdn.net/docs/v3/public.json>@@ -1118,10 +1118,10 @@ Diffed against: <https://core-api-public-docs.b-cdn.net/docs/v3/public.json>- [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)-- [ ] `GET /v2/pullzones/{pullZoneId}/logs (CDN Logging API)` — raw edge access logs — request-level detail for traffic analysis (medium)+- [x] `GET /dnszone/{zoneId}/records` — lookup/child table resolving the DNS zones we already sync into individual records (high)+- [x] `GET /dnszone/{id}/statistics` — DNS query volume per zone, the only usage metric for the DNS product (medium)+- [x] `GET /library/{libraryId}/collections (Stream API)` — lookup resolving the collection IDs carried on videos (medium)+- [x] `GET /v2/pullzones/{pullZoneId}/logs (CDN Logging API)` — raw edge access logs — request-level detail for traffic analysis (medium)- [ ] `GET /billing/summary` — spend per period per service, needed to tie CDN usage to cost (medium)- [ ] `GET /library/{libraryId}/videos/{videoId}/heatmap and /play (Stream API)` — per-video engagement/retention curve; the drop-off analysis people import video data for (medium)- [ ] `GET /pullzone/{pullZoneId}/optimizer/statistics` — image optimizer usage per pull zone, a breakdown of the traffic we would otherwise only see in aggregate (low)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.pyindex 49f42675e536..a496e25ceff7 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,15 +1,21 @@import dataclassesfrom collections.abc import Callable, Iterable, Iterator-from datetime import datetime+from datetime import UTC, datetimefrom typing import Any, Optionalfrom requests import Response+from requests.exceptions import HTTPErrorfrom posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.bunny.settings import (BUNNY_ENDPOINTS,DATE_FROM_PARAM,+ LOG_DATE_FROM_PARAM,+ LOG_DATE_TO_PARAM,+ LOG_EXCLUDED_FIELDS,+ LOG_RETENTION,+ LOG_WINDOW_MARGIN,BunnyEndpointConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value@@ -22,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import create_authfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,+ OffsetPaginator,PageNumberPaginator,SinglePagePaginator,)@@ -34,6 +41,8 @@ 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 CDN Logging API is a third host. It takes the same account API key as the Core API.+BUNNY_LOG_BASE_URL = "https://logging.bunnycdn.com"# The list endpoints accept perPage 5..1000; 1000 minimises round trips for the typically small# zone/library tables.PER_PAGE = 1000@@ -82,9 +91,29 @@ class BunnyHasMoreItemsPaginator(PageNumberPaginator):self._has_next_page = isinstance(body, dict) and bool(body.get("HasMoreItems", False))+class BunnyLogHasMorePaginator(OffsetPaginator):+ """Offset paginator that stops on the Logging API's explicit ``pagination.hasMore`` flag.++ The built-in stop conditions don't fit: the response reports no grand total, and the API+ applies some of its filters after fetching a page, so a short page does not mean the last+ one. The flag is the API's own termination signal.+ """++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ self.offset += self.limit+ try:+ body = response.json()+ except Exception:+ body = None+ pagination = body.get("pagination") if isinstance(body, dict) else None+ self._has_next_page = isinstance(pagination, dict) and bool(pagination.get("hasMore", False))++def _paginator_for(config: BunnyEndpointConfig) -> BasePaginator:if config.charts is not None:return SinglePagePaginator()+ if config.logging_api:+ return BunnyLogHasMorePaginator(limit=PER_PAGE)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.@@ -115,9 +144,16 @@ def _rest_client(access_key: str, base_url: str = BUNNY_BASE_URL) -> RESTClient:)-def _request_params(config: BunnyEndpointConfig, date_from: Optional[str] = None) -> dict[str, Any]:+def _request_params(+ config: BunnyEndpointConfig, date_from: Optional[str] = None, date_to: Optional[str] = None+) -> dict[str, Any]:if config.charts is not None:return {**config.params, DATE_FROM_PARAM: date_from}+ if config.logging_api:+ # The paginator carries this endpoint's page size, alongside its offset. `to` is fixed+ # once per sync (see `_log_date_to`) rather than left to the API's own default of "now",+ # so the window a run walks cannot grow while it walks it.+ return {**config.params, LOG_DATE_FROM_PARAM: date_from, LOG_DATE_TO_PARAM: date_to}return {config.page_size_param: PER_PAGE, **config.params}@@ -135,6 +171,32 @@ def _date_from(db_incremental_field_last_value: Any) -> Optional[str]:return value.strftime(DATE_FROM_FORMAT)+def _log_date_from(db_incremental_field_last_value: Any) -> str:+ """The ``from`` bound a log query asks from. Always set, unlike ``dateFrom``.++ The Logging API returns only the last 24 hours when no window is sent, which would drop+ entries whenever a sync runs less often than daily, so a first run asks from the retention+ edge instead. A later run asks from the newest entry the table already holds, clamped to+ that same edge because the API rejects a window starting before it. The overlap that the+ clamp and the open window end re-read upserts on the request id.+ """+ retention_edge = datetime.now(UTC) - LOG_RETENTION + LOG_WINDOW_MARGIN+ watermark = parse_datetime_value(db_incremental_field_last_value)+ date_from = retention_edge if watermark is None else max(watermark, retention_edge)+ return date_from.strftime(DATE_FROM_FORMAT)+++def _log_date_to() -> str:+ """The ``to`` bound a log query asks up to, captured once when the sync starts.++ The Logging API defaults ``to`` to the moment it handles each request. Sending that default+ on every page would let the window grow for as long as the walk takes, and a busy zone's+ ``pagination.hasMore`` could then stay true indefinitely. Fixing the bound once caps the+ window's size at the number of entries it held when the sync began.+ """+ return datetime.now(UTC).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.@@ -171,6 +233,7 @@ def _endpoint_calls(access_key: str, config: BunnyEndpointConfig) -> Iterator[Buyield BunnyEndpointCall(client=core_client, path=config.path, injected={})return+ child_client = _rest_client(access_key, BUNNY_LOG_BASE_URL) if config.logging_api else core_clientfor 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:@@ -178,7 +241,7 @@ def _endpoint_calls(access_key: str, config: BunnyEndpointConfig) -> Iterator[Buinjected = {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)+ yield BunnyEndpointCall(client=child_client, path=path, injected=injected)continuestream_key = _stream_access_key(parent_row)if stream_key is not None:@@ -238,6 +301,37 @@ def _fanout_list_pages(access_key: str, config: BunnyEndpointConfig) -> Iteratoryield [{**call.injected, **row} for row in page]+def _log_pages(+ access_key: str, config: BunnyEndpointConfig, db_incremental_field_last_value: Any, date_to: str+) -> Iterator[list[dict[str, Any]]]:+ """Walk the CDN access logs of every pull zone that has logging turned on."""+ for call in _endpoint_calls(access_key, config):+ # Recomputed per zone rather than once for the whole walk: a fan-out across many zones+ # can take longer than `LOG_WINDOW_MARGIN` allows, and the API rejects a `from` that has+ # since aged past the retention window it was computed against. `to` stays fixed (see+ # `_log_date_to`) since only the window START can expire this way.+ date_from = _log_date_from(db_incremental_field_last_value)+ params = _request_params(config, date_from, date_to)+ try:+ for page in call.client.paginate(+ call.path,+ params=params,+ data_selector=config.items_selector,+ data_selector_required=True,+ paginator=_paginator_for(config),+ ):+ if page:+ yield [+ {**call.injected, **{k: v for k, v in row.items() if k not in LOG_EXCLUDED_FIELDS}}+ for row in page+ ]+ except HTTPError as error:+ # The Logging API answers 404 for a pull zone with logging turned off. That is a+ # normal per-zone setting, not a failure of the table, so skip the zone.+ if error.response is None or error.response.status_code != 404:+ raise++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():@@ -293,6 +387,12 @@ def bunny_source(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.logging_api:+ date_to = _log_date_to()+ return _source_response(+ config, lambda: _log_pages(access_key, config, db_incremental_field_last_value, date_to)+ )+if config.parent is not None:return _source_response(config, lambda: _fanout_list_pages(access_key, config))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.pyindex bab2efab0c70..d6e75073851e 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@@ -54,6 +54,43 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"LoggingEnabled": "Whether DNS query logging is enabled.",},},+ "dns_records": {+ "description": "A single DNS record inside a bunny.net DNS zone.",+ "docs_url": "https://docs.bunny.net/reference/dnszonepublic_listdnszonerecords",+ "columns": {+ "DnsZoneId": "The ID of the DNS zone the record belongs to.",+ "Id": "The unique ID of the DNS record.",+ "Type": "The record type (0 = A, 1 = AAAA, 2 = CNAME, 3 = TXT, 4 = MX, and so on).",+ "Ttl": "The time-to-live of the record, in seconds.",+ "Value": "The value the record resolves to.",+ "Name": "The record name, relative to the zone's domain.",+ "Weight": "The relative weight used when several records share a name.",+ "Priority": "The priority of the record, for record types that use one.",+ "Port": "The port of the record, for SRV records.",+ "Accelerated": "Whether bunny.net CDN acceleration is enabled for the record.",+ "AcceleratedPullZoneId": "The ID of the pull zone used to accelerate the record.",+ "LatencyZone": "The latency zone the record is routed through.",+ "MonitorStatus": "The current uptime monitoring status of the record.",+ "MonitorType": "The uptime monitoring type configured for the record.",+ "SmartRoutingType": "The smart routing type configured for the record.",+ "GeolocationLatitude": "The latitude used for geolocation routing.",+ "GeolocationLongitude": "The longitude used for geolocation routing.",+ "Disabled": "Whether the record is disabled.",+ "Comment": "The free-text comment stored on the record.",+ "AutoSslIssuance": "Whether an SSL certificate is issued automatically for the record.",+ },+ },+ "dns_zone_statistics": {+ "description": "DNS queries answered for one DNS zone, for one time bucket.",+ "docs_url": "https://docs.bunny.net/reference/getdnszonestatisticsendpoint_statistics",+ "columns": {+ "DnsZoneId": "The ID of the DNS zone the values belong to.",+ "Timestamp": "The start of the interval the values cover.",+ "QueriesServed": "The total number of DNS queries answered in the interval.",+ "NormalQueriesServed": "The number of answered queries that used standard resolution.",+ "SmartQueriesServed": "The number of answered queries that used smart routing.",+ },+ },"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",@@ -114,6 +151,32 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"TotalEgress": "Download traffic served over all protocols, in bytes.",},},+ "pull_zone_logs": {+ "description": "A single CDN edge request served by a pull zone, from the bunny.net access logs. Only zones with logging enabled produce rows, and bunny.net retains a few days of entries.",+ "docs_url": "https://docs.bunny.net/docs/cdn-logging",+ "columns": {+ "pullZoneId": "The ID of the pull zone that served the request.",+ "requestId": "The unique ID of the request.",+ "timestamp": "The time the request reached the edge.",+ "cacheStatus": "The cache status reported by the edge, such as HIT, MISS, EXPIRED or STALE.",+ "statusCode": "The HTTP status code of the response.",+ "bytesSent": "The total bytes sent in the response, headers and body.",+ "bodyBytesSent": "The body-only bytes sent in the response. Only set when extended logging is enabled.",+ "remoteIp": "The client IP address. Partly or fully masked when the zone anonymizes IPs.",+ "countryCode": "The two-letter country code derived from the client IP.",+ "asn": "The autonomous system number derived from the client IP.",+ "asnOrganization": "The name of the organization that owns the autonomous system.",+ "edgeLocation": "The edge location that handled the request.",+ "scheme": "The request scheme, http or https.",+ "host": "The Host header of the request.",+ "path": "The request path, including the query string.",+ "url": "The full request URL.",+ "userAgent": "The User-Agent header of the request.",+ "referer": "The Referer header of the request.",+ "contentRange": "The Content-Range header of the response. Only set when extended logging is enabled.",+ "ja4Fingerprint": "The JA4 TLS fingerprint of the client.",+ },+ },"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",@@ -141,6 +204,19 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"totalWatchTime": "The total watch time of the video, in seconds.",},},+ "video_collections": {+ "description": "A collection inside a bunny.net Stream video library — the grouping the collection ID on a video points at.",+ "docs_url": "https://docs.bunny.net/reference/collection_list",+ "columns": {+ "videoLibraryId": "The ID of the video library the collection belongs to.",+ "guid": "The unique ID of the collection.",+ "name": "The name of the collection.",+ "videoCount": "The number of on-demand videos in the collection, excluding live streams.",+ "liveStreamCount": "The number of live streams in the collection.",+ "totalSize": "The total storage used by the videos in the collection, in bytes.",+ "previewVideoIds": "The video IDs used as preview thumbnails for the collection.",+ },+ },"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",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.pyindex 76be944af701..fa294c26a37a 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,4 +1,5 @@from dataclasses import field+from datetime import timedeltafrom typing import Any, Optionalfrom posthog.dataclasses import frozen@@ -28,6 +29,8 @@ class BunnyEndpointConfig:# 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+ # The CDN Logging API answers on its own host, but still takes the account API key.+ logging_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.@@ -39,7 +42,8 @@ class BunnyEndpointConfig:# 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.+ # The column holding the instant a row covers. Doubles as the incremental cursor, so it is+ # only set where the endpoint filters server-side on it.timestamp_column: Optional[str] = Nonesort_mode: SortMode = "asc"@@ -47,16 +51,41 @@ class BunnyEndpointConfig:# The statistics endpoints all take the same server-side start filter.DATE_FROM_PARAM = "dateFrom"+# The Logging API names its own window start differently, and serves entries from a rolling+# retention window only. It rejects a query that starts before that window, so a run asks from+# the later of the watermark and the oldest instant still retained.+LOG_DATE_FROM_PARAM = "from"+# `to` defaults to the moment the API handles each request, so a run that fixes it once and+# reuses it for every page and pull zone queries a stable window instead of one that keeps+# growing as new entries land during the walk. Without this a busy zone's `hasMore` could stay+# true indefinitely.+LOG_DATE_TO_PARAM = "to"+LOG_RETENTION = timedelta(days=3)+# The window end defaults to the moment the API handles the request, so the start is held just+# inside the retention edge to leave room for that and for request latency.+LOG_WINDOW_MARGIN = timedelta(minutes=5)+# A log row carries the request's decrypted `Authorization` header when the zone has extended+# logging on. That is a live end-user credential no analysis needs, so it never reaches a table.+LOG_EXCLUDED_FIELDS = frozenset({"authorizationHeader"})+# 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.+# default. The Logging API filters the same way, on its own window start.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"),+ "dns_records": BunnyEndpointConfig(+ name="dns_records",+ path="/dnszone/{id}/records",+ # A record id is only documented as unique inside its zone, so the zone id is part of+ # the key.+ primary_keys=["DnsZoneId", "Id"],+ parent=BunnyParentConfig(endpoint="dns_zones", id_field="Id", id_column="DnsZoneId"),+ ),"video_libraries": BunnyEndpointConfig(name="video_libraries", path="/videolibrary", partition_key="DateCreated"),"statistics": BunnyEndpointConfig(name="statistics",@@ -120,6 +149,37 @@ BUNNY_ENDPOINTS: dict[str, BunnyEndpointConfig] = {},sort_mode="desc",),+ "dns_zone_statistics": BunnyEndpointConfig(+ name="dns_zone_statistics",+ path="/dnszone/{id}/statistics",+ primary_keys=["DnsZoneId", "Timestamp"],+ partition_key="Timestamp",+ timestamp_column="Timestamp",+ parent=BunnyParentConfig(endpoint="dns_zones", id_field="Id", id_column="DnsZoneId"),+ # The query-type breakdown the same body carries is keyed by record type rather than by+ # time, so it belongs to a different grain and is left out of this table.+ charts={+ "QueriesServedChart": "QueriesServed",+ "NormalQueriesServedChart": "NormalQueriesServed",+ "SmartQueriesServedChart": "SmartQueriesServed",+ },+ sort_mode="desc",+ ),+ "pull_zone_logs": BunnyEndpointConfig(+ name="pull_zone_logs",+ path="/v2/pullzones/{id}/logs",+ primary_keys=["pullZoneId", "requestId"],+ partition_key="timestamp",+ logging_api=True,+ timestamp_column="timestamp",+ # Offset pagination is only stable while already-read rows keep their offset, so entries+ # are read oldest first and newly arrived ones land past the pages already walked.+ params={"order": "asc"},+ items_selector="data",+ parent=BunnyParentConfig(endpoint="pull_zones", id_field="Id", id_column="pullZoneId"),+ # Rows arrive grouped by pull zone, so the table as a whole is not in timestamp order.+ sort_mode="desc",+ ),"videos": BunnyEndpointConfig(name="videos",path="/library/{id}/videos",@@ -133,6 +193,16 @@ BUNNY_ENDPOINTS: dict[str, BunnyEndpointConfig] = {page_size_param="itemsPerPage",parent=BunnyParentConfig(endpoint="video_libraries", id_field="Id", id_column="videoLibraryId"),),+ "video_collections": BunnyEndpointConfig(+ name="video_collections",+ path="/library/{id}/collections",+ primary_keys=["videoLibraryId", "guid"],+ 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",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.pyindex cc280817af6d..1cd5acbc3b91 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@@ -88,6 +88,9 @@ You can find your account API key under **Account Settings → API** in the [bun# `/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.",+ # The CDN access logs are served by a third host, which takes the account API key.+ "401 Client Error: Unauthorized for url: https://logging.bunnycdn.com": "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://logging.bunnycdn.com": "Your bunny.net account API key does not have access to the CDN access logs. Check the key's permissions, then reconnect.",}def get_schemas(@@ -99,10 +102,10 @@ You can find your account API key under **Account Settings → API** in the [bunforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # 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.+ # Most list endpoints are full refresh only — they expose no server-side timestamp+ # filter, so there is no incremental cursor to advance. The statistics endpoints and the+ # CDN access logs do filter on a start date, and are 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(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.pyindex d99099000287..2dc121bbb5a1 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,6 +1,6 @@import jsonimport dataclasses-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Anyimport pytest@@ -12,13 +12,19 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.bunny.bunny import (BUNNY_BASE_URL,+ BUNNY_LOG_BASE_URL,BUNNY_STREAM_BASE_URL,PER_PAGE,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.bunny.settings import (+ BUNNY_ENDPOINTS,+ ENDPOINTS,+ LOG_RETENTION,+ LOG_WINDOW_MARGIN,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (RESTClientRetryableError,)@@ -29,6 +35,9 @@ CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_importsBUNNY_SESSION_PATCH = ("products.warehouse_sources.backend.temporal.data_imports.sources.bunny.bunny.make_tracked_session")+# `datetime.now` can't be patched on the real (C-level) class, so the module's own reference to+# `datetime` is replaced instead.+BUNNY_DATETIME_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.bunny.bunny.datetime"def _response(@@ -64,6 +73,17 @@ def _stream_response(items: list[dict[str, Any]]) -> Response:return _raw_response({"items": items, "totalItems": len(items), "currentPage": 1, "itemsPerPage": PER_PAGE})+def _log_response(entries: list[dict[str, Any]] | None, *, has_more: bool = False) -> Response:+ """A Logging API page envelope, which carries its own ``pagination.hasMore`` flag."""+ return _raw_response(+ {+ "data": entries,+ "pagination": {"offset": 0, "limit": PER_PAGE, "returned": len(entries or []), "hasMore": has_more},+ "query": {"pullZoneId": 1, "from": "2024-05-01T00:00:00Z", "to": "2024-05-02T00:00:00Z", "order": "asc"},+ }+ )++def _utc(day: int) -> datetime:return datetime(2024, 5, day, tzinfo=UTC)@@ -273,11 +293,15 @@ class TestBunnySourceResponse:("pull_zones", ["Id"], None),("storage_zones", ["Id"], None),("dns_zones", ["Id"], "DateCreated"),+ ("dns_records", ["DnsZoneId", "Id"], None),+ ("dns_zone_statistics", ["DnsZoneId", "Timestamp"], "Timestamp"),+ ("pull_zone_logs", ["pullZoneId", "requestId"], "timestamp"),("video_libraries", ["Id"], "DateCreated"),("statistics", ["Timestamp"], "Timestamp"),("storage_zone_statistics", ["StorageZoneId", "Timestamp"], "Timestamp"),("storage_zone_egress", ["StorageZoneId", "Timestamp"], "Timestamp"),("videos", ["videoLibraryId", "guid"], "dateUploaded"),+ ("video_collections", ["videoLibraryId", "guid"], None),("video_library_statistics", ["videoLibraryId", "timestamp"], "timestamp"),])@@ -440,24 +464,32 @@ class TestStorageZoneFanout:class TestStreamFanout:+ @parameterized.expand(+ [+ ("videos", "/library/7/videos", {"guid": "g1", "videoLibraryId": 7}),+ ("video_collections", "/library/7/collections", {"guid": "c1", "videoLibraryId": 7, "name": "Launch"}),+ ]+ )@mock.patch(CLIENT_SESSION_PATCH)- def test_videos_use_the_library_key_against_the_stream_host(self, MockSession) -> None:+ def test_lists_use_the_library_key_against_the_stream_host(+ self, endpoint: str, expected_path: str, row: dict[str, Any], MockSession+ ) -> None:session = MockSession.return_valuesent = _wire(session,[_response([{"Id": 7, "ReadOnlyApiKey": "lib-ro", "ApiKey": "lib-rw"}], has_more=False),- _stream_response([{"guid": "g1", "videoLibraryId": 7}]),+ _stream_response([row]),_stream_response([]),],)- rows = _rows(_source(_make_manager(), endpoint="videos"))+ rows = _rows(_source(_make_manager(), endpoint=endpoint))- assert rows == [{"guid": "g1", "videoLibraryId": 7}]+ assert rows == [row]# 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].url == f"{BUNNY_STREAM_BASE_URL}{expected_path}"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.@@ -511,3 +543,209 @@ class TestStreamFanout: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}]+++class TestDnsZoneFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_records_are_listed_per_zone_and_carry_the_zone_id(self, MockSession) -> None:+ session = MockSession.return_value+ sent = _wire(+ session,+ [+ _response([{"Id": 41}, {"Id": 42}], has_more=False),+ _response([{"Id": 1, "Type": 0, "Name": "www"}], has_more=True),+ _response([{"Id": 2, "Type": 3, "Name": "@"}], has_more=False),+ _response([{"Id": 3, "Type": 0, "Name": "api"}], has_more=False),+ ],+ )++ rows = _rows(_source(_make_manager(), endpoint="dns_records"))++ assert [s.url for s in sent] == [+ f"{BUNNY_BASE_URL}/dnszone",+ f"{BUNNY_BASE_URL}/dnszone/41/records",+ f"{BUNNY_BASE_URL}/dnszone/41/records",+ f"{BUNNY_BASE_URL}/dnszone/42/records",+ ]+ # The second zone starts over at page 1 rather than continuing the first zone's walk.+ assert [s.params["page"] for s in sent[1:]] == [1, 2, 1]+ assert rows == [+ {"DnsZoneId": 41, "Id": 1, "Type": 0, "Name": "www"},+ {"DnsZoneId": 41, "Id": 2, "Type": 3, "Name": "@"},+ {"DnsZoneId": 42, "Id": 3, "Type": 0, "Name": "api"},+ ]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_statistics_pivot_onto_the_zone_id(self, MockSession) -> None:+ session = MockSession.return_value+ sent = _wire(+ session,+ [+ _response([{"Id": 41}], has_more=False),+ _raw_response(+ {+ "TotalQueriesServed": 9,+ "QueriesServedChart": {"2024-05-01T00:00:00": 9},+ "NormalQueriesServedChart": {"2024-05-01T00:00:00": 7},+ "SmartQueriesServedChart": {"2024-05-01T00:00:00": 2},+ "QueriesByTypeChart": {"A": 6, "TXT": 3},+ }+ ),+ ],+ )++ rows = _rows(_source(_make_manager(), endpoint="dns_zone_statistics"))++ assert sent[1].url == f"{BUNNY_BASE_URL}/dnszone/41/statistics"+ # The query-type breakdown is keyed by record type, a different grain, so it stays out.+ assert rows == [+ {+ "DnsZoneId": 41,+ "Timestamp": _utc(1),+ "QueriesServed": 9,+ "NormalQueriesServed": 7,+ "SmartQueriesServed": 2,+ }+ ]+++class TestPullZoneLogs:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_walks_offsets_until_has_more_is_false(self, MockSession) -> None:+ session = MockSession.return_value+ sent = _wire(+ session,+ [+ _response([{"Id": 3}, {"Id": 4}], has_more=False),+ _log_response([{"requestId": "a", "statusCode": 200}], has_more=True),+ _log_response([{"requestId": "b", "statusCode": 404}], has_more=False),+ _log_response([{"requestId": "c", "statusCode": 200}], has_more=False),+ ],+ )++ rows = _rows(_source(_make_manager(), endpoint="pull_zone_logs"))++ assert [s.url for s in sent[1:]] == [+ f"{BUNNY_LOG_BASE_URL}/v2/pullzones/3/logs",+ f"{BUNNY_LOG_BASE_URL}/v2/pullzones/3/logs",+ f"{BUNNY_LOG_BASE_URL}/v2/pullzones/4/logs",+ ]+ assert sent[1].auth.api_key == "bunny-key"+ # A page shorter than the limit must not end the walk (only `pagination.hasMore` does),+ # and the second zone starts over at the first offset rather than continuing the first's.+ assert [s.params["offset"] for s in sent[1:]] == [0, PER_PAGE, 0]+ assert all(s.params["limit"] == PER_PAGE for s in sent[1:])+ assert sent[1].params["order"] == "asc"+ # `to` is fixed once per sync, not left to the API's own "now" default, so a page cannot+ # widen the window every zone and offset shares.+ assert len({s.params["to"] for s in sent[1:]}) == 1+ assert rows == [+ {"pullZoneId": 3, "requestId": "a", "statusCode": 200},+ {"pullZoneId": 3, "requestId": "b", "statusCode": 404},+ {"pullZoneId": 4, "requestId": "c", "statusCode": 200},+ ]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_a_null_data_page_is_zero_rows_not_a_shape_error(self, MockSession) -> None:+ session = MockSession.return_value+ # The API nulls `data` rather than returning an empty list when the window holds nothing.+ _wire(session, [_response([{"Id": 3}], has_more=False), _log_response(None)])++ assert _rows(_source(_make_manager(), endpoint="pull_zone_logs")) == []++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_the_decrypted_authorization_header_never_reaches_a_row(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response([{"Id": 3}], has_more=False),+ _log_response([{"requestId": "a", "authorizationHeader": "Bearer not-ours-to-keep", "path": "/x"}]),+ ],+ )++ rows = _rows(_source(_make_manager(), endpoint="pull_zone_logs"))++ assert rows == [{"pullZoneId": 3, "requestId": "a", "path": "/x"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_a_zone_with_logging_turned_off_is_skipped(self, MockSession) -> None:+ session = MockSession.return_value+ # 404 means logging is off for that zone, so the remaining zones must still sync.+ _wire(+ session,+ [+ _response([{"Id": 3}, {"Id": 4}], has_more=False),+ _raw_response({"error": "Logging is not enabled for this pull zone"}, status_code=404),+ _log_response([{"requestId": "b"}]),+ ],+ )++ rows = _rows(_source(_make_manager(), endpoint="pull_zone_logs"))++ assert rows == [{"pullZoneId": 4, "requestId": "b"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_an_auth_failure_still_fails_the_table(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"Id": 3}], has_more=False), _raw_response({"error": "x"}, status_code=403)])++ with pytest.raises(requests.HTTPError):+ _rows(_source(_make_manager(), endpoint="pull_zone_logs"))++ @parameterized.expand(+ [+ # No watermark yet: seed the whole window bunny.net still retains.+ ("first_run", None, LOG_RETENTION - LOG_WINDOW_MARGIN),+ # A watermark inside the window is asked from as-is.+ ("recent_watermark", timedelta(hours=6), timedelta(hours=6)),+ # An older one is clamped, because the API rejects a window starting before retention.+ ("stale_watermark", timedelta(days=30), LOG_RETENTION - LOG_WINDOW_MARGIN),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_asks_from_the_watermark_clamped_to_retention(+ self, _name: str, watermark_age: timedelta | None, expected_age: timedelta, MockSession+ ) -> None:+ session = MockSession.return_value+ sent = _wire(session, [_response([{"Id": 3}], has_more=False), _log_response([])])++ now = datetime.now(UTC)+ _rows(+ _source(+ _make_manager(),+ endpoint="pull_zone_logs",+ last_value=None if watermark_age is None else now - watermark_age,+ )+ )++ asked = datetime.strptime(sent[1].params["from"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)+ assert abs((now - expected_age) - asked) < timedelta(minutes=1)++ @mock.patch(CLIENT_SESSION_PATCH)+ @mock.patch(BUNNY_DATETIME_PATCH)+ def test_from_is_reclamped_per_zone_but_to_stays_fixed(self, MockDatetime, MockSession) -> None:+ # A fan-out across many zones can take longer than `LOG_WINDOW_MARGIN` allows. `from`+ # must be recomputed against "now" at each zone so a later zone's request still falls+ # inside the retention window; `to` must not, or the window it walks would grow.+ session = MockSession.return_value+ sent = _wire(+ session,+ [+ _response([{"Id": 3}, {"Id": 4}], has_more=False),+ _log_response([]),+ _log_response([]),+ ],+ )++ base = datetime(2024, 5, 2, 0, 0, 0, tzinfo=UTC)+ # Call order: `_log_date_to` once, then `_log_date_from` once per zone. The second+ # zone's "now" is far enough ahead to move its retention edge.+ MockDatetime.now.side_effect = [base, base, base + LOG_WINDOW_MARGIN + timedelta(minutes=10)]++ _rows(_source(_make_manager(), endpoint="pull_zone_logs"))++ first_from = datetime.strptime(sent[1].params["from"], "%Y-%m-%dT%H:%M:%SZ")+ second_from = datetime.strptime(sent[2].params["from"], "%Y-%m-%dT%H:%M:%SZ")+ assert second_from > first_from+ assert sent[1].params["to"] == sent[2].params["to"]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.pyindex ea03374b9b0f..48b194f13ad0 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@@ -38,12 +38,12 @@ 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_marks_only_the_statistics_tables_incremental(self) -> None:+ def test_get_schemas_marks_only_the_date_filtered_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.+ # Appending would re-add a row per run for every interval the request 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, [])]@@ -63,6 +63,8 @@ class TestBunnySource:"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",+ "401 Client Error: Unauthorized for url: https://logging.bunnycdn.com/v2/pullzones/3/logs?offset=0",+ "403 Client Error: Forbidden for url: https://logging.bunnycdn.com/v2/pullzones/3/logs?offset=0",],)def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:@@ -75,6 +77,8 @@ class TestBunnySource:"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",+ # Logging is simply off for that pull zone, so the sync skips it rather than failing.+ "404 Client Error: Not Found for url: https://logging.bunnycdn.com/v2/pullzones/3/logs",],)def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None: