:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add beehiiv source (#77086)
Tom Owers8841ee318063
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 59256081a31e..3e2748c5b963 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -99,6 +99,7 @@ the row lists both.| baserow | HTTP | requests + `rest_source.RESTClient` | ✅ || baseten | HTTP | requests | ✅ || beamer | HTTP | requests | ✅ |+| beehiiv | HTTP | requests + `rest_source.RESTClient` | ✅ || better_stack | HTTP | requests | ✅ || bettermode | HTTP (GraphQL) | requests | ✅ || bigmailer | HTTP | requests | ✅ |@@ -829,7 +830,6 @@ doesn't conflict with concurrent PRs.- backblaze- basecamp- bcms-- beehiiv- bexio- bigcommerce- bigeyediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/beehiiv.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/beehiiv.pynew file mode 100644index 000000000000..c760db9cfc78--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/beehiiv.py@@ -0,0 +1,176 @@+import dataclasses+from typing import Any, Optional+from urllib.parse import quote++from products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.settings import (+ ENDPOINTS,+ MAX_PAGE,+ PAGE_SIZE,+ PUBLICATION_PATH_PLACEHOLDER,+)+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,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++BASE_HOST = "https://api.beehiiv.com"+REQUEST_TIMEOUT_SECONDS = 30.0+++class BeehiivResumeConfig:+ # Opaque paginator snapshot: `{"cursor": ...}` for cursor endpoints, `{"page": ...}` for+ # paged ones. The manager is namespaced per endpoint so the two shapes can't cross over.+ paginator_state: dict[str, Any]+++def base_url(api_version: str) -> str:+ return f"{BASE_HOST}/{api_version}"+++def resolve_path(path: str, publication_id: str) -> str:+ return path.replace(PUBLICATION_PATH_PLACEHOLDER, quote(publication_id, safe=""))+++def build_paginator(endpoint: str) -> BasePaginator:+ config = ENDPOINTS[endpoint]+ if config.pagination == "cursor":+ return JSONResponseCursorPaginator(cursor_path="next_cursor", cursor_param="cursor")+ return PageNumberPaginator(+ base_page=1,+ page_param="page",+ total_path="total_pages",+ maximum_page=MAX_PAGE,+ )+++def get_resource(endpoint: str, publication_id: str) -> EndpointResource:+ config = ENDPOINTS[endpoint]++ params: dict[str, Any] = {"limit": PAGE_SIZE, **config.params}++ endpoint_config: Endpoint = {+ "path": resolve_path(config.path, publication_id),+ "params": params,+ "data_selector": "data",+ # Every beehiiv list response wraps rows in `data`; a body without it means the shape+ # changed, and syncing 0 rows silently would look like an empty publication.+ "data_selector_required": True,+ "paginator": build_paginator(endpoint),+ }++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def beehiiv_source(+ api_key: str,+ publication_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ api_version: str,+ resumable_source_manager: ResumableSourceManager[BeehiivResumeConfig],+) -> SourceResponse:+ endpoint_config = ENDPOINTS[endpoint]++ client_config: ClientConfig = {+ "base_url": base_url(api_version),+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ }++ config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [get_resource(endpoint, publication_id)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None and resume_config.paginator_state:+ initial_paginator_state = resume_config.paginator_state++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state:+ resumable_source_manager.save_state(BeehiivResumeConfig(paginator_state=state))++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ partitioned = endpoint_config.partition_key is not None++ return SourceResponse(+ name=endpoint_config.name,+ items=lambda: resource,+ primary_keys=[endpoint_config.primary_key],+ sort_mode=endpoint_config.sort_mode,+ partition_count=1 if partitioned else None,+ partition_size=1 if partitioned else None,+ partition_mode="datetime" if partitioned else None,+ partition_format="week" if partitioned else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def validate_credentials(+ api_key: str,+ publication_id: str,+ api_version: str,+ *,+ allow_missing_scope: bool,+) -> tuple[bool, str | None]:+ """Probe the configured publication with the API key.++ ``allow_missing_scope`` accepts a 403 as a valid key: beehiiv API keys are scoped per+ resource, so a key that can read subscriptions but not publications is still usable and+ must not block source creation.+ """+ url = f"{base_url(api_version)}/publications/{quote(publication_id, safe='')}"+ session = make_tracked_session(redact_values=(api_key,))+ try:+ response = session.get(+ url,+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except Exception as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "beehiiv rejected the API key. Create a new key in Settings > Integrations > API."+ if response.status_code == 403:+ if allow_missing_scope:+ return True, None+ return False, "The API key does not have permission to read this publication."+ if response.status_code == 404:+ return False, "No publication found with that ID. Check the publication ID in your beehiiv settings."+ return False, f"beehiiv returned HTTP {response.status_code}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/canonical_descriptions.pynew file mode 100644index 000000000000..8277c1699f0b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/canonical_descriptions.py@@ -0,0 +1,209 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Authors": {+ "description": "Guest authors and team members who can be credited on a publication's posts.",+ "docs_url": "https://developers.beehiiv.com/api-reference/authors/index",+ "columns": {+ "id": "The prefixed ID of the author (guest_xxx for guest authors, user_xxx for platform users).",+ "type": "The author type.",+ "name": "The author display name.",+ "bio": "The biography text for the author.",+ "bio_image_url": "The profile image URL for the author.",+ "social_media_links": "The author's social media links.",+ },+ },+ "Automations": {+ "description": "Automated journeys that run against subscribers of the publication.",+ "docs_url": "https://developers.beehiiv.com/api-reference/automations/index",+ "columns": {+ "id": "A unique prefixed id of the automation.",+ "status": "The current status of the automation.",+ "name": "The name of the automation.",+ "trigger_events": "The types of events that can trigger the automation.",+ "description": "The description of the automation.",+ },+ },+ "ComplimentaryAccess": {+ "description": "Gifted premium access grants, each tied to a premium tier.",+ "docs_url": "https://developers.beehiiv.com/api-reference/complimentary-access/index",+ "columns": {+ "id": "The prefixed ID of the complimentary access object.",+ "duration": "The duration of the gift. Null when time_unit is forever.",+ "time_unit": "The unit of time for the gift duration.",+ "description": "A human-readable description of the gift, for example 3 Months Gift.",+ "tier_id": "The prefixed ID of the associated tier.",+ },+ },+ "ConditionSets": {+ "description": "Reusable sets of conditions used to target subscribers across beehiiv features.",+ "docs_url": "https://developers.beehiiv.com/api-reference/condition-sets/index",+ "columns": {+ "id": "The UUID of the condition set.",+ "name": "The display name of the condition set.",+ "status": "Whether the condition set is currently active or has been archived.",+ "created": "The time the condition set was created, in seconds since the Unix epoch.",+ "updated": "The time the condition set was last updated, in seconds since the Unix epoch.",+ "purpose": "The purpose of the condition set, indicating its intended use.",+ },+ },+ "CustomFields": {+ "description": "Custom field definitions available on the publication's subscriptions.",+ "docs_url": "https://developers.beehiiv.com/api-reference/custom-fields/index",+ "columns": {+ "id": "The ID of the custom field.",+ "kind": "The type of value being stored in the custom field.",+ "display": "The display name of the custom field.",+ "created": "The time the custom field was created, in seconds since the Unix epoch.",+ "options": "Array of option values. Only included when kind is list.",+ },+ },+ "NewsletterLists": {+ "description": "Newsletter lists that subscribers can belong to within the publication.",+ "docs_url": "https://developers.beehiiv.com/api-reference/newsletter-lists/index",+ "columns": {+ "id": "The prefixed ID of the newsletter list.",+ "name": "The name of the newsletter list.",+ "slug": "The URL-friendly slug of the newsletter list.",+ "description": "A description of the newsletter list.",+ "status": "The status of the newsletter list.",+ "auto_subscribe": "Whether new subscribers are automatically subscribed to this list.",+ "subscriber_count": "The number of active subscribers on this list.",+ "created_at": "The time the newsletter list was created, in seconds since the Unix epoch.",+ "updated_at": "The time the newsletter list was last updated, in seconds since the Unix epoch.",+ },+ },+ "Polls": {+ "description": "Polls that can be embedded in posts and answered by subscribers.",+ "docs_url": "https://developers.beehiiv.com/api-reference/polls/index",+ "columns": {+ "id": "The prefixed ID of the poll.",+ "name": "The name of the poll.",+ "question": "The poll question text.",+ "description": "An optional description of the poll.",+ "poll_type": "The type of poll.",+ "status": "The current status of the poll.",+ "created_at": "The time the poll was created, in seconds since the Unix epoch.",+ "poll_choices": "The available choices for this poll.",+ },+ },+ "PostTemplates": {+ "description": "Reusable post templates saved on the publication.",+ "docs_url": "https://developers.beehiiv.com/api-reference/post-templates/index",+ "columns": {+ "id": "The prefixed ID of the post template.",+ "name": "The name of the post template.",+ },+ },+ "Posts": {+ "description": (+ "Newsletter posts, including drafts, scheduled and archived posts, with their email and "+ "web engagement stats."+ ),+ "docs_url": "https://developers.beehiiv.com/api-reference/posts/index",+ "columns": {+ "id": "The prefixed post id.",+ "title": "The title displayed in web views.",+ "subtitle": "The subtitle displayed in web views.",+ "authors": "An array of author names.",+ "created": "The time the post was created, in seconds since the Unix epoch.",+ "status": "The status of the post: draft, confirmed or archived.",+ "publish_date": "The time the post was set to be published, in seconds since the Unix epoch.",+ "displayed_date": "The time displayed in place of the publish_date, in seconds since the Unix epoch.",+ "split_tested": "Whether a split test was run. Only applicable to email posts.",+ "subject_line": "The email subject line. For A/B tests this is the winning subject line.",+ "preview_text": "The email preview text.",+ "slug": "The web slug where this post can be accessed.",+ "thumbnail_url": "The URL of the thumbnail. Defaults to the publication logo if not set.",+ "web_url": "The full URL where this post can be accessed on the web.",+ "preview_url": "A stable URL to the post's email preview in the beehiiv app.",+ "audience": "The audience the post is available to on the web.",+ "platform": "The platform the post is or will be published to.",+ "content_tags": "All content tags associated with the post.",+ "meta_default_title": "The meta tag title for the post, shown as SEO Title in beehiiv.",+ "meta_default_description": "The meta tag description for the post, shown as SEO Description in beehiiv.",+ "newsletter_list_id": "The prefixed ID of the newsletter list this post targets, when set.",+ "hidden_from_feed": "Whether the post is hidden from the website feed.",+ "enforce_gated_content": "Whether the post enforces gated content for non-subscribers.",+ "email_capture_popup": "Whether popup email capture is enabled for this post.",+ "recipients": "The targeting configuration for this post.",+ "recipient_count": "Estimated or actual number of email subscribers targeted by this post.",+ "headers": "Custom email headers set on this post.",+ "from_address": "The from address for this post, falling back to the publication default.",+ "reply_to_address": "The reply-to address for this post, falling back to the publication default.",+ "stats": "Email, web and click engagement metrics for the post.",+ },+ },+ "Publications": {+ "description": "Publications in the beehiiv workspace the API key belongs to.",+ "docs_url": "https://developers.beehiiv.com/api-reference/publications/index",+ "columns": {+ "id": "A unique prefixed id of the publication.",+ "name": "The name of the publication.",+ "organization_name": "The name of the organization.",+ "referral_program_enabled": "Whether the referral program is active for this publication.",+ "created": "The time the publication was created, in seconds since the Unix epoch.",+ "stats": "Subscriber counts and average open and click rates for the publication.",+ },+ },+ "ReferralProgramMilestones": {+ "description": "Milestones in the publication's referral program and the reward each one unlocks.",+ "docs_url": "https://developers.beehiiv.com/api-reference/referral-program/show",+ "columns": {+ "id": "A unique prefixed id of the milestone.",+ "auto_fulfill": (+ "For promo code rewards, whether an email with the reward code is sent automatically "+ "when the milestone is reached."+ ),+ "num_referrals": "The number of referrals needed to reach this milestone.",+ "reward": "The reward object granted at this milestone.",+ },+ },+ "Segments": {+ "description": "Saved subscriber segments and the result of their most recent calculation.",+ "docs_url": "https://developers.beehiiv.com/api-reference/segments/index",+ "columns": {+ "id": "The prefixed ID of the segment.",+ "name": "The name of the segment.",+ "type": "The type of segment: dynamic, static or manual.",+ "last_calculated": "The time the segment was last calculated, in seconds since the Unix epoch.",+ "total_results": "The number of subscriptions in the segment as of the last calculation.",+ "status": "The status of the segment's most recent calculation.",+ "active": "Whether the dynamic segment is still recalculated automatically.",+ },+ },+ "Subscriptions": {+ "description": (+ "Subscribers of the publication, with the UTM parameters and referral data captured when they signed up."+ ),+ "docs_url": "https://developers.beehiiv.com/api-reference/subscriptions/index",+ "columns": {+ "id": "The prefixed subscription id.",+ "email": "The subscriber's email address.",+ "status": "The status of the subscription, for example active, pending or inactive.",+ "created": "The time the subscription was created, in seconds since the Unix epoch.",+ "subscription_tier": "The current tier of the subscription: free or premium.",+ "subscription_premium_tier_names": "The names of the premium tiers the subscription belongs to.",+ "utm_source": "The acquisition source; where the subscriber came from.",+ "utm_medium": "The acquisition medium; how the subscriber got to the publication.",+ "utm_channel": "The acquisition channel.",+ "utm_campaign": "The acquisition campaign.",+ "utm_term": "The acquisition term; typically the keyword or search term.",+ "utm_content": "The acquisition content; typically used for A/B testing or ad variations.",+ "referring_site": "The website the subscriber was referred from.",+ "referral_code": "The code this subscriber uses to refer others.",+ },+ },+ "Tiers": {+ "description": "Premium subscription tiers offered by the publication.",+ "docs_url": "https://developers.beehiiv.com/api-reference/tiers/index",+ "columns": {+ "id": "The prefixed ID of the tier.",+ "name": "The name of the tier.",+ "status": "Whether the tier has any active prices.",+ "description": "The description of the tier.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/settings.pynew file mode 100644index 000000000000..5b021f010ad1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/settings.py@@ -0,0 +1,131 @@+from dataclasses import dataclass, field+from typing import Any, Literal++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField++PUBLICATION_PATH_PLACEHOLDER = "{publication_id}"++# beehiiv caps the deprecated offset pagination at 100 pages; requesting page 101 errors.+MAX_PAGE = 100+PAGE_SIZE = 100++PaginationStyle = Literal["cursor", "page"]+++@dataclass(frozen=True)+class BeehiivEndpointConfig:+ name: str+ path: str+ pagination: PaginationStyle+ primary_key: str = "id"+ # Only creation timestamps are used because beehiiv rows are partitioned by when they were made,+ # never by a column that moves after the fact.+ partition_key: str | None = None+ # Left unset where beehiiv documents no ordering for the endpoint, so the pipeline never+ # assumes an order the API doesn't promise.+ sort_mode: SortMode | None = None+ params: dict[str, Any] = field(default_factory=dict)+++ENDPOINTS: dict[str, BeehiivEndpointConfig] = {+ "Authors": BeehiivEndpointConfig(+ name="Authors",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/authors",+ pagination="page",+ ),+ "Automations": BeehiivEndpointConfig(+ name="Automations",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/automations",+ pagination="page",+ ),+ "ComplimentaryAccess": BeehiivEndpointConfig(+ name="ComplimentaryAccess",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/complimentary_access",+ pagination="cursor",+ ),+ "ConditionSets": BeehiivEndpointConfig(+ name="ConditionSets",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/condition_sets",+ pagination="cursor",+ partition_key="created",+ ),+ "CustomFields": BeehiivEndpointConfig(+ name="CustomFields",+ # beehiiv documents no query params here, but the response still carries the+ # page/total_pages envelope, so paginate defensively rather than reading one page.+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/custom_fields",+ pagination="page",+ partition_key="created",+ ),+ "NewsletterLists": BeehiivEndpointConfig(+ name="NewsletterLists",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/newsletter_lists",+ pagination="page",+ partition_key="created_at",+ params={"direction": "asc"},+ ),+ "Polls": BeehiivEndpointConfig(+ name="Polls",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/polls",+ pagination="cursor",+ partition_key="created_at",+ sort_mode="asc",+ params={"order_by": "created", "direction": "asc"},+ ),+ "PostTemplates": BeehiivEndpointConfig(+ name="PostTemplates",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/post_templates",+ pagination="page",+ ),+ "Posts": BeehiivEndpointConfig(+ name="Posts",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/posts",+ pagination="page",+ partition_key="created",+ sort_mode="asc",+ # `stats` carries the email open/click and web view counts, which is the point of+ # syncing posts. beehiiv warns the aggregation can time out and fall back to+ # consolidated click metrics, so treat the stats columns as best-effort.+ params={"order_by": "created", "direction": "asc", "status": "all", "expand": ["stats"]},+ ),+ "Publications": BeehiivEndpointConfig(+ name="Publications",+ path="/publications",+ pagination="page",+ partition_key="created",+ sort_mode="asc",+ params={"order_by": "created", "direction": "asc", "expand": ["stats"]},+ ),+ "ReferralProgramMilestones": BeehiivEndpointConfig(+ name="ReferralProgramMilestones",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/referral_program",+ pagination="page",+ ),+ "Segments": BeehiivEndpointConfig(+ name="Segments",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/segments",+ pagination="page",+ sort_mode="asc",+ params={"order_by": "created", "direction": "asc", "status": "all"},+ ),+ "Subscriptions": BeehiivEndpointConfig(+ name="Subscriptions",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/subscriptions",+ pagination="cursor",+ partition_key="created",+ sort_mode="asc",+ params={"order_by": "created", "direction": "asc", "status": "all"},+ ),+ "Tiers": BeehiivEndpointConfig(+ name="Tiers",+ path=f"/publications/{PUBLICATION_PATH_PLACEHOLDER}/tiers",+ pagination="page",+ params={"direction": "asc"},+ ),+}++# beehiiv exposes no updated-since or created-after filter on any list endpoint. The one date+# filter (`creation_date` on subscriptions) matches a single day rather than a lower bound, so+# every table is full refresh and no endpoint advertises an incremental field.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/source.pyindex 4111f4d60724..61a43ee23246 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/source.py@@ -1,13 +1,34 @@-from typing import cast+from typing import Optional, castfrom 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.sources.beehiiv.beehiiv import (+ BeehiivResumeConfig,+ beehiiv_source,+ validate_credentials as validate_beehiiv_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.settings import (+ 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,+)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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.beehiiv import (BeehiivSourceConfig,)@@ -15,7 +36,12 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class BeehiivSource(SimpleSource[BeehiivSourceConfig]):+class BeehiivSource(ResumableSource[BeehiivSourceConfig, BeehiivResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://developers.beehiiv.com/api-reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BEEHIIV@@ -26,7 +52,113 @@ class BeehiivSource(SimpleSource[BeehiivSourceConfig]):name=SchemaExternalDataSourceType.BEEHIIV,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="beehiiv",+ caption=(+ "Create an API key in beehiiv under **Settings > Integrations > API**, then paste it "+ "below along with your publication ID. The key needs read access to the resources you "+ "want to sync, for example `subscriptions:read`, `posts:read` and `publications:read`. "+ "API access requires a paid beehiiv plan."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/beehiiv",iconPath="/static/services/beehiiv.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="publication_id",+ label="Publication ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="pub_00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": (+ "beehiiv rejected the API key. Create a new key under Settings > Integrations > API "+ "and reconnect the source."+ ),+ "403 Client Error: Forbidden": (+ "The API key does not have permission for this table. Grant the matching read scope "+ "in beehiiv and reconnect the source."+ ),+ "404 Client Error: Not Found": (+ "beehiiv could not find this publication. Check the publication ID on the source settings."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: BeehiivSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS.keys(), INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: BeehiivSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ publication_id = config.publication_id.strip()+ if not publication_id:+ return False, "Publication ID is required."+ if "/" in publication_id:+ return (+ False,+ "Publication ID must be a single value with no slashes, for example pub_00000000-0000-0000-0000-000000000000.",+ )++ return validate_beehiiv_credentials(+ api_key=config.api_key,+ publication_id=publication_id,+ api_version=self.resolve_api_version(api_version),+ allow_missing_scope=schema_name is None,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BeehiivResumeConfig]:+ # Cursor and page endpoints store incompatible paginator snapshots, so each table keeps+ # its resume state in its own Redis slot.+ return ResumableSourceManager[BeehiivResumeConfig](inputs, BeehiivResumeConfig).with_namespace(+ inputs.schema_name+ )++ def source_for_pipeline(+ self,+ config: BeehiivSourceConfig,+ resumable_source_manager: ResumableSourceManager[BeehiivResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return beehiiv_source(+ api_key=config.api_key,+ publication_id=config.publication_id.strip(),+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/tests/test_beehiiv.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/tests/test_beehiiv.pynew file mode 100644index 000000000000..3c42aaae69aa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/tests/test_beehiiv.py@@ -0,0 +1,264 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.beehiiv import (+ BeehiivResumeConfig,+ beehiiv_source,+ get_resource,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.settings import (+ ENDPOINTS,+ MAX_PAGE,+ PAGE_SIZE,+ PUBLICATION_PATH_PLACEHOLDER,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++REST_CLIENT_SESSION = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source"+ ".rest_client.make_tracked_session"+)+TRANSPORT_SESSION = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.beehiiv.make_tracked_session"+)++CURSOR_ENDPOINTS = [name for name, config in ENDPOINTS.items() if config.pagination == "cursor"]+PAGE_ENDPOINTS = [name for name, config in ENDPOINTS.items() if config.pagination == "page"]+++def _http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ response = Response()+ response.status_code = status_code+ response._content = json.dumps(body).encode()+ response.headers["Content-Type"] = "application/json"+ return response+++def _drive(+ endpoint: str,+ manager: Any,+ responses: list[Response],+ publication_id: str = "pub_123",+) -> list[dict[str, Any]]:+ """Run ``beehiiv_source`` against a mocked session.++ Returns the per-request query params, copied at send time because the paginator+ mutates the Request in place between pages.+ """+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(REST_CLIENT_SESSION) as mock_make_session:+ session = mock_make_session.return_value+ session.headers = {}+ session.prepare_request.side_effect = lambda request: request+ session.send.side_effect = fake_send++ source_response = beehiiv_source(+ api_key="test-key",+ publication_id=publication_id,+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ api_version="v2",+ resumable_source_manager=manager,+ )+ list(cast(Iterable[Any], source_response.items()))++ return sent_params+++def _fresh_manager() -> Any:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ return manager+++class TestBeehiivResourceConfig:+ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))+ def test_publication_placeholder_is_always_substituted(self, endpoint: str) -> None:+ resource = get_resource(endpoint, "pub_abc")+ endpoint_config = cast(dict[str, Any], resource["endpoint"])++ assert PUBLICATION_PATH_PLACEHOLDER not in endpoint_config["path"]++ def test_publication_id_is_url_quoted_into_the_path(self) -> None:+ # The publication id is user-supplied and lands in the URL path; an unescaped+ # value could reach a different beehiiv endpoint than the one we configured.+ resource = get_resource("Subscriptions", "pub_a b/../webhooks")+ endpoint_config = cast(dict[str, Any], resource["endpoint"])++ assert endpoint_config["path"] == "/publications/pub_a%20b%2F..%2Fwebhooks/subscriptions"++ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))+ def test_every_endpoint_requests_full_pages_from_the_data_envelope(self, endpoint: str) -> None:+ # Without an explicit limit beehiiv returns 10 rows a page, and without a required+ # `data` selector a changed response shape would silently sync zero rows.+ resource = get_resource(endpoint, "pub_abc")+ endpoint_config = cast(dict[str, Any], resource["endpoint"])++ assert cast(dict[str, Any], endpoint_config["params"])["limit"] == PAGE_SIZE+ assert endpoint_config["data_selector"] == "data"+ assert endpoint_config["data_selector_required"] is True+++class TestBeehiivCursorPagination:+ @pytest.mark.parametrize("endpoint", CURSOR_ENDPOINTS)+ def test_follows_next_cursor_and_checkpoints_each_non_terminal_page(self, endpoint: str) -> None:+ manager = _fresh_manager()+ responses = [+ _http_response({"data": [{"id": "a"}], "has_more": True, "next_cursor": "cur-1"}),+ _http_response({"data": [{"id": "b"}], "has_more": True, "next_cursor": "cur-2"}),+ _http_response({"data": [{"id": "c"}], "has_more": False, "next_cursor": None}),+ ]++ sent_params = _drive(endpoint, manager, responses)++ assert [params.get("cursor") for params in sent_params] == [None, "cur-1", "cur-2"]+ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ BeehiivResumeConfig(paginator_state={"cursor": "cur-1"}),+ BeehiivResumeConfig(paginator_state={"cursor": "cur-2"}),+ ]++ def test_resume_seeds_the_saved_cursor_on_the_first_request(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = BeehiivResumeConfig(paginator_state={"cursor": "cur-saved"})++ sent_params = _drive(+ "Subscriptions",+ manager,+ [_http_response({"data": [{"id": "a"}], "has_more": False, "next_cursor": None})],+ )++ assert [params.get("cursor") for params in sent_params] == ["cur-saved"]++ def test_terminal_page_does_not_checkpoint(self) -> None:+ manager = _fresh_manager()++ _drive(+ "Subscriptions",+ manager,+ [_http_response({"data": [{"id": "a"}], "has_more": False, "next_cursor": None})],+ )++ manager.save_state.assert_not_called()+ manager.load_state.assert_not_called()+++class TestBeehiivPageNumberPagination:+ @pytest.mark.parametrize("endpoint", PAGE_ENDPOINTS)+ def test_walks_pages_and_stops_at_total_pages(self, endpoint: str) -> None:+ # beehiiv reports total_pages, so the last page must not be followed by a wasted+ # request for an empty page.+ manager = _fresh_manager()+ responses = [+ _http_response({"data": [{"id": "a"}], "page": 1, "total_pages": 2}),+ _http_response({"data": [{"id": "b"}], "page": 2, "total_pages": 2}),+ ]++ sent_params = _drive(endpoint, manager, responses)++ assert [params.get("page") for params in sent_params] == [1, 2]+ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ BeehiivResumeConfig(paginator_state={"page": 2}),+ ]++ def test_stops_at_the_hundred_page_offset_cap(self) -> None:+ # beehiiv rejects offset pagination past page 100, so a publication reporting more+ # pages must stop rather than error the whole sync out.+ manager = _fresh_manager()+ responses = [+ _http_response({"data": [{"id": str(page)}], "page": page, "total_pages": 500})+ for page in range(1, MAX_PAGE + 1)+ ]++ sent_params = _drive("Posts", manager, responses)++ assert [params.get("page") for params in sent_params] == list(range(1, MAX_PAGE + 1))++ def test_resume_seeds_the_saved_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = BeehiivResumeConfig(paginator_state={"page": 7})++ sent_params = _drive(+ "Posts",+ manager,+ [_http_response({"data": [{"id": "a"}], "page": 7, "total_pages": 7})],+ )++ assert [params.get("page") for params in sent_params] == [7]+++class TestBeehiivValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "allow_missing_scope", "expected_ok"),+ [+ (200, True, True),+ (200, False, True),+ (401, True, False),+ (401, False, False),+ # A beehiiv key scoped to subscriptions only cannot read the publication object;+ # that must not block source creation, but it must fail a per-table check.+ (403, True, True),+ (403, False, False),+ (404, True, False),+ (500, True, False),+ ],+ )+ def test_status_code_maps_to_credential_result(+ self, status_code: int, allow_missing_scope: bool, expected_ok: bool+ ) -> None:+ with patch(TRANSPORT_SESSION) as mock_make_session:+ mock_make_session.return_value.get.return_value = _http_response({}, status_code=status_code)++ is_valid, error = validate_credentials(+ api_key="key",+ publication_id="pub_1",+ api_version="v2",+ allow_missing_scope=allow_missing_scope,+ )++ assert is_valid is expected_ok+ assert (error is None) is expected_ok++ def test_transport_failure_is_reported_not_raised(self) -> None:+ with patch(TRANSPORT_SESSION) as mock_make_session:+ mock_make_session.return_value.get.side_effect = OSError("connection reset")++ is_valid, error = validate_credentials(+ api_key="key",+ publication_id="pub_1",+ api_version="v2",+ allow_missing_scope=True,+ )++ assert is_valid is False+ assert error == "connection reset"++ def test_api_key_is_registered_for_redaction(self) -> None:+ # The key rides an Authorization header on a tracked session; without redaction it+ # can land in captured request samples.+ with patch(TRANSPORT_SESSION) as mock_make_session:+ mock_make_session.return_value.get.return_value = _http_response({}, status_code=200)++ validate_credentials(+ api_key="super-secret",+ publication_id="pub_1",+ api_version="v2",+ allow_missing_scope=True,+ )++ assert mock_make_session.call_args.kwargs["redact_values"] == ("super-secret",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/tests/test_beehiiv_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/tests/test_beehiiv_source.pynew file mode 100644index 000000000000..a9594a8abc50--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/beehiiv/tests/test_beehiiv_source.py@@ -0,0 +1,187 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.beehiiv import BeehiivResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.source import BeehiivSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.beehiiv import (+ BeehiivSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++VALIDATE_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.beehiiv.source.validate_beehiiv_credentials"+)+++def _config(publication_id: str = "pub_123") -> BeehiivSourceConfig:+ return BeehiivSourceConfig(api_key="test-key", publication_id=publication_id)+++def _source_inputs(schema_name: str = "Subscriptions") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=7,+ 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-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestBeehiivSource:+ def setup_method(self) -> None:+ self.source = BeehiivSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.BEEHIIV++ def test_source_ships_visible_as_alpha(self) -> None:+ config = self.source.get_source_config++ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_api_key_field_is_secret(self) -> None:+ fields = self.source.get_source_config.fields or []+ by_name = {field.name: field for field in fields if isinstance(field, SourceFieldInputConfig)}++ assert by_name["api_key"].secret is True+ assert by_name["publication_id"].secret is False++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=7)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)++ def test_no_table_advertises_incremental_sync(self) -> None:+ # beehiiv has no updated-since or created-after filter, so an incremental sync would+ # re-walk every page while pretending to be cheap.+ schemas = self.source.get_schemas(_config(), team_id=7)++ assert not any(schema.supports_incremental or schema.supports_append for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)++ def test_get_schemas_filters_by_requested_names(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=7, names=["Posts", "Subscriptions"])++ assert [schema.name for schema in schemas] == ["Posts", "Subscriptions"]++ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))+ def test_canonical_descriptions_cover_every_table(self, endpoint: str) -> None:+ assert endpoint in CANONICAL_DESCRIPTIONS++ def test_canonical_descriptions_have_no_orphan_tables(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS) <= set(ENDPOINTS)++ @pytest.mark.parametrize(+ "endpoint", sorted(name for name, config in ENDPOINTS.items() if config.partition_key is not None)+ )+ def test_partition_key_is_a_documented_column(self, endpoint: str) -> None:+ # Partitioning on a column beehiiv does not return silently produces one null+ # partition for the whole table.+ partition_key = ENDPOINTS[endpoint].partition_key+ columns: dict[str, Any] = CANONICAL_DESCRIPTIONS[endpoint].get("columns") or {}++ assert partition_key in columns+++class TestBeehiivValidateCredentialsWiring:+ def setup_method(self) -> None:+ self.source = BeehiivSource()++ @pytest.mark.parametrize(+ ("publication_id", "expected_error"),+ [+ ("", "Publication ID is required."),+ (" ", "Publication ID is required."),+ (+ "pub_1/webhooks",+ "Publication ID must be a single value with no slashes, for example pub_00000000-0000-0000-0000-000000000000.",+ ),+ (+ "../publications",+ "Publication ID must be a single value with no slashes, for example pub_00000000-0000-0000-0000-000000000000.",+ ),+ ],+ )+ def test_rejects_publication_ids_that_are_not_a_single_path_segment(+ self, publication_id: str, expected_error: str+ ) -> None:+ with patch(VALIDATE_PATCH) as mock_validate:+ is_valid, error = self.source.validate_credentials(_config(publication_id), team_id=7)++ assert is_valid is False+ assert error == expected_error+ mock_validate.assert_not_called()++ @pytest.mark.parametrize(+ ("schema_name", "expected_allow_missing_scope"),+ [(None, True), ("Subscriptions", False)],+ )+ def test_missing_scope_is_only_tolerated_at_source_create(+ self, schema_name: str | None, expected_allow_missing_scope: bool+ ) -> None:+ with patch(VALIDATE_PATCH, return_value=(True, None)) as mock_validate:+ self.source.validate_credentials(_config(), team_id=7, schema_name=schema_name)++ assert mock_validate.call_args.kwargs["allow_missing_scope"] is expected_allow_missing_scope++ def test_publication_id_is_trimmed_before_use(self) -> None:+ with patch(VALIDATE_PATCH, return_value=(True, None)) as mock_validate:+ self.source.validate_credentials(_config(" pub_123 "), team_id=7)++ assert mock_validate.call_args.kwargs["publication_id"] == "pub_123"++ def test_falls_back_to_the_default_api_version(self) -> None:+ with patch(VALIDATE_PATCH, return_value=(True, None)) as mock_validate:+ self.source.validate_credentials(_config(), team_id=7, api_version=None)++ assert mock_validate.call_args.kwargs["api_version"] == "v2"+++class TestBeehiivPipelineDispatch:+ def setup_method(self) -> None:+ self.source = BeehiivSource()++ def test_resume_state_is_namespaced_per_table(self) -> None:+ # Cursor and page endpoints persist incompatible paginator snapshots; sharing one+ # Redis slot would replay a cursor against a paged endpoint.+ subscriptions = self.source.get_resumable_source_manager(_source_inputs("Subscriptions"))+ posts = self.source.get_resumable_source_manager(_source_inputs("Posts"))++ assert subscriptions._data_class is BeehiivResumeConfig+ assert subscriptions._key != posts._key+ assert subscriptions._key.endswith(":Subscriptions")++ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))+ def test_source_response_matches_the_endpoint_catalog(self, endpoint: str) -> None:+ endpoint_config = ENDPOINTS[endpoint]+ manager = MagicMock()+ manager.can_resume.return_value = False++ response = self.source.source_for_pipeline(_config(), manager, _source_inputs(endpoint))++ assert response.name == endpoint+ assert response.primary_keys == [endpoint_config.primary_key]+ assert response.sort_mode == endpoint_config.sort_mode+ if endpoint_config.partition_key is None:+ assert response.partition_keys is None+ assert response.partition_mode is None+ else:+ assert response.partition_keys == [endpoint_config.partition_key]+ assert response.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/beehiiv.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/beehiiv.pyindex 2d6c03e21553..988faf92e60e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/beehiiv.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/beehiiv.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass BeehiivSourceConfig(config.Config):- pass+ api_key: str+ publication_id: str