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 frill import source (#71164)

Tom Owers1c20f0239394
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 7472dba046e0..7b1dffc3f4bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -194,6 +194,7 @@ the row lists both.
| flowlu | HTTP | requests | ✅ |
| fly_io | HTTP | requests | ✅ |
| formbricks | HTTP | requests | ✅ |
+| frill | HTTP | requests | ✅ |
| front | HTTP | requests | ✅ |
| fulcrum | HTTP | requests | ✅ |
| fullstory | HTTP | requests | ✅ |
@@ -653,7 +654,6 @@ doesn't conflict with concurrent PRs.
- freshbooks
- freshchat
- freshservice
-- frill
- fulcrum
- gerrit
- getstream
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/frill/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/canonical_descriptions.py
new file mode 100644
index 000000000000..96fa0e7f2d15
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/canonical_descriptions.py
@@ -0,0 +1,132 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "announcement_categories": {
+ "description": "A category used to group and label announcements (e.g. New, Improvement, Fix).",
+ "docs_url": "https://developers.frill.co/api/reference/announcement-categories",
+ "columns": {
+ "id": "Category ID.",
+ "idx": "Encoded category ID — the unique identifier used across the Frill API.",
+ "name": "Category name.",
+ "color": "Hex RGB color code displayed in the app.",
+ "company_id": "Company ID the category belongs to.",
+ "created_at": "The date and time the category was created (UTC).",
+ "updated_at": "The date and time the category was last updated (UTC).",
+ "translations": "Localized category names.",
+ },
+ },
+ "announcements": {
+ "description": "A product announcement (changelog entry) published to your Frill announcements feed.",
+ "docs_url": "https://developers.frill.co/api/reference/announcements",
+ "columns": {
+ "idx": "A unique identifier for the announcement.",
+ "name": "Name of the announcement.",
+ "slug": "The URL slug of the announcement.",
+ "excerpt": "Short textual description of the announcement.",
+ "content": "Content of the announcement (as Markdown).",
+ "content_html": "Content of the announcement (as HTML).",
+ "reaction_count": "Reactions to the announcement.",
+ "is_published": "Indicates if the announcement is published or not.",
+ "published_at": "The date and time the announcement was published (UTC), or null if still in draft.",
+ "created_at": "The date and time the announcement was created (UTC).",
+ "updated_at": "The date and time the announcement was last updated (UTC).",
+ "author": "Author of this announcement.",
+ "categories": "Categories associated with this announcement.",
+ "ideas": "Ideas associated with this announcement.",
+ },
+ },
+ "comments": {
+ "description": "A public comment or internal note left on an idea.",
+ "docs_url": "https://developers.frill.co/api/reference/comments",
+ "columns": {
+ "idx": "A unique identifier for the comment.",
+ "message": "The raw message content of the comment.",
+ "content": "Structured content as a JSON array (similar to Slate.js/ProseMirror format).",
+ "content_html": "Content rendered as HTML.",
+ "content_markdown": "Content rendered as Markdown.",
+ "is_private": "Indicates if the comment is private (note) or public (comment).",
+ "type": "Type of comment (comment or note).",
+ "created_at": "The date and time the comment was created (UTC).",
+ "updated_at": "The date and time the comment was last updated (UTC).",
+ "follower": "Author of this comment.",
+ "idea_id": "ID of the associated idea.",
+ "attachments": "Files and images attached to this comment.",
+ "_idea_idx": "Unique identifier (idx) of the parent idea, injected during sync for joining to the ideas table.",
+ },
+ },
+ "followers": {
+ "description": "A person who follows, votes on, or comments on ideas in your Frill workspace.",
+ "docs_url": "https://developers.frill.co/api/reference/followers",
+ "columns": {
+ "idx": "A unique identifier for the follower.",
+ "name": "Name of the follower.",
+ "email": "Email address of the follower.",
+ "avatar": "Profile image of the follower (URL).",
+ "attributes": "Custom attributes for the follower.",
+ "companies": "Companies the follower is associated with.",
+ "created_at": "The date and time the follower was created (UTC).",
+ "updated_at": "The date and time the follower was last updated (UTC).",
+ },
+ },
+ "ideas": {
+ "description": "A feature request or piece of feedback submitted to your Frill workspace, with vote and comment counts.",
+ "docs_url": "https://developers.frill.co/api/reference/ideas",
+ "columns": {
+ "idx": "A unique identifier for the idea.",
+ "name": "The name of the idea.",
+ "slug": "The URL slug of the idea.",
+ "excerpt": "A short excerpt or summary of the idea.",
+ "description": "The text description of the idea (legacy field; use content fields for structured data).",
+ "content": "Structured content as a JSON array (similar to Slate.js/ProseMirror format).",
+ "content_html": "Content rendered as HTML.",
+ "content_markdown": "Content rendered as Markdown.",
+ "cover_image": "URL of the image displayed as the cover on the roadmap view.",
+ "vote_count": "Number of votes this idea has received.",
+ "comment_count": "Number of comments on this idea.",
+ "note_count": "Number of internal notes on this idea.",
+ "is_pined": "Has the idea been pinned to the top.",
+ "is_bug": "Denotes if this idea is a bug.",
+ "is_archived": "Denotes if this idea has been archived.",
+ "is_completed": "Denotes if this idea is considered completed / finished.",
+ "show_in_roadmap": "Should the idea be displayed in the roadmap view.",
+ "approval_status": "The approval status of the idea: approved, needs-approval, or rejected.",
+ "created_at": "The date and time the idea was created (UTC).",
+ "updated_at": "The date and time the idea was last updated (UTC).",
+ "author": "Author of the idea.",
+ "status": "Status of the idea.",
+ "topics": "Topics associated with the idea.",
+ "attachments": "Files and images attached to this idea.",
+ },
+ },
+ "statuses": {
+ "description": "A workflow status ideas move through on the roadmap (e.g. Planned, In Progress, Shipped).",
+ "docs_url": "https://developers.frill.co/api/reference/statuses",
+ "columns": {
+ "idx": "A unique identifier for the status.",
+ "name": "Name of the status.",
+ "color": "Color associated with the status (displayed in the app).",
+ },
+ },
+ "topics": {
+ "description": "A topic (tag) used to group and filter ideas.",
+ "docs_url": "https://developers.frill.co/api/reference/topics",
+ "columns": {
+ "idx": "A unique identifier for the topic.",
+ "name": "Name of the topic.",
+ "idea_count": "Number of ideas that have been tagged with this topic.",
+ "order": "The position of the topic in the topic list.",
+ },
+ },
+ "votes": {
+ "description": "A single vote cast by a follower on an idea.",
+ "docs_url": "https://developers.frill.co/api/reference/votes",
+ "columns": {
+ "idx": "A unique identifier for the vote.",
+ "created_at": "The date and time the vote was created (UTC).",
+ "voter": "The user this vote is associated with.",
+ "idea": "The idea this vote is associated with.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/frill/frill.py b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/frill.py
new file mode 100644
index 000000000000..e83ee1a2ca02
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/frill.py
@@ -0,0 +1,247 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.frill.settings import (
+ FRILL_ENDPOINTS,
+ FrillEndpointConfig,
+)
+
+FRILL_BASE_URL = "https://api.frill.co/v1"
+# Documented maximum `limit` for list endpoints (default is 20).
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+
+class FrillRetryableError(Exception):
+ """Raised on 429/5xx so tenacity retries; never reaches get_non_retryable_errors."""
+
+
+class FrillResumeConfig:
+ # `after` cursor into the endpoint's top-level list. For the comments fan-out this is the
+ # cursor into /ideas — comments resume at the last fully processed page of parent ideas.
+ after: Optional[str] = None
+
+
+def _make_session(api_key: str) -> requests.Session:
+ # The key rides in the Authorization header; register it for redaction so it can never
+ # land in tracked HTTP logs/samples regardless of where the API echoes it.
+ # `capture=False`: Frill responses carry arbitrary user-authored feedback — idea/comment
+ # bodies and private internal notes — that the generic name-based scrubber can't anonymize,
+ # so keep those bodies out of the shared HTTP sample store (still metered and logged).
+ return make_tracked_session(
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ redact_values=(api_key,),
+ capture=False,
+ )
+
+
+def _handle_response(response: requests.Response, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:
+ """Classify a single Frill response: retryable, terminal failure, or success body."""
+ if response.status_code == 429 or response.status_code >= 500:
+ raise FrillRetryableError(f"Frill API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Frill API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Frill error bodies look like {"error": true, "message": "..."}; surface any that slip
+ # through with a 2xx status so they fail loudly instead of being parsed as an empty page.
+ if isinstance(data, dict) and data.get("error"):
+ raise requests.HTTPError(f"Frill API error: {data.get('message')} (url: {url})", response=response)
+
+ if not isinstance(data, dict):
+ raise requests.HTTPError(f"Frill API returned an unexpected body (url: {url})", response=response)
+
+ return data
+
+
+@retry(
+ retry=retry_if_exception_type((FrillRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+ return _handle_response(response, url, logger)
+
+
+def _next_cursor(data: dict[str, Any], records: list[dict[str, Any]], current_after: Optional[str]) -> Optional[str]:
+ """Extract the next `after` cursor, or None when pagination is done.
+
+ Frill's docs describe the pagination object as {total, count, hasNextPage, startCursor,
+ endCursor} while the embedded OpenAPI specs show {total, before, after}; handle both
+ shapes conservatively. When neither a hasNextPage flag nor a full page indicates more
+ results, stop — and never reuse a cursor (guards against an infinite loop on API drift).
+ """
+ pagination = data.get("pagination")
+ if not isinstance(pagination, dict):
+ return None
+
+ cursor = pagination.get("endCursor") or pagination.get("after")
+ if not isinstance(cursor, str) or not cursor or cursor == current_after:
+ return None
+
+ has_next = pagination.get("hasNextPage")
+ if has_next is False:
+ return None
+ if has_next is None and len(records) < PAGE_SIZE:
+ return None
+
+ return cursor
+
+
+def _iter_pages(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+ after: Optional[str] = None,
+) -> Iterator[tuple[list[dict[str, Any]], Optional[str]]]:
+ """Yield (records, next_after) per page; next_after is None on the terminal page."""
+ while True:
+ query: dict[str, Any] = {**params, "limit": PAGE_SIZE}
+ if after:
+ query["after"] = after
+ data = _fetch_page(session, url, query, logger)
+
+ raw_records = data.get("data")
+ records = (
+ [record for record in raw_records if isinstance(record, dict)] if isinstance(raw_records, list) else []
+ )
+
+ next_after = _next_cursor(data, records, after) if records else None
+ yield records, next_after
+
+ if next_after is None:
+ break
+ after = next_after
+
+
+def _comment_rows(
+ session: requests.Session,
+ config: FrillEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FrillResumeConfig],
+ ideas_after: Optional[str],
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over ideas: GET /comments requires an `idea_idx`, so comments are fetched per idea.
+
+ The resume cursor tracks the /ideas pagination; it is saved only after every comment of an
+ entire ideas page has been yielded, so a crash re-yields that page (merge dedupes on the
+ primary key) rather than skipping ideas whose comments were never fetched.
+ """
+ ideas_url = f"{FRILL_BASE_URL}{FRILL_ENDPOINTS['ideas'].path}"
+ comments_url = f"{FRILL_BASE_URL}{config.path}"
+
+ for ideas, next_after in _iter_pages(
+ session, ideas_url, dict(FRILL_ENDPOINTS["ideas"].params), logger, after=ideas_after
+ ):
+ for idea in ideas:
+ idea_idx = idea.get("idx")
+ if not isinstance(idea_idx, str) or not idea_idx:
+ continue
+ # Ideas report comment_count/note_count; skip the per-idea request only when both
+ # are explicitly zero (fetch when the fields are missing, to stay conservative).
+ if idea.get("comment_count") == 0 and idea.get("note_count") == 0:
+ continue
+
+ comment_params = {**config.params, "idea_idx": idea_idx}
+ for comments, _ in _iter_pages(session, comments_url, comment_params, logger):
+ if comments:
+ # Comments only carry the idea's integer `idea_id`, while every other stream
+ # keys on `idx` strings — inject the parent idx so rows join back to ideas.
+ yield [{**comment, "_idea_idx": idea_idx} for comment in comments]
+
+ if next_after is not None:
+ resumable_source_manager.save_state(FrillResumeConfig(after=next_after))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FrillResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = FRILL_ENDPOINTS[endpoint]
+ session = _make_session(api_key)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ after = resume.after if resume is not None else None
+ if after is not None:
+ logger.debug(f"Frill: resuming endpoint={endpoint} from cursor={after}")
+
+ if endpoint == "comments":
+ yield from _comment_rows(session, config, logger, resumable_source_manager, after)
+ return
+
+ url = f"{FRILL_BASE_URL}{config.path}"
+ for records, next_after in _iter_pages(session, url, dict(config.params), logger, after=after):
+ if records:
+ yield records
+
+ # Persist AFTER yielding — a crash re-yields the last page (the merge dedupes on the
+ # primary key) rather than skipping it.
+ if next_after is not None:
+ resumable_source_manager.save_state(FrillResumeConfig(after=next_after))
+
+
+def frill_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FrillResumeConfig],
+) -> SourceResponse:
+ config = FRILL_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_credentials(api_key: str) -> bool:
+ # /statuses is the cheapest probe: every workspace ships with default statuses and the
+ # endpoint takes no required params. Reuse the catalog path so it can't drift from sync.
+ url = f"{FRILL_BASE_URL}{FRILL_ENDPOINTS['statuses'].path}"
+ try:
+ response = _make_session(api_key).get(url, params={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False
+
+ if not response.ok:
+ return False
+
+ try:
+ body = response.json()
+ except ValueError:
+ return False
+
+ return isinstance(body, dict) and not body.get("error")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/frill/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/settings.py
new file mode 100644
index 000000000000..5530a9f01524
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/settings.py
@@ -0,0 +1,50 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Frill serves every resource as a GET list endpoint under https://api.frill.co/v1 with
+# cursor pagination (`after` param, `limit` capped at 100). No list endpoint exposes a
+# server-side updated-since/created-since filter, so every stream is full refresh only
+# (see source.py / frill.py). `/comments` requires an `idea_idx` query param, so comments
+# fan out over the ideas list (one comments sub-pagination per idea).
+
+
+@dataclass
+class FrillEndpointConfig:
+ # Path under the API base (https://api.frill.co/v1).
+ path: str
+ # Extra query params sent on every list request for this endpoint.
+ params: dict[str, str] = field(default_factory=dict)
+ # Stable creation timestamp — safe to partition on because it never changes after a
+ # record is created (unlike `updated_at`). Statuses and topics carry no timestamps.
+ partition_key: Optional[str] = "created_at"
+ primary_keys: list[str] = field(default_factory=lambda: ["idx"])
+
+
+FRILL_ENDPOINTS: dict[str, FrillEndpointConfig] = {
+ "announcement_categories": FrillEndpointConfig(path="/announcement-categories"),
+ # Both published and unpublished announcements are returned when `is_published` is omitted.
+ "announcements": FrillEndpointConfig(path="/announcements"),
+ # `idea_idx` is a required param on GET /comments, so this endpoint fans out over ideas.
+ # `included_types` widens the default ('comments') to also sync internal notes; the row's
+ # `type` field distinguishes them. Frill `idx` values are type-prefixed tokens (e.g.
+ # `comment_abc123`) but the docs don't explicitly state global uniqueness, so the injected
+ # parent idea idx is part of the key.
+ "comments": FrillEndpointConfig(
+ path="/comments",
+ params={"included_types": "comments,notes"},
+ primary_keys=["_idea_idx", "idx"],
+ ),
+ "followers": FrillEndpointConfig(path="/followers", params={"include_attributes": "true"}),
+ "ideas": FrillEndpointConfig(path="/ideas"),
+ "statuses": FrillEndpointConfig(path="/statuses", partition_key=None),
+ "topics": FrillEndpointConfig(path="/topics", partition_key=None),
+ "votes": FrillEndpointConfig(path="/votes"),
+}
+
+ENDPOINTS = tuple(FRILL_ENDPOINTS.keys())
+
+# No endpoint exposes a server-side updated-since filter, so no stream is incremental.
+# Kept for parity with other sources and for the (empty) per-endpoint advertised options.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in FRILL_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/frill/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/source.py
index b6b2a647fc3a..53a96c465b98 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/frill/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/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.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.frill.frill import (
+ FrillResumeConfig,
+ frill_source,
+ validate_credentials as validate_frill_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.frill.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FrillSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class FrillSource(SimpleSource[FrillSourceConfig]):
+class FrillSource(ResumableSource[FrillSourceConfig, FrillResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FRILL
@@ -24,7 +47,92 @@ class FrillSource(SimpleSource[FrillSourceConfig]):
name=SchemaExternalDataSourceType.FRILL,
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
label="Frill",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Frill API key to sync your Frill ideas, votes, comments, and announcements into the PostHog Data warehouse.
+
+Find your API key under **Settings → Company** in your [Frill dashboard](https://app.frill.co/settings/company).""",
iconPath="/static/services/frill.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/frill",
+ keywords=["feedback", "roadmap"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ invalid_key_message = (
+ "Your Frill API key is invalid or has been revoked. Find your API key in your Frill "
+ "admin dashboard, then reconnect."
+ )
+ return {
+ # Match on the stable host, not the per-request path/params.
+ "401 Client Error: Unauthorized for url: https://api.frill.co": invalid_key_message,
+ "403 Client Error: Forbidden for url: https://api.frill.co": invalid_key_message,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.frill.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: FrillSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # No Frill list endpoint exposes a server-side updated-since filter, so every stream is
+ # full refresh only — neither incremental nor append is offered.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(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: FrillSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_frill_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Frill API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FrillResumeConfig]:
+ return ResumableSourceManager[FrillResumeConfig](inputs, FrillResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FrillSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FrillResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return frill_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/frill/tests/test_frill.py b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/tests/test_frill.py
new file mode 100644
index 000000000000..4ee9daf35094
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/tests/test_frill.py
@@ -0,0 +1,313 @@
+from typing import Any, Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.frill.frill import (
+ FRILL_BASE_URL,
+ PAGE_SIZE,
+ FrillResumeConfig,
+ FrillRetryableError,
+ _handle_response,
+ _next_cursor,
+ frill_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.frill.settings import ENDPOINTS, FRILL_ENDPOINTS
+
+
+def _resp(body: Any, status: int = 200) -> Any:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = 200 <= status < 400
+ response.json.return_value = body
+ response.text = str(body)
+ return response
+
+
+def _page(
+ records: list[dict[str, Any]],
+ has_next: Optional[bool] = None,
+ end_cursor: Optional[str] = None,
+) -> dict[str, Any]:
+ pagination: dict[str, Any] = {"total": len(records)}
+ if has_next is not None:
+ pagination["hasNextPage"] = has_next
+ if end_cursor is not None:
+ pagination["endCursor"] = end_cursor
+ return {"data": records, "pagination": pagination, "meta": {}}
+
+
+def _manager(resume: FrillResumeConfig | None = None) -> Any:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _drive(
+ endpoint: str, manager: Any, responses: list[Any]
+) -> tuple[list[tuple[str, dict[str, Any]]], list[list[dict[str, Any]]]]:
+ """Drive ``get_rows`` with a mocked tracked session, returning (requests, yielded_batches)."""
+ calls: list[tuple[str, dict[str, Any]]] = []
+ response_iter = iter(responses)
+
+ def fake_get(url: str, params: Any = None, timeout: Any = None, **_kwargs: Any) -> Any:
+ calls.append((url, dict(params or {})))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.frill.frill.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.side_effect = fake_get
+ batches = list(get_rows(api_key="k", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=manager))
+
+ return calls, batches
+
+
+class TestHandleResponse:
+ # Exercise the per-response classification directly, so a single attempt's behaviour can be
+ # asserted without driving the tenacity retry loop (and its real backoff sleeps).
+ def _handle(self, response: Any) -> dict[str, Any]:
+ return _handle_response(response, f"{FRILL_BASE_URL}/ideas", MagicMock())
+
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:
+ with pytest.raises(FrillRetryableError):
+ self._handle(_resp({}, status=status))
+
+ @pytest.mark.parametrize("status", [400, 401, 403])
+ def test_client_errors_raise_http_error(self, status: int) -> None:
+ response = _resp({}, status=status)
+ response.raise_for_status.side_effect = requests.HTTPError(f"{status} Client Error", response=response)
+ with pytest.raises(requests.HTTPError):
+ self._handle(response)
+
+ def test_error_body_on_200_raises_http_error(self) -> None:
+ with pytest.raises(requests.HTTPError, match="provide a valid api_key"):
+ self._handle(_resp({"error": True, "message": "Unauthorized - please provide a valid api_key"}))
+
+ def test_non_dict_body_raises_http_error(self) -> None:
+ with pytest.raises(requests.HTTPError, match="unexpected body"):
+ self._handle(_resp([{"idx": "idea_1"}]))
+
+ def test_success_returns_body(self) -> None:
+ body = _page([{"idx": "idea_1"}], has_next=False)
+ assert self._handle(_resp(body)) == body
+
+
+class TestNextCursor:
+ def test_has_next_page_true_returns_cursor(self) -> None:
+ data = _page([{"idx": "1"}], has_next=True, end_cursor="cur")
+ assert _next_cursor(data, data["data"], None) == "cur"
+
+ def test_has_next_page_false_returns_none(self) -> None:
+ data = _page([{"idx": "1"}], has_next=True, end_cursor="cur")
+ data["pagination"]["hasNextPage"] = False
+ assert _next_cursor(data, data["data"], None) is None
+
+ @pytest.mark.parametrize("body", [{}, {"pagination": None}, {"pagination": {"hasNextPage": True}}])
+ def test_missing_pagination_or_cursor_returns_none(self, body: dict[str, Any]) -> None:
+ assert _next_cursor(body, [{"idx": "1"}], None) is None
+
+ def test_repeated_cursor_returns_none(self) -> None:
+ # Guards against an infinite loop if the API keeps echoing the same cursor.
+ data = _page([{"idx": "1"}], has_next=True, end_cursor="cur")
+ assert _next_cursor(data, data["data"], "cur") is None
+
+ def test_after_shape_full_page_returns_cursor(self) -> None:
+ # The embedded OpenAPI specs describe pagination as {total, before, after} with no
+ # hasNextPage flag; a full page means there may be more results.
+ records = [{"idx": str(i)} for i in range(PAGE_SIZE)]
+ data = {"data": records, "pagination": {"total": 500, "after": "cur"}}
+ assert _next_cursor(data, records, None) == "cur"
+
+ def test_after_shape_short_page_returns_none(self) -> None:
+ records = [{"idx": "1"}]
+ data: dict[str, Any] = {"data": records, "pagination": {"total": 1, "after": "cur"}}
+ assert _next_cursor(data, records, None) is None
+
+
+class TestGetRows:
+ def test_paginates_until_has_next_false_and_saves_after_each_page(self) -> None:
+ manager = _manager()
+ responses = [
+ _resp(_page([{"idx": "idea_1"}], has_next=True, end_cursor="c1")),
+ _resp(_page([{"idx": "idea_2"}], has_next=True, end_cursor="c2")),
+ _resp(_page([{"idx": "idea_3"}], has_next=False)),
+ ]
+
+ calls, batches = _drive("ideas", manager, responses)
+
+ assert [params.get("after") for _, params in calls] == [None, "c1", "c2"]
+ assert all(params.get("limit") == PAGE_SIZE for _, params in calls)
+ assert batches == [[{"idx": "idea_1"}], [{"idx": "idea_2"}], [{"idx": "idea_3"}]]
+ # State is saved after each non-terminal page so a crash re-yields rather than skips.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [FrillResumeConfig(after="c1"), FrillResumeConfig(after="c2")]
+
+ def test_resume_seeds_cursor_from_saved_state(self) -> None:
+ manager = _manager(FrillResumeConfig(after="resume-cursor"))
+
+ calls, batches = _drive("votes", manager, [_resp(_page([{"idx": "vote_1"}], has_next=False))])
+
+ assert calls[0][1].get("after") == "resume-cursor"
+ manager.load_state.assert_called_once()
+ assert len(batches) == 1
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = _manager()
+
+ _, batches = _drive("statuses", manager, [_resp(_page([{"idx": "status_1"}], has_next=False))])
+
+ assert len(batches) == 1
+ manager.save_state.assert_not_called()
+
+ def test_empty_page_yields_nothing(self) -> None:
+ manager = _manager()
+
+ _, batches = _drive("ideas", manager, [_resp(_page([], has_next=False))])
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("endpoint", "param", "value"),
+ [
+ ("followers", "include_attributes", "true"),
+ ],
+ )
+ def test_endpoint_extra_params_are_sent(self, endpoint: str, param: str, value: str) -> None:
+ manager = _manager()
+
+ calls, _ = _drive(endpoint, manager, [_resp(_page([{"idx": "x"}], has_next=False))])
+
+ assert calls[0][0] == f"{FRILL_BASE_URL}{FRILL_ENDPOINTS[endpoint].path}"
+ assert calls[0][1].get(param) == value
+
+ def test_session_carries_bearer_auth_redacts_key_and_disables_capture(self) -> None:
+ manager = _manager()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.frill.frill.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.return_value = _resp(_page([], has_next=False))
+ list(get_rows(api_key="secret", endpoint="ideas", logger=MagicMock(), resumable_source_manager=manager))
+
+ _, kwargs = MockSession.call_args
+ assert kwargs["headers"]["Authorization"] == "Bearer secret"
+ assert kwargs["redact_values"] == ("secret",)
+ # Frill responses carry user-authored feedback/notes the scrubber can't anonymize, so
+ # sample capture must stay off to keep that content out of the shared HTTP sample store.
+ assert kwargs["capture"] is False
+
+
+class TestCommentsFanOut:
+ def test_fans_out_over_ideas_and_injects_parent_idx(self) -> None:
+ manager = _manager()
+ ideas: list[dict[str, Any]] = [
+ {"idx": "idea_a", "comment_count": 2, "note_count": 0},
+ # Both counts explicitly zero — the per-idea request is skipped.
+ {"idx": "idea_b", "comment_count": 0, "note_count": 0},
+ # Counts missing — fetched anyway, to stay conservative.
+ {"idx": "idea_c"},
+ ]
+ responses = [
+ _resp(_page(ideas, has_next=False)),
+ _resp(_page([{"idx": "comment_1"}, {"idx": "comment_2"}], has_next=False)),
+ _resp(_page([], has_next=False)),
+ ]
+
+ calls, batches = _drive("comments", manager, responses)
+
+ assert calls[0][0] == f"{FRILL_BASE_URL}/ideas"
+ comment_calls = [(url, params) for url, params in calls if url.endswith("/comments")]
+ assert [params.get("idea_idx") for _, params in comment_calls] == ["idea_a", "idea_c"]
+ assert all(params.get("included_types") == "comments,notes" for _, params in comment_calls)
+ assert batches == [[{"idx": "comment_1", "_idea_idx": "idea_a"}, {"idx": "comment_2", "_idea_idx": "idea_a"}]]
+ # The single ideas page was terminal, so there is nothing to resume to.
+ manager.save_state.assert_not_called()
+
+ def test_saves_ideas_cursor_after_full_page_of_comments(self) -> None:
+ manager = _manager()
+ responses = [
+ _resp(
+ _page([{"idx": "idea_a", "comment_count": 1, "note_count": 0}], has_next=True, end_cursor="ideas-c1")
+ ),
+ _resp(_page([{"idx": "comment_1"}], has_next=False)),
+ _resp(_page([{"idx": "idea_b", "comment_count": 0, "note_count": 0}], has_next=False)),
+ ]
+
+ _, batches = _drive("comments", manager, responses)
+
+ assert batches == [[{"idx": "comment_1", "_idea_idx": "idea_a"}]]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [FrillResumeConfig(after="ideas-c1")]
+
+ def test_resume_seeds_ideas_cursor(self) -> None:
+ manager = _manager(FrillResumeConfig(after="ideas-resume"))
+
+ calls, _ = _drive("comments", manager, [_resp(_page([], has_next=False))])
+
+ assert calls[0][0] == f"{FRILL_BASE_URL}/ideas"
+ assert calls[0][1].get("after") == "ideas-resume"
+
+
+class TestFrillSource:
+ @pytest.mark.parametrize("endpoint", ENDPOINTS)
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = frill_source(
+ api_key="k", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+
+ config = FRILL_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_comments_primary_key_includes_parent(self) -> None:
+ # Fan-out child rows must be unique table-wide, not per parent.
+ assert FRILL_ENDPOINTS["comments"].primary_keys == ["_idea_idx", "idx"]
+
+ @pytest.mark.parametrize("endpoint", ["statuses", "topics"])
+ def test_endpoints_without_timestamps_are_unpartitioned(self, endpoint: str) -> None:
+ assert FRILL_ENDPOINTS[endpoint].partition_key is None
+
+
+class TestValidateCredentials:
+ def _validate(self, response: Any = None, raises: Exception | None = None) -> bool:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.frill.frill.make_tracked_session"
+ ) as MockSession:
+ get = MockSession.return_value.get
+ if raises is not None:
+ get.side_effect = raises
+ else:
+ get.return_value = response
+ return validate_credentials("k")
+
+ def test_valid_key(self) -> None:
+ assert self._validate(_resp(_page([{"idx": "status_1"}], has_next=False))) is True
+
+ def test_unauthorized_is_invalid(self) -> None:
+ assert self._validate(_resp({"success": False, "message": "Unauthorized"}, status=401)) is False
+
+ def test_error_body_is_invalid(self) -> None:
+ assert self._validate(_resp({"error": True, "message": "bad key"})) is False
+
+ def test_network_error_is_invalid(self) -> None:
+ assert self._validate(raises=requests.ConnectionError("boom")) is False
+
+ def test_non_json_body_is_invalid(self) -> None:
+ response = _resp({})
+ response.json.side_effect = ValueError("not json")
+ assert self._validate(response) is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/frill/tests/test_frill_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/tests/test_frill_source.py
new file mode 100644
index 000000000000..4188d45b57d7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/frill/tests/test_frill_source.py
@@ -0,0 +1,140 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import 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.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.frill.frill import FrillResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.frill.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.frill.source import FrillSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FrillSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "ideas",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "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": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestFrillSource:
+ def setup_method(self) -> None:
+ self.source = FrillSource()
+ self.team_id = 123
+ self.config = FrillSourceConfig(api_key="test-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.FRILL
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Frill"
+ assert config.label == "Frill"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source ships visible — the scaffold-era flag must stay gone.
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/frill.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/frill"
+
+ assert len(config.fields) == 1
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ [
+ "401 Client Error: Unauthorized for url: https://api.frill.co",
+ "403 Client Error: Forbidden for url: https://api.frill.co",
+ ],
+ )
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_all_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Frill exposes no server-side updated-since filter, so every stream is full refresh only.
+ assert all(not s.supports_incremental for s in schemas)
+ assert all(not s.supports_append for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["ideas"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "ideas"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ (True, True, None),
+ (False, False, "Invalid Frill API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.frill.source.validate_frill_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: bool,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("test-key")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FrillResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.frill.source.frill_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(schema_name="votes", team_id=99, job_id="job-xyz")
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ api_key="test-key",
+ endpoint="votes",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ )
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ # Every advertised endpoint should carry a curated description so the warehouse can describe
+ # it deterministically instead of paying for per-team LLM enrichment.
+ assert set(ENDPOINTS).issubset(descriptions.keys())
+ assert all(entry.get("description") for entry in descriptions.values())
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 0ca74192f177..c1fc76de9266 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
@@ -1602,7 +1602,7 @@ class FreshserviceSourceConfig(config.Config):
@config.config
class FrillSourceConfig(config.Config):
- pass
+ api_key: str
@config.config