Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement blogger import source (#66753)

Tom Owers56c1b490604c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 718b91c2ccdc..921d8393662c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -62,6 +62,7 @@ the row lists both.
| bigmailer | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
+| blogger | HTTP | requests | ✅ |
| braintree | HTTP (GraphQL) | requests | ✅ |
| braze | HTTP | requests | ✅ |
| brevo | HTTP | requests | ✅ |
@@ -321,7 +322,6 @@ doesn't conflict with concurrent PRs.
- basecamp
- bigcommerce
- bitly
-- blogger
- bluetally
- boldsign
- box
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/blogger.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/blogger.py
new file mode 100644
index 000000000000..9d0f56e75247
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/blogger.py
@@ -0,0 +1,210 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import urlencode, urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.settings import (
+ BLOGGER_ENDPOINTS,
+ BloggerEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+BLOGGER_BASE_URL = "https://www.googleapis.com/blogger/v3"
+# Blogger caps `maxResults` per resource; 100 is comfortably within the limits for posts/comments/pages.
+DEFAULT_PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class BloggerRetryableError(Exception):
+ """Raised for transient Blogger API failures (429 / 5xx) that tenacity should retry."""
+
+
+class BloggerResumeConfig:
+ # Blogger paginates with an opaque `pageToken`; persisting it lets a heartbeat-timed-out sync pick
+ # back up at the next page instead of restarting the endpoint.
+ page_token: str | None = None
+
+
+def _format_rfc3339(value: Any) -> str:
+ """Format a datetime/date as an RFC 3339 UTC timestamp, which Blogger's date filters require."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def _headers() -> dict[str, str]:
+ return {"Accept": "application/json"}
+
+
+def _raise_sanitized_for_status(response: requests.Response) -> None:
+ """Mirror `requests.Response.raise_for_status()` but strip the URL's query string before it lands
+ in an exception message. Blogger carries the API key in `?key=...`, and these import errors are
+ logged and captured by the shared non-retryable error handler — so the raw `raise_for_status()`
+ message would leak the key. The sanitized URL keeps the stable `.../blogger/v3` prefix that
+ `BloggerSource.get_non_retryable_errors()` matches on, so error classification is unaffected."""
+ if response.ok:
+ return
+ kind = "Client Error" if response.status_code < 500 else "Server Error"
+ safe_url = urlsplit(response.url)._replace(query="").geturl()
+ raise requests.HTTPError(f"{response.status_code} {kind}: {response.reason} for url: {safe_url}", response=response)
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ return f"{BLOGGER_BASE_URL}{path}?{urlencode(params)}"
+
+
+def _build_params(
+ config: BloggerEndpointConfig,
+ api_key: str,
+ page_token: str | None,
+ start_date: str | None,
+) -> dict[str, Any]:
+ # The Google API key always rides as the `key` query param (Blogger has no header form for it).
+ params: dict[str, Any] = {"key": api_key}
+ if config.is_single_object:
+ return params
+
+ params["maxResults"] = DEFAULT_PAGE_SIZE
+ if config.order_by:
+ params["orderBy"] = config.order_by
+ if start_date:
+ params["startDate"] = start_date
+ if page_token:
+ params["pageToken"] = page_token
+ return params
+
+
+@retry(
+ retry=retry_if_exception_type((BloggerRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BloggerRetryableError(f"Blogger API error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ logger.error(f"Blogger API error: status={response.status_code}, body={response.text}")
+ _raise_sanitized_for_status(response)
+
+ return response.json()
+
+
+def validate_credentials(api_key: str, blog_id: str) -> tuple[bool, str | None]:
+ """Probe `blogs.get` for the configured blog. This confirms both the API key and that the key can
+ read the target blog in a single cheap request."""
+ url = _build_url(f"/blogs/{blog_id}", {"key": api_key})
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_headers(), timeout=10)
+ except Exception:
+ return False, "Could not reach the Blogger API. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (400, 401, 403):
+ return False, "Your Blogger API key is invalid or does not have access to this blog."
+ if response.status_code == 404:
+ return False, "No Blogger blog was found for that blog ID."
+ return False, f"The Blogger API returned an unexpected error (status {response.status_code})."
+
+
+def get_rows(
+ api_key: str,
+ blog_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BloggerResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = BLOGGER_ENDPOINTS[endpoint]
+ # One session reused across every page so urllib3 keeps the connection alive. The API key is in the
+ # query string, so register it for redaction in logged URLs and captured samples.
+ session = make_tracked_session(redact_values=(api_key,))
+ headers = _headers()
+
+ if config.is_single_object:
+ data = _fetch_page(session, _build_url(config.path.format(blog_id=blog_id), {"key": api_key}), headers, logger)
+ yield [data]
+ return
+
+ # `startDate` is the only server-side filter Blogger offers; map the user's incremental cursor
+ # (always `published`) onto it. On first sync there's no last value, so we pull full history.
+ start_date: str | None = None
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:
+ start_date = _format_rfc3339(db_incremental_field_last_value)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page_token = resume.page_token if resume is not None else None
+
+ base_path = config.path.format(blog_id=blog_id)
+ while True:
+ url = _build_url(base_path, _build_params(config, api_key, page_token, start_date))
+ data = _fetch_page(session, url, headers, logger)
+
+ items = data.get("items", [])
+ next_token = data.get("nextPageToken")
+
+ if items:
+ yield items
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last page
+ # rather than skipping it — merge dedupes on the primary key.
+ if next_token:
+ resumable_source_manager.save_state(BloggerResumeConfig(page_token=next_token))
+
+ if not next_token:
+ break
+ page_token = next_token
+
+
+def blogger_source(
+ api_key: str,
+ blog_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BloggerResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = BLOGGER_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ blog_id=blog_id,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ # Blogger only returns list results newest-first (its sort-direction param is unavailable), so
+ # incremental endpoints scroll descending. Full-refresh endpoints don't care about order.
+ sort_mode="desc" if config.supports_incremental else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/canonical_descriptions.py
new file mode 100644
index 000000000000..6ae8f562ea16
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/canonical_descriptions.py
@@ -0,0 +1,70 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "blogs": {
+ "description": "The Blogger blog being synced, with its metadata and aggregate post/page counts.",
+ "docs_url": "https://developers.google.com/blogger/docs/3.0/reference/blogs",
+ "columns": {
+ "id": "Unique identifier for the blog.",
+ "name": "The display name of the blog.",
+ "description": "The blog's description.",
+ "published": "RFC 3339 timestamp of when the blog was created.",
+ "updated": "RFC 3339 timestamp of when the blog was last updated.",
+ "url": "The public URL of the blog.",
+ "posts": "Aggregate information about the blog's posts (total count and self link).",
+ "pages": "Aggregate information about the blog's pages (total count and self link).",
+ "locale": "The locale (language, country, variant) configured for the blog.",
+ "status": "Status of the blog (e.g. LIVE).",
+ },
+ },
+ "posts": {
+ "description": "Posts published to the blog. Synced incrementally on the immutable `published` date.",
+ "docs_url": "https://developers.google.com/blogger/docs/3.0/reference/posts",
+ "columns": {
+ "id": "Unique identifier for the post.",
+ "blog": "The blog this post belongs to (contains the blog id).",
+ "published": "RFC 3339 timestamp of when the post was published.",
+ "updated": "RFC 3339 timestamp of when the post was last updated.",
+ "url": "The public URL of the post.",
+ "title": "The title of the post.",
+ "content": "The HTML body of the post.",
+ "author": "The post author (id, display name, url, and image).",
+ "labels": "List of labels applied to the post.",
+ "replies": "Aggregate information about the post's comments (total count and self link).",
+ "images": "Images attached to the post.",
+ "status": "Status of the post (e.g. LIVE, DRAFT, SCHEDULED).",
+ },
+ },
+ "pages": {
+ "description": "Static pages on the blog. Full refresh only — the API exposes no date filter for pages.",
+ "docs_url": "https://developers.google.com/blogger/docs/3.0/reference/pages",
+ "columns": {
+ "id": "Unique identifier for the page.",
+ "blog": "The blog this page belongs to (contains the blog id).",
+ "published": "RFC 3339 timestamp of when the page was created.",
+ "updated": "RFC 3339 timestamp of when the page was last updated.",
+ "url": "The public URL of the page.",
+ "title": "The title of the page.",
+ "content": "The HTML body of the page.",
+ "author": "The page author (id, display name, url, and image).",
+ "status": "Status of the page (e.g. LIVE, DRAFT).",
+ },
+ },
+ "comments": {
+ "description": "Comments across all of the blog's posts. Synced incrementally on the immutable `published` date.",
+ "docs_url": "https://developers.google.com/blogger/docs/3.0/reference/comments",
+ "columns": {
+ "id": "Unique identifier for the comment.",
+ "post": "The post this comment was made on (contains the post id).",
+ "blog": "The blog this comment belongs to (contains the blog id).",
+ "published": "RFC 3339 timestamp of when the comment was published.",
+ "updated": "RFC 3339 timestamp of when the comment was last updated.",
+ "content": "The body of the comment.",
+ "author": "The comment author (id, display name, url, and image).",
+ "inReplyTo": "The comment this comment replies to, if any (contains the parent comment id).",
+ "status": "Status of the comment (e.g. LIVE, PENDING, SPAM).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/settings.py
new file mode 100644
index 000000000000..2842e85818e0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/settings.py
@@ -0,0 +1,75 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class BloggerEndpointConfig:
+ name: str
+ # Path under the Blogger v3 base URL, with a `{blog_id}` placeholder where needed.
+ path: str
+ incremental_fields: list[IncrementalField]
+ # Stable datetime field to partition by. Blogger's `published` never changes once a post/comment
+ # exists, so it's a safe partition key (never use the mutable `updated` field).
+ partition_key: Optional[str] = None
+ # `orderBy` value to request. Only `posts.list` accepts it; `comments.listByBlog` ignores ordering
+ # params and always returns newest-first, so it's left unset there.
+ order_by: Optional[str] = None
+ # True only where the API exposes a genuine server-side date filter (`startDate`). `posts.list`
+ # and `comments.listByBlog` filter on the resource's `published` date; pages/blogs do not.
+ supports_incremental: bool = False
+ # `blogs.get` returns a single blog object rather than a paginated `items` list.
+ is_single_object: bool = False
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+
+
+def _published_incremental_fields() -> list[IncrementalField]:
+ # Blogger's `startDate`/`endDate` filter on the resource's post/comment date (`published`), so
+ # `published` is the only field we can filter server-side. `published` is also immutable, which
+ # makes it a stable cursor that won't rewind.
+ return [
+ {
+ "label": "published",
+ "type": IncrementalFieldType.DateTime,
+ "field": "published",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+BLOGGER_ENDPOINTS: dict[str, BloggerEndpointConfig] = {
+ "blogs": BloggerEndpointConfig(
+ name="blogs",
+ path="/blogs/{blog_id}",
+ incremental_fields=[],
+ is_single_object=True,
+ ),
+ "posts": BloggerEndpointConfig(
+ name="posts",
+ path="/blogs/{blog_id}/posts",
+ partition_key="published",
+ order_by="published",
+ supports_incremental=True,
+ incremental_fields=_published_incremental_fields(),
+ ),
+ "pages": BloggerEndpointConfig(
+ name="pages",
+ path="/blogs/{blog_id}/pages",
+ incremental_fields=[],
+ ),
+ "comments": BloggerEndpointConfig(
+ name="comments",
+ path="/blogs/{blog_id}/comments",
+ partition_key="published",
+ supports_incremental=True,
+ incremental_fields=_published_incremental_fields(),
+ ),
+}
+
+ENDPOINTS = tuple(BLOGGER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BLOGGER_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/source.py
index 0f7141c40a62..e9ee9f1cab0a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/source.py
@@ -1,19 +1,42 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.blogger import (
+ BloggerResumeConfig,
+ blogger_source,
+ validate_credentials as validate_blogger_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.settings import (
+ BLOGGER_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BloggerSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BloggerSource(SimpleSource[BloggerSourceConfig]):
+class BloggerSource(ResumableSource[BloggerSourceConfig, BloggerResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BLOGGER
@@ -24,7 +47,107 @@ class BloggerSource(SimpleSource[BloggerSourceConfig]):
name=SchemaExternalDataSourceType.BLOGGER,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Blogger",
- iconPath="/static/services/blogger.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
+ # Kept hidden for now: shipping in alpha behind the unreleased flag until it has had
+ # an end-to-end sync verified against the live API with real credentials.
unreleasedSource=True,
+ caption="""Enter a Google API key and a Blogger blog ID to pull your Blogger content into the PostHog Data warehouse.
+
+Create an API key in the [Google Cloud console](https://console.cloud.google.com/apis/credentials) and enable the **Blogger API v3** for the project.
+
+Your blog ID is shown in the Blogger dashboard URL (`blogger.com/blog/posts/<blogId>`).
+
+The API key reads publicly visible content (live posts, pages, and comments). Drafts and admin-only data require OAuth, which isn't supported yet.""",
+ iconPath="/static/services/blogger.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/blogger",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="AIza...",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="blog_id",
+ label="Blog ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="1234567890123456789",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A missing/invalid API key, a key not authorized for the Blogger API, or a private blog all
+ # surface as a non-2xx HTTPError once `_fetch_page` calls `raise_for_status()`. Retrying can
+ # never fix a credential/permission problem, so stop the sync. Match on the stable base host.
+ "400 Client Error: Bad Request for url: https://www.googleapis.com/blogger/v3": "Your Blogger API key is invalid. Create a new key in the Google Cloud console with the Blogger API enabled, then reconnect.",
+ "401 Client Error: Unauthorized for url: https://www.googleapis.com/blogger/v3": "Your Blogger API key is invalid or has been revoked. Create a new key in the Google Cloud console, then reconnect.",
+ "403 Client Error: Forbidden for url: https://www.googleapis.com/blogger/v3": "Your Blogger API key cannot access this blog. Enable the Blogger API for your Google Cloud project and confirm the blog is publicly visible, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: BloggerSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = BLOGGER_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=endpoint_config.incremental_fields,
+ should_sync_default=endpoint_config.should_sync_default,
+ detected_primary_keys=endpoint_config.primary_keys,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: BloggerSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_blogger_credentials(config.api_key, config.blog_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BloggerResumeConfig]:
+ return ResumableSourceManager[BloggerResumeConfig](inputs, BloggerResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BloggerSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BloggerResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return blogger_source(
+ api_key=config.api_key,
+ blog_id=config.blog_id,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger.py
new file mode 100644
index 000000000000..99db8c976276
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger.py
@@ -0,0 +1,321 @@
+from datetime import UTC, date, datetime, timedelta, timezone
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger import blogger
+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.blogger import (
+ BloggerResumeConfig,
+ _build_params,
+ _format_rfc3339,
+ blogger_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.settings import BLOGGER_ENDPOINTS
+
+
+class _FakeResponse:
+ def __init__(
+ self,
+ status_code: int,
+ json_data: dict | None = None,
+ *,
+ url: str = "https://www.googleapis.com/blogger/v3",
+ reason: str = "OK",
+ text: str = "",
+ ) -> None:
+ self.status_code = status_code
+ self._json = json_data or {}
+ self.text = text
+ self.url = url
+ self.reason = reason
+ self.ok = 200 <= status_code < 300
+
+ def json(self) -> dict:
+ return self._json
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise requests.HTTPError(
+ f"{self.status_code} error for url: {self.url}", response=cast(requests.Response, self)
+ )
+
+
+class _FakeSession:
+ def __init__(self, response: _FakeResponse) -> None:
+ self._response = response
+ self.requested_urls: list[str] = []
+
+ def get(self, url: str, headers: dict | None = None, timeout: int | None = None) -> _FakeResponse:
+ self.requested_urls.append(url)
+ return self._response
+
+
+class _FakeResumableManager:
+ def __init__(self, state: BloggerResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[BloggerResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> BloggerResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: BloggerResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class _SequentialFetch:
+ """Stand-in for `_fetch_page` that returns canned responses in order and records request URLs."""
+
+ def __init__(self, responses: list[dict]) -> None:
+ self._responses = list(responses)
+ self.urls: list[str] = []
+
+ def __call__(self, session: Any, url: str, headers: dict, logger: Any) -> dict:
+ self.urls.append(url)
+ return self._responses.pop(0)
+
+
+def _collect(
+ endpoint: str,
+ manager: _FakeResumableManager,
+ fetch: _SequentialFetch,
+ **kwargs: Any,
+) -> list[dict]:
+ rows: list[dict] = []
+ with (
+ patch.object(blogger, "_fetch_page", fetch),
+ patch.object(blogger, "make_tracked_session", lambda **_: MagicMock()),
+ ):
+ for batch in get_rows(
+ api_key="K",
+ blog_id="BID",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestFormatRfc3339:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_datetime_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ (
+ "non_utc_converted",
+ datetime(2026, 3, 4, 2, 58, 14, tzinfo=timezone(timedelta(hours=2))),
+ "2026-03-04T00:58:14Z",
+ ),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "opaque-cursor", "opaque-cursor"),
+ ]
+ )
+ def test_format(self, _name: str, value: object, expected: str) -> None:
+ assert _format_rfc3339(value) == expected
+
+ def test_no_plus_zero_offset(self) -> None:
+ assert "+00:00" not in _format_rfc3339(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+
+
+class TestBuildParams:
+ def test_single_object_sends_only_key(self) -> None:
+ params = _build_params(BLOGGER_ENDPOINTS["blogs"], "K", page_token=None, start_date=None)
+ assert params == {"key": "K"}
+
+ def test_posts_sends_max_results_and_order_by(self) -> None:
+ params = _build_params(BLOGGER_ENDPOINTS["posts"], "K", page_token=None, start_date=None)
+ assert params["key"] == "K"
+ assert params["maxResults"] == 100
+ assert params["orderBy"] == "published"
+ assert "startDate" not in params
+ assert "pageToken" not in params
+
+ def test_comments_has_no_order_by(self) -> None:
+ # comments.listByBlog rejects ordering params, so we never send orderBy for it.
+ params = _build_params(BLOGGER_ENDPOINTS["comments"], "K", page_token=None, start_date=None)
+ assert "orderBy" not in params
+
+ def test_start_date_and_page_token_included(self) -> None:
+ params = _build_params(BLOGGER_ENDPOINTS["posts"], "K", page_token="TOK", start_date="2026-03-04T00:00:00Z")
+ assert params["startDate"] == "2026-03-04T00:00:00Z"
+ assert params["pageToken"] == "TOK"
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("bad_request", 400, False),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("not_found", 404, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, expected_ok: bool) -> None:
+ session = _FakeSession(_FakeResponse(status))
+ with patch.object(blogger, "make_tracked_session", lambda **_: session):
+ ok, error = validate_credentials("K", "BID")
+ assert ok is expected_ok
+ if not expected_ok:
+ assert error
+
+ def test_network_error_returns_false(self) -> None:
+ class _Boom:
+ def get(self, *args: Any, **kwargs: Any) -> Any:
+ raise requests.ConnectionError("boom")
+
+ with patch.object(blogger, "make_tracked_session", lambda **_: _Boom()):
+ ok, error = validate_credentials("K", "BID")
+ assert ok is False
+ assert error
+
+
+class TestGetRows:
+ def test_single_object_yields_one_row(self) -> None:
+ fetch = _SequentialFetch([{"id": "B1", "name": "My blog"}])
+ manager = _FakeResumableManager()
+ rows = _collect("blogs", manager, fetch)
+ assert rows == [{"id": "B1", "name": "My blog"}]
+ assert manager.saved == []
+ assert "/blogs/BID?key=K" in fetch.urls[0]
+
+ def test_list_paginates_and_saves_state_only_when_more_pages(self) -> None:
+ fetch = _SequentialFetch(
+ [
+ {"items": [{"id": "p1"}, {"id": "p2"}], "nextPageToken": "T2"},
+ {"items": [{"id": "p3"}], "nextPageToken": None},
+ ]
+ )
+ manager = _FakeResumableManager()
+ rows = _collect("posts", manager, fetch)
+ assert [r["id"] for r in rows] == ["p1", "p2", "p3"]
+ # State is saved once — after the first page (which had a next token), not after the last.
+ assert manager.saved == [BloggerResumeConfig(page_token="T2")]
+ # The second request carries the page token from the first response.
+ assert "pageToken=T2" in fetch.urls[1]
+ # Full refresh sends no startDate.
+ assert all("startDate" not in url for url in fetch.urls)
+
+ def test_incremental_maps_last_value_to_start_date(self) -> None:
+ fetch = _SequentialFetch([{"items": [{"id": "p1"}], "nextPageToken": None}])
+ manager = _FakeResumableManager()
+ _collect(
+ "posts",
+ manager,
+ fetch,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="published",
+ )
+ # Colons are percent-encoded by urlencode.
+ assert "startDate=2026-03-04T02%3A58%3A14Z" in fetch.urls[0]
+
+ def test_first_sync_without_last_value_sends_no_start_date(self) -> None:
+ fetch = _SequentialFetch([{"items": [{"id": "p1"}], "nextPageToken": None}])
+ manager = _FakeResumableManager()
+ _collect(
+ "posts",
+ manager,
+ fetch,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="published",
+ )
+ assert "startDate" not in fetch.urls[0]
+
+ def test_resume_starts_from_saved_page_token(self) -> None:
+ fetch = _SequentialFetch([{"items": [{"id": "p9"}], "nextPageToken": None}])
+ manager = _FakeResumableManager(BloggerResumeConfig(page_token="RESUME"))
+ rows = _collect("posts", manager, fetch)
+ assert [r["id"] for r in rows] == ["p9"]
+ assert "pageToken=RESUME" in fetch.urls[0]
+
+ @parameterized.expand(
+ [
+ # Stop-immediately: a single empty page with no continuation token.
+ ("single_empty_page", [{"items": [], "nextPageToken": None}], 1),
+ # Walk-through: an empty page that still hands back a token loops to the next page,
+ # which is also empty. No state is ever saved for empty pages.
+ (
+ "empty_pages_with_continuation",
+ [{"items": [], "nextPageToken": "T2"}, {"items": [], "nextPageToken": None}],
+ 2,
+ ),
+ ]
+ )
+ def test_empty_items_never_save_state(self, _name: str, responses: list[dict], expected_requests: int) -> None:
+ fetch = _SequentialFetch(responses)
+ manager = _FakeResumableManager()
+ rows = _collect("posts", manager, fetch)
+ assert rows == []
+ # Empty pages never persist a resume token: a crash mid-sequence re-walks the empty pages
+ # rather than skipping past them, so no unseen data is missed on resume.
+ assert manager.saved == []
+ assert len(fetch.urls) == expected_requests
+ if expected_requests > 1:
+ # The continuation token from the empty page still drives the follow-up request.
+ assert "pageToken=T2" in fetch.urls[1]
+
+
+class TestFetchPageErrorSanitization:
+ def test_client_error_strips_api_key_but_keeps_matchable_prefix(self) -> None:
+ # The real URL carries the key in the query string; the raised error must not leak it.
+ leaky_url = "https://www.googleapis.com/blogger/v3/blogs/BID/posts?key=SECRETKEY&maxResults=100"
+ session = _FakeSession(_FakeResponse(400, url=leaky_url, reason="Bad Request"))
+ with pytest.raises(requests.HTTPError) as exc_info:
+ blogger._fetch_page(session, leaky_url, {}, MagicMock()) # type: ignore[arg-type]
+ message = str(exc_info.value)
+ assert "SECRETKEY" not in message
+ # The non-retryable matcher keys are prefixes of this message, so error classification still works.
+ assert "400 Client Error: Bad Request for url: https://www.googleapis.com/blogger/v3" in message
+
+
+class TestBloggerSourceResponse:
+ @parameterized.expand([("posts", "desc"), ("comments", "desc"), ("blogs", "asc"), ("pages", "asc")])
+ def test_sort_mode_matches_incremental(self, endpoint: str, expected: str) -> None:
+ response = blogger_source(
+ api_key="K",
+ blog_id="BID",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == expected
+
+ @parameterized.expand([("posts",), ("comments",)])
+ def test_incremental_endpoints_partition_by_published(self, endpoint: str) -> None:
+ response = blogger_source(
+ api_key="K",
+ blog_id="BID",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["published"]
+ assert response.partition_format == "month"
+
+ @parameterized.expand([("blogs",), ("pages",)])
+ def test_full_refresh_endpoints_have_no_partition(self, endpoint: str) -> None:
+ response = blogger_source(
+ api_key="K",
+ blog_id="BID",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger_source.py
new file mode 100644
index 000000000000..f6347d159b3b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger_source.py
@@ -0,0 +1,196 @@
+from types import SimpleNamespace
+from typing import Any, cast
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.blogger import BloggerResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.source import BloggerSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "posts",
+ "schema_id": "schema-id",
+ "source_id": "source-id",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-id",
+ "logger": MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestBloggerSourceConfig:
+ def test_source_type(self) -> None:
+ assert BloggerSource().source_type == ExternalDataSourceType.BLOGGER
+
+ def test_source_config_metadata(self) -> None:
+ config = BloggerSource().get_source_config
+ assert config.name == SchemaExternalDataSourceType.BLOGGER
+ assert config.category == DataWarehouseSourceCategory.PRODUCTIVITY
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/blogger"
+
+ def test_source_config_fields(self) -> None:
+ fields = {f.name: cast(SourceFieldInputConfig, f) for f in BloggerSource().get_source_config.fields}
+ assert set(fields) == {"api_key", "blog_id"}
+
+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD
+ assert fields["api_key"].required is True
+ assert fields["api_key"].secret is True
+
+ assert fields["blog_id"].type == SourceFieldInputConfigType.TEXT
+ assert fields["blog_id"].required is True
+ assert fields["blog_id"].secret is False
+
+
+class TestBloggerSchemas:
+ def test_get_schemas(self) -> None:
+ schemas = {s.name: s for s in BloggerSource().get_schemas(MagicMock(), team_id=1)}
+ assert set(schemas) == {"blogs", "posts", "pages", "comments"}
+
+ # Only posts/comments expose a server-side date filter, so only they are incremental.
+ assert schemas["posts"].supports_incremental is True
+ assert schemas["comments"].supports_incremental is True
+ assert schemas["pages"].supports_incremental is False
+ assert schemas["blogs"].supports_incremental is False
+
+ assert [f["field"] for f in schemas["posts"].incremental_fields] == ["published"]
+ assert schemas["pages"].incremental_fields == []
+ for schema in schemas.values():
+ assert schema.detected_primary_keys == ["id"]
+
+ def test_get_schemas_names_filter(self) -> None:
+ schemas = BloggerSource().get_schemas(MagicMock(), team_id=1, names=["posts"])
+ assert [s.name for s in schemas] == ["posts"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert BloggerSource.lists_tables_without_credentials is True
+
+ def test_documented_tables_render_with_canonical_descriptions(self) -> None:
+ tables = {t["name"]: t for t in BloggerSource().get_documented_tables()}
+ assert set(tables) == {"blogs", "posts", "pages", "comments"}
+ assert "Incremental" in tables["posts"]["sync_methods"]
+ assert "Incremental" not in tables["pages"]["sync_methods"]
+ # Description comes from canonical_descriptions.py.
+ assert tables["posts"]["description"]
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = BloggerSource().get_canonical_descriptions()
+ assert set(descriptions) == {"blogs", "posts", "pages", "comments"}
+ assert "id" in descriptions["posts"]["columns"]
+
+
+class TestBloggerCredentials:
+ def test_validate_credentials_delegates_to_transport(self) -> None:
+ config = SimpleNamespace(api_key="K", blog_id="BID")
+ with patch.object(source_module, "validate_blogger_credentials", return_value=(True, None)) as mock_validate:
+ result = BloggerSource().validate_credentials(config, team_id=1) # type: ignore[arg-type]
+ assert result == (True, None)
+ mock_validate.assert_called_once_with("K", "BID")
+
+ def test_validate_credentials_propagates_failure(self) -> None:
+ config = SimpleNamespace(api_key="K", blog_id="BID")
+ with patch.object(source_module, "validate_blogger_credentials", return_value=(False, "nope")):
+ result = BloggerSource().validate_credentials(config, team_id=1) # type: ignore[arg-type]
+ assert result == (False, "nope")
+
+ @parameterized.expand(
+ [
+ (
+ "bad_request",
+ "400 Client Error: Bad Request for url: https://www.googleapis.com/blogger/v3/blogs/1/posts",
+ ),
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://www.googleapis.com/blogger/v3/blogs/1"),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://www.googleapis.com/blogger/v3/blogs/1/comments",
+ ),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = BloggerSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://www.googleapis.com/blogger/v3/blogs/1/posts",
+ ),
+ ("read_timeout", "HTTPSConnectionPool(host='www.googleapis.com', port=443): Read timed out."),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable = BloggerSource().get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable)
+
+
+class TestBloggerPipelinePlumbing:
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = BloggerSource().get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BloggerResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> Any:
+ captured.update(kwargs)
+ return MagicMock()
+
+ config = SimpleNamespace(api_key="K", blog_id="BID")
+ inputs = _make_inputs(
+ schema_name="comments",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ incremental_field="published",
+ )
+ with patch.object(source_module, "blogger_source", fake_source):
+ BloggerSource().source_for_pipeline(config, MagicMock(), inputs) # type: ignore[arg-type]
+
+ assert captured["api_key"] == "K"
+ assert captured["blog_id"] == "BID"
+ assert captured["endpoint"] == "comments"
+ assert captured["should_use_incremental_field"] is True
+ assert captured["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+ assert captured["incremental_field"] == "published"
+
+ def test_source_for_pipeline_clears_last_value_when_not_incremental(self) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> Any:
+ captured.update(kwargs)
+ return MagicMock()
+
+ config = SimpleNamespace(api_key="K", blog_id="BID")
+ inputs = _make_inputs(
+ schema_name="posts",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ )
+ with patch.object(source_module, "blogger_source", fake_source):
+ BloggerSource().source_for_pipeline(config, MagicMock(), inputs) # type: ignore[arg-type]
+
+ # When the run isn't incremental, the stale watermark must not leak through as a startDate.
+ assert captured["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index c86d274fdfc4..843b0dded63f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -436,7 +436,8 @@ class BitlySourceConfig(config.Config):
@config.config
class BloggerSourceConfig(config.Config):
- pass
+ api_key: str
+ blog_id: str
@config.config